Finish replacement of Router with AbstractRouter

pull/306/head
Michael 5 years ago
parent a204d7c42e
commit 048fa83c39
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C

@ -303,11 +303,7 @@ add_subdirectory(crypto)
add_subdirectory(libutp)
add_subdirectory(llarp)
set(RC_SRC
daemon/rcutil.cpp
)
set(ALL_SRC ${RC_SRC} ${EXE_SRC} ${LIB_PLATFORM_SRC} ${LIB_SRC})
set(ALL_SRC ${EXE_SRC} ${LIB_PLATFORM_SRC} ${LIB_SRC})
foreach(F ${ALL_SRC})
set_source_files_properties(${F} PROPERTIES COMPILE_FLAGS -DLOG_TAG=\\\"${F}\\\")

@ -177,6 +177,7 @@ set(LIB_SRC
path/transit_hop.cpp
pow.cpp
profiling.cpp
router/abstractrouter.cpp
router/router.cpp
router_contact.cpp
router_id.cpp

@ -130,8 +130,10 @@ namespace llarp
LoadFromFile(const char *fname);
};
using ShortHash = AlignedBuffer< SHORTHASHSIZE >;
using Signature = AlignedBuffer< SIGSIZE >;
using ShortHash = AlignedBuffer< SHORTHASHSIZE >;
struct Signature final : public AlignedBuffer< SIGSIZE >
{
};
using TunnelNonce = AlignedBuffer< TUNNONCESIZE >;
using SymmNonce = AlignedBuffer< NONCESIZE >;
using SymmKey = AlignedBuffer< 32 >;

@ -15,7 +15,9 @@
#include <dht/taglookup.hpp>
#include <messages/dht.hpp>
#include <messages/dht_immediate.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
#include <util/logic.hpp>
#include <vector>
@ -237,7 +239,7 @@ namespace llarp
}
void
Context::Init(const Key_t &us, llarp::Router *r,
Context::Init(const Key_t &us, AbstractRouter *r,
llarp_time_t exploreInterval)
{
router = r;

@ -180,7 +180,7 @@ namespace llarp
/// initialize dht context and explore every exploreInterval milliseconds
void
Init(const Key_t& us, llarp::Router* router,
Init(const Key_t& us, AbstractRouter* router,
llarp_time_t exploreInterval);
/// get localally stored introset by service address
@ -262,8 +262,8 @@ namespace llarp
struct llarp_dht_context
{
llarp::dht::Context impl;
llarp::Router* parent;
llarp_dht_context(llarp::Router* router);
llarp::AbstractRouter* parent;
llarp_dht_context(llarp::AbstractRouter* router);
};
#endif

@ -2,13 +2,13 @@
#include <dht/dht.h>
#include <router_contact.hpp>
llarp_dht_context::llarp_dht_context(llarp::Router *router)
llarp_dht_context::llarp_dht_context(llarp::AbstractRouter *router)
{
parent = router;
}
struct llarp_dht_context *
llarp_dht_context_new(llarp::Router *router)
llarp_dht_context_new(llarp::AbstractRouter *router)
{
return new llarp_dht_context(router);
}

@ -15,12 +15,12 @@ struct llarp_dht_context;
namespace llarp
{
struct Router;
struct AbstractRouter;
}
/// allocator
struct llarp_dht_context*
llarp_dht_context_new(llarp::Router* parent);
llarp_dht_context_new(llarp::AbstractRouter* parent);
/// deallocator
void

@ -2,7 +2,7 @@
#include <dht/context.hpp>
#include <dht/messages/findrouter.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{

@ -3,7 +3,8 @@
#include <dht/context.hpp>
#include <dht/messages/gotrouter.hpp>
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
#include <util/logger.hpp>
namespace llarp

@ -2,7 +2,9 @@
#include <dht/context.hpp>
#include <dht/messages/gotintro.hpp>
#include <router/router.hpp>
#include <messages/dht.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
#include <util/logger.hpp>
namespace llarp

@ -3,7 +3,8 @@
#include <dht/context.hpp>
#include <dht/messages/gotintro.hpp>
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{

@ -3,7 +3,9 @@
#include <dht/context.hpp>
#include <dht/messages/gotrouter.hpp>
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <nodedb.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{

@ -2,7 +2,8 @@
#include <dht/context.hpp>
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{

@ -1,7 +1,8 @@
#include <dht/context.hpp>
#include <dht/messages/gotrouter.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{
@ -107,7 +108,7 @@ namespace llarp
if(!dht.pendingRouterLookups.HasPendingLookupFrom(owner))
{
llarp::LogWarn("Unwarrented GRM from ", From, " txid=", txid);
llarp::LogWarn("Unwarranted GRM from ", From, " txid=", txid);
return false;
}
// no pending lookup

@ -4,7 +4,7 @@
#include <dht/messages/gotintro.hpp>
#include <messages/dht.hpp>
#include <messages/dht_immediate.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{

@ -1,5 +1,6 @@
#include <messages/exit.hpp>
#include <routing/handler.hpp>
#include <crypto/crypto.hpp>
namespace llarp
{
@ -76,7 +77,7 @@ namespace llarp
}
bool
CloseExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
CloseExitMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const
{
return h->HandleCloseExitMessage(this, r);
}

@ -4,7 +4,7 @@ namespace llarp
{
namespace exit
{
Context::Context(llarp::Router* r) : m_Router(r)
Context::Context(AbstractRouter* r) : m_Router(r)
{
}
Context::~Context()

@ -15,7 +15,7 @@ namespace llarp
{
using Config_t = std::unordered_multimap< std::string, std::string >;
Context(llarp::Router *r);
Context(AbstractRouter *r);
~Context();
void
@ -50,7 +50,7 @@ namespace llarp
CalculateExitTraffic(TrafficStats &stats);
private:
llarp::Router *m_Router;
AbstractRouter *m_Router;
std::unordered_map< std::string,
std::unique_ptr< llarp::handlers::ExitEndpoint > >
m_Exits;

@ -1,6 +1,6 @@
#include <exit/endpoint.hpp>
#include <handlers/exit.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{
@ -194,7 +194,8 @@ namespace llarp
Endpoint::GetCurrentPath() const
{
auto router = m_Parent->GetRouter();
return router->paths.GetByUpstream(router->pubkey(), m_CurrentPath);
return router->pathContext().GetByUpstream(router->pubkey(),
m_CurrentPath);
}
} // namespace exit
} // namespace llarp

@ -6,6 +6,8 @@
#include <path/path.hpp>
#include <util/time.hpp>
#include <queue>
namespace llarp
{
namespace handlers

@ -1,4 +1,6 @@
#include <messages/exit.hpp>
#include <crypto/crypto.hpp>
#include <routing/handler.hpp>
namespace llarp
@ -81,7 +83,7 @@ namespace llarp
}
bool
GrantExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
GrantExitMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const
{
return h->HandleGrantExitMessage(this, r);
}

@ -1,5 +1,6 @@
#include <messages/exit.hpp>
#include <crypto/crypto.hpp>
#include <routing/handler.hpp>
namespace llarp
@ -11,7 +12,7 @@ namespace llarp
{
std::array< byte_t, 1024 > tmp;
llarp_buffer_t buf(tmp);
I = llarp::seckey_topublic(sk);
I = seckey_topublic(sk);
Z.Zero();
if(!BEncode(&buf))
{
@ -92,7 +93,8 @@ namespace llarp
}
bool
ObtainExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
ObtainExitMessage::HandleMessage(IMessageHandler* h,
AbstractRouter* r) const
{
return h->HandleObtainExitMessage(this, r);
}

@ -1,4 +1,6 @@
#include <messages/exit.hpp>
#include <crypto/crypto.hpp>
#include <routing/handler.hpp>
namespace llarp
@ -91,7 +93,8 @@ namespace llarp
}
bool
RejectExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
RejectExitMessage::HandleMessage(IMessageHandler* h,
AbstractRouter* r) const
{
return h->HandleRejectExitMessage(this, r);
}

@ -1,7 +1,8 @@
#include <exit/session.hpp>
#include <nodedb.hpp>
#include <path/path.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{
@ -9,8 +10,8 @@ namespace llarp
{
BaseSession::BaseSession(
const llarp::RouterID& router,
std::function< bool(const llarp_buffer_t&) > writepkt, llarp::Router* r,
size_t numpaths, size_t hoplen)
std::function< bool(const llarp_buffer_t&) > writepkt,
AbstractRouter* r, size_t numpaths, size_t hoplen)
: llarp::path::Builder(r, r->dht(), numpaths, hoplen)
, m_ExitRouter(router)
, m_WritePacket(writepkt)
@ -232,13 +233,14 @@ namespace llarp
SNodeSession::SNodeSession(
const llarp::RouterID& snodeRouter,
std::function< bool(const llarp_buffer_t&) > writepkt, llarp::Router* r,
size_t numpaths, size_t hoplen, bool useRouterSNodeKey)
std::function< bool(const llarp_buffer_t&) > writepkt,
AbstractRouter* r, size_t numpaths, size_t hoplen,
bool useRouterSNodeKey)
: BaseSession(snodeRouter, writepkt, r, numpaths, hoplen)
{
if(useRouterSNodeKey)
{
m_ExitIdentity = r->identity;
m_ExitIdentity = r->identity();
}
}
} // namespace exit

@ -21,7 +21,7 @@ namespace llarp
BaseSession(const llarp::RouterID& exitRouter,
std::function< bool(const llarp_buffer_t&) > writepkt,
llarp::Router* r, size_t numpaths, size_t hoplen);
AbstractRouter* r, size_t numpaths, size_t hoplen);
virtual ~BaseSession();
@ -113,7 +113,7 @@ namespace llarp
{
ExitSession(const llarp::RouterID& snodeRouter,
std::function< bool(const llarp_buffer_t&) > writepkt,
llarp::Router* r, size_t numpaths, size_t hoplen)
AbstractRouter* r, size_t numpaths, size_t hoplen)
: BaseSession(snodeRouter, writepkt, r, numpaths, hoplen){};
~ExitSession(){};
@ -132,7 +132,7 @@ namespace llarp
{
SNodeSession(const llarp::RouterID& snodeRouter,
std::function< bool(const llarp_buffer_t&) > writepkt,
llarp::Router* r, size_t numpaths, size_t hoplen,
AbstractRouter* r, size_t numpaths, size_t hoplen,
bool useRouterSNodeKey = false);
~SNodeSession(){};

@ -64,7 +64,7 @@ namespace llarp
bool
TransferTrafficMessage::HandleMessage(IMessageHandler* h,
llarp::Router* r) const
AbstractRouter* r) const
{
return h->HandleTransferTrafficMessage(this, r);
}

@ -1,4 +1,6 @@
#include <messages/exit.hpp>
#include <crypto/crypto.hpp>
#include <routing/handler.hpp>
namespace llarp
@ -82,7 +84,8 @@ namespace llarp
}
bool
UpdateExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
UpdateExitMessage::HandleMessage(IMessageHandler* h,
AbstractRouter* r) const
{
return h->HandleUpdateExitMessage(this, r);
}
@ -119,7 +122,7 @@ namespace llarp
bool
UpdateExitVerifyMessage::HandleMessage(IMessageHandler* h,
llarp::Router* r) const
AbstractRouter* r) const
{
return h->HandleUpdateExitVerifyMessage(this, r);
}

@ -2,7 +2,7 @@
#include <dns/dns.hpp>
#include <net/net.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <util/str.hpp>
#include <cassert>
@ -23,13 +23,13 @@ namespace llarp
static_cast< ExitEndpoint * >(tun->user)->Flush();
}
ExitEndpoint::ExitEndpoint(const std::string &name, Router *r)
ExitEndpoint::ExitEndpoint(const std::string &name, AbstractRouter *r)
: m_Router(r)
, m_Resolver(r->netloop, this)
, m_Resolver(r->netloop(), this)
, m_Name(name)
, m_Tun{{0}, 0, {0}, 0, 0, 0, 0, 0, 0, 0}
, m_LocalResolverAddr("127.0.0.1", 53)
, m_InetToNetwork(name + "_exit_rx", r->netloop, r->netloop)
, m_InetToNetwork(name + "_exit_rx", r->netloop(), r->netloop())
{
m_Tun.user = this;
@ -237,7 +237,7 @@ namespace llarp
{
if(m_ShouldInitTun)
{
if(!llarp_ev_add_tun(GetRouter()->netloop, &m_Tun))
if(!llarp_ev_add_tun(GetRouter()->netloop(), &m_Tun))
{
llarp::LogWarn("Could not create tunnel for exit endpoint");
return false;
@ -251,7 +251,7 @@ namespace llarp
return true;
}
Router *
AbstractRouter *
ExitEndpoint::GetRouter()
{
return m_Router;
@ -542,7 +542,8 @@ namespace llarp
if(wantInternet && !m_PermitExit)
return false;
huint32_t ip = GetIPForIdent(pk);
if(GetRouter()->paths.TransitHopPreviousIsRouter(path, pk.as_array()))
if(GetRouter()->pathContext().TransitHopPreviousIsRouter(path,
pk.as_array()))
{
// we think this path belongs to a service node
// mark it as such so we don't make an outbound session to them

@ -8,12 +8,12 @@
namespace llarp
{
struct Router;
struct AbstractRouter;
namespace handlers
{
struct ExitEndpoint : public dns::IQueryHandler, public util::IStateful
{
ExitEndpoint(const std::string& name, Router* r);
ExitEndpoint(const std::string& name, AbstractRouter* r);
~ExitEndpoint();
void
@ -52,7 +52,7 @@ namespace llarp
void
OnInetPacket(const llarp_buffer_t& buf);
Router*
AbstractRouter*
GetRouter();
llarp_time_t
@ -125,7 +125,7 @@ namespace llarp
void
KickIdentOffExit(const PubKey& pk);
Router* m_Router;
AbstractRouter* m_Router;
dns::Proxy m_Resolver;
bool m_ShouldInitTun;
std::string m_Name;

@ -9,7 +9,7 @@ namespace llarp
{
struct NullEndpoint final : public llarp::service::Endpoint
{
NullEndpoint(const std::string &name, llarp::Router *r,
NullEndpoint(const std::string &name, AbstractRouter *r,
llarp::service::Context *parent)
: llarp::service::Endpoint(name, r, parent){};

@ -10,7 +10,8 @@
#include <dns/dns.hpp>
#include <ev/ev.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <service/context.hpp>
namespace llarp
{
@ -29,12 +30,14 @@ namespace llarp
self->Flush();
}
TunEndpoint::TunEndpoint(const std::string &nickname, llarp::Router *r,
TunEndpoint::TunEndpoint(const std::string &nickname, AbstractRouter *r,
service::Context *parent)
: service::Endpoint(nickname, r, parent)
, m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop, r->netloop)
, m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop, r->netloop)
, m_Resolver(r->netloop, this)
, m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop(),
r->netloop())
, m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop(),
r->netloop())
, m_Resolver(r->netloop(), this)
{
#ifdef ANDROID
tunif.get_fd_promise = &get_tun_fd_promise;

@ -20,7 +20,7 @@ namespace llarp
struct TunEndpoint : public service::Endpoint, public dns::IQueryHandler
{
TunEndpoint(const std::string& nickname, llarp::Router* r,
TunEndpoint(const std::string& nickname, AbstractRouter* r,
llarp::service::Context* parent);
~TunEndpoint();

@ -1,16 +1,17 @@
#include <link/iwp.hpp>
#include <link/iwp_internal.hpp>
#include <router/router.hpp>
namespace llarp
{
namespace iwp
{
std::unique_ptr< ILinkLayer >
NewServerFromRouter(llarp::Router*)
NewServerFromRouter(AbstractRouter*)
{
// TODO: implement me
return nullptr;
}
std::unique_ptr< ILinkLayer >
NewServer(llarp::Crypto*, const SecretKey&, llarp::GetRCFunc,
llarp::LinkMessageHandler, llarp::SessionEstablishedHandler,

@ -1,11 +1,14 @@
#ifndef LLARP_LINK_IWP_HPP
#define LLARP_LINK_IWP_HPP
#include <memory>
#include <link/server.hpp>
#include <memory>
namespace llarp
{
struct AbstractRouter;
namespace iwp
{
std::unique_ptr< ILinkLayer >
@ -17,7 +20,7 @@ namespace llarp
llarp::SessionClosedHandler closed);
std::unique_ptr< ILinkLayer >
NewServerFromRouter(llarp::Router* r);
NewServerFromRouter(AbstractRouter* r);
} // namespace iwp
} // namespace llarp

@ -1,9 +1,10 @@
#include <link/utp.hpp>
#include <crypto/crypto.hpp>
#include <link/server.hpp>
#include <messages/discard.hpp>
#include <messages/link_intro.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <util/buffer.hpp>
#include <util/endian.hpp>
@ -51,17 +52,17 @@ namespace llarp
{
parent = p;
EnterState(eLinkEstablished);
llarp::LogDebug("link established with ", remoteAddr);
LogDebug("link established with ", remoteAddr);
}
llarp::Crypto*
Session::Crypto()
Crypto*
Session::OurCrypto()
{
return parent->Crypto();
return parent->OurCrypto();
}
llarp::Crypto*
LinkLayer::Crypto()
Crypto*
LinkLayer::OurCrypto()
{
return _crypto;
}
@ -140,19 +141,19 @@ namespace llarp
std::copy(K.begin(), K.end(), tmp.begin());
std::copy(n.begin(), n.end(), tmp.begin() + K.size());
// t_h = HS(K + L.n)
if(!Crypto()->shorthash(t_h, llarp_buffer_t(tmp)))
if(!OurCrypto()->shorthash(t_h, llarp_buffer_t(tmp)))
{
llarp::LogError("failed to mix key to ", remoteAddr);
LogError("failed to mix key to ", remoteAddr);
return false;
}
// K = TKE(a.p, B_a.e, sk, t_h)
if(!dh(K, other, secret, t_h))
{
llarp::LogError("key exchange with ", other, " failed");
LogError("key exchange with ", other, " failed");
return false;
}
llarp::LogDebug("keys mixed with session to ", remoteAddr);
LogDebug("keys mixed with session to ", remoteAddr);
return true;
}
@ -165,7 +166,7 @@ namespace llarp
buf.cur += K.size();
std::copy(A.begin(), A.end(), buf.cur);
buf.cur = buf.base;
return Crypto()->shorthash(K, buf);
return OurCrypto()->shorthash(K, buf);
}
void
@ -188,8 +189,8 @@ namespace llarp
if(s >= left)
{
// yes it fills it
llarp::LogDebug("process leftovers, offset=", recvBufOffset,
" sz=", s, " left=", left);
LogDebug("process leftovers, offset=", recvBufOffset, " sz=", s,
" left=", left);
std::copy(buf, buf + left, recvBuf.begin() + recvBufOffset);
s -= left;
recvBufOffset = 0;
@ -202,7 +203,7 @@ namespace llarp
while(s >= FragmentBufferSize)
{
recvBufOffset = 0;
llarp::LogDebug("process full sz=", s);
LogDebug("process full sz=", s);
if(!VerifyThenDecrypt(buf))
return false;
buf += FragmentBufferSize;
@ -211,7 +212,7 @@ namespace llarp
if(s)
{
// hold onto leftovers
llarp::LogDebug("leftovers sz=", s);
LogDebug("leftovers sz=", s);
std::copy(buf, buf + s, recvBuf.begin() + recvBufOffset);
recvBufOffset += s;
}
@ -228,7 +229,7 @@ namespace llarp
auto dlt = now - lastActive;
if(dlt >= sessionTimeout)
{
llarp::LogDebug("session timeout reached for ", remoteAddr);
LogDebug("session timeout reached for ", remoteAddr);
return true;
}
return false;
@ -253,8 +254,7 @@ namespace llarp
static_cast< LinkLayer* >(utp_context_get_userdata(arg->context));
if(l == nullptr)
return 0;
llarp::LogDebug("utp_sendto ", Addr(*arg->address), " ", arg->len,
" bytes");
LogDebug("utp_sendto ", Addr(*arg->address), " ", arg->len, " bytes");
// For whatever reason, the UTP_UDP_DONTFRAG flag is set
// on the socket itself....which isn't correct and causes
// winsock (at minimum) to reeee
@ -316,9 +316,9 @@ namespace llarp
int err = WSAGetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL,
buf, 1024, nullptr);
llarp::LogError("sendto failed: ", buf);
LogError("sendto failed: ", buf);
#else
llarp::LogError("sendto failed: ", strerror(errno));
LogError("sendto failed: ", strerror(errno));
#endif
}
return 0;
@ -335,8 +335,8 @@ namespace llarp
if(session && link)
{
link->HandleTimeout(session);
llarp::LogError(utp_error_code_names[arg->error_code], " via ",
session->remoteAddr);
LogError(utp_error_code_names[arg->error_code], " via ",
session->remoteAddr);
if(arg->error_code != UTP_ETIMEDOUT)
session->Close();
link->RemovePending(session);
@ -347,18 +347,16 @@ namespace llarp
uint64
LinkLayer::OnLog(utp_callback_arguments* arg)
{
llarp::LogDebug(arg->buf);
LogDebug(arg->buf);
return 0;
}
LinkLayer::LinkLayer(llarp::Crypto* crypto,
const SecretKey& routerEncSecret,
llarp::GetRCFunc getrc, llarp::LinkMessageHandler h,
llarp::SignBufferFunc sign,
llarp::SessionEstablishedHandler established,
llarp::SessionRenegotiateHandler reneg,
llarp::TimeoutHandler timeout,
llarp::SessionClosedHandler closed)
LinkLayer::LinkLayer(Crypto* crypto, const SecretKey& routerEncSecret,
GetRCFunc getrc, LinkMessageHandler h,
SignBufferFunc sign,
SessionEstablishedHandler established,
SessionRenegotiateHandler reneg,
TimeoutHandler timeout, SessionClosedHandler closed)
: ILinkLayer(routerEncSecret, getrc, h, sign, established, reneg,
timeout, closed)
{
@ -428,7 +426,7 @@ namespace llarp
if(errno == EAGAIN || errno == EWOULDBLOCK)
errno = 0;
else
llarp::LogError("failed to read icmp for utp ", strerror(errno));
LogError("failed to read icmp for utp ", strerror(errno));
return;
}
@ -511,7 +509,7 @@ namespace llarp
bool
LinkLayer::KeyGen(SecretKey& k)
{
Crypto()->encryption_keygen(k);
OurCrypto()->encryption_keygen(k);
return true;
}
@ -535,12 +533,10 @@ namespace llarp
}
std::unique_ptr< ILinkLayer >
NewServer(llarp::Crypto* crypto, const SecretKey& routerEncSecret,
llarp::GetRCFunc getrc, llarp::LinkMessageHandler h,
llarp::SessionEstablishedHandler est,
llarp::SessionRenegotiateHandler reneg,
llarp::SignBufferFunc sign, llarp::TimeoutHandler timeout,
llarp::SessionClosedHandler closed)
NewServer(Crypto* crypto, const SecretKey& routerEncSecret, GetRCFunc getrc,
LinkMessageHandler h, SessionEstablishedHandler est,
SessionRenegotiateHandler reneg, SignBufferFunc sign,
TimeoutHandler timeout, SessionClosedHandler closed)
{
return std::unique_ptr< ILinkLayer >(
new LinkLayer(crypto, routerEncSecret, getrc, h, sign, est, reneg,
@ -548,20 +544,17 @@ namespace llarp
}
std::unique_ptr< ILinkLayer >
NewServerFromRouter(llarp::Router* r)
NewServerFromRouter(AbstractRouter* r)
{
using namespace std::placeholders;
return NewServer(
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,
std::placeholders::_1),
std::bind(&llarp::Router::CheckRenegotiateValid, r,
std::placeholders::_1, std::placeholders::_2),
std::bind(&llarp::Router::Sign, r, std::placeholders::_1,
std::placeholders::_2),
std::bind(&llarp::Router::OnConnectTimeout, r, std::placeholders::_1),
std::bind(&llarp::Router::SessionClosed, r, std::placeholders::_1));
r->crypto(), r->encryption(), std::bind(&AbstractRouter::rc, r),
std::bind(&AbstractRouter::HandleRecvLinkMessageBuffer, r, _1, _2),
std::bind(&AbstractRouter::OnSessionEstablished, r, _1),
std::bind(&AbstractRouter::CheckRenegotiateValid, r, _1, _2),
std::bind(&AbstractRouter::Sign, r, _1, _2),
std::bind(&AbstractRouter::OnConnectTimeout, r, _1),
std::bind(&AbstractRouter::SessionClosed, r, _1));
}
/// base constructor
@ -595,7 +588,7 @@ namespace llarp
recvBufOffset = 0;
TimedOut = std::bind(&Session::IsTimedOut, this, std::placeholders::_1);
GetPubKey = std::bind(&Session::RemotePubKey, this);
GetRemoteRC = [&]() -> llarp::RouterContact { return this->remoteRC; };
GetRemoteRC = [&]() -> RouterContact { return this->remoteRC; };
GetLinkLayer = std::bind(&Session::GetParent, this);
lastActive = parent->Now();
@ -622,9 +615,9 @@ namespace llarp
remoteTransportPubKey = addr.pubkey;
remoteRC = rc;
RouterID rid = remoteRC.pubkey;
Crypto()->shorthash(txKey, llarp_buffer_t(rid));
OurCrypto()->shorthash(txKey, llarp_buffer_t(rid));
rid = p->GetOurRC().pubkey;
Crypto()->shorthash(rxKey, llarp_buffer_t(rid));
OurCrypto()->shorthash(rxKey, llarp_buffer_t(rid));
sock = s;
assert(utp_set_userdata(sock, this) == this);
@ -638,7 +631,7 @@ namespace llarp
Session::Session(LinkLayer* p, utp_socket* s, const Addr& addr) : Session(p)
{
RouterID rid = p->GetOurRC().pubkey;
Crypto()->shorthash(rxKey, llarp_buffer_t(rid));
OurCrypto()->shorthash(rxKey, llarp_buffer_t(rid));
remoteRC.Clear();
sock = s;
assert(s == sock);
@ -665,10 +658,10 @@ namespace llarp
if(!gotLIM)
{
remoteRC = msg->rc;
Crypto()->shorthash(txKey, llarp_buffer_t(remoteRC.pubkey));
OurCrypto()->shorthash(txKey, llarp_buffer_t(remoteRC.pubkey));
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, Crypto(), _1,
_2, _3, _4),
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, OurCrypto(),
_1, _2, _3, _4),
rxKey, msg->N, remoteRC.enckey,
parent->TransportSecretKey()))
return false;
@ -677,9 +670,9 @@ namespace llarp
llarp_buffer_t buf(tmp);
LinkIntroMessage replymsg;
replymsg.rc = parent->GetOurRC();
if(!replymsg.rc.Verify(Crypto(), parent->Now()))
if(!replymsg.rc.Verify(OurCrypto(), parent->Now()))
{
llarp::LogError("our RC is invalid? closing session to", remoteAddr);
LogError("our RC is invalid? closing session to", remoteAddr);
Close();
return false;
}
@ -687,16 +680,15 @@ namespace llarp
replymsg.P = DefaultLinkSessionLifetime;
if(!replymsg.Sign(parent->Sign))
{
llarp::LogError("failed to sign LIM for inbound handshake from ",
remoteAddr);
LogError("failed to sign LIM for inbound handshake from ",
remoteAddr);
Close();
return false;
}
// encode
if(!replymsg.BEncode(&buf))
{
llarp::LogError("failed to encode LIM for handshake from ",
remoteAddr);
LogError("failed to encode LIM for handshake from ", remoteAddr);
Close();
return false;
}
@ -706,17 +698,17 @@ namespace llarp
// send
if(!SendMessageBuffer(buf))
{
llarp::LogError("failed to repl to handshake from ", remoteAddr);
LogError("failed to repl to handshake from ", remoteAddr);
Close();
return false;
}
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, Crypto(), _1,
_2, _3, _4),
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(),
_1, _2, _3, _4),
txKey, replymsg.N, remoteRC.enckey,
parent->RouterEncryptionSecret()))
return false;
llarp::LogDebug("Sent reply LIM");
LogDebug("Sent reply LIM");
gotLIM = true;
EnterState(eSessionReady);
/// future LIM are used for session renegotiation
@ -748,10 +740,10 @@ namespace llarp
uint32_t s = std::min(FragmentBodyPayloadSize, sz);
if(!EncryptThenHash(ptr, msgid, s, sz - s))
{
llarp::LogError("EncryptThenHash failed?!");
LogError("EncryptThenHash failed?!");
return false;
}
llarp::LogDebug("encrypted ", s, " bytes");
LogDebug("encrypted ", s, " bytes");
ptr += s;
sz -= s;
}
@ -768,9 +760,10 @@ namespace llarp
remoteRC = msg->rc;
gotLIM = true;
if(!DoKeyExchange(
std::bind(&Crypto::transport_dh_server, Crypto(), _1, _2, _3, _4),
rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret()))
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, OurCrypto(), _1,
_2, _3, _4),
rxKey, msg->N, remoteRC.enckey,
parent->RouterEncryptionSecret()))
{
Close();
return false;
@ -790,9 +783,9 @@ namespace llarp
// build our RC
LinkIntroMessage msg;
msg.rc = parent->GetOurRC();
if(!msg.rc.Verify(Crypto(), parent->Now()))
if(!msg.rc.Verify(OurCrypto(), parent->Now()))
{
llarp::LogError("our RC is invalid? closing session to", remoteAddr);
LogError("our RC is invalid? closing session to", remoteAddr);
Close();
return;
}
@ -800,15 +793,14 @@ namespace llarp
msg.P = DefaultLinkSessionLifetime;
if(!msg.Sign(parent->Sign))
{
llarp::LogError("failed to sign LIM for outbound handshake to ",
remoteAddr);
LogError("failed to sign LIM for outbound handshake to ", remoteAddr);
Close();
return;
}
// encode
if(!msg.BEncode(&buf))
{
llarp::LogError("failed to encode LIM for handshake to ", remoteAddr);
LogError("failed to encode LIM for handshake to ", remoteAddr);
Close();
return;
}
@ -818,18 +810,17 @@ namespace llarp
// send
if(!SendMessageBuffer(buf))
{
llarp::LogError("failed to send handshake to ", remoteAddr);
LogError("failed to send handshake to ", remoteAddr);
Close();
return;
}
if(!DoKeyExchange(
std::bind(&Crypto::transport_dh_client, Crypto(), _1, _2, _3, _4),
txKey, msg.N, remoteTransportPubKey,
parent->RouterEncryptionSecret()))
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_client, OurCrypto(), _1,
_2, _3, _4),
txKey, msg.N, remoteTransportPubKey,
parent->RouterEncryptionSecret()))
{
llarp::LogError("failed to mix keys for outbound session to ",
remoteAddr);
LogError("failed to mix keys for outbound session to ", remoteAddr);
Close();
return;
}
@ -863,7 +854,7 @@ namespace llarp
}
if(!self->Recv(arg->buf, arg->len))
{
llarp::LogDebug("recv fail for ", self->remoteAddr);
LogDebug("recv fail for ", self->remoteAddr);
self->Close();
return 0;
}
@ -871,7 +862,7 @@ namespace llarp
}
else
{
llarp::LogWarn("utp_socket got data with no underlying session");
LogWarn("utp_socket got data with no underlying session");
utp_close(arg->socket);
}
return 0;
@ -899,7 +890,7 @@ namespace llarp
}
else if(arg->state == UTP_STATE_EOF)
{
llarp::LogDebug("got eof from ", session->remoteAddr);
LogDebug("got eof from ", session->remoteAddr);
session->Close();
}
}
@ -912,7 +903,7 @@ namespace llarp
LinkLayer* self =
static_cast< LinkLayer* >(utp_context_get_userdata(arg->context));
Addr remote(*arg->address);
llarp::LogDebug("utp accepted from ", remote);
LogDebug("utp accepted from ", remote);
Session* session = new Session(self, arg->socket, remote);
if(!self->PutSession(session))
{
@ -961,14 +952,14 @@ namespace llarp
TunnelNonce nonce(noncePtr);
// encrypt
if(!Crypto()->xchacha20(payload, txKey, nonce))
if(!OurCrypto()->xchacha20(payload, txKey, nonce))
return false;
payload.base = noncePtr;
payload.cur = payload.base;
payload.sz = FragmentBufferSize - FragmentHashSize;
// key'd hash
if(!Crypto()->hmac(buf.data(), payload, txKey))
if(!OurCrypto()->hmac(buf.data(), payload, txKey))
return false;
return MutateKey(txKey, A);
}
@ -999,7 +990,7 @@ namespace llarp
remoteRC = msg->rc;
// recalculate rx key
return DoKeyExchange(
std::bind(&Crypto::transport_dh_server, Crypto(), _1, _2, _3, _4),
std::bind(&Crypto::transport_dh_server, OurCrypto(), _1, _2, _3, _4),
rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret());
}
@ -1025,28 +1016,28 @@ namespace llarp
return false;
// regen our tx Key
return DoKeyExchange(
std::bind(&Crypto::transport_dh_client, Crypto(), _1, _2, _3, _4),
std::bind(&Crypto::transport_dh_client, OurCrypto(), _1, _2, _3, _4),
txKey, lim.N, remoteRC.enckey, parent->RouterEncryptionSecret());
}
bool
Session::VerifyThenDecrypt(const byte_t* ptr)
{
llarp::LogDebug("verify then decrypt ", remoteAddr);
LogDebug("verify then decrypt ", remoteAddr);
ShortHash digest;
llarp_buffer_t hbuf(ptr + FragmentHashSize,
FragmentBufferSize - FragmentHashSize);
if(!Crypto()->hmac(digest.data(), hbuf, rxKey))
if(!OurCrypto()->hmac(digest.data(), hbuf, rxKey))
{
llarp::LogError("keyed hash failed");
LogError("keyed hash failed");
return false;
}
ShortHash expected(ptr);
if(expected != digest)
{
llarp::LogError("Message Integrity Failed: got ", digest, " from ",
remoteAddr, " instead of ", expected);
LogError("Message Integrity Failed: got ", digest, " from ", remoteAddr,
" instead of ", expected);
Close();
return false;
}
@ -1057,9 +1048,9 @@ namespace llarp
llarp_buffer_t out(rxFragBody);
// decrypt
if(!Crypto()->xchacha20_alt(out, in, rxKey, ptr + FragmentHashSize))
if(!OurCrypto()->xchacha20_alt(out, in, rxKey, ptr + FragmentHashSize))
{
llarp::LogError("failed to decrypt message from ", remoteAddr);
LogError("failed to decrypt message from ", remoteAddr);
return false;
}
// get inner nonce
@ -1070,7 +1061,7 @@ namespace llarp
uint32_t msgid;
if(!llarp_buffer_read_uint32(&out, &msgid))
{
llarp::LogError("failed to read msgid");
LogError("failed to read msgid");
return false;
}
// read length and remaining
@ -1078,13 +1069,13 @@ namespace llarp
if(!(llarp_buffer_read_uint16(&out, &length)
&& llarp_buffer_read_uint16(&out, &remaining)))
{
llarp::LogError("failed to read the rest of the header");
LogError("failed to read the rest of the header");
return false;
}
if(length > (out.sz - (out.cur - out.base)))
{
// too big length
llarp::LogError("fragment body too big");
LogError("fragment body too big");
return false;
}
if(msgid < m_NextRXMsgID)
@ -1103,13 +1094,13 @@ namespace llarp
// append data
if(!itr->second.AppendData(out.cur, length))
{
llarp::LogError("inbound buffer is full");
LogError("inbound buffer is full");
return false; // not enough room
}
// mutate key
if(!MutateKey(rxKey, A))
{
llarp::LogError("failed to mutate rx key");
LogError("failed to mutate rx key");
return false;
}
@ -1123,7 +1114,7 @@ namespace llarp
// rewind
buf.underlying.cur = buf.underlying.base;
// process buffer
llarp::LogDebug("got message ", msgid, " from ", remoteAddr);
LogDebug("got message ", msgid, " from ", remoteAddr);
return parent->HandleMessage(this, buf.underlying);
}
return true;
@ -1142,7 +1133,7 @@ namespace llarp
utp_shutdown(sock, SHUT_RDWR);
utp_close(sock);
}
llarp::LogDebug("utp_close ", remoteAddr);
LogDebug("utp_close ", remoteAddr);
utp_set_userdata(sock, nullptr);
}
}

