Convert llarp::Router into an abstract base class

pull/284/head
Michael 5 years ago
parent 8096633753
commit 729cd045f1
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C

@ -400,14 +400,14 @@ extern "C"
void
llarp_main_abort(struct llarp_main *ptr)
{
ptr->ctx->router->logic->stop_timer();
ptr->ctx->router->logic()->stop_timer();
}
void
llarp_main_queryDHT_RC(struct llarp_main *ptr,
struct llarp_router_lookup_job *job)
{
llarp_dht_lookup_router(ptr->ctx->router->dht, job);
llarp_dht_lookup_router(ptr->ctx->router->dht(), job);
}
bool
@ -495,8 +495,8 @@ extern "C"
// llarp::Info("checkOnline - DHT nodes ",
// request->ptr->ctx->router->dht->impl.nodes->nodes.size());
request->online = false;
request->nodes = request->ptr->ctx->router->dht->impl.nodes->nodes.size();
if(request->ptr->ctx->router->dht->impl.nodes->nodes.size())
request->nodes = request->ptr->ctx->router->dht()->impl.nodes->nodes.size();
if(request->ptr->ctx->router->dht()->impl.nodes->nodes.size())
{
// llarp::Info("checkOnline - Going to say we're online");
request->online = true;
@ -516,7 +516,7 @@ extern "C"
request->first = true;
llarp::LogInfo("llarp_main_queryDHT_online - We're online");
llarp::LogInfo("llarp_main_queryDHT_online - Querying DHT");
llarp_dht_lookup_router(request->ptr->ctx->router->dht, request->job);
llarp_dht_lookup_router(request->ptr->ctx->router->dht(), request->job);
}
}
@ -525,7 +525,7 @@ extern "C"
{
// llarp::Info("llarp_main_queryDHT - setting up timer");
request->hook = &llarp_main_queryDHT_online;
request->ptr->ctx->router->logic->call_later(
request->ptr->ctx->router->logic()->call_later(
{1000, request, &llarp_main_checkOnline});
// llarp_dht_lookup_router(ptr->ctx->router->dht, job);
}

@ -66,7 +66,7 @@ namespace llarp
return;
Context *ctx = static_cast< Context * >(u);
ctx->Explore(1);
ctx->router->logic->call_later({orig, ctx, &handle_explore_timer});
ctx->router->logic()->call_later({orig, ctx, &handle_explore_timer});
}
void
@ -233,7 +233,7 @@ namespace llarp
llarp::LogDebug("initialize dht with key ", ourKey);
// start exploring
r->logic->call_later(
r->logic()->call_later(
{exploreInterval, this, &llarp::dht::Context::handle_explore_timer});
// start cleanup timer
ScheduleCleanupTimer();
@ -242,7 +242,7 @@ namespace llarp
void
Context::ScheduleCleanupTimer()
{
router->logic->call_later({1000, this, &handle_cleaner_timer});
router->logic()->call_later({1000, this, &handle_cleaner_timer});
}
void
@ -262,11 +262,11 @@ namespace llarp
Context::RelayRequestForPath(const llarp::PathID_t &id, const IMessage *msg)
{
llarp::routing::DHTMessage reply;
if(!msg->HandleMessage(router->dht, reply.M))
if(!msg->HandleMessage(router->dht(), reply.M))
return false;
if(!reply.M.empty())
{
auto path = router->paths.GetByUpstream(router->pubkey(), id);
auto path = router->pathContext().GetByUpstream(router->pubkey(), id);
return path && path->SendRoutingMessage(&reply, router);
}
return true;
@ -419,13 +419,13 @@ namespace llarp
llarp::Crypto *
Context::Crypto() const
{
return router->crypto.get();
return router->crypto();
}
llarp_time_t
Context::Now() const
{
return llarp_ev_loop_time_now_ms(router->netloop);
return router->Now();
}
} // namespace dht

@ -17,7 +17,7 @@
namespace llarp
{
struct Router;
struct AbstractRouter;
namespace dht
{
@ -58,7 +58,7 @@ namespace llarp
virtual llarp::Crypto*
Crypto() const = 0;
virtual llarp::Router*
virtual llarp::AbstractRouter*
GetRouter() const = 0;
virtual const Key_t&
@ -193,7 +193,7 @@ namespace llarp
void
Explore(size_t N = 3);
llarp::Router* router;
llarp::AbstractRouter* router;
// for router contacts
std::unique_ptr< Bucket< RCNode > > nodes;
@ -213,7 +213,7 @@ namespace llarp
return ourKey;
}
llarp::Router*
llarp::AbstractRouter*
GetRouter() const override
{
return router;

@ -25,7 +25,9 @@ namespace llarp
{
// lookup router
parent->LookupRouter(
pk, std::bind(&Router::HandleDHTLookupForExplore, router, pk, _1));
pk,
std::bind(&AbstractRouter::HandleDHTLookupForExplore, router, pk,
_1));
}
}
} // namespace dht

