Deleted a lot

- RIP llarp/iwp/* and most of llarp/link
pull/2204/head
dr7ana 9 months ago
parent ffb90e87dc
commit aaf688cf81

@ -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> crypto = nullptr;
std::shared_ptr<CryptoManager> cryptoManager = nullptr;
std::shared_ptr<AbstractRouter> router = nullptr;
std::shared_ptr<Router> router = nullptr;
std::shared_ptr<EventLoop> loop = nullptr;
std::shared_ptr<NodeDB> 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<AbstractRouter>
virtual std::shared_ptr<Router>
makeRouter(const std::shared_ptr<EventLoop>& loop);
/// create the nodedb given our current configs

@ -2,7 +2,7 @@
#include "lokinet_jni_common.hpp"
#include <llarp.hpp>
#include <llarp/config/config.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
extern "C"
{
@ -85,7 +85,7 @@ extern "C"
Java_network_loki_lokinet_LokinetDaemon_GetUDPSocket(JNIEnv* env, jobject self)
{
if (auto ptr = GetImpl<llarp::Context>(env, self); ptr and ptr->router)
return ptr->router->OutboundUDPSocket();
return ptr->router->outbound_socket();
return -1;
}

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

@ -1,6 +1,6 @@
#pragma once
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/vpn/platform.hpp>
#include "context_wrapper.h"

@ -1,7 +1,7 @@
#include "vpn_interface.hpp"
#include "context.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
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)}

@ -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<net::IPPacket> m_ReadQueue{PacketQueueSize};
AbstractRouter* const _router;
Router* const _router;
};
} // namespace llarp::apple

@ -16,7 +16,7 @@ namespace llarp::apple
{}
std::shared_ptr<vpn::NetworkInterface>
VPNPlatform::ObtainInterface(vpn::InterfaceInfo, AbstractRouter* router)
VPNPlatform::ObtainInterface(vpn::InterfaceInfo, Router* router)
{
return std::make_shared<VPNInterface>(m_Context, m_PacketWriter, m_OnReadable, router);
}

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

@ -1,7 +1,7 @@
#include "reachability_testing.hpp"
#include <chrono>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/util/logging.hpp>
#include <llarp/crypto/crypto.hpp>
@ -72,7 +72,7 @@ namespace llarp::consensus
}
std::optional<RouterID>
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);

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

@ -90,10 +90,10 @@ namespace llarp
Context::makeNodeDB()
{
return std::make_shared<NodeDB>(
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<AbstractRouter>
std::shared_ptr<Router>
Context::makeRouter(const EventLoop_ptr& loop)
{
return std::make_shared<Router>(loop, makeVPNPlatform());

@ -15,7 +15,7 @@
#include "taglookup.hpp"
#include <llarp/messages/dht_immediate.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/nodedb.hpp>
#include <llarp/profiling.hpp>
@ -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<llarp::service::EncryptedIntroSet>
@ -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<Bucket<RCNode>> _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);
}

@ -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<llarp::service::EncryptedIntroSet>
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<llarp::dht::AbstractDHTMessageHandler> impl;
llarp::AbstractRouter* parent;
llarp_dht_context(llarp::AbstractRouter* router);
llarp::Router* parent;
llarp_dht_context(llarp::Router* router);
};
#endif

@ -2,14 +2,14 @@
#include "dht.h"
#include <llarp/router_contact.hpp>
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);
}

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

@ -2,7 +2,7 @@
#include "context.hpp"
#include <llarp/dht/messages/findrouter.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/nodedb.hpp>
@ -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); });

@ -4,7 +4,7 @@
#include <llarp/dht/messages/gotrouter.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/util/logging.hpp>
@ -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(

@ -3,7 +3,7 @@
#include "context.hpp"
#include <llarp/dht/messages/gotintro.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/util/logging.hpp>
@ -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(

@ -3,7 +3,7 @@
#include "context.hpp"
#include <llarp/dht/messages/gotintro.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
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(

@ -2,7 +2,7 @@
#include "findintro.hpp"
#include "gotintro.hpp"
#include <llarp/routing/message.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/nodedb.hpp>
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)
{

@ -2,7 +2,7 @@
#include <oxenc/bt_serialize.h>
#include <llarp/dht/context.hpp>
#include "gotname.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/rpc/lokid_rpc_client.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/routing/path_dht_message.hpp>
@ -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;

@ -4,7 +4,7 @@
#include "gotrouter.hpp"
#include <llarp/nodedb.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/tooling/dht_event.hpp>
@ -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<std::unique_ptr<AbstractDHTMessage>>& replies) const
{
auto router = dht.GetRouter();
router->NotifyRouterEvent<tooling::FindRouterReceivedEvent>(router->pubkey(), *this);
router->notify_router_event<tooling::FindRouterReceivedEvent>(router->pubkey(), *this);
if (!dht.AllowTransit())
{

@ -4,7 +4,7 @@
#include <llarp/dht/context.hpp>
#include <memory>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/tooling/dht_event.hpp>
#include <utility>
@ -22,7 +22,7 @@ namespace llarp::dht
{
auto* router = dht.GetRouter();
router->NotifyRouterEvent<tooling::GotIntroReceivedEvent>(
router->notify_router_event<tooling::GotIntroReceivedEvent>(
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<std::unique_ptr<AbstractDHTMessage>>& 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<const RelayedGotIntroMessage>(*this);

@ -1,7 +1,7 @@
#include "gotname.hpp"
#include <oxenc/bt_serialize.h>
#include <llarp/dht/context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/path/path_context.hpp>
namespace llarp::dht
@ -60,7 +60,7 @@ namespace llarp::dht
GotNameMessage::handle_message(
AbstractDHTMessageHandler& dht, std::vector<std::unique_ptr<AbstractDHTMessage>>&) 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<const GotNameMessage>(*this);

@ -3,7 +3,7 @@
#include <memory>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/rc_lookup_handler.hpp>
#include <llarp/tooling/rc_event.hpp>
@ -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<const GotRouterMessage>(*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<tooling::RCGossipReceivedEvent>(router->pubkey(), rc);
router->notify_router_event<tooling::RCGossipReceivedEvent>(router->pubkey(), rc);
router->GossipRCIfNeeded(rc);
auto peerDb = router->peerDb();
auto peerDb = router->peer_db();
if (peerDb)
peerDb->handleGossipedRC(rc);
}

@ -3,7 +3,7 @@
#include <llarp/dht/context.hpp>
#include "gotintro.hpp"
#include <llarp/messages/dht_immediate.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/nodedb.hpp>
@ -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");

@ -5,7 +5,7 @@
#include <llarp/dht/messages/gotintro.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <utility>
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(

@ -4,7 +4,7 @@
#include <llarp/dht/messages/findrouter.hpp>
#include <llarp/dht/messages/gotrouter.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/rc_lookup_handler.hpp>
#include <utility>
@ -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();

@ -2,126 +2,123 @@
#include <memory>
#include <stdexcept>
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<handlers::ExitEndpoint>
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<handlers::ExitEndpoint>
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<handlers::ExitEndpoint>(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<handlers::ExitEndpoint>(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

@ -5,52 +5,49 @@
#include <string>
#include <unordered_map>
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<PubKey, std::pair<uint64_t, uint64_t>>;
/// calculate (pk, tx, rx) for all exit traffic
using TrafficStats = std::unordered_map<PubKey, std::pair<uint64_t, uint64_t>>;
void
CalculateExitTraffic(TrafficStats& stats);
void
CalculateExitTraffic(TrafficStats& stats);
std::shared_ptr<handlers::ExitEndpoint>
GetExitEndpoint(std::string name) const;
std::shared_ptr<handlers::ExitEndpoint>
GetExitEndpoint(std::string name) const;
private:
AbstractRouter* m_Router;
std::unordered_map<std::string, std::shared_ptr<handlers::ExitEndpoint>> m_Exits;
std::list<std::shared_ptr<handlers::ExitEndpoint>> m_Closed;
};
} // namespace exit
} // namespace llarp
private:
Router* router;
std::unordered_map<std::string, std::shared_ptr<handlers::ExitEndpoint>> m_Exits;
std::list<std::shared_ptr<handlers::ExitEndpoint>> m_Closed;
};
} // namespace llarp::exit

@ -2,7 +2,7 @@
#include <llarp/handlers/exit.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/quic/tunnel.hpp>
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;
}

@ -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);
}

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

@ -5,7 +5,7 @@
#include <llarp/path/path_context.hpp>
#include <llarp/path/path.hpp>
#include <llarp/quic/tunnel.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/util/meta/memfn.hpp>
#include <utility>
@ -14,7 +14,7 @@ namespace llarp::exit
BaseSession::BaseSession(
const llarp::RouterID& routerId,
std::function<bool(const llarp_buffer_t&)> 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<RouterContact>{*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<RouterContact>& results) {
@ -337,7 +337,7 @@ namespace llarp::exit
SNodeSession::SNodeSession(
const llarp::RouterID& snodeRouter,
std::function<bool(const llarp_buffer_t&)> writepkt,
AbstractRouter* r,
Router* r,
size_t numpaths,
size_t hoplen,
bool useRouterSNodeKey,

@ -38,7 +38,7 @@ namespace llarp
BaseSession(
const llarp::RouterID& exitRouter,
std::function<bool(const llarp_buffer_t&)> 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<bool(const llarp_buffer_t&)> 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<bool(const llarp_buffer_t&)> writepkt,
AbstractRouter* r,
Router* r,
size_t numpaths,
size_t hoplen,
bool useRouterSNodeKey,

File diff suppressed because it is too large Load Diff

@ -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<AddressVariant_t>
@ -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<dns::Server> m_Resolver;
bool m_ShouldInitTun;
std::string m_Name;
bool m_PermitExit;
std::unordered_map<PathID_t, PubKey> m_Paths;
Router* router;
std::shared_ptr<dns::Server> resolver;
bool should_init_tun;
std::string name;
bool permit_exit;
std::unordered_map<PathID_t, PubKey> paths;
std::unordered_map<PubKey, exit::Endpoint*> m_ChosenExits;
std::unordered_map<PubKey, exit::Endpoint*> chosen_exits;
std::unordered_multimap<PubKey, std::unique_ptr<exit::Endpoint>> m_ActiveExits;
std::unordered_multimap<PubKey, std::unique_ptr<exit::Endpoint>> active_exits;
using KeyMap_t = std::unordered_map<PubKey, huint128_t>;
KeyMap_t m_KeyToIP;
std::unordered_map<PubKey, huint128_t> key_to_IP;
using SNodes_t = std::set<PubKey>;
/// set of pubkeys we treat as snodes
SNodes_t m_SNodeKeys;
SNodes_t snode_keys;
using SNodeSessions_t = std::unordered_map<RouterID, std::shared_ptr<exit::SNodeSession>>;
/// snode sessions we are talking to directly
SNodeSessions_t m_SNodeSessions;
SNodeSessions_t snode_sessions;
std::unordered_map<huint128_t, PubKey> m_IPToKey;
std::unordered_map<huint128_t, PubKey> 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<huint128_t, llarp_time_t> m_IPActivity;
std::unordered_map<huint128_t, llarp_time_t> ip_activity;
std::shared_ptr<vpn::NetworkInterface> m_NetIf;
std::shared_ptr<vpn::NetworkInterface> if_net;
SockAddr m_LocalResolverAddr;
std::vector<SockAddr> m_UpstreamResolvers;
SockAddr resolver_addr;
std::vector<SockAddr> upstream_resolvers;
std::shared_ptr<quic::TunnelManager> m_QUIC;
std::shared_ptr<quic::TunnelManager> tunnel_manager;
using PacketQueue_t = std::
priority_queue<net::IPPacket, std::vector<net::IPPacket>, 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

@ -3,7 +3,7 @@
#include <llarp/service/endpoint.hpp>
#include <llarp/service/protocol_type.hpp>
#include <llarp/quic/tunnel.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/ev/ev.hpp>
#include <llarp/vpn/egres_packet_router.hpp>
@ -12,7 +12,7 @@ namespace llarp::handlers
struct NullEndpoint final : public llarp::service::Endpoint,
public std::enable_shared_from_this<NullEndpoint>
{
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(

@ -11,7 +11,7 @@
#include <llarp/dns/dns.hpp>
#include <llarp/ev/ev.hpp>
#include <llarp/net/net.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/route_poker.hpp>
#include <llarp/service/context.hpp>
#include <llarp/service/outbound_context.hpp>
@ -49,7 +49,7 @@ namespace llarp
auto job = std::make_shared<dns::QueryJob>(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<vpn::PacketRouter>(
[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<SockAddr> 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<dns::Message>(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<void(void)> 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;
}

@ -24,7 +24,7 @@ namespace llarp
public dns::Resolver_Base,
public std::enable_shared_from_this<TunEndpoint>
{
TunEndpoint(AbstractRouter* r, llarp::service::Context* parent);
TunEndpoint(Router* r, llarp::service::Context* parent);
~TunEndpoint() override;
vpn::NetworkInterface*

@ -1,72 +0,0 @@
#include "iwp.hpp"
#include "linklayer.hpp"
#include <memory>
#include <llarp/router/abstractrouter.hpp>
namespace llarp
{
namespace iwp
{
LinkLayer_ptr
NewInboundLink(
std::shared_ptr<KeyManager> keyManager,
std::shared_ptr<EventLoop> 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<LinkLayer>(
keyManager,
loop,
getrc,
h,
sign,
before,
est,
reneg,
timeout,
closed,
pumpDone,
work,
true);
}
LinkLayer_ptr
NewOutboundLink(
std::shared_ptr<KeyManager> keyManager,
std::shared_ptr<EventLoop> 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<LinkLayer>(
keyManager,
loop,
getrc,
h,
sign,
before,
est,
reneg,
timeout,
closed,
pumpDone,
work,
false);
}
} // namespace iwp
} // namespace llarp

@ -1,40 +0,0 @@
#pragma once
#include <llarp/link/server.hpp>
#include "linklayer.hpp"
#include <memory>
#include <llarp/config/key_manager.hpp>
namespace llarp::iwp
{
LinkLayer_ptr
NewInboundLink(
std::shared_ptr<KeyManager> keyManager,
std::shared_ptr<EventLoop> 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> keyManager,
std::shared_ptr<EventLoop> 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

@ -1,115 +0,0 @@
#include "linklayer.hpp"
#include "session.hpp"
#include <llarp/config/key_manager.hpp>
#include <memory>
#include <unordered_set>
namespace llarp::iwp
{
LinkLayer::LinkLayer(
std::shared_ptr<KeyManager> keyManager,
std::shared_ptr<EventLoop> 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<AbstractLinkSession> 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<Session>(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<AbstractLinkSession>
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<Session>(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

@ -1,63 +0,0 @@
#pragma once
#include <llarp/constants/link_layer.hpp>
#include <llarp/crypto/crypto.hpp>
#include <llarp/crypto/encrypted.hpp>
#include <llarp/crypto/types.hpp>
#include <llarp/link/server.hpp>
#include <llarp/config/key_manager.hpp>
#include <memory>
#include <llarp/ev/ev.hpp>
namespace llarp::iwp
{
struct Session;
struct LinkLayer final : public ILinkLayer
{
LinkLayer(
std::shared_ptr<KeyManager> keyManager,
std::shared_ptr<EventLoop> 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<AbstractLinkSession>
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<EventLoopWakeup> m_Wakeup;
std::vector<AbstractLinkSession*> m_WakingUp;
const bool m_Inbound;
};
using LinkLayer_ptr = std::shared_ptr<LinkLayer>;
} // namespace llarp::iwp

@ -1,194 +0,0 @@
#include "message_buffer.hpp"
#include "session.hpp"
#include <llarp/crypto/crypto.hpp>
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<uint16_t>(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<void(AbstractLinkSession::Packet_t)> 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<void(AbstractLinkSession::Packet_t)> 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

@ -1,127 +0,0 @@
#pragma once
#include <vector>
#include <llarp/constants/link_layer.hpp>
#include <llarp/link/session.hpp>
#include <llarp/util/aligned.hpp>
#include <llarp/util/buffer.hpp>
#include <llarp/util/types.hpp>
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<MAX_LINK_MSG_SIZE / FragmentSize> 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<void(AbstractLinkSession::Packet_t)> 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<MAX_LINK_MSG_SIZE / FragmentSize> 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<void(AbstractLinkSession::Packet_t)> sendpkt, llarp_time_t now);
AbstractLinkSession::Packet_t
ACKS() const;
};
} // namespace iwp
} // namespace llarp

File diff suppressed because it is too large Load Diff

@ -1,275 +0,0 @@
#pragma once
#include <llarp/link/session.hpp>
#include "linklayer.hpp"
#include "message_buffer.hpp"
#include <llarp/net/ip_address.hpp>
#include <map>
#include <unordered_set>
#include <deque>
#include <llarp/util/priority_queue.hpp>
#include <llarp/util/thread/queue.hpp>
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<Session>
{
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<uint64_t, InboundMessage> m_RXMsgs;
std::map<uint64_t, OutboundMessage> m_TXMsgs;
/// maps rxid to time recieved
std::unordered_map<uint64_t, llarp_time_t> m_ReplayFilter;
/// rx messages to send in next round of multiacks
util::ascending_priority_queue<uint64_t> m_SendMACKs;
using CryptoQueue_t = std::vector<Packet_t>;
CryptoQueue_t m_EncryptNext;
CryptoQueue_t m_DecryptNext;
std::atomic_flag m_PlaintextEmpty;
llarp::thread::Queue<CryptoQueue_t> 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

@ -3,8 +3,10 @@
namespace llarp::link
{
Connection::Connection(
std::shared_ptr<oxen::quic::connection_interface>& c, std::shared_ptr<oxen::quic::Stream>& s)
: conn{c}, control_stream{s}
std::shared_ptr<oxen::quic::connection_interface>& c,
std::shared_ptr<oxen::quic::Stream>& s,
RouterContact& rc)
: conn{c}, control_stream{s}, remote_rc{std::move(rc)}
{}
} // namespace llarp::link

@ -9,16 +9,17 @@ namespace llarp::link
{
struct Connection
{
Connection(
std::shared_ptr<oxen::quic::connection_interface>& c,
std::shared_ptr<oxen::quic::Stream>& s);
std::shared_ptr<oxen::quic::connection_interface> conn;
std::shared_ptr<oxen::quic::Stream> 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<oxen::quic::connection_interface>& c,
std::shared_ptr<oxen::quic::Stream>& s,
RouterContact& rc);
};
} // namespace llarp::link

@ -1,72 +0,0 @@
#include "endpoint.hpp"
#include "link_manager.hpp"
namespace llarp::link
{
std::shared_ptr<link::Connection>
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<oxen::quic::Connection*>(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<link::Connection>(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

@ -1,44 +1,12 @@
#pragma once
#include "connection.hpp"
#include "link_manager.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router_id.hpp>
#include <external/oxen-libquic/include/quic.hpp>
namespace llarp::link
{
struct Endpoint
{
Endpoint(std::shared_ptr<oxen::quic::Endpoint> ep, LinkManager& lm)
: endpoint{std::move(ep)}, link_manager{lm}
{}
std::shared_ptr<oxen::quic::Endpoint> 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<RouterID, std::shared_ptr<link::Connection>> conns;
std::unordered_map<oxen::quic::ConnectionID, RouterID> connid_map;
std::shared_ptr<link::Connection>
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

@ -1,43 +0,0 @@
#include "factory.hpp"
#include <llarp/iwp/iwp.hpp>
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

@ -1,48 +0,0 @@
#pragma once
#include <llarp/config/key_manager.hpp>
#include <string_view>
#include <functional>
#include <memory>
#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<LinkLayer_ptr(
std::shared_ptr<KeyManager>,
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

@ -1,54 +1,103 @@
#include "link_manager.hpp"
#include "connection.hpp"
#include <llarp/router/router.hpp>
#include <llarp/router/rc_lookup_handler.hpp>
#include <llarp/nodedb.hpp>
#include <llarp/crypto/crypto.hpp>
#include <algorithm>
#include <set>
namespace llarp
{
namespace link
{
std::shared_ptr<link::Connection>
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<oxen::quic::Network>()}
, tls_creds{oxen::quic::GNUTLSCreds::make_from_ed_keys(
{reinterpret_cast<const char*>(router.encryption().data()), router.encryption().size()},
{reinterpret_cast<const char*>(router.encryption().toPublic().data()), size_t{32}})}
{reinterpret_cast<const char*>(router.identity().data()), size_t{32}},
{reinterpret_cast<const char*>(router.identity().toPublic().data()), size_t{32}})}
, ep{quic->endpoint(router.local), *this}
{}
std::shared_ptr<link::Connection>
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<RouterID, RouterContact> 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<oxen::quic::Stream> 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<RouterID> 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

@ -1,10 +1,11 @@
#pragma once
#include <llarp/router/rc_lookup_handler.hpp>
#include <llarp/router_contact.hpp>
#include <llarp/peerstats/peer_db.hpp>
#include <llarp/crypto/crypto.hpp>
#include <llarp/util/compare_ptr.hpp>
#include "server.hpp"
#include "endpoint.hpp"
#include <external/oxen-libquic/include/quic.hpp>
#include <unordered_map>
@ -20,6 +21,52 @@ namespace
namespace llarp
{
struct LinkManager;
namespace link
{
struct Connection;
struct Endpoint
{
Endpoint(std::shared_ptr<oxen::quic::Endpoint> ep, LinkManager& lm)
: endpoint{std::move(ep)}, link_manager{lm}
{}
std::shared_ptr<oxen::quic::Endpoint> 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<RouterID, std::shared_ptr<link::Connection>> conns;
std::unordered_map<oxen::quic::ConnectionID, RouterID> connid_map;
std::shared_ptr<link::Connection>
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 <typename... Opt>
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> 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<link::Connection>
get_compatible_link(const RouterContact& rc);
std::atomic<bool> 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<RouterID, llarp_time_t> persisting_conns GUARDED_BY(_mutex);
std::unordered_map<RouterID, SessionStats> last_router_stats;
util::DecayingHashSet<RouterID> clients{path::default_lifetime};
RCLookupHandler* _rcLookup;
std::shared_ptr<NodeDB> _nodedb;
RCLookupHandler* rc_lookup;
std::shared_ptr<NodeDB> 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 <typename... Opt>
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<Opt>(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<link::Connection>(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
*/