@ -6,7 +6,7 @@
namespace llarp
{
struct Router;
struct AbstractRouter;
namespace utp
{
@ -19,7 +19,7 @@ namespace llarp
llarp::SessionClosedHandler closed);
std::unique_ptr< ILinkLayer >
NewServerFromRouter(llarp::Router* r);
NewServerFromRouter(AbstractRouter* r);
} // namespace utp
} // namespace llarp

@ -36,8 +36,7 @@ namespace llarp
constexpr size_t FragmentBufferSize =
FragmentOverheadSize + FragmentBodySize;
static_assert(FragmentBufferSize == 608,
"Fragement Buffer Size is not 608");
static_assert(FragmentBufferSize == 608, "Fragment Buffer Size is not 608");
/// buffer for a single utp fragment
using FragmentBuffer = llarp::AlignedBuffer< FragmentBufferSize >;
@ -161,7 +160,7 @@ namespace llarp
// Router();
llarp::Crypto*
Crypto();
OurCrypto();
/// session state, call EnterState(State) to set
State state;
@ -327,7 +326,7 @@ namespace llarp
#endif
llarp::Crypto*
Crypto();
OurCrypto();
/// pump sessions
void
@ -337,7 +336,7 @@ namespace llarp
void
Stop();
/// rengenerate transport keypair
/// regenerate transport keypair
bool
KeyGen(SecretKey& k);

