1
1
Fork 0
mirror of https://github.com/oxen-io/lokinet synced 2023-12-14 06:53:00 +01:00
lokinet/llarp/path/pathbuilder.cpp

498 lines
13 KiB
C++
Raw Normal View History

2019-01-11 02:19:36 +01:00
#include <path/pathbuilder.hpp>
#include <crypto/crypto.hpp>
#include <messages/relay_commit.hpp>
#include <nodedb.hpp>
2019-06-18 01:19:39 +02:00
#include <path/path_context.hpp>
#include <profiling.hpp>
#include <router/abstractrouter.hpp>
#include <util/buffer.hpp>
2019-09-01 15:26:16 +02:00
#include <util/thread/logic.hpp>
#include <tooling/path_event.hpp>
2018-06-19 00:03:50 +02:00
2018-10-09 14:06:30 +02:00
#include <functional>
2018-06-19 00:03:50 +02:00
namespace llarp
{
struct AsyncPathKeyExchangeContext : std::enable_shared_from_this<AsyncPathKeyExchangeContext>
2018-06-21 14:55:02 +02:00
{
using WorkFunc_t = std::function<void(void)>;
using WorkerFunc_t = std::function<void(WorkFunc_t)>;
using Path_t = path::Path_ptr;
using PathSet_t = path::PathSet_ptr;
PathSet_t pathset = nullptr;
Path_t path = nullptr;
using Handler = std::function<void(std::shared_ptr<AsyncPathKeyExchangeContext>)>;
2018-10-09 14:06:30 +02:00
Handler result;
size_t idx = 0;
2019-07-09 15:47:24 +02:00
AbstractRouter* router = nullptr;
WorkerFunc_t work;
std::shared_ptr<Logic> logic;
LR_CommitMessage LRCM;
2018-06-21 14:55:02 +02:00
2019-06-20 18:22:29 +02:00
void
GenerateNextKey()
2018-06-21 14:55:02 +02:00
{
2018-06-21 16:20:14 +02:00
// current hop
auto& hop = path->hops[idx];
2019-06-20 18:22:29 +02:00
auto& frame = LRCM.frames[idx];
auto crypto = CryptoManager::instance();
2018-06-21 14:55:02 +02:00
// generate key
crypto->encryption_keygen(hop.commkey);
2018-06-21 14:55:02 +02:00
hop.nonce.Randomize();
// do key exchange
if (!crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, hop.nonce))
2018-06-21 14:55:02 +02:00
{
LogError(pathset->Name(), " Failed to generate shared key for path build");
2018-06-21 14:55:02 +02:00
return;
}
// generate nonceXOR valueself->hop->pathKey
crypto->shorthash(hop.nonceXOR, llarp_buffer_t(hop.shared));
2019-06-20 18:22:29 +02:00
++idx;
2018-06-21 16:20:14 +02:00
2019-06-20 18:22:29 +02:00
bool isFarthestHop = idx == path->hops.size();
2018-06-21 16:20:14 +02:00
LR_CommitRecord record;
if (isFarthestHop)
2018-06-21 14:55:02 +02:00
{
hop.upstream = hop.rc.pubkey;
2018-06-21 14:55:02 +02:00
}
else
{
hop.upstream = path->hops[idx].rc.pubkey;
record.nextRC = std::make_unique<RouterContact>(path->hops[idx].rc);
2018-06-21 14:55:02 +02:00
}
2018-06-21 17:46:35 +02:00
// build record
record.lifetime = path::default_lifetime;
record.version = LLARP_PROTO_VERSION;
record.txid = hop.txID;
record.rxid = hop.rxID;
2018-06-21 17:46:35 +02:00
record.tunnelNonce = hop.nonce;
record.nextHop = hop.upstream;
record.commkey = seckey_topublic(hop.commkey);
2018-06-21 17:46:35 +02:00
2019-02-19 16:06:39 +01:00
llarp_buffer_t buf(frame.data(), frame.size());
buf.cur = buf.base + EncryptedFrameOverheadSize;
2018-06-21 17:46:35 +02:00
// encode record
if (!record.BEncode(&buf))
2018-06-21 14:55:02 +02:00
{
// failed to encode?
2019-06-20 18:22:29 +02:00
LogError(pathset->Name(), " Failed to generate Commit Record");
2019-02-19 16:06:39 +01:00
DumpBuffer(buf);
2018-06-21 14:55:02 +02:00
return;
}
// use ephemeral keypair for frame
2018-06-21 14:55:02 +02:00
SecretKey framekey;
crypto->encryption_keygen(framekey);
if (!frame.EncryptInPlace(framekey, hop.rc.enckey))
2018-06-21 14:55:02 +02:00
{
2019-06-20 18:22:29 +02:00
LogError(pathset->Name(), " Failed to encrypt LRCR");
2018-06-21 14:55:02 +02:00
return;
}
if (isFarthestHop)
2018-06-21 14:55:02 +02:00
{
2018-06-21 16:20:14 +02:00
// farthest hop
2019-05-15 16:55:01 +02:00
// TODO: encrypt junk frames because our public keys are not eligator
LogicCall(logic, std::bind(result, shared_from_this()));
2018-06-21 14:55:02 +02:00
}
else
{
2018-06-21 16:20:14 +02:00
// next hop
work(std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, shared_from_this()));
2018-06-21 14:55:02 +02:00
}
}
/// Generate all keys asynchronously and call handler when done
2018-06-21 14:55:02 +02:00
void
AsyncGenerateKeys(Path_t p, std::shared_ptr<Logic> l, WorkerFunc_t worker, Handler func)
2018-06-21 14:55:02 +02:00
{
path = p;
logic = l;
2018-06-21 14:55:02 +02:00
result = func;
work = worker;
2018-06-21 14:55:02 +02:00
for (size_t i = 0; i < path::max_len; ++i)
2018-06-21 14:55:02 +02:00
{
2019-04-26 01:21:19 +02:00
LRCM.frames[i].Randomize();
2018-06-21 14:55:02 +02:00
}
work(std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, shared_from_this()));
2018-06-21 14:55:02 +02:00
}
};
static void
PathBuilderKeysGenerated(std::shared_ptr<AsyncPathKeyExchangeContext> ctx)
2018-06-19 00:03:50 +02:00
{
if (!ctx->pathset->IsStopped())
2018-06-20 14:34:48 +02:00
{
ctx->router->NotifyRouterEvent<tooling::PathAttemptEvent>(ctx->router->pubkey(), ctx->path);
2020-03-01 01:26:23 +01:00
const RouterID remote = ctx->path->Upstream();
2019-07-29 17:10:20 +02:00
const ILinkMessage* msg = &ctx->LRCM;
auto sentHandler = [ctx](auto status) {
if (status == SendStatus::Success)
2020-02-06 18:12:39 +01:00
{
ctx->router->pathContext().AddOwnPath(ctx->pathset, ctx->path);
ctx->pathset->PathBuildStarted(std::move(ctx->path));
2020-02-06 18:12:39 +01:00
}
else
{
LogError(ctx->pathset->Name(), " failed to send LRCM to ", ctx->path->Upstream());
ctx->pathset->HandlePathBuildFailed(std::move(ctx->path));
2020-02-06 18:12:39 +01:00
}
ctx->pathset = nullptr;
2020-02-06 18:12:39 +01:00
};
if (ctx->router->SendToOrQueue(remote, msg, sentHandler))
2018-12-24 17:21:15 +01:00
{
// persist session with router until this path is done
2019-07-29 17:10:20 +02:00
ctx->router->PersistSessionUntil(remote, ctx->path->ExpireTime());
2018-12-24 17:21:15 +01:00
}
else
{
2020-02-06 18:12:39 +01:00
LogError(ctx->pathset->Name(), " failed to queue LRCM to ", remote);
sentHandler(SendStatus::NoLink);
}
2018-06-20 14:34:48 +02:00
}
2018-06-19 00:03:50 +02:00
}
2018-08-30 20:48:43 +02:00
namespace path
2018-06-19 00:03:50 +02:00
{
2019-06-20 18:22:29 +02:00
Builder::Builder(AbstractRouter* p_router, size_t pathNum, size_t hops)
2019-08-02 11:27:27 +02:00
: path::PathSet(pathNum), _run(true), m_router(p_router), numHops(hops)
2018-06-19 00:03:50 +02:00
{
CryptoManager::instance()->encryption_keygen(enckey);
2018-08-30 20:48:43 +02:00
}
2019-05-07 19:46:38 +02:00
void
Builder::ResetInternalState()
{
buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
lastBuild = 0s;
2019-05-07 19:46:38 +02:00
}
2019-11-05 17:58:53 +01:00
void Builder::Tick(llarp_time_t)
2019-04-23 18:13:22 +02:00
{
2019-11-05 17:58:53 +01:00
const auto now = llarp::time_now_ms();
2019-11-07 19:23:06 +01:00
ExpirePaths(now, m_router);
if (ShouldBuildMore(now))
2019-04-23 18:13:22 +02:00
BuildOne();
2019-11-05 17:58:53 +01:00
TickPaths(m_router);
if (m_BuildStats.attempts > 50)
2019-07-01 15:44:25 +02:00
{
if (m_BuildStats.SuccessRatio() <= BuildStats::MinGoodRatio && now - m_LastWarn > 5s)
{
LogWarn(Name(), " has a low path build success. ", m_BuildStats);
m_LastWarn = now;
}
2019-07-01 15:44:25 +02:00
}
2019-04-23 18:13:22 +02:00
}
2019-02-11 18:14:43 +01:00
util::StatusObject
Builder::ExtractStatus() const
2019-02-08 20:43:25 +01:00
{
2019-07-01 15:44:25 +02:00
util::StatusObject obj{{"buildStats", m_BuildStats.ExtractStatus()},
{"numHops", uint64_t(numHops)},
{"numPaths", uint64_t(numDesiredPaths)}};
std::transform(
m_Paths.begin(),
m_Paths.end(),
std::back_inserter(obj["paths"]),
[](const auto& item) -> util::StatusObject { return item.second->ExtractStatus(); });
2019-02-11 18:14:43 +01:00
return obj;
2019-02-08 20:43:25 +01:00
}
2018-08-30 20:48:43 +02:00
bool
Builder::SelectHop(
llarp_nodedb* db,
const std::set<RouterID>& exclude,
RouterContact& cur,
size_t hop,
PathRole roles)
2018-08-30 20:48:43 +02:00
{
2018-11-15 14:47:46 +01:00
(void)roles;
2019-04-05 16:58:22 +02:00
size_t tries = 10;
if (hop == 0)
{
if (m_router->NumberOfConnectedRouters() == 0)
{
return false;
}
bool got = false;
2019-08-02 11:27:27 +02:00
m_router->ForEachPeer(
2019-05-07 15:04:43 +02:00
[&](const ILinkSession* s, bool isOutbound) {
if (s && s->IsEstablished() && isOutbound && !got)
2019-05-07 15:04:43 +02:00
{
const RouterContact rc = s->GetRemoteRC();
2019-09-05 22:20:55 +02:00
#ifdef TESTNET
if (got || exclude.count(rc.pubkey))
2019-09-05 22:20:55 +02:00
#else
if (got || exclude.count(rc.pubkey) || m_router->IsBootstrapNode(rc.pubkey))
2019-09-05 22:20:55 +02:00
#endif
2019-05-07 15:04:43 +02:00
return;
cur = rc;
got = true;
}
2019-04-05 16:58:22 +02:00
},
true);
return got;
}
2019-06-20 18:22:29 +02:00
2018-10-04 19:51:45 +02:00
do
{
cur.Clear();
2018-10-04 19:51:45 +02:00
--tries;
std::set<RouterID> excluding = exclude;
if (db->select_random_hop_excluding(cur, excluding))
{
2019-05-08 16:18:04 +02:00
excluding.insert(cur.pubkey);
if (!m_router->routerProfiling().IsBadForPath(cur.pubkey))
return true;
}
} while (tries > 0);
2019-06-20 18:22:29 +02:00
2019-05-20 00:11:07 +02:00
return false;
2018-08-30 20:48:43 +02:00
}
bool
Builder::Stop()
{
2019-06-20 18:22:29 +02:00
_run = false;
return true;
}
2019-02-05 15:50:33 +01:00
bool
Builder::IsStopped() const
{
return !_run.load();
}
bool
Builder::ShouldRemove() const
{
2019-04-23 18:13:22 +02:00
return IsStopped();
}
const SecretKey&
2018-08-30 20:48:43 +02:00
Builder::GetTunnelEncryptionSecretKey() const
{
return enckey;
}
2018-06-19 00:03:50 +02:00
2018-12-27 13:00:28 +01:00
bool
Builder::BuildCooldownHit(llarp_time_t now) const
{
2020-03-01 16:58:08 +01:00
return now < lastBuild + buildIntervalLimit;
2018-12-27 13:00:28 +01:00
}
2018-08-30 20:48:43 +02:00
bool
2018-10-29 17:48:36 +01:00
Builder::ShouldBuildMore(llarp_time_t now) const
2018-08-30 20:48:43 +02:00
{
if (IsStopped())
2019-04-16 13:44:55 +02:00
return false;
if (BuildCooldownHit(now))
2019-11-05 17:58:53 +01:00
return false;
return PathSet::ShouldBuildMore(now);
2018-08-30 20:48:43 +02:00
}
2018-08-12 19:22:29 +02:00
2018-08-30 20:48:43 +02:00
void
2018-11-14 19:02:27 +01:00
Builder::BuildOne(PathRole roles)
2018-08-30 20:48:43 +02:00
{
std::vector<RouterContact> hops(numHops);
if (SelectHops(m_router->nodedb(), hops, roles))
2018-11-14 19:02:27 +01:00
Build(hops, roles);
}
bool Builder::UrgentBuild(llarp_time_t) const
{
return buildIntervalLimit > MIN_PATH_BUILD_INTERVAL * 4;
}
bool
Builder::DoUrgentBuildAlignedTo(const RouterID remote, std::vector<RouterContact>& hops)
{
const auto aligned = m_router->pathContext().FindOwnedPathsWithEndpoint(remote);
2019-06-20 18:22:29 +02:00
/// pick the lowest latency path that aligns to remote
/// note: peer exhaustion is made worse happen here
Path_ptr p;
llarp_time_t min = std::numeric_limits<llarp_time_t>::max();
for (const auto& path : aligned)
2019-06-20 18:22:29 +02:00
{
if (path->intro.latency < min && path->hops.size() == numHops)
2019-06-20 18:22:29 +02:00
{
p = path;
2019-06-20 18:22:29 +02:00
min = path->intro.latency;
}
}
if (p)
2019-06-20 18:22:29 +02:00
{
for (const auto& hop : p->hops)
2019-06-20 18:22:29 +02:00
{
if (hop.rc.pubkey.IsZero())
2019-06-20 18:22:29 +02:00
return false;
hops.emplace_back(hop.rc);
}
}
return true;
}
bool
Builder::DoBuildAlignedTo(const RouterID remote, std::vector<RouterContact>& hops)
2019-06-20 18:22:29 +02:00
{
std::set<RouterID> routers{remote};
2019-06-20 18:22:29 +02:00
hops.resize(numHops);
2019-08-02 11:27:27 +02:00
auto nodedb = m_router->nodedb();
for (size_t idx = 0; idx < hops.size(); idx++)
{
2019-06-20 18:22:29 +02:00
hops[idx].Clear();
if (idx == numHops - 1)
{
2019-06-20 18:22:29 +02:00
// last hop
if (!nodedb->Get(remote, hops[idx]))
{
2019-08-02 11:27:27 +02:00
m_router->LookupRouter(remote, nullptr);
2019-06-20 18:22:29 +02:00
return false;
}
}
2019-06-20 18:22:29 +02:00
else
{
if (!SelectHop(nodedb, routers, hops[idx], idx, path::ePathRoleAny))
2019-05-08 16:30:55 +02:00
{
2019-06-20 18:22:29 +02:00
return false;
2019-05-08 16:30:55 +02:00
}
}
if (hops[idx].pubkey.IsZero())
2019-06-20 18:22:29 +02:00
return false;
routers.insert(hops[idx].pubkey);
}
2019-06-20 18:22:29 +02:00
return true;
}
bool
Builder::BuildOneAlignedTo(const RouterID remote)
{
std::vector<RouterContact> hops;
2019-06-20 18:22:29 +02:00
/// if we really need this path build it "dangerously"
if (UrgentBuild(m_router->Now()))
{
if (!DoUrgentBuildAlignedTo(remote, hops))
2019-06-20 18:22:29 +02:00
{
return false;
}
}
2019-05-07 15:04:43 +02:00
if (hops.empty())
2019-06-20 18:22:29 +02:00
{
if (!DoBuildAlignedTo(remote, hops))
{
2019-06-20 18:22:29 +02:00
return false;
}
}
2019-05-07 15:04:43 +02:00
LogInfo(Name(), " building path to ", remote);
Build(hops);
return true;
}
bool
Builder::SelectHops(llarp_nodedb* nodedb, std::vector<RouterContact>& hops, PathRole roles)
{
std::set<RouterID> exclude;
for (size_t idx = 0; idx < hops.size(); ++idx)
2018-08-30 20:48:43 +02:00
{
2019-05-08 16:18:04 +02:00
hops[idx].Clear();
size_t tries = 32;
while (tries > 0 && !SelectHop(nodedb, exclude, hops[idx], idx, roles))
2019-06-20 18:22:29 +02:00
{
2019-05-08 16:01:31 +02:00
--tries;
2019-06-20 18:22:29 +02:00
}
if (tries == 0 || hops[idx].pubkey.IsZero())
2019-03-22 13:44:15 +01:00
{
2019-03-22 15:10:30 +01:00
LogWarn(Name(), " failed to select hop ", idx);
2019-03-22 13:44:15 +01:00
return false;
2018-08-30 20:48:43 +02:00
}
exclude.emplace(hops[idx].pubkey);
2018-08-30 20:48:43 +02:00
}
return true;
}
2018-10-29 17:48:36 +01:00
llarp_time_t
Builder::Now() const
{
2019-08-02 11:27:27 +02:00
return m_router->Now();
2018-10-29 17:48:36 +01:00
}
void
Builder::Build(const std::vector<RouterContact>& hops, PathRole roles)
{
if (IsStopped())
return;
2018-10-29 17:48:36 +01:00
lastBuild = Now();
2018-08-30 20:48:43 +02:00
// async generate keys
auto ctx = std::make_shared<AsyncPathKeyExchangeContext>();
ctx->router = m_router;
auto self = GetSelf();
2019-11-05 17:58:53 +01:00
ctx->pathset = self;
2020-02-20 23:20:17 +01:00
std::string path_shortName = "[path " + m_router->ShortName() + "-";
path_shortName = path_shortName + std::to_string(m_router->NextPathBuildNumber()) + "]";
auto path = std::make_shared<path::Path>(hops, self.get(), roles, std::move(path_shortName));
LogInfo(Name(), " build ", path->ShortName(), ": ", path->HopsString());
path->SetBuildResultHook([self](Path_ptr p) { self->HandlePathBuilt(p); });
ctx->AsyncGenerateKeys(
path,
m_router->logic(),
[r = m_router](auto func) { r->QueueWork(std::move(func)); },
&PathBuilderKeysGenerated);
2018-08-30 20:48:43 +02:00
}
2018-06-19 00:03:50 +02:00
void
Builder::HandlePathBuilt(Path_ptr p)
{
buildIntervalLimit = MIN_PATH_BUILD_INTERVAL;
2019-08-02 11:27:27 +02:00
m_router->routerProfiling().MarkPathSuccess(p.get());
LogInfo(p->Name(), " built latency=", p->intro.latency);
2019-07-01 15:44:25 +02:00
m_BuildStats.success++;
}
void
Builder::HandlePathBuildFailed(Path_ptr p)
{
2019-08-02 11:34:56 +02:00
m_router->routerProfiling().MarkPathFail(p.get());
PathSet::HandlePathBuildFailed(p);
DoPathBuildBackoff();
}
void
Builder::DoPathBuildBackoff()
{
static constexpr std::chrono::milliseconds MaxBuildInterval = 30s;
// linear backoff
buildIntervalLimit = std::min(MIN_PATH_BUILD_INTERVAL + buildIntervalLimit, MaxBuildInterval);
LogWarn(Name(), " build interval is now ", buildIntervalLimit);
}
void
Builder::HandlePathBuildTimeout(Path_ptr p)
{
m_router->routerProfiling().MarkPathTimeout(p.get());
PathSet::HandlePathBuildTimeout(p);
DoPathBuildBackoff();
}
2018-08-30 20:48:43 +02:00
void
2018-11-14 19:02:27 +01:00
Builder::ManualRebuild(size_t num, PathRole roles)
2018-08-30 20:48:43 +02:00
{
2019-03-22 15:10:30 +01:00
LogDebug(Name(), " manual rebuild ", num);
while (num--)
2018-11-14 19:02:27 +01:00
BuildOne(roles);
2018-08-30 20:48:43 +02:00
}
2018-06-19 00:03:50 +02:00
2018-08-30 20:48:43 +02:00
} // namespace path
} // namespace llarp