@ -22,7 +22,7 @@ namespace llarp
void
LocalRouterLookup::SendReply()
{
auto path = parent->GetRouter()->paths.GetByUpstream(
auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{

@ -21,7 +21,7 @@ namespace llarp
void
LocalServiceAddressLookup::SendReply()
{
auto path = parent->GetRouter()->paths.GetByUpstream(
auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{

@ -20,7 +20,7 @@ namespace llarp
void
LocalTagLookup::SendReply()
{
auto path = parent->GetRouter()->paths.GetByUpstream(
auto path = parent->GetRouter()->pathContext().GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{

@ -20,7 +20,7 @@ namespace llarp
Key_t k{K};
if(K == us)
{
auto path = dht.router->paths.GetByUpstream(K, pathID);
auto path = dht.router->pathContext().GetByUpstream(K, pathID);
if(path)
{
replies.emplace_back(
@ -33,7 +33,7 @@ namespace llarp
Key_t peer;
// check if we know this in our nodedb first
RouterContact found;
if(dht.router->nodedb->Get(K, found))
if(dht.router->nodedb()->Get(K, found))
{
replies.emplace_back(new GotRouterMessage(k, txid, {found}, false));
return true;
@ -159,7 +159,7 @@ namespace llarp
Key_t k{K};
if(exploritory)
return dht.HandleExploritoryRouterLookup(From, txid, K, replies);
else if(dht.router->nodedb->Get(K, found))
else if(dht.router->nodedb()->Get(K, found))
{
replies.emplace_back(new GotRouterMessage(k, txid, {found}, false));
return true;

@ -25,7 +25,7 @@ namespace llarp
std::vector< std::unique_ptr< IMessage > > &replies) const
{
auto &dht = ctx->impl;
auto crypto = dht.router->crypto.get();
auto crypto = dht.router->crypto();
for(const auto &introset : I)
{
@ -70,7 +70,7 @@ namespace llarp
std::vector< std::unique_ptr< IMessage > > &replies) const
{
// TODO: implement me better?
auto pathset = ctx->impl.router->paths.GetLocalPathSet(pathID);
auto pathset = ctx->impl.router->pathContext().GetLocalPathSet(pathID);
if(pathset)
{
return pathset->HandleGotIntroMessage(this);

@ -87,7 +87,7 @@ namespace llarp
auto &dht = ctx->impl;
if(relayed)
{
auto pathset = ctx->impl.router->paths.GetLocalPathSet(pathID);
auto pathset = ctx->impl.router->pathContext().GetLocalPathSet(pathID);
return pathset && pathset->HandleGotRouterMessage(this);
}
// not relayed

@ -53,7 +53,7 @@ namespace llarp
return false;
}
auto &dht = ctx->impl;
if(!I.Verify(dht.router->crypto.get(), now))
if(!I.Verify(dht.router->crypto(), now))
{
llarp::LogWarn("invalid introset: ", I);
// don't propogate or store
@ -63,7 +63,7 @@ namespace llarp
using namespace std::placeholders;
shorthash_func shorthash =
std::bind(&Crypto::shorthash, dht.router->crypto.get(), _1, _2);
std::bind(&Crypto::shorthash, dht.router->crypto(), _1, _2);
if(I.W && !I.W->IsValid(shorthash, now))
{
llarp::LogWarn("proof of work not good enough for IntroSet");

@ -11,13 +11,13 @@ namespace llarp
const llarp::RouterID& router,
std::function< bool(const llarp_buffer_t&) > writepkt, llarp::Router* r,
size_t numpaths, size_t hoplen)
: llarp::path::Builder(r, r->dht, numpaths, hoplen)
: llarp::path::Builder(r, r->dht(), numpaths, hoplen)
, m_ExitRouter(router)
, m_WritePacket(writepkt)
, m_Counter(0)
, m_LastUse(0)
{
r->crypto->identity_keygen(m_ExitIdentity);
r->crypto()->identity_keygen(m_ExitIdentity);
}
BaseSession::~BaseSession()
@ -79,7 +79,7 @@ namespace llarp
obtain.S = p->NextSeqNo();
obtain.T = llarp::randint();
PopulateRequest(obtain);
if(!obtain.Sign(router->crypto.get(), m_ExitIdentity))
if(!obtain.Sign(router->crypto(), m_ExitIdentity))
{
llarp::LogError("Failed to sign exit request");
return;
@ -108,7 +108,7 @@ namespace llarp
{
llarp::LogInfo(p->Name(), " closing exit path");
llarp::routing::CloseExitMessage msg;
if(!(msg.Sign(router->crypto.get(), m_ExitIdentity)
if(!(msg.Sign(router->crypto(), m_ExitIdentity)
&& p->SendExitClose(&msg, router)))
llarp::LogWarn(p->Name(), " failed to send exit close message");
}

@ -246,7 +246,7 @@ namespace llarp
Crypto *
ExitEndpoint::GetCrypto()
{
return m_Router->crypto.get();
return m_Router->crypto();
}
huint32_t

@ -551,7 +551,7 @@ namespace llarp
NewServerFromRouter(llarp::Router* r)
{
return NewServer(
r->crypto.get(), r->encryption, std::bind(&llarp::Router::rc, r),
r->crypto(), r->encryption, std::bind(&llarp::Router::rc, r),
std::bind(&llarp::Router::HandleRecvLinkMessageBuffer, r,
std::placeholders::_1, std::placeholders::_2),
std::bind(&llarp::Router::OnSessionEstablished, r,

@ -72,7 +72,7 @@ namespace llarp
bool result = true;
for(auto &msg : msgs)
{
result &= msg->HandleMessage(router->dht, reply.msgs);
result &= msg->HandleMessage(router->dht(), reply.msgs);
}
if(reply.msgs.size())
{

@ -117,7 +117,7 @@ namespace llarp
bool
LinkIntroMessage::HandleMessage(llarp::Router* router) const
{
if(!Verify(router->crypto.get()))
if(!Verify(router->crypto()))
return false;
return session->GotLIM(this);
}

@ -43,13 +43,13 @@ namespace llarp
llarp::Crypto*
PathContext::Crypto()
{
return m_Router->crypto.get();
return m_Router->crypto();
}
llarp::Logic*
PathContext::Logic()
{
return m_Router->logic;
return m_Router->logic();
}
llarp::SecretKey&
@ -155,24 +155,26 @@ namespace llarp
IHopHandler*
PathContext::GetByUpstream(const RouterID& remote, const PathID_t& id)
{
auto own = MapGet(m_OurPaths, id,
[](__attribute__((unused)) const PathSet* s) -> bool {
// TODO: is this right?
return true;
},
[remote, id](PathSet* p) -> IHopHandler* {
return p->GetByUpstream(remote, id);
});
auto own = MapGet(
m_OurPaths, id,
[](__attribute__((unused)) const PathSet* s) -> bool {
// TODO: is this right?
return true;
},
[remote, id](PathSet* p) -> IHopHandler* {
return p->GetByUpstream(remote, id);
});
if(own)
return own;
return MapGet(m_TransitPaths, id,
[remote](const std::shared_ptr< TransitHop >& hop) -> bool {
return hop->info.upstream == remote;
},
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
return h.get();
});
return MapGet(
m_TransitPaths, id,
[remote](const std::shared_ptr< TransitHop >& hop) -> bool {
return hop->info.upstream == remote;
},
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
return h.get();
});
}
bool
@ -189,13 +191,14 @@ namespace llarp
IHopHandler*
PathContext::GetByDownstream(const RouterID& remote, const PathID_t& id)
{
return MapGet(m_TransitPaths, id,
[remote](const std::shared_ptr< TransitHop >& hop) -> bool {
return hop->info.downstream == remote;
},
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
return h.get();
});
return MapGet(
m_TransitPaths, id,
[remote](const std::shared_ptr< TransitHop >& hop) -> bool {
return hop->info.downstream == remote;
},
[](const std::shared_ptr< TransitHop >& h) -> IHopHandler* {
return h.get();
});
}
PathSet*
@ -505,12 +508,12 @@ namespace llarp
bool
Path::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r)
AbstractRouter* r)
{
TunnelNonce n = Y;
for(const auto& hop : hops)
{
r->crypto->xchacha20(buf, hop.shared, n);
r->crypto()->xchacha20(buf, hop.shared, n);
n ^= hop.nonceXOR;
}
RelayUpstreamMessage msg;
@ -544,19 +547,19 @@ namespace llarp
bool
Path::HandleDownstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r)
AbstractRouter* r)
{
TunnelNonce n = Y;
for(const auto& hop : hops)
{
n ^= hop.nonceXOR;
r->crypto->xchacha20(buf, hop.shared, n);
r->crypto()->xchacha20(buf, hop.shared, n);
}
return HandleRoutingMessage(buf, r);
}
bool
Path::HandleRoutingMessage(const llarp_buffer_t& buf, llarp::Router* r)
Path::HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r)
{
if(!r->ParseRoutingMessageBuffer(buf, this, RXID()))
{
@ -587,7 +590,7 @@ namespace llarp
bool
Path::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r)
llarp::AbstractRouter* r)
{
std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp;
llarp_buffer_t buf(tmp);
@ -609,7 +612,7 @@ namespace llarp
if(buf.sz < MESSAGE_PAD_SIZE)
{
// randomize padding
r->crypto->randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz);
r->crypto()->randbytes(buf.cur, MESSAGE_PAD_SIZE - buf.sz);
buf.sz = MESSAGE_PAD_SIZE;
}
buf.cur = buf.base;
@ -699,7 +702,7 @@ namespace llarp
Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp::Router* r)
{
llarp::routing::DHTMessage reply;
if(!msg->HandleMessage(r->dht, reply.M))
if(!msg->HandleMessage(r->dht(), reply.M))
return false;
MarkActive(r->Now());
if(reply.M.size())
@ -714,7 +717,7 @@ namespace llarp
/// allows exits to close from their end
if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC))
{
if(msg->Verify(r->crypto.get(), EndpointPubKey()))
if(msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogInfo(Name(), " had its exit closed");
_role &= ~ePathRoleExit;
@ -773,7 +776,7 @@ namespace llarp
{
if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{
if(!msg->Verify(r->crypto.get(), EndpointPubKey()))
if(!msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogError(Name(), "RXM invalid signature");
return false;
@ -792,7 +795,7 @@ namespace llarp
{
if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{
if(!msg->Verify(r->crypto.get(), EndpointPubKey()))
if(!msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogError(Name(), " GXM signature failed");
return false;

@ -32,6 +32,7 @@
namespace llarp
{
struct AbstractRouter;
struct Crypto;
struct LR_CommitMessage;
struct LR_CommitRecord;
@ -112,17 +113,17 @@ namespace llarp
/// send routing message and increment sequence number
virtual bool
SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) = 0;
llarp::AbstractRouter* r) = 0;
// handle data in upstream direction
virtual bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) = 0;
AbstractRouter* r) = 0;
// handle data in downstream direction
virtual bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) = 0;
AbstractRouter* r) = 0;
/// return timestamp last remote activity happened at
virtual llarp_time_t
@ -188,12 +189,12 @@ namespace llarp
// send routing message when end of path
bool
SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
// handle routing message when end of path
bool
HandleRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r);
AbstractRouter* r);
bool
HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg,
@ -257,12 +258,12 @@ namespace llarp
// handle data in upstream direction
bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override;
AbstractRouter* r) override;
// handle data in downstream direction
bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override;
AbstractRouter* r) override;
};
/// configuration for a single hop when building a path
@ -417,7 +418,7 @@ namespace llarp
bool
SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r) override;
llarp::AbstractRouter* r) override;
bool
HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg,
@ -475,17 +476,17 @@ namespace llarp
llarp::Router* r) override;
bool
HandleRoutingMessage(const llarp_buffer_t& buf, llarp::Router* r);
HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r);
// handle data in upstream direction
bool
HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override;
AbstractRouter* r) override;
// handle data in downstream direction
bool
HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
IsReady() const;

@ -173,8 +173,8 @@ namespace llarp
, dht(p_dht)
, numHops(hops)
{
p_router->paths.AddPathBuilder(this);
p_router->crypto->encryption_keygen(enckey);
p_router->pathContext().AddPathBuilder(this);
p_router->crypto()->encryption_keygen(enckey);
_run.store(true);
keygens.store(0);
}
@ -246,7 +246,7 @@ namespace llarp
Builder::BuildOne(PathRole roles)
{
std::vector< RouterContact > hops;
if(SelectHops(router->nodedb, hops, roles))
if(SelectHops(router->nodedb(), hops, roles))
Build(hops, roles);
}
@ -294,14 +294,14 @@ namespace llarp
lastBuild = Now();
// async generate keys
AsyncPathKeyExchangeContext< Builder >* ctx =
new AsyncPathKeyExchangeContext< Builder >(router->crypto.get());
new AsyncPathKeyExchangeContext< Builder >(router->crypto());
ctx->router = router;
ctx->pathset = this;
auto path = new llarp::path::Path(hops, this, roles);
path->SetBuildResultHook(std::bind(&llarp::path::Builder::HandlePathBuilt,
this, std::placeholders::_1));
++keygens;
ctx->AsyncGenerateKeys(path, router->logic, router->tp, this,
ctx->AsyncGenerateKeys(path, router->logic(), router->tp, this,
&PathBuilderKeysGenerated);
}

@ -55,7 +55,7 @@ namespace llarp
bool
TransitHop::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r)
AbstractRouter* r)
{
if(!IsEndpoint(r->pubkey()))
return false;
@ -76,7 +76,7 @@ namespace llarp
{
dlt = MESSAGE_PAD_SIZE - dlt;
// randomize padding
r->crypto->randbytes(buf.cur, dlt);
r->crypto()->randbytes(buf.cur, dlt);
buf.sz += dlt;
}
buf.cur = buf.base;
@ -85,12 +85,12 @@ namespace llarp
bool
TransitHop::HandleDownstream(const llarp_buffer_t& buf,
const TunnelNonce& Y, llarp::Router* r)
const TunnelNonce& Y, AbstractRouter* r)
{
RelayDownstreamMessage msg;
msg.pathid = info.rxID;
msg.Y = Y ^ nonceXOR;
r->crypto->xchacha20(buf, pathKey, Y);
r->crypto()->xchacha20(buf, pathKey, Y);
msg.X = buf;
llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ",
info.upstream, " to ", info.downstream);
@ -99,9 +99,9 @@ namespace llarp
bool
TransitHop::HandleUpstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r)
AbstractRouter* r)
{
r->crypto->xchacha20(buf, pathKey, Y);
r->crypto()->xchacha20(buf, pathKey, Y);
if(IsEndpoint(r->pubkey()))
{
m_LastActivity = r->Now();
@ -124,7 +124,7 @@ namespace llarp
TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp::Router* r)
{
return r->dht->impl.RelayRequestForPath(info.rxID, msg);
return r->dht()->impl.RelayRequestForPath(info.rxID, msg);
}
bool
@ -158,13 +158,13 @@ namespace llarp
TransitHop::HandleObtainExitMessage(
const llarp::routing::ObtainExitMessage* msg, llarp::Router* r)
{
if(msg->Verify(r->crypto.get())
if(msg->Verify(r->crypto())
&& r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0))
{
llarp::routing::GrantExitMessage grant;
grant.S = NextSeqNo();
grant.T = msg->T;
if(!grant.Sign(r->crypto.get(), r->identity))
if(!grant.Sign(r->crypto(), r->identity))
{
llarp::LogError("Failed to sign grant exit message");
return false;
@ -176,7 +176,7 @@ namespace llarp
llarp::routing::RejectExitMessage reject;
reject.S = NextSeqNo();
reject.T = msg->T;
if(!reject.Sign(r->crypto.get(), r->identity))
if(!reject.Sign(r->crypto(), r->identity))
{
llarp::LogError("Failed to sign reject exit message");
return false;
@ -190,13 +190,13 @@ namespace llarp
{
llarp::routing::DataDiscardMessage discard(info.rxID, msg->S);
auto ep = r->exitContext.FindEndpointForPath(info.rxID);
if(ep && msg->Verify(r->crypto.get(), ep->PubKey()))
if(ep && msg->Verify(r->crypto(), ep->PubKey()))
{
ep->Close();
// ep is now gone af
llarp::routing::CloseExitMessage reply;
reply.S = NextSeqNo();
if(reply.Sign(r->crypto.get(), r->identity))
if(reply.Sign(r->crypto(), r->identity))
return SendRoutingMessage(&reply, r);
}
return SendRoutingMessage(&discard, r);
@ -219,7 +219,7 @@ namespace llarp
auto ep = r->exitContext.FindEndpointForPath(msg->P);
if(ep)
{
if(!msg->Verify(r->crypto.get(), ep->PubKey()))
if(!msg->Verify(r->crypto(), ep->PubKey()))
return false;
if(ep->UpdateLocalPath(info.rxID))

@ -80,7 +80,9 @@ struct TryConnectJob
if(!router->IsServiceNode())
{
if(router->routerProfiling.IsBad(rc.pubkey))
router->nodedb->Remove(rc.pubkey);
{
router->nodedb()->Remove(rc.pubkey);
}
}
// delete this
router->pendingEstablishJobs.erase(rc.pubkey);
@ -164,6 +166,10 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &path,
namespace llarp
{
AbstractRouter::~AbstractRouter()
{
}
bool
Router::TryConnectAsync(llarp::RouterContact remote, uint16_t numretries)
{
@ -186,7 +192,7 @@ namespace llarp
// only try establishing if we inserted a new element
TryConnectJob *job = itr.first->second.get();
// try establishing async
logic->queue_job({job, &on_try_connecting});
_logic->queue_job({job, &on_try_connecting});
return true;
}
}
@ -201,15 +207,15 @@ namespace llarp
}
Router::Router(struct llarp_threadpool *_tp, struct llarp_ev_loop *_netloop,
llarp::Logic *_logic)
llarp::Logic *l)
: ready(false)
, netloop(_netloop)
, tp(_tp)
, logic(_logic)
, crypto(std::make_unique< sodium::CryptoLibSodium >())
, _logic(l)
, _crypto(std::make_unique< sodium::CryptoLibSodium >())
, paths(this)
, exitContext(this)
, dht(llarp_dht_context_new(this))
, _dht(llarp_dht_context_new(this))
, inbound_link_msg_parser(this)
, hiddenServiceContext(this)
{
@ -228,7 +234,7 @@ namespace llarp
Router::~Router()
{
llarp_dht_context_free(dht);
llarp_dht_context_free(_dht);
}
bool
@ -257,10 +263,10 @@ namespace llarp
bool
Router::GetRandomGoodRouter(RouterID &router)
{
auto sz = nodedb->entries.size();
auto sz = nodedb()->entries.size();
if(sz == 0)
return false;
auto itr = nodedb->entries.begin();
auto itr = nodedb()->entries.begin();
if(sz > 1)
std::advance(itr, randint() % sz);
router = itr->first;
@ -317,7 +323,7 @@ namespace llarp
}
llarp::RouterContact remoteRC;
// we don't have an open session to that router right now
if(nodedb->Get(remote, remoteRC))
if(nodedb()->Get(remote, remoteRC))
{
// try connecting directly as the rc is loaded from disk
TryConnectAsync(remoteRC, 10);
@ -325,9 +331,9 @@ namespace llarp
}
// we don't have the RC locally so do a dht lookup
dht->impl.LookupRouter(remote,
std::bind(&Router::HandleDHTLookupForSendTo, this,
remote, std::placeholders::_1));
_dht->impl.LookupRouter(remote,
std::bind(&Router::HandleDHTLookupForSendTo, this,
remote, std::placeholders::_1));
return true;
}
@ -343,9 +349,9 @@ namespace llarp
{
return;
}
if(results[0].Verify(crypto.get(), Now()))
if(results[0].Verify(crypto(), Now()))
{
nodedb->Insert(results[0]);
nodedb()->Insert(results[0]);
TryConnectAsync(results[0], 10);
return;
}
@ -391,11 +397,11 @@ namespace llarp
llarp::LogError("failure to decode or verify of remote RC");
return;
}
if(remote.Verify(crypto.get(), Now()))
if(remote.Verify(crypto(), Now()))
{
llarp::LogDebug("verified signature");
// store into filesystem
if(!nodedb->Insert(remote))
if(!nodedb()->Insert(remote))
{
llarp::LogWarn("failed to store");
}
@ -415,16 +421,16 @@ namespace llarp
if(!EnsureEncryptionKey())
return false;
if(usingSNSeed)
return llarp_loadServiceNodeIdentityKey(crypto.get(), ident_keyfile,
return llarp_loadServiceNodeIdentityKey(crypto(), ident_keyfile,
identity);
else
return llarp_findOrCreateIdentity(crypto.get(), ident_keyfile, identity);
return llarp_findOrCreateIdentity(crypto(), ident_keyfile, identity);
}
bool
Router::EnsureEncryptionKey()
{
return llarp_findOrCreateEncryption(crypto.get(), encryption_keyfile,
return llarp_findOrCreateEncryption(crypto(), encryption_keyfile,
this->encryption);
}
@ -460,7 +466,7 @@ namespace llarp
Router::SaveRC()
{
llarp::LogDebug("verify RC signature");
if(!_rc.Verify(crypto.get(), Now()))
if(!_rc.Verify(crypto(), Now()))
{
rc().Dump< MAX_RC_SIZE >();
llarp::LogError("RC is invalid, not saving");
@ -532,7 +538,7 @@ namespace llarp
router->validRouters.emplace(pk, rc);
// track valid router in dht
router->dht->impl.nodes->PutNode(rc);
router->dht()->impl.nodes->PutNode(rc);
// mark success in profile
router->routerProfiling.MarkSuccess(pk);
@ -586,8 +592,8 @@ namespace llarp
return;
for(const auto &rc : results)
{
if(rc.Verify(crypto.get(), Now()))
nodedb->Insert(rc);
if(rc.Verify(crypto(), Now()))
nodedb()->Insert(rc);
else
return;
}
@ -608,18 +614,18 @@ namespace llarp
}
llarp::RouterContact rc;
if(nodedb->Get(remote, rc))
if(nodedb()->Get(remote, rc))
{
// try connecting async
TryConnectAsync(rc, 5);
}
else if(IsServiceNode() || !routerProfiling.IsBad(remote))
{
if(dht->impl.HasRouterLookup(remote))
if(dht()->impl.HasRouterLookup(remote))
return;
llarp::LogInfo("looking up router ", remote);
// dht lookup as we don't know it
dht->impl.LookupRouter(
dht()->impl.LookupRouter(
remote,
std::bind(&Router::HandleDHTLookupForTryEstablishTo, this, remote,
std::placeholders::_1));
@ -655,7 +661,7 @@ namespace llarp
if(whitelistRouters
&& lokinetRouters.find(result.pubkey) == lokinetRouters.end())
continue;
nodedb->Insert(result);
nodedb()->Insert(result);
TryConnectAsync(result, 10);
}
}
@ -673,7 +679,7 @@ namespace llarp
llarp::RouterContact nextRC = _rc;
if(rotateKeys)
{
crypto->encryption_keygen(nextOnionKey);
crypto()->encryption_keygen(nextOnionKey);
std::string f = encryption_keyfile.string();
if(nextOnionKey.SaveToFile(f.c_str()))
{
@ -682,7 +688,7 @@ namespace llarp
}
}
nextRC.last_updated = Now();
if(!nextRC.Sign(crypto.get(), identity))
if(!nextRC.Sign(crypto(), identity))
return false;
_rc = nextRC;
// propagate RC by renegotiating sessions
@ -705,11 +711,11 @@ namespace llarp
return false;
// store it in nodedb async
nodedb->InsertAsync(newrc);
nodedb()->InsertAsync(newrc);
// update dht if required
if(dht->impl.nodes->HasNode(dht::Key_t{newrc.pubkey}))
if(dht()->impl.nodes->HasNode(dht::Key_t{newrc.pubkey}))
{
dht->impl.nodes->PutNode(newrc);
dht()->impl.nodes->PutNode(newrc);
}
// update valid routers
{
@ -726,9 +732,9 @@ namespace llarp
void
Router::ServiceNodeLookupRouterWhenExpired(RouterID router)
{
dht->impl.LookupRouter(router,
std::bind(&Router::HandleDHTLookupForExplore, this,
router, std::placeholders::_1));
dht()->impl.LookupRouter(router,
std::bind(&Router::HandleDHTLookupForExplore, this,
router, std::placeholders::_1));
}
void
@ -748,7 +754,7 @@ namespace llarp
{
// only do this as service node
// client endpoints do this on their own
nodedb->visit([&](const RouterContact &rc) -> bool {
nodedb()->visit([&](const RouterContact &rc) -> bool {
if(rc.ExpiresSoon(now, llarp::randint() % 10000))
ServiceNodeLookupRouterWhenExpired(rc.pubkey);
return true;
@ -783,7 +789,7 @@ namespace llarp
}
}
size_t N = nodedb->num_loaded();
size_t N = nodedb()->num_loaded();
if(N < minRequiredRouters)
{
llarp::LogInfo("We need at least ", minRequiredRouters,
@ -795,7 +801,7 @@ namespace llarp
for(const auto &rc : bootstrapRCList)
{
TryConnectAsync(rc, 4);
dht->impl.ExploreNetworkVia(dht::Key_t{rc.pubkey});
dht()->impl.ExploreNetworkVia(dht::Key_t{rc.pubkey});
}
}
else
@ -819,7 +825,7 @@ namespace llarp
bool
Router::Sign(llarp::Signature &sig, const llarp_buffer_t &buf) const
{
return crypto->sign(sig, identity, buf);
return crypto()->sign(sig, identity, buf);
}
void
@ -859,13 +865,13 @@ namespace llarp
void
Router::ScheduleTicker(uint64_t ms)
{
ticker_job_id = logic->call_later({ms, this, &handle_router_ticker});
ticker_job_id = _logic->call_later({ms, this, &handle_router_ticker});
}
void
Router::SessionClosed(llarp::RouterID remote)
{
__llarp_dht_remove_peer(dht, remote.data());
__llarp_dht_remove_peer(dht(), remote.data());
// remove from valid routers if it's a valid router
validRouters.erase(remote);
llarp::LogInfo("Session to ", remote, " fully closed");
@ -966,9 +972,8 @@ namespace llarp
job->valid = false;
job->hook = nullptr;
job->nodedb = nodedb;
job->logic = logic;
// job->crypto = crypto.get(); // we already have this
job->nodedb = _nodedb;
job->logic = _logic;
job->cryptoworker = tp;
job->diskworker = disk;
if(rc.IsPublicRouter())
@ -984,7 +989,7 @@ namespace llarp
{
if(_running || _stopping)
return false;
this->nodedb = nodedb;
this->_nodedb = nodedb;
if(enableRPCServer)
{
@ -1066,7 +1071,7 @@ namespace llarp
a);
}
llarp::LogInfo("Signing rc...");
if(!_rc.Sign(crypto.get(), identity))
if(!_rc.Sign(crypto(), identity))
{
llarp::LogError("failed to sign rc");
return false;
@ -1083,7 +1088,7 @@ namespace llarp
llarp::LogInfo("starting outbound ", outboundLinks.size(), " links");
for(const auto &link : outboundLinks)
{
if(!link->Start(logic))
if(!link->Start(_logic))
{
llarp::LogWarn("outbound link '", link->Name(), "' failed to start");
return false;
@ -1095,7 +1100,7 @@ namespace llarp
// start links
for(const auto &link : inboundLinks)
{
if(link->Start(logic))
if(link->Start(_logic))
{
llarp::LogDebug("Link ", link->Name(), " started");
IBLinksStarted++;
@ -1119,11 +1124,11 @@ namespace llarp
{
// we are a client
// regenerate keys and resign rc before everything else
crypto->identity_keygen(identity);
crypto->encryption_keygen(encryption);
crypto()->identity_keygen(identity);
crypto()->encryption_keygen(encryption);
_rc.pubkey = llarp::seckey_topublic(identity);
_rc.enckey = llarp::seckey_topublic(encryption);
if(!_rc.Sign(crypto.get(), identity))
if(!_rc.Sign(crypto(), identity))
{
llarp::LogError("failed to regenerate keys and sign RC");
return false;
@ -1148,7 +1153,7 @@ namespace llarp
llarp::LogError("Failed to start hidden service context");
return false;
}
llarp_dht_context_start(dht, pubkey());
llarp_dht_context_start(dht(), pubkey());
ScheduleTicker(1000);
_running.store(true);
return _running;
@ -1166,7 +1171,7 @@ namespace llarp
{
Router *self = static_cast< Router * >(u);
self->StopLinks();
self->logic->call_later({200, self, &RouterAfterStopLinks});
self->_logic->call_later({200, self, &RouterAfterStopLinks});
}
void
@ -1271,7 +1276,7 @@ namespace llarp
exitContext.Stop();
if(rpcServer)
rpcServer->Stop();
logic->call_later({200, this, &RouterAfterStopIssued});
_logic->call_later({200, this, &RouterAfterStopIssued});
}
bool
@ -1286,7 +1291,7 @@ namespace llarp
int wanted = want;
Router *self = this;
self->nodedb->visit(
self->nodedb()->visit(
[self, &want](const llarp::RouterContact &other) -> bool {
// check if we really want to
if(other.ExpiresSoon(self->Now(), 30000))
@ -1312,7 +1317,7 @@ namespace llarp
{
llarp::LogInfo("accepting transit traffic");
paths.AllowTransit();
llarp_dht_allow_transit(dht);
llarp_dht_allow_transit(dht());
return exitContext.AddExitEndpoint("default-connectivity", netConfig);
}
@ -1643,7 +1648,7 @@ namespace llarp
self->bootstrapRCList.pop_back();
return;
}
if(rc.Verify(self->crypto.get(), self->Now()))
if(rc.Verify(self->crypto(), self->Now()))
{
llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey));
}

@ -65,7 +65,55 @@ namespace llarp
}
};
struct Router
struct AbstractRouter
{
virtual ~AbstractRouter() = 0;
virtual Logic *
logic() const = 0;
virtual llarp_dht_context *
dht() const = 0;
virtual Crypto *
crypto() const = 0;
virtual llarp_nodedb *
nodedb() const = 0;
virtual const path::PathContext &
pathContext() const = 0;
virtual path::PathContext &
pathContext() = 0;
virtual const llarp::RouterContact &
rc() const = 0;
virtual const byte_t *
pubkey() const = 0;
virtual llarp_time_t
Now() const = 0;
virtual bool
SendToOrQueue(const llarp::RouterID &remote,
const llarp::ILinkMessage *msg) = 0;
virtual void
PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until) = 0;
virtual bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h, PathID_t rxid) = 0;
virtual void
HandleDHTLookupForExplore(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results) = 0;
};
struct Router final : public AbstractRouter
{
bool ready;
// transient iwp encryption key
@ -92,8 +140,44 @@ namespace llarp
/// should we obey the service node whitelist?
bool whitelistRouters = false;
Logic *
logic() const override
{
return _logic;
}
llarp_dht_context *
dht() const override
{
return _dht;
}
Crypto *
crypto() const override
{
return _crypto.get();
}
llarp_nodedb *
nodedb() const override
{
return _nodedb;
}
const path::PathContext &
pathContext() const override
{
return paths;
}
path::PathContext &
pathContext() override
{
return paths;
}
const llarp::RouterContact &
rc() const
rc() const override
{
return _rc;
}
@ -105,20 +189,19 @@ namespace llarp
llarp_ev_loop *netloop;
llarp_threadpool *tp;
llarp::Logic *logic;
std::unique_ptr< llarp::Crypto > crypto;
llarp::path::PathContext paths;
llarp::exit::Context exitContext;
llarp::SecretKey identity;
llarp::SecretKey encryption;
Logic *_logic;
std::unique_ptr< Crypto > _crypto;
path::PathContext paths;
exit::Context exitContext;
SecretKey identity;
SecretKey encryption;
llarp_threadpool *disk;
llarp_dht_context *dht = nullptr;
llarp_dht_context *_dht = nullptr;
llarp_nodedb *_nodedb;
bool
Sign(Signature &sig, const llarp_buffer_t &buf) const;
llarp_nodedb *nodedb;
// buffer for serializing link messages
std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer;
@ -276,7 +359,8 @@ namespace llarp
StopLinks();
void
PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until);
PersistSessionUntil(const llarp::RouterID &remote,
llarp_time_t until) override;
bool
EnsureIdentity();
@ -291,7 +375,7 @@ namespace llarp
SaveRC();
const byte_t *
pubkey() const
pubkey() const override
{
return llarp::seckey_topublic(identity);
}
@ -322,7 +406,7 @@ namespace llarp
/// MUST be called in the logic thread
bool
SendToOrQueue(const llarp::RouterID &remote,
const llarp::ILinkMessage *msg);
const llarp::ILinkMessage *msg) override;
/// sendto or drop
void
@ -349,7 +433,7 @@ namespace llarp
void
HandleDHTLookupForExplore(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results);
const std::vector< llarp::RouterContact > &results) override;
void
ForEachPeer(
@ -379,7 +463,7 @@ namespace llarp
/// get time from event loop
llarp_time_t
Now() const
Now() const override
{
return llarp_ev_loop_time_now_ms(netloop);
}
@ -396,7 +480,8 @@ namespace llarp
/// return false
bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h, PathID_t rxid);
routing::IMessageHandler *h,
PathID_t rxid) override;
void
ConnectToRandomRouters(int N);

@ -332,7 +332,7 @@ namespace llarp
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port);
return _handler.ServeAsync(router->netloop, router->logic,
return _handler.ServeAsync(router->netloop, router->logic(),
(const sockaddr*)&saddr);
}
};

@ -82,7 +82,7 @@ namespace llarp
++itr;
}
}
m_Router->nodedb->visit([&](const RouterContact &rc) -> bool {
m_Router->nodedb()->visit([&](const RouterContact &rc) -> bool {
if(rc.IsExpired(now))
getFirstEndpoint()->LookupRouterAnon(rc.pubkey);
return true;

@ -18,7 +18,7 @@ namespace llarp
{
Endpoint::Endpoint(const std::string& name, llarp::Router* r,
Context* parent)
: path::Builder(r, r->dht, 6, DEFAULT_HOP_LENGTH)
: path::Builder(r, r->dht(), 6, DEFAULT_HOP_LENGTH)
, context(parent)
, m_Router(r)
, m_Name(name)
@ -118,7 +118,7 @@ namespace llarp
return;
}
m_IntroSet.topic = m_Tag;
if(!m_Identity.SignIntroSet(m_IntroSet, m_Router->crypto.get(), now))
if(!m_Identity.SignIntroSet(m_IntroSet, m_Router->crypto(), now))
{
llarp::LogWarn("failed to sign introset for endpoint ", Name());
return;
@ -360,7 +360,7 @@ namespace llarp
bool
Endpoint::HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg)
{
auto crypto = m_Router->crypto.get();
auto crypto = m_Router->crypto();
std::set< IntroSet > remote;
for(const auto& introset : msg->I)
{
@ -500,7 +500,7 @@ namespace llarp
bool
Endpoint::LoadKeyFile()
{
auto crypto = m_Router->crypto.get();
auto crypto = m_Router->crypto();
if(m_Keyfile.size())
{
if(!m_Identity.EnsureKeys(m_Keyfile, crypto))
@ -765,10 +765,10 @@ namespace llarp
if(itr == m_PendingRouters.end())
return false;
llarp_async_verify_rc* job = new llarp_async_verify_rc;
job->nodedb = m_Router->nodedb;
job->nodedb = m_Router->nodedb();
job->cryptoworker = m_Router->tp;
job->diskworker = m_Router->disk;
job->logic = m_Router->logic;
job->logic = m_Router->logic();
job->hook = nullptr;
job->rc = msg->R[0];
llarp_nodedb_async_verify(job);
@ -783,7 +783,7 @@ namespace llarp
if(router.IsZero())
return;
RouterContact rc;
if(!m_Router->nodedb->Get(router, rc))
if(!m_Router->nodedb()->Get(router, rc))
{
LookupRouterAnon(router);
}
@ -1051,7 +1051,7 @@ namespace llarp
Endpoint::OutboundContext::OutboundContext(const IntroSet& introset,
Endpoint* parent)
: path::Builder(parent->m_Router, parent->m_Router->dht, 3,
: path::Builder(parent->m_Router, parent->m_Router->dht(), 3,
DEFAULT_HOP_LENGTH)
, SendContext(introset.A, {}, this, parent)
, currentIntroSet(introset)
@ -1242,7 +1242,7 @@ namespace llarp
f.C.Zero();
transfer.Y.Randomize();
transfer.P = remoteIntro.pathID;
if(!f.EncryptAndSign(Router()->crypto.get(), m, K, m_Identity))
if(!f.EncryptAndSign(Router()->crypto(), m, K, m_Identity))
{
llarp::LogError("failed to encrypt and sign");
return false;
@ -1281,7 +1281,7 @@ namespace llarp
Endpoint::OutboundContext::BuildOneAlignedTo(const RouterID& remote)
{
llarp::LogInfo(Name(), " building path to ", remote);
auto nodedb = m_Endpoint->Router()->nodedb;
auto nodedb = m_Endpoint->Router()->nodedb();
std::vector< RouterContact > hops;
hops.resize(numHops);
for(size_t hop = 0; hop < numHops; ++hop)
@ -1736,7 +1736,7 @@ namespace llarp
Endpoint::SendContext::EncryptAndSendTo(const llarp_buffer_t& payload,
ProtocolType t)
{
auto crypto = m_Endpoint->Router()->crypto.get();
auto crypto = m_Endpoint->Router()->crypto();
SharedSecret shared;
routing::PathTransferMessage msg;
ProtocolFrame& f = msg.T;
@ -1802,19 +1802,19 @@ namespace llarp
llarp::Logic*
Endpoint::RouterLogic()
{
return m_Router->logic;
return m_Router->logic();
}
llarp::Logic*
Endpoint::EndpointLogic()
{
return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic;
return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic();
}
llarp::Crypto*
Endpoint::Crypto()
{
return m_Router->crypto.get();
return m_Router->crypto();
}
llarp_threadpool*

@ -1,6 +1,7 @@
#include <service/lookup.hpp>
#include <path/path.hpp>
#include <router/router.hpp>
#include <service/endpoint.hpp>
#include <util/time.hpp>
@ -17,8 +18,7 @@ namespace llarp
}
bool
IServiceLookup::SendRequestViaPath(llarp::path::Path *path,
llarp::Router *r)
IServiceLookup::SendRequestViaPath(path::Path *path, Router *r)
{
auto msg = BuildRequestMessage();
if(!msg)

@ -33,7 +33,7 @@ namespace llarp
MOCK_CONST_METHOD0(Crypto, llarp::Crypto*());
MOCK_CONST_METHOD0(GetRouter, llarp::Router*());
MOCK_CONST_METHOD0(GetRouter, llarp::AbstractRouter*());
MOCK_CONST_METHOD0(OurKey, const dht::Key_t&());

Loading…
Cancel
Save