@ -24,7 +24,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
void
Clear() override

@ -1,6 +1,6 @@
#include <messages/dht_immediate.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
namespace llarp
{
@ -65,7 +65,7 @@ namespace llarp
}
bool
DHTImmediateMessage::HandleMessage(llarp::Router *router) const
DHTImmediateMessage::HandleMessage(AbstractRouter *router) const
{
DHTImmediateMessage reply;
reply.session = session;

@ -16,7 +16,7 @@ namespace llarp
~DHTImmediateMessage();
std::vector< std::unique_ptr< llarp::dht::IMessage > > msgs;
std::vector< std::unique_ptr< dht::IMessage > > msgs;
bool
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
@ -25,7 +25,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(llarp::Router* router) const override;
HandleMessage(AbstractRouter* router) const override;
void
Clear() override;

@ -39,7 +39,7 @@ namespace llarp
}
bool
HandleMessage(__attribute__((unused)) llarp::Router* router) const override
HandleMessage(__attribute__((unused)) AbstractRouter* router) const override
{
return true;
}
@ -67,7 +67,7 @@ namespace llarp
}
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override
{
return h->HandleDataDiscardMessage(this, r);
}

@ -56,7 +56,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
};
struct GrantExitMessage final : public IMessage
@ -89,7 +89,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
void
Clear() override
@ -143,7 +143,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
};
struct UpdateExitVerifyMessage final : public IMessage
@ -185,7 +185,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
};
struct UpdateExitMessage final : public IMessage
@ -220,7 +220,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
void
Clear() override
@ -257,7 +257,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
bool
Sign(llarp::Crypto* c, const llarp::SecretKey& sk);

