From aaf688cf8190714ae635c6ed7255ff8714d5f0d8 Mon Sep 17 00:00:00 2001 From: dr7ana Date: Fri, 15 Sep 2023 07:55:32 -0700 Subject: [PATCH] Deleted a lot - RIP llarp/iwp/* and most of llarp/link --- include/llarp.hpp | 6 +- jni/lokinet_daemon.cpp | 4 +- llarp/CMakeLists.txt | 13 - llarp/apple/route_manager.hpp | 2 +- llarp/apple/vpn_interface.cpp | 4 +- llarp/apple/vpn_interface.hpp | 4 +- llarp/apple/vpn_platform.cpp | 2 +- llarp/apple/vpn_platform.hpp | 2 +- llarp/consensus/reachability_testing.cpp | 6 +- llarp/consensus/reachability_testing.hpp | 5 +- llarp/context.cpp | 4 +- llarp/dht/context.cpp | 20 +- llarp/dht/context.hpp | 10 +- llarp/dht/dht.cpp | 4 +- llarp/dht/dht.h | 4 +- llarp/dht/explorenetworkjob.cpp | 4 +- llarp/dht/localrouterlookup.cpp | 4 +- llarp/dht/localserviceaddresslookup.cpp | 4 +- llarp/dht/localtaglookup.cpp | 4 +- llarp/dht/messages/findintro.cpp | 4 +- llarp/dht/messages/findname.cpp | 6 +- llarp/dht/messages/findrouter.cpp | 8 +- llarp/dht/messages/gotintro.cpp | 6 +- llarp/dht/messages/gotname.cpp | 4 +- llarp/dht/messages/gotrouter.cpp | 10 +- llarp/dht/messages/pubintro.cpp | 5 +- llarp/dht/publishservicejob.cpp | 4 +- llarp/dht/recursiverouterlookup.cpp | 4 +- llarp/exit/context.cpp | 181 ++- llarp/exit/context.hpp | 69 +- llarp/exit/endpoint.cpp | 4 +- llarp/exit/exit_messages.cpp | 12 +- llarp/exit/exit_messages.hpp | 12 +- llarp/exit/session.cpp | 12 +- llarp/exit/session.hpp | 6 +- llarp/handlers/exit.cpp | 1411 ++++++++++---------- llarp/handlers/exit.hpp | 62 +- llarp/handlers/null.hpp | 4 +- llarp/handlers/tun.cpp | 41 +- llarp/handlers/tun.hpp | 2 +- llarp/iwp/iwp.cpp | 72 - llarp/iwp/iwp.hpp | 40 - llarp/iwp/linklayer.cpp | 115 -- llarp/iwp/linklayer.hpp | 63 - llarp/iwp/message_buffer.cpp | 194 --- llarp/iwp/message_buffer.hpp | 127 -- llarp/iwp/session.cpp | 1031 -------------- llarp/iwp/session.hpp | 275 ---- llarp/link/connection.cpp | 6 +- llarp/link/connection.hpp | 15 +- llarp/link/endpoint.cpp | 72 - llarp/link/endpoint.hpp | 38 +- llarp/link/factory.cpp | 43 - llarp/link/factory.hpp | 48 - llarp/link/link_manager.cpp | 222 ++- llarp/link/link_manager.hpp | 135 +- llarp/link/server.cpp | 20 +- llarp/link/server.hpp | 278 ---- llarp/link/session.cpp | 11 - llarp/link/session.hpp | 138 -- llarp/lokinet_shared.cpp | 2 +- llarp/messages/dht_immediate.cpp | 4 +- llarp/messages/dht_immediate.hpp | 2 +- llarp/messages/discard.hpp | 4 +- llarp/messages/link_intro.cpp | 4 +- llarp/messages/link_intro.hpp | 2 +- llarp/messages/link_message.hpp | 5 +- llarp/messages/link_message_parser.cpp | 2 +- llarp/messages/link_message_parser.hpp | 6 +- llarp/messages/relay.cpp | 10 +- llarp/messages/relay.hpp | 4 +- llarp/messages/relay_commit.cpp | 42 +- llarp/messages/relay_commit.hpp | 4 +- llarp/messages/relay_status.cpp | 21 +- llarp/messages/relay_status.hpp | 10 +- llarp/net/address_info.cpp | 185 --- llarp/net/address_info.hpp | 98 -- llarp/net/net.hpp | 1 - llarp/path/ihophandler.cpp | 6 +- llarp/path/ihophandler.hpp | 22 +- llarp/path/path.cpp | 86 +- llarp/path/path.hpp | 61 +- llarp/path/path_context.cpp | 33 +- llarp/path/path_context.hpp | 9 +- llarp/path/pathbuilder.cpp | 44 +- llarp/path/pathbuilder.hpp | 4 +- llarp/path/pathset.cpp | 10 +- llarp/path/pathset.hpp | 10 +- llarp/path/transit_hop.cpp | 65 +- llarp/path/transit_hop.hpp | 49 +- llarp/router/abstractrouter.hpp | 397 ------ llarp/router/outbound_message_handler.cpp | 14 +- llarp/router/outbound_message_handler.hpp | 6 +- llarp/router/outbound_session_maker.cpp | 4 +- llarp/router/outbound_session_maker.hpp | 12 +- llarp/router/rc_gossiper.cpp | 35 +- llarp/router/rc_gossiper.hpp | 13 +- llarp/router/rc_lookup_handler.cpp | 202 +-- llarp/router/rc_lookup_handler.hpp | 81 +- llarp/router/route_poker.cpp | 22 +- llarp/router/route_poker.hpp | 6 +- llarp/router/router.cpp | 474 +++---- llarp/router/router.hpp | 456 +++---- llarp/router_contact.hpp | 7 +- llarp/routing/handler.hpp | 26 +- llarp/routing/message.hpp | 4 +- llarp/routing/message_parser.cpp | 5 +- llarp/routing/message_parser.hpp | 4 +- llarp/routing/path_confirm_message.cpp | 2 +- llarp/routing/path_confirm_message.hpp | 2 +- llarp/routing/path_dht_message.cpp | 4 +- llarp/routing/path_dht_message.hpp | 2 +- llarp/routing/path_latency_message.cpp | 2 +- llarp/routing/path_latency_message.hpp | 2 +- llarp/routing/path_transfer_message.cpp | 2 +- llarp/routing/path_transfer_message.hpp | 2 +- llarp/routing/transfer_traffic_message.cpp | 2 +- llarp/routing/transfer_traffic_message.hpp | 2 +- llarp/rpc/lokid_rpc_client.cpp | 764 ++++++----- llarp/rpc/lokid_rpc_client.hpp | 10 +- llarp/rpc/rpc_request.hpp | 2 +- llarp/rpc/rpc_request_definitions.hpp | 1 - llarp/rpc/rpc_server.cpp | 8 +- llarp/rpc/rpc_server.hpp | 6 +- llarp/service/auth.cpp | 10 +- llarp/service/auth.hpp | 2 +- llarp/service/context.cpp | 15 +- llarp/service/context.hpp | 4 +- llarp/service/endpoint.cpp | 97 +- llarp/service/endpoint.hpp | 12 +- llarp/service/endpoint_state.hpp | 2 +- llarp/service/lookup.cpp | 6 +- llarp/service/lookup.hpp | 2 +- llarp/service/outbound_context.cpp | 8 +- llarp/service/protocol.cpp | 8 +- llarp/service/protocol.hpp | 2 +- llarp/service/sendcontext.cpp | 8 +- llarp/tooling/hive_context.cpp | 2 +- llarp/tooling/hive_context.hpp | 2 +- llarp/tooling/router_hive.cpp | 2 +- llarp/vpn/android.hpp | 2 +- llarp/vpn/linux.hpp | 4 +- llarp/vpn/platform.hpp | 6 +- llarp/vpn/win32.cpp | 2 +- llarp/vpn/win32.hpp | 4 +- llarp/win32/wintun.cpp | 8 +- llarp/win32/wintun.hpp | 4 +- pybind/common.hpp | 2 +- pybind/llarp/handlers/pyhandler.hpp | 2 +- pybind/llarp/router.cpp | 14 +- pybind/llarp/tooling/router_hive.cpp | 2 +- pybind/module.cpp | 2 +- test/mocks/mock_context.hpp | 4 +- test/mocks/mock_vpn.hpp | 2 +- 154 files changed, 2639 insertions(+), 5903 deletions(-) delete mode 100644 llarp/iwp/iwp.cpp delete mode 100644 llarp/iwp/iwp.hpp delete mode 100644 llarp/iwp/linklayer.cpp delete mode 100644 llarp/iwp/linklayer.hpp delete mode 100644 llarp/iwp/message_buffer.cpp delete mode 100644 llarp/iwp/message_buffer.hpp delete mode 100644 llarp/iwp/session.cpp delete mode 100644 llarp/iwp/session.hpp delete mode 100644 llarp/link/endpoint.cpp delete mode 100644 llarp/link/factory.cpp delete mode 100644 llarp/link/factory.hpp delete mode 100644 llarp/link/server.hpp delete mode 100644 llarp/link/session.cpp delete mode 100644 llarp/link/session.hpp delete mode 100644 llarp/net/address_info.cpp delete mode 100644 llarp/net/address_info.hpp delete mode 100644 llarp/router/abstractrouter.hpp diff --git a/include/llarp.hpp b/include/llarp.hpp index 2d00bdeba..50955b868 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -21,7 +21,7 @@ namespace llarp struct Config; struct Crypto; struct CryptoManager; - struct AbstractRouter; + struct Router; class NodeDB; namespace thread @@ -40,7 +40,7 @@ namespace llarp { std::shared_ptr crypto = nullptr; std::shared_ptr cryptoManager = nullptr; - std::shared_ptr router = nullptr; + std::shared_ptr router = nullptr; std::shared_ptr loop = nullptr; std::shared_ptr nodedb = nullptr; @@ -89,7 +89,7 @@ namespace llarp /// Creates a router. Can be overridden to allow a different class of router /// to be created instead. Defaults to llarp::Router. - virtual std::shared_ptr + virtual std::shared_ptr makeRouter(const std::shared_ptr& loop); /// create the nodedb given our current configs diff --git a/jni/lokinet_daemon.cpp b/jni/lokinet_daemon.cpp index 8bd90f510..98b6e8b5a 100644 --- a/jni/lokinet_daemon.cpp +++ b/jni/lokinet_daemon.cpp @@ -2,7 +2,7 @@ #include "lokinet_jni_common.hpp" #include #include -#include +#include extern "C" { @@ -85,7 +85,7 @@ extern "C" Java_network_loki_lokinet_LokinetDaemon_GetUDPSocket(JNIEnv* env, jobject self) { if (auto ptr = GetImpl(env, self); ptr and ptr->router) - return ptr->router->OutboundUDPSocket(); + return ptr->router->outbound_socket(); return -1; } diff --git a/llarp/CMakeLists.txt b/llarp/CMakeLists.txt index 4dfdc98a9..cf8a86fb9 100644 --- a/llarp/CMakeLists.txt +++ b/llarp/CMakeLists.txt @@ -194,25 +194,14 @@ add_library(lokinet-layer-onion messages/relay_status.cpp ) -# lokinet-layer-wire is a layer 1 analog which splits up -# layer 2 frames into layer 1 symbols which in the case of iwp are encrypted udp/ip packets -add_library(lokinet-layer-wire - STATIC - iwp/iwp.cpp - iwp/linklayer.cpp - iwp/message_buffer.cpp - iwp/session.cpp -) # lokinet-layer-link is for our layer 2 analog which splits up layer 2 frames into # a series of layer 1 symbols which are then transmitted between lokinet instances add_library(lokinet-layer-link STATIC link/connection.cpp - link/endpoint.cpp link/link_manager.cpp link/session.cpp - link/server.cpp messages/dht_immediate.cpp messages/link_intro.cpp messages/link_message_parser.cpp @@ -454,7 +443,6 @@ link_lokinet_layers( lokinet-layer-routing lokinet-layer-onion lokinet-layer-link - lokinet-layer-wire ) # set me to OFF to disable old codepath @@ -481,7 +469,6 @@ target_link_libraries(lokinet-layers INTERFACE lokinet-layer-routing lokinet-layer-onion lokinet-layer-link - lokinet-layer-wire ) diff --git a/llarp/apple/route_manager.hpp b/llarp/apple/route_manager.hpp index 69403c04d..7dfc37e78 100644 --- a/llarp/apple/route_manager.hpp +++ b/llarp/apple/route_manager.hpp @@ -1,6 +1,6 @@ #pragma once -#include +#include #include #include "context_wrapper.h" diff --git a/llarp/apple/vpn_interface.cpp b/llarp/apple/vpn_interface.cpp index f0b3a6c32..3f128ad17 100644 --- a/llarp/apple/vpn_interface.cpp +++ b/llarp/apple/vpn_interface.cpp @@ -1,7 +1,7 @@ #include "vpn_interface.hpp" #include "context.hpp" -#include +#include namespace llarp::apple { @@ -9,7 +9,7 @@ namespace llarp::apple Context& ctx, packet_write_callback packet_writer, on_readable_callback on_readable, - AbstractRouter* router) + Router* router) : vpn::NetworkInterface{{}} , m_PacketWriter{std::move(packet_writer)} , m_OnReadable{std::move(on_readable)} diff --git a/llarp/apple/vpn_interface.hpp b/llarp/apple/vpn_interface.hpp index b030afd9a..787eb4ebb 100644 --- a/llarp/apple/vpn_interface.hpp +++ b/llarp/apple/vpn_interface.hpp @@ -20,7 +20,7 @@ namespace llarp::apple Context& ctx, packet_write_callback packet_writer, on_readable_callback on_readable, - AbstractRouter* router); + Router* router); // Method to call when a packet has arrived to deliver the packet to lokinet bool @@ -50,7 +50,7 @@ namespace llarp::apple thread::Queue m_ReadQueue{PacketQueueSize}; - AbstractRouter* const _router; + Router* const _router; }; } // namespace llarp::apple diff --git a/llarp/apple/vpn_platform.cpp b/llarp/apple/vpn_platform.cpp index 1d1eafb8e..bc34f6d5c 100644 --- a/llarp/apple/vpn_platform.cpp +++ b/llarp/apple/vpn_platform.cpp @@ -16,7 +16,7 @@ namespace llarp::apple {} std::shared_ptr - VPNPlatform::ObtainInterface(vpn::InterfaceInfo, AbstractRouter* router) + VPNPlatform::ObtainInterface(vpn::InterfaceInfo, Router* router) { return std::make_shared(m_Context, m_PacketWriter, m_OnReadable, router); } diff --git a/llarp/apple/vpn_platform.hpp b/llarp/apple/vpn_platform.hpp index 3e9023ee6..b5b436168 100644 --- a/llarp/apple/vpn_platform.hpp +++ b/llarp/apple/vpn_platform.hpp @@ -17,7 +17,7 @@ namespace llarp::apple void* callback_context); std::shared_ptr - ObtainInterface(vpn::InterfaceInfo, AbstractRouter*) override; + ObtainInterface(vpn::InterfaceInfo, Router*) override; vpn::IRouteManager& RouteManager() override diff --git a/llarp/consensus/reachability_testing.cpp b/llarp/consensus/reachability_testing.cpp index f238907d0..511f49a43 100644 --- a/llarp/consensus/reachability_testing.cpp +++ b/llarp/consensus/reachability_testing.cpp @@ -1,7 +1,7 @@ #include "reachability_testing.hpp" #include -#include +#include #include #include @@ -72,7 +72,7 @@ namespace llarp::consensus } std::optional - reachability_testing::next_random(AbstractRouter* router, const time_point_t& now, bool requeue) + reachability_testing::next_random(Router* router, const time_point_t& now, bool requeue) { if (next_general_test > now) return std::nullopt; @@ -104,7 +104,7 @@ namespace llarp::consensus // We exhausted the queue so repopulate it and try again testing_queue.clear(); - const auto all = router->GetRouterWhitelist(); + const auto all = router->router_whitelist(); testing_queue.insert(testing_queue.begin(), all.begin(), all.end()); std::shuffle(testing_queue.begin(), testing_queue.end(), rng); diff --git a/llarp/consensus/reachability_testing.hpp b/llarp/consensus/reachability_testing.hpp index ecea88039..9792c3cee 100644 --- a/llarp/consensus/reachability_testing.hpp +++ b/llarp/consensus/reachability_testing.hpp @@ -12,7 +12,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; } namespace llarp::consensus @@ -117,8 +117,7 @@ namespace llarp::consensus // `requeue` is mainly for internal use: if false it avoids rebuilding the queue if we run // out (and instead just return nullopt). std::optional - next_random( - AbstractRouter* router, const time_point_t& now = clock_t::now(), bool requeue = true); + next_random(Router* router, const time_point_t& now = clock_t::now(), bool requeue = true); // Removes and returns up to MAX_RETESTS_PER_TICK nodes that are due to be tested (i.e. // next-testing-time <= now). Returns [snrecord, #previous-failures] for each. diff --git a/llarp/context.cpp b/llarp/context.cpp index 487a24066..621c99cf1 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -90,10 +90,10 @@ namespace llarp Context::makeNodeDB() { return std::make_shared( - nodedb_dirname, [r = router.get()](auto call) { r->QueueDiskIO(std::move(call)); }); + nodedb_dirname, [r = router.get()](auto call) { r->queue_disk_io(std::move(call)); }); } - std::shared_ptr + std::shared_ptr Context::makeRouter(const EventLoop_ptr& loop) { return std::make_shared(loop, makeVPNPlatform()); diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index 5bd9f7ad1..c9231df16 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -15,7 +15,7 @@ #include "taglookup.hpp" #include #include -#include +#include #include #include #include @@ -39,7 +39,7 @@ namespace llarp::dht void StoreRC(const RouterContact rc) const override { - GetRouter()->rcLookupHandler().CheckRC(rc); + GetRouter()->rc_lookup_handler().check_rc(rc); } void @@ -148,7 +148,7 @@ namespace llarp::dht /// initialize dht context and explore every exploreInterval milliseconds void - Init(const Key_t& us, AbstractRouter* router) override; + Init(const Key_t& us, Router* router) override; /// get localally stored introset by service address std::optional @@ -161,7 +161,7 @@ namespace llarp::dht void Explore(size_t N = 3); - llarp::AbstractRouter* router{nullptr}; + llarp::Router* router{nullptr}; // for router contacts std::unique_ptr> _nodes; @@ -211,7 +211,7 @@ namespace llarp::dht return ourKey; } - llarp::AbstractRouter* + llarp::Router* GetRouter() const override { return router; @@ -220,7 +220,7 @@ namespace llarp::dht bool GetRCFromNodeDB(const Key_t& k, llarp::RouterContact& rc) const override { - if (const auto maybe = router->nodedb()->Get(k.as_array()); maybe.has_value()) + if (const auto maybe = router->node_db()->Get(k.as_array()); maybe.has_value()) { rc = *maybe; return true; @@ -387,7 +387,7 @@ namespace llarp::dht replies.emplace_back(new GotRouterMessage(requester, txid, {}, false)); return; } - const auto rc = GetRouter()->nodedb()->FindClosestTo(target); + const auto rc = GetRouter()->node_db()->FindClosestTo(target); const Key_t next(rc.pubkey); { if (next == target) @@ -468,7 +468,7 @@ namespace llarp::dht } void - DHTMessageHandler::Init(const Key_t& us, AbstractRouter* r) + DHTMessageHandler::Init(const Key_t& us, Router* r) { router = r; ourKey = us; @@ -502,7 +502,7 @@ namespace llarp::dht return false; if (not reply.dht_msgs.empty()) { - auto path = router->pathContext().GetByUpstream(router->pubkey(), id); + auto path = router->path_context().GetByUpstream(router->pubkey(), id); return path && path->SendRoutingMessage(reply, router); } return true; @@ -622,7 +622,7 @@ namespace llarp::dht { const RouterID id = f.as_array(); // discard shit routers - if (router->routerProfiling().IsBadForConnect(id)) + if (router->router_profiling().IsBadForConnect(id)) continue; closer.emplace_back(id); } diff --git a/llarp/dht/context.hpp b/llarp/dht/context.hpp index 5fc17ec81..292ae862f 100644 --- a/llarp/dht/context.hpp +++ b/llarp/dht/context.hpp @@ -19,7 +19,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; namespace dht { @@ -130,7 +130,7 @@ namespace llarp uint64_t relayOrder) = 0; virtual void - Init(const Key_t& us, AbstractRouter* router) = 0; + Init(const Key_t& us, Router* router) = 0; virtual std::optional GetIntroSetByLocation(const Key_t& location) const = 0; @@ -141,7 +141,7 @@ namespace llarp virtual void ExploreNetworkVia(const Key_t& peer) = 0; - virtual llarp::AbstractRouter* + virtual llarp::Router* GetRouter() const = 0; virtual bool @@ -204,8 +204,8 @@ namespace llarp struct llarp_dht_context { std::unique_ptr impl; - llarp::AbstractRouter* parent; - llarp_dht_context(llarp::AbstractRouter* router); + llarp::Router* parent; + llarp_dht_context(llarp::Router* router); }; #endif diff --git a/llarp/dht/dht.cpp b/llarp/dht/dht.cpp index 8dbecfc8c..8b1b1b4fc 100644 --- a/llarp/dht/dht.cpp +++ b/llarp/dht/dht.cpp @@ -2,14 +2,14 @@ #include "dht.h" #include -llarp_dht_context::llarp_dht_context(llarp::AbstractRouter* router) +llarp_dht_context::llarp_dht_context(llarp::Router* router) { parent = router; impl = llarp::dht::make_handler(); } struct llarp_dht_context* -llarp_dht_context_new(llarp::AbstractRouter* router) +llarp_dht_context_new(llarp::Router* router) { return new llarp_dht_context(router); } diff --git a/llarp/dht/dht.h b/llarp/dht/dht.h index 20ce470c7..618b11350 100644 --- a/llarp/dht/dht.h +++ b/llarp/dht/dht.h @@ -14,12 +14,12 @@ struct llarp_dht_context; namespace llarp { - struct AbstractRouter; + struct Router; } /// allocator struct llarp_dht_context* -llarp_dht_context_new(llarp::AbstractRouter* parent); +llarp_dht_context_new(llarp::Router* parent); /// deallocator void diff --git a/llarp/dht/explorenetworkjob.cpp b/llarp/dht/explorenetworkjob.cpp index 55c35a33c..e0c7ebc02 100644 --- a/llarp/dht/explorenetworkjob.cpp +++ b/llarp/dht/explorenetworkjob.cpp @@ -2,7 +2,7 @@ #include "context.hpp" #include -#include +#include #include @@ -33,7 +33,7 @@ namespace llarp for (const auto& pk : valuesFound) { // lookup router - if (router and router->nodedb()->Has(pk)) + if (router and router->node_db()->Has(pk)) continue; parent->LookupRouter( pk, [router, pk](const auto& res) { router->HandleDHTLookupForExplore(pk, res); }); diff --git a/llarp/dht/localrouterlookup.cpp b/llarp/dht/localrouterlookup.cpp index 2482e37ce..aeb8fafa9 100644 --- a/llarp/dht/localrouterlookup.cpp +++ b/llarp/dht/localrouterlookup.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include @@ -19,7 +19,7 @@ namespace llarp::dht LocalRouterLookup::SendReply() { auto path = - parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + parent->GetRouter()->path_context().GetByUpstream(parent->OurKey().as_array(), localPath); if (!path) { llarp::LogWarn( diff --git a/llarp/dht/localserviceaddresslookup.cpp b/llarp/dht/localserviceaddresslookup.cpp index 4644831a2..45333d61f 100644 --- a/llarp/dht/localserviceaddresslookup.cpp +++ b/llarp/dht/localserviceaddresslookup.cpp @@ -3,7 +3,7 @@ #include "context.hpp" #include #include -#include +#include #include #include @@ -24,7 +24,7 @@ namespace llarp::dht LocalServiceAddressLookup::SendReply() { auto path = - parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + parent->GetRouter()->path_context().GetByUpstream(parent->OurKey().as_array(), localPath); if (!path) { llarp::LogWarn( diff --git a/llarp/dht/localtaglookup.cpp b/llarp/dht/localtaglookup.cpp index 2e6e7f65c..435d770a7 100644 --- a/llarp/dht/localtaglookup.cpp +++ b/llarp/dht/localtaglookup.cpp @@ -3,7 +3,7 @@ #include "context.hpp" #include #include -#include +#include #include namespace llarp::dht @@ -20,7 +20,7 @@ namespace llarp::dht LocalTagLookup::SendReply() { auto path = - parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + parent->GetRouter()->path_context().GetByUpstream(parent->OurKey().as_array(), localPath); if (!path) { llarp::LogWarn( diff --git a/llarp/dht/messages/findintro.cpp b/llarp/dht/messages/findintro.cpp index 93c160965..7a3706cfc 100644 --- a/llarp/dht/messages/findintro.cpp +++ b/llarp/dht/messages/findintro.cpp @@ -2,7 +2,7 @@ #include "findintro.hpp" #include "gotintro.hpp" #include -#include +#include #include namespace llarp::dht @@ -92,7 +92,7 @@ namespace llarp::dht } auto closestRCs = - dht.GetRouter()->nodedb()->FindManyClosestTo(location, IntroSetStorageRedundancy); + dht.GetRouter()->node_db()->FindManyClosestTo(location, IntroSetStorageRedundancy); if (closestRCs.size() <= relayOrder) { diff --git a/llarp/dht/messages/findname.cpp b/llarp/dht/messages/findname.cpp index 255931398..aefa63863 100644 --- a/llarp/dht/messages/findname.cpp +++ b/llarp/dht/messages/findname.cpp @@ -2,7 +2,7 @@ #include #include #include "gotname.hpp" -#include +#include #include #include #include @@ -51,9 +51,9 @@ namespace llarp::dht auto router = dht.GetRouter(); if (pathID.IsZero() or not router->IsServiceNode()) return false; - router->RpcClient()->LookupLNSNameHash( + router->rpc_client()->LookupLNSNameHash( NameHash, [router, pathID = pathID, TxID = TxID](auto maybe) { - auto path = router->pathContext().GetPathForTransfer(pathID); + auto path = router->path_context().GetPathForTransfer(pathID); if (path == nullptr) return; routing::PathDHTMessage msg; diff --git a/llarp/dht/messages/findrouter.cpp b/llarp/dht/messages/findrouter.cpp index e902b7d7a..a22672304 100644 --- a/llarp/dht/messages/findrouter.cpp +++ b/llarp/dht/messages/findrouter.cpp @@ -4,7 +4,7 @@ #include "gotrouter.hpp" #include #include -#include +#include #include #include @@ -21,7 +21,7 @@ namespace llarp::dht const Key_t k{targetKey}; if (k == us) { - auto path = dht.GetRouter()->pathContext().GetByUpstream(targetKey, pathID); + auto path = dht.GetRouter()->path_context().GetByUpstream(targetKey, pathID); if (path) { replies.emplace_back(new GotRouterMessage(k, txid, {dht.GetRouter()->rc()}, false)); @@ -39,7 +39,7 @@ namespace llarp::dht return true; } // check netdb - const auto rc = dht.GetRouter()->nodedb()->FindClosestTo(k); + const auto rc = dht.GetRouter()->node_db()->FindClosestTo(k); if (rc.pubkey == targetKey) { replies.emplace_back(new GotRouterMessage(k, txid, {rc}, false)); @@ -122,7 +122,7 @@ namespace llarp::dht std::vector>& replies) const { auto router = dht.GetRouter(); - router->NotifyRouterEvent(router->pubkey(), *this); + router->notify_router_event(router->pubkey(), *this); if (!dht.AllowTransit()) { diff --git a/llarp/dht/messages/gotintro.cpp b/llarp/dht/messages/gotintro.cpp index 43d135575..9be5a0e5f 100644 --- a/llarp/dht/messages/gotintro.cpp +++ b/llarp/dht/messages/gotintro.cpp @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include #include @@ -22,7 +22,7 @@ namespace llarp::dht { auto* router = dht.GetRouter(); - router->NotifyRouterEvent( + router->notify_router_event( router->pubkey(), Key_t(From.data()), (found.size() > 0 ? found[0] : llarp::service::EncryptedIntroSet{}), @@ -64,7 +64,7 @@ namespace llarp::dht [[maybe_unused]] std::vector>& replies) const { // TODO: implement me better? - auto pathset = dht.GetRouter()->pathContext().GetLocalPathSet(pathID); + auto pathset = dht.GetRouter()->path_context().GetLocalPathSet(pathID); if (pathset) { auto copy = std::make_shared(*this); diff --git a/llarp/dht/messages/gotname.cpp b/llarp/dht/messages/gotname.cpp index 720786d2d..1f927e31b 100644 --- a/llarp/dht/messages/gotname.cpp +++ b/llarp/dht/messages/gotname.cpp @@ -1,7 +1,7 @@ #include "gotname.hpp" #include #include -#include +#include #include namespace llarp::dht @@ -60,7 +60,7 @@ namespace llarp::dht GotNameMessage::handle_message( AbstractDHTMessageHandler& dht, std::vector>&) const { - auto pathset = dht.GetRouter()->pathContext().GetLocalPathSet(pathID); + auto pathset = dht.GetRouter()->path_context().GetLocalPathSet(pathID); if (pathset == nullptr) return false; auto copy = std::make_shared(*this); diff --git a/llarp/dht/messages/gotrouter.cpp b/llarp/dht/messages/gotrouter.cpp index 040570bfb..4113c0b3b 100644 --- a/llarp/dht/messages/gotrouter.cpp +++ b/llarp/dht/messages/gotrouter.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include @@ -80,7 +80,7 @@ namespace llarp::dht { if (relayed) { - auto pathset = dht.GetRouter()->pathContext().GetLocalPathSet(pathID); + auto pathset = dht.GetRouter()->path_context().GetLocalPathSet(pathID); auto copy = std::make_shared(*this); return pathset && pathset->HandleGotRouterMessage(copy); } @@ -113,15 +113,15 @@ namespace llarp::dht // store if valid for (const auto& rc : foundRCs) { - if (not dht.GetRouter()->rcLookupHandler().CheckRC(rc)) + if (not dht.GetRouter()->rc_lookup_handler().check_rc(rc)) return false; if (txid == 0) // txid == 0 on gossip { auto* router = dht.GetRouter(); - router->NotifyRouterEvent(router->pubkey(), rc); + router->notify_router_event(router->pubkey(), rc); router->GossipRCIfNeeded(rc); - auto peerDb = router->peerDb(); + auto peerDb = router->peer_db(); if (peerDb) peerDb->handleGossipedRC(rc); } diff --git a/llarp/dht/messages/pubintro.cpp b/llarp/dht/messages/pubintro.cpp index a5c6cfee7..13bb0b619 100644 --- a/llarp/dht/messages/pubintro.cpp +++ b/llarp/dht/messages/pubintro.cpp @@ -3,7 +3,7 @@ #include #include "gotintro.hpp" #include -#include +#include #include #include @@ -79,7 +79,8 @@ namespace llarp::dht } // identify closest 4 routers - auto closestRCs = dht.GetRouter()->nodedb()->FindManyClosestTo(addr, IntroSetStorageRedundancy); + auto closestRCs = + dht.GetRouter()->node_db()->FindManyClosestTo(addr, IntroSetStorageRedundancy); if (closestRCs.size() != IntroSetStorageRedundancy) { llarp::LogWarn("Received PublishIntroMessage but only know ", closestRCs.size(), " nodes"); diff --git a/llarp/dht/publishservicejob.cpp b/llarp/dht/publishservicejob.cpp index 7c00ffeac..0420688c3 100644 --- a/llarp/dht/publishservicejob.cpp +++ b/llarp/dht/publishservicejob.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include namespace llarp::dht @@ -59,7 +59,7 @@ namespace llarp::dht LocalPublishServiceJob::SendReply() { auto path = - parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + parent->GetRouter()->path_context().GetByUpstream(parent->OurKey().as_array(), localPath); if (!path) { llarp::LogWarn( diff --git a/llarp/dht/recursiverouterlookup.cpp b/llarp/dht/recursiverouterlookup.cpp index d1812e7b4..6ae5096a1 100644 --- a/llarp/dht/recursiverouterlookup.cpp +++ b/llarp/dht/recursiverouterlookup.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include #include @@ -49,7 +49,7 @@ namespace llarp RouterContact found; for (const auto& rc : valuesFound) { - if (found.OtherIsNewer(rc) && parent->GetRouter()->rcLookupHandler().CheckRC(rc)) + if (found.OtherIsNewer(rc) && parent->GetRouter()->rc_lookup_handler().check_rc(rc)) found = rc; } valuesFound.clear(); diff --git a/llarp/exit/context.cpp b/llarp/exit/context.cpp index e229262ba..fdf0a3118 100644 --- a/llarp/exit/context.cpp +++ b/llarp/exit/context.cpp @@ -2,126 +2,123 @@ #include #include -namespace llarp +namespace llarp::exit { - namespace exit - { - Context::Context(AbstractRouter* r) : m_Router(r) - {} - Context::~Context() = default; + Context::Context(Router* r) : router(r) + {} + Context::~Context() = default; - void - Context::Tick(llarp_time_t now) + void + Context::Tick(llarp_time_t now) + { { + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) - { - itr->second->Tick(now); - ++itr; - } - } - { - auto itr = m_Closed.begin(); - while (itr != m_Closed.end()) - { - if ((*itr)->ShouldRemove()) - itr = m_Closed.erase(itr); - else - ++itr; - } + itr->second->Tick(now); + ++itr; } } - - void - Context::Stop() { - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) + auto itr = m_Closed.begin(); + while (itr != m_Closed.end()) { - itr->second->Stop(); - m_Closed.emplace_back(std::move(itr->second)); - itr = m_Exits.erase(itr); + if ((*itr)->ShouldRemove()) + itr = m_Closed.erase(itr); + else + ++itr; } } + } - util::StatusObject - Context::ExtractStatus() const + void + Context::Stop() + { + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - util::StatusObject obj{}; - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) - { - obj[itr->first] = itr->second->ExtractStatus(); - ++itr; - } - return obj; + itr->second->Stop(); + m_Closed.emplace_back(std::move(itr->second)); + itr = m_Exits.erase(itr); } + } - void - Context::CalculateExitTraffic(TrafficStats& stats) + util::StatusObject + Context::ExtractStatus() const + { + util::StatusObject obj{}; + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) - { - itr->second->CalculateTrafficStats(stats); - ++itr; - } + obj[itr->first] = itr->second->ExtractStatus(); + ++itr; } + return obj; + } - exit::Endpoint* - Context::FindEndpointForPath(const PathID_t& path) const + void + Context::CalculateExitTraffic(TrafficStats& stats) + { + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) - { - auto ep = itr->second->FindEndpointByPath(path); - if (ep) - return ep; - ++itr; - } - return nullptr; + itr->second->CalculateTrafficStats(stats); + ++itr; } + } - bool - Context::ObtainNewExit(const PubKey& pk, const PathID_t& path, bool permitInternet) + exit::Endpoint* + Context::FindEndpointForPath(const PathID_t& path) const + { + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - auto itr = m_Exits.begin(); - while (itr != m_Exits.end()) - { - if (itr->second->AllocateNewExit(pk, path, permitInternet)) - return true; - ++itr; - } - return false; + auto ep = itr->second->FindEndpointByPath(path); + if (ep) + return ep; + ++itr; } + return nullptr; + } - std::shared_ptr - Context::GetExitEndpoint(std::string name) const + bool + Context::ObtainNewExit(const PubKey& pk, const PathID_t& path, bool permitInternet) + { + auto itr = m_Exits.begin(); + while (itr != m_Exits.end()) { - if (auto itr = m_Exits.find(name); itr != m_Exits.end()) - { - return itr->second; - } - return nullptr; + if (itr->second->AllocateNewExit(pk, path, permitInternet)) + return true; + ++itr; } + return false; + } - void - Context::AddExitEndpoint( - const std::string& name, const NetworkConfig& networkConfig, const DnsConfig& dnsConfig) + std::shared_ptr + Context::GetExitEndpoint(std::string name) const + { + if (auto itr = m_Exits.find(name); itr != m_Exits.end()) { - if (m_Exits.find(name) != m_Exits.end()) - throw std::invalid_argument{fmt::format("An exit with name {} already exists", name)}; + return itr->second; + } + return nullptr; + } - auto endpoint = std::make_unique(name, m_Router); - endpoint->Configure(networkConfig, dnsConfig); + void + Context::AddExitEndpoint( + const std::string& name, const NetworkConfig& networkConfig, const DnsConfig& dnsConfig) + { + if (m_Exits.find(name) != m_Exits.end()) + throw std::invalid_argument{fmt::format("An exit with name {} already exists", name)}; - // add endpoint - if (!endpoint->Start()) - throw std::runtime_error{fmt::format("Failed to start endpoint {}", name)}; + auto endpoint = std::make_unique(name, router); + endpoint->Configure(networkConfig, dnsConfig); - m_Exits.emplace(name, std::move(endpoint)); - } + // add endpoint + if (!endpoint->Start()) + throw std::runtime_error{fmt::format("Failed to start endpoint {}", name)}; + + m_Exits.emplace(name, std::move(endpoint)); + } - } // namespace exit -} // namespace llarp +} // namespace llarp::exit diff --git a/llarp/exit/context.hpp b/llarp/exit/context.hpp index beb371aee..7c12f6053 100644 --- a/llarp/exit/context.hpp +++ b/llarp/exit/context.hpp @@ -5,52 +5,49 @@ #include #include -namespace llarp +namespace llarp::exit { - namespace exit + /// owner of all the exit endpoints + struct Context { - /// owner of all the exit endpoints - struct Context - { - Context(AbstractRouter* r); - ~Context(); + Context(Router* r); + ~Context(); - void - Tick(llarp_time_t now); + void + Tick(llarp_time_t now); - void - ClearAllEndpoints(); + void + ClearAllEndpoints(); - util::StatusObject - ExtractStatus() const; + util::StatusObject + ExtractStatus() const; - /// send close to all exit sessions and remove all sessions - void - Stop(); + /// send close to all exit sessions and remove all sessions + void + Stop(); - void - AddExitEndpoint( - const std::string& name, const NetworkConfig& networkConfig, const DnsConfig& dnsConfig); + void + AddExitEndpoint( + const std::string& name, const NetworkConfig& networkConfig, const DnsConfig& dnsConfig); - bool - ObtainNewExit(const PubKey& remote, const PathID_t& path, bool permitInternet); + bool + 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>; + /// calculate (pk, tx, rx) for all exit traffic + using TrafficStats = std::unordered_map>; - void - CalculateExitTraffic(TrafficStats& stats); + void + CalculateExitTraffic(TrafficStats& stats); - std::shared_ptr - GetExitEndpoint(std::string name) const; + std::shared_ptr + GetExitEndpoint(std::string name) const; - private: - AbstractRouter* m_Router; - std::unordered_map> m_Exits; - std::list> m_Closed; - }; - } // namespace exit -} // namespace llarp + private: + Router* router; + std::unordered_map> m_Exits; + std::list> m_Closed; + }; +} // namespace llarp::exit diff --git a/llarp/exit/endpoint.cpp b/llarp/exit/endpoint.cpp index 2b29129dc..7a0c418d1 100644 --- a/llarp/exit/endpoint.cpp +++ b/llarp/exit/endpoint.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include namespace llarp::exit @@ -58,7 +58,7 @@ namespace llarp::exit if (!m_Parent->UpdateEndpointPath(m_remoteSignKey, nextPath)) return false; const RouterID us{m_Parent->GetRouter()->pubkey()}; - m_CurrentPath = m_Parent->GetRouter()->pathContext().GetByUpstream(us, nextPath); + m_CurrentPath = m_Parent->GetRouter()->path_context().GetByUpstream(us, nextPath); return true; } diff --git a/llarp/exit/exit_messages.cpp b/llarp/exit/exit_messages.cpp index d850c6192..0385834f3 100644 --- a/llarp/exit/exit_messages.cpp +++ b/llarp/exit/exit_messages.cpp @@ -103,7 +103,7 @@ namespace llarp::routing } bool - ObtainExitMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + ObtainExitMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleObtainExitMessage(*this, r); } @@ -179,7 +179,7 @@ namespace llarp::routing } bool - GrantExitMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + GrantExitMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleGrantExitMessage(*this, r); } @@ -268,7 +268,7 @@ namespace llarp::routing } bool - RejectExitMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + RejectExitMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleRejectExitMessage(*this, r); } @@ -344,7 +344,7 @@ namespace llarp::routing } bool - UpdateExitMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + UpdateExitMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleUpdateExitMessage(*this, r); } @@ -383,7 +383,7 @@ namespace llarp::routing } bool - UpdateExitVerifyMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + UpdateExitVerifyMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleUpdateExitVerifyMessage(*this, r); } @@ -456,7 +456,7 @@ namespace llarp::routing } bool - CloseExitMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + CloseExitMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleCloseExitMessage(*this, r); } diff --git a/llarp/exit/exit_messages.hpp b/llarp/exit/exit_messages.hpp index 7dbe8975e..18e04187e 100644 --- a/llarp/exit/exit_messages.hpp +++ b/llarp/exit/exit_messages.hpp @@ -49,7 +49,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; }; struct GrantExitMessage final : public AbstractRoutingMessage @@ -73,7 +73,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; void clear() override @@ -116,7 +116,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; }; struct UpdateExitVerifyMessage final : public AbstractRoutingMessage @@ -143,7 +143,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; }; struct UpdateExitMessage final : public AbstractRoutingMessage @@ -167,7 +167,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; void clear() override @@ -193,7 +193,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; bool Sign(const llarp::SecretKey& sk); diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index 6d6ea988f..a56b50d38 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include @@ -14,7 +14,7 @@ namespace llarp::exit BaseSession::BaseSession( const llarp::RouterID& routerId, std::function writepkt, - AbstractRouter* r, + Router* r, size_t numpaths, size_t hoplen, EndpointBase* parent) @@ -76,7 +76,7 @@ namespace llarp::exit { if (numHops == 1) { - if (auto maybe = m_router->nodedb()->Get(m_ExitRouter)) + if (auto maybe = m_router->node_db()->Get(m_ExitRouter)) return std::vector{*maybe}; return std::nullopt; } @@ -187,7 +187,7 @@ namespace llarp::exit } }; ForEachPath(sendExitClose); - m_router->pathContext().RemovePathSet(shared_from_this()); + m_router->path_context().RemovePathSet(shared_from_this()); return path::Builder::Stop(); } @@ -309,7 +309,7 @@ namespace llarp::exit if (numHops == 1) { auto r = m_router; - if (const auto maybe = r->nodedb()->Get(m_ExitRouter); maybe.has_value()) + if (const auto maybe = r->node_db()->Get(m_ExitRouter); maybe.has_value()) r->TryConnectAsync(*maybe, 5); else r->LookupRouter(m_ExitRouter, [r](const std::vector& results) { @@ -337,7 +337,7 @@ namespace llarp::exit SNodeSession::SNodeSession( const llarp::RouterID& snodeRouter, std::function writepkt, - AbstractRouter* r, + Router* r, size_t numpaths, size_t hoplen, bool useRouterSNodeKey, diff --git a/llarp/exit/session.hpp b/llarp/exit/session.hpp index 6d90a9b94..6a34be841 100644 --- a/llarp/exit/session.hpp +++ b/llarp/exit/session.hpp @@ -38,7 +38,7 @@ namespace llarp BaseSession( const llarp::RouterID& exitRouter, std::function writepkt, - AbstractRouter* r, + Router* r, size_t numpaths, size_t hoplen, EndpointBase* parent); @@ -198,7 +198,7 @@ namespace llarp ExitSession( const llarp::RouterID& snodeRouter, std::function writepkt, - AbstractRouter* r, + Router* r, size_t numpaths, size_t hoplen, EndpointBase* parent) @@ -228,7 +228,7 @@ namespace llarp SNodeSession( const llarp::RouterID& snodeRouter, std::function writepkt, - AbstractRouter* r, + Router* r, size_t numpaths, size_t hoplen, bool useRouterSNodeKey, diff --git a/llarp/handlers/exit.cpp b/llarp/handlers/exit.cpp index 02f898b11..018e1d2ec 100644 --- a/llarp/handlers/exit.cpp +++ b/llarp/handlers/exit.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include @@ -13,886 +13,883 @@ #include #include -namespace llarp +namespace llarp::handlers { - namespace handlers + ExitEndpoint::ExitEndpoint(std::string name, Router* r) + : router(r) + , name(std::move(name)) + , tunnel_manager{std::make_shared(*this)} { - ExitEndpoint::ExitEndpoint(std::string name, AbstractRouter* r) - : m_Router(r), m_Name(std::move(name)), m_QUIC{std::make_shared(*this)} - { - m_ShouldInitTun = true; - m_QUIC = std::make_shared(*this); - } + should_init_tun = true; + tunnel_manager = std::make_shared(*this); + } - ExitEndpoint::~ExitEndpoint() = default; + ExitEndpoint::~ExitEndpoint() = default; - void - ExitEndpoint::LookupNameAsync( - std::string, std::function)> resultHandler) - { - // TODO: implement me - resultHandler(std::nullopt); - } + void + ExitEndpoint::LookupNameAsync( + std::string, std::function)> resultHandler) + { + // TODO: implement me + resultHandler(std::nullopt); + } - void - ExitEndpoint::LookupServiceAsync( - std::string, std::string, std::function)> resultHandler) + void + ExitEndpoint::LookupServiceAsync( + std::string, std::string, std::function)> resultHandler) + { + // TODO: implement me + resultHandler({}); + } + + std::optional + ExitEndpoint::GetEndpointWithConvoTag(service::ConvoTag tag) const + { + for (const auto& [pathID, pk] : paths) { - // TODO: implement me - resultHandler({}); + if (pathID.as_array() == tag.as_array()) + return RouterID{pk.as_array()}; } - - std::optional - ExitEndpoint::GetEndpointWithConvoTag(service::ConvoTag tag) const + for (const auto& [rid, session] : snode_sessions) { - for (const auto& [pathID, pk] : m_Paths) - { - if (pathID.as_array() == tag.as_array()) - return RouterID{pk.as_array()}; - } - for (const auto& [rid, session] : m_SNodeSessions) - { - PathID_t pathID{tag.as_array()}; - if (session->GetPathByID(pathID)) - return rid; - } - return std::nullopt; + PathID_t pathID{tag.as_array()}; + if (session->GetPathByID(pathID)) + return rid; } + return std::nullopt; + } - std::optional - ExitEndpoint::GetBestConvoTagFor(AddressVariant_t addr) const + std::optional + ExitEndpoint::GetBestConvoTagFor(AddressVariant_t addr) const + { + if (auto* rid = std::get_if(&addr)) { - if (auto* rid = std::get_if(&addr)) - { - service::ConvoTag tag{}; - auto visit = [&tag](exit::Endpoint* const ep) -> bool { - if (not ep) - return false; - if (auto path = ep->GetCurrentPath()) - tag = service::ConvoTag{path->RXID().as_array()}; - return true; - }; - if (VisitEndpointsFor(PubKey{*rid}, visit) and not tag.IsZero()) - return tag; - auto itr = m_SNodeSessions.find(*rid); - if (itr == m_SNodeSessions.end()) - { - return std::nullopt; - } - if (auto path = itr->second->GetPathByRouter(*rid)) - { + service::ConvoTag tag{}; + auto visit = [&tag](exit::Endpoint* const ep) -> bool { + if (not ep) + return false; + if (auto path = ep->GetCurrentPath()) tag = service::ConvoTag{path->RXID().as_array()}; - return tag; - } + return true; + }; + if (VisitEndpointsFor(PubKey{*rid}, visit) and not tag.IsZero()) + return tag; + auto itr = snode_sessions.find(*rid); + if (itr == snode_sessions.end()) + { return std::nullopt; } + if (auto path = itr->second->GetPathByRouter(*rid)) + { + tag = service::ConvoTag{path->RXID().as_array()}; + return tag; + } return std::nullopt; } + return std::nullopt; + } - const EventLoop_ptr& - ExitEndpoint::Loop() - { - return m_Router->loop(); - } + const EventLoop_ptr& + ExitEndpoint::Loop() + { + return router->loop(); + } - bool - ExitEndpoint::SendToOrQueue( - service::ConvoTag tag, const llarp_buffer_t& payload, service::ProtocolType type) + bool + ExitEndpoint::SendToOrQueue( + service::ConvoTag tag, const llarp_buffer_t& payload, service::ProtocolType type) + { + if (auto maybeAddr = GetEndpointWithConvoTag(tag)) { - if (auto maybeAddr = GetEndpointWithConvoTag(tag)) + if (std::holds_alternative(*maybeAddr)) + return false; + if (auto* rid = std::get_if(&*maybeAddr)) { - if (std::holds_alternative(*maybeAddr)) - return false; - if (auto* rid = std::get_if(&*maybeAddr)) + for (auto [itr, end] = active_exits.equal_range(PubKey{*rid}); itr != end; ++itr) { - for (auto [itr, end] = m_ActiveExits.equal_range(PubKey{*rid}); itr != end; ++itr) + if (not itr->second->LooksDead(Now())) { - if (not itr->second->LooksDead(Now())) - { - if (itr->second->QueueInboundTraffic(payload.copy(), type)) - return true; - } + if (itr->second->QueueInboundTraffic(payload.copy(), type)) + return true; } + } - if (not m_Router->PathToRouterAllowed(*rid)) - return false; + if (not router->PathToRouterAllowed(*rid)) + return false; - ObtainSNodeSession(*rid, [pkt = payload.copy(), type](auto session) mutable { - if (session and session->IsReady()) - { - session->SendPacketToRemote(std::move(pkt), type); - } - }); - } - return true; + ObtainSNodeSession(*rid, [pkt = payload.copy(), type](auto session) mutable { + if (session and session->IsReady()) + { + session->SendPacketToRemote(std::move(pkt), type); + } + }); } - return false; + return true; } + return false; + } - bool - ExitEndpoint::EnsurePathTo( - AddressVariant_t addr, - std::function)> hook, - llarp_time_t) + bool + ExitEndpoint::EnsurePathTo( + AddressVariant_t addr, + std::function)> hook, + llarp_time_t) + { + if (std::holds_alternative(addr)) + return false; + if (auto* rid = std::get_if(&addr)) { - if (std::holds_alternative(addr)) - return false; - if (auto* rid = std::get_if(&addr)) + if (snode_keys.count(PubKey{*rid}) or router->PathToRouterAllowed(*rid)) { - if (m_SNodeKeys.count(PubKey{*rid}) or m_Router->PathToRouterAllowed(*rid)) - { - ObtainSNodeSession( - *rid, [hook, routerID = *rid](std::shared_ptr session) { - if (session and session->IsReady()) + ObtainSNodeSession( + *rid, [hook, routerID = *rid](std::shared_ptr session) { + if (session and session->IsReady()) + { + if (auto path = session->GetPathByRouter(routerID)) { - if (auto path = session->GetPathByRouter(routerID)) - { - hook(service::ConvoTag{path->RXID().as_array()}); - } - else - hook(std::nullopt); + hook(service::ConvoTag{path->RXID().as_array()}); } else hook(std::nullopt); - }); - } - else - { - // probably a client - hook(GetBestConvoTagFor(addr)); - } + } + else + hook(std::nullopt); + }); } - return true; - } - - util::StatusObject - ExitEndpoint::ExtractStatus() const - { - util::StatusObject obj{{"permitExit", m_PermitExit}, {"ip", m_IfAddr.ToString()}}; - util::StatusObject exitsObj{}; - for (const auto& item : m_ActiveExits) + else { - exitsObj[item.first.ToString()] = item.second->ExtractStatus(); + // probably a client + hook(GetBestConvoTagFor(addr)); } - obj["exits"] = exitsObj; - return obj; } + return true; + } - bool - ExitEndpoint::SupportsV6() const + util::StatusObject + ExitEndpoint::ExtractStatus() const + { + util::StatusObject obj{{"permitExit", permit_exit}, {"ip", if_addr.ToString()}}; + util::StatusObject exitsObj{}; + for (const auto& item : active_exits) { - return m_UseV6; + exitsObj[item.first.ToString()] = item.second->ExtractStatus(); } + obj["exits"] = exitsObj; + return obj; + } - bool - ExitEndpoint::ShouldHookDNSMessage(const dns::Message& msg) const + bool + ExitEndpoint::SupportsV6() const + { + return use_ipv6; + } + + bool + ExitEndpoint::ShouldHookDNSMessage(const dns::Message& msg) const + { + if (msg.questions.size() == 0) + return false; + // always hook ptr for ranges we own + if (msg.questions[0].qtype == dns::qTypePTR) { - if (msg.questions.size() == 0) - return false; - // always hook ptr for ranges we own - if (msg.questions[0].qtype == dns::qTypePTR) - { - if (auto ip = dns::DecodePTR(msg.questions[0].qname)) - return m_OurRange.Contains(*ip); - return false; - } - 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")) - return true; - if (msg.questions[0].HasTLD(".snode")) - return true; - } + if (auto ip = dns::DecodePTR(msg.questions[0].qname)) + return ip_range.Contains(*ip); return false; } - - bool - ExitEndpoint::MaybeHookDNS( - std::shared_ptr source, - const dns::Message& query, - const SockAddr& to, - const SockAddr& from) + if (msg.questions[0].qtype == dns::qTypeA || msg.questions[0].qtype == dns::qTypeCNAME + || msg.questions[0].qtype == dns::qTypeAAAA) { - if (not ShouldHookDNSMessage(query)) - return false; - - auto job = std::make_shared(source, query, to, from); - if (not HandleHookedDNSMessage(query, [job](auto msg) { job->SendReply(msg.ToBuffer()); })) - job->Cancel(); - return true; + if (msg.questions[0].IsName("localhost.loki")) + return true; + if (msg.questions[0].HasTLD(".snode")) + return true; } + return false; + } - bool - ExitEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function reply) + bool + ExitEndpoint::MaybeHookDNS( + std::shared_ptr source, + const dns::Message& query, + const SockAddr& to, + const SockAddr& from) + { + if (not ShouldHookDNSMessage(query)) + return false; + + auto job = std::make_shared(source, query, to, from); + if (not HandleHookedDNSMessage(query, [job](auto msg) { job->SendReply(msg.ToBuffer()); })) + job->Cancel(); + return true; + } + + bool + ExitEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function reply) + { + if (msg.questions[0].qtype == dns::qTypePTR) { - if (msg.questions[0].qtype == dns::qTypePTR) + auto ip = dns::DecodePTR(msg.questions[0].qname); + if (not ip) + return false; + if (ip == if_addr) { - auto ip = dns::DecodePTR(msg.questions[0].qname); - if (not ip) - return false; - if (ip == m_IfAddr) + RouterID us = GetRouter()->pubkey(); + msg.AddAReply(us.ToString(), 300); + } + else + { + auto itr = ip_to_key.find(*ip); + if (itr != ip_to_key.end() && snode_keys.find(itr->second) != snode_keys.end()) { - RouterID us = GetRouter()->pubkey(); - msg.AddAReply(us.ToString(), 300); + RouterID them = itr->second; + msg.AddAReply(them.ToString()); } else - { - auto itr = m_IPToKey.find(*ip); - if (itr != m_IPToKey.end() && m_SNodeKeys.find(itr->second) != m_SNodeKeys.end()) - { - RouterID them = itr->second; - msg.AddAReply(them.ToString()); - } - else - msg.AddNXReply(); - } + 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)) - msg.AddCNAMEReply(random.ToString(), 1); - else - msg.AddNXReply(); - } - else if (msg.questions[0].IsName("localhost.loki")) + RouterID random; + if (GetRouter()->GetRandomGoodRouter(random)) + msg.AddCNAMEReply(random.ToString(), 1); + else + msg.AddNXReply(); + } + else if (msg.questions[0].IsName("localhost.loki")) + { + RouterID us = router->pubkey(); + msg.AddAReply(us.ToString(), 1); + } + else + msg.AddNXReply(); + } + 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")) + { + RouterID random; + if (GetRouter()->GetRandomGoodRouter(random)) { - RouterID us = m_Router->pubkey(); - msg.AddAReply(us.ToString(), 1); + msg.AddCNAMEReply(random.ToString(), 1); + auto ip = ObtainServiceNodeIP(random); + msg.AddINReply(ip, false); } else msg.AddNXReply(); + reply(msg); + return true; } - else if (msg.questions[0].qtype == dns::qTypeA || msg.questions[0].qtype == dns::qTypeAAAA) + if (msg.questions[0].IsName("localhost.loki")) { - 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")) + msg.AddINReply(GetIfAddr(), isV6); + reply(msg); + return true; + } + // forward dns for snode + RouterID r; + if (r.FromString(msg.questions[0].Name())) + { + huint128_t ip; + PubKey pubKey(r); + if (isV4 && SupportsV6()) { - RouterID random; - if (GetRouter()->GetRandomGoodRouter(random)) - { - msg.AddCNAMEReply(random.ToString(), 1); - auto ip = ObtainServiceNodeIP(random); - msg.AddINReply(ip, false); - } - else - msg.AddNXReply(); - reply(msg); - return true; + msg.hdr_fields |= dns::flags_QR | dns::flags_AA | dns::flags_RA; } - if (msg.questions[0].IsName("localhost.loki")) + else if (snode_keys.find(pubKey) == snode_keys.end()) { - msg.AddINReply(GetIfAddr(), isV6); - reply(msg); + // we do not have it mapped, async obtain it + ObtainSNodeSession( + r, + [&, msg = std::make_shared(msg), reply]( + std::shared_ptr session) { + if (session && session->IsReady()) + { + msg->AddINReply(key_to_IP[pubKey], isV6); + } + else + { + msg->AddNXReply(); + } + reply(*msg); + }); return true; } - // forward dns for snode - RouterID r; - if (r.FromString(msg.questions[0].Name())) + else { - huint128_t ip; - PubKey pubKey(r); - if (isV4 && SupportsV6()) - { - msg.hdr_fields |= dns::flags_QR | dns::flags_AA | dns::flags_RA; - } - else if (m_SNodeKeys.find(pubKey) == m_SNodeKeys.end()) - { - // we do not have it mapped, async obtain it - ObtainSNodeSession( - r, - [&, msg = std::make_shared(msg), reply]( - 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 = key_to_IP.find(pubKey); + if (itr != key_to_IP.end()) { - // we have it mapped already as a service node - auto itr = m_KeyToIP.find(pubKey); - if (itr != m_KeyToIP.end()) - { - ip = itr->second; - msg.AddINReply(ip, isV6); - } - else // fallback case that should never happen (probably) - msg.AddNXReply(); + ip = itr->second; + msg.AddINReply(ip, isV6); } + else // fallback case that should never happen (probably) + msg.AddNXReply(); } - else - msg.AddNXReply(); } - reply(msg); - return true; + else + msg.AddNXReply(); } + reply(msg); + return true; + } - void - ExitEndpoint::ObtainSNodeSession(const RouterID& router, exit::SessionReadyFunc obtainCb) + void + ExitEndpoint::ObtainSNodeSession(const RouterID& rid, exit::SessionReadyFunc obtain_cb) + { + if (not router->rc_lookup_handler().is_session_allowed(rid)) { - if (not m_Router->rcLookupHandler().SessionIsAllowed(router)) - { - obtainCb(nullptr); - return; - } - ObtainServiceNodeIP(router); - m_SNodeSessions[router]->AddReadyHook(obtainCb); + obtain_cb(nullptr); + return; } + ObtainServiceNodeIP(rid); + snode_sessions[rid]->AddReadyHook(obtain_cb); + } - llarp_time_t - ExitEndpoint::Now() const - { - return m_Router->Now(); - } + llarp_time_t + ExitEndpoint::Now() const + { + return router->Now(); + } - bool - ExitEndpoint::VisitEndpointsFor( - const PubKey& pk, std::function visit) const + bool + ExitEndpoint::VisitEndpointsFor( + const PubKey& pk, std::function visit) const + { + for (auto [itr, end] = active_exits.equal_range(pk); itr != end; ++itr) { - for (auto [itr, end] = m_ActiveExits.equal_range(pk); itr != end; ++itr) - { - if (not visit(itr->second.get())) - return true; - } - return false; + if (not visit(itr->second.get())) + return true; } + return false; + } - void - ExitEndpoint::Flush() + void + ExitEndpoint::Flush() + { + while (not inet_to_network.empty()) { - while (not m_InetToNetwork.empty()) - { - auto& top = m_InetToNetwork.top(); + auto& top = inet_to_network.top(); - // get a session by public key - std::optional maybe_pk; - { - auto itr = m_IPToKey.find(top.dstv6()); - if (itr != m_IPToKey.end()) - maybe_pk = itr->second; - } + // get a session by public key + std::optional maybe_pk; + { + auto itr = ip_to_key.find(top.dstv6()); + if (itr != ip_to_key.end()) + maybe_pk = itr->second; + } - auto buf = const_cast(top).steal(); - m_InetToNetwork.pop(); - // we have no session for public key so drop - if (not maybe_pk) - continue; // we are in a while loop + auto buf = const_cast(top).steal(); + inet_to_network.pop(); + // we have no session for public key so drop + if (not maybe_pk) + continue; // we are in a while loop - const auto& pk = *maybe_pk; + const auto& pk = *maybe_pk; - // check if this key is a service node - if (m_SNodeKeys.count(pk)) + // check if this key is a service node + if (snode_keys.count(pk)) + { + // 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 = snode_sessions.find(pk); + if (itr != snode_sessions.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()) - { - itr->second->SendPacketToRemote(std::move(buf), service::ProtocolType::TrafficV4); - // we are in a while loop - continue; - } + itr->second->SendPacketToRemote(std::move(buf), service::ProtocolType::TrafficV4); + // we are in a while loop + continue; } - auto tryFlushingTraffic = - [this, buf = std::move(buf), pk](exit::Endpoint* const ep) -> bool { - if (!ep->QueueInboundTraffic(buf, service::ProtocolType::TrafficV4)) - { - 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)) + } + auto tryFlushingTraffic = [this, buf = std::move(buf), pk](exit::Endpoint* const ep) -> bool { + if (!ep->QueueInboundTraffic(buf, service::ProtocolType::TrafficV4)) { - // we may have all dead sessions, wtf now? LogWarn( Name(), " dropped inbound traffic for session ", pk, - " as we have no working endpoints"); + " as we are overloaded (probably)"); + // continue iteration + return true; } - } - - for (auto& [pubkey, endpoint] : m_ActiveExits) + // break iteration + return false; + }; + if (!VisitEndpointsFor(pk, tryFlushingTraffic)) { - if (!endpoint->Flush()) - { - LogWarn("exit session with ", pubkey, " dropped packets"); - } + // we may have all dead sessions, wtf now? + LogWarn( + Name(), + " dropped inbound traffic for session ", + pk, + " as we have no working endpoints"); } - for (auto& [id, session] : m_SNodeSessions) + } + + for (auto& [pubkey, endpoint] : active_exits) + { + if (!endpoint->Flush()) { - session->FlushUpstream(); - session->FlushDownstream(); + LogWarn("exit session with ", pubkey, " dropped packets"); } } + for (auto& [id, session] : snode_sessions) + { + session->FlushUpstream(); + session->FlushDownstream(); + } + } - bool - ExitEndpoint::Start() + bool + ExitEndpoint::Start() + { + // map our address + const PubKey us(router->pubkey()); + const huint128_t ip = GetIfAddr(); + key_to_IP[us] = ip; + ip_to_key[ip] = us; + ip_activity[ip] = std::numeric_limits::max(); + snode_keys.insert(us); + + if (should_init_tun) { - // 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::max(); - m_SNodeKeys.insert(us); + vpn::InterfaceInfo info; + info.ifname = if_name; + info.addrs.emplace_back(ip_range); - if (m_ShouldInitTun) + if_net = GetRouter()->vpn_platform()->CreateInterface(std::move(info), router); + if (not if_net) { - vpn::InterfaceInfo info; - info.ifname = m_ifname; - info.addrs.emplace_back(m_OurRange); - - m_NetIf = GetRouter()->GetVPNPlatform()->CreateInterface(std::move(info), m_Router); - if (not m_NetIf) - { - llarp::LogError("Could not create interface"); - return false; - } - if (not GetRouter()->loop()->add_network_interface( - m_NetIf, [this](net::IPPacket pkt) { OnInetPacket(std::move(pkt)); })) - { - llarp::LogWarn("Could not create tunnel for exit endpoint"); - return false; - } + llarp::LogError("Could not create interface"); + return false; + } + if (not GetRouter()->loop()->add_network_interface( + if_net, [this](net::IPPacket pkt) { OnInetPacket(std::move(pkt)); })) + { + llarp::LogWarn("Could not create tunnel for exit endpoint"); + return false; + } - GetRouter()->loop()->add_ticker([this] { Flush(); }); + GetRouter()->loop()->add_ticker([this] { Flush(); }); #ifndef _WIN32 - m_Resolver = std::make_shared( - m_Router->loop(), m_DNSConf, if_nametoindex(m_ifname.c_str())); - m_Resolver->Start(); + resolver = + std::make_shared(router->loop(), dns_conf, if_nametoindex(if_name.c_str())); + resolver->Start(); #endif - } - return true; } + return true; + } - AbstractRouter* - ExitEndpoint::GetRouter() - { - return m_Router; - } + Router* + ExitEndpoint::GetRouter() + { + return router; + } - huint128_t - ExitEndpoint::GetIfAddr() const - { - return m_IfAddr; - } + huint128_t + ExitEndpoint::GetIfAddr() const + { + return if_addr; + } - bool - ExitEndpoint::Stop() - { - for (auto& item : m_SNodeSessions) - item.second->Stop(); - return true; - } + bool + ExitEndpoint::Stop() + { + for (auto& item : snode_sessions) + item.second->Stop(); + return true; + } - bool - ExitEndpoint::ShouldRemove() const - { - for (auto& item : m_SNodeSessions) - if (!item.second->ShouldRemove()) - return false; - return true; - } + bool + ExitEndpoint::ShouldRemove() const + { + for (auto& item : snode_sessions) + if (!item.second->ShouldRemove()) + return false; + return true; + } - bool - ExitEndpoint::HasLocalMappedAddrFor(const PubKey& pk) const - { - return m_KeyToIP.find(pk) != m_KeyToIP.end(); - } + bool + ExitEndpoint::HasLocalMappedAddrFor(const PubKey& pk) const + { + return key_to_IP.find(pk) != key_to_IP.end(); + } - huint128_t - ExitEndpoint::GetIPForIdent(const PubKey pk) + huint128_t + ExitEndpoint::GetIPForIdent(const PubKey pk) + { + huint128_t found{}; + if (!HasLocalMappedAddrFor(pk)) { - huint128_t found{}; - if (!HasLocalMappedAddrFor(pk)) + // allocate and map + found = AllocateNewAddress(); + if (!key_to_IP.emplace(pk, found).second) { - // allocate and map - found = AllocateNewAddress(); - if (!m_KeyToIP.emplace(pk, found).second) - { - LogError(Name(), "failed to map ", pk, " to ", found); - return found; - } - if (!m_IPToKey.emplace(found, pk).second) - { - LogError(Name(), "failed to map ", found, " to ", pk); - return found; - } - if (HasLocalMappedAddrFor(pk)) - LogInfo(Name(), " mapping ", pk, " to ", found); - else - LogError(Name(), "failed to map ", pk, " to ", found); + LogError(Name(), "failed to map ", pk, " to ", found); + return found; + } + if (!ip_to_key.emplace(found, pk).second) + { + LogError(Name(), "failed to map ", found, " to ", pk); + return found; } + if (HasLocalMappedAddrFor(pk)) + LogInfo(Name(), " mapping ", pk, " to ", found); else - found = m_KeyToIP[pk]; - - MarkIPActive(found); - m_KeyToIP.rehash(0); - assert(HasLocalMappedAddrFor(pk)); - return found; + LogError(Name(), "failed to map ", pk, " to ", found); } + else + found = key_to_IP[pk]; - huint128_t - ExitEndpoint::AllocateNewAddress() - { - if (m_NextAddr < m_HigestAddr) - return ++m_NextAddr; + MarkIPActive(found); + key_to_IP.rehash(0); + assert(HasLocalMappedAddrFor(pk)); + return found; + } - // find oldest activity ip address - huint128_t found = {0}; - llarp_time_t min = std::numeric_limits::max(); - for (const auto& [addr, time] : m_IPActivity) + huint128_t + ExitEndpoint::AllocateNewAddress() + { + if (next_addr < highest_addr) + return ++next_addr; + + // find oldest activity ip address + huint128_t found = {0}; + llarp_time_t min = std::numeric_limits::max(); + for (const auto& [addr, time] : ip_activity) + { + if (time < min) { - if (time < min) - { - found.h = addr.h; - min = time; - } + found.h = addr.h; + min = time; } - // kick old ident off exit - // TODO: DoS - PubKey pk = m_IPToKey[found]; - KickIdentOffExit(pk); - - return found; } + // kick old ident off exit + // TODO: DoS + PubKey pk = ip_to_key[found]; + KickIdentOffExit(pk); - EndpointBase::AddressVariant_t - ExitEndpoint::LocalAddress() const - { - return RouterID{m_Router->pubkey()}; - } + return found; + } - void - ExitEndpoint::SRVRecordsChanged() - { - m_Router->ModifyOurRC( - [srvRecords = SRVRecords()](RouterContact rc) -> std::optional { - // check if there are any new srv records - bool shouldUpdate = false; + EndpointBase::AddressVariant_t + ExitEndpoint::LocalAddress() const + { + return RouterID{router->pubkey()}; + } - for (const auto& rcSrv : rc.srvRecords) - { - if (srvRecords.count(rcSrv) == 0) - shouldUpdate = true; - } + void + ExitEndpoint::SRVRecordsChanged() + { + router->modify_rc( + [srvRecords = SRVRecords()](RouterContact rc) -> std::optional { + // check if there are any new srv records + bool shouldUpdate = false; - // no new records so don't modify - if (not shouldUpdate) - return std::nullopt; + for (const auto& rcSrv : rc.srvRecords) + { + if (srvRecords.count(rcSrv) == 0) + shouldUpdate = true; + } - // we got new entries so we clear the whole vector on the rc and recreate it - rc.srvRecords.clear(); - for (auto& record : srvRecords) - rc.srvRecords.emplace_back(record); - // set the verssion to 1 because we have srv records - rc.version = 1; - return rc; - }); - } + // no new records so don't modify + if (not shouldUpdate) + return std::nullopt; + + // we got new entries so we clear the whole vector on the rc and recreate it + rc.srvRecords.clear(); + for (auto& record : srvRecords) + rc.srvRecords.emplace_back(record); + // set the verssion to 1 because we have srv records + rc.version = 1; + return rc; + }); + } - std::optional - ExitEndpoint::GetStatFor(AddressVariant_t) const - { - /// TODO: implement me - return std::nullopt; - } + std::optional + ExitEndpoint::GetStatFor(AddressVariant_t) const + { + /// TODO: implement me + return std::nullopt; + } - std::unordered_set - ExitEndpoint::AllRemoteEndpoints() const + std::unordered_set + ExitEndpoint::AllRemoteEndpoints() const + { + std::unordered_set remote; + for (const auto& [path, pubkey] : paths) { - std::unordered_set remote; - for (const auto& [path, pubkey] : m_Paths) - { - remote.insert(RouterID{pubkey}); - } - return remote; + remote.insert(RouterID{pubkey}); } + return remote; + } - bool - ExitEndpoint::QueueOutboundTraffic(net::IPPacket pkt) - { - return m_NetIf && m_NetIf->WritePacket(std::move(pkt)); - } + bool + ExitEndpoint::QueueOutboundTraffic(net::IPPacket pkt) + { + return if_net && if_net->WritePacket(std::move(pkt)); + } - void - 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); - for (auto [exit_itr, end] = m_ActiveExits.equal_range(pk); exit_itr != end;) - exit_itr = m_ActiveExits.erase(exit_itr); - } + void + ExitEndpoint::KickIdentOffExit(const PubKey& pk) + { + LogInfo(Name(), " kicking ", pk, " off exit"); + huint128_t ip = key_to_IP[pk]; + key_to_IP.erase(pk); + ip_to_key.erase(ip); + for (auto [exit_itr, end] = active_exits.equal_range(pk); exit_itr != end;) + exit_itr = active_exits.erase(exit_itr); + } + + void + ExitEndpoint::MarkIPActive(huint128_t ip) + { + ip_activity[ip] = GetRouter()->Now(); + } - void - ExitEndpoint::MarkIPActive(huint128_t ip) - { - m_IPActivity[ip] = GetRouter()->Now(); - } + void + ExitEndpoint::OnInetPacket(net::IPPacket pkt) + { + inet_to_network.emplace(std::move(pkt)); + } - void - ExitEndpoint::OnInetPacket(net::IPPacket pkt) - { - m_InetToNetwork.emplace(std::move(pkt)); - } + bool + ExitEndpoint::QueueSNodePacket(const llarp_buffer_t& buf, huint128_t from) + { + net::IPPacket pkt{buf.view_all()}; + if (pkt.empty()) + return false; + // rewrite ip + if (use_ipv6) + pkt.UpdateIPv6Address(from, if_addr); + else + pkt.UpdateIPv4Address(xhtonl(net::TruncateV6(from)), xhtonl(net::TruncateV6(if_addr))); + return if_net and if_net->WritePacket(std::move(pkt)); + } + + exit::Endpoint* + ExitEndpoint::FindEndpointByPath(const PathID_t& path) + { + exit::Endpoint* endpoint = nullptr; + PubKey pk; + if (auto itr = paths.find(path); itr != paths.end()) + pk = itr->second; + else + return nullptr; + if (auto itr = active_exits.find(pk); itr != active_exits.end()) + { + if (itr->second->PubKey() == pk) + endpoint = itr->second.get(); + } + return endpoint; + } + + bool + ExitEndpoint::UpdateEndpointPath(const PubKey& remote, const PathID_t& next) + { + // check if already mapped + if (auto itr = paths.find(next); itr != paths.end()) + return false; + paths.emplace(next, remote); + return true; + } - bool - ExitEndpoint::QueueSNodePacket(const llarp_buffer_t& buf, huint128_t from) + void + ExitEndpoint::Configure(const NetworkConfig& networkConfig, const DnsConfig& dnsConfig) + { + /* + * TODO: pre-config refactor, this was checking a couple things that were extremely vague + * these could have appeared on either [dns] or [network], but they weren't documented + * anywhere + * + if (k == "type" && v == "null") + { + m_ShouldInitTun = false; + return true; + } + if (k == "exit") { - net::IPPacket pkt{buf.view_all()}; - if (pkt.empty()) - return false; - // rewrite ip - if (m_UseV6) - pkt.UpdateIPv6Address(from, m_IfAddr); - else - pkt.UpdateIPv4Address(xhtonl(net::TruncateV6(from)), xhtonl(net::TruncateV6(m_IfAddr))); - return m_NetIf and m_NetIf->WritePacket(std::move(pkt)); + m_PermitExit = IsTrueValue(v.c_str()); + return true; } + */ + + dns_conf = dnsConfig; - exit::Endpoint* - ExitEndpoint::FindEndpointByPath(const PathID_t& path) + if (networkConfig.m_endpointType == "null") { - exit::Endpoint* endpoint = nullptr; - PubKey pk; - if (auto itr = m_Paths.find(path); itr != m_Paths.end()) - pk = itr->second; - else - return nullptr; - if (auto itr = m_ActiveExits.find(pk); itr != m_ActiveExits.end()) - { - if (itr->second->PubKey() == pk) - endpoint = itr->second.get(); - } - return endpoint; + should_init_tun = false; } - bool - ExitEndpoint::UpdateEndpointPath(const PubKey& remote, const PathID_t& next) + ip_range = networkConfig.m_ifaddr; + if (!ip_range.addr.h) { - // check if already mapped - if (auto itr = m_Paths.find(next); itr != m_Paths.end()) - return false; - m_Paths.emplace(next, remote); - return true; + const auto maybe = router->net().FindFreeRange(); + if (not maybe.has_value()) + throw std::runtime_error("cannot find free interface range"); + ip_range = *maybe; } + const auto host_str = ip_range.BaseAddressString(); + // string, or just a plain char array? + if_addr = ip_range.addr; + next_addr = if_addr; + highest_addr = ip_range.HighestAddr(); + use_ipv6 = not ip_range.IsV4(); - void - ExitEndpoint::Configure(const NetworkConfig& networkConfig, const DnsConfig& dnsConfig) + if_name = networkConfig.m_ifname; + if (if_name.empty()) { - /* - * TODO: pre-config refactor, this was checking a couple things that were extremely vague - * these could have appeared on either [dns] or [network], but they weren't documented - * anywhere - * - if (k == "type" && v == "null") - { - m_ShouldInitTun = false; - return true; - } - if (k == "exit") - { - m_PermitExit = IsTrueValue(v.c_str()); - return true; - } - */ - - m_DNSConf = dnsConfig; - - if (networkConfig.m_endpointType == "null") - { - m_ShouldInitTun = false; - } - - m_OurRange = networkConfig.m_ifaddr; - if (!m_OurRange.addr.h) - { - const auto maybe = m_Router->Net().FindFreeRange(); - if (not maybe.has_value()) - throw std::runtime_error("cannot find free interface range"); - m_OurRange = *maybe; - } - const auto host_str = m_OurRange.BaseAddressString(); - // string, or just a plain char array? - m_IfAddr = m_OurRange.addr; - m_NextAddr = m_IfAddr; - m_HigestAddr = m_OurRange.HighestAddr(); - m_UseV6 = not m_OurRange.IsV4(); - - m_ifname = networkConfig.m_ifname; - if (m_ifname.empty()) - { - const auto maybe = m_Router->Net().FindFreeTun(); - if (not maybe.has_value()) - throw std::runtime_error("cannot find free interface name"); - m_ifname = *maybe; - } - LogInfo(Name(), " set ifname to ", m_ifname); - if (auto* quic = GetQUICTunnel()) - { - quic->listen([ifaddr = net::TruncateV6(m_IfAddr)](std::string_view, uint16_t port) { - return llarp::SockAddr{ifaddr, huint16_t{port}}; - }); - } + const auto maybe = router->net().FindFreeTun(); + if (not maybe.has_value()) + throw std::runtime_error("cannot find free interface name"); + if_name = *maybe; } - - huint128_t - ExitEndpoint::ObtainServiceNodeIP(const RouterID& other) + LogInfo(Name(), " set ifname to ", if_name); + if (auto* quic = GetQUICTunnel()) { - const PubKey pubKey{other}; - const PubKey us{m_Router->pubkey()}; - // just in case - if (pubKey == us) - return m_IfAddr; - - huint128_t ip = GetIPForIdent(pubKey); - if (m_SNodeKeys.emplace(pubKey).second) - { - auto session = std::make_shared( - other, - [this, ip](const auto& buf) { return QueueSNodePacket(buf, ip); }, - GetRouter(), - 2, - 1, - true, - this); - // this is a new service node make an outbound session to them - m_SNodeSessions[other] = session; - } - return ip; + quic->listen([ifaddr = net::TruncateV6(if_addr)](std::string_view, uint16_t port) { + return llarp::SockAddr{ifaddr, huint16_t{port}}; + }); } + } - quic::TunnelManager* - ExitEndpoint::GetQUICTunnel() + huint128_t + ExitEndpoint::ObtainServiceNodeIP(const RouterID& other) + { + const PubKey pubKey{other}; + const PubKey us{router->pubkey()}; + // just in case + if (pubKey == us) + return if_addr; + + huint128_t ip = GetIPForIdent(pubKey); + if (snode_keys.emplace(pubKey).second) + { + auto session = std::make_shared( + other, + [this, ip](const auto& buf) { return QueueSNodePacket(buf, ip); }, + GetRouter(), + 2, + 1, + true, + this); + // this is a new service node make an outbound session to them + snode_sessions[other] = session; + } + return ip; + } + + quic::TunnelManager* + ExitEndpoint::GetQUICTunnel() + { + return tunnel_manager.get(); + } + + bool + ExitEndpoint::AllocateNewExit(const PubKey pk, const PathID_t& path, bool wantInternet) + { + if (wantInternet && !permit_exit) + return false; + path::HopHandler_ptr handler = router->path_context().GetByUpstream(router->pubkey(), path); + if (handler == nullptr) + return false; + auto ip = GetIPForIdent(pk); + if (GetRouter()->path_context().TransitHopPreviousIsRouter(path, pk.as_array())) { - return m_QUIC.get(); + // we think this path belongs to a service node + // mark it as such so we don't make an outbound session to them + snode_keys.emplace(pk.as_array()); } + active_exits.emplace( + pk, std::make_unique(pk, handler, !wantInternet, ip, this)); - bool - ExitEndpoint::AllocateNewExit(const PubKey pk, const PathID_t& path, bool wantInternet) - { - if (wantInternet && !m_PermitExit) - return false; - path::HopHandler_ptr handler = - m_Router->pathContext().GetByUpstream(m_Router->pubkey(), path); - if (handler == nullptr) - return false; - auto ip = GetIPForIdent(pk); - 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(pk, handler, !wantInternet, ip, this)); + paths[path] = pk; - m_Paths[path] = pk; + return HasLocalMappedAddrFor(pk); + } - return HasLocalMappedAddrFor(pk); - } + std::string + ExitEndpoint::Name() const + { + return name; + } - std::string - ExitEndpoint::Name() const - { - return m_Name; - } + void + ExitEndpoint::DelEndpointInfo(const PathID_t& path) + { + paths.erase(path); + } - void - ExitEndpoint::DelEndpointInfo(const PathID_t& path) + void + ExitEndpoint::RemoveExit(const exit::Endpoint* ep) + { + for (auto [itr, end] = active_exits.equal_range(ep->PubKey()); itr != end; ++itr) { - m_Paths.erase(path); + if (itr->second->GetCurrentPath() == ep->GetCurrentPath()) + { + active_exits.erase(itr); + // now ep is gone af + return; + } } + } - void - ExitEndpoint::RemoveExit(const exit::Endpoint* ep) + void + ExitEndpoint::Tick(llarp_time_t now) + { { - for (auto [itr, end] = m_ActiveExits.equal_range(ep->PubKey()); itr != end; ++itr) + auto itr = snode_sessions.begin(); + while (itr != snode_sessions.end()) { - if (itr->second->GetCurrentPath() == ep->GetCurrentPath()) + if (itr->second->IsExpired(now)) + itr = snode_sessions.erase(itr); + else { - m_ActiveExits.erase(itr); - // now ep is gone af - return; + itr->second->Tick(now); + ++itr; } } } - - void - ExitEndpoint::Tick(llarp_time_t now) { + // expire + auto itr = active_exits.begin(); + while (itr != active_exits.end()) { - auto itr = m_SNodeSessions.begin(); - while (itr != m_SNodeSessions.end()) - { - if (itr->second->IsExpired(now)) - itr = m_SNodeSessions.erase(itr); - else - { - itr->second->Tick(now); - ++itr; - } - } + if (itr->second->IsExpired(now)) + itr = active_exits.erase(itr); + else + ++itr; } + // pick chosen exits and tick + chosen_exits.clear(); + itr = active_exits.begin(); + while (itr != active_exits.end()) { - // expire - auto itr = m_ActiveExits.begin(); - while (itr != m_ActiveExits.end()) - { - if (itr->second->IsExpired(now)) - itr = m_ActiveExits.erase(itr); - else - ++itr; - } - // pick chosen exits and tick - m_ChosenExits.clear(); - itr = m_ActiveExits.begin(); - while (itr != m_ActiveExits.end()) + // do we have an exit set for this key? + if (chosen_exits.find(itr->first) != chosen_exits.end()) { - // do we have an exit set for this key? - if (m_ChosenExits.find(itr->first) != m_ChosenExits.end()) + // yes + if (chosen_exits[itr->first]->createdAt < itr->second->createdAt) { - // yes - 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)) - m_ChosenExits[itr->first] = itr->second.get(); - } + // if the iterators's exit is newer use it for the chosen exit for + // key + if (!itr->second->LooksDead(now)) + chosen_exits[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 - m_ChosenExits[itr->first] = itr->second.get(); - // tick which clears the tx rx counters - itr->second->Tick(now); - ++itr; } + else if (!itr->second->LooksDead(now)) // set chosen exit if not dead for key that + // doesn't have one yet + chosen_exits[itr->first] = itr->second.get(); + // tick which clears the tx rx counters + itr->second->Tick(now); + ++itr; } } - } // namespace handlers -} // namespace llarp + } +} // namespace llarp::handlers diff --git a/llarp/handlers/exit.hpp b/llarp/handlers/exit.hpp index 79fc2be47..7899141fa 100644 --- a/llarp/handlers/exit.hpp +++ b/llarp/handlers/exit.hpp @@ -7,7 +7,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; namespace handlers { struct ExitEndpoint : public dns::Resolver_Base, public EndpointBase @@ -31,7 +31,7 @@ namespace llarp const SockAddr& to, const SockAddr& from) override; - ExitEndpoint(std::string name, AbstractRouter* r); + ExitEndpoint(std::string name, Router* r); ~ExitEndpoint() override; std::optional @@ -112,7 +112,7 @@ namespace llarp void OnInetPacket(net::IPPacket buf); - AbstractRouter* + Router* GetRouter(); llarp_time_t @@ -122,7 +122,7 @@ namespace llarp void CalculateTrafficStats(Stats& stats) { - for (auto& [pubkey, endpoint] : m_ActiveExits) + for (auto& [pubkey, endpoint] : active_exits) { stats[pubkey].first += endpoint->TxRate(); stats[pubkey].second += endpoint->RxRate(); @@ -172,7 +172,7 @@ namespace llarp GetIPForIdent(const PubKey pk); /// async obtain snode session and call callback when it's ready to send void - ObtainSNodeSession(const RouterID& router, exit::SessionReadyFunc obtainCb); + ObtainSNodeSession(const RouterID& rid, exit::SessionReadyFunc obtain_cb); private: huint128_t @@ -192,54 +192,52 @@ namespace llarp void KickIdentOffExit(const PubKey& pk); - AbstractRouter* m_Router; - std::shared_ptr m_Resolver; - bool m_ShouldInitTun; - std::string m_Name; - bool m_PermitExit; - std::unordered_map m_Paths; + Router* router; + std::shared_ptr resolver; + bool should_init_tun; + std::string name; + bool permit_exit; + std::unordered_map paths; - std::unordered_map m_ChosenExits; + std::unordered_map chosen_exits; - std::unordered_multimap> m_ActiveExits; + std::unordered_multimap> active_exits; - using KeyMap_t = std::unordered_map; - - KeyMap_t m_KeyToIP; + std::unordered_map key_to_IP; using SNodes_t = std::set; /// set of pubkeys we treat as snodes - SNodes_t m_SNodeKeys; + SNodes_t snode_keys; using SNodeSessions_t = std::unordered_map>; /// snode sessions we are talking to directly - SNodeSessions_t m_SNodeSessions; + SNodeSessions_t snode_sessions; - std::unordered_map m_IPToKey; + std::unordered_map ip_to_key; - huint128_t m_IfAddr; - huint128_t m_HigestAddr; + huint128_t if_addr; + huint128_t highest_addr; - huint128_t m_NextAddr; - IPRange m_OurRange; - std::string m_ifname; + huint128_t next_addr; + IPRange ip_range; + std::string if_name; - std::unordered_map m_IPActivity; + std::unordered_map ip_activity; - std::shared_ptr m_NetIf; + std::shared_ptr if_net; - SockAddr m_LocalResolverAddr; - std::vector m_UpstreamResolvers; + SockAddr resolver_addr; + std::vector upstream_resolvers; - std::shared_ptr m_QUIC; + std::shared_ptr tunnel_manager; using PacketQueue_t = std:: priority_queue, net::IPPacket::CompareOrder>; /// internet to llarp packet queue - PacketQueue_t m_InetToNetwork; - bool m_UseV6; - DnsConfig m_DNSConf; + PacketQueue_t inet_to_network; + bool use_ipv6; + DnsConfig dns_conf; }; } // namespace handlers } // namespace llarp diff --git a/llarp/handlers/null.hpp b/llarp/handlers/null.hpp index bfa0525e8..4d5202fe0 100644 --- a/llarp/handlers/null.hpp +++ b/llarp/handlers/null.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include @@ -12,7 +12,7 @@ namespace llarp::handlers struct NullEndpoint final : public llarp::service::Endpoint, public std::enable_shared_from_this { - NullEndpoint(AbstractRouter* r, llarp::service::Context* parent) + NullEndpoint(Router* r, llarp::service::Context* parent) : llarp::service::Endpoint{r, parent} , m_PacketRouter{new vpn::EgresPacketRouter{[](auto from, auto pkt) { var::visit( diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index e04e44ea7..a9ea3010b 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include #include @@ -49,7 +49,7 @@ namespace llarp auto job = std::make_shared(source, query, to, from); if (HandleHookedDNSMessage(query, [job](auto msg) { job->SendReply(msg.ToBuffer()); })) - Router()->TriggerPump(); + router()->TriggerPump(); else job->Cancel(); return true; @@ -125,7 +125,7 @@ namespace llarp virtual ~TunDNS() = default; explicit TunDNS(TunEndpoint* ep, const llarp::DnsConfig& conf) - : dns::Server{ep->Router()->loop(), conf, 0} + : dns::Server{ep->router()->loop(), conf, 0} , m_QueryBind{conf.m_QueryBind} , m_OurIP{ToNet(ep->GetIfAddr())} , m_Endpoint{ep} @@ -145,8 +145,7 @@ namespace llarp } }; - TunEndpoint::TunEndpoint(AbstractRouter* r, service::Context* parent) - : service::Endpoint{r, parent} + TunEndpoint::TunEndpoint(Router* r, service::Context* parent) : service::Endpoint{r, parent} { m_PacketRouter = std::make_shared( [this](net::IPPacket pkt) { HandleGotUserPacket(std::move(pkt)); }); @@ -180,7 +179,7 @@ namespace llarp if (m_DnsConfig.m_raw_dns) { - if (auto vpn = Router()->GetVPNPlatform()) + if (auto vpn = router()->vpn_platform()) { // get the first local address we know of std::optional localaddr; @@ -196,7 +195,7 @@ namespace llarp if (platform::is_windows) { auto dns_io = vpn->create_packet_io(0, localaddr); - Router()->loop()->add_ticker([r = Router(), dns_io, handler = m_PacketRouter]() { + router()->loop()->add_ticker([r = router(), dns_io, handler = m_PacketRouter]() { net::IPPacket pkt = dns_io->ReadNextPacket(); while (not pkt.empty()) { @@ -306,7 +305,7 @@ namespace llarp method, conf.m_AuthWhitelist, conf.m_AuthStaticTokens, - Router()->lmq(), + router()->lmq(), shared_from_this()); auth->Start(); m_AuthPolicy = std::move(auth); @@ -334,7 +333,7 @@ namespace llarp m_IfName = conf.m_ifname; if (m_IfName.empty()) { - const auto maybe = m_router->Net().FindFreeTun(); + const auto maybe = m_router->net().FindFreeTun(); if (not maybe.has_value()) throw std::runtime_error("cannot find free interface name"); m_IfName = *maybe; @@ -343,7 +342,7 @@ namespace llarp m_OurRange = conf.m_ifaddr; if (!m_OurRange.addr.h) { - const auto maybe = m_router->Net().FindFreeRange(); + const auto maybe = m_router->net().FindFreeRange(); if (not maybe.has_value()) { throw std::runtime_error("cannot find free address range"); @@ -716,7 +715,7 @@ namespace llarp if (is_random_snode(msg)) { RouterID random; - if (Router()->GetRandomGoodRouter(random)) + if (router()->GetRandomGoodRouter(random)) { msg.AddCNAMEReply(random.ToString(), 1); } @@ -766,7 +765,7 @@ namespace llarp 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(msg), isV6); @@ -1024,7 +1023,7 @@ namespace llarp try { - m_NetIf = Router()->GetVPNPlatform()->CreateInterface(std::move(info), Router()); + m_NetIf = router()->vpn_platform()->CreateInterface(std::move(info), router()); } catch (std::exception& ex) { @@ -1040,7 +1039,7 @@ namespace llarp pkt_router->HandleIPPacket(std::move(pkt)); }; - if (not Router()->loop()->add_network_interface(m_NetIf, std::move(handle_packet))) + if (not router()->loop()->add_network_interface(m_NetIf, std::move(handle_packet))) { LogError(Name(), " failed to add network interface"); return false; @@ -1051,7 +1050,7 @@ namespace llarp if constexpr (not llarp::platform::is_apple) { - if (auto maybe = m_router->Net().GetInterfaceIPv6Address(m_IfName)) + if (auto maybe = m_router->net().GetInterfaceIPv6Address(m_IfName)) { m_OurIPv6 = *maybe; LogInfo(Name(), " has ipv6 address ", m_OurIPv6); @@ -1134,7 +1133,7 @@ namespace llarp if (auto itr = m_ExitIPToExitAddress.find(ip); itr != m_ExitIPToExitAddress.end()) return itr->second; - const auto& net = m_router->Net(); + const auto& net = m_router->net(); const bool is_bogon = net.IsBogonIP(ip); // build up our candidates to choose @@ -1209,7 +1208,7 @@ namespace llarp std::function extra_cb; if (not HasFlowToService(addr)) { - extra_cb = [poker = Router()->routePoker()]() { poker->Up(); }; + extra_cb = [poker = router()->routePoker()]() { poker->Up(); }; } pkt.ZeroSourceAddress(); MarkAddressOutbound(addr); @@ -1221,7 +1220,7 @@ namespace llarp if (extra_cb) extra_cb(); ctx->SendPacketToRemote(pkt.ConstBuffer(), service::ProtocolType::Exit); - Router()->TriggerPump(); + router()->TriggerPump(); return; } LogWarn("cannot ensure path to exit ", addr, " so we drop some packets"); @@ -1260,7 +1259,7 @@ namespace llarp if (SendToOrQueue(*maybe, pkt.ConstBuffer(), type)) { MarkIPActive(dst); - Router()->TriggerPump(); + router()->TriggerPump(); return; } } @@ -1280,7 +1279,7 @@ namespace llarp if (SendToOrQueue(*maybe, pkt.ConstBuffer(), type)) { MarkIPActive(dst); - Router()->TriggerPump(); + router()->TriggerPump(); } else { @@ -1436,7 +1435,7 @@ namespace llarp } m_NetworkToUserPktQueue.push(std::move(write)); // wake up so we ensure that all packets are written to user - Router()->TriggerPump(); + router()->TriggerPump(); return true; } diff --git a/llarp/handlers/tun.hpp b/llarp/handlers/tun.hpp index be7db4641..f9b41b74c 100644 --- a/llarp/handlers/tun.hpp +++ b/llarp/handlers/tun.hpp @@ -24,7 +24,7 @@ namespace llarp public dns::Resolver_Base, public std::enable_shared_from_this { - TunEndpoint(AbstractRouter* r, llarp::service::Context* parent); + TunEndpoint(Router* r, llarp::service::Context* parent); ~TunEndpoint() override; vpn::NetworkInterface* diff --git a/llarp/iwp/iwp.cpp b/llarp/iwp/iwp.cpp deleted file mode 100644 index 2ed7e2110..000000000 --- a/llarp/iwp/iwp.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "iwp.hpp" -#include "linklayer.hpp" -#include -#include - -namespace llarp -{ - namespace iwp - { - LinkLayer_ptr - NewInboundLink( - std::shared_ptr keyManager, - std::shared_ptr loop, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t work) - { - return std::make_shared( - keyManager, - loop, - getrc, - h, - sign, - before, - est, - reneg, - timeout, - closed, - pumpDone, - work, - true); - } - - LinkLayer_ptr - NewOutboundLink( - std::shared_ptr keyManager, - std::shared_ptr loop, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t work) - { - return std::make_shared( - keyManager, - loop, - getrc, - h, - sign, - before, - est, - reneg, - timeout, - closed, - pumpDone, - work, - false); - } - } // namespace iwp -} // namespace llarp diff --git a/llarp/iwp/iwp.hpp b/llarp/iwp/iwp.hpp deleted file mode 100644 index 54a353d37..000000000 --- a/llarp/iwp/iwp.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once - -#include -#include "linklayer.hpp" -#include -#include - -namespace llarp::iwp -{ - LinkLayer_ptr - NewInboundLink( - std::shared_ptr keyManager, - std::shared_ptr loop, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t work); - - LinkLayer_ptr - NewOutboundLink( - std::shared_ptr keyManager, - std::shared_ptr loop, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t work); - -} // namespace llarp::iwp diff --git a/llarp/iwp/linklayer.cpp b/llarp/iwp/linklayer.cpp deleted file mode 100644 index a0637ccc0..000000000 --- a/llarp/iwp/linklayer.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include "linklayer.hpp" -#include "session.hpp" -#include -#include -#include - -namespace llarp::iwp -{ - LinkLayer::LinkLayer( - std::shared_ptr keyManager, - std::shared_ptr ev, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t worker, - bool allowInbound) - : ILinkLayer( - keyManager, getrc, h, sign, before, est, reneg, timeout, closed, pumpDone, worker) - , m_Wakeup{ev->make_waker([this]() { HandleWakeupPlaintext(); })} - , m_Inbound{allowInbound} - {} - - std::string_view - LinkLayer::Name() const - { - return "iwp"; - } - - std::string - LinkLayer::PrintableName() const - { - if (m_Inbound) - return "inbound iwp link"; - else - return "outbound iwp link"; - } - - uint16_t - LinkLayer::Rank() const - { - return 2; - } - - void - LinkLayer::RecvFrom(const SockAddr& from, AbstractLinkSession::Packet_t pkt) - { - std::shared_ptr session; - auto itr = m_AuthedAddrs.find(from); - bool isNewSession = false; - if (itr == m_AuthedAddrs.end()) - { - Lock_t lock{m_PendingMutex}; - auto it = m_Pending.find(from); - if (it == m_Pending.end()) - { - if (not m_Inbound) - return; - isNewSession = true; - it = m_Pending.emplace(from, std::make_shared(this, from)).first; - } - session = it->second; - } - else - { - if (auto s_itr = m_AuthedLinks.find(itr->second); s_itr != m_AuthedLinks.end()) - session = s_itr->second; - } - if (session) - { - bool success = session->Recv_LL(std::move(pkt)); - if (not success and isNewSession) - { - LogDebug("Brand new session failed; removing from pending sessions list"); - m_Pending.erase(from); - } - WakeupPlaintext(); - } - } - - std::shared_ptr - LinkLayer::NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) - { - if (m_Inbound) - throw std::logic_error{"inbound link cannot make outbound sessions"}; - return std::make_shared(this, rc, ai); - } - - void - LinkLayer::WakeupPlaintext() - { - m_Wakeup->Trigger(); - } - - void - LinkLayer::HandleWakeupPlaintext() - { - // Copy bare pointers out first because HandlePlaintext can end up removing themselves from the - // structures. - m_WakingUp.clear(); // Reused to minimize allocations. - for (const auto& [router_id, session] : m_AuthedLinks) - m_WakingUp.push_back(session.get()); - for (const auto& [addr, session] : m_Pending) - m_WakingUp.push_back(session.get()); - for (auto* session : m_WakingUp) - session->HandlePlaintext(); - PumpDone(); - } - -} // namespace llarp::iwp diff --git a/llarp/iwp/linklayer.hpp b/llarp/iwp/linklayer.hpp deleted file mode 100644 index 8399f26c2..000000000 --- a/llarp/iwp/linklayer.hpp +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include - -#include - -namespace llarp::iwp -{ - struct Session; - - struct LinkLayer final : public ILinkLayer - { - LinkLayer( - std::shared_ptr keyManager, - std::shared_ptr ev, - GetRCFunc getrc, - LinkMessageHandler h, - SignBufferFunc sign, - BeforeConnectFunc_t before, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t dowork, - bool permitInbound); - - std::shared_ptr - NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) override; - - std::string_view - Name() const override; - - uint16_t - Rank() const override; - - void - RecvFrom(const SockAddr& from, AbstractLinkSession::Packet_t pkt) override; - - void - WakeupPlaintext(); - - std::string - PrintableName() const; - - private: - void - HandleWakeupPlaintext(); - - const std::shared_ptr m_Wakeup; - std::vector m_WakingUp; - const bool m_Inbound; - }; - - using LinkLayer_ptr = std::shared_ptr; -} // namespace llarp::iwp diff --git a/llarp/iwp/message_buffer.cpp b/llarp/iwp/message_buffer.cpp deleted file mode 100644 index e384b2cf8..000000000 --- a/llarp/iwp/message_buffer.cpp +++ /dev/null @@ -1,194 +0,0 @@ -#include "message_buffer.hpp" -#include "session.hpp" -#include - -namespace llarp -{ - namespace iwp - { - OutboundMessage::OutboundMessage( - uint64_t msgid, - AbstractLinkSession::Message_t msg, - llarp_time_t now, - AbstractLinkSession::CompletionHandler handler, - uint16_t priority) - : m_Data{std::move(msg)} - , m_MsgID{msgid} - , m_Completed{handler} - , m_LastFlush{now} - , m_StartedAt{now} - , m_ResendPriority{priority} - { - const llarp_buffer_t buf(m_Data); - CryptoManager::instance()->shorthash(m_Digest, buf); - m_Acks.set(0); - } - - AbstractLinkSession::Packet_t - OutboundMessage::XMIT() const - { - size_t extra = std::min(m_Data.size(), FragmentSize); - auto xmit = CreatePacket(Command::eXMIT, 10 + 32 + extra, 0, 0); - oxenc::write_host_as_big( - static_cast(m_Data.size()), xmit.data() + CommandOverhead + PacketOverhead); - oxenc::write_host_as_big(m_MsgID, xmit.data() + 2 + CommandOverhead + PacketOverhead); - 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) - { - m_Completed(AbstractLinkSession::DeliveryStatus::eDeliverySuccess); - } - m_Completed = nullptr; - } - - bool - OutboundMessage::ShouldFlush(llarp_time_t now) const - { - return now - m_LastFlush >= TXFlushInterval; - } - - void - OutboundMessage::Ack(byte_t bitmask) - { - m_Acks = std::bitset<8>(bitmask); - } - - void - OutboundMessage::FlushUnAcked( - 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) - { - if (not m_Acks[idx / FragmentSize]) - { - const size_t fragsz = idx + FragmentSize < datasz ? FragmentSize : datasz - idx; - auto frag = CreatePacket(Command::eDATA, fragsz + Overhead, 0, 0); - oxenc::write_host_as_big(idx, frag.data() + 2 + PacketOverhead); - oxenc::write_host_as_big(m_MsgID, frag.data() + 4 + PacketOverhead); - std::copy( - m_Data.begin() + idx, - m_Data.begin() + idx + fragsz, - frag.data() + PacketOverhead + Overhead + 2); - sendpkt(std::move(frag)); - } - idx += FragmentSize; - } - m_LastFlush = now; - } - - bool - OutboundMessage::IsTransmitted() const - { - const auto sz = m_Data.size(); - for (uint16_t idx = 0; idx < sz; idx += FragmentSize) - { - if (not m_Acks.test(idx / FragmentSize)) - return false; - } - return true; - } - - bool - OutboundMessage::IsTimedOut(const llarp_time_t now) const - { - // TODO: make configurable by outbound message deliverer - return now > m_StartedAt && now - m_StartedAt > DeliveryTimeout; - } - - void - OutboundMessage::InformTimeout() - { - if (m_Completed) - { - m_Completed(AbstractLinkSession::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} - {} - - void - InboundMessage::HandleData(uint16_t idx, const llarp_buffer_t& buf, llarp_time_t now) - { - if (idx + buf.sz > m_Data.size()) - { - LogWarn("invalid fragment offset ", idx); - return; - } - byte_t* dst = m_Data.data() + idx; - std::copy_n(buf.base, buf.sz, dst); - m_Acks.set(idx / FragmentSize); - LogTrace("got fragment ", idx / FragmentSize); - m_LastActiveAt = now; - } - - AbstractLinkSession::Packet_t - InboundMessage::ACKS() const - { - auto acks = CreatePacket(Command::eACKS, 9); - oxenc::write_host_as_big(m_MsgID, acks.data() + CommandOverhead + PacketOverhead); - acks[PacketOverhead + 10] = AcksBitmask(); - return acks; - } - - byte_t - InboundMessage::AcksBitmask() const - { - return byte_t{(byte_t)m_Acks.to_ulong()}; - } - - bool - InboundMessage::IsCompleted() const - { - const auto sz = m_Data.size(); - for (size_t idx = 0; idx < sz; idx += FragmentSize) - { - if (not m_Acks.test(idx / FragmentSize)) - return false; - } - return true; - } - - bool - InboundMessage::ShouldSendACKS(llarp_time_t now) const - { - return now > m_LastACKSent + ACKResendInterval; - } - - bool - InboundMessage::IsTimedOut(const llarp_time_t now) const - { - return now > m_LastActiveAt && now - m_LastActiveAt > DeliveryTimeout; - } - - void - InboundMessage::SendACKS( - std::function sendpkt, llarp_time_t now) - { - sendpkt(ACKS()); - m_LastACKSent = now; - } - - bool - InboundMessage::Verify() const - { - ShortHash gotten; - const llarp_buffer_t buf(m_Data); - CryptoManager::instance()->shorthash(gotten, buf); - return gotten == m_Digset; - } - } // namespace iwp -} // namespace llarp diff --git a/llarp/iwp/message_buffer.hpp b/llarp/iwp/message_buffer.hpp deleted file mode 100644 index 207a3b2ee..000000000 --- a/llarp/iwp/message_buffer.hpp +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace llarp -{ - namespace iwp - { - enum Command - { - /// keep alive message - ePING = 0, - /// begin transission - eXMIT = 1, - /// fragment data - eDATA = 2, - /// acknolege fragments - eACKS = 3, - /// negative ack - eNACK = 4, - /// multiack - eMACK = 5, - /// close session - eCLOS = 0xff, - }; - - /// max size of data fragments - static constexpr size_t FragmentSize = 1024; - /// plaintext header overhead size - static constexpr size_t CommandOverhead = 2; - - struct OutboundMessage - { - OutboundMessage() = default; - OutboundMessage( - uint64_t msgid, - AbstractLinkSession::Message_t data, - llarp_time_t now, - AbstractLinkSession::CompletionHandler handler, - uint16_t priority); - - AbstractLinkSession::Message_t m_Data; - uint64_t m_MsgID = 0; - std::bitset m_Acks; - AbstractLinkSession::CompletionHandler m_Completed; - llarp_time_t m_LastFlush = 0s; - ShortHash m_Digest; - llarp_time_t m_StartedAt = 0s; - uint16_t m_ResendPriority; - - bool - operator<(const OutboundMessage& other) const - { - // yes, the first order is reversed as higher means more important - // second part is for queue order - int prioA = -m_ResendPriority, prioB = -other.m_ResendPriority; - return std::tie(prioA, m_MsgID) < std::tie(prioB, other.m_MsgID); - } - - AbstractLinkSession::Packet_t - XMIT() const; - - void - Ack(byte_t bitmask); - - void - FlushUnAcked(std::function sendpkt, llarp_time_t now); - - bool - ShouldFlush(llarp_time_t now) const; - - void - Completed(); - - bool - IsTransmitted() const; - - bool - IsTimedOut(llarp_time_t now) const; - - void - InformTimeout(); - }; - - struct InboundMessage - { - InboundMessage() = default; - InboundMessage(uint64_t msgid, uint16_t sz, ShortHash h, llarp_time_t now); - - AbstractLinkSession::Message_t m_Data; - ShortHash m_Digset; - uint64_t m_MsgID = 0; - llarp_time_t m_LastACKSent = 0s; - llarp_time_t m_LastActiveAt = 0s; - std::bitset m_Acks; - - void - HandleData(uint16_t idx, const llarp_buffer_t& buf, llarp_time_t now); - - bool - IsCompleted() const; - - bool - IsTimedOut(llarp_time_t now) const; - - bool - Verify() const; - - byte_t - AcksBitmask() const; - - bool - ShouldSendACKS(llarp_time_t now) const; - - void - SendACKS(std::function sendpkt, llarp_time_t now); - - AbstractLinkSession::Packet_t - ACKS() const; - }; - - } // namespace iwp -} // namespace llarp diff --git a/llarp/iwp/session.cpp b/llarp/iwp/session.cpp deleted file mode 100644 index 93f4f1a45..000000000 --- a/llarp/iwp/session.cpp +++ /dev/null @@ -1,1031 +0,0 @@ -#include "session.hpp" - -#include -#include -#include -#include - -#include - -namespace llarp -{ - namespace iwp - { - AbstractLinkSession::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; - AbstractLinkSession::Packet_t pkt(PacketOverhead + plainsize + pad + CommandOverhead); - // randomize pad - if (pad) - { - CryptoManager::instance()->randbytes( - pkt.data() + PacketOverhead + CommandOverhead + plainsize, pad); - } - // randomize nounce - CryptoManager::instance()->randbytes(pkt.data() + HMACSIZE, TUNNONCESIZE); - pkt[PacketOverhead] = llarp::constants::proto_version; - pkt[PacketOverhead + 1] = cmd; - return pkt; - } - - constexpr size_t PlaintextQueueSize = 512; - - Session::Session(LinkLayer* p, const RouterContact& rc, const AddressInfo& ai) - : m_State{State::Initial} - , m_Inbound{false} - , m_Parent(p) - , m_CreatedAt{p->Now()} - , m_RemoteAddr{ai} - , m_ChosenAI(ai) - , m_RemoteRC(rc) - , m_PlaintextRecv{PlaintextQueueSize} - { - token.Zero(); - m_PlaintextEmpty.test_and_set(); - GotLIM = util::memFn(&Session::GotOutboundLIM, this); - CryptoManager::instance()->shorthash(m_SessionKey, llarp_buffer_t(rc.pubkey)); - } - - Session::Session(LinkLayer* p, const SockAddr& from) - : m_State{State::Initial} - , m_Inbound{true} - , m_Parent(p) - , m_CreatedAt{p->Now()} - , m_RemoteAddr{from} - , m_PlaintextRecv{PlaintextQueueSize} - { - token.Randomize(); - m_PlaintextEmpty.test_and_set(); - GotLIM = util::memFn(&Session::GotInboundLIM, this); - const PubKey pk = m_Parent->GetOurRC().pubkey; - CryptoManager::instance()->shorthash(m_SessionKey, llarp_buffer_t(pk)); - } - - void - Session::Send_LL(const byte_t* buf, size_t sz) - { - LogTrace("send ", sz, " to ", m_RemoteAddr); - const llarp_buffer_t pkt(buf, sz); - m_Parent->SendTo_LL(m_RemoteAddr, pkt); - m_LastTX = time_now_ms(); - m_TXRate += sz; - } - - bool - Session::GotInboundLIM(const LinkIntroMessage* msg) - { - if (msg->rc.pubkey != m_ExpectedIdent) - { - LogError( - "ident key mismatch from ", m_RemoteAddr, " ", msg->rc.pubkey, " != ", m_ExpectedIdent); - return false; - } - 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, true); - } - - bool - Session::GotOutboundLIM(const LinkIntroMessage* msg) - { - if (msg->rc.pubkey != m_RemoteRC.pubkey) - { - LogError("ident key mismatch"); - return false; - } - - m_RemoteRC = msg->rc; - GotLIM = util::memFn(&Session::GotRenegLIM, this); - assert(shared_from_this().use_count() > 1); - SendOurLIM([self = shared_from_this()](AbstractLinkSession::DeliveryStatus st) { - if (st == AbstractLinkSession::DeliveryStatus::eDeliverySuccess) - { - self->m_State = State::Ready; - self->m_Parent->MapAddr(self->m_RemoteRC.pubkey, self.get()); - self->m_Parent->SessionEstablished(self.get(), false); - } - }); - return true; - } - - void - Session::SendOurLIM(AbstractLinkSession::CompletionHandler h) - { - LinkIntroMessage msg; - msg.rc = m_Parent->GetOurRC(); - msg.nonce.Randomize(); - msg.session_period = 60000; - if (not msg.sign(m_Parent->Sign)) - { - LogError("failed to sign our RC for ", m_RemoteAddr); - return; - } - - AbstractLinkSession::Message_t data(LinkIntroMessage::MAX_MSG_SIZE + PacketOverhead); - llarp_buffer_t buf(data); - if (auto str = msg.bt_encode(); not str.empty()) - { - buf.write(str.begin(), str.end()); - } - else - { - log::critical(link_cat, "Error: Failed to encode LIM for {}", m_RemoteAddr); - return; - } - - if (not SendMessageBuffer(std::move(data), h)) - { - LogError("failed to send LIM to ", m_RemoteAddr); - return; - } - LogTrace("sent LIM to ", m_RemoteAddr); - } - - void - Session::EncryptAndSend(AbstractLinkSession::Packet_t data) - { - m_EncryptNext.emplace_back(std::move(data)); - TriggerPump(); - if (!IsEstablished()) - { - EncryptWorker(std::move(m_EncryptNext)); - m_EncryptNext = CryptoQueue_t{}; - } - } - - void - Session::EncryptWorker(CryptoQueue_t msgs) - { - LogTrace("encrypt worker ", msgs.size(), " messages"); - for (auto& pkt : msgs) - { - llarp_buffer_t pktbuf{pkt}; - const TunnelNonce nonce_ptr{pkt.data() + HMACSIZE}; - pktbuf.base += PacketOverhead; - pktbuf.cur = pktbuf.base; - pktbuf.sz -= PacketOverhead; - CryptoManager::instance()->xchacha20(pktbuf, m_SessionKey, nonce_ptr); - pktbuf.base = pkt.data() + HMACSIZE; - pktbuf.sz = pkt.size() - HMACSIZE; - CryptoManager::instance()->hmac(pkt.data(), pktbuf, m_SessionKey); - Send_LL(pkt.data(), pkt.size()); - } - } - - void - Session::Close() - { - if (m_State == State::Closed) - return; - auto close_msg = CreatePacket(Command::eCLOS, 0, 16, 16); - m_Parent->UnmapAddr(m_RemoteAddr); - m_State = State::Closed; - if (m_SentClosed.test_and_set()) - return; - EncryptAndSend(std::move(close_msg)); - - LogInfo(m_Parent->PrintableName(), " closing connection to ", m_RemoteAddr); - } - - bool - Session::SendMessageBuffer( - AbstractLinkSession::Message_t buf, - AbstractLinkSession::CompletionHandler completed, - uint16_t priority) - { - if (m_TXMsgs.size() >= MaxSendQueueSize) - { - if (completed) - completed(AbstractLinkSession::DeliveryStatus::eDeliveryDropped); - return false; - } - 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, priority}) - .first->second; - TriggerPump(); - EncryptAndSend(msg.XMIT()); - if (bufsz > FragmentSize) - { - msg.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); - } - m_Stats.totalInFlightTX++; - LogDebug("send message ", msgid, " to ", m_RemoteAddr); - return true; - } - - void - Session::SendMACK() - { - // send multi acks - while (not m_SendMACKs.empty()) - { - 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(numAcks)}; - byte_t* ptr = mack.data() + 3 + PacketOverhead; - LogTrace("send ", numAcks, " macks to ", m_RemoteAddr); - const auto& itr = m_SendMACKs.top(); - while (numAcks > 0) - { - oxenc::write_host_as_big(itr, ptr); - m_SendMACKs.pop(); - numAcks--; - ptr += sizeof(uint64_t); - } - EncryptAndSend(std::move(mack)); - } - } - - void - Session::TriggerPump() - { - m_Parent->Router()->TriggerPump(); - } - - void - Session::Pump() - { - const auto now = m_Parent->Now(); - if (m_State == State::Ready || m_State == State::LinkIntro) - { - if (ShouldPing()) - SendKeepAlive(); - for (auto& [id, msg] : m_RXMsgs) - { - if (msg.ShouldSendACKS(now)) - { - msg.SendACKS(util::memFn(&Session::EncryptAndSend, this), now); - } - } - std::priority_queue< - OutboundMessage*, - std::vector, - ComparePtr> - to_resend; - for (auto& [id, msg] : m_TXMsgs) - { - if (msg.ShouldFlush(now)) - to_resend.push(&msg); - } - if (not to_resend.empty()) - { - for (auto& msg = to_resend.top(); not to_resend.empty(); to_resend.pop()) - msg->FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); - } - } - if (not m_EncryptNext.empty()) - { - m_Parent->QueueWork( - [self = shared_from_this(), data = m_EncryptNext] { self->EncryptWorker(data); }); - m_EncryptNext.clear(); - } - - if (not m_DecryptNext.empty()) - { - m_Parent->QueueWork( - [self = shared_from_this(), data = m_DecryptNext] { self->DecryptWorker(data); }); - m_DecryptNext.clear(); - } - } - - bool - Session::GotRenegLIM(const LinkIntroMessage* lim) - { - LogDebug("renegotiate session on ", m_RemoteAddr); - return m_Parent->SessionRenegotiate(lim->rc, m_RemoteRC); - } - - bool - Session::RenegotiateSession() - { - SendOurLIM(); - return true; - } - - bool - Session::ShouldPing() const - { - if (m_State == State::Ready) - { - const auto now = m_Parent->Now(); - return now - m_LastTX > PingInterval; - } - return false; - } - - SessionStats - Session::GetSessionStats() const - { - // TODO: thread safety - return m_Stats; - } - - util::StatusObject - Session::ExtractStatus() const - { - const auto now = m_Parent->Now(); - - return { - {"txRateCurrent", m_Stats.currentRateTX}, - {"rxRateCurrent", m_Stats.currentRateRX}, - {"rxPktsRcvd", m_Stats.totalPacketsRX}, - - // leave 'tx' and 'rx' as duplicates of 'xRateCurrent' for compat - {"tx", m_Stats.currentRateTX}, - {"rx", m_Stats.currentRateRX}, - - {"txPktsAcked", m_Stats.totalAckedTX}, - {"txPktsDropped", m_Stats.totalDroppedTX}, - {"txPktsInFlight", m_Stats.totalInFlightTX}, - - {"state", StateToString(m_State)}, - {"inbound", m_Inbound}, - {"replayFilter", m_ReplayFilter.size()}, - {"txMsgQueueSize", m_TXMsgs.size()}, - {"rxMsgQueueSize", m_RXMsgs.size()}, - {"remoteAddr", m_RemoteAddr.ToString()}, - {"remoteRC", m_RemoteRC.ExtractStatus()}, - {"created", to_json(m_CreatedAt)}, - {"uptime", to_json(now - m_CreatedAt)}}; - } - - bool - Session::TimedOut(llarp_time_t now) const - { - if (m_State == State::Ready) - { - return now > m_LastRX - && now - m_LastRX - > (m_Inbound and not m_RemoteRC.IsPublicRouter() ? DefaultLinkSessionLifetime - : SessionAliveTimeout); - } - return now - m_CreatedAt >= LinkLayerConnectTimeout; - } - - bool - Session::ShouldResetRates(llarp_time_t now) const - { - return now >= m_ResetRatesAt; - } - - void - Session::ResetRates() - { - m_Stats.currentRateTX = m_TXRate; - m_Stats.currentRateRX = m_RXRate; - m_RXRate = 0; - m_TXRate = 0; - } - - void - Session::Tick(llarp_time_t now) - { - if (ShouldResetRates(now)) - { - ResetRates(); - m_ResetRatesAt = now + 1s; - } - // remove pending outbound messsages that timed out - // inform waiters - { - auto itr = m_TXMsgs.begin(); - while (itr != m_TXMsgs.end()) - { - if (itr->second.IsTimedOut(now)) - { - m_Stats.totalDroppedTX++; - m_Stats.totalInFlightTX--; - LogTrace("Dropped unacked packet to ", m_RemoteAddr); - itr->second.InformTimeout(); - itr = m_TXMsgs.erase(itr); - } - else - ++itr; - } - } - { - // remove pending inbound messages that timed out - auto itr = m_RXMsgs.begin(); - while (itr != m_RXMsgs.end()) - { - if (itr->second.IsTimedOut(now)) - { - m_ReplayFilter.emplace(itr->first, now); - itr = m_RXMsgs.erase(itr); - } - else - ++itr; - } - } - { - // decay replay window - auto itr = m_ReplayFilter.begin(); - while (itr != m_ReplayFilter.end()) - { - if (itr->second + ReplayWindow <= now) - { - itr = m_ReplayFilter.erase(itr); - } - else - ++itr; - } - } - } - - using Introduction = - AlignedBuffer; - - void - Session::GenerateAndSendIntro() - { - TunnelNonce N; - N.Randomize(); - { - AbstractLinkSession::Packet_t req(Introduction::SIZE + PacketOverhead); - const auto pk = m_Parent->GetOurRC().pubkey; - const auto e_pk = m_Parent->RouterEncryptionSecret().toPublic(); - 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); - 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); - EncryptAndSend(std::move(req)); - } - m_State = State::Introduction; - 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); - return; - } - LogTrace("sent intro to ", m_RemoteAddr); - } - - void - Session::HandleCreateSessionRequest(Packet_t pkt) - { - if (not DecryptMessageInPlace(pkt)) - { - LogError( - m_Parent->PrintableName(), " failed to decrypt session request from ", m_RemoteAddr); - return; - } - if (pkt.size() < token.size() + PacketOverhead) - { - LogError( - m_Parent->PrintableName(), - " 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())) - { - LogError(m_Parent->PrintableName(), " token mismatch from ", m_RemoteAddr); - return; - } - m_LastRX = m_Parent->Now(); - m_State = State::LinkIntro; - SendOurLIM(); - } - - void - Session::HandleGotIntro(Packet_t pkt) - { - if (pkt.size() < (Introduction::SIZE + PacketOverhead)) - { - LogWarn(m_Parent->PrintableName(), " intro too small from ", m_RemoteAddr); - return; - } - byte_t* ptr = pkt.data() + PacketOverhead; - TunnelNonce N; - std::copy_n(ptr, PubKey::SIZE, m_ExpectedIdent.data()); - ptr += PubKey::SIZE; - std::copy_n(ptr, PubKey::SIZE, m_RemoteOnionKey.data()); - ptr += PubKey::SIZE; - std::copy_n(ptr, TunnelNonce::SIZE, N.data()); - 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)) - { - LogError(m_Parent->PrintableName(), " 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); - return; - } - Packet_t reply(token.size() + PacketOverhead); - // random nonce - CryptoManager::instance()->randbytes(reply.data() + HMACSIZE, TUNNONCESIZE); - // set token - std::copy_n(token.data(), token.size(), reply.data() + PacketOverhead); - m_LastRX = m_Parent->Now(); - EncryptAndSend(std::move(reply)); - LogDebug("sent intro ack to ", m_RemoteAddr); - m_State = State::Introduction; - } - - void - Session::HandleGotIntroAck(Packet_t pkt) - { - if (pkt.size() < (token.size() + PacketOverhead)) - { - LogError( - m_Parent->PrintableName(), - " bad intro ack size ", - pkt.size(), - " < ", - token.size() + PacketOverhead, - " from ", - m_RemoteAddr); - return; - } - Packet_t reply(token.size() + PacketOverhead); - if (not DecryptMessageInPlace(pkt)) - { - LogError(m_Parent->PrintableName(), " intro ack decrypt failed from ", m_RemoteAddr); - return; - } - m_LastRX = m_Parent->Now(); - 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); - EncryptAndSend(std::move(reply)); - LogDebug("sent session request to ", m_RemoteAddr); - m_State = State::LinkIntro; - } - - bool - Session::DecryptMessageInPlace(Packet_t& pkt) - { - if (pkt.size() <= PacketOverhead) - { - LogError("packet too small from ", m_RemoteAddr); - return false; - } - const llarp_buffer_t buf(pkt); - ShortHash H; - 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)) - { - LogError("failed to caclulate keyed hash for ", m_RemoteAddr); - return false; - } - const ShortHash expected{buf.base}; - if (H != expected) - { - LogDebug( - m_Parent->PrintableName(), - " keyed hash mismatch ", - H, - " != ", - expected, - " from ", - m_RemoteAddr, - " state=", - int(m_State), - " size=", - buf.sz); - return false; - } - const TunnelNonce N{curbuf.base}; - curbuf.base += 32; - curbuf.sz -= 32; - LogTrace("decrypt: ", curbuf.sz, " bytes from ", m_RemoteAddr); - return CryptoManager::instance()->xchacha20(curbuf, m_SessionKey, N); - } - - void - Session::Start() - { - if (m_Inbound) - return; - GenerateAndSendIntro(); - } - - void - Session::HandleSessionData(Packet_t pkt) - { - m_DecryptNext.emplace_back(std::move(pkt)); - TriggerPump(); - } - - void - Session::DecryptWorker(CryptoQueue_t msgs) - { - auto itr = msgs.begin(); - while (itr != msgs.end()) - { - auto& pkt = *itr; - if (not DecryptMessageInPlace(pkt)) - { - itr = msgs.erase(itr); - LogError("failed to decrypt session data from ", m_RemoteAddr); - continue; - } - if (pkt[PacketOverhead] != llarp::constants::proto_version) - { - LogError( - "protocol version mismatch ", - int(pkt[PacketOverhead]), - " != ", - llarp::constants::proto_version); - itr = msgs.erase(itr); - continue; - } - ++itr; - } - m_PlaintextRecv.tryPushBack(std::move(msgs)); - m_PlaintextEmpty.clear(); - m_Parent->WakeupPlaintext(); - } - - void - Session::HandlePlaintext() - { - if (m_PlaintextEmpty.test_and_set()) - return; - while (auto maybe_queue = m_PlaintextRecv.tryPopFront()) - { - for (auto& result : *maybe_queue) - { - LogTrace("Command ", int(result[PacketOverhead + 1]), " from ", m_RemoteAddr); - switch (result[PacketOverhead + 1]) - { - case Command::eXMIT: - HandleXMIT(std::move(result)); - break; - case Command::eDATA: - HandleDATA(std::move(result)); - break; - case Command::eACKS: - HandleACKS(std::move(result)); - break; - case Command::ePING: - HandlePING(std::move(result)); - break; - case Command::eNACK: - HandleNACK(std::move(result)); - break; - case Command::eCLOS: - HandleCLOS(std::move(result)); - break; - case Command::eMACK: - HandleMACK(std::move(result)); - break; - default: - LogError("invalid command ", int(result[PacketOverhead + 1]), " from ", m_RemoteAddr); - } - } - } - SendMACK(); - m_Parent->WakeupPlaintext(); - } - - void - Session::HandleMACK(Packet_t data) - { - 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))) - { - LogError("short mack from ", m_RemoteAddr); - return; - } - LogTrace("got ", int(numAcks), " mack from ", m_RemoteAddr); - byte_t* ptr = data.data() + CommandOverhead + PacketOverhead + 1; - while (numAcks > 0) - { - auto acked = oxenc::load_big_to_host(ptr); - LogTrace("mack containing txid=", acked, " from ", m_RemoteAddr); - auto itr = m_TXMsgs.find(acked); - if (itr != m_TXMsgs.end()) - { - m_Stats.totalAckedTX++; - m_Stats.totalInFlightTX--; - itr->second.Completed(); - m_TXMsgs.erase(itr); - } - else - { - LogTrace("ignored mack for txid=", acked, " from ", m_RemoteAddr); - } - ptr += sizeof(uint64_t); - numAcks--; - } - } - - void - Session::HandleNACK(Packet_t data) - { - if (data.size() < (CommandOverhead + sizeof(uint64_t) + PacketOverhead)) - { - LogError("short nack from ", m_RemoteAddr); - return; - } - auto txid = oxenc::load_big_to_host(data.data() + CommandOverhead + PacketOverhead); - LogTrace("got nack on ", txid, " from ", m_RemoteAddr); - auto itr = m_TXMsgs.find(txid); - if (itr != m_TXMsgs.end()) - { - EncryptAndSend(itr->second.XMIT()); - } - m_LastRX = m_Parent->Now(); - } - - void - Session::HandleXMIT(Packet_t data) - { - static constexpr size_t XMITOverhead = - (CommandOverhead + PacketOverhead + sizeof(uint16_t) + sizeof(uint64_t) - + ShortHash::SIZE); - if (data.size() < XMITOverhead) - { - LogError("short XMIT from ", m_RemoteAddr); - return; - } - auto* pos = data.data() + CommandOverhead + PacketOverhead; - auto sz = oxenc::load_big_to_host(pos); - pos += sizeof(sz); - auto rxid = oxenc::load_big_to_host(pos); - pos += sizeof(rxid); - auto p2 = pos + ShortHash::SIZE; - assert(p2 == data.data() + XMITOverhead); - LogTrace("rxid=", rxid, " sz=", sz, " h=", oxenc::to_hex(pos, p2), " from ", m_RemoteAddr); - m_LastRX = m_Parent->Now(); - { - // check for replay - auto itr = m_ReplayFilter.find(rxid); - if (itr != m_ReplayFilter.end()) - { - m_SendMACKs.emplace(rxid); - LogTrace("duplicate rxid=", rxid, " from ", m_RemoteAddr); - return; - } - } - { - const auto now = m_Parent->Now(); - auto itr = m_RXMsgs.find(rxid); - if (itr == m_RXMsgs.end()) - { - itr = m_RXMsgs.emplace(rxid, InboundMessage{rxid, sz, ShortHash{pos}, m_Parent->Now()}) - .first; - TriggerPump(); - - sz = std::min(sz, uint16_t{FragmentSize}); - 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()) - { - return; - } - - if (not itr->second.Verify()) - { - LogError("bad short xmit hash from ", m_RemoteAddr); - return; - } - } - HandleRecvMsgCompleted(itr->second); - } - } - else - LogTrace("got duplicate xmit on ", rxid, " from ", m_RemoteAddr); - } - } - - void - Session::HandleDATA(Packet_t data) - { - 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(); - auto sz = oxenc::load_big_to_host(data.data() + CommandOverhead + PacketOverhead); - auto rxid = oxenc::load_big_to_host( - 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()) - { - LogTrace("no rxid=", rxid, " for ", m_RemoteAddr); - auto nack = CreatePacket(Command::eNACK, 8); - oxenc::write_host_as_big(rxid, nack.data() + PacketOverhead + CommandOverhead); - EncryptAndSend(std::move(nack)); - } - else - { - LogTrace("replay hit for rxid=", rxid, " for ", m_RemoteAddr); - m_SendMACKs.emplace(rxid); - } - return; - } - - { - 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.Verify()) - { - HandleRecvMsgCompleted(itr->second); - } - else - { - LogError("hash mismatch for message ", itr->first); - } - } - } - - void - Session::HandleRecvMsgCompleted(const InboundMessage& msg) - { - const auto rxid = msg.m_MsgID; - if (m_ReplayFilter.emplace(rxid, m_Parent->Now()).second) - { - m_Parent->HandleMessage(this, msg.m_Data); - EncryptAndSend(msg.ACKS()); - LogDebug("recv'd message ", rxid, " from ", m_RemoteAddr); - } - m_RXMsgs.erase(rxid); - } - - void - Session::HandleACKS(Packet_t data) - { - if (data.size() < (11 + PacketOverhead)) - { - LogError("short ACKS from ", m_RemoteAddr); - return; - } - const auto now = m_Parent->Now(); - m_LastRX = now; - auto txid = oxenc::load_big_to_host(data.data() + 2 + PacketOverhead); - auto itr = m_TXMsgs.find(txid); - if (itr == m_TXMsgs.end()) - { - LogTrace("no txid=", txid, " for ", m_RemoteAddr); - return; - } - itr->second.Ack(data[10 + PacketOverhead]); - - if (itr->second.IsTransmitted()) - { - LogDebug("sent message ", itr->first, " to ", m_RemoteAddr); - itr->second.Completed(); - itr = m_TXMsgs.erase(itr); - } - else - { - itr->second.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); - } - } - - void - Session::HandleCLOS(Packet_t) - { - LogInfo("remote closed by ", m_RemoteAddr); - Close(); - } - - void - Session::HandlePING(Packet_t) - { - m_LastRX = m_Parent->Now(); - } - - bool - Session::SendKeepAlive() - { - if (m_State == State::Ready) - { - EncryptAndSend(CreatePacket(Command::ePING, 0)); - return true; - } - return false; - } - - bool - Session::IsEstablished() const - { - return m_State == State::Ready; - } - - bool - Session::Recv_LL(AbstractLinkSession::Packet_t data) - { - m_RXRate += data.size(); - - // TODO: differentiate between good and bad RX packets here - m_Stats.totalPacketsRX++; - switch (m_State) - { - case State::Initial: - if (m_Inbound) - { - // initial data - // enter introduction phase - if (DecryptMessageInPlace(data)) - { - HandleGotIntro(std::move(data)); - } - else - { - LogDebug("bad intro from ", m_RemoteAddr); - return false; - } - } - break; - case State::Introduction: - if (m_Inbound) - { - // we are replying to an intro ack - HandleCreateSessionRequest(std::move(data)); - } - else - { - // we got an intro ack - // send a session request - HandleGotIntroAck(std::move(data)); - } - break; - case State::LinkIntro: - default: - HandleSessionData(std::move(data)); - break; - } - return true; - } - - std::string - Session::StateToString(State state) - { - switch (state) - { - case State::Initial: - return "Initial"; - case State::Introduction: - return "Introduction"; - case State::LinkIntro: - return "LinkIntro"; - case State::Ready: - return "Ready"; - case State::Closed: - return "Close"; - default: - return "Invalid"; - } - } - } // namespace iwp -} // namespace llarp diff --git a/llarp/iwp/session.hpp b/llarp/iwp/session.hpp deleted file mode 100644 index 6d6e8faa2..000000000 --- a/llarp/iwp/session.hpp +++ /dev/null @@ -1,275 +0,0 @@ -#pragma once - -#include -#include "linklayer.hpp" -#include "message_buffer.hpp" -#include - -#include -#include -#include - -#include -#include - -namespace llarp::iwp -{ - /// packet crypto overhead size - static constexpr size_t PacketOverhead = HMACSIZE + TUNNONCESIZE; - /// creates a packet with plaintext size + wire overhead + random pad - AbstractLinkSession::Packet_t - 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 - static constexpr auto ReceivalTimeout = (DeliveryTimeout * 8) / 5; - /// How long to keep a replay window for - static constexpr auto ReplayWindow = (ReceivalTimeout * 3) / 2; - /// How often to acks RX messages - static constexpr auto ACKResendInterval = DeliveryTimeout / 2; - /// How often to retransmit TX fragments - static constexpr auto TXFlushInterval = (DeliveryTimeout / 5) * 4; - /// How often we send a keepalive - static constexpr std::chrono::milliseconds PingInterval = 5s; - /// How long we wait for a session to die with no tx from them - static constexpr auto SessionAliveTimeout = PingInterval * 5; - - struct Session : public AbstractLinkSession, public std::enable_shared_from_this - { - using Time_t = std::chrono::milliseconds; - - /// maximum number of messages we can ack in a multiack - static constexpr std::size_t MaxACKSInMACK = 1024 / sizeof(uint64_t); - - /// outbound session - Session(LinkLayer* parent, const RouterContact& rc, const AddressInfo& ai); - /// inbound session - Session(LinkLayer* parent, const SockAddr& from); - - // Signal the event loop that a pump is needed (idempotent) - void - TriggerPump(); - - // Does the actual pump - void - Pump() override; - - void - Tick(llarp_time_t now) override; - - bool - SendMessageBuffer( - AbstractLinkSession::Message_t msg, - CompletionHandler resultHandler, - uint16_t priority = 0) override; - - void - Send_LL(const byte_t* buf, size_t sz); - - void EncryptAndSend(AbstractLinkSession::Packet_t); - - void - Start() override; - - void - Close() override; - - bool Recv_LL(AbstractLinkSession::Packet_t) override; - - bool - SendKeepAlive() override; - - bool - IsEstablished() const override; - - bool - TimedOut(llarp_time_t now) const override; - - PubKey - GetPubKey() const override - { - return m_RemoteRC.pubkey; - } - - const SockAddr& - GetRemoteEndpoint() const override - { - return m_RemoteAddr; - } - - RouterContact - GetRemoteRC() const override - { - return m_RemoteRC; - } - - size_t - SendQueueBacklog() const override - { - return m_TXMsgs.size(); - } - - ILinkLayer* - GetLinkLayer() const override - { - return m_Parent; - } - - bool - RenegotiateSession() override; - - bool - ShouldPing() const override; - - SessionStats - GetSessionStats() const override; - - util::StatusObject - ExtractStatus() const override; - - bool - IsInbound() const override - { - return m_Inbound; - } - void - HandlePlaintext() override; - - private: - enum class State - { - /// we have no data recv'd - Initial, - /// we are in introduction phase - Introduction, - /// we sent our LIM - LinkIntro, - /// handshake done and LIM has been obtained - Ready, - /// we are closed now - Closed - }; - static std::string - StateToString(State state); - State m_State; - SessionStats m_Stats; - - /// are we inbound session ? - const bool m_Inbound; - /// parent link layer - LinkLayer* const m_Parent; - const llarp_time_t m_CreatedAt; - const SockAddr m_RemoteAddr; - - AddressInfo m_ChosenAI; - /// remote rc - RouterContact m_RemoteRC; - /// session key - SharedSecret m_SessionKey; - /// session token - AlignedBuffer<24> token; - - PubKey m_ExpectedIdent; - PubKey m_RemoteOnionKey; - - llarp_time_t m_LastTX = 0s; - llarp_time_t m_LastRX = 0s; - - // accumulate for periodic rate calculation - uint64_t m_TXRate = 0; - uint64_t m_RXRate = 0; - - llarp_time_t m_ResetRatesAt = 0s; - - uint64_t m_TXID = 0; - - bool - ShouldResetRates(llarp_time_t now) const; - - void - ResetRates(); - - std::map m_RXMsgs; - std::map m_TXMsgs; - - /// maps rxid to time recieved - std::unordered_map m_ReplayFilter; - /// rx messages to send in next round of multiacks - util::ascending_priority_queue m_SendMACKs; - - using CryptoQueue_t = std::vector; - - CryptoQueue_t m_EncryptNext; - CryptoQueue_t m_DecryptNext; - - std::atomic_flag m_PlaintextEmpty; - llarp::thread::Queue m_PlaintextRecv; - std::atomic_flag m_SentClosed; - - void - EncryptWorker(CryptoQueue_t msgs); - - void - DecryptWorker(CryptoQueue_t msgs); - - void - HandleGotIntro(Packet_t pkt); - - void - HandleGotIntroAck(Packet_t pkt); - - void - HandleCreateSessionRequest(Packet_t pkt); - - void - HandleAckSession(Packet_t pkt); - - void - HandleSessionData(Packet_t pkt); - - bool - DecryptMessageInPlace(Packet_t& pkt); - - void - SendMACK(); - - void - HandleRecvMsgCompleted(const InboundMessage& msg); - - void - GenerateAndSendIntro(); - - bool - GotInboundLIM(const LinkIntroMessage* msg); - - bool - GotOutboundLIM(const LinkIntroMessage* msg); - - bool - GotRenegLIM(const LinkIntroMessage* msg); - - void - SendOurLIM(AbstractLinkSession::CompletionHandler h = nullptr); - - void - HandleXMIT(Packet_t msg); - - void - HandleDATA(Packet_t msg); - - void - HandleACKS(Packet_t msg); - - void - HandleNACK(Packet_t msg); - - void - HandlePING(Packet_t msg); - - void - HandleCLOS(Packet_t msg); - - void - HandleMACK(Packet_t msg); - }; -} // namespace llarp::iwp diff --git a/llarp/link/connection.cpp b/llarp/link/connection.cpp index 025eae8e6..8fcb21cff 100644 --- a/llarp/link/connection.cpp +++ b/llarp/link/connection.cpp @@ -3,8 +3,10 @@ namespace llarp::link { Connection::Connection( - std::shared_ptr& c, std::shared_ptr& s) - : conn{c}, control_stream{s} + std::shared_ptr& c, + std::shared_ptr& s, + RouterContact& rc) + : conn{c}, control_stream{s}, remote_rc{std::move(rc)} {} } // namespace llarp::link diff --git a/llarp/link/connection.hpp b/llarp/link/connection.hpp index b0c7e0815..916803674 100644 --- a/llarp/link/connection.hpp +++ b/llarp/link/connection.hpp @@ -9,16 +9,17 @@ namespace llarp::link { struct Connection { - Connection( - std::shared_ptr& c, - std::shared_ptr& s); - std::shared_ptr conn; std::shared_ptr control_stream; - RouterContact remote_rc; - bool inbound; // one side of a connection will be responsible for some things, e.g. heartbeat - bool remote_is_relay; + // one side of a connection will be responsible for some things, e.g. heartbeat + bool inbound{false}; + bool remote_is_relay{true}; + + Connection( + std::shared_ptr& c, + std::shared_ptr& s, + RouterContact& rc); }; } // namespace llarp::link diff --git a/llarp/link/endpoint.cpp b/llarp/link/endpoint.cpp deleted file mode 100644 index 95376029c..000000000 --- a/llarp/link/endpoint.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "endpoint.hpp" -#include "link_manager.hpp" - -namespace llarp::link -{ - std::shared_ptr - Endpoint::get_conn(const RouterContact& rc) const - { - for (const auto& [rid, conn] : conns) - { - if (conn->remote_rc == rc) - return conn; - } - - return nullptr; - } - - bool - Endpoint::have_conn(const RouterID& remote, bool client_only) const - { - if (auto itr = conns.find(remote); itr != conns.end()) - { - if (not(itr->second->remote_is_relay and client_only)) - return true; - } - - return false; - } - - // TOFIX: use the new close methods after bumping libquic - bool - Endpoint::deregister_peer(RouterID remote) - { - if (auto itr = conns.find(remote); itr != conns.end()) - { - endpoint->close_connection(*dynamic_cast(itr->second->conn.get())); - conns.erase(itr); - return true; - } - - return false; - } - - bool - Endpoint::establish_connection(const oxen::quic::opt::local_addr& remote) - { - try - { - oxen::quic::dgram_data_callback dgram_cb = - [this](oxen::quic::dgram_interface& dgi, bstring dgram) { - link_manager.recv_data_message(dgi, dgram); - }; - - auto conn_interface = endpoint->connect(remote, link_manager.tls_creds, dgram_cb); - auto control_stream = conn_interface->get_new_stream(); - - // TOFIX: get a real RouterID after refactoring it - RouterID rid; - auto [itr, b] = conns.emplace(rid); - itr->second = std::make_shared(conn_interface, control_stream); - connid_map.emplace(conn_interface->scid(), rid); - - return true; - } - catch (...) - { - log::error(quic_cat, "Error: failed to establish connection to {}", remote); - return false; - } - } - -} // namespace llarp::link diff --git a/llarp/link/endpoint.hpp b/llarp/link/endpoint.hpp index e4fca1449..b5090c56a 100644 --- a/llarp/link/endpoint.hpp +++ b/llarp/link/endpoint.hpp @@ -1,44 +1,12 @@ #pragma once #include "connection.hpp" +#include "link_manager.hpp" -#include +#include #include #include namespace llarp::link -{ - struct Endpoint - { - Endpoint(std::shared_ptr ep, LinkManager& lm) - : endpoint{std::move(ep)}, link_manager{lm} - {} - - std::shared_ptr endpoint; - LinkManager& link_manager; - - // for outgoing packets, we route via RouterID; map RouterID->Connection - // for incoming packets, we get a ConnectionID; map ConnectionID->RouterID - std::unordered_map> conns; - std::unordered_map connid_map; - - std::shared_ptr - get_conn(const RouterContact&) const; - - bool - have_conn(const RouterID& remote, bool client_only) const; - - bool - deregister_peer(RouterID remote); - - bool - establish_connection(const oxen::quic::opt::local_addr& remote); - }; - -} // namespace llarp::link - -/* -- Refactor RouterID to use gnutls info and maybe ConnectionID - -*/ +{} // namespace llarp::link diff --git a/llarp/link/factory.cpp b/llarp/link/factory.cpp deleted file mode 100644 index f94e01053..000000000 --- a/llarp/link/factory.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "factory.hpp" -#include - -namespace llarp -{ - LinkFactory::LinkType - LinkFactory::TypeFromName(std::string_view str) - { - if (str == "iwp") - return LinkType::eLinkIWP; - if (str == "mempipe") - return LinkType::eLinkMempipe; - return LinkType::eLinkUnknown; - } - - std::string - LinkFactory::NameFromType(LinkFactory::LinkType tp) - { - switch (tp) - { - case LinkType::eLinkIWP: - return "iwp"; - case LinkType::eLinkMempipe: - return "mempipe"; - default: - return "unspec"; - } - } - - LinkFactory::Factory - LinkFactory::Obtain(LinkFactory::LinkType tp, bool permitInbound) - { - switch (tp) - { - case LinkType::eLinkIWP: - if (permitInbound) - return llarp::iwp::NewInboundLink; - return llarp::iwp::NewOutboundLink; - default: - return nullptr; - } - } -} // namespace llarp diff --git a/llarp/link/factory.hpp b/llarp/link/factory.hpp deleted file mode 100644 index e87f31464..000000000 --- a/llarp/link/factory.hpp +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once -#include -#include -#include -#include - -#include "server.hpp" - -namespace llarp -{ - /// LinkFactory is responsible for returning std::functions that create the - /// link layer types - struct LinkFactory - { - enum class LinkType - { - eLinkUTP, - eLinkIWP, - eLinkMempipe, - eLinkUnknown - }; - - using Factory = std::function, - GetRCFunc, - LinkMessageHandler, - SignBufferFunc, - SessionEstablishedHandler, - SessionRenegotiateHandler, - TimeoutHandler, - SessionClosedHandler, - PumpDoneHandler)>; - - /// get link type by name string - /// if invalid returns eLinkUnspec - static LinkType - TypeFromName(std::string_view name); - - /// turns a link type into a string representation - static std::string - NameFromType(LinkType t); - - /// obtain a link factory of a certain type - static Factory - Obtain(LinkType t, bool permitInbound); - }; - -} // namespace llarp diff --git a/llarp/link/link_manager.cpp b/llarp/link/link_manager.cpp index e226b96ff..3bff19ebc 100644 --- a/llarp/link/link_manager.cpp +++ b/llarp/link/link_manager.cpp @@ -1,54 +1,103 @@ #include "link_manager.hpp" +#include "connection.hpp" #include #include #include -#include #include #include namespace llarp { + namespace link + { + std::shared_ptr + Endpoint::get_conn(const RouterContact& rc) const + { + for (const auto& [rid, conn] : conns) + { + if (conn->remote_rc == rc) + return conn; + } + + return nullptr; + } + + bool + Endpoint::have_conn(const RouterID& remote, bool client_only) const + { + if (auto itr = conns.find(remote); itr != conns.end()) + { + if (not(itr->second->remote_is_relay and client_only)) + return true; + } + + return false; + } + + bool + Endpoint::deregister_peer(RouterID remote) + { + if (auto itr = conns.find(remote); itr != conns.end()) + { + itr->second->conn->close_connection(); + conns.erase(itr); + return true; + } + + return false; + } + + size_t + Endpoint::num_connected(bool clients_only) const + { + size_t count = 0; + + for (const auto& c : conns) + { + if (not(c.second->remote_is_relay and clients_only)) + count += 1; + } + + return count; + } + + bool + Endpoint::get_random_connection(RouterContact& router) const + { + if (const auto size = conns.size(); size) + { + auto itr = conns.begin(); + std::advance(itr, randint() % size); + router = itr->second->remote_rc; + return true; + } + + log::warning(quic_cat, "Error: failed to fetch random connection"); + return false; + } + } // namespace link LinkManager::LinkManager(Router& r) : router{r} , quic{std::make_unique()} , tls_creds{oxen::quic::GNUTLSCreds::make_from_ed_keys( - {reinterpret_cast(router.encryption().data()), router.encryption().size()}, - {reinterpret_cast(router.encryption().toPublic().data()), size_t{32}})} + {reinterpret_cast(router.identity().data()), size_t{32}}, + {reinterpret_cast(router.identity().toPublic().data()), size_t{32}})} , ep{quic->endpoint(router.local), *this} {} - std::shared_ptr - LinkManager::get_compatible_link(const RouterContact& rc) - { - if (stopping) - return nullptr; - - if (auto c = ep.get_conn(rc); c) - return c; - - return nullptr; - } - // TODO: replace with control/data message sending with libquic bool - LinkManager::send_to( - const RouterID& remote, - const llarp_buffer_t&, - AbstractLinkSession::CompletionHandler completed, - uint16_t) + LinkManager::send_to(const RouterID& remote, const llarp_buffer_t&, uint16_t) { if (stopping) return false; if (not have_connection_to(remote)) { - if (completed) - { - completed(AbstractLinkSession::DeliveryStatus::eDeliveryDropped); - } + // TODO: some error callback to report message send failure return false; } @@ -81,15 +130,6 @@ namespace llarp log::warning(logcat, "Peer {} not found for de-registeration!"); } - void - LinkManager::connect_to(const oxen::quic::opt::local_addr& remote) - { - if (auto rv = ep.establish_connection(remote); rv) - log::info(quic_cat, "Connection to {} successfully established!", remote); - else - log::info(quic_cat, "Connection to {} unsuccessfully established", remote); - } - void LinkManager::stop() { @@ -98,7 +138,7 @@ namespace llarp return; } - util::Lock l(_mutex); + util::Lock l(m); LogInfo("stopping links"); stopping = true; @@ -112,7 +152,7 @@ namespace llarp if (stopping) return; - util::Lock l(_mutex); + util::Lock l(m); persisting_conns[remote] = std::max(until, persisting_conns[remote]); if (have_client_connection_to(remote)) @@ -125,17 +165,7 @@ namespace llarp size_t LinkManager::get_num_connected(bool clients_only) const { - size_t count{0}; - for (const auto& ep : endpoints) - { - for (const auto& conn : ep.connections) - { - if (not(conn.second.remote_is_relay and clients_only)) - count++; - } - } - - return count; + return ep.num_connected(clients_only); } size_t @@ -147,31 +177,7 @@ namespace llarp bool LinkManager::get_random_connected(RouterContact& router) const { - std::unordered_map connectedRouters; - - for (const auto& ep : endpoints) - { - for (const auto& [router_id, conn] : ep.connections) - { - connectedRouters.emplace(router_id, conn.remote_rc); - } - } - - const auto sz = connectedRouters.size(); - if (sz) - { - auto itr = connectedRouters.begin(); - if (sz > 1) - { - std::advance(itr, randint() % sz); - } - - router = itr->second; - - return true; - } - - return false; + return ep.get_random_connection(router); } // TODO: this? perhaps no longer necessary in the same way? @@ -189,7 +195,7 @@ namespace llarp // TODO: this util::StatusObject - LinkManager::ExtractStatus() const + LinkManager::extract_status() const { return {}; } @@ -198,15 +204,17 @@ namespace llarp LinkManager::init(RCLookupHandler* rcLookup) { stopping = false; - _rcLookup = rcLookup; - _nodedb = router->nodedb(); + rc_lookup = rcLookup; + node_db = router.node_db(); } void LinkManager::connect_to(RouterID router) { auto fn = [this]( - const RouterID& rid, const RouterContact* const rc, const RCRequestResult res) { + [[maybe_unused]] const RouterID& rid, + const RouterContact* const rc, + const RCRequestResult res) { if (res == RCRequestResult::Success) connect_to(*rc); /* TODO: @@ -215,26 +223,18 @@ namespace llarp */ }; - _rcLookup->GetRC(router, fn); + rc_lookup->get_rc(router, fn); } // This function assumes the RC has already had its signature verified and connection is allowed. void LinkManager::connect_to(RouterContact rc) { - // TODO: connection failed callback if (have_connection_to(rc.pubkey)) + { + // TODO: connection failed callback return; - - // RC shouldn't be valid if this is the case, but may as well sanity check... - // TODO: connection failed callback - if (rc.addrs.empty()) - return; - - // TODO: connection failed callback - auto* ep = get_compatible_link(rc); - if (ep == nullptr) - return; + } // TODO: connection established/failed callbacks oxen::quic::stream_data_callback stream_cb = @@ -245,51 +245,41 @@ namespace llarp // TODO: once "compatible link" cares about address, actually choose addr to connect to // based on which one is compatible with the link we chose. For now, just use // the first one. - auto& selected = rc.addrs[0]; - oxen::quic::opt::remote_addr remote{selected.IPString(), selected.port}; + auto& remote_addr = rc.addr; + // TODO: confirm remote end is using the expected pubkey (RouterID). // TODO: ALPN for "client" vs "relay" (could just be set on endpoint creation) // TODO: does connect() inherit the endpoint's datagram data callback, and do we want it to if // so? - auto conn_interface = ep->endpoint->connect(remote, stream_cb, tls_creds); - - std::shared_ptr stream = conn_interface->get_new_stream(); - - llarp::link::Connection conn; - conn.conn = conn_interface; - conn.control_stream = stream; - conn.remote_rc = rc; - conn.inbound = false; - conn.remote_is_relay = true; - - ep->connections[rc.pubkey] = std::move(conn); - ep->connid_map[conn_interface->scid()] = rc.pubkey; + if (auto rv = ep.establish_connection(remote_addr, rc, stream_cb, tls_creds); rv) + { + log::info(quic_cat, "Connection to {} successfully established!", remote_addr); + return; + } + log::warning(quic_cat, "Connection to {} successfully established!", remote_addr); } void - LinkManager::connect_to_random(int numDesired) + LinkManager::connect_to_random(int num_conns) { std::set exclude; - auto remainingDesired = numDesired; + auto remainder = num_conns; + do { auto filter = [exclude](const auto& rc) -> bool { return exclude.count(rc.pubkey) == 0; }; - RouterContact other; - if (const auto maybe = _nodedb->GetRandom(filter)) + if (auto maybe_other = node_db->GetRandom(filter)) { - other = *maybe; - } - else - break; + exclude.insert(maybe_other->pubkey); - exclude.insert(other.pubkey); - if (not _rcLookup->SessionIsAllowed(other.pubkey)) - continue; + if (not rc_lookup->is_session_allowed(maybe_other->pubkey)) + continue; - Connect(other); - --remainingDesired; - } while (remainingDesired > 0); + connect_to(*maybe_other); + --remainder; + } + } while (remainder > 0); } void diff --git a/llarp/link/link_manager.hpp b/llarp/link/link_manager.hpp index 92fbbe1a5..edad06f05 100644 --- a/llarp/link/link_manager.hpp +++ b/llarp/link/link_manager.hpp @@ -1,10 +1,11 @@ #pragma once +#include +#include +#include +#include #include -#include "server.hpp" -#include "endpoint.hpp" - #include #include @@ -20,6 +21,52 @@ namespace namespace llarp { + struct LinkManager; + + namespace link + { + struct Connection; + + struct Endpoint + { + Endpoint(std::shared_ptr ep, LinkManager& lm) + : endpoint{std::move(ep)}, link_manager{lm} + {} + + std::shared_ptr endpoint; + LinkManager& link_manager; + + // for outgoing packets, we route via RouterID; map RouterID->Connection + // for incoming packets, we get a ConnectionID; map ConnectionID->RouterID + std::unordered_map> conns; + std::unordered_map connid_map; + + std::shared_ptr + get_conn(const RouterContact&) const; + + bool + have_conn(const RouterID& remote, bool client_only) const; + + bool + deregister_peer(RouterID remote); + + size_t + num_connected(bool clients_only) const; + + bool + get_random_connection(RouterContact& router) const; + // DISCUSS: added template to forward callbacks/etc to endpoint->connect(...). + // This would be useful after combining link_manager with the redundant classes + // listed below. As a result, link_manager would be holding all the relevant + // callbacks, tls_creds, and other context required for endpoint management + template + bool + establish_connection(const oxen::quic::Address& remote, RouterContact& rc, Opt&&... opts); + + private: + }; + } // namespace link + enum class SessionResult { Establish, @@ -52,11 +99,7 @@ namespace llarp explicit LinkManager(Router& r); bool - send_to( - const RouterID& remote, - const llarp_buffer_t& buf, - AbstractLinkSession::CompletionHandler completed, - uint16_t priority); + send_to(const RouterID& remote, const llarp_buffer_t& buf, uint16_t priority); bool have_connection_to(const RouterID& remote, bool client_only = false) const; @@ -67,9 +110,6 @@ namespace llarp void deregister_peer(RouterID remote); - void - connect_to(const oxen::quic::opt::local_addr& remote); - void connect_to(RouterID router); @@ -98,18 +138,18 @@ namespace llarp update_peer_db(std::shared_ptr peerDb); util::StatusObject - ExtractStatus() const; + extract_status() const; void init(RCLookupHandler* rcLookup); // Attempts to connect to a number of random routers. // - // This will try to connect to *up to* numDesired routers, but will not + // This will try to connect to *up to* num_conns routers, but will not // check if we already have a connection to any of the random set, as making // that thread safe would be slow...I think. void - connect_to_random(int numDesired); + connect_to_random(int num_conns); // TODO: tune these (maybe even remove max?) now that we're switching to quic /// always maintain this many connections to other routers @@ -120,21 +160,19 @@ namespace llarp private: friend struct link::Endpoint; - std::shared_ptr - get_compatible_link(const RouterContact& rc); - std::atomic stopping; - mutable util::Mutex _mutex; // protects m_PersistingSessions + // DISCUSS: is this necessary? can we reduce the amount of locking and nuke this + mutable util::Mutex m; // protects persisting_conns // sessions to persist -> timestamp to end persist at std::unordered_map persisting_conns GUARDED_BY(_mutex); - std::unordered_map last_router_stats; - util::DecayingHashSet clients{path::default_lifetime}; - RCLookupHandler* _rcLookup; - std::shared_ptr _nodedb; + RCLookupHandler* rc_lookup; + std::shared_ptr node_db; + + oxen::quic::Address addr; Router& router; @@ -151,4 +189,57 @@ namespace llarp recv_control_message(oxen::quic::Stream& stream, bstring_view packet); }; + namespace link + { + template + bool + Endpoint::establish_connection( + const oxen::quic::Address& remote, RouterContact& rc, Opt&&... opts) + { + try + { + oxen::quic::dgram_data_callback dgram_cb = + [this](oxen::quic::dgram_interface& dgi, bstring dgram) { + link_manager.recv_data_message(dgi, dgram); + }; + + auto conn_interface = + endpoint->connect(remote, link_manager.tls_creds, dgram_cb, std::forward(opts)...); + auto control_stream = conn_interface->get_new_stream(); + + // TOFIX: get a real RouterID after refactoring RouterID + RouterID rid; + auto [itr, b] = conns.emplace(rid); + itr->second = std::make_shared(conn_interface, rc, control_stream); + connid_map.emplace(conn_interface->scid(), rid); + + return true; + } + catch (...) + { + log::error(quic_cat, "Error: failed to establish connection to {}", remote); + return false; + } + } + } // namespace link + } // namespace llarp + +/* +- Refactor RouterID to use gnutls info and maybe ConnectionID +- Combine routerID and connectionID to simplify mapping in llarp/link/endpoint.hpp +- Combine llarp/link/session.hpp into llarp/link/connection.hpp::Connection + +- Combine llarp/link/server.hpp::ILinkLayer into llarp/link/endpoint.hpp::Endpoint + - must maintain metadata storage, callbacks, etc +- If: one endpoint for ipv4 and ipv6 + - Then: can potentially combine: + - llarp/link/endpoint.hpp + - llarp/link/link_manager.hpp + - llarp/link/outbound_message_handler.hpp + - llarp/link/outbound_session_maker.hpp + + -> Yields mega-combo endpoint managing object? + - Can avoid "kitchen sink" by greatly reducing complexity of implementation + +*/ diff --git a/llarp/link/server.cpp b/llarp/link/server.cpp index 12d56155a..5c9aef414 100644 --- a/llarp/link/server.cpp +++ b/llarp/link/server.cpp @@ -1,4 +1,3 @@ -#include "server.hpp" #include #include #include @@ -7,7 +6,7 @@ #include #include #include -#include +#include #include static constexpr auto LINK_LAYER_TICK_INTERVAL = 100ms; @@ -132,7 +131,7 @@ namespace llarp } void - ILinkLayer::Bind(AbstractRouter* router, SockAddr bind_addr) + ILinkLayer::Bind(Router* router, SockAddr bind_addr) { if (router->Net().IsLoopbackAddress(bind_addr.getIP())) throw std::runtime_error{"cannot udp bind socket on loopback"}; @@ -248,21 +247,6 @@ namespace llarp return false; } - bool - ILinkLayer::PickAddress(const RouterContact& rc, llarp::AddressInfo& picked) const - { - auto OurDialect = Name(); - for (const auto& addr : rc.addrs) - { - if (addr.dialect == OurDialect) - { - picked = addr; - return true; - } - } - return false; - } - util::StatusObject ILinkLayer::ExtractStatus() const { diff --git a/llarp/link/server.hpp b/llarp/link/server.hpp deleted file mode 100644 index 1f2de21b7..000000000 --- a/llarp/link/server.hpp +++ /dev/null @@ -1,278 +0,0 @@ -#pragma once - -#include -#include -#include "session.hpp" -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace llarp -{ - /// handle a link layer message. this allows for the message to be handled by "upper layers" - /// - /// currently called from iwp::Session when messages are sent or received. - using LinkMessageHandler = std::function; - - /// sign a buffer with identity key. this function should take the given `llarp_buffer_t` and - /// sign it, prividing the signature in the out variable `Signature&`. - /// - /// currently called from iwp::Session for signing LIMs (link introduction messages) - using SignBufferFunc = std::function; - - /// handle connection timeout - /// - /// currently called from ILinkLayer::Pump() when an unestablished session times out - using TimeoutHandler = std::function; - - /// get our RC - /// - /// currently called by iwp::Session to include as part of a LIM (link introduction message) - using GetRCFunc = std::function; - - /// handler of session established - /// return false to reject - /// return true to accept - /// - /// currently called in iwp::Session when a valid LIM is received. - 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 - /// - /// currently called from iwp::Session when we receive a renegotiation LIM - using SessionRenegotiateHandler = std::function; - - /// handles close of all sessions with pubkey - /// - /// Note that this handler is called while m_AuthedLinksMutex is held - /// - /// currently called from iwp::ILinkSession when a previously established session times out - using SessionClosedHandler = std::function; - - /// notifies router that a link session has ended its pump and we should flush - /// messages to upper layers - /// - /// currently called at the end of every iwp::Session::Pump() call - using PumpDoneHandler = std::function; - - using Work_t = std::function; - /// queue work to worker thread - using WorkerFunc_t = std::function; - - /// before connection hook, called before we try connecting via outbound link - using BeforeConnectFunc_t = std::function; - - struct ILinkLayer - { - ILinkLayer( - std::shared_ptr keyManager, - GetRCFunc getrc, - LinkMessageHandler handler, - SignBufferFunc signFunc, - BeforeConnectFunc_t before, - SessionEstablishedHandler sessionEstablish, - SessionRenegotiateHandler renegotiate, - TimeoutHandler timeout, - SessionClosedHandler closed, - PumpDoneHandler pumpDone, - WorkerFunc_t doWork); - virtual ~ILinkLayer() = default; - - /// get current time via event loop - llarp_time_t - Now() const; - - bool - HasSessionTo(const RouterID& pk); - - void - ForEachSession(std::function visit, bool randomize = false) - const EXCLUDES(m_AuthedLinksMutex); - - void - ForEachSession(std::function visit) EXCLUDES(m_AuthedLinksMutex); - - void - UnmapAddr(const SockAddr& addr); - - void - SendTo_LL(const SockAddr& to, const llarp_buffer_t& pkt); - - void - Bind(AbstractRouter* router, SockAddr addr); - - virtual std::shared_ptr - NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) = 0; - - /// fetch a session by the identity pubkey it claims - std::shared_ptr - FindSessionByPubkey(RouterID pk); - - virtual void - Pump(); - - virtual void - RecvFrom(const SockAddr& from, AbstractLinkSession::Packet_t pkt) = 0; - - bool - PickAddress(const RouterContact& rc, AddressInfo& picked) const; - - bool - TryEstablishTo(RouterContact rc); - - bool - Start(); - - virtual void - Stop(); - - virtual std::string_view - Name() const = 0; - - util::StatusObject - ExtractStatus() const EXCLUDES(m_AuthedLinksMutex); - - void - CloseSessionTo(const RouterID& remote); - - void - KeepAliveSessionTo(const RouterID& remote); - - virtual bool - SendTo( - const RouterID& remote, - const llarp_buffer_t& buf, - AbstractLinkSession::CompletionHandler completed, - uint16_t priority); - - virtual bool - GetOurAddressInfo(AddressInfo& addr) const; - - bool - VisitSessionByPubkey(const RouterID& pk, std::function visit) - EXCLUDES(m_AuthedLinksMutex); - - virtual uint16_t - Rank() const = 0; - - const byte_t* - TransportPubKey() const; - - const SecretKey& - RouterEncryptionSecret() const - { - return m_RouterEncSecret; - } - - const SecretKey& - TransportSecretKey() const; - - bool - IsCompatable(const llarp::RouterContact& other) const - { - const auto us = Name(); - for (const auto& ai : other.addrs) - if (ai.dialect == us) - return true; - return false; - } - - bool - MapAddr(const RouterID& pk, AbstractLinkSession* s); - - void - Tick(llarp_time_t now); - - LinkMessageHandler HandleMessage; - TimeoutHandler HandleTimeout; - SignBufferFunc Sign; - GetRCFunc GetOurRC; - BeforeConnectFunc_t BeforeConnect; - SessionEstablishedHandler SessionEstablished; - SessionClosedHandler SessionClosed; - SessionRenegotiateHandler SessionRenegotiate; - PumpDoneHandler PumpDone; - std::shared_ptr keyManager; - WorkerFunc_t QueueWork; - - bool - operator<(const ILinkLayer& other) const - { - auto rankA = Rank(), rankB = other.Rank(); - auto nameA = Name(), nameB = other.Name(); - return std::tie(rankA, nameA, m_ourAddr) < std::tie(rankB, nameB, other.m_ourAddr); - } - - /// called by link session to remove a pending session who is timed out - // void - // RemovePending(ILinkSession* s) EXCLUDES(m_PendingMutex); - - /// count the number of sessions that are yet to be fully connected - size_t - NumberOfPendingSessions() const - { - Lock_t lock(m_PendingMutex); - return m_Pending.size(); - } - - // Returns the file description of the UDP server, if available. - std::optional - GetUDPFD() const; - - // Gets a pointer to the router owning us. - AbstractRouter* - Router() const - { - return m_Router; - } - - /// Get the local sock addr we are bound on - const SockAddr& - LocalSocketAddr() const - { - return m_ourAddr; - } - - private: - const SecretKey& m_RouterEncSecret; - - protected: -#ifdef TRACY_ENABLE - using Lock_t = std::lock_guard; - using Mutex_t = std::mutex; -#else - using Lock_t = util::NullLock; - using Mutex_t = util::NullMutex; -#endif - bool - PutSession(const std::shared_ptr& s); - - AbstractRouter* m_Router; - SockAddr m_ourAddr; - std::shared_ptr m_udp; - SecretKey m_SecretKey; - - using AuthedLinks = std::unordered_multimap>; - using Pending = std::unordered_map>; - 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)); - Pending m_Pending GUARDED_BY(m_PendingMutex); - std::unordered_map m_AuthedAddrs; - std::unordered_map m_RecentlyClosed; - - private: - std::shared_ptr m_repeater_keepalive; - }; - - using LinkLayer_ptr = std::shared_ptr; -} // namespace llarp diff --git a/llarp/link/session.cpp b/llarp/link/session.cpp deleted file mode 100644 index a7894780c..000000000 --- a/llarp/link/session.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "session.hpp" - -namespace llarp -{ - bool - AbstractLinkSession::IsRelay() const - { - return GetRemoteRC().IsPublicRouter(); - } - -} // namespace llarp diff --git a/llarp/link/session.hpp b/llarp/link/session.hpp deleted file mode 100644 index 8c5b96d94..000000000 --- a/llarp/link/session.hpp +++ /dev/null @@ -1,138 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include - -namespace llarp -{ - struct LinkIntroMessage; - struct AbstractLinkMessage; - struct ILinkLayer; - - struct SessionStats - { - // rate - uint64_t currentRateRX = 0; - uint64_t currentRateTX = 0; - - uint64_t totalPacketsRX = 0; - - uint64_t totalAckedTX = 0; - uint64_t totalDroppedTX = 0; - uint64_t totalInFlightTX = 0; - }; - - struct AbstractLinkSession - { - virtual ~AbstractLinkSession() = default; - - /// delivery status of a message - enum class DeliveryStatus - { - eDeliverySuccess = 0, - eDeliveryDropped = 1 - }; - - /// hook for utp for when we have established a connection - virtual void - OnLinkEstablished(ILinkLayer*){}; - - /// called during pumping - virtual void - Pump() = 0; - - /// called every timer tick - virtual void Tick(llarp_time_t) = 0; - - /// message delivery result hook function - using CompletionHandler = std::function; - - using Packet_t = std::vector; - using Message_t = std::vector; - - /// send a message buffer to the remote endpoint - virtual bool - SendMessageBuffer(Message_t, CompletionHandler handler, uint16_t priority) = 0; - - /// start the connection - virtual void - Start() = 0; - - virtual void - Close() = 0; - - /// recv packet on low layer - /// not used by utp - virtual bool - Recv_LL(Packet_t) - { - return true; - } - - /// send a keepalive to the remote endpoint - virtual bool - SendKeepAlive() = 0; - - /// return true if we are established - virtual bool - IsEstablished() const = 0; - - /// return true if this session has timed out - virtual bool - TimedOut(llarp_time_t now) const = 0; - - /// get remote public identity key - virtual PubKey - GetPubKey() const = 0; - - /// is an inbound session or not - virtual bool - IsInbound() const = 0; - - /// get remote address - virtual const SockAddr& - GetRemoteEndpoint() const = 0; - - // get remote rc - virtual RouterContact - GetRemoteRC() const = 0; - - /// is this session a session to a relay? - bool - IsRelay() const; - - /// handle a valid LIM - std::function GotLIM; - - /// send queue current blacklog - virtual size_t - SendQueueBacklog() const = 0; - - /// get parent link layer - virtual ILinkLayer* - GetLinkLayer() const = 0; - - /// renegotiate session when we have a new RC locally - virtual bool - RenegotiateSession() = 0; - - /// return true if we should send an explicit keepalive message - virtual bool - ShouldPing() const = 0; - - /// return the current stats for this session - virtual SessionStats - GetSessionStats() const = 0; - - virtual util::StatusObject - ExtractStatus() const = 0; - - virtual void - HandlePlaintext() = 0; - }; -} // namespace llarp diff --git a/llarp/lokinet_shared.cpp b/llarp/lokinet_shared.cpp index 7d4a0f085..33488edb2 100644 --- a/llarp/lokinet_shared.cpp +++ b/llarp/lokinet_shared.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include #include diff --git a/llarp/messages/dht_immediate.cpp b/llarp/messages/dht_immediate.cpp index 86b8420db..2b1585084 100644 --- a/llarp/messages/dht_immediate.cpp +++ b/llarp/messages/dht_immediate.cpp @@ -1,6 +1,6 @@ #include "dht_immediate.hpp" -#include +#include #include namespace llarp @@ -62,7 +62,7 @@ namespace llarp } bool - DHTImmediateMessage::handle_message(AbstractRouter* router) const + DHTImmediateMessage::handle_message(Router* router) const { DHTImmediateMessage reply; reply.session = session; diff --git a/llarp/messages/dht_immediate.hpp b/llarp/messages/dht_immediate.hpp index 25c6f6288..905fed8c4 100644 --- a/llarp/messages/dht_immediate.hpp +++ b/llarp/messages/dht_immediate.hpp @@ -21,7 +21,7 @@ namespace llarp decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; void clear() override; diff --git a/llarp/messages/discard.hpp b/llarp/messages/discard.hpp index cebc5782d..44535e734 100644 --- a/llarp/messages/discard.hpp +++ b/llarp/messages/discard.hpp @@ -57,7 +57,7 @@ namespace llarp } bool - handle_message(AbstractRouter* /*router*/) const override + handle_message(Router* /*router*/) const override { return true; } @@ -84,7 +84,7 @@ namespace llarp } bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override { return h->HandleDataDiscardMessage(*this, r); } diff --git a/llarp/messages/link_intro.cpp b/llarp/messages/link_intro.cpp index 70b4b6df6..05377caa0 100644 --- a/llarp/messages/link_intro.cpp +++ b/llarp/messages/link_intro.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include @@ -91,7 +91,7 @@ namespace llarp } bool - LinkIntroMessage::handle_message(AbstractRouter* /*router*/) const + LinkIntroMessage::handle_message(Router* /*router*/) const { if (!verify()) return false; diff --git a/llarp/messages/link_intro.hpp b/llarp/messages/link_intro.hpp index c76b4ac81..51b5276e0 100644 --- a/llarp/messages/link_intro.hpp +++ b/llarp/messages/link_intro.hpp @@ -24,7 +24,7 @@ namespace llarp bt_encode() const override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; bool decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) override; diff --git a/llarp/messages/link_message.hpp b/llarp/messages/link_message.hpp index 91602a174..237fda914 100644 --- a/llarp/messages/link_message.hpp +++ b/llarp/messages/link_message.hpp @@ -2,7 +2,6 @@ #include "common.hpp" -#include #include #include #include @@ -12,7 +11,7 @@ namespace llarp { struct AbstractLinkSession; - struct AbstractRouter; + struct Router; /// parsed link layer message struct AbstractLinkMessage : private AbstractSerializable @@ -31,7 +30,7 @@ namespace llarp bt_encode() const override = 0; virtual bool - handle_message(AbstractRouter* router) const = 0; + handle_message(Router* router) const = 0; virtual bool decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) = 0; diff --git a/llarp/messages/link_message_parser.cpp b/llarp/messages/link_message_parser.cpp index ae4cf7e58..5651fc9df 100644 --- a/llarp/messages/link_message_parser.cpp +++ b/llarp/messages/link_message_parser.cpp @@ -28,7 +28,7 @@ namespace llarp msg_holder_t() = default; }; - LinkMessageParser::LinkMessageParser(AbstractRouter* _router) + LinkMessageParser::LinkMessageParser(Router* _router) : router(_router), from(nullptr), msg(nullptr), holder(std::make_unique()) {} diff --git a/llarp/messages/link_message_parser.hpp b/llarp/messages/link_message_parser.hpp index 584142418..dffe4f75b 100644 --- a/llarp/messages/link_message_parser.hpp +++ b/llarp/messages/link_message_parser.hpp @@ -7,13 +7,13 @@ namespace llarp { - struct AbstractRouter; + struct Router; struct AbstractLinkMessage; struct AbstractLinkSession; struct LinkMessageParser { - LinkMessageParser(AbstractRouter* router); + LinkMessageParser(Router* router); ~LinkMessageParser(); bool @@ -38,7 +38,7 @@ namespace llarp private: bool firstkey; - AbstractRouter* router; + Router* router; AbstractLinkSession* from; AbstractLinkMessage* msg; diff --git a/llarp/messages/relay.cpp b/llarp/messages/relay.cpp index 02a0e0b54..5eeaf8b6c 100644 --- a/llarp/messages/relay.cpp +++ b/llarp/messages/relay.cpp @@ -1,7 +1,7 @@ #include "relay.hpp" #include -#include +#include #include namespace llarp @@ -52,9 +52,9 @@ namespace llarp } bool - RelayUpstreamMessage::handle_message(AbstractRouter* r) const + RelayUpstreamMessage::handle_message(Router* r) const { - auto path = r->pathContext().GetByDownstream(session->GetPubKey(), pathid); + auto path = r->path_context().GetByDownstream(session->GetPubKey(), pathid); if (path) { return path->HandleUpstream(llarp_buffer_t(enc), nonce, r); @@ -108,9 +108,9 @@ namespace llarp } bool - RelayDownstreamMessage::handle_message(AbstractRouter* r) const + RelayDownstreamMessage::handle_message(Router* r) const { - auto path = r->pathContext().GetByUpstream(session->GetPubKey(), pathid); + auto path = r->path_context().GetByUpstream(session->GetPubKey(), pathid); if (path) { return path->HandleDownstream(llarp_buffer_t(enc), nonce, r); diff --git a/llarp/messages/relay.hpp b/llarp/messages/relay.hpp index d7b6c26ce..266a01aef 100644 --- a/llarp/messages/relay.hpp +++ b/llarp/messages/relay.hpp @@ -21,7 +21,7 @@ namespace llarp bt_encode() const override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; void clear() override; @@ -50,7 +50,7 @@ namespace llarp bt_encode() const override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; void clear() override; diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index e93475d20..c62cee90d 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -5,7 +5,7 @@ #include #include #include -#include +#include #include #include #include @@ -68,19 +68,19 @@ namespace llarp } bool - LR_CommitMessage::handle_message(AbstractRouter* router) const + LR_CommitMessage::handle_message(Router* router) const { if (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->path_context().AllowingTransit()) { llarp::LogError("got LRCM when not permitting transit"); return false; } - return AsyncDecrypt(&router->pathContext()); + return AsyncDecrypt(&router->path_context()); } bool @@ -212,7 +212,7 @@ namespace llarp static void OnForwardLRCMResult( - AbstractRouter* router, + Router* router, std::shared_ptr path, const PathID_t pathid, const RouterID nextHop, @@ -246,7 +246,7 @@ namespace llarp std::abort(); break; } - router->QueueWork([router, path, pathid, nextHop, pathKey, status] { + router->queue_work([router, path, pathid, nextHop, pathKey, status] { LR_StatusMessage::CreateAndSend(router, path, pathid, nextHop, pathKey, status); }); } @@ -259,7 +259,7 @@ namespace llarp { llarp::LogError("duplicate transit hop ", self->hop->info); LR_StatusMessage::CreateAndSend( - self->context->Router(), + self->context->router(), self->hop, self->hop->info.rxID, self->hop->info.downstream, @@ -278,7 +278,7 @@ namespace llarp // we hit a limit so tell it to slow tf down llarp::LogError("client path build hit limit ", *self->fromAddr); OnForwardLRCMResult( - self->context->Router(), + self->context->router(), self->hop, self->hop->info.rxID, self->hop->info.downstream, @@ -290,7 +290,7 @@ namespace llarp #endif } - if (not self->context->Router()->PathToRouterAllowed(self->hop->info.upstream)) + if (not self->context->router()->PathToRouterAllowed(self->hop->info.upstream)) { // we are not allowed to forward it ... now what? llarp::LogError( @@ -298,7 +298,7 @@ namespace llarp self->hop->info.upstream, "not allowed, dropping build request on the floor"); OnForwardLRCMResult( - self->context->Router(), + self->context->router(), self->hop, self->hop->info.rxID, self->hop->info.downstream, @@ -309,9 +309,9 @@ namespace llarp } // persist sessions to upstream and downstream routers until the commit // ends - self->context->Router()->PersistSessionUntil( + self->context->router()->PersistSessionUntil( self->hop->info.downstream, self->hop->ExpireTime() + 10s); - self->context->Router()->PersistSessionUntil( + self->context->router()->PersistSessionUntil( self->hop->info.upstream, self->hop->ExpireTime() + 10s); // put hop self->context->PutTransitHop(self->hop); @@ -319,7 +319,7 @@ namespace llarp using std::placeholders::_1; auto func = [self](auto status) { OnForwardLRCMResult( - self->context->Router(), + self->context->router(), self->hop, self->hop->info.rxID, self->hop->info.downstream, @@ -329,7 +329,7 @@ namespace llarp }; self->context->ForwardLRCM(self->hop->info.upstream, self->frames, func); // trigger idempotent pump to ensure that the build messages propagate - self->context->Router()->TriggerPump(); + self->context->router()->TriggerPump(); } // this is called from the logic thread @@ -346,14 +346,14 @@ namespace llarp else { // persist session to downstream until path expiration - self->context->Router()->PersistSessionUntil( + self->context->router()->PersistSessionUntil( self->hop->info.downstream, self->hop->ExpireTime() + 10s); // put hop self->context->PutTransitHop(self->hop); } if (!LR_StatusMessage::CreateAndSend( - self->context->Router(), + self->context->router(), self->hop, self->hop->info.rxID, self->hop->info.downstream, @@ -371,7 +371,7 @@ namespace llarp static void 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) { @@ -434,8 +434,8 @@ namespace llarp // TODO: check if we really want to accept it self->hop->started = now; - self->context->Router()->NotifyRouterEvent( - self->context->Router()->pubkey(), self->hop); + self->context->router()->NotifyRouterEvent( + self->context->router()->pubkey(), self->hop); size_t sz = self->frames[0].size(); // shift @@ -472,7 +472,7 @@ namespace llarp }); } // trigger idempotent pump to ensure that the build messages propagate - self->context->Router()->TriggerPump(); + self->context->router()->TriggerPump(); } }; @@ -486,7 +486,7 @@ namespace llarp // decrypt frames async frameDecrypt->decrypter->AsyncDecrypt( - frameDecrypt->frames[0], frameDecrypt, [r = context->Router()](auto func) { + frameDecrypt->frames[0], frameDecrypt, [r = context->router()](auto func) { r->QueueWork(std::move(func)); }); return true; diff --git a/llarp/messages/relay_commit.hpp b/llarp/messages/relay_commit.hpp index f6c1c371f..b7c27c5e6 100644 --- a/llarp/messages/relay_commit.hpp +++ b/llarp/messages/relay_commit.hpp @@ -13,7 +13,7 @@ namespace llarp { // forward declare - struct AbstractRouter; + struct Router; namespace path { struct PathContext; @@ -67,7 +67,7 @@ namespace llarp bt_encode() const override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; bool AsyncDecrypt(llarp::path::PathContext* context) const; diff --git a/llarp/messages/relay_status.cpp b/llarp/messages/relay_status.cpp index 44a02f3de..d831df8d2 100644 --- a/llarp/messages/relay_status.cpp +++ b/llarp/messages/relay_status.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include #include @@ -23,14 +23,14 @@ namespace llarp std::array frames; uint64_t status = 0; HopHandler_ptr hop; - AbstractRouter* router; + Router* router; PathID_t pathid; LRSM_AsyncHandler( std::array _frames, uint64_t _status, HopHandler_ptr _hop, - AbstractRouter* _router, + Router* _router, PathID_t pathid) : frames{std::move(_frames)} , status{_status} @@ -44,7 +44,8 @@ namespace llarp void handle() { - router->NotifyRouterEvent(router->pubkey(), pathid, status); + router->notify_router_event( + router->pubkey(), pathid, status); hop->HandleLRSM(status, frames, router); } @@ -52,7 +53,7 @@ namespace llarp queue_handle() { auto func = [self = shared_from_this()] { self->handle(); }; - router->QueueWork(func); + router->queue_work(func); } }; @@ -126,7 +127,7 @@ namespace llarp } bool - LR_StatusMessage::handle_message(AbstractRouter* router) const + LR_StatusMessage::handle_message(Router* router) const { llarp::LogDebug("Received LR_Status message from (", session->GetPubKey(), ")"); if (frames.size() != path::max_len) @@ -135,7 +136,7 @@ namespace llarp return false; } - auto path = router->pathContext().GetByUpstream(session->GetPubKey(), pathid); + auto path = router->path_context().GetByUpstream(session->GetPubKey(), pathid); if (not path) { llarp::LogWarn("unhandled LR_Status message: no associated path found pathid=", pathid); @@ -156,7 +157,7 @@ namespace llarp // call this from a worker thread bool LR_StatusMessage::CreateAndSend( - AbstractRouter* router, + Router* router, std::shared_ptr hop, const PathID_t pathid, const RouterID nextHop, @@ -219,7 +220,7 @@ namespace llarp void LR_StatusMessage::QueueSendMessage( - AbstractRouter* router, + Router* router, const RouterID nextHop, std::shared_ptr msg, std::shared_ptr hop) @@ -231,7 +232,7 @@ namespace llarp void LR_StatusMessage::SendMessage( - AbstractRouter* router, + Router* router, const RouterID nextHop, std::shared_ptr msg, std::shared_ptr hop) diff --git a/llarp/messages/relay_status.hpp b/llarp/messages/relay_status.hpp index e30d6479f..f0ce9bdd2 100644 --- a/llarp/messages/relay_status.hpp +++ b/llarp/messages/relay_status.hpp @@ -13,7 +13,7 @@ namespace llarp { // forward declare - struct AbstractRouter; + struct Router; namespace path { struct PathContext; @@ -79,14 +79,14 @@ namespace llarp bt_encode() const override; bool - handle_message(AbstractRouter* router) const override; + handle_message(Router* router) const override; void SetDummyFrames(); static bool CreateAndSend( - AbstractRouter* router, + Router* router, std::shared_ptr hop, const PathID_t pathid, const RouterID nextHop, @@ -98,14 +98,14 @@ namespace llarp static void QueueSendMessage( - AbstractRouter* router, + Router* router, const RouterID nextHop, std::shared_ptr msg, std::shared_ptr hop); static void SendMessage( - AbstractRouter* router, + Router* router, const RouterID nextHop, std::shared_ptr msg, std::shared_ptr hop); diff --git a/llarp/net/address_info.cpp b/llarp/net/address_info.cpp deleted file mode 100644 index a0f972570..000000000 --- a/llarp/net/address_info.cpp +++ /dev/null @@ -1,185 +0,0 @@ -#include "address_info.hpp" -#include - -#ifndef _WIN32 -#include -#endif -#include "net.hpp" -#include -#include - -#include - -namespace llarp -{ - bool - 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; - } - - bool - operator<(const AddressInfo& lhs, const AddressInfo& rhs) - { - return std::tie(lhs.rank, lhs.ip, lhs.port) < std::tie(rhs.rank, rhs.ip, rhs.port); - } - - std::variant - AddressInfo::IP() const - { - return SockAddr{ip}.getIP(); - } - - bool - AddressInfo::decode_key(const llarp_buffer_t& key, llarp_buffer_t* buf) - { - uint64_t i; - char tmp[128] = {0}; - - llarp_buffer_t strbuf; - - // rank - if (key.startswith("c")) - { - if (!bencode_read_integer(buf, &i)) - return false; - - if (i > 65536 || i <= 0) - return false; - - rank = i; - return true; - } - - // dialect - if (key.startswith("d")) - { - if (!bencode_read_string(buf, &strbuf)) - return false; - if (strbuf.sz > sizeof(tmp)) - return false; - memcpy(tmp, strbuf.base, strbuf.sz); - tmp[strbuf.sz] = 0; - dialect = std::string(tmp); - return true; - } - - // encryption public key - if (key.startswith("e")) - { - return pubkey.BDecode(buf); - } - - // ip address - if (key.startswith("i")) - { - if (!bencode_read_string(buf, &strbuf)) - return false; - - if (strbuf.sz >= sizeof(tmp)) - return false; - - memcpy(tmp, strbuf.base, strbuf.sz); - tmp[strbuf.sz] = 0; - return inet_pton(AF_INET6, tmp, &ip.s6_addr[0]) == 1; - } - - // port - if (key.startswith("p")) - { - if (!bencode_read_integer(buf, &i)) - return false; - - if (i > 65536 || i <= 0) - return false; - - port = i; - return true; - } - - // version - if (key.startswith("v")) - { - if (!bencode_read_integer(buf, &i)) - return false; - return i == llarp::constants::proto_version; - } - - // bad key - return false; - } - - std::string - AddressInfo::bt_encode() const - { - char ipbuff[128] = {0}; - oxenc::bt_dict_producer btdp; - - try - { - btdp.append("c", rank); - btdp.append("d", dialect); - btdp.append("e", pubkey.ToView()); - - const char* ipstr = inet_ntop(AF_INET6, (void*)&ip, ipbuff, sizeof(ipbuff)); - - btdp.append("i", std::string_view{ipstr, strnlen(ipstr, sizeof(ipbuff))}); - btdp.append("p", port); - btdp.append("v", version); - } - catch (...) - { - log::critical(net_cat, "Error: AddressInfo failed to bt encode contents!"); - } - - return std::move(btdp).str(); - } - - IpAddress - AddressInfo::toIpAddress() const - { - SockAddr addr(ip); - addr.setPort(port); - return {addr}; - } - - void - AddressInfo::fromSockAddr(const SockAddr& addr) - { - const auto* addr6 = static_cast(addr); - memcpy(ip.s6_addr, addr6->sin6_addr.s6_addr, sizeof(ip.s6_addr)); - port = addr.getPort(); - } - - std::string - AddressInfo::ToString() const - { - char tmp[INET6_ADDRSTRLEN] = {0}; - inet_ntop(AF_INET6, (void*)&ip, tmp, sizeof(tmp)); - return fmt::format("[{}]:{}", tmp, port); - } - - std::string - AddressInfo::IPString() const - { - char tmp[INET6_ADDRSTRLEN] = {0}; - inet_ntop(AF_INET6, (void*)&ip, tmp, sizeof(tmp)); - return std::string{tmp}; - } - - void - to_json(nlohmann::json& j, const AddressInfo& a) - { - char tmp[128] = {0}; - inet_ntop(AF_INET6, (void*)&a.ip, tmp, sizeof(tmp)); - - j = nlohmann::json{ - {"rank", a.rank}, - {"dialect", a.dialect}, - {"pubkey", a.pubkey.ToString()}, - {"in6_addr", tmp}, - {"port", a.port}}; - } -} // namespace llarp diff --git a/llarp/net/address_info.hpp b/llarp/net/address_info.hpp deleted file mode 100644 index a1971cbca..000000000 --- a/llarp/net/address_info.hpp +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include -#include "ip_address.hpp" -#include "net.h" -#include -#include - -#include -#include - -#include - -/** - * address_info.hpp - * - * utilities for handling addresses on the llarp network - */ - -/// address information model -namespace llarp -{ - struct AddressInfo - { - uint16_t rank; - std::string dialect; - llarp::PubKey pubkey; - in6_addr ip = {}; - uint16_t port; - uint64_t version = llarp::constants::proto_version; - - bool - BDecode(llarp_buffer_t* buf) - { - return bencode_decode_dict(*this, buf); - } - - std::string - bt_encode() const; - - bool - decode_key(const llarp_buffer_t& k, llarp_buffer_t* buf); - - /// Return an IpAddress representing the address portion of this AddressInfo - IpAddress - toIpAddress() const; - - /// Updates our ip and port to reflect that of the given SockAddr - void - fromSockAddr(const SockAddr& address); - - /// get this as an explicit v4 or explicit v6 - net::ipaddr_t - IP() const; - - /// get this as an v4 or throw if it is not one - inline net::ipv4addr_t - IPv4() const - { - auto ip = IP(); - if (auto* ptr = std::get_if(&ip)) - return *ptr; - throw std::runtime_error{"no ipv4 address found in address info"}; - } - - std::string - ToString() const; - - std::string - IPString() const; - }; - - void - to_json(nlohmann::json& j, const AddressInfo& a); - - bool - operator==(const AddressInfo& lhs, const AddressInfo& rhs); - - bool - operator<(const AddressInfo& lhs, const AddressInfo& rhs); - - template <> - constexpr inline bool IsToStringFormattable = true; - -} // namespace llarp - -namespace std -{ - template <> - struct hash - { - size_t - operator()(const llarp::AddressInfo& addr) const - { - return std::hash{}(addr.pubkey); - } - }; -} // namespace std diff --git a/llarp/net/net.hpp b/llarp/net/net.hpp index b3a7af8e4..f21531029 100644 --- a/llarp/net/net.hpp +++ b/llarp/net/net.hpp @@ -1,7 +1,6 @@ #pragma once #include "uint128.hpp" -#include "address_info.hpp" #include "ip_address.hpp" #include "net_int.hpp" #include "net.h" diff --git a/llarp/path/ihophandler.cpp b/llarp/path/ihophandler.cpp index 3b7055cb9..9927765ef 100644 --- a/llarp/path/ihophandler.cpp +++ b/llarp/path/ihophandler.cpp @@ -1,5 +1,5 @@ #include "ihophandler.hpp" -#include +#include namespace llarp { @@ -7,7 +7,7 @@ namespace llarp { // handle data in upstream direction bool - IHopHandler::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) + IHopHandler::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router* r) { auto& pkt = m_UpstreamQueue.emplace_back(); pkt.first.resize(X.sz); @@ -19,7 +19,7 @@ namespace llarp // handle data in downstream direction bool - IHopHandler::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) + IHopHandler::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router* r) { auto& pkt = m_DownstreamQueue.emplace_back(); pkt.first.resize(X.sz); diff --git a/llarp/path/ihophandler.hpp b/llarp/path/ihophandler.hpp index e9bc981f3..68312a627 100644 --- a/llarp/path/ihophandler.hpp +++ b/llarp/path/ihophandler.hpp @@ -13,7 +13,7 @@ struct llarp_buffer_t; namespace llarp { - struct AbstractRouter; + struct Router; namespace routing { @@ -43,21 +43,21 @@ namespace llarp /// send routing message and increment sequence number virtual bool - SendRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r) = 0; + SendRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r) = 0; // 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, Router*); // 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, Router*); /// return timestamp last remote activity happened at virtual llarp_time_t LastRemoteActivityAt() const = 0; virtual bool - HandleLRSM(uint64_t status, std::array& frames, AbstractRouter* r) = 0; + HandleLRSM(uint64_t status, std::array& frames, Router* r) = 0; uint64_t NextSeqNo() @@ -66,10 +66,10 @@ namespace llarp } virtual void - FlushUpstream(AbstractRouter* r) = 0; + FlushUpstream(Router* r) = 0; virtual void - FlushDownstream(AbstractRouter* r) = 0; + FlushDownstream(Router* r) = 0; protected: uint64_t m_SequenceNum = 0; @@ -79,15 +79,15 @@ namespace llarp util::DecayingHashSet m_DownstreamReplayFilter; virtual void - UpstreamWork(TrafficQueue_t queue, AbstractRouter* r) = 0; + UpstreamWork(TrafficQueue_t queue, Router* r) = 0; virtual void - DownstreamWork(TrafficQueue_t queue, AbstractRouter* r) = 0; + DownstreamWork(TrafficQueue_t queue, Router* r) = 0; virtual void - HandleAllUpstream(std::vector msgs, AbstractRouter* r) = 0; + HandleAllUpstream(std::vector msgs, Router* r) = 0; virtual void - HandleAllDownstream(std::vector msgs, AbstractRouter* r) = 0; + HandleAllDownstream(std::vector msgs, Router* r) = 0; }; using HopHandler_ptr = std::shared_ptr; diff --git a/llarp/path/path.cpp b/llarp/path/path.cpp index c0d188ccb..c8204a33b 100644 --- a/llarp/path/path.cpp +++ b/llarp/path/path.cpp @@ -10,7 +10,7 @@ #include "transit_hop.hpp" #include #include -#include +#include #include #include #include @@ -66,7 +66,7 @@ namespace llarp::path } bool - Path::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) + Path::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router* r) { if (not m_UpstreamReplayFilter.Insert(Y)) return false; @@ -74,7 +74,7 @@ namespace llarp::path } bool - Path::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) + Path::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router* r) { if (not m_DownstreamReplayFilter.Insert(Y)) return false; @@ -146,7 +146,7 @@ namespace llarp::path } bool - Path::HandleLRSM(uint64_t status, std::array& frames, AbstractRouter* r) + Path::HandleLRSM(uint64_t status, std::array& frames, Router* r) { uint64_t currentStatus = status; @@ -204,7 +204,7 @@ namespace llarp::path { if (failedAt) { - r->NotifyRouterEvent(Endpoint(), RXID(), *failedAt); + r->notify_router_event(Endpoint(), RXID(), *failedAt); LogWarn( Name(), " build failed at ", @@ -213,10 +213,10 @@ namespace llarp::path LRStatusCodeToString(currentStatus), " hops=", HopsString()); - r->routerProfiling().MarkHopFail(*failedAt); + r->router_profiling().MarkHopFail(*failedAt); } else - r->routerProfiling().MarkPathFail(this); + r->router_profiling().MarkPathFail(this); llarp::LogDebug("LR_Status message processed, path build failed"); if (currentStatus & LR_StatusRecord::FAIL_TIMEOUT) @@ -240,7 +240,7 @@ namespace llarp::path "invalid destination"); if (failedAt) { - r->loop()->call([nodedb = r->nodedb(), router = *failedAt]() { + r->loop()->call([nodedb = r->node_db(), router = *failedAt]() { LogInfo("router ", router, " is deregistered so we remove it"); nodedb->Remove(router); }); @@ -411,7 +411,7 @@ namespace llarp::path } bool - Path::SendLatencyMessage(AbstractRouter* r) + Path::SendLatencyMessage(Router* r) { const auto now = r->Now(); // send path latency test @@ -428,7 +428,7 @@ namespace llarp::path } void - Path::Tick(llarp_time_t now, AbstractRouter* r) + Path::Tick(llarp_time_t now, Router* r) { if (Expired(now)) return; @@ -449,7 +449,7 @@ namespace llarp::path if (dlt >= path::build_timeout) { LogWarn(Name(), " waited for ", ToString(dlt), " and no path was built"); - r->routerProfiling().MarkPathFail(this); + r->router_profiling().MarkPathFail(this); EnterState(ePathExpired, now); return; } @@ -473,7 +473,7 @@ namespace llarp::path if (dlt >= path::alive_timeout) { LogWarn(Name(), " waited for ", ToString(dlt), " and path looks dead"); - r->routerProfiling().MarkPathFail(this); + r->router_profiling().MarkPathFail(this); EnterState(ePathTimeout, now); } } @@ -485,7 +485,7 @@ namespace llarp::path } void - Path::HandleAllUpstream(std::vector msgs, AbstractRouter* r) + Path::HandleAllUpstream(std::vector msgs, Router* r) { for (const auto& msg : msgs) { @@ -502,7 +502,7 @@ namespace llarp::path } void - Path::UpstreamWork(TrafficQueue_t msgs, AbstractRouter* r) + Path::UpstreamWork(TrafficQueue_t msgs, Router* r) { std::vector sendmsgs(msgs.size()); size_t idx = 0; @@ -527,24 +527,24 @@ namespace llarp::path } void - Path::FlushUpstream(AbstractRouter* r) + Path::FlushUpstream(Router* r) { if (not m_UpstreamQueue.empty()) { - r->QueueWork([self = shared_from_this(), - data = std::exchange(m_UpstreamQueue, {}), - r]() mutable { self->UpstreamWork(std::move(data), r); }); + r->queue_work([self = shared_from_this(), + data = std::exchange(m_UpstreamQueue, {}), + r]() mutable { self->UpstreamWork(std::move(data), r); }); } } void - Path::FlushDownstream(AbstractRouter* r) + Path::FlushDownstream(Router* r) { if (not m_DownstreamQueue.empty()) { - r->QueueWork([self = shared_from_this(), - data = std::exchange(m_DownstreamQueue, {}), - r]() mutable { self->DownstreamWork(std::move(data), r); }); + r->queue_work([self = shared_from_this(), + data = std::exchange(m_DownstreamQueue, {}), + r]() mutable { self->DownstreamWork(std::move(data), r); }); } } @@ -576,7 +576,7 @@ namespace llarp::path } void - Path::DownstreamWork(TrafficQueue_t msgs, AbstractRouter* r) + Path::DownstreamWork(TrafficQueue_t msgs, Router* r) { std::vector sendMsgs(msgs.size()); size_t idx = 0; @@ -598,7 +598,7 @@ namespace llarp::path } void - Path::HandleAllDownstream(std::vector msgs, AbstractRouter* r) + Path::HandleAllDownstream(std::vector msgs, Router* r) { for (const auto& msg : msgs) { @@ -613,7 +613,7 @@ namespace llarp::path } bool - Path::HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r) + Path::HandleRoutingMessage(const llarp_buffer_t& buf, Router* r) { if (!r->ParseRoutingMessageBuffer(buf, this, RXID())) { @@ -624,8 +624,7 @@ namespace llarp::path } bool - Path::HandleUpdateExitVerifyMessage( - const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) + Path::HandleUpdateExitVerifyMessage(const routing::UpdateExitVerifyMessage& msg, Router* r) { (void)r; if (m_UpdateExitTX && msg.tx_id == m_UpdateExitTX) @@ -657,7 +656,7 @@ namespace llarp::path std::move around. */ bool - Path::SendRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r) + Path::SendRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r) { std::array tmp; llarp_buffer_t buf(tmp); @@ -692,15 +691,14 @@ namespace llarp::path } bool - Path::HandlePathTransferMessage( - const routing::PathTransferMessage& /*msg*/, AbstractRouter* /*r*/) + Path::HandlePathTransferMessage(const routing::PathTransferMessage& /*msg*/, Router* /*r*/) { 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, Router* r) { MarkActive(r->Now()); if (m_DropHandler) @@ -709,7 +707,7 @@ namespace llarp::path } bool - Path::HandlePathConfirmMessage(AbstractRouter* r) + Path::HandlePathConfirmMessage(Router* r) { LogDebug("Path Build Confirm, path: ", ShortName()); const auto now = llarp::time_now_ms(); @@ -718,7 +716,7 @@ namespace llarp::path // finish initializing introduction intro.expiry = buildStarted + hops[0].lifetime; - r->routerProfiling().MarkPathSuccess(this); + r->router_profiling().MarkPathSuccess(this); // persist session with upstream router until the path is done r->PersistSessionUntil(Upstream(), intro.expiry); @@ -730,7 +728,7 @@ namespace llarp::path } bool - Path::HandlePathConfirmMessage(const routing::PathConfirmMessage& /*msg*/, AbstractRouter* r) + Path::HandlePathConfirmMessage(const routing::PathConfirmMessage& /*msg*/, Router* r) { return HandlePathConfirmMessage(r); } @@ -761,7 +759,7 @@ namespace llarp::path constexpr auto MaxLatencySamples = 8; bool - Path::HandlePathLatencyMessage(const routing::PathLatencyMessage&, AbstractRouter* r) + Path::HandlePathLatencyMessage(const routing::PathLatencyMessage&, Router* r) { const auto now = r->Now(); MarkActive(now); @@ -785,7 +783,7 @@ namespace llarp::path /// this is the Client's side of handling a DHT message. it's handled /// in-place. bool - Path::HandleDHTMessage(const dht::AbstractDHTMessage& msg, AbstractRouter* r) + Path::HandleDHTMessage(const dht::AbstractDHTMessage& msg, Router* r) { MarkActive(r->Now()); routing::PathDHTMessage reply; @@ -797,7 +795,7 @@ namespace llarp::path } bool - Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* /*r*/) + Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, Router* /*r*/) { /// allows exits to close from their end if (SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) @@ -817,7 +815,7 @@ namespace llarp::path } bool - Path::SendExitRequest(const routing::ObtainExitMessage& msg, AbstractRouter* r) + Path::SendExitRequest(const routing::ObtainExitMessage& msg, Router* r) { LogInfo(Name(), " sending exit request to ", Endpoint()); m_ExitObtainTX = msg.tx_id; @@ -825,7 +823,7 @@ namespace llarp::path } bool - Path::SendExitClose(const routing::CloseExitMessage& msg, AbstractRouter* r) + Path::SendExitClose(const routing::CloseExitMessage& msg, Router* r) { LogInfo(Name(), " closing exit to ", Endpoint()); // mark as not exit anymore @@ -834,7 +832,7 @@ namespace llarp::path } bool - Path::HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) + Path::HandleObtainExitMessage(const routing::ObtainExitMessage& msg, Router* r) { (void)msg; (void)r; @@ -843,7 +841,7 @@ namespace llarp::path } bool - Path::HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) + Path::HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, Router* r) { (void)msg; (void)r; @@ -852,7 +850,7 @@ namespace llarp::path } bool - Path::HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) + Path::HandleRejectExitMessage(const routing::RejectExitMessage& msg, Router* r) { if (m_ExitObtainTX && msg.tx_id == m_ExitObtainTX) { @@ -870,7 +868,7 @@ namespace llarp::path } bool - Path::HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) + Path::HandleGrantExitMessage(const routing::GrantExitMessage& msg, Router* r) { if (m_ExitObtainTX && msg.tx_id == m_ExitObtainTX) { @@ -901,7 +899,7 @@ namespace llarp::path } bool - Path::HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, AbstractRouter* r) + Path::HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, Router* r) { // check if we can handle exit data if (!SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) diff --git a/llarp/path/path.hpp b/llarp/path/path.hpp index 82e2fafcb..91998f74a 100644 --- a/llarp/path/path.hpp +++ b/llarp/path/path.hpp @@ -27,7 +27,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; struct LR_CommitMessage; namespace path @@ -203,11 +203,11 @@ namespace llarp // handle data in upstream direction bool - HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) override; + HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router*) override; // handle data in downstream direction bool - HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) override; + HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, Router*) override; const std::string& ShortName() const; @@ -222,8 +222,7 @@ namespace llarp } bool - HandleLRSM( - uint64_t status, std::array& frames, AbstractRouter* r) override; + HandleLRSM(uint64_t status, std::array& frames, Router* r) override; void SetBuildResultHook(BuildResultHookFunc func); @@ -288,47 +287,45 @@ namespace llarp Rebuild(); void - Tick(llarp_time_t now, AbstractRouter* r); + Tick(llarp_time_t now, Router* r); bool - SendRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r) override; + SendRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r) override; bool - HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) override; + HandleObtainExitMessage(const routing::ObtainExitMessage& msg, Router* r) override; bool HandleUpdateExitVerifyMessage( - const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) override; + const routing::UpdateExitVerifyMessage& msg, Router* r) override; bool - HandleTransferTrafficMessage( - const routing::TransferTrafficMessage& msg, AbstractRouter* r) override; + HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, Router* r) override; bool - HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) override; + HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, Router* r) override; bool - HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* r) override; + HandleCloseExitMessage(const routing::CloseExitMessage& msg, Router* r) override; bool - HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) override; + HandleGrantExitMessage(const routing::GrantExitMessage& msg, Router* r) override; bool - HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) override; + HandleRejectExitMessage(const routing::RejectExitMessage& msg, Router* r) override; bool - HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, AbstractRouter* r) override; + HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, Router* r) override; bool - HandlePathConfirmMessage(AbstractRouter* r); + HandlePathConfirmMessage(Router* r); bool - HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, AbstractRouter* r) override; + HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, Router* r) override; bool - HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, AbstractRouter* r) override; + HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, Router* r) override; bool - HandlePathTransferMessage( - const routing::PathTransferMessage& msg, AbstractRouter* r) override; + HandlePathTransferMessage(const routing::PathTransferMessage& msg, Router* r) override; bool HandleHiddenServiceFrame(const service::ProtocolFrameMessage& frame) override; @@ -337,10 +334,10 @@ namespace llarp HandleGotIntroMessage(const dht::GotIntroMessage& msg); bool - HandleDHTMessage(const dht::AbstractDHTMessage& msg, AbstractRouter* r) override; + HandleDHTMessage(const dht::AbstractDHTMessage& msg, Router* r) override; bool - HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r); + HandleRoutingMessage(const llarp_buffer_t& buf, Router* r); bool IsReady() const; @@ -375,33 +372,33 @@ namespace llarp } bool - SendExitRequest(const routing::ObtainExitMessage& msg, AbstractRouter* r); + SendExitRequest(const routing::ObtainExitMessage& msg, Router* r); bool - SendExitClose(const routing::CloseExitMessage& msg, AbstractRouter* r); + SendExitClose(const routing::CloseExitMessage& msg, Router* r); void - FlushUpstream(AbstractRouter* r) override; + FlushUpstream(Router* r) override; void - FlushDownstream(AbstractRouter* r) override; + FlushDownstream(Router* r) override; protected: void - UpstreamWork(TrafficQueue_t queue, AbstractRouter* r) override; + UpstreamWork(TrafficQueue_t queue, Router* r) override; void - DownstreamWork(TrafficQueue_t queue, AbstractRouter* r) override; + DownstreamWork(TrafficQueue_t queue, Router* r) override; void - HandleAllUpstream(std::vector msgs, AbstractRouter* r) override; + HandleAllUpstream(std::vector msgs, Router* r) override; void - HandleAllDownstream(std::vector msgs, AbstractRouter* r) override; + HandleAllDownstream(std::vector msgs, Router* r) override; private: bool - SendLatencyMessage(AbstractRouter* r); + SendLatencyMessage(Router* r); /// call obtained exit hooks bool diff --git a/llarp/path/path_context.cpp b/llarp/path/path_context.cpp index 82bb0e63d..92ccace92 100644 --- a/llarp/path/path_context.cpp +++ b/llarp/path/path_context.cpp @@ -1,17 +1,16 @@ #include "path.hpp" #include "path_context.hpp" -#include #include -#include +#include #include namespace llarp::path { static constexpr auto DefaultPathBuildLimit = 500ms; - PathContext::PathContext(AbstractRouter* router) - : m_Router(router), m_AllowTransit(false), m_PathLimits(DefaultPathBuildLimit) + PathContext::PathContext(Router* router) + : router(router), m_AllowTransit(false), m_PathLimits(DefaultPathBuildLimit) {} void @@ -44,19 +43,19 @@ namespace llarp::path const EventLoop_ptr& PathContext::loop() { - return m_Router->loop(); + return router->loop(); } const SecretKey& PathContext::EncryptionSecretKey() { - return m_Router->encryption(); + return router->encryption(); } bool PathContext::HopIsUs(const RouterID& k) const { - return std::equal(m_Router->pubkey(), m_Router->pubkey() + PUBKEYSIZE, k.begin()); + return std::equal(router->pubkey(), router->pubkey() + PUBKEYSIZE, k.begin()); } PathContext::EndpointPathPtrSet @@ -86,7 +85,7 @@ namespace llarp::path LogDebug("forwarding LRCM to ", nextHop); - return m_Router->SendToOrQueue(nextHop, msg, handler); + return router->SendToOrQueue(nextHop, msg, handler); } template < @@ -274,13 +273,7 @@ namespace llarp::path const byte_t* PathContext::OurRouterID() const { - return m_Router->pubkey(); - } - - AbstractRouter* - PathContext::Router() - { - return m_Router; + return router->pubkey(); } TransitHop_ptr @@ -303,15 +296,15 @@ namespace llarp::path void PathContext::PumpUpstream() { - m_TransitPaths.ForEach([&](auto& ptr) { ptr->FlushUpstream(m_Router); }); - m_OurPaths.ForEach([&](auto& ptr) { ptr->FlushUpstream(m_Router); }); + m_TransitPaths.ForEach([&](auto& ptr) { ptr->FlushUpstream(router); }); + m_OurPaths.ForEach([&](auto& ptr) { ptr->FlushUpstream(router); }); } void PathContext::PumpDownstream() { - m_TransitPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(m_Router); }); - m_OurPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(m_Router); }); + m_TransitPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(router); }); + m_OurPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(router); }); } uint64_t @@ -357,7 +350,7 @@ namespace llarp::path { if (itr->second->Expired(now)) { - m_Router->outboundMessageHandler().RemovePath(itr->first); + router->outboundMessageHandler().RemovePath(itr->first); itr = map.erase(itr); } else diff --git a/llarp/path/path_context.hpp b/llarp/path/path_context.hpp index 621e4629e..359ebddc1 100644 --- a/llarp/path/path_context.hpp +++ b/llarp/path/path_context.hpp @@ -17,7 +17,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; struct LR_CommitMessage; struct RelayDownstreamMessage; struct RelayUpstreamMessage; @@ -32,7 +32,7 @@ namespace llarp struct PathContext { - explicit PathContext(AbstractRouter* router); + explicit PathContext(Router* router); /// called from router tick function void @@ -160,9 +160,6 @@ namespace llarp const EventLoop_ptr& loop(); - AbstractRouter* - Router(); - const SecretKey& EncryptionSecretKey(); @@ -178,7 +175,7 @@ namespace llarp CurrentOwnedPaths(path::PathStatus status = path::PathStatus::ePathEstablished); private: - AbstractRouter* m_Router; + Router* router; SyncTransitMap_t m_TransitPaths; SyncOwnedPathsMap_t m_OurPaths; bool m_AllowTransit; diff --git a/llarp/path/pathbuilder.cpp b/llarp/path/pathbuilder.cpp index 72c5000ba..eb58efc16 100644 --- a/llarp/path/pathbuilder.cpp +++ b/llarp/path/pathbuilder.cpp @@ -6,7 +6,7 @@ #include #include #include -#include +#include #include #include #include @@ -33,7 +33,7 @@ namespace llarp Handler result; size_t idx = 0; - AbstractRouter* router = nullptr; + Router* router = nullptr; WorkerFunc_t work; EventLoop_ptr loop; LR_CommitMessage LRCM; @@ -139,9 +139,9 @@ namespace llarp if (ctx->pathset->IsStopped()) return; - ctx->router->NotifyRouterEvent(ctx->router->pubkey(), ctx->path); + ctx->router->notify_router_event(ctx->router->pubkey(), ctx->path); - ctx->router->pathContext().AddOwnPath(ctx->pathset, ctx->path); + ctx->router->path_context().AddOwnPath(ctx->pathset, ctx->path); ctx->pathset->PathBuildStarted(ctx->path); const RouterID remote = ctx->path->Upstream(); @@ -184,7 +184,7 @@ namespace llarp return m_EdgeLimiter.Contains(router); } - Builder::Builder(AbstractRouter* p_router, size_t pathNum, size_t hops) + Builder::Builder(Router* p_router, size_t pathNum, size_t hops) : path::PathSet{pathNum}, _run{true}, m_router{p_router}, numHops{hops} { CryptoManager::instance()->encryption_keygen(enckey); @@ -202,7 +202,7 @@ namespace llarp { PathSet::Tick(now); now = llarp::time_now_ms(); - m_router->pathBuildLimiter().Decay(now); + m_router->pathbuild_limiter().Decay(now); ExpirePaths(now, m_router); if (ShouldBuildMore(now)) @@ -252,7 +252,7 @@ namespace llarp if (BuildCooldownHit(rc.pubkey)) return; - if (m_router->routerProfiling().IsBadForPath(rc.pubkey)) + if (m_router->router_profiling().IsBadForPath(rc.pubkey)) return; found = rc; @@ -266,9 +266,9 @@ namespace llarp Builder::GetHopsForBuild() { auto filter = [r = m_router](const auto& rc) -> bool { - return not r->routerProfiling().IsBadForPath(rc.pubkey, 1); + return not r->router_profiling().IsBadForPath(rc.pubkey, 1); }; - if (const auto maybe = m_router->nodedb()->GetRandom(filter)) + if (const auto maybe = m_router->node_db()->GetRandom(filter)) { return GetHopsAlignedToForBuild(maybe->pubkey); } @@ -309,7 +309,7 @@ namespace llarp bool Builder::BuildCooldownHit(RouterID edge) const { - return m_router->pathBuildLimiter().Limited(edge); + return m_router->pathbuild_limiter().Limited(edge); } bool @@ -344,7 +344,7 @@ namespace llarp std::optional> Builder::GetHopsAlignedToForBuild(RouterID endpoint, const std::set& exclude) { - const auto pathConfig = m_router->GetConfig()->paths; + const auto pathConfig = m_router->config()->paths; std::vector hops; { @@ -358,7 +358,7 @@ namespace llarp }; RouterContact endpointRC; - if (const auto maybe = m_router->nodedb()->Get(endpoint)) + if (const auto maybe = m_router->node_db()->Get(endpoint)) { endpointRC = *maybe; } @@ -382,7 +382,7 @@ namespace llarp hopsSet.insert(endpointRC); hopsSet.insert(hops.begin(), hops.end()); - if (r->routerProfiling().IsBadForPath(rc.pubkey, 1)) + if (r->router_profiling().IsBadForPath(rc.pubkey, 1)) return false; for (const auto& hop : hopsSet) { @@ -398,7 +398,7 @@ namespace llarp return rc.pubkey != endpointRC.pubkey; }; - if (const auto maybe = m_router->nodedb()->GetRandom(filter)) + if (const auto maybe = m_router->node_db()->GetRandom(filter)) hops.emplace_back(*maybe); else return std::nullopt; @@ -432,7 +432,7 @@ namespace llarp return; lastBuild = Now(); const RouterID edge{hops[0].pubkey}; - if (not m_router->pathBuildLimiter().Attempt(edge)) + if (not m_router->pathbuild_limiter().Attempt(edge)) { LogWarn(Name(), " building too fast to edge router ", edge); return; @@ -451,7 +451,7 @@ namespace llarp ctx->AsyncGenerateKeys( path, m_router->loop(), - [r = m_router](auto func) { r->QueueWork(std::move(func)); }, + [r = m_router](auto func) { r->queue_work(std::move(func)); }, &PathBuilderKeysGenerated); } @@ -459,7 +459,7 @@ namespace llarp Builder::HandlePathBuilt(Path_ptr p) { buildIntervalLimit = PATH_BUILD_RATE; - m_router->routerProfiling().MarkPathSuccess(p.get()); + m_router->router_profiling().MarkPathSuccess(p.get()); LogInfo(p->Name(), " built latency=", ToString(p->intro.latency)); m_BuildStats.success++; @@ -484,7 +484,7 @@ namespace llarp void Builder::HandlePathBuildTimeout(Path_ptr p) { - m_router->routerProfiling().MarkPathTimeout(p.get()); + m_router->router_profiling().MarkPathTimeout(p.get()); PathSet::HandlePathBuildTimeout(p); DoPathBuildBackoff(); for (const auto& hop : p->hops) @@ -493,20 +493,20 @@ namespace llarp // look up router and see if it's still on the network m_router->loop()->call_soon([router, r = m_router]() { LogInfo("looking up ", router, " because of path build timeout"); - r->rcLookupHandler().GetRC( + r->rc_lookup_handler().get_rc( router, [r](const auto& router, const auto* rc, auto result) { if (result == RCRequestResult::Success && rc != nullptr) { LogInfo("refreshed rc for ", router); - r->nodedb()->PutIfNewer(*rc); + r->node_db()->PutIfNewer(*rc); } else { // remove all connections to this router as it's probably not registered anymore LogWarn("removing router ", router, " because of path build timeout"); - r->linkManager().deregister_peer(router); - r->nodedb()->Remove(router); + r->link_manager().deregister_peer(router); + r->node_db()->Remove(router); } }, true); diff --git a/llarp/path/pathbuilder.hpp b/llarp/path/pathbuilder.hpp index a01198974..f9cf2e3d2 100644 --- a/llarp/path/pathbuilder.hpp +++ b/llarp/path/pathbuilder.hpp @@ -57,14 +57,14 @@ namespace llarp DoPathBuildBackoff(); public: - AbstractRouter* const m_router; + Router* const m_router; SecretKey enckey; size_t numHops; llarp_time_t lastBuild = 0s; llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; /// construct - Builder(AbstractRouter* p_router, size_t numDesiredPaths, size_t numHops); + Builder(Router* p_router, size_t numDesiredPaths, size_t numHops); virtual ~Builder() = default; diff --git a/llarp/path/pathset.cpp b/llarp/path/pathset.cpp index 1f15c3fd7..f05a372f7 100644 --- a/llarp/path/pathset.cpp +++ b/llarp/path/pathset.cpp @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include @@ -62,7 +62,7 @@ namespace llarp::path } void - PathSet::TickPaths(AbstractRouter* r) + PathSet::TickPaths(Router* r) { const auto now = llarp::time_now_ms(); Lock_t l{m_PathsMutex}; @@ -92,7 +92,7 @@ namespace llarp::path } void - PathSet::ExpirePaths(llarp_time_t now, AbstractRouter* router) + PathSet::ExpirePaths(llarp_time_t now, Router* router) { Lock_t l(m_PathsMutex); if (m_Paths.size() == 0) @@ -452,13 +452,13 @@ namespace llarp::path } void - PathSet::UpstreamFlush(AbstractRouter* r) + PathSet::UpstreamFlush(Router* r) { ForEachPath([r](const Path_ptr& p) { p->FlushUpstream(r); }); } void - PathSet::DownstreamFlush(AbstractRouter* r) + PathSet::DownstreamFlush(Router* r) { ForEachPath([r](const Path_ptr& p) { p->FlushDownstream(r); }); } diff --git a/llarp/path/pathset.hpp b/llarp/path/pathset.hpp index cbaeb52f2..581c38dfa 100644 --- a/llarp/path/pathset.hpp +++ b/llarp/path/pathset.hpp @@ -156,7 +156,7 @@ namespace llarp GetByUpstream(RouterID remote, PathID_t rxid) const; void - ExpirePaths(llarp_time_t now, AbstractRouter* router); + ExpirePaths(llarp_time_t now, Router* router); /// get the number of paths in this status size_t @@ -268,7 +268,7 @@ namespace llarp std::function filter) const; virtual bool - PublishIntroSet(const service::EncryptedIntroSet&, AbstractRouter*) + PublishIntroSet(const service::EncryptedIntroSet&, Router*) { return false; } @@ -299,10 +299,10 @@ namespace llarp } void - UpstreamFlush(AbstractRouter* r); + UpstreamFlush(Router* r); void - DownstreamFlush(AbstractRouter* r); + DownstreamFlush(Router* r); size_t numDesiredPaths; @@ -310,7 +310,7 @@ namespace llarp BuildStats m_BuildStats; void - TickPaths(AbstractRouter* r); + TickPaths(Router* r); using Mtx_t = util::NullMutex; using Lock_t = util::NullLock; diff --git a/llarp/path/transit_hop.cpp b/llarp/path/transit_hop.cpp index c99020023..8b81cc9c6 100644 --- a/llarp/path/transit_hop.cpp +++ b/llarp/path/transit_hop.cpp @@ -9,7 +9,7 @@ #include #include "path_context.hpp" #include "transit_hop.hpp" -#include +#include #include #include #include @@ -50,7 +50,7 @@ namespace llarp::path } bool - TransitHop::HandleLRSM(uint64_t status, std::array& frames, AbstractRouter* r) + TransitHop::HandleLRSM(uint64_t status, std::array& frames, Router* r) { auto msg = std::make_shared(frames); msg->status = status; @@ -85,7 +85,7 @@ namespace llarp::path std::move around. */ bool - TransitHop::SendRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r) + TransitHop::SendRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r) { if (!IsEndpoint(r->pubkey())) return false; @@ -113,7 +113,7 @@ namespace llarp::path } void - TransitHop::DownstreamWork(TrafficQueue_t msgs, AbstractRouter* r) + TransitHop::DownstreamWork(TrafficQueue_t msgs, Router* r) { auto flushIt = [self = shared_from_this(), r]() { std::vector msgs; @@ -149,7 +149,7 @@ namespace llarp::path } void - TransitHop::UpstreamWork(TrafficQueue_t msgs, AbstractRouter* r) + TransitHop::UpstreamWork(TrafficQueue_t msgs, Router* r) { for (auto& ev : msgs) { @@ -175,7 +175,7 @@ namespace llarp::path } void - TransitHop::HandleAllUpstream(std::vector msgs, AbstractRouter* r) + TransitHop::HandleAllUpstream(std::vector msgs, Router* r) { if (IsEndpoint(r->pubkey())) { @@ -213,7 +213,7 @@ namespace llarp::path } void - TransitHop::HandleAllDownstream(std::vector msgs, AbstractRouter* r) + TransitHop::HandleAllDownstream(std::vector msgs, Router* r) { for (const auto& msg : msgs) { @@ -230,38 +230,37 @@ namespace llarp::path } void - TransitHop::FlushUpstream(AbstractRouter* r) + TransitHop::FlushUpstream(Router* r) { if (not m_UpstreamQueue.empty()) { - r->QueueWork([self = shared_from_this(), - data = std::exchange(m_UpstreamQueue, {}), - r]() mutable { self->UpstreamWork(std::move(data), r); }); + r->queue_work([self = shared_from_this(), + data = std::exchange(m_UpstreamQueue, {}), + r]() mutable { self->UpstreamWork(std::move(data), r); }); } } void - TransitHop::FlushDownstream(AbstractRouter* r) + TransitHop::FlushDownstream(Router* r) { if (not m_DownstreamQueue.empty()) { - r->QueueWork([self = shared_from_this(), - data = std::exchange(m_DownstreamQueue, {}), - r]() mutable { self->DownstreamWork(std::move(data), r); }); + r->queue_work([self = shared_from_this(), + data = std::exchange(m_DownstreamQueue, {}), + r]() mutable { self->DownstreamWork(std::move(data), r); }); } } /// 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::AbstractDHTMessage& msg, AbstractRouter* r) + TransitHop::HandleDHTMessage(const llarp::dht::AbstractDHTMessage& msg, Router* r) { return r->dht()->RelayRequestForPath(info.rxID, msg); } bool - TransitHop::HandlePathLatencyMessage( - const llarp::routing::PathLatencyMessage& msg, AbstractRouter* r) + TransitHop::HandlePathLatencyMessage(const llarp::routing::PathLatencyMessage& msg, Router* r) { llarp::routing::PathLatencyMessage reply; reply.latency = msg.sent_time; @@ -271,8 +270,7 @@ namespace llarp::path bool TransitHop::HandlePathConfirmMessage( - [[maybe_unused]] const llarp::routing::PathConfirmMessage& msg, - [[maybe_unused]] AbstractRouter* r) + [[maybe_unused]] const llarp::routing::PathConfirmMessage& msg, [[maybe_unused]] Router* r) { llarp::LogWarn("unwarranted path confirm message on ", info); return false; @@ -280,16 +278,14 @@ namespace llarp::path bool TransitHop::HandleDataDiscardMessage( - [[maybe_unused]] const llarp::routing::DataDiscardMessage& msg, - [[maybe_unused]] AbstractRouter* r) + [[maybe_unused]] const llarp::routing::DataDiscardMessage& msg, [[maybe_unused]] Router* r) { llarp::LogWarn("unwarranted path data discard message on ", info); return false; } bool - TransitHop::HandleObtainExitMessage( - const llarp::routing::ObtainExitMessage& msg, AbstractRouter* r) + TransitHop::HandleObtainExitMessage(const llarp::routing::ObtainExitMessage& msg, Router* r) { if (msg.Verify() && r->exitContext().ObtainNewExit(msg.pubkey, info.rxID, msg.flag != 0)) { @@ -317,7 +313,7 @@ namespace llarp::path } bool - TransitHop::HandleCloseExitMessage(const llarp::routing::CloseExitMessage& msg, AbstractRouter* r) + TransitHop::HandleCloseExitMessage(const llarp::routing::CloseExitMessage& msg, Router* r) { const llarp::routing::DataDiscardMessage discard(info.rxID, msg.sequence_number); auto ep = r->exitContext().FindEndpointForPath(info.rxID); @@ -340,7 +336,7 @@ namespace llarp::path bool TransitHop::HandleUpdateExitVerifyMessage( - const llarp::routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) + const llarp::routing::UpdateExitVerifyMessage& msg, Router* r) { (void)msg; (void)r; @@ -349,8 +345,7 @@ namespace llarp::path } bool - TransitHop::HandleUpdateExitMessage( - const llarp::routing::UpdateExitMessage& msg, AbstractRouter* r) + TransitHop::HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage& msg, Router* r) { auto ep = r->exitContext().FindEndpointForPath(msg.path_id); if (ep) @@ -372,8 +367,7 @@ namespace llarp::path } bool - TransitHop::HandleRejectExitMessage( - const llarp::routing::RejectExitMessage& msg, AbstractRouter* r) + TransitHop::HandleRejectExitMessage(const llarp::routing::RejectExitMessage& msg, Router* r) { (void)msg; (void)r; @@ -382,7 +376,7 @@ namespace llarp::path } bool - TransitHop::HandleGrantExitMessage(const llarp::routing::GrantExitMessage& msg, AbstractRouter* r) + TransitHop::HandleGrantExitMessage(const llarp::routing::GrantExitMessage& msg, Router* r) { (void)msg; (void)r; @@ -392,7 +386,7 @@ namespace llarp::path bool TransitHop::HandleTransferTrafficMessage( - const llarp::routing::TransferTrafficMessage& msg, AbstractRouter* r) + const llarp::routing::TransferTrafficMessage& msg, Router* r) { auto endpoint = r->exitContext().FindEndpointForPath(info.rxID); if (endpoint) @@ -418,10 +412,9 @@ namespace llarp::path } bool - TransitHop::HandlePathTransferMessage( - const llarp::routing::PathTransferMessage& msg, AbstractRouter* r) + TransitHop::HandlePathTransferMessage(const llarp::routing::PathTransferMessage& msg, Router* r) { - auto path = r->pathContext().GetPathForTransfer(msg.path_id); + auto path = r->path_context().GetPathForTransfer(msg.path_id); llarp::routing::DataDiscardMessage discarded{msg.path_id, msg.sequence_number}; if (path == nullptr || msg.protocol_frame_msg.path_id != info.txID) { @@ -457,7 +450,7 @@ namespace llarp::path } void - TransitHop::QueueDestroySelf(AbstractRouter* r) + TransitHop::QueueDestroySelf(Router* r) { r->loop()->call([self = shared_from_this()] { self->SetSelfDestruct(); }); } diff --git a/llarp/path/transit_hop.hpp b/llarp/path/transit_hop.hpp index a52374734..4752eca76 100644 --- a/llarp/path/transit_hop.hpp +++ b/llarp/path/transit_hop.hpp @@ -100,8 +100,7 @@ namespace llarp } bool - HandleLRSM( - uint64_t status, std::array& frames, AbstractRouter* r) override; + HandleLRSM(uint64_t status, std::array& frames, Router* r) override; std::string ToString() const; @@ -117,47 +116,45 @@ namespace llarp // send routing message when end of path bool - SendRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r) override; + SendRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r) override; // handle routing message when end of path bool - HandleRoutingMessage(const routing::AbstractRoutingMessage& msg, AbstractRouter* r); + HandleRoutingMessage(const routing::AbstractRoutingMessage& msg, Router* r); bool - HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, AbstractRouter* r) override; + HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, Router* r) override; bool - HandlePathConfirmMessage(AbstractRouter* r); + HandlePathConfirmMessage(Router* r); bool - HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, AbstractRouter* r) override; + HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, Router* r) override; bool - HandlePathTransferMessage( - const routing::PathTransferMessage& msg, AbstractRouter* r) override; + HandlePathTransferMessage(const routing::PathTransferMessage& msg, Router* r) override; bool - HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, AbstractRouter* r) override; + HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, Router* r) override; bool - HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) override; + HandleObtainExitMessage(const routing::ObtainExitMessage& msg, Router* r) override; bool HandleUpdateExitVerifyMessage( - const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) override; + const routing::UpdateExitVerifyMessage& msg, Router* r) override; bool - HandleTransferTrafficMessage( - const routing::TransferTrafficMessage& msg, AbstractRouter* r) override; + HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, Router* r) override; bool - HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) override; + HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, Router* r) override; bool - HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) override; + HandleGrantExitMessage(const routing::GrantExitMessage& msg, Router* r) override; bool - HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) override; + HandleRejectExitMessage(const routing::RejectExitMessage& msg, Router* r) override; bool - HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* r) override; + HandleCloseExitMessage(const routing::CloseExitMessage& msg, Router* r) override; bool HandleHiddenServiceFrame(const service::ProtocolFrameMessage& /*frame*/) override @@ -171,29 +168,29 @@ namespace llarp HandleGotIntroMessage(const dht::GotIntroMessage& msg); bool - HandleDHTMessage(const dht::AbstractDHTMessage& msg, AbstractRouter* r) override; + HandleDHTMessage(const dht::AbstractDHTMessage& msg, Router* r) override; void - FlushUpstream(AbstractRouter* r) override; + FlushUpstream(Router* r) override; void - FlushDownstream(AbstractRouter* r) override; + FlushDownstream(Router* r) override; void - QueueDestroySelf(AbstractRouter* r); + QueueDestroySelf(Router* r); protected: void - UpstreamWork(TrafficQueue_t queue, AbstractRouter* r) override; + UpstreamWork(TrafficQueue_t queue, Router* r) override; void - DownstreamWork(TrafficQueue_t queue, AbstractRouter* r) override; + DownstreamWork(TrafficQueue_t queue, Router* r) override; void - HandleAllUpstream(std::vector msgs, AbstractRouter* r) override; + HandleAllUpstream(std::vector msgs, Router* r) override; void - HandleAllDownstream(std::vector msgs, AbstractRouter* r) override; + HandleAllDownstream(std::vector msgs, Router* r) override; private: void diff --git a/llarp/router/abstractrouter.hpp b/llarp/router/abstractrouter.hpp deleted file mode 100644 index 109e265fe..000000000 --- a/llarp/router/abstractrouter.hpp +++ /dev/null @@ -1,397 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include "outbound_message_handler.hpp" -#include -#include -#include -#include -#include -#include -#include - -#include - -#ifdef LOKINET_HIVE -#include -#endif - -struct llarp_buffer_t; -struct llarp_dht_context; - -namespace oxenmq -{ - class OxenMQ; -} - -namespace llarp -{ - class NodeDB; - struct Config; - struct RouterID; - struct AbstractLinkMessage; - struct AbstractLinkSession; - struct PathID_t; - struct Profiling; - struct SecretKey; - struct Signature; - struct OutboundMessageHandler; - struct LinkManager; - struct RCLookupHandler; - struct RoutePoker; - - namespace dht - { - struct AbstractDHTMessageHandler; - } - - namespace dns - { - class I_SystemSettings; - } - - namespace net - { - class Platform; - } - - namespace exit - { - struct Context; - } - - namespace rpc - { - struct LokidRpcClient; - } - - namespace path - { - struct PathContext; - } - - namespace routing - { - struct AbstractRoutingMessageHandler; - } - - namespace service - { - struct Context; - } - - namespace thread - { - class ThreadPool; - } - - namespace vpn - { - class Platform; - } - - using LMQ_ptr = std::shared_ptr; - - struct AbstractRouter : public std::enable_shared_from_this - { -#ifdef LOKINET_HIVE - tooling::RouterHive* hive = nullptr; -#endif - - virtual ~AbstractRouter() = default; - - virtual bool - HandleRecvLinkMessageBuffer(AbstractLinkSession* from, const llarp_buffer_t& msg) = 0; - - virtual const net::Platform& - Net() const = 0; - - virtual const LMQ_ptr& - lmq() const = 0; - - virtual vpn::Platform* - GetVPNPlatform() const = 0; - - virtual const std::shared_ptr& - RpcClient() const = 0; - - virtual std::shared_ptr - dht() const = 0; - - virtual const std::shared_ptr& - nodedb() const = 0; - - virtual const path::PathContext& - pathContext() const = 0; - - virtual path::PathContext& - pathContext() = 0; - - virtual const RouterContact& - rc() const = 0; - - /// modify our rc - /// modify returns nullopt if unmodified otherwise it returns the new rc to be sigend and - /// published out - virtual void - ModifyOurRC(std::function(RouterContact)> modify) = 0; - - virtual exit::Context& - exitContext() = 0; - - virtual const std::shared_ptr& - keyManager() const = 0; - - virtual const SecretKey& - identity() const = 0; - - virtual const SecretKey& - encryption() const = 0; - - virtual Profiling& - routerProfiling() = 0; - - virtual const EventLoop_ptr& - loop() const = 0; - - /// call function in crypto worker - virtual void QueueWork(std::function) = 0; - - /// call function in disk io thread - virtual void QueueDiskIO(std::function) = 0; - - virtual std::shared_ptr - GetConfig() const - { - return nullptr; - } - - virtual service::Context& - hiddenServiceContext() = 0; - - virtual const service::Context& - hiddenServiceContext() const = 0; - - virtual OutboundMessageHandler& - outboundMessageHandler() = 0; - - virtual LinkManager& - linkManager() = 0; - - virtual const std::shared_ptr& - routePoker() const = 0; - - virtual RCLookupHandler& - rcLookupHandler() = 0; - - virtual std::shared_ptr - peerDb() = 0; - - virtual bool - Sign(Signature& sig, const llarp_buffer_t& buf) const = 0; - - virtual bool - Configure(std::shared_ptr conf, bool isSNode, std::shared_ptr nodedb) = 0; - - virtual bool - IsServiceNode() const = 0; - - /// Called to determine if we're in a bad state (which gets reported to our oxend) that should - /// prevent uptime proofs from going out to the network (so that the error state gets noticed). - /// Currently this means we require a decent number of peers whenever we are fully staked - /// (active or decommed). - virtual std::optional - OxendErrorState() const = 0; - - virtual bool - StartRpcServer() = 0; - - virtual bool - Run() = 0; - - virtual bool - IsRunning() const = 0; - - virtual bool - LooksAlive() const = 0; - - /// stop running the router logic gracefully - virtual void - Stop() = 0; - - /// indicate we are about to sleep for a while - virtual void - Freeze() = 0; - - /// thaw from long sleep or network changed event - virtual void - Thaw() = 0; - - /// non gracefully stop the router - virtual void - Die() = 0; - - /// Trigger a pump of low level links. Idempotent. - virtual void - TriggerPump() = 0; - - virtual bool - IsBootstrapNode(RouterID r) const = 0; - - virtual const byte_t* - pubkey() const = 0; - - /// get what our real public ip is if we can know it - virtual std::optional> - OurPublicIP() const = 0; - - /// connect to N random routers - virtual void - ConnectToRandomRouters(int N) = 0; - - virtual bool - TryConnectAsync(RouterContact rc, uint16_t tries) = 0; - - /// called by link when a remote session has no more sessions open - virtual void - SessionClosed(RouterID remote) = 0; - - /// returns system clock milliseconds since epoch - virtual llarp_time_t - Now() const = 0; - - /// returns milliseconds since started - virtual llarp_time_t - Uptime() const = 0; - - virtual bool - GetRandomGoodRouter(RouterID& r) = 0; - - virtual bool - SendToOrQueue( - const RouterID& remote, - const AbstractLinkMessage& msg, - SendStatusHandler handler = nullptr) = 0; - - virtual void - PersistSessionUntil(const RouterID& remote, llarp_time_t until) = 0; - - virtual bool - ParseRoutingMessageBuffer( - const llarp_buffer_t& buf, - routing::AbstractRoutingMessageHandler* h, - const PathID_t& rxid) = 0; - - /// count the number of service nodes we are connected to - virtual size_t - NumberOfConnectedRouters() const = 0; - - /// count the number of clients that are connected to us - virtual size_t - NumberOfConnectedClients() const = 0; - - virtual bool - GetRandomConnectedRouter(RouterContact& result) const = 0; - - virtual void - HandleDHTLookupForExplore(RouterID remote, const std::vector& results) = 0; - - virtual void SetDownHook(std::function){}; - - /// lookup router by pubkey - /// if we are a service node this is done direct otherwise it's done via - /// path - virtual void - LookupRouter(RouterID remote, RouterLookupHandler resultHandler) = 0; - - /// check if newRc matches oldRC and update local rc for this remote contact - /// if valid - /// returns true on valid and updated - /// returns false otherwise - virtual bool - CheckRenegotiateValid(RouterContact newRc, RouterContact oldRC) = 0; - - /// set router's service node whitelist - virtual void - SetRouterWhitelist( - const std::vector& whitelist, - const std::vector& greylist, - const std::vector& unfundedlist) = 0; - - virtual std::unordered_set - GetRouterWhitelist() const = 0; - - /// visit each connected link session - virtual void - ForEachPeer( - std::function visit, bool randomize) const = 0; - - virtual bool - SessionToRouterAllowed(const RouterID& router) const = 0; - - virtual bool - PathToRouterAllowed(const RouterID& router) const = 0; - - /// return true if we have an exit as a client - virtual bool - HasClientExit() const - { - return false; - }; - - virtual path::BuildLimiter& - pathBuildLimiter() = 0; - - /// return true if we have at least 1 session to this router in either - /// direction - virtual bool - HasSessionTo(const RouterID& router) const = 0; - - virtual uint32_t - NextPathBuildNumber() = 0; - - virtual std::string - ShortName() const = 0; - - virtual util::StatusObject - ExtractStatus() const = 0; - - virtual util::StatusObject - ExtractSummaryStatus() const = 0; - - /// gossip an rc if required - virtual void - GossipRCIfNeeded(const RouterContact rc) = 0; - - virtual std::string - status_line() = 0; - - /// Templated convenience function to generate a RouterHive event and - /// delegate to non-templated (and overridable) function for handling. - template - void - NotifyRouterEvent([[maybe_unused]] Params&&... args) const - { - // TODO: no-op when appropriate - auto event = std::make_unique(args...); - HandleRouterEvent(std::move(event)); - } - - virtual int - OutboundUDPSocket() const - { - return -1; - } - - protected: - /// Virtual function to handle RouterEvent. HiveRouter overrides this in - /// order to inject the event. The default implementation in Router simply - /// logs it. - virtual void - HandleRouterEvent(tooling::RouterEventPtr event) const = 0; - }; -} // namespace llarp diff --git a/llarp/router/outbound_message_handler.cpp b/llarp/router/outbound_message_handler.cpp index 37a8c214a..5743f9dbc 100644 --- a/llarp/router/outbound_message_handler.cpp +++ b/llarp/router/outbound_message_handler.cpp @@ -24,8 +24,8 @@ namespace llarp const RouterID& remote, const AbstractLinkMessage& msg, SendStatusHandler callback) { // if the destination is invalid, callback with failure and return - if (not _router->linkManager().have_client_connection_to(remote) - and not _router->rcLookupHandler().SessionIsAllowed(remote)) + if (not _router->link_manager().have_client_connection_to(remote) + and not _router->rc_lookup_handler().is_session_allowed(remote)) { DoCallback(callback, SendStatus::InvalidRouter); return true; @@ -47,7 +47,7 @@ namespace llarp std::copy_n(_buf.data(), _buf.size(), ent.message.data()); // if we have a session to the destination, queue the message and return - if (_router->linkManager().have_connection_to(remote)) + if (_router->link_manager().have_connection_to(remote)) { QueueOutboundMessage(std::move(ent)); return true; @@ -126,7 +126,7 @@ namespace llarp } void - OutboundMessageHandler::Init(AbstractRouter* router) + OutboundMessageHandler::Init(Router* router) { _router = router; outboundMessageQueues.emplace(zeroID, MessageQueue()); @@ -170,7 +170,7 @@ namespace llarp void OutboundMessageHandler::QueueSessionCreation(const RouterID& remote) { - _router->linkManager().Connect(remote); + _router->link_manager().Connect(remote); } /** Note: This is where AbstractLinkMessage::bt_encode() is called. Contextually, this is @@ -196,7 +196,7 @@ namespace llarp const llarp_buffer_t buf{ent.message}; m_queueStats.sent++; SendStatusHandler callback = ent.inform; - return _router->linkManager().send_to( + return _router->link_manager().send_to( ent.router, buf, [this, callback](AbstractLinkSession::DeliveryStatus status) { @@ -213,7 +213,7 @@ namespace llarp bool OutboundMessageHandler::SendIfSession(const MessageQueueEntry& ent) { - if (_router->linkManager().have_connection_to(ent.router)) + if (_router->link_manager().have_connection_to(ent.router)) { return Send(ent); } diff --git a/llarp/router/outbound_message_handler.hpp b/llarp/router/outbound_message_handler.hpp index a71c6849f..da688b75a 100644 --- a/llarp/router/outbound_message_handler.hpp +++ b/llarp/router/outbound_message_handler.hpp @@ -25,7 +25,7 @@ namespace llarp Congestion }; - struct AbstractRouter; + struct Router; enum class SessionResult; struct AbstractLinkMessage; struct RouterID; @@ -88,7 +88,7 @@ namespace llarp ExtractStatus() const; void - Init(AbstractRouter* router); + Init(Router* router); private: /* A message that has been queued for sending, but not yet @@ -210,7 +210,7 @@ namespace llarp std::queue roundRobinOrder; - AbstractRouter* _router; + Router* _router; util::ContentionKiller m_Killer; diff --git a/llarp/router/outbound_session_maker.cpp b/llarp/router/outbound_session_maker.cpp index 387ecb0cf..b6812fa35 100644 --- a/llarp/router/outbound_session_maker.cpp +++ b/llarp/router/outbound_session_maker.cpp @@ -1,6 +1,6 @@ #include "outbound_session_maker.hpp" -#include "abstractrouter.hpp" +#include "Router.hpp" #include #include #include @@ -157,7 +157,7 @@ namespace llarp void OutboundSessionMaker::Init( - AbstractRouter* router, + Router* router, LinkManager* linkManager, RCLookupHandler* rcLookup, Profiling* profiler, diff --git a/llarp/router/outbound_session_maker.hpp b/llarp/router/outbound_session_maker.hpp index 7749268da..6f2a87125 100644 --- a/llarp/router/outbound_session_maker.hpp +++ b/llarp/router/outbound_session_maker.hpp @@ -1,5 +1,13 @@ #pragma once +/* + Note: + - this class is marked for destruction + - functionality to be absorbed into llarp/link/link_manager.hpp + - can be subdivided into multiple objects + +*/ + #include "rc_lookup_handler.hpp" #include @@ -80,7 +88,7 @@ namespace llarp void Init( - AbstractRouter* router, + Router* router, LinkManager* linkManager, RCLookupHandler* rcLookup, Profiling* profiler, @@ -125,7 +133,7 @@ namespace llarp std::unordered_map pendingCallbacks GUARDED_BY(_mutex); - AbstractRouter* _router = nullptr; + Router* _router = nullptr; LinkManager* _linkManager = nullptr; RCLookupHandler* _rcLookup = nullptr; Profiling* _profiler = nullptr; diff --git a/llarp/router/rc_gossiper.cpp b/llarp/router/rc_gossiper.cpp index 986e25f4a..701255602 100644 --- a/llarp/router/rc_gossiper.cpp +++ b/llarp/router/rc_gossiper.cpp @@ -12,42 +12,41 @@ namespace llarp // (30 minutes * 2) - 5 minutes static constexpr auto GossipOurRCInterval = (RCGossipFilterDecayInterval * 2) - (5min); - RCGossiper::RCGossiper() - : m_Filter(std::chrono::duration_cast(RCGossipFilterDecayInterval)) + RCGossiper::RCGossiper() : filter(std::chrono::duration_cast(RCGossipFilterDecayInterval)) {} void - RCGossiper::Init(LinkManager* l, const RouterID& ourID, AbstractRouter* router) + RCGossiper::Init(LinkManager* l, const RouterID& ourID, Router* router) { - m_OurRouterID = ourID; - m_LinkManager = l; - m_router = router; + rid = ourID; + link_manager = l; + router = router; } bool RCGossiper::ShouldGossipOurRC(Time_t now) const { - return now >= (m_LastGossipedOurRC + GossipOurRCInterval); + return now >= (last_rc_gossip + GossipOurRCInterval); } bool RCGossiper::IsOurRC(const RouterContact& rc) const { - return rc.pubkey == m_OurRouterID; + return rc.pubkey == rid; } void RCGossiper::Decay(Time_t now) { - m_Filter.Decay(now); + filter.Decay(now); } void RCGossiper::Forget(const RouterID& pk) { - m_Filter.Remove(pk); - if (m_OurRouterID == pk) - m_LastGossipedOurRC = 0s; + filter.Remove(pk); + if (rid == pk) + last_rc_gossip = 0s; } TimePoint_t @@ -61,9 +60,9 @@ namespace llarp std::optional RCGossiper::LastGossipAt() const { - if (m_LastGossipedOurRC == 0s) + if (last_rc_gossip == 0s) return std::nullopt; - return DateClock_t::time_point{m_LastGossipedOurRC}; + return DateClock_t::time_point{last_rc_gossip}; } bool @@ -72,13 +71,13 @@ namespace llarp // only distribute public routers if (not rc.IsPublicRouter()) return false; - if (m_LinkManager == nullptr) + if (link_manager == nullptr) return false; const RouterID pubkey(rc.pubkey); // filter check - if (m_Filter.Contains(pubkey)) + if (filter.Contains(pubkey)) return false; - m_Filter.Insert(pubkey); + filter.Insert(pubkey); const auto now = time_now_ms(); // is this our rc? @@ -91,7 +90,7 @@ namespace llarp return false; } // ya pop it - m_LastGossipedOurRC = now; + last_rc_gossip = now; } // send a GRCM as gossip method diff --git a/llarp/router/rc_gossiper.hpp b/llarp/router/rc_gossiper.hpp index a82840e77..b753bb838 100644 --- a/llarp/router/rc_gossiper.hpp +++ b/llarp/router/rc_gossiper.hpp @@ -3,7 +3,6 @@ #include #include "outbound_message_handler.hpp" #include -#include "abstractrouter.hpp" namespace llarp { @@ -31,7 +30,7 @@ namespace llarp IsOurRC(const RouterContact& rc) const; void - Init(LinkManager*, const RouterID&, AbstractRouter*); + Init(LinkManager*, const RouterID&, Router*); void Forget(const RouterID& router); @@ -43,11 +42,11 @@ namespace llarp LastGossipAt() const; private: - RouterID m_OurRouterID; - Time_t m_LastGossipedOurRC = 0s; - LinkManager* m_LinkManager = nullptr; - util::DecayingHashSet m_Filter; + RouterID rid; + Time_t last_rc_gossip = 0s; + LinkManager* link_manager = nullptr; + util::DecayingHashSet filter; - AbstractRouter* m_router; + Router* router; }; } // namespace llarp diff --git a/llarp/router/rc_lookup_handler.cpp b/llarp/router/rc_lookup_handler.cpp index f55d50e82..86305248f 100644 --- a/llarp/router/rc_lookup_handler.cpp +++ b/llarp/router/rc_lookup_handler.cpp @@ -2,7 +2,6 @@ #include "rc_lookup_handler.hpp" #include -#include #include #include #include @@ -10,7 +9,7 @@ #include #include #include -#include "abstractrouter.hpp" +#include "router.hpp" #include #include @@ -19,17 +18,17 @@ namespace llarp { void - RCLookupHandler::AddValidRouter(const RouterID& router) + RCLookupHandler::add_valid_router(const RouterID& router) { util::Lock l(_mutex); - whitelistRouters.insert(router); + router_whitelist.insert(router); } void - RCLookupHandler::RemoveValidRouter(const RouterID& router) + RCLookupHandler::remove_valid_router(const RouterID& router) { util::Lock l(_mutex); - whitelistRouters.erase(router); + router_whitelist.erase(router); } static void @@ -40,7 +39,7 @@ namespace llarp } void - RCLookupHandler::SetRouterWhitelist( + RCLookupHandler::set_router_whitelist( const std::vector& whitelist, const std::vector& greylist, const std::vector& greenlist) @@ -49,34 +48,34 @@ namespace llarp return; util::Lock l(_mutex); - loadColourList(whitelistRouters, whitelist); - loadColourList(greylistRouters, greylist); - loadColourList(greenlistRouters, greenlist); + loadColourList(router_whitelist, whitelist); + loadColourList(router_greylist, greylist); + loadColourList(router_greenlist, greenlist); - LogInfo("lokinet service node list now has ", whitelistRouters.size(), " active routers"); + LogInfo("lokinet service node list now has ", router_whitelist.size(), " active routers"); } bool - RCLookupHandler::HaveReceivedWhitelist() const + RCLookupHandler::has_received_whitelist() const { util::Lock l(_mutex); - return not whitelistRouters.empty(); + return not router_whitelist.empty(); } void - RCLookupHandler::GetRC(const RouterID& router, RCRequestCallback callback, bool forceLookup) + RCLookupHandler::get_rc(const RouterID& router, RCRequestCallback callback, bool forceLookup) { RouterContact remoteRC; if (not forceLookup) { - if (const auto maybe = _nodedb->Get(router); maybe.has_value()) + if (const auto maybe = node_db->Get(router); maybe.has_value()) { remoteRC = *maybe; if (callback) { callback(router, &remoteRC, RCRequestResult::Success); } - FinalizeRequest(router, &remoteRC, RCRequestResult::Success); + finalize_request(router, &remoteRC, RCRequestResult::Success); return; } } @@ -85,7 +84,7 @@ namespace llarp { util::Lock l(_mutex); - auto itr_pair = pendingCallbacks.emplace(router, CallbacksQueue{}); + auto itr_pair = pending_callbacks.emplace(router, callback_que{}); if (callback) { @@ -96,14 +95,14 @@ namespace llarp if (shouldDoLookup) { - auto fn = [this, router](const auto& res) { HandleDHTLookupResult(router, res); }; + auto fn = [this, router](const auto& res) { handle_dht_lookup_result(router, res); }; // if we are a client try using the hidden service endpoints if (!isServiceNode) { bool sent = false; LogInfo("Lookup ", router, " anonymously"); - _hiddenServiceContext->ForEachService( + hidden_service_context->ForEachService( [&](const std::string&, const std::shared_ptr& ep) -> bool { const bool success = ep->LookupRouterAnon(router, fn); sent = sent || success; @@ -114,22 +113,22 @@ namespace llarp LogWarn("cannot lookup ", router, " anonymously"); } - if (!_dht->LookupRouter(router, fn)) + if (!dht->LookupRouter(router, fn)) { - FinalizeRequest(router, nullptr, RCRequestResult::RouterNotFound); + finalize_request(router, nullptr, RCRequestResult::RouterNotFound); } else { - _routerLookupTimes[router] = std::chrono::steady_clock::now(); + router_lookup_times[router] = std::chrono::steady_clock::now(); } } } bool - RCLookupHandler::IsGreylisted(const RouterID& remote) const + RCLookupHandler::is_grey_listed(const RouterID& remote) const { - if (_strictConnectPubkeys.size() && _strictConnectPubkeys.count(remote) == 0 - && !RemoteInBootstrap(remote)) + if (strict_connect_pubkeys.size() && strict_connect_pubkeys.count(remote) == 0 + && !is_remote_in_bootstrap(remote)) { return false; } @@ -139,29 +138,29 @@ namespace llarp util::Lock lock{_mutex}; - return greylistRouters.count(remote); + return router_greylist.count(remote); } bool - RCLookupHandler::IsGreenlisted(const RouterID& remote) const + RCLookupHandler::is_green_listed(const RouterID& remote) const { util::Lock lock{_mutex}; - return greenlistRouters.count(remote); + return router_greenlist.count(remote); } bool - RCLookupHandler::IsRegistered(const RouterID& remote) const + RCLookupHandler::is_registered(const RouterID& remote) const { util::Lock lock{_mutex}; - return whitelistRouters.count(remote) || greylistRouters.count(remote) - || greenlistRouters.count(remote); + return router_whitelist.count(remote) || router_greylist.count(remote) + || router_greenlist.count(remote); } bool - RCLookupHandler::PathIsAllowed(const RouterID& remote) const + RCLookupHandler::is_path_allowed(const RouterID& remote) const { - if (_strictConnectPubkeys.size() && _strictConnectPubkeys.count(remote) == 0 - && !RemoteInBootstrap(remote)) + if (strict_connect_pubkeys.size() && strict_connect_pubkeys.count(remote) == 0 + && !is_remote_in_bootstrap(remote)) { return false; } @@ -171,14 +170,14 @@ namespace llarp util::Lock lock{_mutex}; - return whitelistRouters.count(remote); + return router_whitelist.count(remote); } bool - RCLookupHandler::SessionIsAllowed(const RouterID& remote) const + RCLookupHandler::is_session_allowed(const RouterID& remote) const { - if (_strictConnectPubkeys.size() && _strictConnectPubkeys.count(remote) == 0 - && !RemoteInBootstrap(remote)) + if (strict_connect_pubkeys.size() && strict_connect_pubkeys.count(remote) == 0 + && !is_remote_in_bootstrap(remote)) { return false; } @@ -188,19 +187,19 @@ namespace llarp util::Lock lock{_mutex}; - return whitelistRouters.count(remote) or greylistRouters.count(remote); + return router_whitelist.count(remote) or router_greylist.count(remote); } bool - RCLookupHandler::CheckRC(const RouterContact& rc) const + RCLookupHandler::check_rc(const RouterContact& rc) const { - if (not SessionIsAllowed(rc.pubkey)) + if (not is_session_allowed(rc.pubkey)) { - _dht->DelRCNodeAsync(dht::Key_t{rc.pubkey}); + dht->DelRCNodeAsync(dht::Key_t{rc.pubkey}); return false; } - if (not rc.Verify(_dht->Now())) + if (not rc.Verify(dht->Now())) { LogWarn("RC for ", RouterID(rc.pubkey), " is invalid"); return false; @@ -210,26 +209,26 @@ namespace llarp if (rc.IsPublicRouter()) { LogDebug("Adding or updating RC for ", RouterID(rc.pubkey), " to nodedb and dht."); - _loop->call([rc, n = _nodedb] { n->PutIfNewer(rc); }); - _dht->PutRCNodeAsync(rc); + loop->call([rc, n = node_db] { n->PutIfNewer(rc); }); + dht->PutRCNodeAsync(rc); } return true; } size_t - RCLookupHandler::NumberOfStrictConnectRouters() const + RCLookupHandler::num_strict_connect_routers() const { - return _strictConnectPubkeys.size(); + return strict_connect_pubkeys.size(); } bool - RCLookupHandler::GetRandomWhitelistRouter(RouterID& router) const + RCLookupHandler::get_random_whitelist_router(RouterID& router) const { util::Lock l(_mutex); - const auto sz = whitelistRouters.size(); - auto itr = whitelistRouters.begin(); + const auto sz = router_whitelist.size(); + auto itr = router_whitelist.begin(); if (sz == 0) return false; if (sz > 1) @@ -239,22 +238,22 @@ namespace llarp } bool - RCLookupHandler::CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) + RCLookupHandler::check_renegotiate_valid(RouterContact newrc, RouterContact oldrc) { // mismatch of identity ? if (newrc.pubkey != oldrc.pubkey) return false; - if (!SessionIsAllowed(newrc.pubkey)) + if (!is_session_allowed(newrc.pubkey)) return false; - auto func = [this, newrc] { CheckRC(newrc); }; - _work(func); + auto func = [this, newrc] { check_rc(newrc); }; + work_func(func); // update dht if required - if (_dht->Nodes()->HasNode(dht::Key_t{newrc.pubkey})) + if (dht->Nodes()->HasNode(dht::Key_t{newrc.pubkey})) { - _dht->Nodes()->PutNode(newrc); + dht->Nodes()->PutNode(newrc); } // TODO: check for other places that need updating the RC @@ -262,14 +261,14 @@ namespace llarp } void - RCLookupHandler::PeriodicUpdate(llarp_time_t now) + RCLookupHandler::periodic_update(llarp_time_t now) { // try looking up stale routers std::unordered_set routersToLookUp; - _nodedb->VisitInsertedBefore( + node_db->VisitInsertedBefore( [&](const RouterContact& rc) { - if (HavePendingLookup(rc.pubkey)) + if (has_pending_lookup(rc.pubkey)) return; routersToLookUp.insert(rc.pubkey); }, @@ -277,26 +276,26 @@ namespace llarp for (const auto& router : routersToLookUp) { - GetRC(router, nullptr, true); + get_rc(router, nullptr, true); } - _nodedb->RemoveStaleRCs(_bootstrapRouterIDList, now - RouterContact::StaleInsertionAge); + node_db->RemoveStaleRCs(boostrap_rid_list, now - RouterContact::StaleInsertionAge); } void - RCLookupHandler::ExploreNetwork() + RCLookupHandler::explore_network() { - const size_t known = _nodedb->NumLoaded(); - if (_bootstrapRCList.empty() && known == 0) + const size_t known = node_db->NumLoaded(); + if (bootstrap_rc_list.empty() && known == 0) { LogError("we have no bootstrap nodes specified"); } - else if (known <= _bootstrapRCList.size()) + else if (known <= bootstrap_rc_list.size()) { - for (const auto& rc : _bootstrapRCList) + for (const auto& rc : bootstrap_rc_list) { LogInfo("Doing explore via bootstrap node: ", RouterID(rc.pubkey)); - _dht->ExploreNetworkVia(dht::Key_t{rc.pubkey}); + dht->ExploreNetworkVia(dht::Key_t{rc.pubkey}); } } @@ -313,9 +312,9 @@ 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 : router_whitelist) { - if (now > _routerLookupTimes[r] + RerequestInterval and not _nodedb->Has(r)) + if (now > router_lookup_times[r] + RerequestInterval and not node_db->Has(r)) { lookupRouters.emplace_back(r); } @@ -329,11 +328,11 @@ namespace llarp } for (const auto& r : lookupRouters) - GetRC(r, nullptr, true); + get_rc(r, nullptr, true); return; } // service nodes gossip, not explore - if (_dht->GetRouter()->IsServiceNode()) + if (dht->GetRouter()->IsServiceNode()) return; // explore via every connected peer @@ -356,11 +355,11 @@ namespace llarp } void - RCLookupHandler::Init( - std::shared_ptr dht, + RCLookupHandler::init( + std::shared_ptr d, std::shared_ptr nodedb, - EventLoop_ptr loop, - WorkerFunc_t dowork, + EventLoop_ptr l, + worker_func dowork, LinkManager* linkManager, service::Context* hiddenServiceContext, const std::unordered_set& strictConnectPubkeys, @@ -368,58 +367,59 @@ namespace llarp bool useWhitelist_arg, bool isServiceNode_arg) { - _dht = dht; - _nodedb = std::move(nodedb); - _loop = std::move(loop); - _work = std::move(dowork); - _hiddenServiceContext = hiddenServiceContext; - _strictConnectPubkeys = strictConnectPubkeys; - _bootstrapRCList = bootstrapRCList; - _linkManager = linkManager; + dht = d; + node_db = std::move(nodedb); + loop = std::move(l); + work_func = std::move(dowork); + hidden_service_context = hiddenServiceContext; + strict_connect_pubkeys = strictConnectPubkeys; + bootstrap_rc_list = bootstrapRCList; + link_manager = linkManager; useWhitelist = useWhitelist_arg; isServiceNode = isServiceNode_arg; - for (const auto& rc : _bootstrapRCList) + for (const auto& rc : bootstrap_rc_list) { - _bootstrapRouterIDList.insert(rc.pubkey); + boostrap_rid_list.insert(rc.pubkey); } } void - RCLookupHandler::HandleDHTLookupResult(RouterID remote, const std::vector& results) + RCLookupHandler::handle_dht_lookup_result( + RouterID remote, const std::vector& results) { if (not results.size()) { - FinalizeRequest(remote, nullptr, RCRequestResult::RouterNotFound); + finalize_request(remote, nullptr, RCRequestResult::RouterNotFound); return; } - if (not SessionIsAllowed(remote)) + if (not is_session_allowed(remote)) { - FinalizeRequest(remote, &results[0], RCRequestResult::InvalidRouter); + finalize_request(remote, &results[0], RCRequestResult::InvalidRouter); return; } - if (not CheckRC(results[0])) + if (not check_rc(results[0])) { - FinalizeRequest(remote, &results[0], RCRequestResult::BadRC); + finalize_request(remote, &results[0], RCRequestResult::BadRC); return; } - FinalizeRequest(remote, &results[0], RCRequestResult::Success); + finalize_request(remote, &results[0], RCRequestResult::Success); } bool - RCLookupHandler::HavePendingLookup(RouterID remote) const + RCLookupHandler::has_pending_lookup(RouterID remote) const { util::Lock l(_mutex); - return pendingCallbacks.find(remote) != pendingCallbacks.end(); + return pending_callbacks.find(remote) != pending_callbacks.end(); } bool - RCLookupHandler::RemoteInBootstrap(const RouterID& remote) const + RCLookupHandler::is_remote_in_bootstrap(const RouterID& remote) const { - for (const auto& rc : _bootstrapRCList) + for (const auto& rc : bootstrap_rc_list) { if (rc.pubkey == remote) { @@ -430,19 +430,19 @@ namespace llarp } void - RCLookupHandler::FinalizeRequest( + RCLookupHandler::finalize_request( const RouterID& router, const RouterContact* const rc, RCRequestResult result) { - CallbacksQueue movedCallbacks; + callback_que movedCallbacks; { util::Lock l(_mutex); - auto itr = pendingCallbacks.find(router); + auto itr = pending_callbacks.find(router); - if (itr != pendingCallbacks.end()) + if (itr != pending_callbacks.end()) { movedCallbacks.splice(movedCallbacks.begin(), itr->second); - pendingCallbacks.erase(itr); + pending_callbacks.erase(itr); } } // lock diff --git a/llarp/router/rc_lookup_handler.hpp b/llarp/router/rc_lookup_handler.hpp index 45bb0291c..7220d4f15 100644 --- a/llarp/router/rc_lookup_handler.hpp +++ b/llarp/router/rc_lookup_handler.hpp @@ -44,20 +44,19 @@ namespace llarp struct RCLookupHandler { public: - using Work_t = std::function; - using WorkerFunc_t = std::function; - using CallbacksQueue = std::list; + using worker_func = std::function)>; + using callback_que = std::list; ~RCLookupHandler() = default; void - AddValidRouter(const RouterID& router) EXCLUDES(_mutex); + add_valid_router(const RouterID& router) EXCLUDES(_mutex); void - RemoveValidRouter(const RouterID& router) EXCLUDES(_mutex); + remove_valid_router(const RouterID& router) EXCLUDES(_mutex); void - SetRouterWhitelist( + set_router_whitelist( const std::vector& whitelist, const std::vector& greylist, const std::vector& greenlist @@ -65,55 +64,55 @@ namespace llarp ) EXCLUDES(_mutex); bool - HaveReceivedWhitelist() const; + has_received_whitelist() const; void - GetRC(const RouterID& router, RCRequestCallback callback, bool forceLookup = false) + get_rc(const RouterID& router, RCRequestCallback callback, bool forceLookup = false) EXCLUDES(_mutex); bool - PathIsAllowed(const RouterID& remote) const EXCLUDES(_mutex); + is_path_allowed(const RouterID& remote) const EXCLUDES(_mutex); bool - SessionIsAllowed(const RouterID& remote) const EXCLUDES(_mutex); + is_session_allowed(const RouterID& remote) const EXCLUDES(_mutex); bool - IsGreylisted(const RouterID& remote) const EXCLUDES(_mutex); + is_grey_listed(const RouterID& remote) const EXCLUDES(_mutex); // "greenlist" = new routers (i.e. "green") that aren't fully funded yet bool - IsGreenlisted(const RouterID& remote) const EXCLUDES(_mutex); + is_green_listed(const RouterID& remote) const EXCLUDES(_mutex); // registered just means that there is at least an operator stake, but doesn't require the node // be fully funded, active, or not decommed. (In other words: it is any of the white, grey, or // green list). bool - IsRegistered(const RouterID& remote) const EXCLUDES(_mutex); + is_registered(const RouterID& remote) const EXCLUDES(_mutex); bool - CheckRC(const RouterContact& rc) const; + check_rc(const RouterContact& rc) const; bool - GetRandomWhitelistRouter(RouterID& router) const EXCLUDES(_mutex); + get_random_whitelist_router(RouterID& router) const EXCLUDES(_mutex); bool - CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc); + check_renegotiate_valid(RouterContact newrc, RouterContact oldrc); void - PeriodicUpdate(llarp_time_t now); + periodic_update(llarp_time_t now); void - ExploreNetwork(); + explore_network(); size_t - NumberOfStrictConnectRouters() const; + num_strict_connect_routers() const; void - Init( + init( std::shared_ptr dht, std::shared_ptr nodedb, std::shared_ptr loop, - WorkerFunc_t dowork, + worker_func dowork, LinkManager* linkManager, service::Context* hiddenServiceContext, const std::unordered_set& strictConnectPubkeys, @@ -122,56 +121,56 @@ namespace llarp bool isServiceNode_arg); std::unordered_set - Whitelist() const + whitelist() const { util::Lock lock{_mutex}; - return whitelistRouters; + return router_whitelist; } private: void - HandleDHTLookupResult(RouterID remote, const std::vector& results); + handle_dht_lookup_result(RouterID remote, const std::vector& results); bool - HavePendingLookup(RouterID remote) const EXCLUDES(_mutex); + has_pending_lookup(RouterID remote) const EXCLUDES(_mutex); bool - RemoteInBootstrap(const RouterID& remote) const; + is_remote_in_bootstrap(const RouterID& remote) const; void - FinalizeRequest(const RouterID& router, const RouterContact* const rc, RCRequestResult result) + finalize_request(const RouterID& router, const RouterContact* const rc, RCRequestResult result) EXCLUDES(_mutex); mutable util::Mutex _mutex; // protects pendingCallbacks, whitelistRouters - std::shared_ptr _dht = nullptr; - std::shared_ptr _nodedb; - std::shared_ptr _loop; - WorkerFunc_t _work = nullptr; - service::Context* _hiddenServiceContext = nullptr; - LinkManager* _linkManager = nullptr; + std::shared_ptr dht = nullptr; + std::shared_ptr node_db; + std::shared_ptr loop; + worker_func work_func = nullptr; + service::Context* hidden_service_context = nullptr; + LinkManager* link_manager = nullptr; /// explicit whitelist of routers we will connect to directly (not for /// service nodes) - std::unordered_set _strictConnectPubkeys; + std::unordered_set strict_connect_pubkeys; - std::set _bootstrapRCList; - std::unordered_set _bootstrapRouterIDList; + std::set bootstrap_rc_list; + std::unordered_set boostrap_rid_list; - std::unordered_map pendingCallbacks GUARDED_BY(_mutex); + std::unordered_map pending_callbacks GUARDED_BY(_mutex); bool useWhitelist = false; bool isServiceNode = false; // whitelist = active routers - std::unordered_set whitelistRouters GUARDED_BY(_mutex); + std::unordered_set router_whitelist GUARDED_BY(_mutex); // greylist = fully funded, but decommissioned routers - std::unordered_set greylistRouters GUARDED_BY(_mutex); + std::unordered_set router_greylist GUARDED_BY(_mutex); // greenlist = registered but not fully-staked routers - std::unordered_set greenlistRouters GUARDED_BY(_mutex); + std::unordered_set router_greenlist GUARDED_BY(_mutex); using TimePoint = std::chrono::steady_clock::time_point; - std::unordered_map _routerLookupTimes; + std::unordered_map router_lookup_times; }; } // namespace llarp diff --git a/llarp/router/route_poker.cpp b/llarp/router/route_poker.cpp index 1471ac911..cd9434bdd 100644 --- a/llarp/router/route_poker.cpp +++ b/llarp/router/route_poker.cpp @@ -1,5 +1,5 @@ #include "route_poker.hpp" -#include +#include "router.hpp" #include #include #include @@ -36,7 +36,7 @@ namespace llarp { if (ip.n and gateway.n and IsEnabled()) { - vpn::IRouteManager& route = m_Router->GetVPNPlatform()->RouteManager(); + vpn::IRouteManager& route = m_Router->vpn_platform()->RouteManager(); route.DelRoute(ip, gateway); } } @@ -46,7 +46,7 @@ namespace llarp { if (ip.n and gateway.n and IsEnabled()) { - vpn::IRouteManager& route = m_Router->GetVPNPlatform()->RouteManager(); + vpn::IRouteManager& route = m_Router->vpn_platform()->RouteManager(); route.AddRoute(ip, gateway); } } @@ -63,7 +63,7 @@ namespace llarp } void - RoutePoker::Start(AbstractRouter* router) + RoutePoker::Start(Router* router) { m_Router = router; if (not IsEnabled()) @@ -101,10 +101,10 @@ namespace llarp RoutePoker::~RoutePoker() { - if (not m_Router or not m_Router->GetVPNPlatform()) + if (not m_Router or not m_Router->vpn_platform()) return; - auto& route = m_Router->GetVPNPlatform()->RouteManager(); + auto& route = m_Router->vpn_platform()->RouteManager(); for (const auto& [ip, gateway] : m_PokedRoutes) { if (gateway.n and ip.n) @@ -120,7 +120,7 @@ namespace llarp throw std::runtime_error{"Attempting to use RoutePoker before calling Init"}; if (m_Router->IsServiceNode()) return false; - if (const auto& conf = m_Router->GetConfig()) + if (const auto& conf = m_Router->config()) return conf->network.m_EnableRoutePoker; throw std::runtime_error{"Attempting to use RoutePoker with router with no config set"}; @@ -137,7 +137,7 @@ namespace llarp if (ep == nullptr) return; // ensure we have a vpn platform - auto* platform = m_Router->GetVPNPlatform(); + auto* platform = m_Router->vpn_platform(); if (platform == nullptr) return; // ensure we have a vpn interface @@ -214,10 +214,10 @@ namespace llarp { log::info(logcat, "RoutePoker coming up; poking routes"); - vpn::IRouteManager& route = m_Router->GetVPNPlatform()->RouteManager(); + vpn::IRouteManager& route = m_Router->vpn_platform()->RouteManager(); // black hole all routes if enabled - if (m_Router->GetConfig()->network.m_BlackholeRoutes) + if (m_Router->config()->network.m_BlackholeRoutes) route.AddBlackhole(); // explicit route pokes for first hops @@ -246,7 +246,7 @@ namespace llarp if (IsEnabled() and m_up) { - vpn::IRouteManager& route = m_Router->GetVPNPlatform()->RouteManager(); + vpn::IRouteManager& route = m_Router->vpn_platform()->RouteManager(); const auto ep = m_Router->hiddenServiceContext().GetDefault(); if (auto* vpn = ep->GetVPNInterface()) route.DelDefaultRouteViaInterface(*vpn); diff --git a/llarp/router/route_poker.hpp b/llarp/router/route_poker.hpp index 9a0feb65c..a5399cecc 100644 --- a/llarp/router/route_poker.hpp +++ b/llarp/router/route_poker.hpp @@ -8,7 +8,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; struct RoutePoker : public std::enable_shared_from_this { @@ -19,7 +19,7 @@ namespace llarp DelRoute(net::ipv4addr_t ip); void - Start(AbstractRouter* router); + Start(Router* router); ~RoutePoker(); @@ -62,7 +62,7 @@ namespace llarp std::optional m_CurrentGateway; - AbstractRouter* m_Router = nullptr; + Router* m_Router = nullptr; bool m_up{false}; }; } // namespace llarp diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index 9303f8b7d..8b7eee69b 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -9,8 +9,6 @@ #include #include #include -#include -#include #include #include #include @@ -48,14 +46,13 @@ namespace llarp static auto logcat = log::Cat("router"); Router::Router(EventLoop_ptr loop, std::shared_ptr vpnPlatform) - : ready{false} - , m_lmq{std::make_shared()} + : _lmq{std::make_shared()} , _loop{std::move(loop)} - , _vpnPlatform{std::move(vpnPlatform)} + , _vpn{std::move(vpnPlatform)} , paths{this} , _exitContext{this} , _dht{dht::make_handler()} - , m_DiskThread{m_lmq->add_tagged_thread("disk")} + , _disk_thread{_lmq->add_tagged_thread("disk")} , inbound_link_msg_parser{this} , _hiddenServiceContext{this} , m_RoutePoker{std::make_shared()} @@ -64,14 +61,14 @@ namespace llarp platform::is_simulation ? std::chrono::milliseconds{(llarp::randint() % 1250) + 2000} : 0s} { - m_keyManager = std::make_shared(); + _key_manager = std::make_shared(); // for lokid, so we don't close the connection when syncing the whitelist - m_lmq->MAX_MSG_SIZE = -1; - _stopping.store(false); - _running.store(false); + _lmq->MAX_MSG_SIZE = -1; + is_stopping.store(false); + is_running.store(false); _lastTick = llarp::time_now_ms(); - m_NextExploreAt = Clock_t::now(); - m_Pump = _loop->make_waker([this]() { PumpLL(); }); + m_NextExploreAt = std::chrono::steady_clock::now(); + loop_wakeup = _loop->make_waker([this]() { PumpLL(); }); } Router::~Router() @@ -85,7 +82,7 @@ namespace llarp Router::PumpLL() { llarp::LogTrace("Router::PumpLL() start"); - if (_stopping.load()) + if (is_stopping.load()) return; paths.PumpDownstream(); paths.PumpUpstream(); @@ -97,16 +94,16 @@ namespace llarp util::StatusObject Router::ExtractStatus() const { - if (not _running) + if (not is_running) util::StatusObject{{"running", false}}; return util::StatusObject{ {"running", true}, - {"numNodesKnown", _nodedb->NumLoaded()}, + {"numNodesKnown", _node_db->NumLoaded()}, {"dht", _dht->ExtractStatus()}, {"services", _hiddenServiceContext.ExtractStatus()}, {"exit", _exitContext.ExtractStatus()}, - {"links", _linkManager.ExtractStatus()}, + {"links", _link_manager.extract_status()}, {"outboundMessages", _outboundMessageHandler.ExtractStatus()}}; } @@ -114,12 +111,12 @@ namespace llarp util::StatusObject Router::ExtractSummaryStatus() const { - if (!_running) + if (!is_running) return util::StatusObject{{"running", false}}; auto services = _hiddenServiceContext.ExtractStatus(); - auto link_types = _linkManager.ExtractStatus(); + auto link_types = _link_manager.extract_status(); uint64_t tx_rate = 0; uint64_t rx_rate = 0; @@ -192,7 +189,7 @@ namespace llarp {"uptime", to_json(Uptime())}, {"numPathsBuilt", pathsCount}, {"numPeersConnected", peers}, - {"numRoutersKnown", _nodedb->NumLoaded()}, + {"numRoutersKnown", _node_db->NumLoaded()}, {"ratio", ratio}, {"txRate", tx_rate}, {"rxRate", rx_rate}, @@ -212,7 +209,7 @@ namespace llarp bool Router::HandleRecvLinkMessageBuffer(AbstractLinkSession* session, const llarp_buffer_t& buf) { - if (_stopping) + if (is_stopping) return true; if (!session) @@ -273,7 +270,7 @@ namespace llarp void Router::PersistSessionUntil(const RouterID& remote, llarp_time_t until) { - _linkManager.set_conn_persist(remote, until); + _link_manager.set_conn_persist(remote, until); } void @@ -294,12 +291,12 @@ namespace llarp bool Router::GetRandomGoodRouter(RouterID& router) { - if (whitelistRouters) + if (follow_whitelist) { - return _rcLookupHandler.GetRandomWhitelistRouter(router); + return _rc_lookup_handler.get_random_whitelist_router(router); } - if (const auto maybe = nodedb()->GetRandom([](const auto&) -> bool { return true; })) + if (const auto maybe = node_db()->GetRandom([](const auto&) -> bool { return true; })) { router = maybe->pubkey; return true; @@ -310,7 +307,7 @@ namespace llarp void Router::TriggerPump() { - m_Pump->Trigger(); + loop_wakeup->Trigger(); } bool @@ -346,7 +343,7 @@ namespace llarp if (remote.Verify(Now())) { LogDebug("verified signature"); - _linkManager.Connect(remote); + _link_manager.connect_to(remote); } else LogError(rcfile, " contains invalid RC"); @@ -355,9 +352,9 @@ namespace llarp bool Router::EnsureIdentity() { - _encryption = m_keyManager->encryptionKey; + _encryption = _key_manager->encryptionKey; - if (whitelistRouters) + if (follow_whitelist) { #if defined(ANDROID) || defined(IOS) LogError("running a service node on mobile device is not possible."); @@ -375,10 +372,10 @@ namespace llarp numTries++; try { - _identity = RpcClient()->ObtainIdentityKey(); + _identity = rpc_client()->ObtainIdentityKey(); const RouterID pk{pubkey()}; LogWarn("Obtained lokid identity key: ", pk); - RpcClient()->StartPings(); + rpc_client()->StartPings(); break; } catch (const std::exception& e) @@ -398,7 +395,7 @@ namespace llarp } else { - _identity = m_keyManager->identityKey; + _identity = _key_manager->identityKey; } if (_identity.IsZero()) @@ -414,8 +411,8 @@ namespace llarp { llarp::sys::service_manager->starting(); - m_Config = std::move(c); - auto& conf = *m_Config; + config = std::move(c); + auto& conf = *config; // Do logging config as early as possible to get the configured log level applied @@ -432,18 +429,18 @@ namespace llarp log::add_sink(log_type, log_type == log::Type::System ? "lokinet" : conf.logging.m_logFile); // re-add rpc log sink if rpc enabled, else free it - if (m_Config->api.m_enableRPCServer and llarp::logRingBuffer) + if (config->api.m_enableRPCServer and llarp::logRingBuffer) log::add_sink(llarp::logRingBuffer, llarp::log::DEFAULT_PATTERN_MONO); else llarp::logRingBuffer = nullptr; log::debug(logcat, "Configuring router"); - whitelistRouters = conf.lokid.whitelistRouters; - if (whitelistRouters) + follow_whitelist = conf.lokid.whitelistRouters; + if (follow_whitelist) { lokidRPCAddr = oxenmq::address(conf.lokid.lokidRPCAddr); - m_lokidRpcClient = std::make_shared(m_lmq, weak_from_this()); + _rpc_client = std::make_shared(_lmq, weak_from_this()); } log::debug(logcat, "Starting RPC server"); @@ -451,28 +448,28 @@ namespace llarp throw std::runtime_error("Failed to start rpc server"); if (conf.router.m_workerThreads > 0) - m_lmq->set_general_threads(conf.router.m_workerThreads); + _lmq->set_general_threads(conf.router.m_workerThreads); log::debug(logcat, "Starting OMQ server"); - m_lmq->start(); + _lmq->start(); - _nodedb = std::move(nodedb); + _node_db = std::move(nodedb); - m_isServiceNode = conf.router.m_isRelay; + is_service_node = conf.router.m_isRelay; log::debug( - logcat, m_isServiceNode ? "Running as a relay (service node)" : "Running as a client"); + logcat, is_service_node ? "Running as a relay (service node)" : "Running as a client"); - if (whitelistRouters) + if (follow_whitelist) { - m_lokidRpcClient->ConnectAsync(lokidRPCAddr); + _rpc_client->ConnectAsync(lokidRPCAddr); } log::debug(logcat, "Initializing key manager"); - if (not m_keyManager->initialize(conf, true, isSNode)) + if (not _key_manager->initialize(conf, true, isSNode)) throw std::runtime_error("KeyManager failed to initialize"); log::debug(logcat, "Initializing from configuration"); - if (!FromConfig(conf)) + if (!from_config(conf)) throw std::runtime_error("FromConfig() failed"); log::debug(logcat, "Initializing identity"); @@ -486,36 +483,36 @@ namespace llarp Router::HandleSaveRC() const { std::string fname = our_rc_file.string(); - _rc.Write(fname.c_str()); + router_contact.Write(fname.c_str()); } bool Router::SaveRC() { LogDebug("verify RC signature"); - if (!_rc.Verify(Now())) + if (!router_contact.Verify(Now())) { Dump(rc()); LogError("RC is invalid, not saving"); return false; } - if (m_isServiceNode) - _nodedb->Put(_rc); - QueueDiskIO([&]() { HandleSaveRC(); }); + if (is_service_node) + _node_db->Put(router_contact); + queue_disk_io([&]() { HandleSaveRC(); }); return true; } bool Router::IsServiceNode() const { - return m_isServiceNode; + return is_service_node; } bool - Router::TooFewPeers() const + Router::insufficient_peers() const { constexpr int KnownPeerWarningThreshold = 5; - return nodedb()->NumLoaded() < KnownPeerWarningThreshold; + return node_db()->NumLoaded() < KnownPeerWarningThreshold; } std::optional @@ -523,7 +520,7 @@ namespace llarp { // If we're in the white or gray list then we *should* be establishing connections to other // routers, so if we have almost no peers then something is almost certainly wrong. - if (LooksFunded() and TooFewPeers()) + if (appear_funder() and insufficient_peers()) return "too few peer connections; lokinet is not adequately connected to the network"; return std::nullopt; } @@ -536,7 +533,7 @@ namespace llarp _onDown(); log::debug(logcat, "stopping mainloop"); _loop->stop(); - _running.store(false); + is_running.store(false); } bool @@ -547,72 +544,72 @@ namespace llarp } bool - Router::LooksDecommissioned() const + Router::appear_decommed() const { - return IsServiceNode() and whitelistRouters and _rcLookupHandler.HaveReceivedWhitelist() - and _rcLookupHandler.IsGreylisted(pubkey()); + return IsServiceNode() and follow_whitelist and _rc_lookup_handler.has_received_whitelist() + and _rc_lookup_handler.is_grey_listed(pubkey()); } bool - Router::LooksFunded() const + Router::appear_funder() const { - return IsServiceNode() and whitelistRouters and _rcLookupHandler.HaveReceivedWhitelist() - and _rcLookupHandler.SessionIsAllowed(pubkey()); + return IsServiceNode() and follow_whitelist and _rc_lookup_handler.has_received_whitelist() + and _rc_lookup_handler.is_session_allowed(pubkey()); } bool - Router::LooksRegistered() const + Router::appear_registered() const { - return IsServiceNode() and whitelistRouters and _rcLookupHandler.HaveReceivedWhitelist() - and _rcLookupHandler.IsRegistered(pubkey()); + return IsServiceNode() and follow_whitelist and _rc_lookup_handler.has_received_whitelist() + and _rc_lookup_handler.is_registered(pubkey()); } bool - Router::ShouldTestOtherRouters() const + Router::can_test_routers() const { if (not IsServiceNode()) return false; - if (not whitelistRouters) + if (not follow_whitelist) return true; - if (not _rcLookupHandler.HaveReceivedWhitelist()) + if (not _rc_lookup_handler.has_received_whitelist()) return false; - return _rcLookupHandler.SessionIsAllowed(pubkey()); + return _rc_lookup_handler.is_session_allowed(pubkey()); } bool Router::SessionToRouterAllowed(const RouterID& router) const { - return _rcLookupHandler.SessionIsAllowed(router); + return _rc_lookup_handler.is_session_allowed(router); } bool Router::PathToRouterAllowed(const RouterID& router) const { - if (LooksDecommissioned()) + if (appear_decommed()) { // we are decom'd don't allow any paths outbound at all return false; } - return _rcLookupHandler.PathIsAllowed(router); + return _rc_lookup_handler.is_path_allowed(router); } size_t Router::NumberOfConnectedRouters() const { - return _linkManager.get_num_connected(); + return _link_manager.get_num_connected(); } size_t Router::NumberOfConnectedClients() const { - return _linkManager.get_num_connected_clients(); + return _link_manager.get_num_connected_clients(); } bool - Router::UpdateOurRC(bool rotateKeys) + Router::update_rc(bool rotateKeys) { SecretKey nextOnionKey; - RouterContact nextRC = _rc; + RouterContact nextRC = router_contact; if (rotateKeys) { CryptoManager::instance()->encryption_keygen(nextOnionKey); @@ -628,7 +625,7 @@ namespace llarp return false; if (!nextRC.Verify(time_now_ms(), false)) return false; - _rc = std::move(nextRC); + router_contact = std::move(nextRC); if (rotateKeys) { // TODO: libquic change @@ -648,7 +645,7 @@ namespace llarp } bool - Router::FromConfig(const Config& conf) + Router::from_config(const Config& conf) { // Set netid before anything else log::debug(logcat, "Network ID set to {}", conf.router.m_netId); @@ -666,18 +663,18 @@ namespace llarp "shape correlation !!!!"); NetID::DefaultValue() = NetID(reinterpret_cast(netid.c_str())); // reset netid in our rc - _rc.netID = llarp::NetID(); + router_contact.netID = llarp::NetID(); } // Router config - _rc.SetNick(conf.router.m_nickname); - _linkManager.max_connected_routers = conf.router.m_maxConnectedRouters; - _linkManager.min_connected_routers = conf.router.m_minConnectedRouters; + router_contact.SetNick(conf.router.m_nickname); + _link_manager.max_connected_routers = conf.router.m_maxConnectedRouters; + _link_manager.min_connected_routers = conf.router.m_minConnectedRouters; - encryption_keyfile = m_keyManager->m_encKeyPath; - our_rc_file = m_keyManager->m_rcPath; - transport_keyfile = m_keyManager->m_transportKeyPath; - ident_keyfile = m_keyManager->m_idKeyPath; + encryption_keyfile = _key_manager->m_encKeyPath; + our_rc_file = _key_manager->m_rcPath; + transport_keyfile = _key_manager->m_transportKeyPath; + identity_keyfile = _key_manager->m_idKeyPath; if (auto maybe_ip = conf.links.PublicAddress) _ourAddress = var::visit([](auto&& ip) { return SockAddr{ip}; }, *maybe_ip); @@ -767,7 +764,7 @@ namespace llarp if (bootstrapRCList.empty() and not conf.bootstrap.seednode) { auto fallbacks = llarp::load_bootstrap_fallbacks(); - if (auto itr = fallbacks.find(_rc.netID.ToString()); itr != fallbacks.end()) + if (auto itr = fallbacks.find(router_contact.netID.ToString()); itr != fallbacks.end()) { bootstrapRCList = itr->second; log::debug(logcat, "loaded {} default fallback bootstrap routers", bootstrapRCList.size()); @@ -792,21 +789,21 @@ namespace llarp // Init components after relevant config settings loaded _outboundMessageHandler.Init(this); - _linkManager.init(&_rcLookupHandler); - _rcLookupHandler.Init( + _link_manager.init(&_rc_lookup_handler); + _rc_lookup_handler.init( _dht, - _nodedb, + _node_db, _loop, - util::memFn(&AbstractRouter::QueueWork, this), - &_linkManager, + util::memFn(&Router::queue_work, this), + &_link_manager, &_hiddenServiceContext, strictConnectPubkeys, bootstrapRCList, - whitelistRouters, - m_isServiceNode); + follow_whitelist, + is_service_node); // FIXME: kludge for now, will be part of larger cleanup effort. - if (m_isServiceNode) + if (is_service_node) InitInboundLinks(); else InitOutboundLinks(); @@ -825,12 +822,12 @@ namespace llarp else { LogInfo("loading router profiles from ", _profilesFile); - routerProfiling().Load(_profilesFile); + router_profiling().Load(_profilesFile); } } else { - routerProfiling().Disable(); + router_profiling().Disable(); LogInfo("router profiling disabled"); } @@ -846,7 +843,7 @@ namespace llarp bool Router::CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) { - return _rcLookupHandler.CheckRenegotiateValid(newrc, oldrc); + return _rc_lookup_handler.check_renegotiate_valid(newrc, oldrc); } bool @@ -860,28 +857,28 @@ namespace llarp } bool - Router::ShouldReportStats(llarp_time_t now) const + Router::should_report_stats(llarp_time_t now) const { static constexpr auto ReportStatsInterval = 1h; - return now - m_LastStatsReport > ReportStatsInterval; + return now - _last_stats_report > ReportStatsInterval; } void - Router::ReportStats() + Router::report_stats() { const auto now = Now(); - LogInfo(nodedb()->NumLoaded(), " RCs loaded"); + LogInfo(node_db()->NumLoaded(), " RCs loaded"); LogInfo(bootstrapRCList.size(), " bootstrap peers"); LogInfo(NumberOfConnectedRouters(), " router connections"); if (IsServiceNode()) { LogInfo(NumberOfConnectedClients(), " client connections"); - LogInfo(ToString(_rc.Age(now)), " since we last updated our RC"); - LogInfo(ToString(_rc.TimeUntilExpires(now)), " until our RC expires"); + LogInfo(ToString(router_contact.Age(now)), " since we last updated our RC"); + LogInfo(ToString(router_contact.TimeUntilExpires(now)), " until our RC expires"); } - if (m_LastStatsReport > 0s) - LogInfo(ToString(now - m_LastStatsReport), " last reported stats"); - m_LastStatsReport = now; + if (_last_stats_report > 0s) + LogInfo(ToString(now - _last_stats_report), " last reported stats"); + _last_stats_report = now; } std::string @@ -895,14 +892,14 @@ namespace llarp fmt::format_to( out, " snode | known/svc/clients: {}/{}/{}", - nodedb()->NumLoaded(), + node_db()->NumLoaded(), NumberOfConnectedRouters(), NumberOfConnectedClients()); fmt::format_to( out, " | {} active paths | block {} ", - pathContext().CurrentTransitPaths(), - (m_lokidRpcClient ? m_lokidRpcClient->BlockHeight() : 0)); + path_context().CurrentTransitPaths(), + (_rpc_client ? _rpc_client->BlockHeight() : 0)); auto maybe_last = _rcGossiper.LastGossipAt(); fmt::format_to( out, @@ -915,7 +912,7 @@ namespace llarp fmt::format_to( out, " client | known/connected: {}/{}", - nodedb()->NumLoaded(), + node_db()->NumLoaded(), NumberOfConnectedRouters()); if (auto ep = hiddenServiceContext().GetDefault()) @@ -923,7 +920,7 @@ namespace llarp fmt::format_to( out, " | paths/endpoints {}/{}", - pathContext().CurrentOwnedPaths(), + path_context().CurrentOwnedPaths(), ep->UniqueEndpoints()); if (auto success_rate = ep->CurrentBuildStats().SuccessRatio(); success_rate < 0.5) @@ -939,7 +936,7 @@ namespace llarp void Router::Tick() { - if (_stopping) + if (is_stopping) return; // LogDebug("tick router"); const auto now = Now(); @@ -952,30 +949,30 @@ namespace llarp llarp::sys::service_manager->report_periodic_stats(); - m_PathBuildLimiter.Decay(now); + _pathbuild_limiter.Decay(now); - routerProfiling().Tick(); + router_profiling().Tick(); - if (ShouldReportStats(now)) + if (should_report_stats(now)) { - ReportStats(); + report_stats(); } _rcGossiper.Decay(now); - _rcLookupHandler.PeriodicUpdate(now); + _rc_lookup_handler.periodic_update(now); - const bool gotWhitelist = _rcLookupHandler.HaveReceivedWhitelist(); + const bool gotWhitelist = _rc_lookup_handler.has_received_whitelist(); const bool isSvcNode = IsServiceNode(); - const bool decom = LooksDecommissioned(); - bool shouldGossip = isSvcNode and whitelistRouters and gotWhitelist - and _rcLookupHandler.SessionIsAllowed(pubkey()); + const bool decom = appear_decommed(); + bool shouldGossip = isSvcNode and follow_whitelist and gotWhitelist + and _rc_lookup_handler.is_session_allowed(pubkey()); if (isSvcNode - and (_rc.ExpiresSoon(now, std::chrono::milliseconds(randint() % 10000)) or (now - _rc.last_updated) > rcRegenInterval)) + and (router_contact.ExpiresSoon(now, std::chrono::milliseconds(randint() % 10000)) or (now - router_contact.last_updated) > rcRegenInterval)) { LogInfo("regenerating RC"); - if (UpdateOurRC()) + if (update_rc()) { // our rc changed so we should gossip it shouldGossip = true; @@ -989,10 +986,10 @@ namespace llarp { // if we have the whitelist enabled, we have fetched the list and we are in either // the white or grey list, we want to gossip our RC - GossipRCIfNeeded(_rc); + GossipRCIfNeeded(router_contact); } // remove RCs for nodes that are no longer allowed by network policy - nodedb()->RemoveIf([&](const RouterContact& rc) -> bool { + node_db()->RemoveIf([&](const RouterContact& rc) -> bool { // don't purge bootstrap nodes from nodedb if (IsBootstrapNode(rc.pubkey)) { @@ -1023,7 +1020,7 @@ namespace llarp // 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 (follow_whitelist and not gotWhitelist) { log::debug(logcat, "Skipping check on {}: don't have whitelist yet", rc.pubkey); return false; @@ -1032,7 +1029,7 @@ namespace llarp // the whitelist enabled and we got the whitelist // check against the whitelist and remove if it's not // in the whitelist OR if there is no whitelist don't remove - if (gotWhitelist and not _rcLookupHandler.SessionIsAllowed(rc.pubkey)) + if (gotWhitelist and not _rc_lookup_handler.is_session_allowed(rc.pubkey)) { log::debug(logcat, "Removing {}: not a valid router", rc.pubkey); return true; @@ -1063,30 +1060,30 @@ namespace llarp // mark peers as de-registered for (auto& peer : closePeers) - _linkManager.deregister_peer(std::move(peer)); + _link_manager.deregister_peer(std::move(peer)); - _linkManager.check_persisting_conns(now); + _link_manager.check_persisting_conns(now); size_t connected = NumberOfConnectedRouters(); const int interval = isSvcNode ? 5 : 2; - const auto timepoint_now = Clock_t::now(); + const auto timepoint_now = std::chrono::steady_clock::now(); if (timepoint_now >= m_NextExploreAt and not decom) { - _rcLookupHandler.ExploreNetwork(); + _rc_lookup_handler.explore_network(); m_NextExploreAt = timepoint_now + std::chrono::seconds(interval); } - size_t connectToNum = _linkManager.min_connected_routers; - const auto strictConnect = _rcLookupHandler.NumberOfStrictConnectRouters(); + size_t connectToNum = _link_manager.min_connected_routers; + const auto strictConnect = _rc_lookup_handler.num_strict_connect_routers(); if (strictConnect > 0 && connectToNum > strictConnect) { connectToNum = strictConnect; } - if (isSvcNode and now >= m_NextDecommissionWarn) + if (isSvcNode and now >= next_decomm_warning) { constexpr auto DecommissionWarnInterval = 5min; - if (auto registered = LooksRegistered(), funded = LooksFunded(); + if (auto registered = appear_registered(), funded = appear_funder(); not(registered and funded and not decom)) { // complain about being deregistered/decommed/unfunded @@ -1096,52 +1093,52 @@ namespace llarp not registered ? "deregistered" : decom ? "decommissioned" : "not fully staked"); - m_NextDecommissionWarn = now + DecommissionWarnInterval; + next_decomm_warning = now + DecommissionWarnInterval; } - else if (TooFewPeers()) + else if (insufficient_peers()) { log::error( logcat, "We appear to be an active service node, but have only {} known peers.", - nodedb()->NumLoaded()); - m_NextDecommissionWarn = now + DecommissionWarnInterval; + node_db()->NumLoaded()); + next_decomm_warning = now + DecommissionWarnInterval; } } // if we need more sessions to routers and we are not a service node kicked from the network or // we are a client we shall connect out to others - if (connected < connectToNum and (LooksFunded() or not isSvcNode)) + if (connected < connectToNum and (appear_funder() or not isSvcNode)) { size_t dlt = connectToNum - connected; LogDebug("connecting to ", dlt, " random routers to keep alive"); - _linkManager.connect_to_random(dlt); + _link_manager.connect_to_random(dlt); } _hiddenServiceContext.Tick(now); _exitContext.Tick(now); // save profiles - if (routerProfiling().ShouldSave(now) and m_Config->network.m_saveProfiles) + if (router_profiling().ShouldSave(now) and config->network.m_saveProfiles) { - QueueDiskIO([&]() { routerProfiling().Save(_profilesFile); }); + queue_disk_io([&]() { router_profiling().Save(_profilesFile); }); } - _nodedb->Tick(now); + _node_db->Tick(now); - if (m_peerDb) + if (_peer_db) { // TODO: throttle this? // TODO: need to capture session stats when session terminates / is removed from link // manager - _linkManager.update_peer_db(m_peerDb); + _link_manager.update_peer_db(_peer_db); - if (m_peerDb->shouldFlush(now)) + if (_peer_db->shouldFlush(now)) { LogDebug("Queing database flush..."); - QueueDiskIO([this]() { + queue_disk_io([this]() { try { - m_peerDb->flushDatabase(); + _peer_db->flushDatabase(); } catch (std::exception& ex) { @@ -1188,7 +1185,7 @@ namespace llarp LogInfo("Session to ", remote, " fully closed"); if (IsServiceNode()) return; - if (const auto maybe = nodedb()->Get(remote); maybe.has_value()) + if (const auto maybe = node_db()->Get(remote); maybe.has_value()) { for (const auto& addr : maybe->addrs) m_RoutePoker->DelRoute(addr.IPv4()); @@ -1199,21 +1196,21 @@ namespace llarp void Router::ConnectionTimedOut(AbstractLinkSession* session) { - if (m_peerDb) + if (_peer_db) { RouterID id{session->GetPubKey()}; // TODO: make sure this is a public router (on whitelist)? - m_peerDb->modifyPeerStats(id, [&](PeerStats& stats) { stats.numConnectionTimeouts++; }); + _peer_db->modifyPeerStats(id, [&](PeerStats& stats) { stats.numConnectionTimeouts++; }); } } void - Router::ModifyOurRC(std::function(RouterContact)> modify) + Router::modify_rc(std::function(RouterContact)> modify) { if (auto maybe = modify(rc())) { - _rc = *maybe; - UpdateOurRC(); + router_contact = *maybe; + update_rc(); _rcGossiper.GossipRC(rc()); } } @@ -1223,19 +1220,19 @@ namespace llarp Router::ConnectionEstablished(AbstractLinkSession* session, bool inbound) { RouterID id{session->GetPubKey()}; - if (m_peerDb) + if (_peer_db) { // TODO: make sure this is a public router (on whitelist)? - m_peerDb->modifyPeerStats(id, [&](PeerStats& stats) { stats.numConnectionSuccesses++; }); + _peer_db->modifyPeerStats(id, [&](PeerStats& stats) { stats.numConnectionSuccesses++; }); } - NotifyRouterEvent(pubkey(), id, inbound); + notify_router_event(pubkey(), id, inbound); return true; } bool Router::GetRandomConnectedRouter(RouterContact& result) const { - return _linkManager.get_random_connected(result); + return _link_manager.get_random_connected(result); } void @@ -1243,7 +1240,7 @@ namespace llarp { for (const auto& rc : results) { - _rcLookupHandler.CheckRC(rc); + _rc_lookup_handler.check_rc(rc); } } @@ -1251,7 +1248,7 @@ namespace llarp void Router::LookupRouter(RouterID remote, RouterLookupHandler resultHandler) { - _rcLookupHandler.GetRC( + _rc_lookup_handler.get_rc( remote, [=](const RouterID& id, const RouterContact* const rc, const RCRequestResult result) { (void)id; @@ -1268,19 +1265,19 @@ namespace llarp } void - Router::SetRouterWhitelist( + Router::set_router_whitelist( const std::vector& whitelist, const std::vector& greylist, const std::vector& unfundedlist) { - _rcLookupHandler.SetRouterWhitelist(whitelist, greylist, unfundedlist); + _rc_lookup_handler.set_router_whitelist(whitelist, greylist, unfundedlist); } bool Router::StartRpcServer() { - if (m_Config->api.m_enableRPCServer) - m_RPCServer = std::make_unique(m_lmq, *this); + if (config->api.m_enableRPCServer) + m_RPCServer = std::make_unique(_lmq, *this); return true; } @@ -1288,28 +1285,28 @@ namespace llarp bool Router::Run() { - if (_running || _stopping) + if (is_running || is_stopping) return false; // set public signing key - _rc.pubkey = seckey_topublic(identity()); + router_contact.pubkey = seckey_topublic(identity()); // set router version if service node if (IsServiceNode()) { - _rc.routerVersion = RouterVersion(llarp::VERSION, llarp::constants::proto_version); + router_contact.routerVersion = RouterVersion(llarp::VERSION, llarp::constants::proto_version); } - if (IsServiceNode() and not _rc.IsPublicRouter()) + if (IsServiceNode() and not router_contact.IsPublicRouter()) { LogError("we are configured as relay but have no reachable addresses"); return false; } // set public encryption key - _rc.enckey = seckey_topublic(encryption()); + router_contact.enckey = seckey_topublic(encryption()); LogInfo("Signing rc..."); - if (!_rc.Sign(identity())) + if (!router_contact.Sign(identity())) { LogError("failed to sign rc"); return false; @@ -1335,9 +1332,9 @@ namespace llarp const RouterID us = pubkey(); LogInfo("initalized service node: ", us); // init gossiper here - _rcGossiper.Init(&_linkManager, us, this); + _rcGossiper.Init(&_link_manager, us, this); // relays do not use profiling - routerProfiling().Disable(); + router_profiling().Disable(); } else { @@ -1345,9 +1342,9 @@ namespace llarp // regenerate keys and resign rc before everything else CryptoManager::instance()->identity_keygen(_identity); CryptoManager::instance()->encryption_keygen(_encryption); - _rc.pubkey = seckey_topublic(identity()); - _rc.enckey = seckey_topublic(encryption()); - if (!_rc.Sign(identity())) + router_contact.pubkey = seckey_topublic(identity()); + router_contact.enckey = seckey_topublic(encryption()); + if (!router_contact.Sign(identity())) { LogError("failed to regenerate keys and sign RC"); return false; @@ -1363,38 +1360,38 @@ namespace llarp { LogInfo("Loading nodedb from disk..."); - _nodedb->LoadFromDisk(); + _node_db->LoadFromDisk(); } _dht->Init(llarp::dht::Key_t(pubkey()), this); for (const auto& rc : bootstrapRCList) { - nodedb()->Put(rc); + node_db()->Put(rc); _dht->Nodes()->PutNode(rc); LogInfo("added bootstrap node ", RouterID{rc.pubkey}); } - LogInfo("have ", _nodedb->NumLoaded(), " routers"); + LogInfo("have ", _node_db->NumLoaded(), " routers"); _loop->call_every(ROUTER_TICK_INTERVAL, weak_from_this(), [this] { Tick(); }); m_RoutePoker->Start(this); - _running.store(true); + is_running.store(true); _startedAt = Now(); - if (whitelistRouters) + if (follow_whitelist) { // do service node testing if we are in service node whitelist mode _loop->call_every(consensus::REACHABILITY_TESTING_TIMER_INTERVAL, weak_from_this(), [this] { // dont run tests if we are not running or we are stopping - if (not _running) + if (not is_running) return; // dont run tests if we think we should not test other routers // this occurs when we are deregistered or do not have the service node list // yet when we expect to have one. - if (not ShouldTestOtherRouters()) + if (not can_test_routers()) return; - auto tests = m_routerTesting.get_failing(); - if (auto maybe = m_routerTesting.next_random(this)) + auto tests = router_testing.get_failing(); + if (auto maybe = router_testing.next_random(this)) { tests.emplace_back(*maybe, 0); } @@ -1405,13 +1402,13 @@ namespace llarp LogDebug( router, " is no longer a registered service node so we remove it from the testing list"); - m_routerTesting.remove_node_from_failing(router); + router_testing.remove_node_from_failing(router); continue; } LogDebug("Establishing session to ", router, " for SN testing"); // try to make a session to this random router // this will do a dht lookup if needed - _linkManager.Connect(router); + _link_manager.connect_to(router); /* * TODO: container of pending snode test routers to be queried on @@ -1460,13 +1457,13 @@ namespace llarp }); } llarp::sys::service_manager->ready(); - return _running; + return is_running; } bool Router::IsRunning() const { - return _running; + return is_running; } llarp_time_t @@ -1484,7 +1481,7 @@ namespace llarp llarp::sys::service_manager->stopping(); Close(); log::debug(logcat, "stopping oxenmq"); - m_lmq.reset(); + _lmq.reset(); } void @@ -1494,25 +1491,25 @@ namespace llarp log::debug(logcat, "stopping links"); StopLinks(); log::debug(logcat, "saving nodedb to disk"); - nodedb()->SaveToDisk(); + node_db()->SaveToDisk(); _loop->call_later(200ms, [this] { AfterStopLinks(); }); } void Router::StopLinks() { - _linkManager.stop(); + _link_manager.stop(); } void Router::Die() { - if (!_running) + if (!is_running) return; - if (_stopping) + if (is_stopping) return; - _stopping.store(true); + is_stopping.store(true); if (log::get_level_default() != log::Level::off) log::reset_level(log::Level::info); LogWarn("stopping router hard"); @@ -1526,18 +1523,18 @@ namespace llarp void Router::Stop() { - if (!_running) + if (!is_running) { log::debug(logcat, "Stop called, but not running"); return; } - if (_stopping) + if (is_stopping) { log::debug(logcat, "Stop called, but already stopping"); return; } - _stopping.store(true); + is_stopping.store(true); if (auto level = log::get_level_default(); level > log::Level::info and level != log::Level::off) log::reset_level(log::Level::info); @@ -1559,7 +1556,7 @@ namespace llarp bool Router::HasSessionTo(const RouterID& remote) const { - return _linkManager.have_connection_to(remote); + return _link_manager.have_connection_to(remote); } std::string @@ -1571,7 +1568,7 @@ namespace llarp uint32_t Router::NextPathBuildNumber() { - return path_build_count++; + return _path_build_count++; } void @@ -1581,7 +1578,7 @@ namespace llarp auto connected = NumberOfConnectedRouters(); if (connected >= want) return; - _linkManager.connect_to_random(want); + _link_manager.connect_to_random(want); } bool @@ -1590,7 +1587,7 @@ namespace llarp LogInfo("accepting transit traffic"); paths.AllowTransit(); _dht->AllowTransit() = true; - _exitContext.AddExitEndpoint("default", m_Config->network, m_Config->dns); + _exitContext.AddExitEndpoint("default", config->network, config->dns); return true; } @@ -1604,26 +1601,26 @@ namespace llarp return false; } - if (not _rcLookupHandler.SessionIsAllowed(rc.pubkey)) + if (not _rc_lookup_handler.is_session_allowed(rc.pubkey)) { return false; } - _linkManager.Connect(rc); + _link_manager.connect_to(rc); return true; } void - Router::QueueWork(std::function func) + Router::queue_work(std::function func) { - m_lmq->job(std::move(func)); + _lmq->job(std::move(func)); } void - Router::QueueDiskIO(std::function func) + Router::queue_disk_io(std::function func) { - m_lmq->job(std::move(func), m_DiskThread); + _lmq->job(std::move(func), _disk_thread); } bool @@ -1636,7 +1633,7 @@ namespace llarp } std::optional> - Router::OurPublicIP() const + Router::public_ip() const { if (_ourAddress) return _ourAddress->getIP(); @@ -1658,58 +1655,27 @@ namespace llarp return found; } - void - Router::AddAddressToRC(AddressInfo& ai) - { - // override ip and port as needed - if (_ourAddress) - { - const auto ai_ip = ai.IP(); - const auto override_ip = _ourAddress->getIP(); - - auto ai_ip_str = var::visit([](auto&& ip) { return ip.ToString(); }, ai_ip); - auto override_ip_str = var::visit([](auto&& ip) { return ip.ToString(); }, override_ip); - - if ((not Net().IsBogonIP(ai_ip)) and (not Net().IsBogonIP(override_ip)) - and ai_ip != override_ip) - throw std::runtime_error{ - "Lokinet is bound to public IP '{}', but public-ip is set to '{}'. Either fix the " - "[router]:public-ip setting or set a bind address in the [bind] section of the " - "config."_format(ai_ip_str, override_ip_str)}; - ai.fromSockAddr(*_ourAddress); - } - if (RouterContact::BlockBogons && Net().IsBogon(ai.ip)) - throw std::runtime_error{var::visit( - [](auto&& ip) { - return "cannot use " + ip.ToString() - + " as a public ip as it is in a non routable ip range"; - }, - ai.IP())}; - LogInfo("adding address: ", ai); - _rc.addrs.push_back(ai); - } - void Router::InitInboundLinks() { - auto addrs = m_Config->links.InboundListenAddrs; - if (m_isServiceNode and addrs.empty()) + auto addrs = config->links.InboundListenAddrs; + if (is_service_node and addrs.empty()) { LogInfo("Inferring Public Address"); - auto maybe_port = m_Config->links.PublicPort; - if (m_Config->router.PublicPort and not maybe_port) - maybe_port = m_Config->router.PublicPort; + auto maybe_port = config->links.PublicPort; + if (config->router.PublicPort and not maybe_port) + maybe_port = config->router.PublicPort; if (not maybe_port) maybe_port = net::port_t::from_host(constants::DefaultInboundIWPPort); - if (auto maybe_addr = Net().MaybeInferPublicAddr(*maybe_port)) + if (auto maybe_addr = net().MaybeInferPublicAddr(*maybe_port)) { LogInfo("Public Address looks to be ", *maybe_addr); addrs.emplace_back(std::move(*maybe_addr)); } } - if (m_isServiceNode and addrs.empty()) + if (is_service_node and addrs.empty()) throw std::runtime_error{"we are a service node and we have no inbound links configured"}; // create inbound links, if we are a service node @@ -1718,7 +1684,7 @@ namespace llarp if (bind_addr.getPort() == 0) throw std::invalid_argument{"inbound link cannot use port 0"}; - if (Net().IsWildcardAddress(bind_addr.getIP())) + if (net().IsWildcardAddress(bind_addr.getIP())) { if (auto maybe_ip = OurPublicIP()) bind_addr.setIP(*maybe_ip); @@ -1741,9 +1707,9 @@ namespace llarp void Router::InitOutboundLinks() { - auto addrs = m_Config->links.OutboundLinks; + auto addrs = config->links.OutboundLinks; if (addrs.empty()) - addrs.emplace_back(Net().Wildcard()); + addrs.emplace_back(net().Wildcard()); for (auto& bind_addr : addrs) { @@ -1754,13 +1720,13 @@ namespace llarp } const llarp::net::Platform& - Router::Net() const + Router::net() const { return *llarp::net::Platform::Default_ptr(); } void - Router::MessageSent(const RouterID& remote, SendStatus status) + Router::message_sent(const RouterID& remote, SendStatus status) { if (status == SendStatus::Success) { @@ -1773,7 +1739,7 @@ namespace llarp } void - Router::HandleRouterEvent(tooling::RouterEventPtr event) const + Router::handle_router_event(tooling::RouterEventPtr event) const { LogDebug(event->ToString()); } diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index 7090462cc..09aa4885d 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -1,7 +1,5 @@ #pragma once -#include "abstractrouter.hpp" - #include #include #include @@ -12,13 +10,14 @@ #include #include #include -#include #include #include #include #include #include #include +#include +#include #include "outbound_message_handler.hpp" #include "rc_gossiper.hpp" #include "rc_lookup_handler.hpp" @@ -52,7 +51,7 @@ namespace libquic = oxen::quic; namespace llarp { - class RouteManager final /* : public AbstractRouter */ + class RouteManager final /* : public Router */ { public: std::shared_ptr @@ -62,198 +61,273 @@ namespace llarp std::shared_ptr ep; }; - struct Router final : public AbstractRouter + struct Router : std::enable_shared_from_this { - llarp_time_t _lastPump = 0s; - bool ready; + private: + llarp_time_t last_pump = 0s; // transient iwp encryption key fs::path transport_keyfile; - // long term identity key - fs::path ident_keyfile; - + fs::path identity_keyfile; fs::path encryption_keyfile; - // path to write our self signed rc to fs::path our_rc_file; - // use file based logging? - bool m_UseFileLogging = false; - + bool use_file_logging = false; // our router contact - RouterContact _rc; - + RouterContact router_contact; /// should we obey the service node whitelist? - bool whitelistRouters = false; + bool follow_whitelist = false; + std::shared_ptr _lmq; + path::BuildLimiter _pathbuild_limiter; + std::shared_ptr loop_wakeup; + + std::atomic is_stopping; + std::atomic is_running; + + int _outbound_udp_socket = -1; + bool is_service_node = false; + + std::optional _ourAddress; + oxen::quic::Address local; + + EventLoop_ptr _loop; + std::shared_ptr _vpn; + path::PathContext paths; + exit::Context _exitContext; + SecretKey _identity; + SecretKey _encryption; + std::shared_ptr _dht; + std::shared_ptr _node_db; + llarp_time_t _startedAt; + const oxenmq::TaggedThreadID _disk_thread; + oxen::quic::Network _net; - LMQ_ptr m_lmq; + llarp_time_t _last_stats_report = 0s; + llarp_time_t next_decomm_warning = time_now_ms() + 15s; + std::shared_ptr _key_manager; + std::shared_ptr _peer_db; + std::shared_ptr _config; + uint32_t _path_build_count = 0; - path::BuildLimiter m_PathBuildLimiter; + consensus::reachability_testing router_testing; - std::shared_ptr m_Pump; + bool + should_report_stats(llarp_time_t now) const; + + void + report_stats(); + + bool + update_rc(bool rotateKeys = false); + + bool + from_config(const Config& conf); + + void + message_sent(const RouterID& remote, SendStatus status); + + bool + insufficient_peers() const; + + protected: + void + handle_router_event(tooling::RouterEventPtr event) const; + + virtual bool + disableGossipingRC_TestingOnly() + { + return false; + }; + + public: + std::shared_ptr + config() const + { + return _config; + } path::BuildLimiter& - pathBuildLimiter() override + pathbuild_limiter() { - return m_PathBuildLimiter; + return _pathbuild_limiter; } const llarp::net::Platform& - Net() const override; + net() const; - const LMQ_ptr& - lmq() const override + const std::shared_ptr& + lmq() const { - return m_lmq; + return _lmq; } const std::shared_ptr& - RpcClient() const override + rpc_client() const { - return m_lokidRpcClient; + return _rpc_client; } std::shared_ptr - dht() const override + dht() const { return _dht; } - std::optional> - OurPublicIP() const override; - - util::StatusObject - ExtractStatus() const override; - - util::StatusObject - ExtractSummaryStatus() const override; - - const std::shared_ptr& - nodedb() const override + // TOFIX: THIS + OutboundMessageHandler& + outboundMessageHandler() { - return _nodedb; + return _outboundMessageHandler; } - const path::PathContext& - pathContext() const override + LinkManager& + link_manager() { - return paths; + return _link_manager; } - path::PathContext& - pathContext() override + RCLookupHandler& + rc_lookup_handler() { - return paths; + return _rc_lookup_handler; } - const RouterContact& - rc() const override + std::shared_ptr + peer_db() { - return _rc; + return _peer_db; } - void - ModifyOurRC(std::function(RouterContact)> modify) override; - - void - SetRouterWhitelist( - const std::vector& whitelist, - const std::vector& greylist, - const std::vector& unfunded) override; - - std::unordered_set - GetRouterWhitelist() const override + inline int + outbound_udp_socket() const { - return _rcLookupHandler.Whitelist(); + return _outbound_udp_socket; } exit::Context& - exitContext() override + exitContext() { return _exitContext; } const std::shared_ptr& - keyManager() const override + key_manager() const { - return m_keyManager; + return _key_manager; } const SecretKey& - identity() const override + identity() const { return _identity; } const SecretKey& - encryption() const override + encryption() const { return _encryption; } Profiling& - routerProfiling() override + router_profiling() { - return _routerProfiling; + return _router_profiling; } const EventLoop_ptr& - loop() const override + loop() const { return _loop; } vpn::Platform* - GetVPNPlatform() const override + vpn_platform() const + { + return _vpn.get(); + } + + const std::shared_ptr& + node_db() const + { + return _node_db; + } + + path::PathContext& + path_context() { - return _vpnPlatform.get(); + return paths; + } + + const RouterContact& + rc() const + { + return router_contact; + } + + std::optional> + public_ip() const; + + util::StatusObject + ExtractStatus() const; + + util::StatusObject + ExtractSummaryStatus() const; + + std::unordered_set + router_whitelist() const + { + return _rc_lookup_handler.whitelist(); + } + + void + modify_rc(std::function(RouterContact)> modify); + + void + set_router_whitelist( + const std::vector& whitelist, + const std::vector& greylist, + const std::vector& unfunded); + + template + void + notify_router_event([[maybe_unused]] Params&&... args) const + { + // TODO: no-op when appropriate + auto event = std::make_unique(args...); + handle_router_event(std::move(event)); } void - QueueWork(std::function func) override; + queue_work(std::function func); void - QueueDiskIO(std::function func) override; + queue_disk_io(std::function func); /// return true if we look like we are a decommissioned service node bool - LooksDecommissioned() const; + appear_decommed() const; /// return true if we look like we are a registered, fully-staked service node (either active or /// decommissioned). This condition determines when we are allowed to (and attempt to) connect /// to other peers when running as a service node. bool - LooksFunded() const; + appear_funded() const; /// return true if we a registered service node; not that this only requires a partial stake, /// and does not imply that this service node is *active* or fully funded. bool - LooksRegistered() const; + appear_registered() const; /// return true if we look like we are allowed and able to test other routers bool - ShouldTestOtherRouters() const; - - std::optional _ourAddress; - oxen::quic::Address local; - - EventLoop_ptr _loop; - std::shared_ptr _vpnPlatform; - path::PathContext paths; - exit::Context _exitContext; - SecretKey _identity; - SecretKey _encryption; - std::shared_ptr _dht; - std::shared_ptr _nodedb; - llarp_time_t _startedAt; - const oxenmq::TaggedThreadID m_DiskThread; - oxen::quic::Network _net; + can_test_routers() const; llarp_time_t - Uptime() const override; + Uptime() const; bool - Sign(Signature& sig, const llarp_buffer_t& buf) const override; + Sign(Signature& sig, const llarp_buffer_t& buf) const; /// how often do we resign our RC? milliseconds. // TODO: make configurable @@ -268,13 +342,13 @@ namespace llarp service::Context _hiddenServiceContext; service::Context& - hiddenServiceContext() override + hiddenServiceContext() { return _hiddenServiceContext; } const service::Context& - hiddenServiceContext() const override + hiddenServiceContext() const { return _hiddenServiceContext; } @@ -284,13 +358,13 @@ namespace llarp std::function _onDown; void - SetDownHook(std::function hook) override + SetDownHook(std::function hook) { _onDown = hook; } bool - LooksAlive() const override + LooksAlive() const { const llarp_time_t now = Now(); return now <= _lastTick || (now - _lastTick) <= llarp_time_t{30000}; @@ -300,7 +374,7 @@ namespace llarp BootstrapList bootstrapRCList; const std::shared_ptr& - routePoker() const override + routePoker() const { return m_RoutePoker; } @@ -308,7 +382,7 @@ namespace llarp std::shared_ptr m_RoutePoker; void - TriggerPump() override; + TriggerPump(); void PumpLL(); @@ -317,63 +391,32 @@ namespace llarp const llarp_time_t _randomStartDelay; - std::shared_ptr m_lokidRpcClient; + std::shared_ptr _rpc_client; oxenmq::address lokidRPCAddr; - Profiling _routerProfiling; + Profiling _router_profiling; fs::path _profilesFile; OutboundMessageHandler _outboundMessageHandler; - LinkManager _linkManager{*this}; - RCLookupHandler _rcLookupHandler; + LinkManager _link_manager{*this}; + RCLookupHandler _rc_lookup_handler; RCGossiper _rcGossiper; std::string - status_line() override; + status_line(); - using Clock_t = std::chrono::steady_clock; - using TimePoint_t = Clock_t::time_point; + using TimePoint_t = std::chrono::steady_clock::time_point; TimePoint_t m_NextExploreAt; - OutboundMessageHandler& - outboundMessageHandler() override - { - return _outboundMessageHandler; - } - - LinkManager& - linkManager() override - { - return _linkManager; - } - - RCLookupHandler& - rcLookupHandler() override - { - return _rcLookupHandler; - } - - std::shared_ptr - peerDb() override - { - return m_peerDb; - } - - inline int - OutboundUDPSocket() const override - { - return m_OutboundUDPSocket; - } - void - GossipRCIfNeeded(const RouterContact rc) override; + GossipRCIfNeeded(const RouterContact rc); explicit Router(EventLoop_ptr loop, std::shared_ptr vpnPlatform); - ~Router() override; + ~Router(); bool - HandleRecvLinkMessageBuffer(AbstractLinkSession* from, const llarp_buffer_t& msg) override; + HandleRecvLinkMessageBuffer(AbstractLinkSession* from, const llarp_buffer_t& msg); void InitInboundLinks(); @@ -382,7 +425,7 @@ namespace llarp InitOutboundLinks(); bool - GetRandomGoodRouter(RouterID& r) override; + GetRandomGoodRouter(RouterID& r); /// initialize us as a service node /// return true on success @@ -390,47 +433,47 @@ namespace llarp InitServiceNode(); bool - IsRunning() const override; + IsRunning() const; /// return true if we are running in service node mode bool - IsServiceNode() const override; + IsServiceNode() const; std::optional - OxendErrorState() const override; + OxendErrorState() const; void Close(); bool - Configure(std::shared_ptr conf, bool isSNode, std::shared_ptr nodedb) override; + Configure(std::shared_ptr conf, bool isSNode, std::shared_ptr nodedb); bool - StartRpcServer() override; + StartRpcServer(); void - Freeze() override; + Freeze(); void - Thaw() override; + Thaw(); bool - Run() override; + Run(); /// stop running the router logic gracefully void - Stop() override; + Stop(); /// non graceful stop router void - Die() override; + Die(); /// close all sessions and shutdown all links void StopLinks(); void - PersistSessionUntil(const RouterID& remote, llarp_time_t until) override; + PersistSessionUntil(const RouterID& remote, llarp_time_t until); bool EnsureIdentity(); @@ -439,9 +482,10 @@ namespace llarp EnsureEncryptionKey(); bool - SessionToRouterAllowed(const RouterID& router) const override; + SessionToRouterAllowed(const RouterID& router) const; + bool - PathToRouterAllowed(const RouterID& router) const override; + PathToRouterAllowed(const RouterID& router) const; void HandleSaveRC() const; @@ -451,10 +495,10 @@ namespace llarp /// return true if we are a client with an exit configured bool - HasClientExit() const override; + HasClientExit() const; const byte_t* - pubkey() const override + pubkey() const { return seckey_topublic(_identity); } @@ -463,7 +507,7 @@ namespace llarp try_connect(fs::path rcfile); bool - TryConnectAsync(RouterContact rc, uint16_t tries) override; + TryConnectAsync(RouterContact rc, uint16_t tries); /// send to remote router or queue for sending /// returns false on overflow @@ -472,27 +516,27 @@ namespace llarp /// MUST be called in the logic thread bool SendToOrQueue( - const RouterID& remote, const AbstractLinkMessage& msg, SendStatusHandler handler) override; + const RouterID& remote, const AbstractLinkMessage& msg, SendStatusHandler handler); void - ForEachPeer(std::function visit, bool randomize = false) - const override; + ForEachPeer( + std::function visit, bool randomize = false) const; void ForEachPeer(std::function visit); - bool IsBootstrapNode(RouterID) const override; + bool IsBootstrapNode(RouterID) const; /// check if newRc matches oldRC and update local rc for this remote contact /// if valid /// returns true on valid and updated /// returns false otherwise bool - CheckRenegotiateValid(RouterContact newRc, RouterContact oldRC) override; + CheckRenegotiateValid(RouterContact newRc, RouterContact oldRC); /// called by link when a remote session has no more sessions open void - SessionClosed(RouterID remote) override; + SessionClosed(RouterID remote); /// called by link when an unestablished connection times out void @@ -507,7 +551,7 @@ namespace llarp Tick(); llarp_time_t - Now() const override + Now() const { return llarp::time_now_ms(); } @@ -517,103 +561,41 @@ namespace llarp /// return false bool ParseRoutingMessageBuffer( - const llarp_buffer_t& buf, - routing::AbstractRoutingMessageHandler* h, - const PathID_t& rxid) override; + const llarp_buffer_t& buf, routing::AbstractRoutingMessageHandler* h, const PathID_t& rxid); void - ConnectToRandomRouters(int N) override; + ConnectToRandomRouters(int N); /// count the number of unique service nodes connected via pubkey size_t - NumberOfConnectedRouters() const override; + NumberOfConnectedRouters() const; /// count the number of unique clients connected by pubkey size_t - NumberOfConnectedClients() const override; + NumberOfConnectedClients() const; bool - GetRandomConnectedRouter(RouterContact& result) const override; + GetRandomConnectedRouter(RouterContact& result) const; void - HandleDHTLookupForExplore(RouterID remote, const std::vector& results) override; + HandleDHTLookupForExplore(RouterID remote, const std::vector& results); void - LookupRouter(RouterID remote, RouterLookupHandler resultHandler) override; + LookupRouter(RouterID remote, RouterLookupHandler resultHandler); bool - HasSessionTo(const RouterID& remote) const override; + HasSessionTo(const RouterID& remote) const; std::string - ShortName() const override; + ShortName() const; uint32_t - NextPathBuildNumber() override; + NextPathBuildNumber(); void AfterStopLinks(); void AfterStopIssued(); - - std::shared_ptr m_Config; - - std::shared_ptr - GetConfig() const override - { - return m_Config; - } - - int m_OutboundUDPSocket = -1; - - private: - std::atomic _stopping; - std::atomic _running; - - bool m_isServiceNode = false; - - // Delay warning about being decommed/dereged until we've had enough time to sync up with oxend - static constexpr auto DECOMM_WARNING_STARTUP_DELAY = 15s; - - llarp_time_t m_LastStatsReport = 0s; - llarp_time_t m_NextDecommissionWarn = time_now_ms() + DECOMM_WARNING_STARTUP_DELAY; - std::shared_ptr m_keyManager; - std::shared_ptr m_peerDb; - - uint32_t path_build_count = 0; - - consensus::reachability_testing m_routerTesting; - - bool - ShouldReportStats(llarp_time_t now) const; - - void - ReportStats(); - - bool - UpdateOurRC(bool rotateKeys = false); - - bool - FromConfig(const Config& conf); - - void - MessageSent(const RouterID& remote, SendStatus status); - - bool - TooFewPeers() const; - - void - AddAddressToRC(AddressInfo& ai); - - protected: - void - HandleRouterEvent(tooling::RouterEventPtr event) const override; - - virtual bool - disableGossipingRC_TestingOnly() - { - return false; - }; }; - } // namespace llarp diff --git a/llarp/router_contact.hpp b/llarp/router_contact.hpp index ed6a8dcd8..6fcd021ae 100644 --- a/llarp/router_contact.hpp +++ b/llarp/router_contact.hpp @@ -2,7 +2,6 @@ #include "llarp/constants/version.hpp" #include "llarp/crypto/types.hpp" -#include "llarp/net/address_info.hpp" #include "llarp/net/exit_info.hpp" #include "llarp/util/aligned.hpp" #include "llarp/util/bencode.hpp" @@ -11,6 +10,8 @@ #include "llarp/dns/srv_data.hpp" +#include + #include #include #include @@ -75,7 +76,7 @@ namespace llarp } // advertised addresses - std::vector addrs; + oxen::quic::Address addr; // network identifier NetID netID; // public encryption public key @@ -124,7 +125,7 @@ namespace llarp bool operator==(const RouterContact& other) const { - return addrs == other.addrs && enckey == other.enckey && pubkey == other.pubkey + return addr == other.addr && enckey == other.enckey && pubkey == other.pubkey && signature == other.signature && nickname == other.nickname && last_updated == other.last_updated && netID == other.netID; } diff --git a/llarp/routing/handler.hpp b/llarp/routing/handler.hpp index adca3cdd6..e28a1f4c0 100644 --- a/llarp/routing/handler.hpp +++ b/llarp/routing/handler.hpp @@ -4,7 +4,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; namespace dht { @@ -34,42 +34,42 @@ namespace llarp struct AbstractRoutingMessageHandler { virtual bool - HandleObtainExitMessage(const ObtainExitMessage& msg, AbstractRouter* r) = 0; + HandleObtainExitMessage(const ObtainExitMessage& msg, Router* r) = 0; virtual bool - HandleGrantExitMessage(const GrantExitMessage& msg, AbstractRouter* r) = 0; + HandleGrantExitMessage(const GrantExitMessage& msg, Router* r) = 0; virtual bool - HandleRejectExitMessage(const RejectExitMessage& msg, AbstractRouter* r) = 0; + HandleRejectExitMessage(const RejectExitMessage& msg, Router* r) = 0; virtual bool - HandleTransferTrafficMessage(const TransferTrafficMessage& msg, AbstractRouter* r) = 0; + HandleTransferTrafficMessage(const TransferTrafficMessage& msg, Router* r) = 0; virtual bool - HandleUpdateExitMessage(const UpdateExitMessage& msg, AbstractRouter* r) = 0; + HandleUpdateExitMessage(const UpdateExitMessage& msg, Router* r) = 0; virtual bool - HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage& msg, AbstractRouter* r) = 0; + HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage& msg, Router* r) = 0; virtual bool - HandleCloseExitMessage(const CloseExitMessage& msg, AbstractRouter* r) = 0; + HandleCloseExitMessage(const CloseExitMessage& msg, Router* r) = 0; virtual bool - HandleDataDiscardMessage(const DataDiscardMessage& msg, AbstractRouter* r) = 0; + HandleDataDiscardMessage(const DataDiscardMessage& msg, Router* r) = 0; virtual bool - HandlePathTransferMessage(const PathTransferMessage& msg, AbstractRouter* r) = 0; + HandlePathTransferMessage(const PathTransferMessage& msg, Router* r) = 0; virtual bool HandleHiddenServiceFrame(const service::ProtocolFrameMessage& msg) = 0; virtual bool - HandlePathConfirmMessage(const PathConfirmMessage& msg, AbstractRouter* r) = 0; + HandlePathConfirmMessage(const PathConfirmMessage& msg, Router* r) = 0; virtual bool - HandlePathLatencyMessage(const PathLatencyMessage& msg, AbstractRouter* r) = 0; + HandlePathLatencyMessage(const PathLatencyMessage& msg, Router* r) = 0; virtual bool - HandleDHTMessage(const dht::AbstractDHTMessage& msg, AbstractRouter* r) = 0; + HandleDHTMessage(const dht::AbstractDHTMessage& msg, Router* r) = 0; }; using MessageHandler_ptr = std::shared_ptr; diff --git a/llarp/routing/message.hpp b/llarp/routing/message.hpp index 5a4700bb7..ac04d30b3 100644 --- a/llarp/routing/message.hpp +++ b/llarp/routing/message.hpp @@ -13,7 +13,7 @@ namespace namespace llarp { - struct AbstractRouter; + struct Router; namespace routing { struct AbstractRoutingMessageHandler; @@ -35,7 +35,7 @@ namespace llarp bt_encode() const override = 0; virtual bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const = 0; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const = 0; virtual void clear() = 0; diff --git a/llarp/routing/message_parser.cpp b/llarp/routing/message_parser.cpp index 5f7e5b537..64b214d13 100644 --- a/llarp/routing/message_parser.cpp +++ b/llarp/routing/message_parser.cpp @@ -106,10 +106,7 @@ namespace llarp::routing bool InboundMessageParser::ParseMessageBuffer( - const llarp_buffer_t& buf, - AbstractRoutingMessageHandler* h, - const PathID_t& from, - AbstractRouter* r) + const llarp_buffer_t& buf, AbstractRoutingMessageHandler* h, const PathID_t& from, Router* r) { bool result = false; msg = nullptr; diff --git a/llarp/routing/message_parser.hpp b/llarp/routing/message_parser.hpp index 968260224..0ee7a5cee 100644 --- a/llarp/routing/message_parser.hpp +++ b/llarp/routing/message_parser.hpp @@ -7,7 +7,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; struct PathID_t; namespace routing @@ -25,7 +25,7 @@ namespace llarp const llarp_buffer_t& buf, AbstractRoutingMessageHandler* handler, const PathID_t& from, - AbstractRouter* r); + Router* r); bool operator()(llarp_buffer_t* buffer, llarp_buffer_t* key); diff --git a/llarp/routing/path_confirm_message.cpp b/llarp/routing/path_confirm_message.cpp index 3b41386e7..268e2e4b8 100644 --- a/llarp/routing/path_confirm_message.cpp +++ b/llarp/routing/path_confirm_message.cpp @@ -47,7 +47,7 @@ namespace llarp::routing } bool - PathConfirmMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + PathConfirmMessage::handle_message(AbstractRoutingMessageHandler* h, Router* 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 986f0f967..d7f4f1624 100644 --- a/llarp/routing/path_confirm_message.hpp +++ b/llarp/routing/path_confirm_message.hpp @@ -20,7 +20,7 @@ namespace llarp::routing decode_key(const llarp_buffer_t& key, llarp_buffer_t* val) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; void clear() override diff --git a/llarp/routing/path_dht_message.cpp b/llarp/routing/path_dht_message.cpp index 3f5bddb96..bca3ad5e9 100644 --- a/llarp/routing/path_dht_message.cpp +++ b/llarp/routing/path_dht_message.cpp @@ -1,6 +1,6 @@ #include "path_dht_message.hpp" -#include +#include #include "handler.hpp" namespace llarp::routing @@ -58,7 +58,7 @@ namespace llarp::routing /// (e.g. dht::IMessage::HandleMessage()) in-place and is the case where a /// client receives a DHT message bool - PathDHTMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + PathDHTMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { // set source as us const llarp::dht::Key_t us(r->pubkey()); diff --git a/llarp/routing/path_dht_message.hpp b/llarp/routing/path_dht_message.hpp index af8b473aa..365a2e837 100644 --- a/llarp/routing/path_dht_message.hpp +++ b/llarp/routing/path_dht_message.hpp @@ -20,7 +20,7 @@ namespace llarp::routing bt_encode() const override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; void clear() override diff --git a/llarp/routing/path_latency_message.cpp b/llarp/routing/path_latency_message.cpp index 4715311ee..b70b7041c 100644 --- a/llarp/routing/path_latency_message.cpp +++ b/llarp/routing/path_latency_message.cpp @@ -43,7 +43,7 @@ namespace llarp::routing } bool - PathLatencyMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + PathLatencyMessage::handle_message(AbstractRoutingMessageHandler* h, Router* 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 3a5ec3473..fdbfc42ed 100644 --- a/llarp/routing/path_latency_message.hpp +++ b/llarp/routing/path_latency_message.hpp @@ -25,6 +25,6 @@ namespace llarp::routing } bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; }; } // namespace llarp::routing diff --git a/llarp/routing/path_transfer_message.cpp b/llarp/routing/path_transfer_message.cpp index f210b0eb0..fd840997d 100644 --- a/llarp/routing/path_transfer_message.cpp +++ b/llarp/routing/path_transfer_message.cpp @@ -44,7 +44,7 @@ namespace llarp::routing } bool - PathTransferMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + PathTransferMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandlePathTransferMessage(*this, r); } diff --git a/llarp/routing/path_transfer_message.hpp b/llarp/routing/path_transfer_message.hpp index 2ede43560..d156ef2ff 100644 --- a/llarp/routing/path_transfer_message.hpp +++ b/llarp/routing/path_transfer_message.hpp @@ -28,7 +28,7 @@ namespace llarp::routing bt_encode() const override; bool - handle_message(AbstractRoutingMessageHandler*, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler*, Router* r) const override; void clear() override diff --git a/llarp/routing/transfer_traffic_message.cpp b/llarp/routing/transfer_traffic_message.cpp index c46d3acb0..3e2737710 100644 --- a/llarp/routing/transfer_traffic_message.cpp +++ b/llarp/routing/transfer_traffic_message.cpp @@ -65,7 +65,7 @@ namespace llarp::routing } bool - TransferTrafficMessage::handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const + TransferTrafficMessage::handle_message(AbstractRoutingMessageHandler* h, Router* r) const { return h->HandleTransferTrafficMessage(*this, r); } diff --git a/llarp/routing/transfer_traffic_message.hpp b/llarp/routing/transfer_traffic_message.hpp index 14f24ef50..890c178f4 100644 --- a/llarp/routing/transfer_traffic_message.hpp +++ b/llarp/routing/transfer_traffic_message.hpp @@ -44,6 +44,6 @@ namespace llarp::routing decode_key(const llarp_buffer_t& k, llarp_buffer_t* val) override; bool - handle_message(AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(AbstractRoutingMessageHandler* h, Router* r) const override; }; } // namespace llarp::routing diff --git a/llarp/rpc/lokid_rpc_client.cpp b/llarp/rpc/lokid_rpc_client.cpp index 6f409f88e..0db01fd66 100644 --- a/llarp/rpc/lokid_rpc_client.cpp +++ b/llarp/rpc/lokid_rpc_client.cpp @@ -3,467 +3,461 @@ #include #include -#include +#include #include #include #include #include -namespace llarp +namespace llarp::rpc { - namespace rpc + static constexpr oxenmq::LogLevel + toLokiMQLogLevel(log::Level level) { - static constexpr oxenmq::LogLevel - toLokiMQLogLevel(log::Level level) + switch (level) { - switch (level) - { - case log::Level::critical: - return oxenmq::LogLevel::fatal; - case log::Level::err: - return oxenmq::LogLevel::error; - case log::Level::warn: - return oxenmq::LogLevel::warn; - case log::Level::info: - return oxenmq::LogLevel::info; - case log::Level::debug: - return oxenmq::LogLevel::debug; - case log::Level::trace: - case log::Level::off: - default: - return oxenmq::LogLevel::trace; - } + case log::Level::critical: + return oxenmq::LogLevel::fatal; + case log::Level::err: + return oxenmq::LogLevel::error; + case log::Level::warn: + return oxenmq::LogLevel::warn; + case log::Level::info: + return oxenmq::LogLevel::info; + case log::Level::debug: + return oxenmq::LogLevel::debug; + case log::Level::trace: + case log::Level::off: + default: + return oxenmq::LogLevel::trace; } + } - LokidRpcClient::LokidRpcClient(LMQ_ptr lmq, std::weak_ptr r) - : m_lokiMQ{std::move(lmq)}, m_Router{std::move(r)} - { - // m_lokiMQ->log_level(toLokiMQLogLevel(LogLevel::Instance().curLevel)); + LokidRpcClient::LokidRpcClient(std::shared_ptr lmq, std::weak_ptr r) + : m_lokiMQ{std::move(lmq)}, m_Router{std::move(r)} + { + // m_lokiMQ->log_level(toLokiMQLogLevel(LogLevel::Instance().curLevel)); - // new block handler - m_lokiMQ->add_category("notify", oxenmq::Access{oxenmq::AuthLevel::none}) - .add_command("block", [this](oxenmq::Message& m) { HandleNewBlock(m); }); + // new block handler + m_lokiMQ->add_category("notify", oxenmq::Access{oxenmq::AuthLevel::none}) + .add_command("block", [this](oxenmq::Message& m) { HandleNewBlock(m); }); - // TODO: proper auth here - auto lokidCategory = m_lokiMQ->add_category("lokid", oxenmq::Access{oxenmq::AuthLevel::none}); - lokidCategory.add_request_command( - "get_peer_stats", [this](oxenmq::Message& m) { HandleGetPeerStats(m); }); - m_UpdatingList = false; - } + // TODO: proper auth here + auto lokidCategory = m_lokiMQ->add_category("lokid", oxenmq::Access{oxenmq::AuthLevel::none}); + lokidCategory.add_request_command( + "get_peer_stats", [this](oxenmq::Message& m) { HandleGetPeerStats(m); }); + m_UpdatingList = false; + } - void - LokidRpcClient::ConnectAsync(oxenmq::address url) + void + LokidRpcClient::ConnectAsync(oxenmq::address url) + { + if (auto router = m_Router.lock()) { - if (auto router = m_Router.lock()) + if (not router->IsServiceNode()) { - if (not router->IsServiceNode()) - { - throw std::runtime_error("we cannot talk to lokid while not a service node"); - } - LogInfo("connecting to lokid via LMQ at ", url.full_address()); - m_Connection = m_lokiMQ->connect_remote( - url, - [](oxenmq::ConnectionID) {}, - [self = shared_from_this(), url](oxenmq::ConnectionID, std::string_view f) { - llarp::LogWarn("Failed to connect to lokid: ", f); - if (auto router = self->m_Router.lock()) - { - router->loop()->call([self, url]() { self->ConnectAsync(url); }); - } - }); + throw std::runtime_error("we cannot talk to lokid while not a service node"); } + LogInfo("connecting to lokid via LMQ at ", url.full_address()); + m_Connection = m_lokiMQ->connect_remote( + url, + [](oxenmq::ConnectionID) {}, + [self = shared_from_this(), url](oxenmq::ConnectionID, std::string_view f) { + llarp::LogWarn("Failed to connect to lokid: ", f); + if (auto router = self->m_Router.lock()) + { + router->loop()->call([self, url]() { self->ConnectAsync(url); }); + } + }); } + } - void - LokidRpcClient::Command(std::string_view cmd) + void + LokidRpcClient::Command(std::string_view cmd) + { + LogDebug("lokid command: ", cmd); + m_lokiMQ->send(*m_Connection, std::move(cmd)); + } + + void + LokidRpcClient::HandleNewBlock(oxenmq::Message& msg) + { + if (msg.data.size() != 2) { - LogDebug("lokid command: ", cmd); - m_lokiMQ->send(*m_Connection, std::move(cmd)); + LogError( + "we got an invalid new block notification with ", + msg.data.size(), + " parts instead of 2 parts so we will not update the list of service nodes"); + return; // bail } - - void - LokidRpcClient::HandleNewBlock(oxenmq::Message& msg) + try { - if (msg.data.size() != 2) - { - LogError( - "we got an invalid new block notification with ", - msg.data.size(), - " parts instead of 2 parts so we will not update the list of service nodes"); - return; // bail - } - try - { - m_BlockHeight = std::stoll(std::string{msg.data[0]}); - } - catch (std::exception& ex) - { - LogError("bad block height: ", ex.what()); - return; // bail - } - - LogDebug("new block at height ", m_BlockHeight); - // don't upadate on block notification if an update is pending - if (not m_UpdatingList) - UpdateServiceNodeList(); + m_BlockHeight = std::stoll(std::string{msg.data[0]}); } - - void - LokidRpcClient::UpdateServiceNodeList() + catch (std::exception& ex) { - if (m_UpdatingList.exchange(true)) - return; // update already in progress - - nlohmann::json request{ - {"fields", - { - {"pubkey_ed25519", true}, - {"service_node_pubkey", true}, - {"funded", true}, - {"active", true}, - {"block_hash", true}, - }}, - }; - if (!m_LastUpdateHash.empty()) - request["poll_block_hash"] = m_LastUpdateHash; - - Request( - "rpc.get_service_nodes", - [self = shared_from_this()](bool success, std::vector data) { - if (not success) - LogWarn("failed to update service node list"); - else if (data.size() < 2) - LogWarn("oxend gave empty reply for service node list"); - else + LogError("bad block height: ", ex.what()); + return; // bail + } + + LogDebug("new block at height ", m_BlockHeight); + // don't upadate on block notification if an update is pending + if (not m_UpdatingList) + UpdateServiceNodeList(); + } + + void + LokidRpcClient::UpdateServiceNodeList() + { + if (m_UpdatingList.exchange(true)) + return; // update already in progress + + nlohmann::json request{ + {"fields", + { + {"pubkey_ed25519", true}, + {"service_node_pubkey", true}, + {"funded", true}, + {"active", true}, + {"block_hash", true}, + }}, + }; + if (!m_LastUpdateHash.empty()) + request["poll_block_hash"] = m_LastUpdateHash; + + Request( + "rpc.get_service_nodes", + [self = shared_from_this()](bool success, std::vector data) { + if (not success) + LogWarn("failed to update service node list"); + else if (data.size() < 2) + LogWarn("oxend gave empty reply for service node list"); + else + { + try { - try + auto json = nlohmann::json::parse(std::move(data[1])); + if (json.at("status") != "OK") + throw std::runtime_error{"get_service_nodes did not return 'OK' status"}; + if (auto it = json.find("unchanged"); + it != json.end() and it->is_boolean() and it->get()) + LogDebug("service node list unchanged"); + else { - auto json = nlohmann::json::parse(std::move(data[1])); - if (json.at("status") != "OK") - throw std::runtime_error{"get_service_nodes did not return 'OK' status"}; - if (auto it = json.find("unchanged"); - it != json.end() and it->is_boolean() and it->get()) - LogDebug("service node list unchanged"); + self->HandleNewServiceNodeList(json.at("service_node_states")); + if (auto it = json.find("block_hash"); it != json.end() and it->is_string()) + self->m_LastUpdateHash = it->get(); else - { - self->HandleNewServiceNodeList(json.at("service_node_states")); - if (auto it = json.find("block_hash"); it != json.end() and it->is_string()) - self->m_LastUpdateHash = it->get(); - else - self->m_LastUpdateHash.clear(); - } - } - catch (const std::exception& ex) - { - LogError("failed to process service node list: ", ex.what()); + self->m_LastUpdateHash.clear(); } } + catch (const std::exception& ex) + { + LogError("failed to process service node list: ", ex.what()); + } + } - // set down here so that the 1) we don't start updating until we're completely finished - // with the previous update; and 2) so that m_UpdatingList also guards m_LastUpdateHash - self->m_UpdatingList = false; - }, - request.dump()); - } + // set down here so that the 1) we don't start updating until we're completely finished + // with the previous update; and 2) so that m_UpdatingList also guards m_LastUpdateHash + self->m_UpdatingList = false; + }, + request.dump()); + } - void - LokidRpcClient::StartPings() - { - constexpr auto PingInterval = 30s; + void + LokidRpcClient::StartPings() + { + constexpr auto PingInterval = 30s; - auto router = m_Router.lock(); - if (not router) - return; + auto router = m_Router.lock(); + if (not router) + return; - auto makePingRequest = router->loop()->make_caller([self = shared_from_this()]() { - // send a ping - PubKey pk{}; - auto r = self->m_Router.lock(); - if (not r) - return; // router has gone away, maybe shutting down? - - pk = r->pubkey(); - - nlohmann::json payload = { - {"pubkey_ed25519", oxenc::to_hex(pk.begin(), pk.end())}, - {"version", {VERSION[0], VERSION[1], VERSION[2]}}}; - - if (auto err = r->OxendErrorState()) - payload["error"] = *err; - - self->Request( - "admin.lokinet_ping", - [](bool success, std::vector data) { - (void)data; - LogDebug("Received response for ping. Successful: ", success); - }, - payload.dump()); - - // subscribe to block updates - self->Request("sub.block", [](bool success, std::vector data) { - if (data.empty() or not success) - { - LogError("failed to subscribe to new blocks"); - return; - } - LogDebug("subscribed to new blocks: ", data[0]); - }); - // Trigger an update on a regular timer as well in case we missed a block notify for some - // reason (e.g. oxend restarts and loses the subscription); we poll using the last known - // hash so that the poll is very cheap (basically empty) if the block hasn't advanced. - self->UpdateServiceNodeList(); - }); + auto makePingRequest = router->loop()->make_caller([self = shared_from_this()]() { + // send a ping + PubKey pk{}; + auto r = self->m_Router.lock(); + if (not r) + return; // router has gone away, maybe shutting down? - // Fire one ping off right away to get things going. - makePingRequest(); - m_lokiMQ->add_timer(std::move(makePingRequest), PingInterval); - } + pk = r->pubkey(); - void - LokidRpcClient::HandleNewServiceNodeList(const nlohmann::json& j) - { - std::unordered_map keymap; - std::vector activeNodeList, decommNodeList, unfundedNodeList; - if (not j.is_array()) - throw std::runtime_error{ - "Invalid service node list: expected array of service node states"}; + nlohmann::json payload = { + {"pubkey_ed25519", oxenc::to_hex(pk.begin(), pk.end())}, + {"version", {VERSION[0], VERSION[1], VERSION[2]}}}; - for (auto& snode : j) - { - const auto ed_itr = snode.find("pubkey_ed25519"); - if (ed_itr == snode.end() or not ed_itr->is_string()) - continue; - const auto svc_itr = snode.find("service_node_pubkey"); - if (svc_itr == snode.end() or not svc_itr->is_string()) - continue; - const auto active_itr = snode.find("active"); - if (active_itr == snode.end() or not active_itr->is_boolean()) - continue; - const bool active = active_itr->get(); - const auto funded_itr = snode.find("funded"); - if (funded_itr == snode.end() or not funded_itr->is_boolean()) - continue; - const bool funded = funded_itr->get(); - - RouterID rid; - PubKey pk; - if (not rid.FromHex(ed_itr->get()) - or not pk.FromHex(svc_itr->get())) - continue; - - keymap[rid] = pk; - (active ? activeNodeList - : funded ? decommNodeList - : unfundedNodeList) - .push_back(std::move(rid)); - } + if (auto err = r->OxendErrorState()) + payload["error"] = *err; - if (activeNodeList.empty()) - { - LogWarn("got empty service node list, ignoring."); - return; - } + self->Request( + "admin.lokinet_ping", + [](bool success, std::vector data) { + (void)data; + LogDebug("Received response for ping. Successful: ", success); + }, + payload.dump()); - // inform router about the new list - if (auto router = m_Router.lock()) - { - auto& loop = router->loop(); - loop->call([this, - active = std::move(activeNodeList), - decomm = std::move(decommNodeList), - unfunded = std::move(unfundedNodeList), - keymap = std::move(keymap), - router = std::move(router)]() mutable { - m_KeyMap = std::move(keymap); - router->SetRouterWhitelist(active, decomm, unfunded); - }); - } - else - LogWarn("Cannot update whitelist: router object has gone away"); + // subscribe to block updates + self->Request("sub.block", [](bool success, std::vector data) { + if (data.empty() or not success) + { + LogError("failed to subscribe to new blocks"); + return; + } + LogDebug("subscribed to new blocks: ", data[0]); + }); + // Trigger an update on a regular timer as well in case we missed a block notify for some + // reason (e.g. oxend restarts and loses the subscription); we poll using the last known + // hash so that the poll is very cheap (basically empty) if the block hasn't advanced. + self->UpdateServiceNodeList(); + }); + + // Fire one ping off right away to get things going. + makePingRequest(); + m_lokiMQ->add_timer(std::move(makePingRequest), PingInterval); + } + + void + LokidRpcClient::HandleNewServiceNodeList(const nlohmann::json& j) + { + std::unordered_map keymap; + std::vector activeNodeList, decommNodeList, unfundedNodeList; + if (not j.is_array()) + throw std::runtime_error{"Invalid service node list: expected array of service node states"}; + + for (auto& snode : j) + { + const auto ed_itr = snode.find("pubkey_ed25519"); + if (ed_itr == snode.end() or not ed_itr->is_string()) + continue; + const auto svc_itr = snode.find("service_node_pubkey"); + if (svc_itr == snode.end() or not svc_itr->is_string()) + continue; + const auto active_itr = snode.find("active"); + if (active_itr == snode.end() or not active_itr->is_boolean()) + continue; + const bool active = active_itr->get(); + const auto funded_itr = snode.find("funded"); + if (funded_itr == snode.end() or not funded_itr->is_boolean()) + continue; + const bool funded = funded_itr->get(); + + RouterID rid; + PubKey pk; + if (not rid.FromHex(ed_itr->get()) + or not pk.FromHex(svc_itr->get())) + continue; + + keymap[rid] = pk; + (active ? activeNodeList + : funded ? decommNodeList + : unfundedNodeList) + .push_back(std::move(rid)); } - void - LokidRpcClient::InformConnection(RouterID router, bool success) + if (activeNodeList.empty()) { - if (auto r = m_Router.lock()) - { - r->loop()->call([router, success, this]() { - if (auto itr = m_KeyMap.find(router); itr != m_KeyMap.end()) - { - const nlohmann::json request = { - {"passed", success}, {"pubkey", itr->second.ToHex()}, {"type", "lokinet"}}; - Request( - "admin.report_peer_status", - [self = shared_from_this()](bool success, std::vector) { - if (not success) - { - LogError("Failed to report connection status to oxend"); - return; - } - LogDebug("reported connection status to core"); - }, - request.dump()); - } - }); - } + LogWarn("got empty service node list, ignoring."); + return; } - SecretKey - LokidRpcClient::ObtainIdentityKey() + // inform router about the new list + if (auto router = m_Router.lock()) { - std::promise promise; - Request( - "admin.get_service_privkeys", - [self = shared_from_this(), &promise](bool success, std::vector data) { - try + auto& loop = router->loop(); + loop->call([this, + active = std::move(activeNodeList), + decomm = std::move(decommNodeList), + unfunded = std::move(unfundedNodeList), + keymap = std::move(keymap), + router = std::move(router)]() mutable { + m_KeyMap = std::move(keymap); + router->set_router_whitelist(active, decomm, unfunded); + }); + } + else + LogWarn("Cannot update whitelist: router object has gone away"); + } + + void + LokidRpcClient::InformConnection(RouterID router, bool success) + { + if (auto r = m_Router.lock()) + { + r->loop()->call([router, success, this]() { + if (auto itr = m_KeyMap.find(router); itr != m_KeyMap.end()) + { + const nlohmann::json request = { + {"passed", success}, {"pubkey", itr->second.ToHex()}, {"type", "lokinet"}}; + Request( + "admin.report_peer_status", + [self = shared_from_this()](bool success, std::vector) { + if (not success) + { + LogError("Failed to report connection status to oxend"); + return; + } + LogDebug("reported connection status to core"); + }, + request.dump()); + } + }); + } + } + + SecretKey + LokidRpcClient::ObtainIdentityKey() + { + std::promise promise; + Request( + "admin.get_service_privkeys", + [self = shared_from_this(), &promise](bool success, std::vector data) { + try + { + if (not success) { - if (not success) - { - throw std::runtime_error( - "failed to get private key request " - "failed"); - } - if (data.empty() or data.size() < 2) - { - throw std::runtime_error( - "failed to get private key request " - "data empty"); - } - const auto j = nlohmann::json::parse(data[1]); - SecretKey k; - if (not k.FromHex(j.at("service_node_ed25519_privkey").get())) - { - throw std::runtime_error("failed to parse private key"); - } - promise.set_value(k); + throw std::runtime_error( + "failed to get private key request " + "failed"); } - catch (const std::exception& e) + if (data.empty() or data.size() < 2) { - LogWarn("Caught exception while trying to request admin keys: ", e.what()); - promise.set_exception(std::current_exception()); + throw std::runtime_error( + "failed to get private key request " + "data empty"); } - catch (...) + const auto j = nlohmann::json::parse(data[1]); + SecretKey k; + if (not k.FromHex(j.at("service_node_ed25519_privkey").get())) { - LogWarn("Caught non-standard exception while trying to request admin keys"); - promise.set_exception(std::current_exception()); + throw std::runtime_error("failed to parse private key"); } - }); - auto ftr = promise.get_future(); - return ftr.get(); - } + promise.set_value(k); + } + catch (const std::exception& e) + { + LogWarn("Caught exception while trying to request admin keys: ", e.what()); + promise.set_exception(std::current_exception()); + } + catch (...) + { + LogWarn("Caught non-standard exception while trying to request admin keys"); + promise.set_exception(std::current_exception()); + } + }); + auto ftr = promise.get_future(); + return ftr.get(); + } - void - LokidRpcClient::LookupLNSNameHash( - dht::Key_t namehash, - std::function)> resultHandler) - { - LogDebug("Looking Up LNS NameHash ", namehash); - const nlohmann::json req{{"type", 2}, {"name_hash", namehash.ToHex()}}; - Request( - "rpc.lns_resolve", - [this, resultHandler](bool success, std::vector data) { - std::optional maybe = std::nullopt; - if (success) + void + LokidRpcClient::LookupLNSNameHash( + dht::Key_t namehash, std::function)> resultHandler) + { + LogDebug("Looking Up LNS NameHash ", namehash); + const nlohmann::json req{{"type", 2}, {"name_hash", namehash.ToHex()}}; + Request( + "rpc.lns_resolve", + [this, resultHandler](bool success, std::vector data) { + std::optional maybe = std::nullopt; + if (success) + { + try { - try - { - service::EncryptedName result; - const auto j = nlohmann::json::parse(data[1]); - result.ciphertext = oxenc::from_hex(j["encrypted_value"].get()); - const auto nonce = oxenc::from_hex(j["nonce"].get()); - if (nonce.size() != result.nonce.size()) - { - throw std::invalid_argument{fmt::format( - "nonce size mismatch: {} != {}", nonce.size(), result.nonce.size())}; - } - - std::copy_n(nonce.data(), nonce.size(), result.nonce.data()); - maybe = result; - } - catch (std::exception& ex) + service::EncryptedName result; + const auto j = nlohmann::json::parse(data[1]); + result.ciphertext = oxenc::from_hex(j["encrypted_value"].get()); + const auto nonce = oxenc::from_hex(j["nonce"].get()); + if (nonce.size() != result.nonce.size()) { - LogError("failed to parse response from lns lookup: ", ex.what()); + throw std::invalid_argument{fmt::format( + "nonce size mismatch: {} != {}", nonce.size(), result.nonce.size())}; } + + std::copy_n(nonce.data(), nonce.size(), result.nonce.data()); + maybe = result; } - if (auto r = m_Router.lock()) + catch (std::exception& ex) { - r->loop()->call( - [resultHandler, maybe = std::move(maybe)]() { resultHandler(std::move(maybe)); }); + LogError("failed to parse response from lns lookup: ", ex.what()); } - }, - req.dump()); + } + if (auto r = m_Router.lock()) + { + r->loop()->call( + [resultHandler, maybe = std::move(maybe)]() { resultHandler(std::move(maybe)); }); + } + }, + req.dump()); + } + + void + LokidRpcClient::HandleGetPeerStats(oxenmq::Message& msg) + { + LogInfo("Got request for peer stats (size: ", msg.data.size(), ")"); + for (auto str : msg.data) + { + LogInfo(" :", str); } - void - LokidRpcClient::HandleGetPeerStats(oxenmq::Message& msg) + if (auto router = m_Router.lock()) { - LogInfo("Got request for peer stats (size: ", msg.data.size(), ")"); - for (auto str : msg.data) + if (not router->peer_db()) { - LogInfo(" :", str); + LogWarn("HandleGetPeerStats called when router has no peerDb set up."); + + // TODO: this can sometimes occur if lokid hits our API before we're done configuring + // (mostly an issue in a loopback testnet) + msg.send_reply("EAGAIN"); + return; } - if (auto router = m_Router.lock()) + try { - if (not router->peerDb()) + // msg.data[0] is expected to contain a bt list of router ids (in our preferred string + // format) + if (msg.data.empty()) { - LogWarn("HandleGetPeerStats called when router has no peerDb set up."); - - // TODO: this can sometimes occur if lokid hits our API before we're done configuring - // (mostly an issue in a loopback testnet) - msg.send_reply("EAGAIN"); + LogWarn("lokid requested peer stats with no request body"); + msg.send_reply("peer stats request requires list of router IDs"); return; } - try + std::vector routerIdStrings; + oxenc::bt_deserialize(msg.data[0], routerIdStrings); + + std::vector routerIds; + routerIds.reserve(routerIdStrings.size()); + + for (const auto& routerIdString : routerIdStrings) { - // msg.data[0] is expected to contain a bt list of router ids (in our preferred string - // format) - if (msg.data.empty()) + RouterID id; + if (not id.FromString(routerIdString)) { - LogWarn("lokid requested peer stats with no request body"); - msg.send_reply("peer stats request requires list of router IDs"); + LogWarn("lokid sent us an invalid router id: ", routerIdString); + msg.send_reply("Invalid router id"); return; } - std::vector routerIdStrings; - oxenc::bt_deserialize(msg.data[0], routerIdStrings); - - std::vector routerIds; - routerIds.reserve(routerIdStrings.size()); - - for (const auto& routerIdString : routerIdStrings) - { - RouterID id; - if (not id.FromString(routerIdString)) - { - LogWarn("lokid sent us an invalid router id: ", routerIdString); - msg.send_reply("Invalid router id"); - return; - } - - routerIds.push_back(std::move(id)); - } + routerIds.push_back(std::move(id)); + } - auto statsList = router->peerDb()->listPeerStats(routerIds); + auto statsList = router->peer_db()->listPeerStats(routerIds); - int32_t bufSize = - 256 + (statsList.size() * 1024); // TODO: tune this or allow to grow dynamically - auto buf = std::unique_ptr(new uint8_t[bufSize]); - llarp_buffer_t llarpBuf(buf.get(), bufSize); + int32_t bufSize = + 256 + (statsList.size() * 1024); // TODO: tune this or allow to grow dynamically + auto buf = std::unique_ptr(new uint8_t[bufSize]); + llarp_buffer_t llarpBuf(buf.get(), bufSize); - PeerStats::BEncodeList(statsList, &llarpBuf); + PeerStats::BEncodeList(statsList, &llarpBuf); - msg.send_reply( - std::string_view((const char*)llarpBuf.base, llarpBuf.cur - llarpBuf.base)); - } - catch (const std::exception& e) - { - LogError("Failed to handle get_peer_stats request: ", e.what()); - msg.send_reply("server error"); - } + msg.send_reply(std::string_view((const char*)llarpBuf.base, llarpBuf.cur - llarpBuf.base)); + } + catch (const std::exception& e) + { + LogError("Failed to handle get_peer_stats request: ", e.what()); + msg.send_reply("server error"); } } - } // namespace rpc -} // namespace llarp + } +} // namespace llarp::rpc diff --git a/llarp/rpc/lokid_rpc_client.hpp b/llarp/rpc/lokid_rpc_client.hpp index cbd9b459f..becca7e29 100644 --- a/llarp/rpc/lokid_rpc_client.hpp +++ b/llarp/rpc/lokid_rpc_client.hpp @@ -10,16 +10,14 @@ namespace llarp { - struct AbstractRouter; + struct Router; namespace rpc { - using LMQ_ptr = std::shared_ptr; - /// The LokidRpcClient uses loki-mq to talk to make API requests to lokid. struct LokidRpcClient : public std::enable_shared_from_this { - explicit LokidRpcClient(LMQ_ptr lmq, std::weak_ptr r); + explicit LokidRpcClient(std::shared_ptr lmq, std::weak_ptr r); /// Connect to lokid async void @@ -87,9 +85,9 @@ namespace llarp HandleNewBlock(oxenmq::Message& msg); std::optional m_Connection; - LMQ_ptr m_lokiMQ; + std::shared_ptr m_lokiMQ; - std::weak_ptr m_Router; + std::weak_ptr m_Router; std::atomic m_UpdatingList; std::string m_LastUpdateHash; diff --git a/llarp/rpc/rpc_request.hpp b/llarp/rpc/rpc_request.hpp index caf50d9f3..8801298c8 100644 --- a/llarp/rpc/rpc_request.hpp +++ b/llarp/rpc/rpc_request.hpp @@ -7,7 +7,7 @@ #include "json_bt.hpp" #include #include -#include +#include #include #include #include diff --git a/llarp/rpc/rpc_request_definitions.hpp b/llarp/rpc/rpc_request_definitions.hpp index 565f34572..340eb6c41 100644 --- a/llarp/rpc/rpc_request_definitions.hpp +++ b/llarp/rpc/rpc_request_definitions.hpp @@ -2,7 +2,6 @@ #include "rpc_request_decorators.hpp" #include "llarp/net/ip_range.hpp" -#include "llarp/router/abstractrouter.hpp" #include "llarp/router/route_poker.hpp" #include "llarp/service/address.hpp" #include "llarp/service/endpoint.hpp" diff --git a/llarp/rpc/rpc_server.cpp b/llarp/rpc/rpc_server.cpp index 746557f63..ae7ac5f58 100644 --- a/llarp/rpc/rpc_server.cpp +++ b/llarp/rpc/rpc_server.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include @@ -77,7 +77,7 @@ namespace llarp::rpc } std::shared_ptr - GetEndpointByName(AbstractRouter& r, std::string name) + GetEndpointByName(Router& r, std::string name) { if (r.IsServiceNode()) { @@ -99,11 +99,11 @@ namespace llarp::rpc regs.emplace(RPC::name, std::move(cback)); } - RPCServer::RPCServer(LMQ_ptr lmq, AbstractRouter& r) + RPCServer::RPCServer(LMQ_ptr lmq, Router& r) : m_LMQ{std::move(lmq)}, m_Router(r), log_subs{*m_LMQ, llarp::logRingBuffer} { // copied logic loop as placeholder - for (const auto& addr : r.GetConfig()->api.m_rpcBindAddresses) + for (const auto& addr : r.get_config()->api.m_rpcBindAddresses) { m_LMQ->listen_plain(addr.zmq_address()); LogInfo("Bound RPC server to ", addr.full_address()); diff --git a/llarp/rpc/rpc_server.hpp b/llarp/rpc/rpc_server.hpp index bda5d6888..56bb1f11e 100644 --- a/llarp/rpc/rpc_server.hpp +++ b/llarp/rpc/rpc_server.hpp @@ -13,7 +13,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; } // namespace llarp namespace @@ -81,7 +81,7 @@ namespace llarp::rpc class RPCServer { public: - explicit RPCServer(LMQ_ptr, AbstractRouter&); + explicit RPCServer(LMQ_ptr, Router&); ~RPCServer() = default; void @@ -118,7 +118,7 @@ namespace llarp::rpc invoke(Config& config); LMQ_ptr m_LMQ; - AbstractRouter& m_Router; + Router& m_Router; oxen::log::PubsubLogger log_subs; }; diff --git a/llarp/service/auth.cpp b/llarp/service/auth.cpp index 1c6ce91fb..90faef6f3 100644 --- a/llarp/service/auth.cpp +++ b/llarp/service/auth.cpp @@ -1,7 +1,7 @@ #include "auth.hpp" #include -#include +#include #include "protocol.hpp" #include #include @@ -87,7 +87,7 @@ namespace llarp::service { const std::set m_Files; const AuthFileType m_Type; - AbstractRouter* const m_Router; + Router* const m_Router; mutable util::Mutex m_Access; std::unordered_set m_Pending; /// returns an auth result for a auth info challange, opens every file until it finds a token @@ -131,7 +131,7 @@ namespace llarp::service } public: - FileAuthPolicy(AbstractRouter* r, std::set files, AuthFileType filetype) + FileAuthPolicy(Router* r, std::set files, AuthFileType filetype) : m_Files{std::move(files)}, m_Type{filetype}, m_Router{r} {} @@ -153,7 +153,7 @@ namespace llarp::service } if (msg->proto == ProtocolType::Auth) { - m_Router->QueueDiskIO( + m_Router->queue_disk_io( [self = shared_from_this(), auth = AuthInfo{std::string{ reinterpret_cast(msg->payload.data()), msg->payload.size()}}, @@ -180,7 +180,7 @@ namespace llarp::service }; std::shared_ptr - MakeFileAuthPolicy(AbstractRouter* r, std::set files, AuthFileType filetype) + MakeFileAuthPolicy(Router* r, std::set files, AuthFileType filetype) { return std::make_shared(r, std::move(files), filetype); } diff --git a/llarp/service/auth.hpp b/llarp/service/auth.hpp index b87f9eab7..f357ca86b 100644 --- a/llarp/service/auth.hpp +++ b/llarp/service/auth.hpp @@ -95,6 +95,6 @@ namespace llarp::service /// make an IAuthPolicy that reads out of a static file std::shared_ptr - MakeFileAuthPolicy(AbstractRouter*, std::set files, AuthFileType fileType); + MakeFileAuthPolicy(Router*, std::set files, AuthFileType fileType); } // namespace llarp::service diff --git a/llarp/service/context.cpp b/llarp/service/context.cpp index 4b7c00bb4..68b62c014 100644 --- a/llarp/service/context.cpp +++ b/llarp/service/context.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include "endpoint.hpp" #include @@ -14,29 +14,28 @@ namespace llarp static auto logcat = log::Cat("service"); namespace { - using EndpointConstructor = - std::function; + using EndpointConstructor = std::function; using EndpointConstructors = std::map; static EndpointConstructors endpointConstructors = { {"tun", - [](AbstractRouter* r, service::Context* c) { + [](Router* r, service::Context* c) { return std::make_shared(r, c); }}, {"android", - [](AbstractRouter* r, service::Context* c) { + [](Router* r, service::Context* c) { return std::make_shared(r, c); }}, {"ios", - [](AbstractRouter* r, service::Context* c) { + [](Router* r, service::Context* c) { return std::make_shared(r, c); }}, - {"null", [](AbstractRouter* r, service::Context* c) { + {"null", [](Router* r, service::Context* c) { return std::make_shared(r, c); }}}; } // namespace - Context::Context(AbstractRouter* r) : m_Router(r) + Context::Context(Router* r) : m_Router(r) {} Context::~Context() = default; diff --git a/llarp/service/context.hpp b/llarp/service/context.hpp index 3694d9772..ce5ff8e8a 100644 --- a/llarp/service/context.hpp +++ b/llarp/service/context.hpp @@ -16,7 +16,7 @@ namespace llarp /// only supports one endpoint per instance struct Context { - explicit Context(AbstractRouter* r); + explicit Context(Router* r); ~Context(); void @@ -66,7 +66,7 @@ namespace llarp StartAll(); private: - AbstractRouter* const m_Router; + Router* const m_Router; std::unordered_map> m_Endpoints; std::list> m_Stopped; }; diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 875171800..6cd921fb0 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -48,7 +48,7 @@ namespace llarp { static auto logcat = log::Cat("endpoint"); - Endpoint::Endpoint(AbstractRouter* r, Context* parent) + Endpoint::Endpoint(Router* r, Context* parent) : path::Builder{r, 3, path::default_len} , context{parent} , m_InboundTrafficQueue{512} @@ -170,7 +170,7 @@ namespace llarp LogWarn("failed to generate introset for endpoint ", Name()); return; } - if (PublishIntroSet(*maybe, Router())) + if (PublishIntroSet(*maybe, router())) { LogInfo("(re)publishing introset for endpoint ", Name()); } @@ -181,7 +181,7 @@ namespace llarp } bool - Endpoint::IsReady() const + Endpoint::is_ready() const { const auto now = Now(); if (introSet().intros.empty()) @@ -308,7 +308,7 @@ namespace llarp }; // handles when we resolved a .snode - auto handleResolvedSNodeName = [resultHandler, nodedb = Router()->nodedb()](auto router_id) { + auto handleResolvedSNodeName = [resultHandler, nodedb = router()->node_db()](auto router_id) { std::vector result{}; if (auto maybe_rc = nodedb->Get(router_id)) { @@ -674,7 +674,7 @@ namespace llarp const auto& keyfile = m_state->m_Keyfile; if (!keyfile.empty()) { - m_Identity.EnsureKeys(keyfile, Router()->keyManager()->needBackup()); + m_Identity.EnsureKeys(keyfile, router()->key_manager()->needBackup()); } else { @@ -710,7 +710,7 @@ namespace llarp Endpoint::~Endpoint() = default; bool - Endpoint::PublishIntroSet(const EncryptedIntroSet& introset, AbstractRouter* r) + Endpoint::PublishIntroSet(const EncryptedIntroSet& introset, Router* r) { const auto paths = GetManyPathsWithUniqueEndpoints( this, @@ -734,7 +734,7 @@ namespace llarp { for (size_t i = 0; i < llarp::dht::IntroSetRequestsPerRelay; ++i) { - r->NotifyRouterEvent( + r->notify_router_event( r->pubkey(), llarp::dht::Key_t{introset.derivedSigningKey.as_array()}, RouterID(path->hops[path->hops.size() - 1].rc.pubkey), @@ -815,10 +815,7 @@ namespace llarp bool Endpoint::PublishIntroSetVia( - const EncryptedIntroSet& introset, - AbstractRouter* r, - path::Path_ptr path, - uint64_t relayOrder) + const EncryptedIntroSet& introset, Router* r, path::Path_ptr path, uint64_t relayOrder) { auto job = new PublishIntroSetJob(this, GenTXID(), introset, relayOrder, PublishIntrosetTimeout); @@ -879,9 +876,9 @@ namespace llarp std::unordered_set exclude; ForEachPath([&exclude](auto path) { exclude.insert(path->Endpoint()); }); const auto maybe = - m_router->nodedb()->GetRandom([exclude, r = m_router](const auto& rc) -> bool { + m_router->node_db()->GetRandom([exclude, r = m_router](const auto& rc) -> bool { return exclude.count(rc.pubkey) == 0 - and not r->routerProfiling().IsBadForPath(rc.pubkey); + and not r->router_profiling().IsBadForPath(rc.pubkey); }); if (not maybe.has_value()) return std::nullopt; @@ -945,10 +942,10 @@ namespace llarp { for (auto& rc : msg->foundRCs) { - Router()->QueueWork([this, rc, msg]() mutable { + router()->queue_work([this, rc, msg]() mutable { bool valid = rc.Verify(llarp::time_now_ms()); - Router()->loop()->call([this, valid, rc = std::move(rc), msg] { - Router()->nodedb()->PutIfNewer(rc); + router()->loop()->call([this, valid, rc = std::move(rc), msg] { + router()->node_db()->PutIfNewer(rc); HandleVerifyGotRouter(msg, rc.pubkey, valid); }); }); @@ -1037,7 +1034,7 @@ namespace llarp bool Endpoint::ReadyForNetwork() const { - return IsReady() and ReadyToDoLookup(GetUniqueEndpointsForLookup().size()); + return is_ready() and ReadyToDoLookup(GetUniqueEndpointsForLookup().size()); } bool @@ -1134,37 +1131,37 @@ namespace llarp } void - Endpoint::EnsureRouterIsKnown(const RouterID& router) + Endpoint::EnsureRouterIsKnown(const RouterID& rid) { - if (router.IsZero()) + if (rid.IsZero()) return; - if (!Router()->nodedb()->Has(router)) + if (!router()->node_db()->Has(rid)) { - LookupRouterAnon(router, nullptr); + LookupRouterAnon(rid, nullptr); } } bool - Endpoint::LookupRouterAnon(RouterID router, RouterLookupHandler handler) + Endpoint::LookupRouterAnon(RouterID rid, RouterLookupHandler handler) { using llarp::dht::FindRouterMessage; auto& routers = m_state->m_PendingRouters; - if (routers.find(router) == routers.end()) + if (routers.find(rid) == routers.end()) { - auto path = GetEstablishedPathClosestTo(router); + auto path = GetEstablishedPathClosestTo(rid); routing::PathDHTMessage msg; auto txid = GenTXID(); - msg.dht_msgs.emplace_back(std::make_unique(txid, router)); + msg.dht_msgs.emplace_back(std::make_unique(txid, rid)); if (path) msg.sequence_number = path->NextSeqNo(); - if (path && path->SendRoutingMessage(msg, Router())) + if (path && path->SendRoutingMessage(msg, router())) { - RouterLookupJob job{this, [handler, router, nodedb = m_router->nodedb()](auto results) { + RouterLookupJob job{this, [handler, rid, nodedb = m_router->node_db()](auto results) { if (results.empty()) { - LogInfo("could not find ", router, ", remove it from nodedb"); - nodedb->Remove(router); + LogInfo("could not find ", rid, ", remove it from nodedb"); + nodedb->Remove(rid); } if (handler) handler(results); @@ -1174,9 +1171,9 @@ namespace llarp auto dhtMsg = dynamic_cast(msg.dht_msgs[0].get()); assert(dhtMsg != nullptr); - m_router->NotifyRouterEvent(m_router->pubkey(), *dhtMsg); + m_router->notify_router_event(router()->pubkey(), *dhtMsg); - routers.emplace(router, std::move(job)); + routers.emplace(rid, std::move(job)); return true; } } @@ -1219,7 +1216,7 @@ namespace llarp Endpoint::QueueRecvData(RecvDataEvent ev) { m_RecvQueue.tryPushBack(std::move(ev)); - Router()->TriggerPump(); + router()->TriggerPump(); } bool @@ -1291,7 +1288,7 @@ namespace llarp || (msg->proto == ProtocolType::QUIC and m_quic)) { m_InboundTrafficQueue.tryPushBack(std::move(msg)); - Router()->TriggerPump(); + router()->TriggerPump(); return true; } if (msg->proto == ProtocolType::Control) @@ -1317,7 +1314,7 @@ namespace llarp } else { - Router()->loop()->call([h = std::move(hook)] { h({AuthResultCode::eAuthAccepted, "OK"}); }); + router()->loop()->call([h = std::move(hook)] { h({AuthResultCode::eAuthAccepted, "OK"}); }); } } @@ -1416,7 +1413,7 @@ namespace llarp RemoveConvoTag(frame.convo_tag); return true; } - if (not frame.AsyncDecryptAndVerify(Router()->loop(), p, m_Identity, this)) + if (not frame.AsyncDecryptAndVerify(router()->loop(), p, m_Identity, this)) { ResetConvoTag(frame.convo_tag, p, frame.path_id); } @@ -1426,7 +1423,7 @@ namespace llarp void Endpoint::HandlePathDied(path::Path_ptr p) { - m_router->routerProfiling().MarkPathTimeout(p.get()); + m_router->router_profiling().MarkPathTimeout(p.get()); ManualRebuild(1); path::Builder::HandlePathDied(p); RegenAndPublishIntroSet(); @@ -1448,7 +1445,7 @@ namespace llarp { // tell all our existing remote sessions about this introset update - const auto now = Router()->Now(); + const auto now = router()->Now(); auto& lookups = m_state->m_PendingServiceLookups; if (introset) { @@ -1613,7 +1610,7 @@ namespace llarp " order=", order); order++; - if (job->SendRequestViaPath(path, Router())) + if (job->SendRequestViaPath(path, router())) { hookAdded = true; } @@ -1662,7 +1659,7 @@ namespace llarp ConvoTag{maybe->as_array()}, pkt.ConstBuffer(), ProtocolType::TrafficV4, 0); return false; }, - Router(), + router(), 1, numHops, false, @@ -1739,7 +1736,7 @@ namespace llarp if (s) { s->SendPacketToRemote(pkt->ConstBuffer(), t); - Router()->TriggerPump(); + router()->TriggerPump(); } }); return true; @@ -1782,7 +1779,7 @@ namespace llarp queue.pop(); } - auto router = Router(); + auto r = router(); // TODO: locking on this container for (const auto& [addr, outctx] : m_state->m_RemoteSessions) { @@ -1790,7 +1787,7 @@ namespace llarp outctx->Pump(now); } // TODO: locking on this container - for (const auto& [router, session] : m_state->m_SNodeSessions) + for (const auto& [r, session] : m_state->m_SNodeSessions) session->FlushUpstream(); // send queue flush @@ -1798,11 +1795,11 @@ namespace llarp { SendEvent_t item = m_SendQueue.popFront(); item.first->sequence_number = item.second->NextSeqNo(); - if (item.second->SendRoutingMessage(*item.first, router)) + if (item.second->SendRoutingMessage(*item.first, r)) ConvoTagTX(item.first->protocol_frame_msg.convo_tag); } - UpstreamFlush(router); + UpstreamFlush(r); } std::optional @@ -2006,7 +2003,7 @@ namespace llarp f.sequence_number = m->seqno; f.path_id = p->intro.path_id; transfer->path_id = replyIntro.path_id; - Router()->QueueWork([transfer, p, m, K, this]() { + router()->queue_work([transfer, p, m, K, this]() { if (not transfer->protocol_frame_msg.EncryptAndSign(*m, K, m_Identity)) { LogError( @@ -2015,7 +2012,7 @@ namespace llarp return; } m_SendQueue.tryPushBack(SendEvent_t{transfer, p}); - Router()->TriggerPump(); + router()->TriggerPump(); }); return true; } @@ -2107,8 +2104,8 @@ namespace llarp < requiredPaths; } - AbstractRouter* - Endpoint::Router() + Router* + Endpoint::router() { return m_state->m_Router; } @@ -2116,7 +2113,7 @@ namespace llarp const EventLoop_ptr& Endpoint::Loop() { - return Router()->loop(); + return router()->loop(); } void diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index 4c24b4392..422d11c1e 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -67,14 +67,14 @@ namespace llarp public IDataHandler, public EndpointBase { - Endpoint(AbstractRouter* r, Context* parent); + Endpoint(Router* r, Context* parent); ~Endpoint() override; /// return true if we are ready to recv packets from the void. /// really should be ReadyForInboundTraffic() but the diff is HUGE and we need to rewrite this /// component anyways. bool - IsReady() const; + is_ready() const; void QueueRecvData(RecvDataEvent ev) override; @@ -146,8 +146,8 @@ namespace llarp const EventLoop_ptr& Loop() override; - AbstractRouter* - Router(); + Router* + router(); virtual bool LoadKeyFile(); @@ -189,11 +189,11 @@ namespace llarp } bool - PublishIntroSet(const EncryptedIntroSet& i, AbstractRouter* r) override; + PublishIntroSet(const EncryptedIntroSet& i, Router* r) override; bool PublishIntroSetVia( - const EncryptedIntroSet& i, AbstractRouter* r, path::Path_ptr p, uint64_t relayOrder); + const EncryptedIntroSet& i, Router* r, path::Path_ptr p, uint64_t relayOrder); bool HandleGotIntroMessage(std::shared_ptr msg) override; diff --git a/llarp/service/endpoint_state.hpp b/llarp/service/endpoint_state.hpp index 7cbae0894..4764effbb 100644 --- a/llarp/service/endpoint_state.hpp +++ b/llarp/service/endpoint_state.hpp @@ -26,7 +26,7 @@ namespace llarp { std::set m_SnodeBlacklist; - AbstractRouter* m_Router; + Router* m_Router; std::string m_Keyfile; std::string m_Name; std::string m_NetNS; diff --git a/llarp/service/lookup.cpp b/llarp/service/lookup.cpp index e1895b051..ff6266a85 100644 --- a/llarp/service/lookup.cpp +++ b/llarp/service/lookup.cpp @@ -2,12 +2,12 @@ #include #include -#include +#include #include namespace llarp { - struct AbstractRouter; + struct Router; namespace service { @@ -19,7 +19,7 @@ namespace llarp } bool - IServiceLookup::SendRequestViaPath(path::Path_ptr path, AbstractRouter* r) + IServiceLookup::SendRequestViaPath(path::Path_ptr path, Router* r) { auto msg = BuildRequestMessage(); if (!msg) diff --git a/llarp/service/lookup.hpp b/llarp/service/lookup.hpp index 4a485c1de..8a15a48b0 100644 --- a/llarp/service/lookup.hpp +++ b/llarp/service/lookup.hpp @@ -69,7 +69,7 @@ namespace llarp /// build a new request message and send it via a path virtual bool - SendRequestViaPath(path::Path_ptr p, AbstractRouter* r); + SendRequestViaPath(path::Path_ptr p, Router* r); ILookupHolder* m_parent; uint64_t txid; diff --git a/llarp/service/outbound_context.cpp b/llarp/service/outbound_context.cpp index a461b88eb..672f00cf9 100644 --- a/llarp/service/outbound_context.cpp +++ b/llarp/service/outbound_context.cpp @@ -5,7 +5,7 @@ #include "endpoint_util.hpp" #include "protocol_type.hpp" -#include +#include #include #include #include @@ -53,7 +53,7 @@ namespace llarp::service constexpr auto OutboundContextNumPaths = 4; OutboundContext::OutboundContext(const IntroSet& introset, Endpoint* parent) - : path::Builder{parent->Router(), OutboundContextNumPaths, parent->numHops} + : path::Builder{parent->router(), OutboundContextNumPaths, parent->numHops} , SendContext{introset.addressKeys, {}, this, parent} , location{introset.addressKeys.Addr().ToKey()} , addr{introset.addressKeys.Addr()} @@ -266,7 +266,7 @@ namespace llarp::service // ensure we have a sender put for this convo tag m_DataHandler->PutSenderFor(currentConvoTag, currentIntroSet.addressKeys, false); // encrypt frame async - m_Endpoint->Router()->QueueWork([ex, frame] { return AsyncKeyExchange::Encrypt(ex, frame); }); + m_Endpoint->router()->queue_work([ex, frame] { return AsyncKeyExchange::Encrypt(ex, frame); }); LogInfo(Name(), " send intro frame T=", currentConvoTag); } @@ -302,7 +302,7 @@ namespace llarp::service m_Endpoint->GenTXID(), (IntrosetUpdateInterval / 2) + (2 * path->intro.latency) + IntrosetLookupGraceInterval); relayOrder++; - if (job->SendRequestViaPath(path, m_Endpoint->Router())) + if (job->SendRequestViaPath(path, m_Endpoint->router())) updatingIntroSet = true; } } diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index d9abccc85..d3d4d63e7 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -5,7 +5,7 @@ #include #include #include "endpoint.hpp" -#include +#include #include namespace llarp::service @@ -412,7 +412,7 @@ namespace llarp::service auto dh = std::make_shared( loop, localIdent, handler, msg, *this, recvPath->intro); dh->path = recvPath; - handler->Router()->QueueWork([dh = std::move(dh)] { return AsyncFrameDecrypt::Work(dh); }); + handler->router()->queue_work([dh = std::move(dh)] { return AsyncFrameDecrypt::Work(dh); }); return true; } @@ -447,7 +447,7 @@ namespace llarp::service loop->call([msg, hook]() { hook(msg); }); } }; - handler->Router()->QueueWork( + handler->router()->queue_work( [v, msg = std::move(msg), recvPath = std::move(recvPath), callback, handler]() { auto resetTag = [handler, tag = v->frame.convo_tag, from = v->frame.path_id, path = recvPath]() { @@ -508,7 +508,7 @@ namespace llarp::service bool ProtocolFrameMessage::handle_message( - routing::AbstractRoutingMessageHandler* h, AbstractRouter* /*r*/) const + routing::AbstractRoutingMessageHandler* h, Router* /*r*/) const { return h->HandleHiddenServiceFrame(*this); } diff --git a/llarp/service/protocol.hpp b/llarp/service/protocol.hpp index adb8daeaa..ef9757a99 100644 --- a/llarp/service/protocol.hpp +++ b/llarp/service/protocol.hpp @@ -172,7 +172,7 @@ namespace llarp Verify(const ServiceInfo& from) const; bool - handle_message(routing::AbstractRoutingMessageHandler* h, AbstractRouter* r) const override; + handle_message(routing::AbstractRoutingMessageHandler* h, Router* r) const override; }; } // namespace service } // namespace llarp diff --git a/llarp/service/sendcontext.cpp b/llarp/service/sendcontext.cpp index 4572b0c98..d0ca16464 100644 --- a/llarp/service/sendcontext.cpp +++ b/llarp/service/sendcontext.cpp @@ -1,6 +1,6 @@ #include "sendcontext.hpp" -#include +#include #include #include "endpoint.hpp" #include @@ -30,7 +30,7 @@ namespace llarp::service std::make_shared(*msg, remoteIntro.path_id), path)) == thread::QueueReturn::Success) { - m_Endpoint->Router()->TriggerPump(); + m_Endpoint->router()->TriggerPump(); return true; } return false; @@ -39,7 +39,7 @@ namespace llarp::service void SendContext::FlushUpstream() { - auto r = m_Endpoint->Router(); + auto r = m_Endpoint->router(); std::unordered_set flushpaths; auto rttRMS = 0ms; while (auto maybe = m_SendQueue.tryPopFront()) @@ -112,7 +112,7 @@ namespace llarp::service m->sender = m_Endpoint->GetIdentity().pub; m->tag = f->convo_tag; m->PutBuffer(payload); - m_Endpoint->Router()->QueueWork([f, m, shared, path, this] { + m_Endpoint->router()->queue_work([f, m, shared, path, this] { if (not f->EncryptAndSign(*m, shared, m_Endpoint->GetIdentity())) { LogError(m_PathSet->Name(), " failed to sign message"); diff --git a/llarp/tooling/hive_context.cpp b/llarp/tooling/hive_context.cpp index c029d7ecb..130fe28e0 100644 --- a/llarp/tooling/hive_context.cpp +++ b/llarp/tooling/hive_context.cpp @@ -7,7 +7,7 @@ namespace tooling HiveContext::HiveContext(RouterHive* hive) : m_hive(hive) {} - std::shared_ptr + std::shared_ptr HiveContext::makeRouter(const llarp::EventLoop_ptr& loop) { return std::make_shared(loop, makeVPNPlatform(), m_hive); diff --git a/llarp/tooling/hive_context.hpp b/llarp/tooling/hive_context.hpp index 99963a90c..c9fd3a80a 100644 --- a/llarp/tooling/hive_context.hpp +++ b/llarp/tooling/hive_context.hpp @@ -11,7 +11,7 @@ namespace tooling { HiveContext(RouterHive* hive); - std::shared_ptr + std::shared_ptr makeRouter(const llarp::EventLoop_ptr& loop) override; /// Get this context's router as a HiveRouter. diff --git a/llarp/tooling/router_hive.cpp b/llarp/tooling/router_hive.cpp index d58a0608a..ea77071e2 100644 --- a/llarp/tooling/router_hive.cpp +++ b/llarp/tooling/router_hive.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include diff --git a/llarp/vpn/android.hpp b/llarp/vpn/android.hpp index 3364e75fa..3cbe25e18 100644 --- a/llarp/vpn/android.hpp +++ b/llarp/vpn/android.hpp @@ -88,7 +88,7 @@ namespace llarp::vpn {} std::shared_ptr - ObtainInterface(InterfaceInfo info, AbstractRouter*) override + ObtainInterface(InterfaceInfo info, Router*) override { return std::make_shared(std::move(info), fd); } diff --git a/llarp/vpn/linux.hpp b/llarp/vpn/linux.hpp index cfc99cdc8..d39e11a7b 100644 --- a/llarp/vpn/linux.hpp +++ b/llarp/vpn/linux.hpp @@ -18,7 +18,7 @@ #include -#include +#include #include #include @@ -442,7 +442,7 @@ namespace llarp::vpn public: std::shared_ptr - ObtainInterface(InterfaceInfo info, AbstractRouter*) override + ObtainInterface(InterfaceInfo info, Router*) override { return std::make_shared(std::move(info)); }; diff --git a/llarp/vpn/platform.hpp b/llarp/vpn/platform.hpp index 9ae880bb9..0885518e4 100644 --- a/llarp/vpn/platform.hpp +++ b/llarp/vpn/platform.hpp @@ -11,7 +11,7 @@ namespace llarp { struct Context; - struct AbstractRouter; + struct Router; } // namespace llarp namespace llarp::vpn @@ -123,7 +123,7 @@ namespace llarp::vpn /// get a new network interface fully configured given the interface info /// blocks until ready, throws on error virtual std::shared_ptr - ObtainInterface(InterfaceInfo info, AbstractRouter* router) = 0; + ObtainInterface(InterfaceInfo info, Router* router) = 0; public: Platform() = default; @@ -133,7 +133,7 @@ namespace llarp::vpn /// create and start a network interface inline std::shared_ptr - CreateInterface(InterfaceInfo info, AbstractRouter* router) + CreateInterface(InterfaceInfo info, Router* router) { if (auto netif = ObtainInterface(std::move(info), router)) { diff --git a/llarp/vpn/win32.cpp b/llarp/vpn/win32.cpp index f6f4a452e..2027076ba 100644 --- a/llarp/vpn/win32.cpp +++ b/llarp/vpn/win32.cpp @@ -111,7 +111,7 @@ namespace llarp::win32 } std::shared_ptr - VPNPlatform::ObtainInterface(InterfaceInfo info, AbstractRouter* router) + VPNPlatform::ObtainInterface(InterfaceInfo info, Router* router) { return wintun::make_interface(std::move(info), router); } diff --git a/llarp/vpn/win32.hpp b/llarp/vpn/win32.hpp index 40ea98e33..ac5248935 100644 --- a/llarp/vpn/win32.hpp +++ b/llarp/vpn/win32.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include @@ -63,7 +63,7 @@ namespace llarp::win32 DelDefaultRouteViaInterface(NetworkInterface& vpn) override; std::shared_ptr - ObtainInterface(InterfaceInfo info, AbstractRouter* router) override; + ObtainInterface(InterfaceInfo info, Router* router) override; std::shared_ptr create_packet_io( diff --git a/llarp/win32/wintun.cpp b/llarp/win32/wintun.cpp index ca77c61fa..10569a69e 100644 --- a/llarp/win32/wintun.cpp +++ b/llarp/win32/wintun.cpp @@ -10,7 +10,7 @@ extern "C" #include "guid.hpp" #include #include -#include +#include #include #include #include @@ -273,7 +273,7 @@ namespace llarp::win32 class WintunInterface : public vpn::NetworkInterface { - AbstractRouter* const _router; + Router* const _router; std::shared_ptr _adapter; std::shared_ptr _session; thread::Queue _recv_queue; @@ -284,7 +284,7 @@ namespace llarp::win32 static inline constexpr size_t packet_queue_length = 1024; public: - WintunInterface(vpn::InterfaceInfo info, AbstractRouter* router) + WintunInterface(vpn::InterfaceInfo info, Router* router) : vpn::NetworkInterface{std::move(info)} , _router{router} , _adapter{std::make_shared(m_Info.ifname)} @@ -385,7 +385,7 @@ namespace llarp::win32 namespace wintun { std::shared_ptr - make_interface(const llarp::vpn::InterfaceInfo& info, llarp::AbstractRouter* r) + make_interface(const llarp::vpn::InterfaceInfo& info, llarp::Router* r) { WintunInitialize(); return std::static_pointer_cast( diff --git a/llarp/win32/wintun.hpp b/llarp/win32/wintun.hpp index 1d2e7a7dc..9ae7834f3 100644 --- a/llarp/win32/wintun.hpp +++ b/llarp/win32/wintun.hpp @@ -4,7 +4,7 @@ namespace llarp { - struct AbstractRouter; + struct Router; } namespace llarp::vpn @@ -17,6 +17,6 @@ namespace llarp::win32::wintun { /// makes a new vpn interface with a wintun context given info and a router pointer std::shared_ptr - make_interface(const vpn::InterfaceInfo& info, AbstractRouter* router); + make_interface(const vpn::InterfaceInfo& info, Router* router); } // namespace llarp::win32::wintun diff --git a/pybind/common.hpp b/pybind/common.hpp index 83769d2c7..655dccf06 100644 --- a/pybind/common.hpp +++ b/pybind/common.hpp @@ -21,7 +21,7 @@ namespace llarp CryptoTypes_Init(py::module& mod); void - AbstractRouter_Init(py::module& mod); + Router_Init(py::module& mod); void RouterID_Init(py::module& mod); diff --git a/pybind/llarp/handlers/pyhandler.hpp b/pybind/llarp/handlers/pyhandler.hpp index 3f712dcc6..db90076af 100644 --- a/pybind/llarp/handlers/pyhandler.hpp +++ b/pybind/llarp/handlers/pyhandler.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include namespace llarp { diff --git a/pybind/llarp/router.cpp b/pybind/llarp/router.cpp index 04fe8b0bc..c32d51e9f 100644 --- a/pybind/llarp/router.cpp +++ b/pybind/llarp/router.cpp @@ -1,17 +1,17 @@ #include -#include +#include #include namespace llarp { void - AbstractRouter_Init(py::module& mod) + Router_Init(py::module& mod) { - py::class_>(mod, "AbstractRouter") - .def("rc", &AbstractRouter::rc) - .def("Stop", &AbstractRouter::Stop) - .def("peerDb", &AbstractRouter::peerDb); + py::class_>(mod, "Router") + .def("rc", &Router::rc) + .def("Stop", &Router::Stop) + .def("peerDb", &Router::peerDb); } } // namespace llarp @@ -21,7 +21,7 @@ namespace tooling void HiveRouter_Init(py::module& mod) { - py::class_>(mod, "HiveRouter") + py::class_>(mod, "HiveRouter") .def("disableGossiping", &HiveRouter::disableGossiping) .def("enableGossiping", &HiveRouter::enableGossiping); } diff --git a/pybind/llarp/tooling/router_hive.cpp b/pybind/llarp/tooling/router_hive.cpp index cae413113..0eabc7e33 100644 --- a/pybind/llarp/tooling/router_hive.cpp +++ b/pybind/llarp/tooling/router_hive.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include namespace tooling diff --git a/pybind/module.cpp b/pybind/module.cpp index d122c19b5..dc75ace23 100644 --- a/pybind/module.cpp +++ b/pybind/module.cpp @@ -5,7 +5,7 @@ PYBIND11_MODULE(pyllarp, m) { tooling::RouterHive_Init(m); tooling::RouterEvent_Init(m); - llarp::AbstractRouter_Init(m); + llarp::Router_Init(m); tooling::HiveRouter_Init(m); llarp::PeerDb_Init(m); llarp::PeerStats_Init(m); diff --git a/test/mocks/mock_context.hpp b/test/mocks/mock_context.hpp index b24e929a3..e25e0ef26 100644 --- a/test/mocks/mock_context.hpp +++ b/test/mocks/mock_context.hpp @@ -17,10 +17,10 @@ namespace mocks loop = std::shared_ptr{const_cast(&_net), [](Network*) {}}; } - std::shared_ptr + std::shared_ptr makeRouter(const std::shared_ptr&) override { - return std::static_pointer_cast( + return std::static_pointer_cast( std::make_shared(_net, makeVPNPlatform())); } diff --git a/test/mocks/mock_vpn.hpp b/test/mocks/mock_vpn.hpp index 9e7a3f374..22cc4bcdb 100644 --- a/test/mocks/mock_vpn.hpp +++ b/test/mocks/mock_vpn.hpp @@ -47,7 +47,7 @@ namespace mocks {} virtual std::shared_ptr - ObtainInterface(llarp::vpn::InterfaceInfo info, llarp::AbstractRouter*) override + ObtainInterface(llarp::vpn::InterfaceInfo info, llarp::Router*) override { return std::make_shared(info); };