lokinet/llarp/router.cpp

1303 lines
31 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-07-09 04:26:27 +00:00
#include "llarp/iwp/establish_job.hpp"
#include "llarp/iwp/server.hpp"
#include "llarp/iwp/session.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>
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;
llarp_link_establish_job *establish_job;
};
2018-02-01 13:21:00 +00:00
} // namespace llarp
2017-11-28 14:05:31 +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-05-22 19:19:06 +00:00
llarp_rc_clear(&rc);
}
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-05-22 19:19:06 +00:00
llarp_rc_free(&rc);
}
2018-02-01 17:07:01 +00:00
bool
llarp_router::HandleRecvLinkMessage(llarp_link_session *session,
llarp_buffer_t buf)
{
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)
{
m_PersistingSessions[remote] = until;
}
bool
2018-06-01 14:08:54 +00:00
llarp_router::SendToOrQueue(const llarp::RouterID &remote,
2018-06-22 00:25:30 +00:00
const llarp::ILinkMessage *msg)
{
llarp_link *chosen = nullptr;
2018-07-26 22:06:11 +00:00
if(!outboundLink->has_session_to(remote))
2018-06-06 21:23:57 +00:00
{
for(auto link : inboundLinks)
{
2018-07-26 22:06:11 +00:00
if(link->has_session_to(remote))
{
chosen = link;
break;
}
}
2018-06-06 21:23:57 +00:00
}
else
chosen = outboundLink;
2018-06-01 14:08:54 +00:00
2018-06-20 12:34:48 +00:00
if(chosen)
{
SendTo(remote, msg, chosen);
delete msg;
return true;
}
2018-06-19 17:11:24 +00:00
// this will create an entry in the obmq if it's not already there
2018-06-20 17:45:44 +00:00
auto itr = outboundMesssageQueue.find(remote);
if(itr == outboundMesssageQueue.end())
{
2018-07-24 06:31:25 +00:00
outboundMesssageQueue.insert(std::make_pair(remote, MessageQueue()));
2018-06-20 17:45:44 +00:00
}
2018-06-19 17:11:24 +00:00
outboundMesssageQueue[remote].push(msg);
2018-06-01 14:08:54 +00:00
2018-06-20 12:34:48 +00:00
// we don't have an open session to that router right now
auto rc = llarp_nodedb_get_rc(nodedb, remote);
if(rc)
2018-06-01 14:08:54 +00:00
{
2018-06-20 12:34:48 +00:00
// try connecting directly as the rc is loaded from disk
llarp_router_try_connect(this, rc, 10);
return true;
2018-06-01 14:08:54 +00:00
}
2018-06-23 14:55:25 +00:00
// this would never be true, as everything is in memory
// but we'll keep around if we ever need to swap them out of memory
2018-06-29 12:15:15 +00:00
// but it's best to keep the paradigm that everythign is in memory at this
// point in development as it will reduce complexity
2018-06-23 14:55:25 +00:00
/*
2018-06-20 12:34:48 +00:00
// try requesting the rc from the disk
llarp_async_load_rc *job = new llarp_async_load_rc;
job->diskworker = disk;
job->nodedb = nodedb;
job->logic = logic;
job->user = this;
job->hook = &HandleAsyncLoadRCForSendTo;
memcpy(job->pubkey, remote, PUBKEYSIZE);
llarp_nodedb_async_load_rc(job);
2018-06-23 14:55:25 +00:00
*/
// we don't have the RC locally so do a dht lookup
llarp_router_lookup_job *lookup = new llarp_router_lookup_job;
lookup->user = this;
2018-07-17 04:37:50 +00:00
llarp_rc_clear(&lookup->result);
2018-06-29 14:43:06 +00:00
memcpy(lookup->target, remote, PUBKEYSIZE);
2018-06-23 14:55:25 +00:00
lookup->hook = &HandleDHTLookupForSendTo;
llarp_dht_lookup_router(this->dht, lookup);
2018-06-20 12:34:48 +00:00
2018-06-01 14:08:54 +00:00
return true;
}
2018-06-23 14:55:25 +00:00
/*
2018-06-13 12:58:51 +00:00
void
llarp_router::HandleAsyncLoadRCForSendTo(llarp_async_load_rc *job)
{
llarp_router *router = static_cast< llarp_router * >(job->user);
if(job->loaded)
{
llarp_router_try_connect(router, &job->rc, 10);
}
else
{
2018-06-14 15:10:31 +00:00
// we don't have the RC locally so do a dht lookup
llarp_router_lookup_job *lookup = new llarp_router_lookup_job;
lookup->user = router;
2018-06-28 15:10:25 +00:00
memcpy(lookup->target, job->pubkey, PUBKEYSIZE);
2018-06-14 15:10:31 +00:00
lookup->hook = &HandleDHTLookupForSendTo;
llarp_dht_lookup_router(router->dht, lookup);
}
2018-06-14 15:39:54 +00:00
delete job;
2018-06-14 15:10:31 +00:00
}
2018-06-23 14:55:25 +00:00
*/
2018-06-13 12:58:51 +00:00
2018-06-14 15:10:31 +00:00
void
llarp_router::HandleDHTLookupForSendTo(llarp_router_lookup_job *job)
{
llarp_router *self = static_cast< llarp_router * >(job->user);
if(job->found)
{
llarp_router_try_connect(self, &job->result, 10);
}
else
{
self->DiscardOutboundFor(job->target);
2018-06-13 12:58:51 +00:00
}
2018-08-14 21:17:18 +00:00
llarp_rc_free(&job->result);
2018-06-14 15:10:31 +00:00
delete job;
2018-06-13 12:58:51 +00:00
}
void
llarp_router::try_connect(fs::path rcfile)
{
llarp_rc remote;
llarp_rc_new(&remote);
if(!llarp_rc_read(rcfile.string().c_str(), &remote))
{
llarp::LogError("failure to decode or verify of remote RC");
return;
}
if(llarp_rc_verify_sig(&crypto, &remote))
2018-05-16 18:13:18 +00:00
{
2018-07-13 09:28:50 +00:00
llarp::LogDebug("verified signature");
// store into filesystem
// TODO: should this be async?
if(!llarp_nodedb_put_rc(nodedb, &remote))
{
llarp::LogWarn("failed to store");
}
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
llarp::LogError("failed to verify signature of RC", rcfile);
llarp_rc_free(&remote);
}
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(
&crypto, encryption_keyfile.string().c_str(), &this->encryption);
2018-06-10 14:05:48 +00:00
}
void
llarp_router::AddInboundLink(struct llarp_link *link)
{
inboundLinks.push_back(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-05-20 17:45:47 +00:00
if(!llarp_rc_verify_sig(&crypto, &rc))
{
llarp::LogError("RC has bad signature not saving");
2018-05-20 17:45:47 +00:00
return false;
}
byte_t tmp[MAX_RC_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
2018-05-20 17:45:47 +00:00
if(llarp_rc_bencode(&rc, &buf))
{
std::ofstream f(our_rc_file.string());
2018-08-02 23:30:34 +00:00
2018-05-20 17:45:47 +00:00
if(f.is_open())
{
f.write((char *)buf.base, buf.cur - buf.base);
llarp::LogInfo("our RC saved to ", our_rc_file.string().c_str());
2018-05-20 17:45:47 +00:00
return true;
}
}
llarp::LogError("did not save RC to ", our_rc_file.string().c_str());
2018-05-20 17:45:47 +00:00
return false;
}
void
llarp_router::Close()
{
2018-07-13 09:28:50 +00:00
llarp::LogInfo("Closing ", inboundLinks.size(), " server bindings");
for(auto link : inboundLinks)
{
link->stop_link();
2018-05-28 20:51:15 +00:00
delete link;
}
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_link();
delete outboundLink;
outboundLink = nullptr;
}
}
2018-05-29 13:40:26 +00:00
void
2018-06-14 17:35:12 +00:00
llarp_router::connect_job_retry(void *user, uint64_t orig, uint64_t left)
2018-05-29 13:40:26 +00:00
{
2018-06-14 17:35:12 +00:00
if(left)
return;
2018-05-29 13:40:26 +00:00
llarp_link_establish_job *job =
static_cast< llarp_link_establish_job * >(user);
2018-06-06 21:23:57 +00:00
llarp::Addr remote = job->ai;
2018-06-20 12:34:48 +00:00
if(job->link)
{
llarp::LogInfo("trying to establish session again with ", remote);
job->link->try_establish(job);
2018-06-20 12:34:48 +00:00
}
else
{
llarp::LogError("establish session retry failed, no link for ", remote);
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-06-14 17:35:12 +00:00
llarp::PubKey pk = job->rc.pubkey;
2018-05-30 20:56:47 +00:00
llarp_rc_free(&job->rc);
2018-06-14 17:35:12 +00:00
ctx->router->pendingEstablishJobs.erase(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
auto session = ctx->establish_job->session;
if(session)
session->close();
2018-05-30 20:56:47 +00:00
}
llarp_rc_free(&job->rc);
2018-06-14 17:35:12 +00:00
router->pendingEstablishJobs.erase(pk);
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");
// refresh valid routers RC value if it's there
2018-06-10 14:05:48 +00:00
auto v = router->validRouters.find(pk);
if(v != router->validRouters.end())
2018-05-30 20:56:47 +00:00
{
// free previous RC members
llarp_rc_free(&v->second);
}
2018-06-10 14:05:48 +00:00
router->validRouters[pk] = job->rc;
// track valid router in dht
__llarp_dht_put_peer(router->dht, &router->validRouters[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
{
auto session = ctx->establish_job->session;
router->FlushOutboundFor(pk, session->get_parent());
2018-06-14 17:35:12 +00:00
// this frees the job
router->pendingEstablishJobs.erase(pk);
}
2018-07-03 13:33:37 +00:00
else // this was an inbound session
2018-07-03 13:34:46 +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-08-14 21:17:18 +00:00
void
llarp_router::TryEstablishTo(const llarp::RouterID &remote)
{
auto rc = llarp_nodedb_get_rc(nodedb, remote);
if(rc)
{
// try connecting
llarp_router_try_connect(this, rc, 5);
}
else
{
// dht lookup as we don't know it
llarp_router_lookup_job *lookup = new llarp_router_lookup_job();
lookup->user = this;
llarp_rc_clear(&lookup->result);
memcpy(lookup->target, remote, PUBKEYSIZE);
lookup->hook = &HandleDHTLookupForTryEstablishTo;
lookup->iterative = false;
2018-08-14 21:17:18 +00:00
llarp_dht_lookup_router(this->dht, lookup);
}
}
void
llarp_router::HandleDHTLookupForTryEstablishTo(llarp_router_lookup_job *job)
{
if(job->found)
{
llarp_router_try_connect(static_cast< llarp_router * >(job->user),
&job->result, 5);
}
llarp_rc_free(&job->result);
delete job;
}
2018-06-19 17:11:24 +00:00
void
llarp_router::HandleExploritoryPathBuildStarted(llarp_pathbuild_job *job)
{
delete job;
}
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-08-14 21:17:18 +00:00
auto now = llarp_time_now_ms();
2018-06-18 22:03:50 +00:00
paths.ExpirePaths();
2018-06-19 17:11:24 +00:00
if(inboundLinks.size() == 0)
{
2018-08-14 21:17:18 +00:00
{
auto itr = m_PersistingSessions.begin();
while(itr != m_PersistingSessions.end())
{
auto link = GetLinkWithSessionByPubkey(itr->first);
if(now <= itr->second)
{
// persisting ended
if(link)
link->CloseSessionTo(itr->first);
itr = m_PersistingSessions.erase(itr);
}
else
{
if(link)
{
link->KeepAliveSessionTo(itr->first);
}
else
{
TryEstablishTo(itr->first);
}
++itr;
}
}
}
2018-06-19 17:11:24 +00:00
auto N = llarp_nodedb_num_loaded(nodedb);
2018-07-25 01:39:12 +00:00
if(N > 3)
2018-06-19 17:11:24 +00:00
{
paths.BuildPaths();
2018-06-19 17:11:24 +00:00
}
else
{
2018-07-25 01:39:12 +00:00
llarp::LogInfo(
"We need more than 3 service nodes to build paths but we have ", N);
2018-06-19 17:11:24 +00:00
}
hiddenServiceContext.Tick();
2018-06-19 17:11:24 +00:00
}
paths.TickPaths();
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-06-22 00:25:30 +00:00
llarp_router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg,
2018-06-20 12:34:48 +00:00
llarp_link *link)
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-06-20 12:34:48 +00:00
if(link)
{
2018-07-26 22:06:11 +00:00
link->sendto(remote, buf);
2018-06-20 12:34:48 +00:00
return;
}
2018-07-26 22:06:11 +00:00
bool sent = outboundLink->sendto(remote, buf);
if(!sent)
2018-06-06 12:46:26 +00:00
{
for(auto link : inboundLinks)
2018-06-06 12:46:26 +00:00
{
if(!sent)
{
2018-07-26 22:06:11 +00:00
sent = link->sendto(remote, buf);
}
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)
{
// remove from valid routers and dht if it's a valid router
auto itr = validRouters.find(remote);
if(itr == validRouters.end())
return;
2018-06-13 16:32:34 +00:00
__llarp_dht_remove_peer(dht, remote);
llarp_rc_free(&itr->second);
validRouters.erase(itr);
2018-05-30 20:56:47 +00:00
}
2018-07-03 13:33:37 +00:00
llarp_link *
llarp_router::GetLinkWithSessionByPubkey(const llarp::RouterID &pubkey)
{
for(auto &link : inboundLinks)
{
2018-07-26 22:06:11 +00:00
if(link->has_session_to(pubkey))
2018-07-03 13:33:37 +00:00
return link;
}
2018-07-26 22:06:11 +00:00
if(outboundLink->has_session_to(pubkey))
2018-07-03 13:33:37 +00:00
return outboundLink;
return nullptr;
}
2018-06-01 14:08:54 +00:00
void
llarp_router::FlushOutboundFor(const llarp::RouterID &remote,
llarp_link *chosen)
2018-06-01 14:08:54 +00:00
{
llarp::LogDebug("Flush outbound for ", remote);
2018-06-01 14:08:54 +00:00
auto itr = outboundMesssageQueue.find(remote);
if(itr == outboundMesssageQueue.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::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer);
auto &msg = itr->second.front();
if(!msg->BEncode(&buf))
{
llarp::LogWarn("failed to encode outbound message, buffer size left: ",
llarp_buffer_size_left(buf));
2018-06-01 14:08:54 +00:00
delete msg;
itr->second.pop();
continue;
}
// set size of message
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
2018-07-26 22:06:11 +00:00
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
delete msg;
itr->second.pop();
}
}
2018-05-30 20:56:47 +00:00
void
llarp_router::on_try_connect_result(llarp_link_establish_job *job)
{
llarp_router *router = static_cast< llarp_router * >(job->user);
if(job->session)
{
// llarp::LogDebug("try_connect got session");
2018-08-02 04:34:46 +00:00
// auto session = job->session;
// router->async_verify_RC(session->get_remote_router(), false, job);
2018-05-30 20:56:47 +00:00
return;
}
// llarp::LogDebug("try_connect no session");
2018-06-14 17:35:12 +00:00
llarp::PubKey pk = job->pubkey;
2018-06-13 12:58:51 +00:00
if(job->retries > 0)
{
job->retries--;
2018-06-14 17:35:12 +00:00
job->timeout *= 3;
job->timeout /= 2;
llarp::LogInfo("session not established with ", pk, " relaxing timeout to ",
job->timeout);
2018-06-14 17:35:12 +00:00
// exponential backoff
llarp_logic_call_later(
router->logic, {job->timeout, job, &llarp_router::connect_job_retry});
2018-06-13 12:58:51 +00:00
}
else
{
llarp::LogWarn("failed to connect to ", pk,
" dropping all pending messages");
2018-06-13 16:32:34 +00:00
router->DiscardOutboundFor(pk);
2018-06-14 17:35:12 +00:00
router->pendingEstablishJobs.erase(pk);
2018-06-13 12:58:51 +00:00
}
}
2018-06-13 12:58:51 +00:00
void
llarp_router::DiscardOutboundFor(const llarp::RouterID &remote)
{
auto &queue = outboundMesssageQueue[remote];
while(queue.size())
{
delete queue.front();
queue.pop();
}
outboundMesssageQueue.erase(remote);
}
bool
llarp_router::GetRandomConnectedRouter(llarp_rc *result) const
{
auto sz = validRouters.size();
if(sz)
{
auto itr = validRouters.begin();
if(sz > 1)
std::advance(itr, llarp_randint() % sz);
llarp_rc_copy(result, &itr->second);
return true;
}
return false;
}
2018-05-30 20:56:47 +00:00
void
2018-07-03 13:13:56 +00:00
llarp_router::async_verify_RC(llarp_rc *rc, bool isExpectingClient,
2018-05-30 20:56:47 +00:00
llarp_link_establish_job *establish_job)
{
llarp_async_verify_rc *job = new llarp_async_verify_rc;
2018-06-13 12:58:51 +00:00
job->user = new llarp::async_verify_context{this, establish_job};
job->rc = {};
job->valid = false;
2018-06-13 12:58:51 +00:00
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-07-03 13:13:56 +00:00
llarp_rc_copy(&job->rc, rc);
2018-05-30 20:56:47 +00:00
if(isExpectingClient)
job->hook = &llarp_router::on_verify_client_rc;
else
job->hook = &llarp_router::on_verify_server_rc;
llarp_nodedb_async_verify(job);
2018-05-30 20:56:47 +00:00
}
void
llarp_router::Run()
{
// zero out router contact
llarp::Zero(&rc, sizeof(llarp_rc));
// fill our address list
2018-08-02 23:03:23 +00:00
rc.addrs = llarp_ai_list_new();
2018-06-29 12:15:15 +00:00
sockaddr *dest = (sockaddr *)&this->ip4addr;
llarp::Addr publicAddr(*dest);
2018-06-29 12:15:15 +00:00
if(this->publicOverride)
2018-06-28 11:50:01 +00:00
{
2018-06-29 12:15:15 +00:00
if(publicAddr)
2018-06-28 11:59:50 +00:00
{
llarp::LogInfo("public address:port ", publicAddr);
2018-06-28 11:59:50 +00:00
}
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(auto link : inboundLinks)
{
2018-05-22 19:19:06 +00:00
llarp_ai addr;
link->get_our_address(&addr);
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");
}
2018-08-02 23:03:23 +00:00
if(!a.isPrivate())
{
llarp::LogInfo("Loading Addr: ", a, " into our RC");
llarp_ai_list_pushback(rc.addrs, &addr);
}
};
if(this->publicOverride)
{
// llarp::LogWarn("Need to load our public IP into RC!");
2018-06-29 12:15:15 +00:00
llarp_link *link = nullptr;
2018-06-29 12:15:15 +00:00
if(inboundLinks.size() == 1)
{
link = inboundLinks.front();
}
else
{
2018-06-29 12:15:15 +00:00
if(!inboundLinks.size())
{
llarp::LogError("No inbound links found, aborting");
return;
}
link = inboundLinks.front();
/*
// create a new link
link = new llarp_link;
llarp::Zero(link, sizeof(llarp_link));
2018-06-29 12:15:15 +00:00
llarp_iwp_args args = {
.crypto = &this->crypto,
.logic = this->logic,
.cryptoworker = this->tp,
.router = this,
.keyfile = this->transport_keyfile.c_str(),
};
iwp_link_init(link, args);
if(llarp_link_initialized(link))
{
2018-06-29 12:15:15 +00:00
}
*/
}
link->get_our_address(&this->addrInfo);
// override ip and port
2018-06-29 12:15:15 +00:00
this->addrInfo.ip = *publicAddr.addr6();
this->addrInfo.port = publicAddr.port();
llarp::LogInfo("Loaded our public ", publicAddr, " override into RC!");
// we need the link to set the pubkey
llarp_ai_list_pushback(rc.addrs, &this->addrInfo);
}
// set public encryption key
llarp_rc_set_pubenckey(&rc, llarp::seckey_topublic(encryption));
char ftmp[68] = {0};
const char *hexKey = llarp::HexEncode< llarp::PubKey, decltype(ftmp) >(
llarp::seckey_topublic(encryption), ftmp);
llarp::LogInfo("Your Encryption pubkey ", hexKey);
// set public signing key
llarp_rc_set_pubsigkey(&rc, llarp::seckey_topublic(identity));
hexKey = llarp::HexEncode< llarp::PubKey, decltype(ftmp) >(
llarp::seckey_topublic(identity), ftmp);
llarp::LogInfo("Your Identity pubkey ", hexKey);
2018-05-22 19:19:06 +00:00
llarp_rc_sign(&crypto, identity, &rc);
if(!SaveRC())
2018-05-22 19:19:06 +00:00
{
return;
2018-05-22 19:19:06 +00:00
}
llarp::LogDebug("starting outbound link");
if(!outboundLink->start_link(logic))
{
llarp::LogWarn("outbound link failed to start");
}
2018-06-10 14:05:48 +00:00
int IBLinksStarted = 0;
// start links
for(auto link : inboundLinks)
{
if(link->start_link(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
{
// 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);
}
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);
for(const auto &itr : self->connect)
{
llarp::LogInfo("connecting to node ", itr.first);
self->try_connect(itr.second);
}
2018-02-01 17:07:01 +00:00
}
bool
llarp_router::InitOutboundLink()
{
if(outboundLink)
return true;
2018-08-02 23:30:34 +00:00
llarp_iwp_args args = {
2018-08-10 21:34:11 +00:00
&crypto, logic, tp, this, transport_keyfile.string(),
};
2018-08-10 21:34:11 +00:00
auto link = new llarp_link(args);
auto afs = {AF_INET, AF_INET6};
if(link)
{
llarp::LogInfo("outbound link initialized");
for(auto af : afs)
{
if(link->configure(netloop, "*", af, 0))
{
outboundLink = link;
llarp::LogInfo("outbound link ready");
return true;
}
}
}
delete link;
llarp::LogError("failed to initialize outbound link");
return false;
}
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
2018-07-03 13:34:53 +00:00
llarp_crypto_libsodium_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
bool
llarp_router_try_connect(struct llarp_router *router, struct llarp_rc *remote,
uint16_t numretries)
{
char ftmp[68] = {0};
const char *hexname =
llarp::HexEncode< llarp::PubKey, decltype(ftmp) >(remote->pubkey, ftmp);
2018-07-03 13:34:46 +00:00
2018-07-03 13:34:53 +00:00
// do we already have a pending job for this remote?
if(router->HasPendingConnectJob(remote->pubkey))
{
llarp::LogDebug("We have pending connect jobs to ", hexname);
2018-06-18 22:03:50 +00:00
return false;
}
2018-07-03 13:34:53 +00:00
// try first address only
llarp_ai addr;
if(llarp_ai_list_index(remote->addrs, 0, &addr))
{
auto link = router->outboundLink;
2018-07-24 06:22:03 +00:00
auto itr = router->pendingEstablishJobs.insert(
2018-07-03 13:34:53 +00:00
std::make_pair(remote->pubkey, llarp_link_establish_job()));
auto job = &itr.first->second;
llarp_ai_copy(&job->ai, &addr);
memcpy(job->pubkey, remote->pubkey, PUBKEYSIZE);
job->retries = numretries;
job->timeout = 10000;
job->result = &llarp_router::on_try_connect_result;
// give router as user pointer
job->user = router;
// try establishing
link->try_establish(job);
2018-07-03 13:34:53 +00:00
return true;
2018-07-03 13:34:46 +00:00
}
llarp::LogWarn("couldn't get first address for ", hexname);
2018-07-03 13:34:53 +00:00
return false;
}
2018-07-03 13:34:53 +00:00
void
llarp_rc_clear(struct llarp_rc *rc)
{
// zero out router contact
llarp::Zero(rc, sizeof(llarp_rc));
}
2018-05-20 17:45:47 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_rc_set_pubenckey(struct llarp_rc *rc, const uint8_t *pubenckey)
{
// set public encryption key
memcpy(rc->enckey, pubenckey, PUBKEYSIZE);
}
2018-06-21 13:33:42 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_rc_set_pubsigkey(struct llarp_rc *rc, const uint8_t *pubsigkey)
{
// set public signing key
memcpy(rc->pubkey, pubsigkey, PUBKEYSIZE);
}
2018-07-03 13:34:46 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_rc_set_pubkey(struct llarp_rc *rc, const uint8_t *pubenckey,
const uint8_t *pubsigkey)
{
// set public encryption key
llarp_rc_set_pubenckey(rc, pubenckey);
// set public signing key
llarp_rc_set_pubsigkey(rc, pubsigkey);
}
2018-07-03 13:34:46 +00:00
bool
llarp_rc_read(const char *fpath, llarp_rc *result)
2018-07-03 13:34:53 +00:00
{
fs::path our_rc_file(fpath);
std::error_code ec;
if(!fs::exists(our_rc_file, ec))
2018-07-03 13:34:46 +00:00
{
2018-07-03 13:34:53 +00:00
printf("File[%s] not found\n", fpath);
return false;
2018-06-18 22:03:50 +00:00
}
2018-08-02 23:30:34 +00:00
std::ifstream f(our_rc_file.string(), std::ios::binary);
2018-08-02 23:30:34 +00:00
2018-07-03 13:34:53 +00:00
if(!f.is_open())
2018-07-03 13:34:46 +00:00
{
2018-07-03 13:34:53 +00:00
printf("Can't open file [%s]\n", fpath);
return false;
2018-07-03 13:34:46 +00:00
}
2018-07-03 13:34:53 +00:00
byte_t tmp[MAX_RC_SIZE];
llarp_buffer_t buf = llarp::StackBuffer< decltype(tmp) >(tmp);
f.seekg(0, std::ios::end);
size_t sz = f.tellg();
f.seekg(0, std::ios::beg);
if(sz > buf.sz)
return false;
2018-07-03 13:34:53 +00:00
f.read((char *)buf.base, sz);
// printf("contents[%s]\n", tmpc);
llarp::Zero(result, sizeof(llarp_rc));
if(!llarp_rc_bdecode(result, &buf))
2018-07-03 13:34:53 +00:00
{
llarp::LogError("Can't decode ", fpath);
return false;
2018-07-03 13:34:53 +00:00
}
return true;
2018-07-03 13:34:53 +00:00
}
2018-06-21 13:33:42 +00:00
2018-07-03 13:34:53 +00:00
bool
llarp_rc_addr_list_iter(struct llarp_ai_list_iter *iter, struct llarp_ai *ai)
{
struct llarp_rc *rc = (llarp_rc *)iter->user;
llarp_ai_list_pushback(rc->addrs, ai);
return true;
}
2018-06-18 22:05:02 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_rc_set_addrs(struct llarp_rc *rc, struct llarp_alloc *mem,
struct llarp_ai_list *addr)
{
rc->addrs = llarp_ai_list_new();
struct llarp_ai_list_iter ai_itr;
ai_itr.user = rc;
ai_itr.visit = &llarp_rc_addr_list_iter;
llarp_ai_list_iterate(addr, &ai_itr);
}
2018-06-18 22:03:50 +00:00
2018-07-03 13:34:53 +00:00
bool
llarp_rc_write(struct llarp_rc *rc, const char *fpath)
{
fs::path our_rc_file(fpath);
byte_t tmp[MAX_RC_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
if(llarp_rc_bencode(rc, &buf))
2018-06-21 14:20:14 +00:00
{
std::ofstream f(our_rc_file.string(), std::ios::binary);
2018-07-03 13:34:53 +00:00
if(f.is_open())
2018-06-18 22:03:50 +00:00
{
2018-07-03 13:34:53 +00:00
f.write((char *)buf.base, buf.cur - buf.base);
return true;
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
void
llarp_rc_sign(llarp_crypto *crypto, const byte_t *seckey, struct llarp_rc *rc)
{
byte_t buf[MAX_RC_SIZE];
auto signbuf = llarp::StackBuffer< decltype(buf) >(buf);
// zero out previous signature
llarp::Zero(rc->signature, sizeof(rc->signature));
// encode
if(llarp_rc_bencode(rc, &signbuf))
{
// sign
signbuf.sz = signbuf.cur - signbuf.base;
crypto->sign(rc->signature, seckey, signbuf);
2018-06-18 22:03:50 +00:00
}
2018-07-03 13:34:53 +00:00
}
2018-06-18 22:05:02 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_stop_router(struct llarp_router *router)
{
if(router)
router->Close();
}
2018-06-20 17:45:44 +00:00
2018-07-03 13:34:53 +00:00
void
llarp_router_iterate_links(struct llarp_router *router,
struct llarp_router_link_iter i)
{
for(auto link : router->inboundLinks)
if(!i.visit(&i, router, link))
return;
i.visit(&i, router, router->outboundLink);
}
2018-06-21 14:20:14 +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
void
llarp_router_override_path_selection(struct llarp_router *router,
llarp_pathbuilder_select_hop_func func)
{
if(func)
router->selectHopFunc = func;
}
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,
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");
crypto->encryption_keygen(*encryption);
std::ofstream f(path.string(), std::ios::binary);
if(f.is_open())
{
f.write((char *)encryption, SECKEYSIZE);
}
}
2018-08-02 23:30:34 +00:00
std::ifstream f(path.string(), std::ios::binary);
if(f.is_open())
{
f.read((char *)encryption, 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
}
struct llarp_link *link = nullptr;
if(StrEq(section, "bind"))
{
if(!StrEq(key, "*"))
{
llarp_iwp_args args = {
&self->crypto,
self->logic,
self->tp,
self,
2018-08-10 21:34:11 +00:00
self->transport_keyfile.string(),
};
2018-08-10 21:34:11 +00:00
llarp::LogInfo("interface specific binding activated");
link = new llarp_link(args);
if(link)
{
llarp::LogInfo("link ", key, " initialized");
if(link->configure(self->netloop, key, af, proto))
{
self->AddInboundLink(link);
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(link->configure(self->netloop, key, af, proto))
{
self->AddInboundLink(link);
return;
}
}
}
2018-06-23 14:55:25 +00:00
else
{
llarp::LogError("link ", key, " failed to initialize. Link state",
link);
2018-06-23 14:55:25 +00:00
}
}
llarp::LogError("link ", key,
" failed to configure. (Note: We don't support * yet)");
}
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"))
{
}
2018-05-23 20:37:43 +00:00
else if(StrEq(section, "router"))
{
if(StrEq(key, "nickname"))
{
if(llarp_rc_set_nickname(&self->rc, val))
{
// set logger name here
_glog.nodeName = self->rc.Nick();
}
else
llarp::LogWarn("failed to set nickname to ", val);
}
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(*dest);
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);
self->ip4addr.sin_port = htons(atoi(val));
2018-06-29 12:15:15 +00:00
self->addrInfo.port = htons(atoi(val));
self->publicOverride = true;
}
2018-05-23 20:37:43 +00:00
}
2018-01-19 16:51:27 +00:00
}
2018-02-01 13:21:00 +00:00
} // namespace llarp