@ -1,7 +1,8 @@
#include <messages/link_intro.hpp>
#include <crypto/crypto.hpp>
#include <router_contact.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <util/bencode.h>
#include <util/logger.hpp>
@ -115,7 +116,7 @@ namespace llarp
}
bool
LinkIntroMessage::HandleMessage(llarp::Router* router) const
LinkIntroMessage::HandleMessage(AbstractRouter* router) const
{
if(!Verify(router->crypto()))
return false;

@ -34,7 +34,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(llarp::Router* router) const override;
HandleMessage(AbstractRouter* router) const override;
bool
Sign(std::function< bool(Signature&, const llarp_buffer_t&) > signer);

@ -1,12 +1,36 @@
#include <messages/link_message_parser.hpp>
#include <messages/dht_immediate.hpp>
#include <messages/discard.hpp>
#include <messages/link_intro.hpp>
#include <messages/link_message.hpp>
#include <messages/relay_commit.hpp>
#include <messages/relay.hpp>
#include <router_contact.hpp>
#include <util/buffer.hpp>
#include <util/logger.hpp>
namespace llarp
{
InboundMessageParser::InboundMessageParser(Router* _router) : router(_router)
struct InboundMessageParser::msg_holder_t
{
LinkIntroMessage i;
RelayDownstreamMessage d;
RelayUpstreamMessage u;
DHTImmediateMessage m;
LR_CommitMessage c;
DiscardMessage x;
};
InboundMessageParser::InboundMessageParser(AbstractRouter* _router)
: router(_router)
, from(nullptr)
, msg(nullptr)
, holder(std::make_unique< msg_holder_t >())
{
}
InboundMessageParser::~InboundMessageParser()
{
}
@ -46,22 +70,22 @@ namespace llarp
switch(*strbuf.cur)
{
case 'i':
handler->msg = &handler->holder.i;
handler->msg = &handler->holder->i;
break;
case 'd':
handler->msg = &handler->holder.d;
handler->msg = &handler->holder->d;
break;
case 'u':
handler->msg = &handler->holder.u;
handler->msg = &handler->holder->u;
break;
case 'm':
handler->msg = &handler->holder.m;
handler->msg = &handler->holder->m;
break;
case 'c':
handler->msg = &handler->holder.c;
handler->msg = &handler->holder->c;
break;
case 'x':
handler->msg = &handler->holder.x;
handler->msg = &handler->holder->x;
break;
default:
return false;

@ -5,15 +5,12 @@
#include <router_id.hpp>
#include <util/bencode.hpp>
#include <queue>
#include <vector>
namespace llarp
{
struct ILinkSession;
struct Router;
using SendQueue = std::queue< ILinkMessage* >;
struct AbstractRouter;
/// parsed link layer message
struct ILinkMessage : public IBEncodeMessage
@ -29,7 +26,7 @@ namespace llarp
}
virtual bool
HandleMessage(Router* router) const = 0;
HandleMessage(AbstractRouter* router) const = 0;
virtual void
Clear() = 0;

@ -1,18 +1,21 @@
#ifndef LLARP_LINK_MESSAGE_PARSER_HPP
#define LLARP_LINK_MESSAGE_PARSER_HPP
#include <messages/discard.hpp>
#include <messages/dht_immediate.hpp>
#include <messages/link_intro.hpp>
#include <messages/link_message.hpp>
#include <messages/relay.hpp>
#include <messages/relay_commit.hpp>
#include <router_id.hpp>
#include <util/bencode.h>
#include <memory>
namespace llarp
{
struct AbstractRouter;
struct ILinkMessage;
struct ILinkSession;
struct InboundMessageParser
{
InboundMessageParser(Router* router);
InboundMessageParser(AbstractRouter* router);
~InboundMessageParser();
dict_reader reader;
static bool
@ -37,21 +40,12 @@ namespace llarp
private:
bool firstkey;
Router* router;
ILinkSession* from = nullptr;
ILinkMessage* msg = nullptr;
struct msg_holder_t
{
LinkIntroMessage i;
RelayDownstreamMessage d;
RelayUpstreamMessage u;
DHTImmediateMessage m;
LR_CommitMessage c;
DiscardMessage x;
};
msg_holder_t holder;
AbstractRouter* router;
ILinkSession* from;
ILinkMessage* msg;
struct msg_holder_t;
std::unique_ptr< msg_holder_t > holder;
};
} // namespace llarp
#endif

@ -22,7 +22,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
void
Clear() override

@ -27,7 +27,7 @@ namespace llarp
};
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
};
} // namespace routing
} // namespace llarp

@ -31,7 +31,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(IMessageHandler*, llarp::Router* r) const override;
HandleMessage(IMessageHandler*, AbstractRouter* r) const override;
void
Clear() override

@ -1,6 +1,7 @@
#include <messages/relay.hpp>
#include <router/router.hpp>
#include <path/path.hpp>
#include <router/abstractrouter.hpp>
#include <util/bencode.hpp>
namespace llarp
@ -58,9 +59,9 @@ namespace llarp
}
bool
RelayUpstreamMessage::HandleMessage(llarp::Router *r) const
RelayUpstreamMessage::HandleMessage(AbstractRouter *r) const
{
auto path = r->paths.GetByDownstream(session->GetPubKey(), pathid);
auto path = r->pathContext().GetByDownstream(session->GetPubKey(), pathid);
if(path)
{
return path->HandleUpstream(llarp_buffer_t(X), Y, r);
@ -121,9 +122,9 @@ namespace llarp
}
bool
RelayDownstreamMessage::HandleMessage(llarp::Router *r) const
RelayDownstreamMessage::HandleMessage(AbstractRouter *r) const
{
auto path = r->paths.GetByUpstream(session->GetPubKey(), pathid);
auto path = r->pathContext().GetByUpstream(session->GetPubKey(), pathid);
if(path)
{
return path->HandleDownstream(llarp_buffer_t(X), Y, r);

@ -27,7 +27,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(llarp::Router* router) const override;
HandleMessage(AbstractRouter* router) const override;
void
Clear() override;
@ -49,7 +49,7 @@ namespace llarp
BEncode(llarp_buffer_t* buf) const override;
bool
HandleMessage(llarp::Router* router) const override;
HandleMessage(AbstractRouter* router) const override;
void
Clear() override;

@ -2,10 +2,11 @@
#include <messages/path_confirm.hpp>
#include <path/path.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <util/bencode.hpp>
#include <util/buffer.hpp>
#include <util/logger.hpp>
#include <util/logic.hpp>
namespace llarp
{
@ -60,7 +61,7 @@ namespace llarp
}
bool
LR_CommitMessage::HandleMessage(llarp::Router* router) const
LR_CommitMessage::HandleMessage(AbstractRouter* router) const
{
if(frames.size() != MAXHOPS)
{
@ -68,12 +69,12 @@ namespace llarp
"!=", MAXHOPS);
return false;
}
if(!router->paths.AllowingTransit())
if(!router->pathContext().AllowingTransit())
{
llarp::LogError("got LRCM when not permitting transit");
return false;
}
return AsyncDecrypt(&router->paths);
return AsyncDecrypt(&router->pathContext());
}
bool

@ -13,6 +13,7 @@
namespace llarp
{
// forward declare
struct AbstractRouter;
namespace path
{
struct PathContext;
@ -63,7 +64,7 @@ namespace llarp
BEncode(llarp_buffer_t *buf) const;
bool
HandleMessage(llarp::Router *router) const;
HandleMessage(AbstractRouter *router) const;
bool
AsyncDecrypt(llarp::path::PathContext *context) const;

@ -45,7 +45,7 @@ namespace llarp
DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* val) override;
bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const override;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const override;
};
} // namespace routing
} // namespace llarp

