lokinet/llarp/router.cpp

1268 lines
30 KiB
C++
Raw Normal View History

2018-08-02 23:03:23 +00:00
#include "router.hpp"
2018-04-05 14:23:14 +00:00
#include <llarp/proto.h>
2018-08-10 21:34:11 +00:00
#include <llarp/iwp.hpp>
#include <llarp/link_message.hpp>
2018-09-04 12:55:20 +00:00
#include <llarp/link/utp.hpp>
2018-10-19 11:41:36 +00:00
#include <llarp/rpc.hpp>
2018-05-21 13:17:07 +00:00
#include "buffer.hpp"
#include "encode.hpp"
#include "llarp/net.hpp"
#include "logger.hpp"
#include "str.hpp"
2017-11-28 14:05:31 +00:00
2018-05-20 17:45:47 +00:00
#include <fstream>
2018-10-09 01:38:25 +00:00
#include <cstdlib>
2018-05-20 17:45:47 +00:00
namespace llarp
{
void
router_iter_config(llarp_config_iterator *iter, const char *section,
const char *key, const char *val);
2018-05-30 20:56:47 +00:00
struct async_verify_context
{
llarp_router *router;
2018-09-06 11:46:19 +00:00
TryConnectJob *establish_job;
2018-05-30 20:56:47 +00:00
};
2018-02-01 13:21:00 +00:00
} // namespace llarp
2017-11-28 14:05:31 +00:00
2018-09-06 11:46:19 +00:00
struct TryConnectJob
{
2018-09-06 11:46:19 +00:00
llarp::RouterContact rc;
llarp::ILinkLayer *link;
llarp_router *router;
uint16_t triesLeft;
TryConnectJob(const llarp::RouterContact &remote, llarp::ILinkLayer *l,
uint16_t tries, llarp_router *r)
2018-09-06 11:46:19 +00:00
: rc(remote), link(l), router(r), triesLeft(tries)
{
}
void
Failed()
{
link->CloseSessionTo(rc.pubkey);
}
void
Success()
{
}
void
AttemptTimedout()
{
router->routerProfiling.MarkTimeout(rc.pubkey);
if(ShouldRetry())
{
Attempt();
return;
}
if(router->routerProfiling.IsBad(rc.pubkey))
llarp_nodedb_del_rc(router->nodedb, rc.pubkey);
// delete this
2018-09-06 20:31:58 +00:00
router->pendingEstablishJobs.erase(rc.pubkey);
}
void
Attempt()
{
--triesLeft;
link->TryEstablishTo(rc);
}
bool
ShouldRetry() const
{
return triesLeft > 0;
}
};
static void
on_try_connecting(void *u)
{
2018-09-06 11:46:19 +00:00
TryConnectJob *j = static_cast< TryConnectJob * >(u);
j->Attempt();
}
2018-08-30 18:48:43 +00:00
bool
llarp_router_try_connect(struct llarp_router *router,
const llarp::RouterContact &remote,
uint16_t numretries)
{
// do we already have a pending job for this remote?
if(router->HasPendingConnectJob(remote.pubkey))
{
llarp::LogDebug("We have pending connect jobs to ", remote.pubkey);
return false;
}
2018-09-06 11:46:19 +00:00
auto link = router->outboundLink.get();
auto itr = router->pendingEstablishJobs.insert(std::make_pair(
remote.pubkey,
std::make_unique< TryConnectJob >(remote, link, numretries, router)));
TryConnectJob *job = itr.first->second.get();
// try establishing async
llarp_logic_queue_job(router->logic, {job, &on_try_connecting});
return true;
2018-08-30 18:48:43 +00:00
}
2018-09-04 19:15:06 +00:00
void
2018-09-06 13:16:24 +00:00
llarp_router::HandleLinkSessionEstablished(llarp::RouterContact rc)
2018-09-04 19:15:06 +00:00
{
2018-09-06 11:46:19 +00:00
async_verify_RC(rc);
2018-09-04 19:15:06 +00:00
}
2018-06-01 14:08:54 +00:00
llarp_router::llarp_router()
2018-06-13 16:32:34 +00:00
: ready(false)
, paths(this)
, dht(llarp_dht_context_new(this))
2018-06-26 16:23:43 +00:00
, inbound_link_msg_parser(this)
, hiddenServiceContext(this)
2018-06-10 14:05:48 +00:00
{
// set rational defaults
this->ip4addr.sin_family = AF_INET;
2018-06-29 12:15:15 +00:00
this->ip4addr.sin_port = htons(1090);
}
2018-01-29 14:27:24 +00:00
llarp_router::~llarp_router()
{
2018-06-01 14:08:54 +00:00
llarp_dht_context_free(dht);
}
2018-02-01 17:07:01 +00:00
bool
llarp_router::HandleRecvLinkMessageBuffer(llarp::ILinkSession *session,
llarp_buffer_t buf)
{
if(!session)
{
llarp::LogWarn("no link session");
return false;
}
2018-06-26 16:23:43 +00:00
return inbound_link_msg_parser.ProcessFrom(session, buf);
}
2018-08-14 21:17:18 +00:00
void
llarp_router::PersistSessionUntil(const llarp::RouterID &remote,
llarp_time_t until)
{
2018-08-22 16:19:51 +00:00
llarp::LogDebug("persist session to ", remote, " until ", until);
if(m_PersistingSessions.find(remote) == m_PersistingSessions.end())
m_PersistingSessions[remote] = until;
else
{
if(m_PersistingSessions[remote] < until)
m_PersistingSessions[remote] = until;
}
2018-08-14 21:17:18 +00:00
}
constexpr size_t MaxPendingSendQueueSize = 8;
bool
2018-06-01 14:08:54 +00:00
llarp_router::SendToOrQueue(const llarp::RouterID &remote,
2018-09-06 13:16:24 +00:00
const llarp::ILinkMessage *msg)
{
2018-08-31 19:46:25 +00:00
if(inboundLinks.size() == 0)
{
if(outboundLink->HasSessionTo(remote))
{
SendTo(remote, msg, outboundLink.get());
return true;
}
}
2018-08-31 19:46:25 +00:00
else
2018-06-20 12:34:48 +00:00
{
for(const auto &link : inboundLinks)
{
if(link->HasSessionTo(remote))
{
SendTo(remote, msg, link.get());
return true;
}
}
2018-06-20 12:34:48 +00:00
}
// no link available
2018-06-19 17:11:24 +00:00
// this will create an entry in the obmq if it's not already there
2018-08-29 20:40:26 +00:00
auto itr = outboundMessageQueue.find(remote);
if(itr == outboundMessageQueue.end())
2018-06-20 17:45:44 +00:00
{
2018-08-29 20:40:26 +00:00
outboundMessageQueue.insert(std::make_pair(remote, MessageQueue()));
2018-06-20 17:45:44 +00:00
}
// encode
llarp_buffer_t buf =
llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer);
if(!msg->BEncode(&buf))
return false;
// queue buffer
auto &q = outboundMessageQueue[remote];
2018-09-19 13:27:15 +00:00
if(q.size() < MaxPendingSendQueueSize)
{
buf.sz = buf.cur - buf.base;
q.emplace(buf.sz);
memcpy(q.back().data(), buf.base, buf.sz);
}
else
{
llarp::LogWarn("tried to queue a message to ", remote,
" but the queue is full so we drop it like it's hawt");
2018-10-07 15:29:36 +00:00
}
llarp::RouterContact remoteRC;
// we don't have an open session to that router right now
if(llarp_nodedb_get_rc(nodedb, remote, remoteRC))
{
// try connecting directly as the rc is loaded from disk
llarp_router_try_connect(this, remoteRC, 10);
return true;
2018-06-01 14:08:54 +00:00
}
2018-10-07 15:29:36 +00:00
// we don't have the RC locally so do a dht lookup
dht->impl.LookupRouter(remote,
std::bind(&llarp_router::HandleDHTLookupForSendTo,
this, remote, std::placeholders::_1));
return true;
}
2018-06-14 15:10:31 +00:00
void
2018-08-30 18:48:43 +00:00
llarp_router::HandleDHTLookupForSendTo(
llarp::RouterID remote, const std::vector< llarp::RouterContact > &results)
2018-06-14 15:10:31 +00:00
{
2018-08-30 18:48:43 +00:00
if(results.size())
2018-06-14 15:10:31 +00:00
{
2018-08-30 18:48:43 +00:00
llarp_nodedb_put_rc(nodedb, results[0]);
llarp_router_try_connect(this, results[0], 10);
2018-09-09 18:18:34 +00:00
async_verify_RC(results[0]);
2018-06-14 15:10:31 +00:00
}
else
{
2018-08-30 18:48:43 +00:00
DiscardOutboundFor(remote);
2018-06-13 12:58:51 +00:00
}
}
void
llarp_router::ForEachPeer(
std::function< void(const llarp::ILinkSession *, bool) > visit) const
{
outboundLink->ForEachSession(
[visit](const llarp::ILinkSession *peer) { visit(peer, true); });
for(const auto &link : inboundLinks)
{
link->ForEachSession(
[visit](const llarp::ILinkSession *peer) { visit(peer, false); });
}
}
void
llarp_router::try_connect(fs::path rcfile)
{
2018-08-30 18:48:43 +00:00
llarp::RouterContact remote;
if(!remote.Read(rcfile.string().c_str()))
{
llarp::LogError("failure to decode or verify of remote RC");
return;
}
2018-10-15 12:02:32 +00:00
if(remote.Verify(&crypto))
2018-05-16 18:13:18 +00:00
{
2018-07-13 09:28:50 +00:00
llarp::LogDebug("verified signature");
// store into filesystem
2018-08-30 18:48:43 +00:00
if(!llarp_nodedb_put_rc(nodedb, remote))
{
llarp::LogWarn("failed to store");
}
2018-08-30 18:48:43 +00:00
if(!llarp_router_try_connect(this, remote, 10))
{
// or error?
llarp::LogWarn("session already made");
}
2018-05-16 18:13:18 +00:00
}
2018-02-01 17:06:49 +00:00
else
2018-10-15 12:02:32 +00:00
llarp::LogError(rcfile, " contains invalid RC");
}
bool
llarp_router::EnsureIdentity()
2018-05-20 17:45:47 +00:00
{
2018-06-10 14:05:48 +00:00
if(!EnsureEncryptionKey())
return false;
return llarp_findOrCreateIdentity(&crypto, ident_keyfile.string().c_str(),
identity);
2018-05-20 17:45:47 +00:00
}
2018-06-10 14:05:48 +00:00
bool
llarp_router::EnsureEncryptionKey()
{
return llarp_findOrCreateEncryption(
2018-08-30 18:48:43 +00:00
&crypto, encryption_keyfile.string().c_str(), encryption);
2018-06-10 14:05:48 +00:00
}
void
llarp_router::AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link)
{
inboundLinks.push_back(std::move(link));
2018-04-05 14:23:14 +00:00
}
bool
llarp_router::Ready()
{
return outboundLink != nullptr;
}
2018-01-29 14:27:24 +00:00
bool
llarp_router::SaveRC()
2018-05-20 17:45:47 +00:00
{
llarp::LogDebug("verify RC signature");
2018-10-15 12:02:32 +00:00
if(!rc().Verify(&crypto))
2018-05-20 17:45:47 +00:00
{
rc().Dump< MAX_RC_SIZE >();
2018-10-15 12:02:32 +00:00
llarp::LogError("RC is invalid, not saving");
2018-05-20 17:45:47 +00:00
return false;
}
return rc().Write(our_rc_file.string().c_str());
2018-05-20 17:45:47 +00:00
}
void
llarp_router::Close()
{
2018-07-13 09:28:50 +00:00
llarp::LogInfo("Closing ", inboundLinks.size(), " server bindings");
for(const auto &link : inboundLinks)
{
link->Stop();
}
inboundLinks.clear();
2018-07-13 09:28:50 +00:00
llarp::LogInfo("Closing LokiNetwork client");
2018-08-18 14:01:21 +00:00
if(outboundLink)
{
outboundLink->Stop();
outboundLink.reset(nullptr);
2018-06-20 12:34:48 +00:00
}
2018-05-29 13:40:26 +00:00
}
void
2018-05-30 20:56:47 +00:00
llarp_router::on_verify_client_rc(llarp_async_verify_rc *job)
{
2018-05-30 20:56:47 +00:00
llarp::async_verify_context *ctx =
static_cast< llarp::async_verify_context * >(job->user);
2018-08-30 18:48:43 +00:00
ctx->router->pendingEstablishJobs.erase(job->rc.pubkey);
auto router = ctx->router;
llarp::PubKey pk(job->rc.pubkey);
router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk));
2018-05-30 20:56:47 +00:00
delete ctx;
}
void
llarp_router::on_verify_server_rc(llarp_async_verify_rc *job)
{
llarp::async_verify_context *ctx =
static_cast< llarp::async_verify_context * >(job->user);
auto router = ctx->router;
2018-06-14 17:35:12 +00:00
llarp::PubKey pk(job->rc.pubkey);
2018-05-30 20:56:47 +00:00
if(!job->valid)
{
llarp::LogWarn("invalid server RC");
2018-05-30 20:56:47 +00:00
if(ctx->establish_job)
{
// was an outbound attempt
ctx->establish_job->Failed();
2018-05-30 20:56:47 +00:00
}
2018-06-14 17:35:12 +00:00
router->DiscardOutboundFor(pk);
2018-05-30 20:56:47 +00:00
return;
}
2018-06-23 14:55:25 +00:00
// we're valid, which means it's already been committed to the nodedb
2018-05-30 20:56:47 +00:00
llarp::LogDebug("rc verified and saved to nodedb");
2018-09-06 11:46:19 +00:00
if(router->validRouters.count(pk))
{
router->validRouters.erase(pk);
}
2018-09-06 13:16:24 +00:00
llarp::RouterContact rc = job->rc;
router->validRouters.insert(std::make_pair(pk, rc));
2018-06-10 14:05:48 +00:00
// track valid router in dht
2018-09-06 13:16:24 +00:00
router->dht->impl.nodes->PutNode(rc);
2018-05-30 20:56:47 +00:00
// mark success in profile
router->routerProfiling.MarkSuccess(pk);
2018-05-30 20:56:47 +00:00
// this was an outbound establish job
2018-07-03 13:33:37 +00:00
if(ctx->establish_job)
2018-05-30 20:56:47 +00:00
{
ctx->establish_job->Success();
}
2018-09-06 20:31:58 +00:00
router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk));
2018-05-30 20:56:47 +00:00
}
2018-06-03 13:04:51 +00:00
void
llarp_router::handle_router_ticker(void *user, uint64_t orig, uint64_t left)
{
if(left)
return;
llarp_router *self = static_cast< llarp_router * >(user);
self->ticker_job_id = 0;
self->Tick();
self->ScheduleTicker(orig);
}
2018-05-30 20:56:47 +00:00
2018-10-07 15:29:36 +00:00
void
2018-08-14 21:17:18 +00:00
llarp_router::TryEstablishTo(const llarp::RouterID &remote)
{
2018-08-30 18:48:43 +00:00
llarp::RouterContact rc;
if(llarp_nodedb_get_rc(nodedb, remote, rc))
2018-08-14 21:17:18 +00:00
{
2018-08-30 18:48:43 +00:00
// try connecting async
2018-08-14 21:17:18 +00:00
llarp_router_try_connect(this, rc, 5);
}
2018-10-07 15:29:36 +00:00
else if(!routerProfiling.IsBad(remote))
2018-08-14 21:17:18 +00:00
{
if(dht->impl.HasRouterLookup(remote))
2018-10-07 15:29:36 +00:00
return;
llarp::LogInfo("looking up router ", remote);
2018-08-14 21:17:18 +00:00
// dht lookup as we don't know it
2018-08-30 18:48:43 +00:00
dht->impl.LookupRouter(
remote,
std::bind(&llarp_router::HandleDHTLookupForTryEstablishTo, this, remote,
2018-08-30 18:48:43 +00:00
std::placeholders::_1));
2018-08-14 21:17:18 +00:00
}
}
void
llarp_router::OnConnectTimeout(const llarp::RouterID &remote)
{
auto itr = pendingEstablishJobs.find(remote);
if(itr != pendingEstablishJobs.end())
{
itr->second->AttemptTimedout();
}
}
2018-08-14 21:17:18 +00:00
void
2018-08-30 18:48:43 +00:00
llarp_router::HandleDHTLookupForTryEstablishTo(
llarp::RouterID remote, const std::vector< llarp::RouterContact > &results)
2018-08-14 21:17:18 +00:00
{
if(results.size() == 0)
{
routerProfiling.MarkTimeout(remote);
}
2018-08-31 19:46:25 +00:00
for(const auto &result : results)
{
llarp_nodedb_put_rc(nodedb, result);
llarp_router_try_connect(this, result, 10);
2018-09-09 18:18:34 +00:00
async_verify_RC(result);
}
2018-06-19 17:11:24 +00:00
}
size_t
llarp_router::NumberOfConnectedRouters() const
{
return validRouters.size();
}
2018-06-03 13:04:51 +00:00
void
llarp_router::Tick()
{
2018-07-13 13:36:51 +00:00
// llarp::LogDebug("tick router");
2018-10-29 16:48:36 +00:00
auto now = llarp_ev_loop_time_now_ms(netloop);
paths.ExpirePaths(now);
2018-06-19 17:11:24 +00:00
{
2018-08-22 16:19:51 +00:00
auto itr = m_PersistingSessions.begin();
while(itr != m_PersistingSessions.end())
2018-08-14 21:17:18 +00:00
{
2018-08-22 16:19:51 +00:00
auto link = GetLinkWithSessionByPubkey(itr->first);
2018-09-18 14:17:15 +00:00
if(now < itr->second)
2018-08-14 21:17:18 +00:00
{
2018-08-22 16:19:51 +00:00
if(link)
2018-08-14 21:17:18 +00:00
{
2018-08-22 16:19:51 +00:00
llarp::LogDebug("keepalive to ", itr->first);
link->KeepAliveSessionTo(itr->first);
2018-08-14 21:17:18 +00:00
}
else
{
2018-08-22 16:19:51 +00:00
llarp::LogDebug("establish to ", itr->first);
TryEstablishTo(itr->first);
2018-08-14 21:17:18 +00:00
}
}
2018-09-18 14:17:15 +00:00
++itr;
2018-08-14 21:17:18 +00:00
}
2018-08-22 16:19:51 +00:00
}
if(inboundLinks.size() == 0)
{
2018-10-07 15:29:36 +00:00
auto N = llarp_nodedb_num_loaded(nodedb);
if(N < minRequiredRouters)
2018-06-19 17:11:24 +00:00
{
llarp::LogInfo("We need at least ", minRequiredRouters,
" service nodes to build paths but we have ", N);
2018-09-19 11:54:58 +00:00
auto explore = std::max(NumberOfConnectedRouters(), size_t(1));
dht->impl.Explore(explore);
2018-06-19 17:11:24 +00:00
}
2018-10-29 16:48:36 +00:00
paths.BuildPaths(now);
hiddenServiceContext.Tick();
2018-06-19 17:11:24 +00:00
}
if(NumberOfConnectedRouters() < minConnectedRouters)
2018-09-13 12:04:36 +00:00
{
ConnectToRandomRouters(minConnectedRouters);
}
2018-10-29 16:48:36 +00:00
paths.TickPaths(now);
2018-06-03 13:04:51 +00:00
}
2018-05-30 20:56:47 +00:00
2018-06-06 12:46:26 +00:00
void
2018-09-06 13:16:24 +00:00
llarp_router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg,
llarp::ILinkLayer *selected)
2018-06-06 12:46:26 +00:00
{
llarp_buffer_t buf =
llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer);
if(!msg->BEncode(&buf))
{
llarp::LogWarn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
2018-06-06 12:46:26 +00:00
return;
}
// set size of message
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
2018-09-06 13:16:24 +00:00
llarp::LogDebug("send ", buf.sz, " bytes to ", remote);
if(selected)
2018-06-20 12:34:48 +00:00
{
2018-09-06 13:16:24 +00:00
if(!selected->SendTo(remote, buf))
llarp::LogWarn("message to ", remote, " was dropped");
2018-06-20 12:34:48 +00:00
return;
}
bool sent = outboundLink->SendTo(remote, buf);
if(!sent)
2018-06-06 12:46:26 +00:00
{
for(const auto &link : inboundLinks)
2018-06-06 12:46:26 +00:00
{
if(!sent)
{
sent = link->SendTo(remote, buf);
}
2018-06-06 12:46:26 +00:00
}
}
if(!sent)
llarp::LogWarn("message to ", remote, " was dropped");
2018-06-06 12:46:26 +00:00
}
2018-06-03 13:04:51 +00:00
void
llarp_router::ScheduleTicker(uint64_t ms)
{
ticker_job_id =
llarp_logic_call_later(logic, {ms, this, &handle_router_ticker});
}
void
llarp_router::SessionClosed(const llarp::RouterID &remote)
{
__llarp_dht_remove_peer(dht, remote);
// remove from valid routers if it's a valid router
auto itr = validRouters.find(remote);
if(itr == validRouters.end())
return;
validRouters.erase(itr);
2018-05-30 20:56:47 +00:00
}
llarp::ILinkLayer *
2018-07-03 13:33:37 +00:00
llarp_router::GetLinkWithSessionByPubkey(const llarp::RouterID &pubkey)
{
if(outboundLink->HasSessionTo(pubkey))
return outboundLink.get();
for(const auto &link : inboundLinks)
2018-07-03 13:33:37 +00:00
{
if(link->HasSessionTo(pubkey))
return link.get();
2018-07-03 13:33:37 +00:00
}
return nullptr;
}
2018-06-01 14:08:54 +00:00
void
llarp_router::FlushOutboundFor(const llarp::RouterID &remote,
llarp::ILinkLayer *chosen)
2018-06-01 14:08:54 +00:00
{
llarp::LogDebug("Flush outbound for ", remote);
2018-09-06 20:31:58 +00:00
pendingEstablishJobs.erase(remote);
2018-08-29 20:40:26 +00:00
auto itr = outboundMessageQueue.find(remote);
if(itr == outboundMessageQueue.end())
2018-06-20 12:34:48 +00:00
{
2018-06-01 14:08:54 +00:00
return;
2018-06-20 12:34:48 +00:00
}
2018-07-03 13:33:37 +00:00
if(!chosen)
{
DiscardOutboundFor(remote);
return;
}
2018-06-01 14:08:54 +00:00
while(itr->second.size())
{
auto buf = llarp::ConstBuffer(itr->second.front());
if(!chosen->SendTo(remote, buf))
llarp::LogWarn("failed to send outboud message to ", remote, " via ",
chosen->Name());
2018-06-01 14:08:54 +00:00
itr->second.pop();
}
}
2018-06-13 12:58:51 +00:00
void
llarp_router::DiscardOutboundFor(const llarp::RouterID &remote)
{
2018-08-29 20:40:26 +00:00
outboundMessageQueue.erase(remote);
2018-06-13 12:58:51 +00:00
}
bool
2018-08-30 18:48:43 +00:00
llarp_router::GetRandomConnectedRouter(llarp::RouterContact &result) const
{
auto sz = validRouters.size();
if(sz)
{
auto itr = validRouters.begin();
if(sz > 1)
std::advance(itr, llarp_randint() % sz);
2018-08-30 18:48:43 +00:00
result = itr->second;
return true;
}
return false;
}
2018-05-30 20:56:47 +00:00
void
2018-09-06 11:46:19 +00:00
llarp_router::async_verify_RC(const llarp::RouterContact &rc)
2018-05-30 20:56:47 +00:00
{
2018-08-30 18:48:43 +00:00
llarp_async_verify_rc *job = new llarp_async_verify_rc();
llarp::async_verify_context *ctx = new llarp::async_verify_context();
ctx->router = this;
2018-09-06 11:46:19 +00:00
ctx->establish_job = nullptr;
auto itr = pendingEstablishJobs.find(rc.pubkey);
if(itr != pendingEstablishJobs.end())
ctx->establish_job = itr->second.get();
job->user = ctx;
job->rc = rc;
job->valid = false;
job->hook = nullptr;
job->nodedb = nodedb;
2018-06-13 12:58:51 +00:00
job->logic = logic;
// job->crypto = &crypto; // we already have this
job->cryptoworker = tp;
2018-06-13 12:58:51 +00:00
job->diskworker = disk;
2018-09-06 11:46:19 +00:00
if(rc.IsPublicRouter())
2018-05-30 20:56:47 +00:00
job->hook = &llarp_router::on_verify_server_rc;
2018-09-06 11:46:19 +00:00
else
job->hook = &llarp_router::on_verify_client_rc;
llarp_nodedb_async_verify(job);
2018-05-30 20:56:47 +00:00
}
void
llarp_router::Run()
{
2018-10-09 12:06:30 +00:00
if(enableRPCServer)
{
if(rpcBindAddr.empty())
{
rpcBindAddr = DefaultRPCBindAddr;
}
2018-10-19 11:41:36 +00:00
rpcServer = std::make_unique< llarp::rpc::Server >(this);
2018-10-25 19:06:16 +00:00
while(!rpcServer->Start(rpcBindAddr))
2018-10-09 12:06:30 +00:00
{
2018-10-25 19:06:16 +00:00
llarp::LogError("failed to bind jsonrpc to ", rpcBindAddr);
std::this_thread::sleep_for(std::chrono::seconds(1));
2018-10-09 12:06:30 +00:00
}
2018-10-25 19:06:16 +00:00
llarp::LogInfo("Bound RPC server to ", rpcBindAddr);
2018-10-09 12:06:30 +00:00
}
2018-10-04 17:34:26 +00:00
routerProfiling.Load(routerProfilesFile.c_str());
2018-10-09 01:38:25 +00:00
llarp::Addr publicAddr(this->addrInfo);
2018-06-29 12:15:15 +00:00
if(this->publicOverride)
2018-06-28 11:50:01 +00:00
{
2018-10-09 12:38:41 +00:00
llarp::LogDebug("public address:port ", publicAddr);
2018-06-28 11:50:01 +00:00
}
2018-06-29 12:15:15 +00:00
llarp::LogInfo("You have ", inboundLinks.size(), " inbound links");
for(const auto &link : inboundLinks)
{
2018-08-30 18:48:43 +00:00
llarp::AddressInfo addr;
if(!link->GetOurAddressInfo(addr))
continue;
llarp::Addr a(addr);
2018-06-29 12:15:15 +00:00
if(this->publicOverride && a.sameAddr(publicAddr))
{
llarp::LogInfo("Found adapter for public address");
}
if(!llarp::IsBogon(*a.addr6()))
{
llarp::LogInfo("Loading Addr: ", a, " into our RC");
_rc.addrs.push_back(addr);
}
};
if(this->publicOverride)
{
llarp::ILinkLayer *link = nullptr;
// llarp::LogWarn("Need to load our public IP into RC!");
2018-06-29 12:15:15 +00:00
if(inboundLinks.size() == 1)
{
2018-09-30 11:17:48 +00:00
link = inboundLinks[0].get();
}
else
{
if(inboundLinks.size())
{
link = inboundLinks[0].get();
}
else
{
llarp::LogWarn(
"No need to set public ipv4 and port if no external interface "
"binds, turning off public override");
this->publicOverride = false;
link = nullptr;
}
}
if(link && link->GetOurAddressInfo(this->addrInfo))
{
// override ip and port
this->addrInfo.ip = *publicAddr.addr6();
this->addrInfo.port = publicAddr.port();
llarp::LogInfo("Loaded our public ", publicAddr, " override into RC!");
_rc.addrs.push_back(this->addrInfo);
}
}
2018-10-09 12:38:41 +00:00
// set public encryption key
_rc.enckey = llarp::seckey_topublic(encryption);
llarp::LogInfo("Your Encryption pubkey ", rc().enckey);
// set public signing key
_rc.pubkey = llarp::seckey_topublic(identity);
llarp::LogInfo("Your Identity pubkey ", rc().pubkey);
2018-08-31 13:51:24 +00:00
llarp::LogInfo("Signing rc...");
if(!_rc.Sign(&crypto, identity))
2018-08-30 18:48:43 +00:00
{
llarp::LogError("failed to sign rc");
return;
}
if(!SaveRC())
2018-05-22 19:19:06 +00:00
{
return;
2018-05-22 19:19:06 +00:00
}
2018-09-10 13:43:36 +00:00
llarp::LogInfo("have ", llarp_nodedb_num_loaded(nodedb), " routers");
llarp::LogDebug("starting outbound link");
if(!outboundLink->Start(logic))
{
llarp::LogWarn("outbound link failed to start");
}
2018-06-10 14:05:48 +00:00
int IBLinksStarted = 0;
// start links
for(const auto &link : inboundLinks)
{
if(link->Start(logic))
2018-06-10 14:05:48 +00:00
{
llarp::LogDebug("Link ", link->Name(), " started");
2018-06-10 14:05:48 +00:00
IBLinksStarted++;
}
else
llarp::LogWarn("Link ", link->Name(), " failed to start");
}
2018-06-10 14:05:48 +00:00
if(IBLinksStarted > 0)
{
// initialize as service node
InitServiceNode();
2018-06-20 17:45:44 +00:00
// immediate connect all for service node
2018-07-20 04:50:28 +00:00
uint64_t delay = llarp_randint() % 100;
2018-06-20 17:45:44 +00:00
llarp_logic_call_later(logic, {delay, this, &ConnectAll});
}
else
2018-06-21 12:55:02 +00:00
{
// we are a client
// regenerate keys and resign rc before everything else
crypto.identity_keygen(identity);
crypto.encryption_keygen(encryption);
_rc.pubkey = llarp::seckey_topublic(identity);
_rc.enckey = llarp::seckey_topublic(encryption);
if(!_rc.Sign(&crypto, identity))
{
llarp::LogError("failed to regenerate keys and sign RC");
return;
}
// don't create default if we already have some defined
if(this->ShouldCreateDefaultHiddenService())
{
// generate default hidden service
if(!CreateDefaultHiddenService())
return;
}
2018-06-21 12:55:02 +00:00
// delayed connect all for clients
2018-07-20 04:50:28 +00:00
uint64_t delay = ((llarp_randint() % 10) * 500) + 500;
2018-06-20 17:45:44 +00:00
llarp_logic_call_later(logic, {delay, this, &ConnectAll});
2018-06-10 14:05:48 +00:00
}
2018-06-13 16:32:34 +00:00
llarp::PubKey ourPubkey = pubkey();
llarp::LogInfo("starting dht context as ", ourPubkey);
2018-06-13 16:32:34 +00:00
llarp_dht_context_start(dht, ourPubkey);
2018-06-20 17:45:44 +00:00
ScheduleTicker(1000);
}
bool
llarp_router::ShouldCreateDefaultHiddenService()
{
// llarp::LogInfo("IfName: ", this->defaultIfName, " defaultIfName: ",
// this->defaultIfName);
if(this->defaultIfName == "auto" || this->defaultIfName == "auto")
{
// auto detect if we have any pre-defined endpoints
// no if we have a endpoints
llarp::LogInfo("Auto mode detected, hasEndpoints: ",
std::to_string(this->hiddenServiceContext.hasEndpoints()));
if(this->hiddenServiceContext.hasEndpoints())
return false;
// we don't have any endpoints, auto configure settings
// set a default IP range
this->defaultIfAddr = llarp::findFreePrivateRange();
if(this->defaultIfAddr == "")
{
llarp::LogError(
"Could not find any free lokitun interface names, can't auto set up "
"default HS context for client");
this->defaultIfAddr = "no";
return false;
}
// pick an ifName
this->defaultIfName = llarp::findFreeLokiTunIfName();
if(this->defaultIfName == "")
{
llarp::LogError(
"Could not find any free private ip ranges, can't auto set up "
"default HS context for client");
this->defaultIfName = "no";
return false;
}
// auto config'd, go ahead and create it
return true;
}
// not auto mode then just check to make sure it's explicitly disabled
if(this->defaultIfAddr != "" && this->defaultIfAddr != "no"
&& this->defaultIfName != "" && this->defaultIfName != "no")
{
return true;
}
return false;
}
2018-06-10 14:05:48 +00:00
void
llarp_router::InitServiceNode()
{
llarp::LogInfo("accepting transit traffic");
2018-06-10 14:05:48 +00:00
paths.AllowTransit();
2018-06-13 16:32:34 +00:00
llarp_dht_allow_transit(dht);
2018-06-10 14:05:48 +00:00
}
void
llarp_router::ConnectAll(void *user, uint64_t orig, uint64_t left)
{
if(left)
return;
llarp_router *self = static_cast< llarp_router * >(user);
// connect to all explicit connections in connect block
for(const auto &itr : self->connect)
{
llarp::LogInfo("connecting to node ", itr.first);
self->try_connect(itr.second);
}
2018-09-13 12:04:36 +00:00
}
bool
llarp_router::HasSessionTo(const llarp::RouterID &remote) const
{
return validRouters.find(remote) != validRouters.end();
}
void
llarp_router::ConnectToRandomRouters(int want)
2018-09-13 12:04:36 +00:00
{
int wanted = want;
2018-09-13 12:04:36 +00:00
llarp_router *self = this;
llarp_nodedb_visit_loaded(
self->nodedb, [self, &want](const llarp::RouterContact &other) -> bool {
2018-09-13 12:04:36 +00:00
if(llarp_randint() % 2 == 0
&& !(self->HasSessionTo(other.pubkey)
|| self->HasPendingConnectJob(other.pubkey)))
{
llarp_router_try_connect(self, other, 5);
--want;
}
return want > 0;
});
2018-09-16 12:09:21 +00:00
if(wanted != want)
llarp::LogInfo("connecting to ", abs(want - wanted), " out of ", wanted,
" random routers");
2018-02-01 17:07:01 +00:00
}
2018-09-13 12:04:36 +00:00
2018-09-17 11:47:34 +00:00
bool
llarp_router::ReloadConfig(const llarp_config *conf)
{
return true;
}
bool
llarp_router::InitOutboundLink()
{
if(outboundLink)
return true;
2018-08-02 23:30:34 +00:00
2018-09-04 12:55:20 +00:00
auto link = llarp::utp::NewServer(this);
if(!link->EnsureKeys(transport_keyfile.string().c_str()))
{
llarp::LogError("failed to load ", transport_keyfile);
return false;
}
auto afs = {AF_INET, AF_INET6};
for(auto af : afs)
{
if(link->Configure(netloop, "*", af, 0))
{
outboundLink = std::move(link);
llarp::LogInfo("outbound link ready");
return true;
}
}
return false;
}
bool
llarp_router::CreateDefaultHiddenService()
{
2018-10-05 15:05:52 +00:00
return hiddenServiceContext.AddDefaultEndpoint(defaultIfAddr, defaultIfName);
}
2018-06-14 17:35:12 +00:00
bool
llarp_router::HasPendingConnectJob(const llarp::RouterID &remote)
{
return pendingEstablishJobs.find(remote) != pendingEstablishJobs.end();
}
2018-07-03 13:34:53 +00:00
struct llarp_router *
llarp_init_router(struct llarp_threadpool *tp, struct llarp_ev_loop *netloop,
struct llarp_logic *logic)
2018-06-18 22:05:02 +00:00
{
2018-07-03 13:34:53 +00:00
llarp_router *router = new llarp_router();
if(router)
2018-06-18 22:05:02 +00:00
{
2018-07-03 13:34:53 +00:00
router->netloop = netloop;
router->tp = tp;
router->logic = logic;
2018-07-16 03:32:13 +00:00
// TODO: make disk io threadpool count configurable
2018-06-18 22:03:50 +00:00
#ifdef TESTNET
2018-07-03 13:34:53 +00:00
router->disk = tp;
2018-06-18 22:03:50 +00:00
#else
2018-07-03 13:34:53 +00:00
router->disk = llarp_init_threadpool(1, "llarp-diskio");
2018-06-18 22:03:50 +00:00
#endif
llarp_crypto_init(&router->crypto);
2018-05-20 17:45:47 +00:00
}
2018-07-03 13:34:53 +00:00
return router;
}
2018-01-08 13:49:05 +00:00
2018-07-03 13:34:53 +00:00
bool
llarp_configure_router(struct llarp_router *router, struct llarp_config *conf)
{
llarp_config_iterator iter;
iter.user = router;
iter.visit = llarp::router_iter_config;
llarp_config_iter(conf, &iter);
if(!router->InitOutboundLink())
return false;
if(!router->Ready())
2018-06-18 22:03:50 +00:00
{
2018-07-03 13:34:53 +00:00
return false;
2018-06-18 22:03:50 +00:00
}
2018-07-03 13:34:53 +00:00
return router->EnsureIdentity();
}
2018-07-03 13:34:53 +00:00
void
llarp_run_router(struct llarp_router *router, struct llarp_nodedb *nodedb)
{
router->nodedb = nodedb;
router->Run();
}
2018-07-03 13:34:53 +00:00
void
llarp_stop_router(struct llarp_router *router)
{
if(router)
{
2018-07-03 13:34:53 +00:00
router->Close();
2018-10-04 17:34:26 +00:00
router->routerProfiling.Save(router->routerProfilesFile.c_str());
}
2018-07-03 13:34:53 +00:00
}
2018-06-20 17:45:44 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_free_router(struct llarp_router **router)
{
if(*router)
2018-07-03 13:34:46 +00:00
{
2018-07-03 13:34:53 +00:00
delete *router;
2018-07-03 13:34:46 +00:00
}
2018-07-03 13:34:53 +00:00
*router = nullptr;
}
2018-06-20 17:45:44 +00:00
2018-07-03 13:34:53 +00:00
bool
llarp_findOrCreateIdentity(llarp_crypto *crypto, const char *fpath,
byte_t *secretkey)
{
llarp::LogDebug("find or create ", fpath);
2018-07-03 13:34:53 +00:00
fs::path path(fpath);
std::error_code ec;
if(!fs::exists(path, ec))
{
llarp::LogInfo("generating new identity key");
2018-07-03 13:34:53 +00:00
crypto->identity_keygen(secretkey);
std::ofstream f(path.string(), std::ios::binary);
if(f.is_open())
{
2018-07-03 13:34:53 +00:00
f.write((char *)secretkey, SECKEYSIZE);
}
}
std::ifstream f(path.string(), std::ios::binary);
2018-07-03 13:34:53 +00:00
if(f.is_open())
{
f.read((char *)secretkey, SECKEYSIZE);
return true;
}
llarp::LogInfo("failed to get identity key");
2018-07-03 13:34:53 +00:00
return false;
}
2018-06-21 13:33:42 +00:00
2018-06-21 13:06:13 +00:00
// C++ ...
bool
llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath,
2018-08-31 12:46:54 +00:00
llarp::SecretKey &encryption)
{
llarp::LogDebug("find or create ", fpath);
fs::path path(fpath);
std::error_code ec;
if(!fs::exists(path, ec))
{
llarp::LogInfo("generating new encryption key");
2018-08-31 12:46:54 +00:00
crypto->encryption_keygen(encryption);
std::ofstream f(path.string(), std::ios::binary);
if(f.is_open())
{
2018-08-31 12:46:54 +00:00
f.write((char *)encryption.data(), SECKEYSIZE);
}
}
2018-08-02 23:30:34 +00:00
std::ifstream f(path.string(), std::ios::binary);
if(f.is_open())
{
2018-08-31 12:46:54 +00:00
f.read((char *)encryption.data(), SECKEYSIZE);
return true;
}
llarp::LogInfo("failed to get encryption key");
return false;
2018-01-08 13:49:05 +00:00
}
2018-01-19 16:51:27 +00:00
2018-07-09 17:32:11 +00:00
bool
llarp_router::LoadHiddenServiceConfig(const char *fname)
{
llarp::LogDebug("opening hidden service config ", fname);
llarp::service::Config conf;
if(!conf.Load(fname))
return false;
for(const auto &config : conf.services)
{
if(!hiddenServiceContext.AddEndpoint(config))
2018-07-09 17:32:11 +00:00
return false;
}
return true;
}
2018-05-17 20:00:58 +00:00
namespace llarp
{
void
router_iter_config(llarp_config_iterator *iter, const char *section,
const char *key, const char *val)
2018-05-20 17:45:47 +00:00
{
llarp_router *self = static_cast< llarp_router * >(iter->user);
2018-08-10 21:34:11 +00:00
int af;
uint16_t proto;
if(StrEq(val, "eth"))
{
#ifdef AF_LINK
2018-05-29 13:40:26 +00:00
af = AF_LINK;
#endif
#ifdef AF_PACKET
2018-05-29 13:40:26 +00:00
af = AF_PACKET;
#endif
proto = LLARP_ETH_PROTO;
}
2018-05-20 17:45:47 +00:00
else
{
// try IPv4 first
2018-05-29 12:15:48 +00:00
af = AF_INET;
proto = std::atoi(val);
2018-05-20 17:45:47 +00:00
}
if(StrEq(section, "bind"))
{
if(!StrEq(key, "*"))
{
2018-09-04 12:55:20 +00:00
auto server = llarp::utp::NewServer(self);
if(!server->EnsureKeys(self->transport_keyfile.string().c_str()))
{
llarp::LogError("failed to ensure keyfile ", self->transport_keyfile);
return;
}
if(server->Configure(self->netloop, key, af, proto))
{
self->AddInboundLink(server);
return;
}
if(af == AF_INET6)
{
// we failed to configure IPv6
// try IPv4
llarp::LogInfo("link ", key,
" failed to configure IPv6, trying IPv4");
af = AF_INET;
if(server->Configure(self->netloop, key, af, proto))
{
self->AddInboundLink(server);
return;
}
2018-06-23 14:55:25 +00:00
}
llarp::LogError("Failed to set up curvecp link");
}
}
else if(StrEq(section, "network"))
{
if(StrEq(key, "ifaddr"))
{
self->defaultIfAddr = val;
}
if(StrEq(key, "ifname"))
{
self->defaultIfName = val;
}
}
2018-10-09 12:06:30 +00:00
else if(StrEq(section, "api"))
{
if(StrEq(key, "enabled"))
{
self->enableRPCServer = IsTrueValue(val);
}
if(StrEq(key, "bind"))
{
self->rpcBindAddr = val;
}
if(StrEq(key, "authkey"))
{
// TODO: add pubkey to whitelist
}
}
2018-07-09 17:32:11 +00:00
else if(StrEq(section, "services"))
{
if(self->LoadHiddenServiceConfig(val))
{
llarp::LogInfo("loaded hidden service config for ", key);
}
else
{
llarp::LogWarn("failed to load hidden service config for ", key);
}
}
else if(StrEq(section, "connect"))
{
self->connect[key] = val;
2018-04-05 14:43:16 +00:00
}
else if(StrEq(section, "network"))
{
if(StrEq(key, "profiles"))
{
2018-10-04 17:34:26 +00:00
self->routerProfilesFile = val;
self->routerProfiling.Load(val);
llarp::LogInfo("setting profiles to ", self->routerProfilesFile);
}
2018-09-13 12:04:36 +00:00
if(StrEq(key, "min-connected"))
{
self->minConnectedRouters = std::max(atoi(val), 0);
}
if(StrEq(key, "max-connected"))
{
self->maxConnectedRouters = std::max(atoi(val), 1);
}
}
2018-05-23 20:37:43 +00:00
else if(StrEq(section, "router"))
{
if(StrEq(key, "nickname"))
{
self->_rc.SetNick(val);
2018-08-30 18:48:43 +00:00
// set logger name here
_glog.nodeName = self->rc().Nick();
}
2018-06-10 14:05:48 +00:00
if(StrEq(key, "encryption-privkey"))
{
self->encryption_keyfile = val;
}
2018-05-23 20:37:43 +00:00
if(StrEq(key, "contact-file"))
{
self->our_rc_file = val;
}
if(StrEq(key, "transport-privkey"))
{
self->transport_keyfile = val;
}
if(StrEq(key, "ident-privkey"))
{
self->ident_keyfile = val;
}
if(StrEq(key, "public-address"))
{
llarp::LogInfo("public ip ", val, " size ", strlen(val));
2018-06-29 12:15:15 +00:00
if(strlen(val) < 17)
{
// assume IPv4
// inet_pton(AF_INET, val, &self->ip4addr.sin_addr);
2018-06-29 12:15:15 +00:00
// struct sockaddr dest;
// sockaddr *dest = (sockaddr *)&self->ip4addr;
llarp::Addr a(val);
llarp::LogInfo("setting public ipv4 ", a);
2018-06-29 12:15:15 +00:00
self->addrInfo.ip = *a.addr6();
2018-06-28 11:59:50 +00:00
self->publicOverride = true;
}
2018-06-29 12:15:15 +00:00
// llarp::Addr a(val);
}
if(StrEq(key, "public-port"))
{
llarp::LogInfo("Setting public port ", val);
2018-10-09 01:38:25 +00:00
int p = atoi(val);
// Not needed to flip upside-down - this is done in llarp::Addr(const
// AddressInfo&)
2018-10-09 03:33:56 +00:00
self->ip4addr.sin_port = p;
self->addrInfo.port = p;
2018-06-29 12:15:15 +00:00
self->publicOverride = true;
}
2018-05-23 20:37:43 +00:00
}
2018-10-09 12:06:30 +00:00
}
2018-02-01 13:21:00 +00:00
} // namespace llarp