@ -1,4 +1,3 @@
#include "server.hpp"
#include <llarp/ev/ev.hpp>
#include <llarp/ev/udp_handle.hpp>
#include <llarp/crypto/crypto.hpp>
@ -7,7 +6,7 @@
#include <llarp/util/fs.hpp>
#include <utility>
#include <unordered_set>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <oxenc/variant.h>
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
{

@ -1,278 +0,0 @@
#pragma once
#include <llarp/crypto/types.hpp>
#include <llarp/ev/ev.hpp>
#include "session.hpp"
#include <llarp/net/sock_addr.hpp>
#include <llarp/router_contact.hpp>
#include <llarp/util/status.hpp>
#include <llarp/util/thread/threading.hpp>
#include <llarp/config/key_manager.hpp>
#include <list>
#include <memory>
#include <unordered_map>
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<bool(AbstractLinkSession*, const llarp_buffer_t&)>;
/// 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<bool(Signature&, const llarp_buffer_t&)>;
/// handle connection timeout
///
/// currently called from ILinkLayer::Pump() when an unestablished session times out
using TimeoutHandler = std::function<void(AbstractLinkSession*)>;
/// get our RC
///
/// currently called by iwp::Session to include as part of a LIM (link introduction message)
using GetRCFunc = std::function<const llarp::RouterContact&(void)>;
/// 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<bool(AbstractLinkSession*, bool)>;
/// 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<bool(llarp::RouterContact, llarp::RouterContact)>;
/// 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<void(llarp::RouterID)>;
/// 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<void(void)>;
using Work_t = std::function<void(void)>;
/// queue work to worker thread
using WorkerFunc_t = std::function<void(Work_t)>;
/// before connection hook, called before we try connecting via outbound link
using BeforeConnectFunc_t = std::function<void(llarp::RouterContact)>;
struct ILinkLayer
{
ILinkLayer(
std::shared_ptr<KeyManager> 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<void(const AbstractLinkSession*)> visit, bool randomize = false)
const EXCLUDES(m_AuthedLinksMutex);
void
ForEachSession(std::function<void(AbstractLinkSession*)> 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<AbstractLinkSession>
NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) = 0;
/// fetch a session by the identity pubkey it claims
std::shared_ptr<AbstractLinkSession>
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<bool(AbstractLinkSession*)> 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> 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<int>
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<LockableBase(std::mutex)>;
using Mutex_t = std::mutex;
#else
using Lock_t = util::NullLock;
using Mutex_t = util::NullMutex;
#endif
bool
PutSession(const std::shared_ptr<AbstractLinkSession>& s);
AbstractRouter* m_Router;
SockAddr m_ourAddr;
std::shared_ptr<llarp::UDPHandle> m_udp;
SecretKey m_SecretKey;
using AuthedLinks = std::unordered_multimap<RouterID, std::shared_ptr<AbstractLinkSession>>;
using Pending = std::unordered_map<SockAddr, std::shared_ptr<AbstractLinkSession>>;
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<SockAddr, RouterID> m_AuthedAddrs;
std::unordered_map<SockAddr, llarp_time_t> m_RecentlyClosed;
private:
std::shared_ptr<int> m_repeater_keepalive;
};
using LinkLayer_ptr = std::shared_ptr<ILinkLayer>;
} // namespace llarp