@ -2,8 +2,13 @@
#include <messages/dht.hpp>
#include <messages/discard.hpp>
#include <messages/exit.hpp>
#include <messages/path_latency.hpp>
#include <messages/relay_commit.hpp>
#include <messages/transfer_traffic.hpp>
#include <path/pathbuilder.hpp>
#include <router/router.hpp>
#include <profiling.hpp>
#include <router/abstractrouter.hpp>
#include <util/buffer.hpp>
#include <util/endian.hpp>
@ -13,7 +18,7 @@ namespace llarp
{
namespace path
{
PathContext::PathContext(llarp::Router* router)
PathContext::PathContext(AbstractRouter* router)
: m_Router(router), m_AllowTransit(false)
{
}
@ -37,25 +42,25 @@ namespace llarp
llarp_threadpool*
PathContext::Worker()
{
return m_Router->tp;
return m_Router->threadpool();
}
llarp::Crypto*
Crypto*
PathContext::Crypto()
{
return m_Router->crypto();
}
llarp::Logic*
Logic*
PathContext::Logic()
{
return m_Router->logic();
}
llarp::SecretKey&
const SecretKey&
PathContext::EncryptionSecretKey()
{
return m_Router->encryption;
return m_Router->encryption();
}
bool
@ -69,7 +74,7 @@ namespace llarp
PathContext::ForwardLRCM(const RouterID& nextHop,
const std::array< EncryptedFrame, 8 >& frames)
{
llarp::LogDebug("forwarding LRCM to ", nextHop);
LogDebug("forwarding LRCM to ", nextHop);
LR_CommitMessage msg;
msg.frames = frames;
return m_Router->SendToOrQueue(nextHop, &msg);
@ -217,7 +222,7 @@ namespace llarp
return m_Router->pubkey();
}
llarp::Router*
AbstractRouter*
PathContext::Router()
{
return m_Router;
@ -424,13 +429,12 @@ namespace llarp
}
else if(st == ePathBuilding)
{
llarp::LogInfo("path ", Name(), " is building");
LogInfo("path ", Name(), " is building");
buildStarted = now;
}
else if(st == ePathEstablished && _status == ePathBuilding)
{
llarp::LogInfo("path ", Name(), " is built, took ", now - buildStarted,
" ms");
LogInfo("path ", Name(), " is built, took ", now - buildStarted, " ms");
}
_status = st;
}
@ -489,7 +493,7 @@ namespace llarp
}
void
Path::Tick(llarp_time_t now, llarp::Router* r)
Path::Tick(llarp_time_t now, AbstractRouter* r)
{
if(Expired(now))
return;
@ -501,7 +505,7 @@ namespace llarp
auto dlt = now - buildStarted;
if(dlt >= PATH_BUILD_TIMEOUT)
{
r->routerProfiling.MarkPathFail(this);
r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now);
return;
}
@ -514,8 +518,8 @@ namespace llarp
auto dlt = now - m_LastLatencyTestTime;
if(dlt > 5000 && m_LastLatencyTestID == 0)
{
llarp::routing::PathLatencyMessage latency;
latency.T = llarp::randint();
routing::PathLatencyMessage latency;
latency.T = randint();
m_LastLatencyTestID = latency.T;
m_LastLatencyTestTime = now;
SendRoutingMessage(&latency, r);
@ -526,7 +530,7 @@ namespace llarp
&& now - m_LastRecvMessage > PATH_ALIVE_TIMEOUT)
{
// TODO: send close exit message
// r->routerProfiling.MarkPathFail(this);
// r->routerProfiling().MarkPathFail(this);
// EnterState(ePathTimeout, now);
return;
}
@ -538,19 +542,19 @@ namespace llarp
{
if(m_CheckForDead(this, dlt))
{
r->routerProfiling.MarkPathFail(this);
r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now);
}
}
else
{
r->routerProfiling.MarkPathFail(this);
r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now);
}
}
else if(dlt >= 10000 && m_LastRecvMessage == 0)
{
r->routerProfiling.MarkPathFail(this);
r->routerProfiling().MarkPathFail(this);
EnterState(ePathTimeout, now);
}
}
@ -572,7 +576,7 @@ namespace llarp
msg.pathid = TXID();
if(r->SendToOrQueue(Upstream(), &msg))
return true;
llarp::LogError("send to ", Upstream(), " failed");
LogError("send to ", Upstream(), " failed");
return false;
}
@ -613,7 +617,7 @@ namespace llarp
{
if(!r->ParseRoutingMessageBuffer(buf, this, RXID()))
{
llarp::LogWarn("Failed to parse inbound routing message");
LogWarn("Failed to parse inbound routing message");
return false;
}
m_LastRecvMessage = r->Now();
@ -622,7 +626,7 @@ namespace llarp
bool
Path::HandleUpdateExitVerifyMessage(
const llarp::routing::UpdateExitVerifyMessage* msg, llarp::Router* r)
const routing::UpdateExitVerifyMessage* msg, AbstractRouter* r)
{
(void)r;
if(m_UpdateExitTX && msg->T == m_UpdateExitTX)
@ -639,19 +643,18 @@ namespace llarp
}
bool
Path::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::AbstractRouter* r)
Path::SendRoutingMessage(const routing::IMessage* msg, AbstractRouter* r)
{
std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp;
llarp_buffer_t buf(tmp);
// should help prevent bad paths with uninitialised members
// FIXME: Why would we get uninitialised IMessages?
// should help prevent bad paths with uninitialized members
// FIXME: Why would we get uninitialized IMessages?
if(msg->version != LLARP_PROTO_VERSION)
return false;
if(!msg->BEncode(&buf))
{
llarp::LogError("Bencode failed");
llarp::DumpBuffer(buf);
LogError("Bencode failed");
DumpBuffer(buf);
return false;
}
// make nonce
@ -670,18 +673,18 @@ namespace llarp
}
bool
Path::HandlePathTransferMessage(
__attribute__((unused)) const llarp::routing::PathTransferMessage* msg,
__attribute__((unused)) llarp::Router* r)
Path::HandlePathTransferMessage(__attribute__((unused))
const routing::PathTransferMessage* msg,
__attribute__((unused)) AbstractRouter* r)
{
llarp::LogWarn("unwarranted path transfer message on tx=", TXID(),
" rx=", RXID());
LogWarn("unwarranted path transfer message on tx=", TXID(),
" rx=", RXID());
return false;
}
bool
Path::HandleDataDiscardMessage(
const llarp::routing::DataDiscardMessage* msg, llarp::Router* r)
Path::HandleDataDiscardMessage(const routing::DataDiscardMessage* msg,
AbstractRouter* r)
{
MarkActive(r->Now());
if(m_DropHandler)
@ -690,9 +693,9 @@ namespace llarp
}
bool
Path::HandlePathConfirmMessage(
__attribute__((unused)) const llarp::routing::PathConfirmMessage* msg,
llarp::Router* r)
Path::HandlePathConfirmMessage(__attribute__((unused))
const routing::PathConfirmMessage* msg,
AbstractRouter* r)
{
auto now = r->Now();
if(_status == ePathBuilding)
@ -700,33 +703,33 @@ namespace llarp
// finish initializing introduction
intro.expiresAt = buildStarted + hops[0].lifetime;
r->routerProfiling.MarkPathSuccess(this);
r->routerProfiling().MarkPathSuccess(this);
// persist session with upstream router until the path is done
r->PersistSessionUntil(Upstream(), intro.expiresAt);
MarkActive(now);
// send path latency test
llarp::routing::PathLatencyMessage latency;
latency.T = llarp::randint();
routing::PathLatencyMessage latency;
latency.T = randint();
m_LastLatencyTestID = latency.T;
m_LastLatencyTestTime = now;
return SendRoutingMessage(&latency, r);
}
llarp::LogWarn("got unwarrented path confirm message on tx=", RXID(),
" rx=", RXID());
LogWarn("got unwarranted path confirm message on tx=", RXID(),
" rx=", RXID());
return false;
}
bool
Path::HandleHiddenServiceFrame(const llarp::service::ProtocolFrame* frame)
Path::HandleHiddenServiceFrame(const service::ProtocolFrame* frame)
{
MarkActive(m_PathSet->Now());
return m_DataHandler && m_DataHandler(this, frame);
}
bool
Path::HandlePathLatencyMessage(
const llarp::routing::PathLatencyMessage* msg, llarp::Router* r)
Path::HandlePathLatencyMessage(const routing::PathLatencyMessage* msg,
AbstractRouter* r)
{
auto now = r->Now();
MarkActive(now);
@ -743,15 +746,15 @@ namespace llarp
}
else
{
llarp::LogWarn("unwarrented path latency message via ", Upstream());
LogWarn("unwarranted path latency message via ", Upstream());
return false;
}
}
bool
Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp::Router* r)
Path::HandleDHTMessage(const dht::IMessage* msg, AbstractRouter* r)
{
llarp::routing::DHTMessage reply;
routing::DHTMessage reply;
if(!msg->HandleMessage(r->dht(), reply.M))
return false;
MarkActive(r->Now());
@ -761,102 +764,101 @@ namespace llarp
}
bool
Path::HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg,
llarp::Router* r)
Path::HandleCloseExitMessage(const routing::CloseExitMessage* msg,
AbstractRouter* r)
{
/// allows exits to close from their end
if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC))
{
if(msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogInfo(Name(), " had its exit closed");
LogInfo(Name(), " had its exit closed");
_role &= ~ePathRoleExit;
return true;
}
else
llarp::LogError(Name(), " CXM from exit with bad signature");
LogError(Name(), " CXM from exit with bad signature");
}
else
llarp::LogError(Name(), " unwarrented CXM");
LogError(Name(), " unwarranted CXM");
return false;
}
bool
Path::SendExitRequest(const llarp::routing::ObtainExitMessage* msg,
llarp::Router* r)
Path::SendExitRequest(const routing::ObtainExitMessage* msg,
AbstractRouter* r)
{
llarp::LogInfo(Name(), " sending exit request to ", Endpoint());
LogInfo(Name(), " sending exit request to ", Endpoint());
m_ExitObtainTX = msg->T;
return SendRoutingMessage(msg, r);
}
bool
Path::SendExitClose(const llarp::routing::CloseExitMessage* msg,
llarp::Router* r)
Path::SendExitClose(const routing::CloseExitMessage* msg, AbstractRouter* r)
{
llarp::LogInfo(Name(), " closing exit to ", Endpoint());
LogInfo(Name(), " closing exit to ", Endpoint());
// mark as not exit anymore
_role &= ~ePathRoleExit;
return SendRoutingMessage(msg, r);
}
bool
Path::HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg,
llarp::Router* r)
Path::HandleObtainExitMessage(const routing::ObtainExitMessage* msg,
AbstractRouter* r)
{
(void)msg;
(void)r;
llarp::LogError(Name(), " got unwarrented OXM");
LogError(Name(), " got unwarranted OXM");
return false;
}
bool
Path::HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg,
llarp::Router* r)
Path::HandleUpdateExitMessage(const routing::UpdateExitMessage* msg,
AbstractRouter* r)
{
(void)msg;
(void)r;
llarp::LogError(Name(), " got unwarrented UXM");
LogError(Name(), " got unwarranted UXM");
return false;
}
bool
Path::HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg,
llarp::Router* r)
Path::HandleRejectExitMessage(const routing::RejectExitMessage* msg,
AbstractRouter* r)
{
if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{
if(!msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogError(Name(), "RXM invalid signature");
LogError(Name(), "RXM invalid signature");
return false;
}
llarp::LogInfo(Name(), " ", Endpoint(), " Rejected exit");
LogInfo(Name(), " ", Endpoint(), " Rejected exit");
MarkActive(r->Now());
return InformExitResult(msg->B);
}
llarp::LogError(Name(), " got unwarrented RXM");
LogError(Name(), " got unwarranted RXM");
return false;
}
bool
Path::HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg,
llarp::Router* r)
Path::HandleGrantExitMessage(const routing::GrantExitMessage* msg,
AbstractRouter* r)
{
if(m_ExitObtainTX && msg->T == m_ExitObtainTX)
{
if(!msg->Verify(r->crypto(), EndpointPubKey()))
{
llarp::LogError(Name(), " GXM signature failed");
LogError(Name(), " GXM signature failed");
return false;
}
// we now can send exit traffic
_role |= ePathRoleExit;
llarp::LogInfo(Name(), " ", Endpoint(), " Granted exit");
LogInfo(Name(), " ", Endpoint(), " Granted exit");
MarkActive(r->Now());
return InformExitResult(0);
}
llarp::LogError(Name(), " got unwarrented GXM");
LogError(Name(), " got unwarranted GXM");
return false;
}
@ -872,7 +874,7 @@ namespace llarp
bool
Path::HandleTransferTrafficMessage(
const llarp::routing::TransferTrafficMessage* msg, llarp::Router* r)
const routing::TransferTrafficMessage* msg, AbstractRouter* r)
{
// check if we can handle exit data
if(!SupportsAnyRoles(ePathRoleExit | ePathRoleSVC))

@ -32,10 +32,12 @@
namespace llarp
{
class Logic;
struct AbstractRouter;
struct Crypto;
struct LR_CommitMessage;
struct LR_CommitRecord;
namespace path
{
struct TransitHopInfo
@ -198,46 +200,46 @@ namespace llarp
bool
HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathConfirmMessage(const llarp::routing::PathConfirmMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathTransferMessage(const llarp::routing::PathTransferMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathLatencyMessage(const llarp::routing::PathLatencyMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleUpdateExitVerifyMessage(
const llarp::routing::UpdateExitVerifyMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleTransferTrafficMessage(
const llarp::routing::TransferTrafficMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleHiddenServiceFrame(__attribute__((
@ -253,7 +255,7 @@ namespace llarp
bool
HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
// handle data in upstream direction
bool
@ -422,7 +424,7 @@ namespace llarp
Expired(llarp_time_t now) const override;
void
Tick(llarp_time_t now, llarp::Router* r);
Tick(llarp_time_t now, AbstractRouter* r);
bool
SendRoutingMessage(const llarp::routing::IMessage* msg,
@ -430,47 +432,47 @@ namespace llarp
bool
HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleUpdateExitVerifyMessage(
const llarp::routing::UpdateExitVerifyMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleTransferTrafficMessage(
const llarp::routing::TransferTrafficMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathConfirmMessage(const llarp::routing::PathConfirmMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathLatencyMessage(const llarp::routing::PathLatencyMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandlePathTransferMessage(const llarp::routing::PathTransferMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleHiddenServiceFrame(
@ -481,7 +483,7 @@ namespace llarp
bool
HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp::Router* r) override;
AbstractRouter* r) override;
bool
HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r);
@ -530,11 +532,11 @@ namespace llarp
bool
SendExitRequest(const llarp::routing::ObtainExitMessage* msg,
llarp::Router* r);
AbstractRouter* r);
bool
SendExitClose(const llarp::routing::CloseExitMessage* msg,
llarp::Router* r);
AbstractRouter* r);
private:
/// call obtained exit hooks
@ -568,7 +570,7 @@ namespace llarp
struct PathContext
{
PathContext(llarp::Router* router);
PathContext(AbstractRouter* router);
~PathContext();
/// called from router tick function
@ -665,17 +667,17 @@ namespace llarp
llarp::Logic*
Logic();
llarp::Router*
AbstractRouter*
Router();
llarp::SecretKey&
const llarp::SecretKey&
EncryptionSecretKey();
const byte_t*
OurRouterID() const;
private:
llarp::Router* m_Router;
AbstractRouter* m_Router;
SyncTransitMap_t m_TransitPaths;
SyncTransitMap_t m_Paths;
SyncOwnedPathsMap_t m_OurPaths;

@ -6,7 +6,10 @@
namespace llarp
{
using PathID_t = AlignedBuffer< PATHIDSIZE >;
}
struct PathID_t final : public AlignedBuffer< PATHIDSIZE >
{
};
} // namespace llarp
#endif

@ -1,9 +1,12 @@
#include <path/pathbuilder.hpp>
#include <messages/relay_commit.hpp>
#include <nodedb.hpp>
#include <path/path.hpp>
#include <router/router.hpp>
#include <profiling.hpp>
#include <router/abstractrouter.hpp>
#include <util/buffer.hpp>
#include <util/logic.hpp>
#include <functional>
@ -21,7 +24,7 @@ namespace llarp
Handler result;
size_t idx = 0;
llarp::Router* router = nullptr;
AbstractRouter* router = nullptr;
llarp_threadpool* worker = nullptr;
llarp::Logic* logic = nullptr;
llarp::Crypto* crypto = nullptr;
@ -123,7 +126,7 @@ namespace llarp
{
}
/// Generate all keys asynchronously and call hadler when done
/// Generate all keys asynchronously and call handler when done
void
AsyncGenerateKeys(Path_t* p, llarp::Logic* l, llarp_threadpool* pool,
User* u, Handler func)
@ -154,7 +157,7 @@ namespace llarp
// persist session with router until this path is done
ctx->router->PersistSessionUntil(remote, ctx->path->ExpireTime());
// add own path
ctx->router->paths.AddOwnPath(ctx->pathset, ctx->path);
ctx->router->pathContext().AddOwnPath(ctx->pathset, ctx->path);
ctx->path = nullptr;
}
else
@ -166,7 +169,7 @@ namespace llarp
namespace path
{
Builder::Builder(llarp::Router* p_router, struct llarp_dht_context* p_dht,
Builder::Builder(AbstractRouter* p_router, struct llarp_dht_context* p_dht,
size_t pathNum, size_t hops)
: llarp::path::PathSet(pathNum)
, router(p_router)
@ -181,7 +184,7 @@ namespace llarp
Builder::~Builder()
{
router->paths.RemovePathBuilder(this);
router->pathContext().RemovePathBuilder(this);
}
util::StatusObject
@ -215,7 +218,7 @@ namespace llarp
--tries;
if(db->select_random_hop(prev, cur, hop))
return true;
} while(router->routerProfiling.IsBad(cur.pubkey) && tries > 0);
} while(router->routerProfiling().IsBad(cur.pubkey) && tries > 0);
return false;
}
@ -317,7 +320,7 @@ namespace llarp
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->threadpool(), this,
&PathBuilderKeysGenerated);
}

@ -22,7 +22,7 @@ namespace llarp
std::atomic< bool > _run;
public:
llarp::Router* router;
AbstractRouter* router;
llarp_dht_context* dht;
llarp::SecretKey enckey;
size_t numHops;
@ -33,7 +33,7 @@ namespace llarp
std::atomic< uint8_t > keygens;
/// construct
Builder(llarp::Router* p_router, llarp_dht_context* p_dht,
Builder(AbstractRouter* p_router, llarp_dht_context* p_dht,
size_t numPaths, size_t numHops);
virtual ~Builder();

@ -58,7 +58,7 @@ namespace llarp
}
void
PathSet::Tick(llarp_time_t now, llarp::Router* r)
PathSet::Tick(llarp_time_t now, AbstractRouter* r)
{
Lock_t l(m_PathsMutex);
for(auto& item : m_Paths)

@ -65,7 +65,7 @@ namespace llarp
/// tick owned paths
void
Tick(llarp_time_t now, llarp::Router* r);
Tick(llarp_time_t now, AbstractRouter* r);
/// count the number of paths that will exist at this timestamp in future
size_t
@ -186,7 +186,7 @@ namespace llarp
std::set< llarp::service::Introduction >& intros) const;
virtual bool
PublishIntroSet(__attribute__((unused)) llarp::Router* r)
PublishIntroSet(__attribute__((unused)) AbstractRouter* r)
{
return false;
}

@ -1,8 +1,13 @@
#include <path/path.hpp>
#include <dht/context.hpp>
#include <exit/context.hpp>
#include <messages/discard.hpp>
#include <router/router.hpp>
#include <messages/exit.hpp>
#include <messages/path_latency.hpp>
#include <messages/path_transfer.hpp>
#include <messages/relay_commit.hpp>
#include <router/abstractrouter.hpp>
#include <routing/handler.hpp>
#include <util/buffer.hpp>
#include <util/endian.hpp>
@ -122,14 +127,14 @@ namespace llarp
bool
TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg,
llarp::Router* r)
AbstractRouter* r)
{
return r->dht()->impl.RelayRequestForPath(info.rxID, msg);
}
bool
TransitHop::HandlePathLatencyMessage(
const llarp::routing::PathLatencyMessage* msg, llarp::Router* r)
const llarp::routing::PathLatencyMessage* msg, AbstractRouter* r)
{
llarp::routing::PathLatencyMessage reply;
reply.L = msg->T;
@ -139,7 +144,7 @@ namespace llarp
bool
TransitHop::HandlePathConfirmMessage(
__attribute__((unused)) const llarp::routing::PathConfirmMessage* msg,
__attribute__((unused)) llarp::Router* r)
__attribute__((unused)) AbstractRouter* r)
{
llarp::LogWarn("unwarranted path confirm message on ", info);
return false;
@ -148,7 +153,7 @@ namespace llarp
bool
TransitHop::HandleDataDiscardMessage(
__attribute__((unused)) const llarp::routing::DataDiscardMessage* msg,
__attribute__((unused)) llarp::Router* r)
__attribute__((unused)) AbstractRouter* r)
{
llarp::LogWarn("unwarranted path data discard message on ", info);
return false;
@ -156,15 +161,15 @@ namespace llarp
bool
TransitHop::HandleObtainExitMessage(
const llarp::routing::ObtainExitMessage* msg, llarp::Router* r)
const llarp::routing::ObtainExitMessage* msg, AbstractRouter* r)
{
if(msg->Verify(r->crypto())
&& r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0))
&& 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(), r->identity))
if(!grant.Sign(r->crypto(), r->identity()))
{
llarp::LogError("Failed to sign grant exit message");
return false;
@ -176,7 +181,7 @@ namespace llarp
llarp::routing::RejectExitMessage reject;
reject.S = NextSeqNo();
reject.T = msg->T;
if(!reject.Sign(r->crypto(), r->identity))
if(!reject.Sign(r->crypto(), r->identity()))
{
llarp::LogError("Failed to sign reject exit message");
return false;
@ -186,17 +191,17 @@ namespace llarp
bool
TransitHop::HandleCloseExitMessage(
const llarp::routing::CloseExitMessage* msg, llarp::Router* r)
const llarp::routing::CloseExitMessage* msg, AbstractRouter* r)
{
llarp::routing::DataDiscardMessage discard(info.rxID, msg->S);
auto ep = r->exitContext.FindEndpointForPath(info.rxID);
auto ep = r->exitContext().FindEndpointForPath(info.rxID);
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(), r->identity))
if(reply.Sign(r->crypto(), r->identity()))
return SendRoutingMessage(&reply, r);
}
return SendRoutingMessage(&discard, r);
@ -204,7 +209,7 @@ namespace llarp
bool
TransitHop::HandleUpdateExitVerifyMessage(
const llarp::routing::UpdateExitVerifyMessage* msg, llarp::Router* r)
const llarp::routing::UpdateExitVerifyMessage* msg, AbstractRouter* r)
{
(void)msg;
(void)r;
@ -214,9 +219,9 @@ namespace llarp
bool
TransitHop::HandleUpdateExitMessage(
const llarp::routing::UpdateExitMessage* msg, llarp::Router* r)
const llarp::routing::UpdateExitMessage* msg, AbstractRouter* r)
{
auto ep = r->exitContext.FindEndpointForPath(msg->P);
auto ep = r->exitContext().FindEndpointForPath(msg->P);
if(ep)
{
if(!msg->Verify(r->crypto(), ep->PubKey()))
@ -237,29 +242,29 @@ namespace llarp
bool
TransitHop::HandleRejectExitMessage(
const llarp::routing::RejectExitMessage* msg, llarp::Router* r)
const llarp::routing::RejectExitMessage* msg, AbstractRouter* r)
{
(void)msg;
(void)r;
llarp::LogError(info, " got unwarrented RXM");
llarp::LogError(info, " got unwarranted RXM");
return false;
}
bool
TransitHop::HandleGrantExitMessage(
const llarp::routing::GrantExitMessage* msg, llarp::Router* r)
const llarp::routing::GrantExitMessage* msg, AbstractRouter* r)
{
(void)msg;
(void)r;
llarp::LogError(info, " got unwarrented GXM");
llarp::LogError(info, " got unwarranted GXM");
return false;
}
bool
TransitHop::HandleTransferTrafficMessage(
const llarp::routing::TransferTrafficMessage* msg, llarp::Router* r)
const llarp::routing::TransferTrafficMessage* msg, AbstractRouter* r)
{
auto endpoint = r->exitContext.FindEndpointForPath(info.rxID);
auto endpoint = r->exitContext().FindEndpointForPath(info.rxID);
if(endpoint)
{
bool sent = true;
@ -284,9 +289,9 @@ namespace llarp
bool
TransitHop::HandlePathTransferMessage(
const llarp::routing::PathTransferMessage* msg, llarp::Router* r)
const llarp::routing::PathTransferMessage* msg, AbstractRouter* r)
{
auto path = r->paths.GetPathForTransfer(msg->P);
auto path = r->pathContext().GetPathForTransfer(msg->P);
llarp::routing::DataDiscardMessage discarded(msg->P, msg->S);
if(!path)
{

@ -0,0 +1,8 @@
#include <router/abstractrouter.hpp>
namespace llarp
{
AbstractRouter::~AbstractRouter()
{
}
} // namespace llarp

@ -0,0 +1,144 @@
#ifndef LLARP_ABSTRACT_ROUTER_HPP
#define LLARP_ABSTRACT_ROUTER_HPP
#include <util/types.hpp>
#include <vector>
struct llarp_buffer_t;
struct llarp_dht_context;
struct llarp_ev_loop;
struct llarp_nodedb;
struct llarp_threadpool;
namespace llarp
{
struct Crypto;
class Logic;
struct RouterContact;
struct RouterID;
struct ILinkMessage;
struct ILinkSession;
struct PathID_t;
struct Profiling;
struct SecretKey;
struct Signature;
namespace exit
{
struct Context;
}
namespace path
{
struct PathContext;
}
namespace routing
{
struct IMessageHandler;
}
struct AbstractRouter
{
virtual ~AbstractRouter() = 0;
virtual void
OnSessionEstablished(RouterContact rc) = 0;
virtual bool
HandleRecvLinkMessageBuffer(ILinkSession *from,
const llarp_buffer_t &msg) = 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 RouterContact &
rc() const = 0;
virtual exit::Context &
exitContext() = 0;
virtual const SecretKey &
identity() const = 0;
virtual const SecretKey &
encryption() const = 0;
virtual Profiling &
routerProfiling() = 0;
virtual llarp_ev_loop *
netloop() const = 0;
virtual llarp_threadpool *
threadpool() = 0;
virtual llarp_threadpool *
diskworker() = 0;
virtual bool
Sign(Signature &sig, const llarp_buffer_t &buf) const = 0;
virtual const byte_t *
pubkey() const = 0;
virtual void
OnConnectTimeout(ILinkSession *session) = 0;
/// called by link when a remote session has no more sessions open
virtual void
SessionClosed(RouterID remote) = 0;
virtual llarp_time_t
Now() const = 0;
virtual bool
GetRandomGoodRouter(RouterID &r) = 0;
virtual bool
SendToOrQueue(const RouterID &remote, const ILinkMessage *msg) = 0;
virtual void
PersistSessionUntil(const RouterID &remote, llarp_time_t until) = 0;
virtual bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h,
const PathID_t &rxid) = 0;
virtual size_t
NumberOfConnectedRouters() const = 0;
virtual bool
GetRandomConnectedRouter(RouterContact &result) const = 0;
virtual void
HandleDHTLookupForExplore(RouterID remote,
const std::vector< RouterContact > &results) = 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;
};
} // namespace llarp
#endif

File diff suppressed because it is too large Load Diff

@ -1,6 +1,8 @@
#ifndef LLARP_ROUTER_HPP
#define LLARP_ROUTER_HPP
#include <router/abstractrouter.hpp>
#include <constants/link_layer.hpp>
#include <crypto/types.hpp>
#include <ev/ev.h>
@ -66,54 +68,6 @@ namespace llarp
}
};
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, public util::IStateful
{
bool ready;
@ -133,7 +87,7 @@ namespace llarp
fs::path our_rc_file = "rc.signed";
// our router contact
llarp::RouterContact _rc;
RouterContact _rc;
/// are we using the lokid service node seed ?
bool usingSNSeed = false;
@ -180,31 +134,73 @@ namespace llarp
return paths;
}
const llarp::RouterContact &
const RouterContact &
rc() const override
{
return _rc;
}
exit::Context &
exitContext() override
{
return _exitContext;
}
const SecretKey &
identity() const override
{
return _identity;
}
const SecretKey &
encryption() const override
{
return _encryption;
}
Profiling &
routerProfiling() override
{
return _routerProfiling;
}
llarp_ev_loop *
netloop() const override
{
return _netloop;
}
llarp_threadpool *
threadpool() override
{
return tp;
}
llarp_threadpool *
diskworker() override
{
return disk;
}
// our ipv4 public setting
bool publicOverride = false;
struct sockaddr_in ip4addr;
llarp::AddressInfo addrInfo;
AddressInfo addrInfo;
llarp_ev_loop *netloop;
llarp_ev_loop *_netloop;
llarp_threadpool *tp;
Logic *_logic;
std::unique_ptr< Crypto > _crypto;
path::PathContext paths;
exit::Context exitContext;
SecretKey identity;
SecretKey encryption;
exit::Context _exitContext;
SecretKey _identity;
SecretKey _encryption;
llarp_threadpool *disk;
llarp_dht_context *_dht = nullptr;
llarp_nodedb *_nodedb;
bool
Sign(Signature &sig, const llarp_buffer_t &buf) const;
Sign(Signature &sig, const llarp_buffer_t &buf) const override;
// buffer for serializing link messages
std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer;
@ -223,10 +219,10 @@ namespace llarp
uint32_t ticker_job_id = 0;
llarp::InboundMessageParser inbound_link_msg_parser;
llarp::routing::InboundMessageParser inbound_routing_msg_parser;
InboundMessageParser inbound_link_msg_parser;
routing::InboundMessageParser inbound_routing_msg_parser;
llarp::service::Context hiddenServiceContext;
service::Context hiddenServiceContext;
using NetConfig_t = std::unordered_multimap< std::string, std::string >;
@ -235,10 +231,10 @@ namespace llarp
/// identity keys whitelist of routers we will connect to directly (not for
/// service nodes)
std::set< llarp::RouterID > strictConnectPubkeys;
std::set< RouterID > strictConnectPubkeys;
/// bootstrap RCs
std::list< llarp::RouterContact > bootstrapRCList;
std::list< RouterContact > bootstrapRCList;
bool
ExitEnabled() const
@ -247,7 +243,7 @@ namespace llarp
auto itr = netConfig.find("exit");
if(itr == netConfig.end())
return false;
return llarp::IsTrueValue(itr->second.c_str());
return IsTrueValue(itr->second.c_str());
}
bool
@ -258,76 +254,70 @@ namespace llarp
const std::string DefaultRPCBindAddr = "127.0.0.1:1190";
bool enableRPCServer = true;
std::unique_ptr< llarp::rpc::Server > rpcServer;
std::unique_ptr< rpc::Server > rpcServer;
std::string rpcBindAddr = DefaultRPCBindAddr;
/// lokid caller
const std::string DefaultLokidRPCAddr = "127.0.0.1:22023";
std::unique_ptr< llarp::rpc::Caller > rpcCaller;
std::unique_ptr< rpc::Caller > rpcCaller;
std::string lokidRPCAddr = DefaultLokidRPCAddr;
std::string lokidRPCUser = "";
std::string lokidRPCPassword = "";
std::set< std::unique_ptr< llarp::ILinkLayer >,
CompareLinks< llarp::ILinkLayer > >
std::set< std::unique_ptr< ILinkLayer >, CompareLinks< ILinkLayer > >
outboundLinks;
std::set< std::unique_ptr< llarp::ILinkLayer >,
CompareLinks< llarp::ILinkLayer > >
std::set< std::unique_ptr< ILinkLayer >, CompareLinks< ILinkLayer > >
inboundLinks;
llarp::Profiling routerProfiling;
Profiling _routerProfiling;
std::string routerProfilesFile = "profiles.dat";
using MessageQueue = std::queue< std::vector< byte_t > >;
/// outbound message queue
std::unordered_map< llarp::RouterID, MessageQueue, llarp::RouterID::Hash >
std::unordered_map< RouterID, MessageQueue, RouterID::Hash >
outboundMessageQueue;
/// loki verified routers
std::unordered_map< llarp::RouterID, llarp::RouterContact,
llarp::RouterID::Hash >
validRouters;
std::unordered_map< RouterID, RouterContact, RouterID::Hash > validRouters;
// pending establishing session with routers
std::unordered_map< llarp::RouterID, std::unique_ptr< TryConnectJob >,
llarp::RouterID::Hash >
std::unordered_map< RouterID, std::unique_ptr< TryConnectJob >,
RouterID::Hash >
pendingEstablishJobs;
// pending RCs to be verified by pubkey
std::unordered_map< llarp::RouterID, llarp_async_verify_rc,
llarp::RouterID::Hash >
std::unordered_map< RouterID, llarp_async_verify_rc, RouterID::Hash >
pendingVerifyRC;
// sessions to persist -> timestamp to end persist at
std::unordered_map< llarp::RouterID, llarp_time_t, llarp::RouterID::Hash >
std::unordered_map< RouterID, llarp_time_t, RouterID::Hash >
m_PersistingSessions;
// lokinet routers from lokid, maps pubkey to when we think it will expire,
// set to max value right now
std::unordered_map< llarp::RouterID, llarp_time_t, llarp::PubKey::Hash >
lokinetRouters;
std::unordered_map< RouterID, llarp_time_t, PubKey::Hash > lokinetRouters;
Router(struct llarp_threadpool *tp, struct llarp_ev_loop *netloop,
llarp::Logic *logic);
Router(struct llarp_threadpool *tp, struct llarp_ev_loop *__netloop,
Logic *logic);
~Router();
void
OnSessionEstablished(llarp::RouterContact rc);
OnSessionEstablished(RouterContact rc) override;
bool
HandleRecvLinkMessageBuffer(llarp::ILinkSession *from,
const llarp_buffer_t &msg);
HandleRecvLinkMessageBuffer(ILinkSession *from,
const llarp_buffer_t &msg) override;
void
AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link);
AddInboundLink(std::unique_ptr< ILinkLayer > &link);
bool
InitOutboundLinks();
bool
GetRandomGoodRouter(RouterID &r);
GetRandomGoodRouter(RouterID &r) override;
/// initialize us as a service node
/// return true on success
@ -345,7 +335,7 @@ namespace llarp
LoadHiddenServiceConfig(const char *fname);
bool
AddHiddenService(const llarp::service::Config::section_t &config);
AddHiddenService(const service::Config::section_t &config);
bool
Configure(Config *conf);
@ -365,8 +355,7 @@ namespace llarp
StopLinks();
void
PersistSessionUntil(const llarp::RouterID &remote,
llarp_time_t until) override;
PersistSessionUntil(const RouterID &remote, llarp_time_t until) override;
bool
EnsureIdentity();
@ -375,7 +364,7 @@ namespace llarp
EnsureEncryptionKey();
bool
ConnectionToRouterAllowed(const llarp::RouterID &router) const;
ConnectionToRouterAllowed(const RouterID &router) const;
bool
SaveRC();
@ -383,14 +372,14 @@ namespace llarp
const byte_t *
pubkey() const override
{
return llarp::seckey_topublic(identity);
return seckey_topublic(_identity);
}
void
OnConnectTimeout(ILinkSession *session);
OnConnectTimeout(ILinkSession *session) override;
bool
HasPendingConnectJob(const llarp::RouterID &remote);
HasPendingConnectJob(const RouterID &remote);
void
try_connect(fs::path rcfile);
@ -411,49 +400,44 @@ namespace llarp
/// NOT threadsafe
/// MUST be called in the logic thread
bool
SendToOrQueue(const llarp::RouterID &remote,
const llarp::ILinkMessage *msg) override;
SendToOrQueue(const RouterID &remote, const ILinkMessage *msg) override;
/// sendto or drop
void
SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg,
llarp::ILinkLayer *chosen);
SendTo(RouterID remote, const ILinkMessage *msg, ILinkLayer *chosen);
/// manually flush outbound message queue for just 1 router
void
FlushOutboundFor(llarp::RouterID remote,
llarp::ILinkLayer *chosen = nullptr);
FlushOutboundFor(RouterID remote, ILinkLayer *chosen = nullptr);
/// manually discard all pending messages to remote router
void
DiscardOutboundFor(const llarp::RouterID &remote);
DiscardOutboundFor(const RouterID &remote);
/// try establishing a session to a remote router
void
TryEstablishTo(const llarp::RouterID &remote);
TryEstablishTo(const RouterID &remote);
/// lookup a router by pubkey when it expires when we are a service node
void
ServiceNodeLookupRouterWhenExpired(llarp::RouterID remote);
ServiceNodeLookupRouterWhenExpired(RouterID remote);
void
HandleDHTLookupForExplore(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results) override;
RouterID remote, const std::vector< RouterContact > &results) override;
void
ForEachPeer(
std::function< void(const llarp::ILinkSession *, bool) > visit) const;
ForEachPeer(std::function< void(const ILinkSession *, bool) > visit) const;
void
ForEachPeer(std::function< void(llarp::ILinkSession *) > visit);
ForEachPeer(std::function< void(ILinkSession *) > visit);
/// check if newRc matches oldRC and update local rc for this remote contact
/// if valid
/// returns true on valid and updated
/// returns false otherwise
bool
CheckRenegotiateValid(RouterContact newRc, RouterContact oldRC);
CheckRenegotiateValid(RouterContact newRc, RouterContact oldRC) override;
/// flush outbound message queue
void
@ -461,7 +445,7 @@ namespace llarp
/// called by link when a remote session has no more sessions open
void
SessionClosed(RouterID remote);
SessionClosed(RouterID remote) override;
/// call internal router ticker
void
@ -471,15 +455,15 @@ namespace llarp
llarp_time_t
Now() const override
{
return llarp_ev_loop_time_now_ms(netloop);
return llarp_ev_loop_time_now_ms(_netloop);
}
/// schedule ticker to call i ms from now
void
ScheduleTicker(uint64_t i = 1000);
llarp::ILinkLayer *
GetLinkWithSessionByPubkey(const llarp::RouterID &remote);
ILinkLayer *
GetLinkWithSessionByPubkey(const RouterID &remote);
/// parse a routing message in a buffer and handle it with a handler if
/// successful parsing return true on parse and handle success otherwise
@ -487,35 +471,33 @@ namespace llarp
bool
ParseRoutingMessageBuffer(const llarp_buffer_t &buf,
routing::IMessageHandler *h,
PathID_t rxid) override;
const PathID_t &rxid) override;
void
ConnectToRandomRouters(int N);
size_t
NumberOfConnectedRouters() const;
NumberOfConnectedRouters() const override;
bool
TryConnectAsync(llarp::RouterContact rc, uint16_t tries);
TryConnectAsync(RouterContact rc, uint16_t tries);
bool
GetRandomConnectedRouter(llarp::RouterContact &result) const;
GetRandomConnectedRouter(RouterContact &result) const override;
void
async_verify_RC(const llarp::RouterContact &rc, llarp::ILinkLayer *link);
async_verify_RC(const RouterContact &rc, ILinkLayer *link);
void
HandleDHTLookupForSendTo(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results);
HandleDHTLookupForSendTo(RouterID remote,
const std::vector< RouterContact > &results);
bool
HasSessionTo(const llarp::RouterID &remote) const;
HasSessionTo(const RouterID &remote) const;
void
HandleDHTLookupForTryEstablishTo(
llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results);
RouterID remote, const std::vector< RouterContact > &results);
static void
on_verify_client_rc(llarp_async_verify_rc *context);

