lokinet/llarp/path/pathbuilder.cpp

375 lines
9.8 KiB
C++
Raw Normal View History

2019-01-11 01:19:36 +00:00
#include <path/pathbuilder.hpp>
#include <messages/relay_commit.hpp>
#include <nodedb.hpp>
2019-01-11 01:19:36 +00:00
#include <path/path.hpp>
#include <profiling.hpp>
#include <router/abstractrouter.hpp>
#include <util/buffer.hpp>
#include <util/logic.hpp>
2018-06-18 22:03:50 +00:00
2018-10-09 12:06:30 +00:00
#include <functional>
2018-06-18 22:03:50 +00:00
namespace llarp
{
2018-06-21 12:55:02 +00:00
template < typename User >
struct AsyncPathKeyExchangeContext
{
typedef path::Path Path_t;
typedef path::Builder PathSet_t;
PathSet_t* pathset = nullptr;
Path_t* path = nullptr;
2018-10-09 12:06:30 +00:00
typedef std::function< void(AsyncPathKeyExchangeContext< User >*) > Handler;
User* user = nullptr;
Handler result;
2018-06-21 12:55:02 +00:00
size_t idx = 0;
AbstractRouter* router = nullptr;
2018-06-21 12:55:02 +00:00
llarp_threadpool* worker = nullptr;
Logic* logic = nullptr;
Crypto* crypto = nullptr;
LR_CommitMessage LRCM;
2018-06-21 12:55:02 +00:00
2019-02-05 14:50:33 +00:00
~AsyncPathKeyExchangeContext()
{
if(path)
delete path;
}
2018-06-21 12:55:02 +00:00
static void
HandleDone(void* u)
{
AsyncPathKeyExchangeContext< User >* ctx =
static_cast< AsyncPathKeyExchangeContext< User >* >(u);
ctx->result(ctx);
2018-10-09 12:06:30 +00:00
delete ctx;
2018-06-21 12:55:02 +00:00
}
static void
GenerateNextKey(void* u)
{
AsyncPathKeyExchangeContext< User >* ctx =
static_cast< AsyncPathKeyExchangeContext< User >* >(u);
2018-06-21 14:20:14 +00:00
// current hop
2018-06-21 12:55:02 +00:00
auto& hop = ctx->path->hops[ctx->idx];
auto& frame = ctx->LRCM.frames[ctx->idx];
2018-06-21 12:55:02 +00:00
// generate key
ctx->crypto->encryption_keygen(hop.commkey);
hop.nonce.Randomize();
// do key exchange
2018-08-30 18:48:43 +00:00
if(!ctx->crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey,
hop.nonce))
2018-06-21 12:55:02 +00:00
{
2019-03-22 14:10:30 +00:00
LogError(ctx->pathset->Name(),
" Failed to generate shared key for path build");
delete ctx;
2018-06-21 12:55:02 +00:00
return;
}
// generate nonceXOR valueself->hop->pathKey
2019-02-03 00:31:10 +00:00
ctx->crypto->shorthash(hop.nonceXOR, llarp_buffer_t(hop.shared));
2018-06-21 12:55:02 +00:00
++ctx->idx;
2018-06-21 14:20:14 +00:00
bool isFarthestHop = ctx->idx == ctx->path->hops.size();
2018-06-21 14:20:14 +00:00
if(isFarthestHop)
2018-06-21 12:55:02 +00:00
{
hop.upstream = hop.rc.pubkey;
2018-06-21 12:55:02 +00:00
}
else
{
hop.upstream = ctx->path->hops[ctx->idx].rc.pubkey;
2018-06-21 12:55:02 +00:00
}
2018-06-21 15:46:35 +00:00
// build record
LR_CommitRecord record;
record.version = LLARP_PROTO_VERSION;
record.txid = hop.txID;
record.rxid = hop.rxID;
2018-06-21 15:46:35 +00:00
record.tunnelNonce = hop.nonce;
record.nextHop = hop.upstream;
record.commkey = seckey_topublic(hop.commkey);
2018-06-21 15:46:35 +00:00
2019-02-19 15:06:39 +00:00
llarp_buffer_t buf(frame.data(), frame.size());
buf.cur = buf.base + EncryptedFrameOverheadSize;
2018-06-21 15:46:35 +00:00
// encode record
2019-02-19 15:06:39 +00:00
if(!record.BEncode(&buf))
2018-06-21 12:55:02 +00:00
{
// failed to encode?
2019-03-22 14:10:30 +00:00
LogError(ctx->pathset->Name(), " Failed to generate Commit Record");
2019-02-19 15:06:39 +00:00
DumpBuffer(buf);
delete ctx;
2018-06-21 12:55:02 +00:00
return;
}
2019-02-19 15:06:39 +00:00
frame.Resize(buf.cur - buf.base);
// use ephemeral keypair for frame
2018-06-21 12:55:02 +00:00
SecretKey framekey;
ctx->crypto->encryption_keygen(framekey);
2018-08-30 18:48:43 +00:00
if(!frame.EncryptInPlace(framekey, hop.rc.enckey, ctx->crypto))
2018-06-21 12:55:02 +00:00
{
2019-03-22 14:10:30 +00:00
LogError(ctx->pathset->Name(), " Failed to encrypt LRCR");
delete ctx;
2018-06-21 12:55:02 +00:00
return;
}
2018-06-21 14:20:14 +00:00
if(isFarthestHop)
2018-06-21 12:55:02 +00:00
{
2018-06-21 14:20:14 +00:00
// farthest hop
2018-12-10 14:14:55 +00:00
ctx->logic->queue_job({ctx, &HandleDone});
2018-06-21 12:55:02 +00:00
}
else
{
2018-06-21 14:20:14 +00:00
// next hop
llarp_threadpool_queue_job(ctx->worker, {ctx, &GenerateNextKey});
2018-06-21 12:55:02 +00:00
}
}
AsyncPathKeyExchangeContext(Crypto* c) : crypto(c)
2018-06-21 12:55:02 +00:00
{
}
/// Generate all keys asynchronously and call handler when done
2018-06-21 12:55:02 +00:00
void
AsyncGenerateKeys(Path_t* p, Logic* l, llarp_threadpool* pool, User* u,
Handler func)
2018-06-21 12:55:02 +00:00
{
path = p;
logic = l;
user = u;
result = func;
worker = pool;
2019-04-05 14:58:22 +00:00
for(size_t idx = 0; idx < path::max_len; ++idx)
2018-06-21 12:55:02 +00:00
{
LRCM.frames[idx].Randomize();
2018-06-21 12:55:02 +00:00
}
llarp_threadpool_queue_job(pool, {this, &GenerateNextKey});
}
};
static void
PathBuilderKeysGenerated(AsyncPathKeyExchangeContext< path::Builder >* ctx)
2018-06-18 22:03:50 +00:00
{
2019-02-05 14:50:33 +00:00
if(!ctx->pathset->IsStopped())
2018-06-20 12:34:48 +00:00
{
2018-12-24 16:21:15 +00:00
RouterID remote = ctx->path->Upstream();
const ILinkMessage* msg = &ctx->LRCM;
if(ctx->router->SendToOrQueue(remote, msg))
{
// persist session with router until this path is done
ctx->router->PersistSessionUntil(remote, ctx->path->ExpireTime());
// add own path
ctx->router->pathContext().AddOwnPath(ctx->pathset, ctx->path);
2019-02-05 14:50:33 +00:00
ctx->path = nullptr;
2018-12-24 16:21:15 +00:00
}
else
2019-03-22 14:10:30 +00:00
LogError(ctx->pathset->Name(), " failed to send LRCM to ", remote);
2018-06-20 12:34:48 +00:00
}
// decrement keygen counter
ctx->pathset->keygens--;
2018-06-18 22:03:50 +00:00
}
2018-08-30 18:48:43 +00:00
namespace path
2018-06-18 22:03:50 +00:00
{
Builder::Builder(AbstractRouter* p_router, struct llarp_dht_context* p_dht,
2018-08-30 18:48:43 +00:00
size_t pathNum, size_t hops)
: path::PathSet(pathNum), router(p_router), dht(p_dht), numHops(hops)
2018-06-18 22:03:50 +00:00
{
p_router->pathContext().AddPathBuilder(this);
p_router->crypto()->encryption_keygen(enckey);
_run.store(true);
keygens.store(0);
2018-06-18 22:03:50 +00:00
}
2018-08-30 18:48:43 +00:00
Builder::~Builder()
{
router->pathContext().RemovePathBuilder(this);
2018-08-30 18:48:43 +00:00
}
2019-02-11 17:14:43 +00:00
util::StatusObject
Builder::ExtractStatus() const
2019-02-08 19:43:25 +00:00
{
2019-02-11 17:14:43 +00:00
util::StatusObject obj{{"keygens", uint64_t(keygens.load())},
{"numHops", uint64_t(numHops)},
{"numPaths", uint64_t(m_NumPaths)}};
std::vector< util::StatusObject > pathObjs;
std::transform(m_Paths.begin(), m_Paths.end(),
std::back_inserter(pathObjs),
[](const auto& item) -> util::StatusObject {
return item.second->ExtractStatus();
});
obj.Put("paths", pathObjs);
return obj;
2019-02-08 19:43:25 +00:00
}
2018-08-30 18:48:43 +00:00
bool
Builder::SelectHop(llarp_nodedb* db, const RouterContact& prev,
2018-11-14 18:02:27 +00:00
RouterContact& cur, size_t hop, PathRole roles)
2018-08-30 18:48:43 +00:00
{
2018-11-15 13:47:46 +00:00
(void)roles;
2019-04-05 14:58:22 +00:00
size_t tries = 10;
if(hop == 0)
{
if(router->NumberOfConnectedRouters() == 0)
return false;
bool got = false;
2019-04-05 14:58:22 +00:00
router->ForEachPeer(
[&](const ILinkSession* s, bool) {
2019-04-09 16:27:47 +00:00
const PubKey k(s->GetPubKey());
if(got || router->IsBootstrapNode(k)
|| router->routerProfiling().IsBad(k))
2019-04-05 14:58:22 +00:00
return;
cur = s->GetRemoteRC();
got = true;
},
true);
return got;
}
std::set< RouterID > exclude = {prev.pubkey};
2018-10-04 17:51:45 +00:00
do
{
cur.Clear();
2018-10-04 17:51:45 +00:00
--tries;
if(db->select_random_hop_excluding(cur, exclude))
{
if(!router->routerProfiling().IsBad(cur.pubkey))
return true;
exclude.insert(cur.pubkey);
}
} while(tries > 0);
return tries > 0;
2018-08-30 18:48:43 +00:00
}
bool
Builder::Stop()
{
_run.store(false);
return true;
}
2019-02-05 14:50:33 +00:00
bool
Builder::IsStopped() const
{
return !_run.load();
}
bool
Builder::ShouldRemove() const
{
2019-02-05 14:50:33 +00:00
if(!IsStopped())
return false;
return keygens.load() > 0;
}
const SecretKey&
2018-08-30 18:48:43 +00:00
Builder::GetTunnelEncryptionSecretKey() const
{
return enckey;
}
2018-06-18 22:03:50 +00:00
2018-12-27 12:00:28 +00:00
bool
Builder::BuildCooldownHit(llarp_time_t now) const
{
return now < lastBuild || now - lastBuild < buildIntervalLimit;
2018-12-27 12:00:28 +00:00
}
2018-08-30 18:48:43 +00:00
bool
2018-10-29 16:48:36 +00:00
Builder::ShouldBuildMore(llarp_time_t now) const
2018-08-30 18:48:43 +00:00
{
2019-03-07 22:53:36 +00:00
if(llarp::randint() % 3 >= 1)
return PathSet::ShouldBuildMore(now) && !BuildCooldownHit(now);
return false;
2018-08-30 18:48:43 +00:00
}
2018-08-12 17:22:29 +00:00
2018-08-30 18:48:43 +00:00
void
2018-11-14 18:02:27 +00:00
Builder::BuildOne(PathRole roles)
2018-08-30 18:48:43 +00:00
{
2018-08-31 14:41:04 +00:00
std::vector< RouterContact > hops;
if(SelectHops(router->nodedb(), hops, roles))
2018-11-14 18:02:27 +00:00
Build(hops, roles);
}
bool
Builder::SelectHops(llarp_nodedb* nodedb,
2018-11-14 18:02:27 +00:00
std::vector< RouterContact >& hops, PathRole roles)
{
2018-09-06 11:46:19 +00:00
hops.resize(numHops);
2018-08-30 18:48:43 +00:00
size_t idx = 0;
while(idx < numHops)
{
2019-03-22 12:44:15 +00:00
size_t tries = 4;
2018-08-30 18:48:43 +00:00
if(idx == 0)
{
2019-03-22 12:44:15 +00:00
while(tries > 0 && !SelectHop(nodedb, hops[0], hops[0], 0, roles))
--tries;
2018-08-30 18:48:43 +00:00
}
else
{
2019-03-22 12:44:15 +00:00
while(tries > 0
&& !SelectHop(nodedb, hops[idx - 1], hops[idx], idx, roles))
--tries;
}
if(tries == 0)
{
2019-03-22 14:10:30 +00:00
LogWarn(Name(), " failed to select hop ", idx);
2019-03-22 12:44:15 +00:00
return false;
2018-08-30 18:48:43 +00:00
}
++idx;
}
return true;
}
2018-10-29 16:48:36 +00:00
llarp_time_t
Builder::Now() const
{
return router->Now();
}
void
2018-11-14 18:02:27 +00:00
Builder::Build(const std::vector< RouterContact >& hops, PathRole roles)
{
2019-02-05 14:50:33 +00:00
if(IsStopped())
return;
2018-10-29 16:48:36 +00:00
lastBuild = Now();
2018-08-30 18:48:43 +00:00
// async generate keys
AsyncPathKeyExchangeContext< Builder >* ctx =
new AsyncPathKeyExchangeContext< Builder >(router->crypto());
2018-12-07 13:38:49 +00:00
ctx->router = router;
2018-08-30 18:48:43 +00:00
ctx->pathset = this;
auto path = new path::Path(hops, this, roles);
2019-03-22 14:10:30 +00:00
path->SetBuildResultHook([this](Path* p) { this->HandlePathBuilt(p); });
++keygens;
ctx->AsyncGenerateKeys(path, router->logic(), router->threadpool(), this,
&PathBuilderKeysGenerated);
2018-08-30 18:48:43 +00:00
}
2018-06-18 22:03:50 +00:00
void
Builder::HandlePathBuilt(Path* p)
{
buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
2019-03-04 17:03:18 +00:00
router->routerProfiling().MarkPathSuccess(p);
2019-03-22 14:10:30 +00:00
LogInfo(p->Name(), " built latency=", p->intro.latency);
}
void
Builder::HandlePathBuildTimeout(Path* p)
{
// linear backoff
2019-01-07 17:28:59 +00:00
static constexpr llarp_time_t MaxBuildInterval = 30 * 1000;
buildIntervalLimit =
std::min(1000 + buildIntervalLimit, MaxBuildInterval);
2019-03-31 15:09:59 +00:00
router->routerProfiling().MarkPathFail(p);
PathSet::HandlePathBuildTimeout(p);
}
2018-08-30 18:48:43 +00:00
void
2018-11-14 18:02:27 +00:00
Builder::ManualRebuild(size_t num, PathRole roles)
2018-08-30 18:48:43 +00:00
{
2019-03-22 14:10:30 +00:00
LogDebug(Name(), " manual rebuild ", num);
2018-08-30 18:48:43 +00:00
while(num--)
2018-11-14 18:02:27 +00:00
BuildOne(roles);
2018-08-30 18:48:43 +00:00
}
2018-06-18 22:03:50 +00:00
2018-08-30 18:48:43 +00:00
} // namespace path
} // namespace llarp