@ -1,11 +0,0 @@
#include "session.hpp"
namespace llarp
{
bool
AbstractLinkSession::IsRelay() const
{
return GetRemoteRC().IsPublicRouter();
}
} // namespace llarp

@ -1,138 +0,0 @@
#pragma once
#include <llarp/crypto/types.hpp>
#include <llarp/net/net.hpp>
#include <llarp/ev/ev.hpp>
#include <llarp/router_contact.hpp>
#include <llarp/util/types.hpp>
#include <functional>
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<void(DeliveryStatus)>;
using Packet_t = std::vector<byte_t>;
using Message_t = std::vector<byte_t>;
/// 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<bool(const LinkIntroMessage* msg)> 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

@ -3,7 +3,7 @@
#include <llarp/config/config.hpp>
#include <llarp/crypto/crypto_libsodium.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/service/context.hpp>
#include <llarp/quic/tunnel.hpp>
#include <llarp/nodedb.hpp>

@ -1,6 +1,6 @@
#include "dht_immediate.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/dht/context.hpp>
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;

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

@ -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);
}

@ -2,7 +2,7 @@
#include <llarp/crypto/crypto.hpp>
#include <llarp/router_contact.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/util/bencode.h>
#include <llarp/util/logging.hpp>
@ -91,7 +91,7 @@ namespace llarp
}
bool
LinkIntroMessage::handle_message(AbstractRouter* /*router*/) const
LinkIntroMessage::handle_message(Router* /*router*/) const
{
if (!verify())
return false;

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

@ -2,7 +2,6 @@
#include "common.hpp"
#include <llarp/link/session.hpp>
#include <llarp/router_id.hpp>
#include <llarp/util/bencode.hpp>
#include <llarp/path/path_types.hpp>
@ -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;

@ -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<msg_holder_t>())
{}

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