@ -1,6 +1,7 @@
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#include <routing/handler.hpp>
namespace llarp
{
@ -49,7 +50,7 @@ namespace llarp
}
bool
DHTMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const
DHTMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const
{
// set source as us
llarp::dht::Key_t us{r->pubkey()};

@ -1,68 +1,85 @@
#ifndef LLARP_ROUTING_HANDLER_HPP
#define LLARP_ROUTING_HANDLER_HPP
#include <messages/exit.hpp>
#include <messages/path_confirm.hpp>
#include <messages/path_latency.hpp>
#include <messages/path_transfer.hpp>
#include <messages/transfer_traffic.hpp>
#include <util/buffer.hpp>
namespace llarp
{
struct AbstractRouter;
namespace dht
{
struct IMessage;
}
namespace service
{
struct ProtocolFrame;
}
namespace routing
{
struct DataDiscardMessage;
struct GrantExitMessage;
struct ObtainExitMessage;
struct RejectExitMessage;
struct TransferTrafficMessage;
struct UpdateExitMessage;
struct UpdateExitVerifyMessage;
struct CloseExitMessage;
struct PathTransferMessage;
struct PathConfirmMessage;
struct PathLatencyMessage;
// handles messages on the routing level
struct IMessageHandler
{
virtual bool
HandleObtainExitMessage(const ObtainExitMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleGrantExitMessage(const GrantExitMessage *msg, llarp::Router *r) = 0;
HandleGrantExitMessage(const GrantExitMessage *msg,
AbstractRouter *r) = 0;
virtual bool
HandleRejectExitMessage(const RejectExitMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleTransferTrafficMessage(const TransferTrafficMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleUpdateExitMessage(const UpdateExitMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleCloseExitMessage(const CloseExitMessage *msg, llarp::Router *r) = 0;
HandleCloseExitMessage(const CloseExitMessage *msg,
AbstractRouter *r) = 0;
virtual bool
HandleDataDiscardMessage(const DataDiscardMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandlePathTransferMessage(const PathTransferMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleHiddenServiceFrame(const service::ProtocolFrame *msg) = 0;
virtual bool
HandlePathConfirmMessage(const PathConfirmMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandlePathLatencyMessage(const PathLatencyMessage *msg,
llarp::Router *r) = 0;
AbstractRouter *r) = 0;
virtual bool
HandleDHTMessage(const llarp::dht::IMessage *msg, llarp::Router *r) = 0;
HandleDHTMessage(const dht::IMessage *msg, AbstractRouter *r) = 0;
};
} // namespace routing
} // namespace llarp

@ -7,14 +7,14 @@
namespace llarp
{
struct Router;
struct AbstractRouter;
namespace routing
{
struct IMessageHandler;
struct IMessage : public llarp::IBEncodeMessage
{
llarp::PathID_t from;
PathID_t from;
uint64_t S;
IMessage() : llarp::IBEncodeMessage(), S(0)
@ -24,7 +24,7 @@ namespace llarp
virtual ~IMessage(){};
virtual bool
HandleMessage(IMessageHandler* h, llarp::Router* r) const = 0;
HandleMessage(IMessageHandler* h, AbstractRouter* r) const = 0;
virtual void
Clear() = 0;

@ -1,16 +1,47 @@
#include <routing/message_parser.hpp>
#include <messages/dht.hpp>
#include <messages/discard.hpp>
#include <messages/exit.hpp>
#include <messages/path_confirm.hpp>
#include <messages/path_latency.hpp>
#include <messages/path_transfer.hpp>
#include <messages/transfer_traffic.hpp>
#include <path/path_types.hpp>
#include <util/mem.hpp>
namespace llarp
{
namespace routing
{
struct InboundMessageParser::MessageHolder
{
DataDiscardMessage D;
PathLatencyMessage L;
DHTMessage M;
PathConfirmMessage P;
PathTransferMessage T;
service::ProtocolFrame H;
TransferTrafficMessage I;
GrantExitMessage G;
RejectExitMessage J;
ObtainExitMessage O;
UpdateExitMessage U;
CloseExitMessage C;
};
InboundMessageParser::InboundMessageParser()
: firstKey(false)
, key('\0')
, msg(nullptr)
, m_Holder(std::make_unique< MessageHolder >())
{
reader.user = this;
reader.on_key = &OnKey;
firstKey = false;
}
InboundMessageParser::~InboundMessageParser()
{
}
bool
@ -39,40 +70,40 @@ namespace llarp
switch(self->key)
{
case 'D':
self->msg = &self->m_Holder.D;
self->msg = &self->m_Holder->D;
break;
case 'L':
self->msg = &self->m_Holder.L;
self->msg = &self->m_Holder->L;
break;
case 'M':
self->msg = &self->m_Holder.M;
self->msg = &self->m_Holder->M;
break;
case 'P':
self->msg = &self->m_Holder.P;
self->msg = &self->m_Holder->P;
break;
case 'T':
self->msg = &self->m_Holder.T;
self->msg = &self->m_Holder->T;
break;
case 'H':
self->msg = &self->m_Holder.H;
self->msg = &self->m_Holder->H;
break;
case 'I':
self->msg = &self->m_Holder.I;
self->msg = &self->m_Holder->I;
break;
case 'G':
self->msg = &self->m_Holder.G;
self->msg = &self->m_Holder->G;
break;
case 'J':
self->msg = &self->m_Holder.J;
self->msg = &self->m_Holder->J;
break;
case 'O':
self->msg = &self->m_Holder.O;
self->msg = &self->m_Holder->O;
break;
case 'U':
self->msg = &self->m_Holder.U;
self->msg = &self->m_Holder->U;
break;
case 'C':
self->msg = &self->m_Holder.C;
self->msg = &self->m_Holder->C;
break;
default:
llarp::LogError("invalid routing message id: ", *strbuf.cur);
@ -90,7 +121,7 @@ namespace llarp
InboundMessageParser::ParseMessageBuffer(const llarp_buffer_t& buf,
IMessageHandler* h,
const PathID_t& from,
llarp::Router* r)
AbstractRouter* r)
{
bool result = false;
msg = nullptr;

@ -1,56 +1,42 @@
#ifndef LLARP_ROUTING_MESSAGE_PARSER_HPP
#define LLARP_ROUTING_MESSAGE_PARSER_HPP
#include <messages/dht.hpp>
#include <messages/discard.hpp>
#include <messages/path_confirm.hpp>
#include <messages/path_latency.hpp>
#include <messages/path_transfer.hpp>
#include <path/path_types.hpp>
#include <util/bencode.hpp>
#include <util/bencode.h>
#include <util/buffer.hpp>
#include <memory>
namespace llarp
{
struct Router;
struct AbstractRouter;
struct PathID_t;
namespace routing
{
struct IMessage;
struct IMessageHandler;
struct InboundMessageParser
{
InboundMessageParser();
~InboundMessageParser();
bool
ParseMessageBuffer(const llarp_buffer_t& buf, IMessageHandler* handler,
const PathID_t& from, llarp::Router* r);
const PathID_t& from, AbstractRouter* r);
private:
static bool
OnKey(dict_reader* r, llarp_buffer_t* key);
bool firstKey;
char key;
dict_reader reader;
struct MessageHolder
{
DataDiscardMessage D;
PathLatencyMessage L;
DHTMessage M;
PathConfirmMessage P;
PathTransferMessage T;
service::ProtocolFrame H;
TransferTrafficMessage I;
GrantExitMessage G;
RejectExitMessage J;
ObtainExitMessage O;
UpdateExitMessage U;
CloseExitMessage C;
};
IMessage* msg = nullptr;
MessageHolder m_Holder;
struct MessageHolder;
IMessage* msg;
std::unique_ptr< MessageHolder > m_Holder;
};
} // namespace routing
} // namespace llarp

@ -53,7 +53,7 @@ namespace llarp
bool
PathConfirmMessage::HandleMessage(IMessageHandler* h,
llarp::Router* r) const
AbstractRouter* r) const
{
return h && h->HandlePathConfirmMessage(this, r);
}

@ -47,7 +47,7 @@ namespace llarp
bool
PathLatencyMessage::HandleMessage(IMessageHandler* h,
llarp::Router* r) const
AbstractRouter* r) const
{
return h && h->HandlePathLatencyMessage(this, r);
}

@ -59,7 +59,7 @@ namespace llarp
bool
PathTransferMessage::HandleMessage(IMessageHandler* h,
llarp::Router* r) const
AbstractRouter* r) const
{
return h->HandlePathTransferMessage(this, r);
}

@ -1,6 +1,6 @@
#include <rpc/rpc.hpp>
#include <router/router.hpp>
#include <router/abstractrouter.hpp>
#ifdef USE_ABYSS
#include <util/encode.hpp>
@ -116,7 +116,7 @@ namespace llarp
struct CallerImpl : public ::abyss::http::JSONRPC
{
Router* router;
AbstractRouter* router;
llarp_time_t m_NextKeyUpdate = 0;
const llarp_time_t KeyUpdateInterval = 1000 * 60 * 2;
using PubkeyList_t = GetServiceNodeListHandler::PubkeyList_t;
@ -124,7 +124,7 @@ namespace llarp
std::string username;
std::string password;
CallerImpl(Router* r) : ::abyss::http::JSONRPC(), router(r)
CallerImpl(AbstractRouter* r) : ::abyss::http::JSONRPC(), router(r)
{
}
@ -207,8 +207,8 @@ namespace llarp
struct Handler : public ::abyss::httpd::IRPCHandler
{
Router* router;
Handler(::abyss::httpd::ConnImpl* conn, Router* r)
AbstractRouter* router;
Handler(::abyss::httpd::ConnImpl* conn, AbstractRouter* r)
: ::abyss::httpd::IRPCHandler(conn), router(r)
{
}
@ -293,11 +293,11 @@ namespace llarp
struct ReqHandlerImpl : public ::abyss::httpd::BaseReqHandler
{
ReqHandlerImpl(Router* r, llarp_time_t reqtimeout)
ReqHandlerImpl(AbstractRouter* r, llarp_time_t reqtimeout)
: ::abyss::httpd::BaseReqHandler(reqtimeout), router(r)
{
}
Router* router;
AbstractRouter* router;
::abyss::httpd::IRPCHandler*
CreateHandler(::abyss::httpd::ConnImpl* conn)
{
@ -307,10 +307,10 @@ namespace llarp
struct ServerImpl
{
Router* router;
AbstractRouter* router;
ReqHandlerImpl _handler;
ServerImpl(Router* r) : router(r), _handler(r, 2000)
ServerImpl(AbstractRouter* r) : router(r), _handler(r, 2000)
{
}
@ -346,7 +346,7 @@ namespace llarp
#else
struct ServerImpl
{
ServerImpl(__attribute__((unused)) Router* r){};
ServerImpl(__attribute__((unused)) AbstractRouter* r){};
bool
Start(__attribute__((unused)) const std::string& addr)
@ -362,7 +362,7 @@ namespace llarp
struct CallerImpl
{
CallerImpl(__attribute__((unused)) Router* r)
CallerImpl(__attribute__((unused)) AbstractRouter* r)
{
}
@ -395,7 +395,8 @@ namespace llarp
#endif
Caller::Caller(Router* r) : m_Impl(std::make_unique< CallerImpl >(r))
Caller::Caller(AbstractRouter* r)
: m_Impl(std::make_unique< CallerImpl >(r))
{
}
@ -427,7 +428,8 @@ namespace llarp
m_Impl->SetBasicAuth(user, passwd);
}
Server::Server(Router* r) : m_Impl(std::make_unique< ServerImpl >(r))
Server::Server(AbstractRouter* r)
: m_Impl(std::make_unique< ServerImpl >(r))
{
}

@ -10,7 +10,7 @@
namespace llarp
{
struct PubKey;
struct Router;
struct AbstractRouter;
namespace rpc
{
@ -19,7 +19,7 @@ namespace llarp
/// jsonrpc server
struct Server
{
Server(Router* r);
Server(AbstractRouter* r);
~Server();
bool
@ -38,7 +38,7 @@ namespace llarp
/// jsonrpc caller
struct Caller
{
Caller(Router* r);
Caller(AbstractRouter* r);
~Caller();
/// set http basic auth for use with remote rpc endpoint

@ -2,14 +2,15 @@
#include <handlers/null.hpp>
#include <handlers/tun.hpp>
#include <router/router.hpp>
#include <nodedb.hpp>
#include <router/abstractrouter.hpp>
#include <service/endpoint.hpp>
namespace llarp
{
namespace service
{
Context::Context(llarp::Router *r) : m_Router(r)
Context::Context(AbstractRouter *r) : m_Router(r)
{
}
@ -312,16 +313,16 @@ namespace llarp
static std::map< std::string,
std::function< llarp::service::Endpoint *(
const std::string &, llarp::Router *,
const std::string &, AbstractRouter *,
llarp::service::Context *) > >
endpointConstructors = {
{"tun",
[](const std::string &nick, llarp::Router *r,
[](const std::string &nick, AbstractRouter *r,
llarp::service::Context *c) -> llarp::service::Endpoint * {
return new llarp::handlers::TunEndpoint(nick, r, c);
}},
{"null",
[](const std::string &nick, llarp::Router *r,
[](const std::string &nick, AbstractRouter *r,
llarp::service::Context *c) -> llarp::service::Endpoint * {
return new llarp::handlers::NullEndpoint(nick, r, c);
}}};

@ -15,7 +15,7 @@ namespace llarp
/// holds all the hidden service endpoints we own
struct Context : public util::IStateful
{
Context(llarp::Router *r);
Context(AbstractRouter *r);
~Context();
void
@ -96,7 +96,7 @@ namespace llarp
StartAll();
private:
llarp::Router *m_Router;
AbstractRouter *m_Router;
std::unordered_map< std::string, std::unique_ptr< Endpoint > >
m_Endpoints;
std::list< std::unique_ptr< Endpoint > > m_Stopped;

@ -6,7 +6,10 @@
#include <dht/messages/gotrouter.hpp>
#include <dht/messages/pubintro.hpp>
#include <messages/dht.hpp>
#include <router/router.hpp>
#include <messages/path_transfer.hpp>
#include <nodedb.hpp>
#include <profiling.hpp>
#include <router/abstractrouter.hpp>
#include <service/protocol.hpp>
#include <util/logic.hpp>
@ -16,7 +19,7 @@ namespace llarp
{
namespace service
{
Endpoint::Endpoint(const std::string& name, llarp::Router* r,
Endpoint::Endpoint(const std::string& name, AbstractRouter* r,
Context* parent)
: path::Builder(r, r->dht(), 6, DEFAULT_HOP_LENGTH)
, context(parent)
@ -69,7 +72,7 @@ namespace llarp
if(m_IsolatedNetLoop)
return m_IsolatedNetLoop;
else
return m_Router->netloop;
return m_Router->netloop();
}
bool
@ -623,7 +626,7 @@ namespace llarp
}
bool
Endpoint::PublishIntroSet(llarp::Router* r)
Endpoint::PublishIntroSet(AbstractRouter* r)
{
// publish via near router
RouterID location = m_Identity.pub.Addr().as_array();
@ -671,7 +674,7 @@ namespace llarp
}
bool
Endpoint::PublishIntroSetVia(llarp::Router* r, path::Path* path)
Endpoint::PublishIntroSetVia(AbstractRouter* r, path::Path* path)
{
auto job = new PublishIntroSetJob(this, GenTXID(), m_IntroSet);
if(job->SendRequestViaPath(path, r))
@ -809,8 +812,8 @@ namespace llarp
return false;
llarp_async_verify_rc* job = new llarp_async_verify_rc;
job->nodedb = m_Router->nodedb();
job->cryptoworker = m_Router->tp;
job->diskworker = m_Router->disk;
job->cryptoworker = m_Router->threadpool();
job->diskworker = m_Router->diskworker();
job->logic = m_Router->logic();
job->hook = nullptr;
job->rc = msg->R[0];
@ -1312,12 +1315,13 @@ namespace llarp
}
}
// no converstation
return EnsurePathToService(remote,
[](Address, OutboundContext* c) {
if(c)
c->UpdateIntroSet(true);
},
5000, false);
return EnsurePathToService(
remote,
[](Address, OutboundContext* c) {
if(c)
c->UpdateIntroSet(true);
},
5000, false);
}
bool
@ -1354,8 +1358,9 @@ namespace llarp
{
nodedb->select_random_hop(hops[hop - 1], hops[hop], hop);
--tries;
} while(m_Endpoint->Router()->routerProfiling.IsBad(hops[hop].pubkey)
&& tries > 0);
} while(
m_Endpoint->Router()->routerProfiling().IsBad(hops[hop].pubkey)
&& tries > 0);
return tries > 0;
}
return false;
@ -1898,7 +1903,7 @@ namespace llarp
llarp_threadpool*
Endpoint::Worker()
{
return m_Router->tp;
return m_Router->threadpool();
}
} // namespace service

@ -37,7 +37,7 @@ namespace llarp
static const size_t MAX_OUTBOUND_CONTEXT_COUNT = 4;
Endpoint(const std::string& nickname, llarp::Router* r, Context* parent);
Endpoint(const std::string& nickname, AbstractRouter* r, Context* parent);
~Endpoint();
virtual util::StatusObject
@ -84,7 +84,7 @@ namespace llarp
llarp_threadpool*
Worker();
llarp::Router*
AbstractRouter*
Router()
{
return m_Router;
@ -106,10 +106,10 @@ namespace llarp
EnsureReplyPath(const ServiceInfo& addr);
bool
PublishIntroSet(llarp::Router* r) override;
PublishIntroSet(AbstractRouter* r) override;
bool
PublishIntroSetVia(llarp::Router* r, path::Path* p);
PublishIntroSetVia(AbstractRouter* r, path::Path* p);
bool
HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg) override;
@ -461,7 +461,7 @@ namespace llarp
std::unique_ptr< llarp::exit::BaseSession > m_Exit;
private:
llarp::Router* m_Router;
AbstractRouter* m_Router;
llarp_threadpool* m_IsolatedWorker = nullptr;
llarp::Logic* m_IsolatedLogic = nullptr;
llarp_ev_loop* m_IsolatedNetLoop = nullptr;

@ -1,12 +1,13 @@
#include <service/lookup.hpp>
#include <path/path.hpp>
#include <router/router.hpp>
#include <service/endpoint.hpp>
#include <util/time.hpp>
namespace llarp
{
struct AbstractRouter;
namespace service
{
IServiceLookup::IServiceLookup(ILookupHolder *p, uint64_t tx,
@ -18,7 +19,7 @@ namespace llarp
}
bool
IServiceLookup::SendRequestViaPath(path::Path *path, Router *r)
IServiceLookup::SendRequestViaPath(path::Path *path, AbstractRouter *r)
{
auto msg = BuildRequestMessage();
if(!msg)

@ -48,7 +48,7 @@ namespace llarp
/// build a new requset message and send it via a path
bool
SendRequestViaPath(llarp::path::Path* p, llarp::Router* r);
SendRequestViaPath(llarp::path::Path* p, AbstractRouter* r);
ILookupHolder* parent;
uint64_t txid;

@ -392,7 +392,8 @@ namespace llarp
bool
ProtocolFrame::HandleMessage(llarp::routing::IMessageHandler* h,
__attribute__((unused)) llarp::Router* r) const
__attribute__((unused))
AbstractRouter* r) const
{
return h->HandleHiddenServiceFrame(this);
}

@ -134,7 +134,7 @@ namespace llarp
Verify(Crypto* c, const ServiceInfo& from) const;
bool
HandleMessage(routing::IMessageHandler* h, Router* r) const override;
HandleMessage(routing::IMessageHandler* h, AbstractRouter* r) const override;
};
} // namespace service
} // namespace llarp

@ -23,9 +23,9 @@ TEST_F(ExitTest, AddMultipleIP)
conf.emplace("exit", "true");
conf.emplace("type", "null");
conf.emplace("ifaddr", "10.0.0.1/24");
ASSERT_TRUE(r.exitContext.AddExitEndpoint("test-exit", conf));
ASSERT_TRUE(r.exitContext.ObtainNewExit(pk, firstPath, true));
ASSERT_TRUE(r.exitContext.ObtainNewExit(pk, secondPath, true));
ASSERT_TRUE(r.exitContext.FindEndpointForPath(firstPath)->LocalIP()
== r.exitContext.FindEndpointForPath(secondPath)->LocalIP());
ASSERT_TRUE(r.exitContext().AddExitEndpoint("test-exit", conf));
ASSERT_TRUE(r.exitContext().ObtainNewExit(pk, firstPath, true));
ASSERT_TRUE(r.exitContext().ObtainNewExit(pk, secondPath, true));
ASSERT_TRUE(r.exitContext().FindEndpointForPath(firstPath)->LocalIP()
== r.exitContext().FindEndpointForPath(secondPath)->LocalIP());
};

Loading…
Cancel
Save