lokinet/llarp/service/endpoint.cpp

1094 lines
31 KiB
C++
Raw Normal View History

2018-08-04 02:59:32 +00:00
2018-07-18 03:10:21 +00:00
#include <llarp/dht/messages/findintro.hpp>
#include <llarp/messages/dht.hpp>
#include <llarp/service/endpoint.hpp>
2018-07-19 04:58:39 +00:00
#include <llarp/service/protocol.hpp>
#include "buffer.hpp"
#include "router.hpp"
namespace llarp
{
namespace service
{
Endpoint::Endpoint(const std::string& name, llarp_router* r)
2018-08-30 18:48:43 +00:00
: path::Builder(r, r->dht, 2, 4), m_Router(r), m_Name(name)
{
2018-07-18 22:50:05 +00:00
m_Tag.Zero();
}
bool
Endpoint::SetOption(const std::string& k, const std::string& v)
{
if(k == "keyfile")
{
m_Keyfile = v;
}
2018-07-18 03:10:21 +00:00
if(k == "tag")
{
m_Tag = v;
llarp::LogInfo("Setting tag to ", v);
2018-07-18 03:10:21 +00:00
}
if(k == "prefetch-tag")
{
m_PrefetchTags.insert(v);
}
if(k == "prefetch-addr")
{
Address addr;
if(addr.FromString(v))
m_PrefetchAddrs.insert(addr);
}
2018-08-09 19:02:17 +00:00
if(k == "netns")
{
m_NetNS = v;
m_OnInit.push_back(std::bind(&Endpoint::IsolateNetwork, this));
}
return true;
}
bool
Endpoint::IsolateNetwork()
{
llarp::LogInfo("isolating network to namespace ", m_NetNS);
2018-08-09 19:02:17 +00:00
m_IsolatedWorker = llarp_init_isolated_net_threadpool(
2018-08-26 12:51:22 +00:00
m_NetNS.c_str(), &SetupIsolatedNetwork, &RunIsolatedMainLoop, this);
2018-08-09 19:02:17 +00:00
m_IsolatedLogic = llarp_init_single_process_logic(m_IsolatedWorker);
return true;
}
llarp_ev_loop*
Endpoint::EndpointNetLoop()
{
if(m_IsolatedNetLoop)
return m_IsolatedNetLoop;
else
return m_Router->netloop;
}
2018-08-16 14:34:15 +00:00
bool
Endpoint::NetworkIsIsolated() const
{
return m_IsolatedLogic && m_IsolatedWorker;
}
2018-08-09 19:02:17 +00:00
bool
2018-08-18 14:01:21 +00:00
Endpoint::SetupIsolatedNetwork(void* user, bool failed)
2018-08-09 19:02:17 +00:00
{
2018-08-20 19:12:12 +00:00
return static_cast< Endpoint* >(user)->DoNetworkIsolation(!failed);
2018-08-09 19:02:17 +00:00
}
2018-08-10 03:51:38 +00:00
bool
Endpoint::HasPendingPathToService(const Address& addr) const
{
return m_PendingServiceLookups.find(addr)
!= m_PendingServiceLookups.end();
}
void
2018-07-18 22:50:05 +00:00
Endpoint::Tick(llarp_time_t now)
{
/// reset tx id for publish
if(now - m_LastPublishAttempt >= INTROSET_PUBLISH_RETRY_INTERVAL)
m_CurrentPublishTX = 0;
2018-07-19 04:58:39 +00:00
// publish descriptors
2018-07-18 22:50:05 +00:00
if(ShouldPublishDescriptors(now))
{
2018-07-19 04:58:39 +00:00
std::set< Introduction > I;
2018-07-18 03:10:21 +00:00
if(!GetCurrentIntroductions(I))
{
2018-07-16 03:32:13 +00:00
llarp::LogWarn("could not publish descriptors for endpoint ", Name(),
" because we couldn't get any introductions");
if(ShouldBuildMore())
ManualRebuild(1);
return;
}
2018-07-20 04:50:28 +00:00
m_IntroSet.I.clear();
for(const auto& intro : I)
m_IntroSet.I.push_back(intro);
2018-07-18 22:50:05 +00:00
m_IntroSet.topic = m_Tag;
2018-07-18 03:10:21 +00:00
if(!m_Identity.SignIntroSet(m_IntroSet, &m_Router->crypto))
{
2018-07-16 03:32:13 +00:00
llarp::LogWarn("failed to sign introset for endpoint ", Name());
return;
}
2018-07-17 06:17:13 +00:00
if(PublishIntroSet(m_Router))
{
2018-07-16 03:32:13 +00:00
llarp::LogInfo("publishing introset for endpoint ", Name());
}
else
{
2018-07-16 03:32:13 +00:00
llarp::LogWarn("failed to publish intro set for endpoint ", Name());
}
}
// expire pending tx
{
2018-08-14 21:17:18 +00:00
std::set< service::IntroSet > empty;
auto itr = m_PendingLookups.begin();
while(itr != m_PendingLookups.end())
{
if(itr->second->IsTimedOut(now))
{
2018-08-14 21:17:18 +00:00
std::unique_ptr< IServiceLookup > lookup = std::move(itr->second);
llarp::LogInfo(lookup->name, " timed out txid=", lookup->txid);
lookup->HandleResponse(empty);
itr = m_PendingLookups.erase(itr);
}
else
++itr;
}
}
2018-08-14 21:17:18 +00:00
// expire pending router lookups
{
auto itr = m_PendingRouters.begin();
while(itr != m_PendingRouters.end())
{
if(itr->second.IsExpired(now))
2018-08-14 22:07:58 +00:00
{
llarp::LogInfo("lookup for ", itr->first, " timed out");
2018-08-14 21:17:18 +00:00
itr = m_PendingRouters.erase(itr);
2018-08-14 22:07:58 +00:00
}
2018-08-14 21:17:18 +00:00
else
++itr;
}
}
// prefetch addrs
for(const auto& addr : m_PrefetchAddrs)
{
if(!HasPathToService(addr))
{
2018-08-22 15:52:10 +00:00
if(!EnsurePathToService(
addr, [](Address addr, OutboundContext* ctx) {}, 10000))
{
llarp::LogWarn("failed to ensure path to ", addr);
}
}
}
2018-07-19 04:58:39 +00:00
// prefetch tags
2018-07-18 03:10:21 +00:00
for(const auto& tag : m_PrefetchTags)
{
auto itr = m_PrefetchedTags.find(tag);
if(itr == m_PrefetchedTags.end())
{
2018-08-14 21:17:18 +00:00
itr =
m_PrefetchedTags.insert(std::make_pair(tag, CachedTagResult(tag)))
.first;
2018-07-19 04:58:39 +00:00
}
for(const auto& introset : itr->second.result)
{
2018-08-10 03:51:38 +00:00
if(HasPendingPathToService(introset.A.Addr()))
continue;
2018-08-14 21:17:18 +00:00
if(!EnsurePathToService(introset.A.Addr(),
2018-08-22 15:52:10 +00:00
[](Address addr, OutboundContext* ctx) {},
2018-07-19 04:58:39 +00:00
10000))
{
llarp::LogWarn("failed to ensure path to ", introset.A.Addr(),
2018-08-10 03:51:38 +00:00
" for tag ", tag.ToString());
}
2018-07-18 03:10:21 +00:00
}
2018-07-18 22:50:05 +00:00
itr->second.Expire(now);
if(itr->second.ShouldRefresh(now))
2018-07-18 03:10:21 +00:00
{
auto path = PickRandomEstablishedPath();
if(path)
{
2018-08-14 21:17:18 +00:00
auto job = new TagLookupJob(this, &itr->second);
job->SendRequestViaPath(path, Router());
2018-07-18 03:10:21 +00:00
}
}
}
// tick remote sessions
{
auto itr = m_RemoteSessions.begin();
while(itr != m_RemoteSessions.end())
{
if(itr->second->Tick(now))
{
itr = m_RemoteSessions.erase(itr);
}
else
++itr;
}
}
2018-07-18 03:10:21 +00:00
}
uint64_t
Endpoint::GenTXID()
{
2018-07-20 04:50:28 +00:00
uint64_t txid = llarp_randint();
2018-07-18 03:10:21 +00:00
while(m_PendingLookups.find(txid) != m_PendingLookups.end())
++txid;
return txid;
}
2018-07-16 03:32:13 +00:00
std::string
Endpoint::Name() const
{
return m_Name + ":" + m_Identity.pub.Name();
}
bool
Endpoint::HasPathToService(const Address& addr) const
{
return m_RemoteSessions.find(addr) != m_RemoteSessions.end();
}
2018-08-04 02:59:32 +00:00
void
Endpoint::PutLookup(IServiceLookup* lookup, uint64_t txid)
{
2018-08-18 15:34:06 +00:00
m_PendingLookups.insert(
std::make_pair(txid, std::unique_ptr< IServiceLookup >(lookup)));
2018-08-04 02:59:32 +00:00
}
bool
Endpoint::HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg)
{
auto crypto = &m_Router->crypto;
2018-07-18 03:10:21 +00:00
std::set< IntroSet > remote;
for(const auto& introset : msg->I)
{
2018-07-18 22:50:05 +00:00
if(!introset.VerifySignature(crypto))
{
2018-07-18 22:50:05 +00:00
llarp::LogInfo("invalid introset signature for ", introset,
" on endpoint ", Name());
2018-07-19 04:58:39 +00:00
if(m_Identity.pub == introset.A && m_CurrentPublishTX == msg->T)
{
IntroSetPublishFail();
}
2018-07-18 22:50:05 +00:00
return false;
}
2018-07-19 04:58:39 +00:00
if(m_Identity.pub == introset.A && m_CurrentPublishTX == msg->T)
2018-07-18 22:50:05 +00:00
{
llarp::LogInfo(
"got introset publish confirmation for hidden service endpoint ",
2018-07-16 03:32:13 +00:00
Name());
2018-07-17 06:17:13 +00:00
IntroSetPublished();
2018-07-18 03:10:21 +00:00
return true;
}
else
{
2018-07-18 03:10:21 +00:00
remote.insert(introset);
}
}
2018-07-18 03:10:21 +00:00
auto itr = m_PendingLookups.find(msg->T);
if(itr == m_PendingLookups.end())
{
llarp::LogWarn("invalid lookup response for hidden service endpoint ",
Name(), " txid=", msg->T);
2018-07-20 04:50:28 +00:00
return true;
2018-07-18 03:10:21 +00:00
}
2018-08-14 21:17:18 +00:00
std::unique_ptr< IServiceLookup > lookup = std::move(itr->second);
2018-07-18 03:10:21 +00:00
m_PendingLookups.erase(itr);
2018-08-14 21:17:18 +00:00
lookup->HandleResponse(remote);
return true;
}
2018-08-09 19:02:17 +00:00
void
Endpoint::PutSenderFor(const ConvoTag& tag, const ServiceInfo& info)
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
{
itr = m_Sessions.insert(std::make_pair(tag, Session{})).first;
}
itr->second.remote = info;
itr->second.lastUsed = llarp_time_now_ms();
}
bool
Endpoint::GetSenderFor(const ConvoTag& tag, ServiceInfo& si) const
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
return false;
si = itr->second.remote;
return true;
}
void
Endpoint::PutIntroFor(const ConvoTag& tag, const Introduction& intro)
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
{
itr = m_Sessions.insert(std::make_pair(tag, Session{})).first;
}
itr->second.intro = intro;
itr->second.lastUsed = llarp_time_now_ms();
}
bool
Endpoint::GetIntroFor(const ConvoTag& tag, Introduction& intro) const
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
return false;
intro = itr->second.intro;
return true;
}
bool
Endpoint::GetConvoTagsForService(const ServiceInfo& info,
std::set< ConvoTag >& tags) const
{
bool inserted = false;
auto itr = m_Sessions.begin();
while(itr != m_Sessions.end())
{
if(itr->second.remote == info)
{
inserted |= tags.insert(itr->first).second;
}
}
return inserted;
}
bool
Endpoint::GetCachedSessionKeyFor(const ConvoTag& tag,
const byte_t*& secret) const
2018-08-09 19:02:17 +00:00
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
return false;
secret = itr->second.sharedKey.data();
2018-08-09 19:02:17 +00:00
return true;
}
void
Endpoint::PutCachedSessionKeyFor(const ConvoTag& tag, const SharedSecret& k)
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
{
itr = m_Sessions.insert(std::make_pair(tag, Session{})).first;
}
itr->second.sharedKey = k;
itr->second.lastUsed = llarp_time_now_ms();
}
bool
Endpoint::Start()
{
auto crypto = &m_Router->crypto;
if(m_Keyfile.size())
{
if(!m_Identity.EnsureKeys(m_Keyfile, crypto))
return false;
}
else
{
m_Identity.RegenerateKeys(crypto);
}
2018-08-09 19:02:17 +00:00
if(!m_DataHandler)
{
m_DataHandler = this;
}
2018-08-16 14:34:15 +00:00
// this does network isolation
2018-08-09 19:02:17 +00:00
while(m_OnInit.size())
{
if(m_OnInit.front()())
m_OnInit.pop_front();
else
return false;
}
return true;
}
Endpoint::~Endpoint()
{
}
2018-07-18 03:10:21 +00:00
bool
Endpoint::CachedTagResult::HandleResponse(
2018-07-18 22:50:05 +00:00
const std::set< IntroSet >& introsets)
2018-07-18 03:10:21 +00:00
{
2018-07-19 04:58:39 +00:00
auto now = llarp_time_now_ms();
2018-07-18 22:50:05 +00:00
for(const auto& introset : introsets)
2018-07-19 04:58:39 +00:00
if(result.insert(introset).second)
lastModified = now;
llarp::LogInfo("Tag result for ", tag.ToString(), " got ",
introsets.size(), " results from lookup, have ",
result.size(), " cached last modified at ", lastModified,
" is ", now - lastModified, "ms old");
2018-07-18 03:10:21 +00:00
return true;
}
2018-07-18 22:50:05 +00:00
void
Endpoint::CachedTagResult::Expire(llarp_time_t now)
{
auto itr = result.begin();
while(itr != result.end())
{
if(itr->HasExpiredIntros(now))
{
2018-07-19 04:58:39 +00:00
llarp::LogInfo("Removing expired tag Entry ", itr->A.Name());
itr = result.erase(itr);
lastModified = now;
2018-07-18 22:50:05 +00:00
}
else
{
++itr;
}
}
}
2018-07-18 03:10:21 +00:00
llarp::routing::IMessage*
2018-08-14 21:17:18 +00:00
Endpoint::CachedTagResult::BuildRequestMessage(uint64_t txid)
2018-07-18 03:10:21 +00:00
{
llarp::routing::DHTMessage* msg = new llarp::routing::DHTMessage();
msg->M.emplace_back(new llarp::dht::FindIntroMessage(tag, txid));
2018-07-19 04:58:39 +00:00
lastRequest = llarp_time_now_ms();
2018-07-18 03:10:21 +00:00
return msg;
}
bool
Endpoint::PublishIntroSet(llarp_router* r)
{
2018-08-10 21:34:11 +00:00
auto path = GetEstablishedPathClosestTo(m_Identity.pub.Addr().ToRouter());
2018-07-18 03:10:21 +00:00
if(path)
{
2018-07-20 04:50:28 +00:00
m_CurrentPublishTX = llarp_randint();
2018-07-18 03:10:21 +00:00
llarp::routing::DHTMessage msg;
msg.M.emplace_back(new llarp::dht::PublishIntroMessage(
2018-08-04 02:59:32 +00:00
m_IntroSet, m_CurrentPublishTX, 4));
2018-07-18 03:10:21 +00:00
if(path->SendRoutingMessage(&msg, r))
{
m_LastPublishAttempt = llarp_time_now_ms();
llarp::LogInfo(Name(), " publishing introset");
return true;
}
}
2018-08-04 02:59:32 +00:00
llarp::LogWarn(Name(), " publish introset failed, no path");
return false;
2018-07-18 03:10:21 +00:00
}
void
Endpoint::IntroSetPublishFail()
{
llarp::LogWarn("failed to publish introset for ", Name());
m_CurrentPublishTX = 0;
}
bool
2018-07-18 22:50:05 +00:00
Endpoint::ShouldPublishDescriptors(llarp_time_t now) const
2018-07-18 03:10:21 +00:00
{
2018-07-18 22:50:05 +00:00
if(m_IntroSet.HasExpiredIntros(now))
2018-07-18 03:10:21 +00:00
return m_CurrentPublishTX == 0
&& now - m_LastPublishAttempt >= INTROSET_PUBLISH_RETRY_INTERVAL;
return m_CurrentPublishTX == 0
&& now - m_LastPublish >= INTROSET_PUBLISH_INTERVAL;
}
void
Endpoint::IntroSetPublished()
{
m_CurrentPublishTX = 0;
m_LastPublish = llarp_time_now_ms();
llarp::LogInfo(Name(), " IntroSet publish confirmed");
}
struct HiddenServiceAddressLookup : public IServiceLookup
{
2018-08-14 21:17:18 +00:00
~HiddenServiceAddressLookup()
{
}
2018-07-22 23:14:29 +00:00
Address remote;
2018-08-10 21:34:11 +00:00
typedef std::function< bool(const IntroSet*) > HandlerFunc;
HandlerFunc handle;
2018-08-04 02:59:32 +00:00
2018-08-10 21:34:11 +00:00
HiddenServiceAddressLookup(Endpoint* p, HandlerFunc h,
const Address& addr, uint64_t tx)
2018-08-14 21:17:18 +00:00
: IServiceLookup(p, tx, "HSLookup"), remote(addr), handle(h)
{
}
bool
HandleResponse(const std::set< IntroSet >& results)
{
2018-08-10 03:51:38 +00:00
llarp::LogInfo("found ", results.size(), " for ", remote.ToString());
2018-07-22 23:14:29 +00:00
if(results.size() == 1)
{
llarp::LogInfo("hidden service lookup for ", remote.ToString(),
" success");
2018-08-10 21:34:11 +00:00
handle(&*results.begin());
}
else
{
llarp::LogInfo("no response in hidden service lookup for ",
remote.ToString());
2018-08-10 21:34:11 +00:00
handle(nullptr);
}
2018-08-14 21:17:18 +00:00
return false;
}
2018-07-22 23:14:29 +00:00
llarp::routing::IMessage*
BuildRequestMessage()
{
llarp::routing::DHTMessage* msg = new llarp::routing::DHTMessage();
msg->M.emplace_back(new llarp::dht::FindIntroMessage(txid, remote, 5));
2018-08-10 21:34:11 +00:00
llarp::LogInfo("build request for ", remote);
2018-07-22 23:14:29 +00:00
return msg;
}
};
2018-08-09 19:02:17 +00:00
bool
2018-08-18 14:01:21 +00:00
Endpoint::DoNetworkIsolation(bool failed)
2018-08-09 19:02:17 +00:00
{
2018-08-18 14:01:21 +00:00
if(failed)
return IsolationFailed();
llarp_ev_loop_alloc(&m_IsolatedNetLoop);
return SetupNetworking();
}
void
Endpoint::RunIsolatedMainLoop(void* user)
{
Endpoint* self = static_cast< Endpoint* >(user);
llarp_ev_loop_run_single_process(self->m_IsolatedNetLoop,
self->m_IsolatedWorker,
self->m_IsolatedLogic);
2018-08-09 19:02:17 +00:00
}
2018-07-22 23:14:29 +00:00
void
Endpoint::PutNewOutboundContext(const llarp::service::IntroSet& introset)
{
Address addr;
2018-08-10 21:34:11 +00:00
introset.A.CalculateAddress(addr.data());
2018-07-22 23:14:29 +00:00
// only add new session if it's not there
if(m_RemoteSessions.find(addr) == m_RemoteSessions.end())
{
OutboundContext* ctx = new OutboundContext(introset, this);
2018-08-23 18:02:02 +00:00
m_RemoteSessions.insert(
std::make_pair(addr, std::unique_ptr< OutboundContext >(ctx)));
2018-07-22 23:14:29 +00:00
llarp::LogInfo("Created New outbound context for ", addr.ToString());
}
// inform pending
auto itr = m_PendingServiceLookups.find(addr);
if(itr != m_PendingServiceLookups.end())
{
2018-08-14 21:17:18 +00:00
auto f = itr->second;
2018-07-22 23:14:29 +00:00
m_PendingServiceLookups.erase(itr);
2018-08-22 15:52:10 +00:00
f(itr->first, m_RemoteSessions.at(addr).get());
2018-07-22 23:14:29 +00:00
}
}
2018-08-10 21:34:11 +00:00
bool
Endpoint::HandleGotRouterMessage(const llarp::dht::GotRouterMessage* msg)
{
bool success = false;
if(msg->R.size() == 1)
{
auto itr = m_PendingRouters.find(msg->R[0].pubkey);
if(itr == m_PendingRouters.end())
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->logic = nullptr;
job->hook = nullptr;
2018-08-30 18:48:43 +00:00
job->rc = msg->R[0];
2018-08-10 21:34:11 +00:00
llarp_nodedb_async_verify(job);
return true;
}
return success;
}
void
Endpoint::EnsureRouterIsKnown(const RouterID& router)
{
2018-08-14 22:07:58 +00:00
if(router.IsZero())
return;
2018-08-30 18:48:43 +00:00
RouterContact rc;
if(!llarp_nodedb_get_rc(m_Router->nodedb, router, rc))
2018-08-10 21:34:11 +00:00
{
if(m_PendingRouters.find(router) == m_PendingRouters.end())
{
auto path = GetEstablishedPathClosestTo(router);
routing::DHTMessage msg;
auto txid = GenTXID();
msg.M.emplace_back(
2018-08-10 21:34:11 +00:00
new dht::FindRouterMessage({}, dht::Key_t(router), txid));
2018-08-14 21:17:18 +00:00
if(path && path->SendRoutingMessage(&msg, m_Router))
2018-08-10 21:34:11 +00:00
{
llarp::LogInfo(Name(), " looking up ", router);
2018-08-14 21:17:18 +00:00
m_PendingRouters.insert(
std::make_pair(router, RouterLookupJob(this)));
2018-08-10 21:34:11 +00:00
}
else
{
llarp::LogError("failed to send request for router lookup");
}
}
}
}
void
Endpoint::HandlePathBuilt(path::Path* p)
{
p->SetDataHandler(std::bind(&Endpoint::HandleHiddenServiceFrame, this,
std::placeholders::_1));
}
bool
Endpoint::HandleHiddenServiceFrame(const ProtocolFrame* frame)
{
2018-08-09 19:02:17 +00:00
return frame->AsyncDecryptAndVerify(EndpointLogic(), Crypto(), Worker(),
m_Identity, m_DataHandler);
}
void
Endpoint::OutboundContext::HandlePathBuilt(path::Path* p)
{
p->SetDataHandler(
std::bind(&Endpoint::OutboundContext::HandleHiddenServiceFrame, this,
std::placeholders::_1));
}
bool
Endpoint::OutboundContext::HandleHiddenServiceFrame(
const ProtocolFrame* frame)
{
return m_Parent->HandleHiddenServiceFrame(frame);
}
2018-08-10 21:34:11 +00:00
bool
Endpoint::OnOutboundLookup(const IntroSet* introset)
{
if(!introset)
return false;
PutNewOutboundContext(*introset);
return true;
}
2018-07-19 04:58:39 +00:00
bool
Endpoint::EnsurePathToService(const Address& remote, PathEnsureHook hook,
llarp_time_t timeoutMS)
{
2018-08-10 21:34:11 +00:00
auto path = GetEstablishedPathClosestTo(remote.ToRouter());
if(!path)
{
llarp::LogWarn("No outbound path for lookup yet");
return false;
}
llarp::LogInfo(Name(), " Ensure Path to ", remote.ToString());
2018-07-22 23:14:29 +00:00
{
auto itr = m_RemoteSessions.find(remote);
if(itr != m_RemoteSessions.end())
{
2018-08-22 15:52:10 +00:00
hook(itr->first, itr->second.get());
2018-07-22 23:14:29 +00:00
return true;
}
}
auto itr = m_PendingServiceLookups.find(remote);
if(itr != m_PendingServiceLookups.end())
{
// duplicate
llarp::LogWarn("duplicate pending service lookup to ",
remote.ToString());
2018-07-22 23:14:29 +00:00
return false;
}
2018-07-22 23:14:29 +00:00
m_PendingServiceLookups.insert(std::make_pair(remote, hook));
2018-08-10 21:34:11 +00:00
HiddenServiceAddressLookup* job = new HiddenServiceAddressLookup(
this,
std::bind(&Endpoint::OnOutboundLookup, this, std::placeholders::_1),
remote, GenTXID());
2018-08-10 21:34:11 +00:00
if(job->SendRequestViaPath(path, Router()))
return true;
llarp::LogError("send via path failed");
return false;
2018-07-19 04:58:39 +00:00
}
Endpoint::OutboundContext::OutboundContext(const IntroSet& intro,
Endpoint* parent)
2018-08-30 18:48:43 +00:00
: path::Builder(parent->m_Router, parent->m_Router->dht, 2, 4)
, currentIntroSet(intro)
2018-07-12 18:21:44 +00:00
, m_Parent(parent)
2018-07-12 18:21:44 +00:00
{
2018-07-22 23:14:29 +00:00
selectedIntro.Clear();
ShiftIntroduction();
2018-07-12 18:21:44 +00:00
}
Endpoint::OutboundContext::~OutboundContext()
{
}
2018-08-10 21:34:11 +00:00
bool
Endpoint::OutboundContext::OnIntroSetUpdate(const IntroSet* i)
2018-07-22 23:14:29 +00:00
{
2018-08-10 21:34:11 +00:00
if(i && i->IsNewerThan(currentIntroSet))
2018-07-22 23:14:29 +00:00
{
2018-08-10 21:34:11 +00:00
currentIntroSet = *i;
2018-07-22 23:14:29 +00:00
}
2018-08-10 21:34:11 +00:00
return true;
2018-07-22 23:14:29 +00:00
}
2018-08-22 15:52:10 +00:00
bool
Endpoint::SendToOrQueue(const Address& remote, llarp_buffer_t data,
ProtocolType t)
{
if(HasPathToService(remote))
{
m_RemoteSessions[remote]->AsyncEncryptAndSendTo(data, t);
return true;
}
auto itr = m_PendingTraffic.find(remote);
if(itr == m_PendingTraffic.end())
{
m_PendingTraffic.insert(std::make_pair(remote, PendingBufferQueue()));
EnsurePathToService(remote,
[&](Address addr, OutboundContext* ctx) {
if(ctx)
{
auto itr = m_PendingTraffic.find(addr);
if(itr != m_PendingTraffic.end())
{
while(itr->second.size())
{
auto& front = itr->second.front();
ctx->AsyncEncryptAndSendTo(front.Buffer(),
front.protocol);
itr->second.pop();
}
}
}
m_PendingTraffic.erase(addr);
},
10000);
}
m_PendingTraffic[remote].emplace(data, t);
return true;
}
2018-08-10 21:34:11 +00:00
void
Endpoint::OutboundContext::ShiftIntroduction()
2018-07-12 18:21:44 +00:00
{
2018-08-10 21:34:11 +00:00
for(const auto& intro : currentIntroSet.I)
{
2018-08-10 21:34:11 +00:00
m_Parent->EnsureRouterIsKnown(selectedIntro.router);
if(intro.expiresAt > selectedIntro.expiresAt)
{
2018-08-10 21:34:11 +00:00
selectedIntro = intro;
}
}
2018-08-14 21:17:18 +00:00
ManualRebuild(2);
2018-07-12 18:21:44 +00:00
}
2018-07-19 04:58:39 +00:00
void
Endpoint::OutboundContext::AsyncEncryptAndSendTo(llarp_buffer_t data,
ProtocolType protocol)
{
2018-08-14 21:17:18 +00:00
auto path = GetPathByRouter(selectedIntro.router);
if(!path)
{
llarp::LogError("No Path to ", selectedIntro.router, " yet");
return;
}
2018-07-19 04:58:39 +00:00
if(sequenceNo)
{
2018-08-14 21:17:18 +00:00
EncryptAndSendTo(path, data, protocol);
2018-07-19 04:58:39 +00:00
}
else
{
2018-08-14 21:17:18 +00:00
AsyncGenIntro(path, data, protocol);
2018-07-19 04:58:39 +00:00
}
}
2018-07-22 23:14:29 +00:00
struct AsyncIntroGen
2018-07-19 04:58:39 +00:00
{
llarp_logic* logic;
llarp_crypto* crypto;
byte_t* sharedKey;
2018-08-09 19:02:17 +00:00
ServiceInfo remote;
const Identity& m_LocalIdentity;
2018-07-22 23:14:29 +00:00
ProtocolMessage msg;
ProtocolFrame frame;
2018-08-09 19:02:17 +00:00
Introduction intro;
2018-08-14 21:17:18 +00:00
const PQPubKey introPubKey;
2018-07-22 23:14:29 +00:00
std::function< void(ProtocolFrame&) > hook;
2018-08-09 19:02:17 +00:00
IDataHandler* handler;
2018-07-19 04:58:39 +00:00
2018-07-22 23:14:29 +00:00
AsyncIntroGen(llarp_logic* l, llarp_crypto* c, byte_t* key,
const ServiceInfo& r, const Identity& localident,
2018-08-14 21:17:18 +00:00
const PQPubKey& introsetPubKey, const Introduction& us,
IDataHandler* h)
2018-07-19 04:58:39 +00:00
: logic(l)
, crypto(c)
, sharedKey(key)
2018-08-09 19:02:17 +00:00
, remote(r)
2018-07-22 23:14:29 +00:00
, m_LocalIdentity(localident)
2018-08-09 19:02:17 +00:00
, intro(us)
2018-08-14 21:17:18 +00:00
, introPubKey(introsetPubKey)
2018-08-09 19:02:17 +00:00
, handler(h)
2018-07-19 04:58:39 +00:00
{
}
2018-07-22 23:14:29 +00:00
static void
Result(void* user)
{
AsyncIntroGen* self = static_cast< AsyncIntroGen* >(user);
2018-08-09 19:02:17 +00:00
// put values
self->handler->PutCachedSessionKeyFor(self->msg.tag, self->sharedKey);
self->handler->PutIntroFor(self->msg.tag, self->msg.introReply);
self->handler->PutSenderFor(self->msg.tag, self->remote);
2018-07-22 23:14:29 +00:00
self->hook(self->frame);
delete self;
}
2018-07-19 04:58:39 +00:00
static void
Work(void* user)
{
2018-07-22 23:14:29 +00:00
AsyncIntroGen* self = static_cast< AsyncIntroGen* >(user);
// derive ntru session key component
SharedSecret K;
self->crypto->pqe_encrypt(self->frame.C, K, self->introPubKey);
2018-07-22 23:14:29 +00:00
// randomize Nounce
self->frame.N.Randomize();
// compure post handshake session key
byte_t tmp[64];
// K
memcpy(tmp, K, 32);
// PKE (A, B, N)
2018-08-13 23:25:36 +00:00
if(!self->m_LocalIdentity.KeyExchange(self->crypto->dh_client, tmp + 32,
self->remote, self->frame.N))
llarp::LogError("failed to derive x25519 shared key component");
// H (K + PKE(A, B, N))
self->crypto->shorthash(self->sharedKey,
llarp::StackBuffer< decltype(tmp) >(tmp));
2018-08-09 19:02:17 +00:00
// randomize tag
self->msg.tag.Randomize();
// set sender
self->msg.sender = self->m_LocalIdentity.pub;
2018-08-09 19:02:17 +00:00
// set our introduction
self->msg.introReply = self->intro;
2018-07-22 23:14:29 +00:00
// encrypt and sign
if(self->frame.EncryptAndSign(self->crypto, self->msg, K,
self->m_LocalIdentity))
llarp_logic_queue_job(self->logic, {self, &Result});
else
llarp::LogError("failed to encrypt and sign");
2018-07-19 04:58:39 +00:00
}
};
void
2018-08-14 21:17:18 +00:00
Endpoint::OutboundContext::AsyncGenIntro(path::Path* p,
llarp_buffer_t payload,
ProtocolType t)
2018-07-19 04:58:39 +00:00
{
2018-08-09 19:02:17 +00:00
AsyncIntroGen* ex = new AsyncIntroGen(
m_Parent->RouterLogic(), m_Parent->Crypto(), sharedKey,
2018-08-14 21:17:18 +00:00
currentIntroSet.A, m_Parent->GetIdentity(), currentIntroSet.K,
selectedIntro, m_Parent->m_DataHandler);
2018-07-22 23:14:29 +00:00
ex->hook = std::bind(&Endpoint::OutboundContext::Send, this,
std::placeholders::_1);
ex->msg.PutBuffer(payload);
2018-08-14 21:17:18 +00:00
ex->msg.introReply = p->intro;
2018-07-19 04:58:39 +00:00
llarp_threadpool_queue_job(m_Parent->Worker(),
2018-07-22 23:14:29 +00:00
{ex, &AsyncIntroGen::Work});
2018-07-19 04:58:39 +00:00
}
void
2018-07-22 23:14:29 +00:00
Endpoint::OutboundContext::Send(ProtocolFrame& msg)
2018-07-19 04:58:39 +00:00
{
2018-07-22 23:14:29 +00:00
// in this context we assume the message contents are encrypted
auto now = llarp_time_now_ms();
if(currentIntroSet.HasExpiredIntros(now))
{
UpdateIntroSet();
}
if(selectedIntro.expiresAt <= now || now - selectedIntro.expiresAt > 1000)
{
ShiftIntroduction();
}
2018-08-14 21:17:18 +00:00
// XXX: this may be a different path that that was put into the protocol
// message inside the protocol frame
2018-07-22 23:14:29 +00:00
auto path = GetPathByRouter(selectedIntro.router);
if(path)
{
2018-08-12 17:22:29 +00:00
routing::PathTransferMessage transfer(msg, selectedIntro.pathID);
2018-08-14 21:17:18 +00:00
llarp::LogDebug("sending frame via ", path->Upstream(), " to ",
path->Endpoint(), " for ", Name());
if(!path->SendRoutingMessage(&transfer, m_Parent->Router()))
llarp::LogError("Failed to send frame on path");
2018-07-22 23:14:29 +00:00
}
else
{
llarp::LogWarn("No path to ", selectedIntro.router);
}
}
2018-08-04 02:59:32 +00:00
std::string
Endpoint::OutboundContext::Name() const
{
return "OBContext:" + m_Parent->Name() + "-"
+ currentIntroSet.A.Addr().ToString();
}
void
Endpoint::OutboundContext::UpdateIntroSet()
{
2018-08-10 21:34:11 +00:00
auto addr = currentIntroSet.A.Addr();
auto path = m_Parent->GetEstablishedPathClosestTo(addr.ToRouter());
if(path)
{
2018-08-10 21:34:11 +00:00
HiddenServiceAddressLookup* job = new HiddenServiceAddressLookup(
m_Parent,
std::bind(&Endpoint::OutboundContext::OnIntroSetUpdate, this,
std::placeholders::_1),
addr, m_Parent->GenTXID());
if(!job->SendRequestViaPath(path, m_Parent->Router()))
llarp::LogError("send via path failed");
}
else
{
llarp::LogWarn(
"Cannot update introset no path for outbound session to ",
currentIntroSet.A.Addr().ToString());
}
}
bool
Endpoint::OutboundContext::Tick(llarp_time_t now)
{
2018-08-09 19:02:17 +00:00
if(selectedIntro.expiresAt >= now
|| selectedIntro.expiresAt - now < 30000)
{
UpdateIntroSet();
}
2018-08-14 21:17:18 +00:00
m_Parent->EnsureRouterIsKnown(selectedIntro.router);
// TODO: check for expiration of outbound context
return false;
2018-07-19 04:58:39 +00:00
}
bool
2018-08-30 18:48:43 +00:00
Endpoint::OutboundContext::SelectHop(llarp_nodedb* db,
const RouterContact& prev,
RouterContact& cur, size_t hop)
{
2018-08-12 17:22:29 +00:00
if(hop == numHops - 1)
{
2018-08-30 18:48:43 +00:00
if(llarp_nodedb_get_rc(db, selectedIntro.router, cur))
{
return true;
}
else
{
// we don't have it?
llarp::LogError(
2018-08-09 19:02:17 +00:00
"cannot build aligned path, don't have router for "
"introduction ",
selectedIntro);
2018-08-12 17:22:29 +00:00
m_Parent->EnsureRouterIsKnown(selectedIntro.router);
return false;
}
}
else
2018-08-30 18:48:43 +00:00
return path::Builder::SelectHop(db, prev, cur, hop);
}
2018-08-09 19:02:17 +00:00
uint64_t
Endpoint::GetSeqNoForConvo(const ConvoTag& tag)
{
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
return 0;
return ++(itr->second.seqno);
}
2018-07-19 04:58:39 +00:00
void
2018-08-14 21:17:18 +00:00
Endpoint::OutboundContext::EncryptAndSendTo(path::Path* p,
llarp_buffer_t payload,
ProtocolType t)
2018-07-19 04:58:39 +00:00
{
2018-08-09 19:02:17 +00:00
auto path = GetPathByRouter(selectedIntro.router);
if(path)
{
std::set< ConvoTag > tags;
if(!m_Parent->m_DataHandler->GetConvoTagsForService(currentIntroSet.A,
tags))
{
llarp::LogError("no open converstations with remote endpoint?");
return;
}
auto crypto = m_Parent->Crypto();
const byte_t* shared = nullptr;
2018-08-12 17:22:29 +00:00
routing::PathTransferMessage msg;
ProtocolFrame& f = msg.T;
2018-08-09 19:02:17 +00:00
f.N.Randomize();
f.T = *tags.begin();
f.S = m_Parent->GetSeqNoForConvo(f.T);
if(m_Parent->m_DataHandler->GetCachedSessionKeyFor(f.T, shared))
{
2018-08-12 17:22:29 +00:00
ProtocolMessage m;
2018-08-14 21:17:18 +00:00
m.proto = t;
m.introReply = path->intro;
2018-08-12 17:22:29 +00:00
m.sender = m_Parent->m_Identity.pub;
m.PutBuffer(payload);
2018-08-09 19:02:17 +00:00
if(!f.EncryptAndSign(crypto, m, shared, m_Parent->m_Identity))
2018-08-09 19:02:17 +00:00
{
llarp::LogError("failed to sign");
return;
}
}
else
{
llarp::LogError("No cached session key");
return;
}
msg.P = selectedIntro.pathID;
msg.Y.Randomize();
if(!path->SendRoutingMessage(&msg, m_Parent->Router()))
{
llarp::LogWarn("Failed to send routing message for data");
}
}
else
{
llarp::LogError("no outbound path for sending message");
}
2018-07-19 04:58:39 +00:00
}
llarp_logic*
2018-08-09 19:02:17 +00:00
Endpoint::RouterLogic()
2018-07-19 04:58:39 +00:00
{
return m_Router->logic;
}
2018-08-09 19:02:17 +00:00
llarp_logic*
Endpoint::EndpointLogic()
{
return m_IsolatedLogic ? m_IsolatedLogic : m_Router->logic;
}
2018-07-19 04:58:39 +00:00
llarp_crypto*
Endpoint::Crypto()
{
return &m_Router->crypto;
}
llarp_threadpool*
Endpoint::Worker()
{
return m_Router->tp;
}
2018-07-12 18:21:44 +00:00
} // namespace service
2018-07-16 03:32:13 +00:00
} // namespace llarp