@ -1,7 +1,7 @@
#include "relay.hpp"
#include <llarp/path/path_context.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/util/bencode.hpp>
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);

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

@ -5,7 +5,7 @@
#include <llarp/nodedb.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/path/transit_hop.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/outbound_message_handler.hpp>
#include <llarp/routing/path_confirm_message.hpp>
#include <llarp/util/bencode.hpp>
@ -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::TransitHop> 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<LRCMFrameDecrypt> 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<tooling::PathRequestReceivedEvent>(
self->context->Router()->pubkey(), self->hop);
self->context->router()->NotifyRouterEvent<tooling::PathRequestReceivedEvent>(
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;

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

@ -3,7 +3,7 @@
#include <llarp/crypto/crypto.hpp>
#include <llarp/path/path_context.hpp>
#include <llarp/path/ihophandler.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_confirm_message.hpp>
#include <llarp/util/bencode.hpp>
#include <llarp/util/buffer.hpp>
@ -23,14 +23,14 @@ namespace llarp
std::array<EncryptedFrame, 8> frames;
uint64_t status = 0;
HopHandler_ptr hop;
AbstractRouter* router;
Router* router;
PathID_t pathid;
LRSM_AsyncHandler(
std::array<EncryptedFrame, 8> _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<tooling::PathStatusReceivedEvent>(router->pubkey(), pathid, status);
router->notify_router_event<tooling::PathStatusReceivedEvent>(
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<path::TransitHop> 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<LR_StatusMessage> msg,
std::shared_ptr<path::TransitHop> hop)
@ -231,7 +232,7 @@ namespace llarp
void
LR_StatusMessage::SendMessage(
AbstractRouter* router,
Router* router,
const RouterID nextHop,
std::shared_ptr<LR_StatusMessage> msg,
std::shared_ptr<path::TransitHop> hop)

@ -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<path::TransitHop> 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<LR_StatusMessage> msg,
std::shared_ptr<path::TransitHop> hop);
static void
SendMessage(
AbstractRouter* router,
Router* router,
const RouterID nextHop,
std::shared_ptr<LR_StatusMessage> msg,
std::shared_ptr<path::TransitHop> hop);

@ -1,185 +0,0 @@
#include "address_info.hpp"
#include <stdexcept>
#ifndef _WIN32
#include <arpa/inet.h>
#endif
#include "net.hpp"
#include <llarp/util/bencode.h>
#include <llarp/util/mem.h>
#include <cstring>
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<nuint32_t, nuint128_t>
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<const sockaddr_in6*>(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

@ -1,98 +0,0 @@
#pragma once
#include <llarp/crypto/types.hpp>
#include "ip_address.hpp"
#include "net.h"
#include <llarp/util/bencode.hpp>
#include <llarp/util/mem.h>
#include <string>
#include <vector>
#include <oxenc/variant.h>
/**
* 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<net::ipv4addr_t>(&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<AddressInfo> = true;
} // namespace llarp
namespace std
{
template <>
struct hash<llarp::AddressInfo>
{
size_t
operator()(const llarp::AddressInfo& addr) const
{
return std::hash<llarp::PubKey>{}(addr.pubkey);
}
};
} // namespace std

@ -1,7 +1,6 @@
#pragma once
#include "uint128.hpp"
#include "address_info.hpp"
#include "ip_address.hpp"
#include "net_int.hpp"
#include "net.h"

@ -1,5 +1,5 @@
#include "ihophandler.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
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);

@ -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<EncryptedFrame, 8>& frames, AbstractRouter* r) = 0;
HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& 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<TunnelNonce> 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<RelayUpstreamMessage> msgs, AbstractRouter* r) = 0;
HandleAllUpstream(std::vector<RelayUpstreamMessage> msgs, Router* r) = 0;
virtual void
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, AbstractRouter* r) = 0;
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, Router* r) = 0;
};
using HopHandler_ptr = std::shared_ptr<IHopHandler>;

@ -10,7 +10,7 @@
#include "transit_hop.hpp"
#include <llarp/nodedb.hpp>
#include <llarp/profiling.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/routing/path_latency_message.hpp>
#include <llarp/routing/transfer_traffic_message.hpp>
@ -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<EncryptedFrame, 8>& frames, AbstractRouter* r)
Path::HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& frames, Router* r)
{
uint64_t currentStatus = status;
@ -204,7 +204,7 @@ namespace llarp::path
{
if (failedAt)
{
r->NotifyRouterEvent<tooling::PathBuildRejectedEvent>(Endpoint(), RXID(), *failedAt);
r->notify_router_event<tooling::PathBuildRejectedEvent>(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<RelayUpstreamMessage> msgs, AbstractRouter* r)
Path::HandleAllUpstream(std::vector<RelayUpstreamMessage> 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<RelayUpstreamMessage> 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<RelayDownstreamMessage> sendMsgs(msgs.size());
size_t idx = 0;
@ -598,7 +598,7 @@ namespace llarp::path
}
void
Path::HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, AbstractRouter* r)
Path::HandleAllDownstream(std::vector<RelayDownstreamMessage> 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<byte_t, MAX_LINK_MSG_SIZE / 2> 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))

@ -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<EncryptedFrame, 8>& frames, AbstractRouter* r) override;
HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& 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<RelayUpstreamMessage> msgs, AbstractRouter* r) override;
HandleAllUpstream(std::vector<RelayUpstreamMessage> msgs, Router* r) override;
void
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, AbstractRouter* r) override;
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, Router* r) override;
private:
bool
SendLatencyMessage(AbstractRouter* r);
SendLatencyMessage(Router* r);
/// call obtained exit hooks
bool

@ -1,17 +1,16 @@
#include "path.hpp"
#include "path_context.hpp"
#include <llarp/router/outbound_message_handler.hpp>
#include <llarp/messages/relay_commit.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/outbound_message_handler.hpp>
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

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

@ -6,7 +6,7 @@
#include <llarp/nodedb.hpp>
#include <llarp/util/logging.hpp>
#include <llarp/profiling.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/router/rc_lookup_handler.hpp>
#include <llarp/util/buffer.hpp>
#include <llarp/tooling/path_event.hpp>
@ -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<tooling::PathAttemptEvent>(ctx->router->pubkey(), ctx->path);
ctx->router->notify_router_event<tooling::PathAttemptEvent>(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<std::vector<RouterContact>>
Builder::GetHopsAlignedToForBuild(RouterID endpoint, const std::set<RouterID>& exclude)
{
const auto pathConfig = m_router->GetConfig()->paths;
const auto pathConfig = m_router->config()->paths;
std::vector<RouterContact> 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);

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

@ -4,7 +4,7 @@
#include <llarp/router/outbound_message_handler.hpp>
#include <llarp/dht/messages/pubintro.hpp>
#include <llarp/routing/path_dht_message.hpp>
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <random>
@ -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); });
}

@ -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<bool(const service::Introduction&)> 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;

@ -9,7 +9,7 @@
#include <llarp/messages/relay_status.hpp>
#include "path_context.hpp"
#include "transit_hop.hpp"
#include <llarp/router/abstractrouter.hpp>
#include <llarp/router/router.hpp>
#include <llarp/routing/path_latency_message.hpp>
#include <llarp/routing/path_transfer_message.hpp>
#include <llarp/routing/handler.hpp>
@ -50,7 +50,7 @@ namespace llarp::path
}
bool
TransitHop::HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& frames, AbstractRouter* r)
TransitHop::HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& frames, Router* r)
{
auto msg = std::make_shared<LR_StatusMessage>(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<RelayDownstreamMessage> 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<RelayUpstreamMessage> msgs, AbstractRouter* r)
TransitHop::HandleAllUpstream(std::vector<RelayUpstreamMessage> msgs, Router* r)
{
if (IsEndpoint(r->pubkey()))
{
@ -213,7 +213,7 @@ namespace llarp::path
}
void
TransitHop::HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, AbstractRouter* r)
TransitHop::HandleAllDownstream(std::vector<RelayDownstreamMessage> 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(); });
}

@ -100,8 +100,7 @@ namespace llarp
}
bool
HandleLRSM(
uint64_t status, std::array<EncryptedFrame, 8>& frames, AbstractRouter* r) override;
HandleLRSM(uint64_t status, std::array<EncryptedFrame, 8>& 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<RelayUpstreamMessage> msgs, AbstractRouter* r) override;
HandleAllUpstream(std::vector<RelayUpstreamMessage> msgs, Router* r) override;
void
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, AbstractRouter* r) override;
HandleAllDownstream(std::vector<RelayDownstreamMessage> msgs, Router* r) override;
private:
void

@ -1,397 +0,0 @@
#pragma once
#include <llarp/config/config.hpp>
#include <llarp/config/key_manager.hpp>
#include <memory>
#include <llarp/util/types.hpp>
#include <llarp/util/status.hpp>
#include "outbound_message_handler.hpp"
#include <vector>
#include <llarp/ev/ev.hpp>
#include <functional>
#include <llarp/router_contact.hpp>
#include <llarp/tooling/router_event.hpp>
#include <llarp/peerstats/peer_db.hpp>
#include <llarp/consensus/reachability_testing.hpp>
#include <optional>
#ifdef LOKINET_HIVE
#include <llarp/tooling/router_event.hpp>
#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<oxenmq::OxenMQ>;
struct AbstractRouter : public std::enable_shared_from_this<AbstractRouter>
{
#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<rpc::LokidRpcClient>&
RpcClient() const = 0;
virtual std::shared_ptr<dht::AbstractDHTMessageHandler>
dht() const = 0;
virtual const std::shared_ptr<NodeDB>&
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<std::optional<RouterContact>(RouterContact)> modify) = 0;
virtual exit::Context&
exitContext() = 0;
virtual const std::shared_ptr<KeyManager>&
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<void(void)>) = 0;
/// call function in disk io thread
virtual void QueueDiskIO(std::function<void(void)>) = 0;
virtual std::shared_ptr<Config>
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>&
routePoker() const = 0;
virtual RCLookupHandler&
rcLookupHandler() = 0;
virtual std::shared_ptr<PeerDb>
peerDb() = 0;
virtual bool
Sign(Signature& sig, const llarp_buffer_t& buf) const = 0;
virtual bool
Configure(std::shared_ptr<Config> conf, bool isSNode, std::shared_ptr<NodeDB> 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<std::string>
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<std::variant<nuint32_t, nuint128_t>>
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<RouterContact>& results) = 0;
virtual void SetDownHook(std::function<void(void)>){};
/// 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<RouterID>& whitelist,
const std::vector<RouterID>& greylist,
const std::vector<RouterID>& unfundedlist) = 0;
virtual std::unordered_set<RouterID>
GetRouterWhitelist() const = 0;
/// visit each connected link session
virtual void
ForEachPeer(
std::function<void(const AbstractLinkSession*, bool)> 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 <class EventType, class... Params>
void
NotifyRouterEvent([[maybe_unused]] Params&&... args) const
{
// TODO: no-op when appropriate
auto event = std::make_unique<EventType>(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

@ -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);
}

@ -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<PathID_t> roundRobinOrder;
AbstractRouter* _router;
Router* _router;
util::ContentionKiller m_Killer;

@ -1,6 +1,6 @@
#include "outbound_session_maker.hpp"
#include "abstractrouter.hpp"
#include "Router.hpp"
#include <llarp/tooling/peer_stats_event.hpp>
#include <llarp/link/server.hpp>
#include <llarp/router_contact.hpp>
@ -157,7 +157,7 @@ namespace llarp
void
OutboundSessionMaker::Init(
AbstractRouter* router,
Router* router,
LinkManager* linkManager,
RCLookupHandler* rcLookup,
Profiling* profiler,

@ -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 <llarp/util/thread/threading.hpp>
@ -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<RouterID, CallbacksQueue> pendingCallbacks GUARDED_BY(_mutex);
AbstractRouter* _router = nullptr;
Router* _router = nullptr;
LinkManager* _linkManager = nullptr;
RCLookupHandler* _rcLookup = nullptr;
Profiling* _profiler = nullptr;

@ -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<Time_t>(RCGossipFilterDecayInterval))
RCGossiper::RCGossiper() : filter(std::chrono::duration_cast<Time_t>(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<TimePoint_t>
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

@ -3,7 +3,6 @@
#include <llarp/util/decaying_hashset.hpp>
#include "outbound_message_handler.hpp"
#include <llarp/link/link_manager.hpp>
#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<RouterID> m_Filter;
RouterID rid;
Time_t last_rc_gossip = 0s;
LinkManager* link_manager = nullptr;
util::DecayingHashSet<RouterID> filter;
AbstractRouter* m_router;
Router* router;
};
} // namespace llarp

@ -2,7 +2,6 @@
#include "rc_lookup_handler.hpp"
#include <llarp/link/link_manager.hpp>
#include <llarp/link/server.hpp>
#include <llarp/crypto/crypto.hpp>
#include <llarp/service/context.hpp>
#include <llarp/router_contact.hpp>
@ -10,7 +9,7 @@
#include <llarp/util/thread/threading.hpp>
#include <llarp/nodedb.hpp>
#include <llarp/dht/context.hpp>
#include "abstractrouter.hpp"
#include "router.hpp"
#include <iterator>
#include <functional>
@ -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<RouterID>& whitelist,
const std::vector<RouterID>& greylist,
const std::vector<RouterID>& 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<service::Endpoint>& 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<RouterID> 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::AbstractDHTMessageHandler> dht,
RCLookupHandler::init(
std::shared_ptr<dht::AbstractDHTMessageHandler> d,
std::shared_ptr<NodeDB> nodedb,
EventLoop_ptr loop,
WorkerFunc_t dowork,
EventLoop_ptr l,
worker_func dowork,
LinkManager* linkManager,
service::Context* hiddenServiceContext,
const std::unordered_set<RouterID>& 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<RouterContact>& results)
RCLookupHandler::handle_dht_lookup_result(
RouterID remote, const std::vector<RouterContact>& 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

@ -44,20 +44,19 @@ namespace llarp
struct RCLookupHandler
{
public:
using Work_t = std::function<void(void)>;
using WorkerFunc_t = std::function<void(Work_t)>;
using CallbacksQueue = std::list<RCRequestCallback>;
using worker_func = std::function<void(std::function<void()>)>;
using callback_que = std::list<RCRequestCallback>;
~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<RouterID>& whitelist,
const std::vector<RouterID>& greylist,
const std::vector<RouterID>& 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::AbstractDHTMessageHandler> dht,
std::shared_ptr<NodeDB> nodedb,
std::shared_ptr<EventLoop> loop,
WorkerFunc_t dowork,
worker_func dowork,
LinkManager* linkManager,
service::Context* hiddenServiceContext,
const std::unordered_set<RouterID>& strictConnectPubkeys,
@ -122,56 +121,56 @@ namespace llarp
bool isServiceNode_arg);
std::unordered_set<RouterID>
Whitelist() const
whitelist() const
{
util::Lock lock{_mutex};
return whitelistRouters;
return router_whitelist;
}
private:
void
HandleDHTLookupResult(RouterID remote, const std::vector<RouterContact>& results);
handle_dht_lookup_result(RouterID remote, const std::vector<RouterContact>& 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::AbstractDHTMessageHandler> _dht = nullptr;
std::shared_ptr<NodeDB> _nodedb;
std::shared_ptr<EventLoop> _loop;
WorkerFunc_t _work = nullptr;
service::Context* _hiddenServiceContext = nullptr;
LinkManager* _linkManager = nullptr;
std::shared_ptr<dht::AbstractDHTMessageHandler> dht = nullptr;
std::shared_ptr<NodeDB> node_db;
std::shared_ptr<EventLoop> 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<RouterID> _strictConnectPubkeys;
std::unordered_set<RouterID> strict_connect_pubkeys;
std::set<RouterContact> _bootstrapRCList;
std::unordered_set<RouterID> _bootstrapRouterIDList;
std::set<RouterContact> bootstrap_rc_list;
std::unordered_set<RouterID> boostrap_rid_list;
std::unordered_map<RouterID, CallbacksQueue> pendingCallbacks GUARDED_BY(_mutex);
std::unordered_map<RouterID, callback_que> pending_callbacks GUARDED_BY(_mutex);
bool useWhitelist = false;
bool isServiceNode = false;
// whitelist = active routers
std::unordered_set<RouterID> whitelistRouters GUARDED_BY(_mutex);
std::unordered_set<RouterID> router_whitelist GUARDED_BY(_mutex);
// greylist = fully funded, but decommissioned routers
std::unordered_set<RouterID> greylistRouters GUARDED_BY(_mutex);
std::unordered_set<RouterID> router_greylist GUARDED_BY(_mutex);
// greenlist = registered but not fully-staked routers
std::unordered_set<RouterID> greenlistRouters GUARDED_BY(_mutex);
std::unordered_set<RouterID> router_greenlist GUARDED_BY(_mutex);
using TimePoint = std::chrono::steady_clock::time_point;
std::unordered_map<RouterID, TimePoint> _routerLookupTimes;
std::unordered_map<RouterID, TimePoint> router_lookup_times;
};
} // namespace llarp

@ -1,5 +1,5 @@
#include "route_poker.hpp"
#include <llarp/router/abstractrouter.hpp>
#include "router.hpp"
#include <llarp/net/sock_addr.hpp>
#include <llarp/service/context.hpp>
#include <llarp/dns/platform.hpp>
@ -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);

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

Loading…
Cancel
Save