i2pd/libi2pd/NetDb.cpp

1175 lines
34 KiB
C++
Raw Normal View History

2014-12-31 14:14:53 +00:00
#include <string.h>
2013-11-20 12:46:09 +00:00
#include <fstream>
2014-01-21 00:12:59 +00:00
#include <vector>
2014-01-22 20:32:50 +00:00
#include <boost/asio.hpp>
#include <stdexcept>
2016-02-11 00:00:00 +00:00
#include "I2PEndian.h"
2015-11-03 14:15:49 +00:00
#include "Base.h"
2016-05-11 19:12:38 +00:00
#include "Crypto.h"
2013-11-13 12:59:21 +00:00
#include "Log.h"
2013-11-20 12:46:09 +00:00
#include "Timestamp.h"
2013-11-13 12:59:21 +00:00
#include "I2NPProtocol.h"
#include "Tunnel.h"
#include "Transports.h"
2013-11-19 01:37:38 +00:00
#include "RouterContext.h"
2014-01-03 02:22:48 +00:00
#include "Garlic.h"
#include "NetDb.hpp"
2016-11-14 17:05:44 +00:00
#include "Config.h"
2013-11-13 12:59:21 +00:00
using namespace i2p::transport;
2013-11-13 12:59:21 +00:00
namespace i2p
{
namespace data
{
NetDb netdb;
2016-11-14 17:05:44 +00:00
NetDb::NetDb (): m_IsRunning (false), m_Thread (nullptr), m_Reseeder (nullptr), m_Storage("netDb", "r", "routerInfo-", "dat"), m_FloodfillBootstrap(nullptr), m_HiddenMode(false)
2013-11-13 12:59:21 +00:00
{
}
NetDb::~NetDb ()
{
2014-03-19 18:08:09 +00:00
Stop ();
2015-01-19 18:57:37 +00:00
delete m_Reseeder;
2013-11-13 12:59:21 +00:00
}
2013-11-19 01:37:38 +00:00
void NetDb::Start ()
2016-08-29 19:34:59 +00:00
{
m_Storage.SetPlace(i2p::fs::GetDataDir());
m_Storage.Init(i2p::data::GetBase64SubstitutionTable(), 64);
InitProfilesStorage ();
2016-08-29 19:26:19 +00:00
m_Families.LoadCertificates ();
Load ();
2017-02-02 20:40:57 +00:00
uint16_t threshold; i2p::config::GetOption("reseed.threshold", threshold);
if (m_RouterInfos.size () < threshold) // reseed if # of router less than threshold
2015-01-19 18:57:37 +00:00
Reseed ();
2014-12-15 17:38:35 +00:00
2015-01-15 01:27:19 +00:00
m_IsRunning = true;
2013-11-19 01:37:38 +00:00
m_Thread = new std::thread (std::bind (&NetDb::Run, this));
}
void NetDb::Stop ()
{
2015-04-11 19:39:23 +00:00
if (m_IsRunning)
2013-11-19 01:37:38 +00:00
{
2016-08-05 18:23:54 +00:00
for (auto& it: m_RouterInfos)
2015-04-11 19:39:23 +00:00
it.second->SaveProfile ();
DeleteObsoleteProfiles ();
m_RouterInfos.clear ();
m_Floodfills.clear ();
if (m_Thread)
{
m_IsRunning = false;
m_Queue.WakeUp ();
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
m_LeaseSets.clear();
m_Requests.Stop ();
2016-06-13 15:34:44 +00:00
}
2013-11-19 01:37:38 +00:00
}
2016-08-29 19:26:19 +00:00
2013-11-19 01:37:38 +00:00
void NetDb::Run ()
{
2016-07-28 17:24:25 +00:00
uint32_t lastSave = 0, lastPublish = 0, lastExploratory = 0, lastManageRequest = 0, lastDestinationCleanup = 0;
2013-11-19 01:37:38 +00:00
while (m_IsRunning)
{
try
2013-11-20 12:46:09 +00:00
{
2015-06-16 17:32:42 +00:00
auto msg = m_Queue.GetNextWithTimeout (15000); // 15 sec
if (msg)
{
int numMsgs = 0;
2015-02-12 16:40:42 +00:00
while (msg)
2013-11-20 12:46:09 +00:00
{
2015-12-18 04:03:07 +00:00
LogPrint(eLogDebug, "NetDb: got request with type ", (int) msg->GetTypeID ());
2015-01-02 04:00:33 +00:00
switch (msg->GetTypeID ())
{
case eI2NPDatabaseStore:
2015-06-16 17:32:42 +00:00
HandleDatabaseStoreMsg (msg);
break;
case eI2NPDatabaseSearchReply:
2015-06-16 17:32:42 +00:00
HandleDatabaseSearchReplyMsg (msg);
break;
case eI2NPDatabaseLookup:
2015-06-16 17:32:42 +00:00
HandleDatabaseLookupMsg (msg);
break;
default: // WTF?
2015-12-18 04:03:07 +00:00
LogPrint (eLogError, "NetDb: unexpected message type ", (int) msg->GetTypeID ());
2015-06-16 17:32:42 +00:00
//i2p::HandleI2NPMessage (msg);
}
2015-02-12 16:40:42 +00:00
if (numMsgs > 100) break;
msg = m_Queue.Get ();
numMsgs++;
2013-11-20 12:46:09 +00:00
}
}
if (!m_IsRunning) break;
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
if (ts - lastManageRequest >= 15) // manage requests every 15 seconds
{
2015-04-09 16:45:00 +00:00
m_Requests.ManageRequests ();
lastManageRequest = ts;
}
2014-07-31 16:59:43 +00:00
if (ts - lastSave >= 60) // save routers, manage leasesets and validate subscriptions every minute
{
2014-02-13 03:02:39 +00:00
if (lastSave)
2014-02-14 21:10:25 +00:00
{
SaveUpdated ();
2014-07-31 16:59:43 +00:00
ManageLeaseSets ();
2014-02-14 21:10:25 +00:00
}
2014-02-13 03:02:39 +00:00
lastSave = ts;
}
2016-07-28 17:24:25 +00:00
if (ts - lastDestinationCleanup >= i2p::garlic::INCOMING_TAGS_EXPIRATION_TIMEOUT)
{
i2p::context.CleanupDestination ();
lastDestinationCleanup = ts;
}
if (ts - lastPublish >= NETDB_PUBLISH_INTERVAL && !m_HiddenMode) // publish
2014-02-13 03:02:39 +00:00
{
Publish ();
lastPublish = ts;
2013-11-20 12:46:09 +00:00
}
2015-01-10 21:08:13 +00:00
if (ts - lastExploratory >= 30) // exploratory every 30 seconds
{
auto numRouters = m_RouterInfos.size ();
if (numRouters == 0)
{
throw std::runtime_error("No known routers, reseed seems to be totally failed");
}
2016-11-14 17:05:44 +00:00
else // we have peers now
m_FloodfillBootstrap = nullptr;
2015-01-10 21:08:13 +00:00
if (numRouters < 2500 || ts - lastExploratory >= 90)
{
numRouters = 800/numRouters;
if (numRouters < 1) numRouters = 1;
if (numRouters > 9) numRouters = 9;
m_Requests.ManageRequests ();
if(!m_HiddenMode)
Explore (numRouters);
2015-01-10 21:08:13 +00:00
lastExploratory = ts;
}
}
2013-11-20 12:46:09 +00:00
}
catch (std::exception& ex)
2013-11-20 12:46:09 +00:00
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogError, "NetDb: runtime exception: ", ex.what ());
2013-11-20 12:46:09 +00:00
}
2013-11-19 01:37:38 +00:00
}
}
2013-11-13 12:59:21 +00:00
2016-02-17 20:36:55 +00:00
bool NetDb::AddRouterInfo (const uint8_t * buf, int len)
2014-12-11 20:41:04 +00:00
{
IdentityEx identity;
2014-12-12 03:31:39 +00:00
if (identity.FromBuffer (buf, len))
2016-02-17 20:36:55 +00:00
return AddRouterInfo (identity.GetIdentHash (), buf, len);
return false;
2014-12-11 20:41:04 +00:00
}
void NetDb::SetHidden(bool hide) {
// TODO: remove reachable addresses from router info
m_HiddenMode = hide;
}
2016-02-17 20:36:55 +00:00
bool NetDb::AddRouterInfo (const IdentHash& ident, const uint8_t * buf, int len)
2014-07-22 00:14:11 +00:00
{
2016-02-17 20:36:55 +00:00
bool updated = true;
2014-11-21 18:29:19 +00:00
auto r = FindRouter (ident);
if (r)
{
2016-02-17 20:36:55 +00:00
if (r->IsNewer (buf, len))
{
r->Update (buf, len);
2016-01-18 00:00:00 +00:00
LogPrint (eLogInfo, "NetDb: RouterInfo updated: ", ident.ToBase64());
2016-02-22 15:27:43 +00:00
// TODO: check if floodfill has been changed
2016-02-17 20:36:55 +00:00
}
else
2016-11-15 17:17:21 +00:00
{
2016-02-17 20:36:55 +00:00
LogPrint (eLogDebug, "NetDb: RouterInfo is older: ", ident.ToBase64());
2016-11-15 17:17:21 +00:00
updated = false;
}
}
else
{
2015-01-15 01:27:19 +00:00
r = std::make_shared<RouterInfo> (buf, len);
2016-01-16 20:36:30 +00:00
if (!r->IsUnreachable ())
2014-11-21 18:29:19 +00:00
{
2016-11-15 17:17:21 +00:00
bool inserted = false;
2016-01-16 20:36:30 +00:00
{
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
2016-11-15 17:17:21 +00:00
inserted = m_RouterInfos.insert ({r->GetIdentHash (), r}).second;
}
if (inserted)
{
LogPrint (eLogInfo, "NetDb: RouterInfo added: ", ident.ToBase64());
if (r->IsFloodfill () && r->IsReachable ()) // floodfill must be reachable
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
m_Floodfills.push_back (r);
}
2016-01-16 20:36:30 +00:00
}
2016-11-15 17:17:21 +00:00
else
2016-01-16 20:36:30 +00:00
{
2016-11-15 17:17:21 +00:00
LogPrint (eLogWarning, "NetDb: Duplicated RouterInfo ", ident.ToBase64());
updated = false;
2016-01-16 20:36:30 +00:00
}
2014-10-06 01:59:05 +00:00
}
2016-02-17 20:36:55 +00:00
else
updated = false;
}
2015-01-14 21:11:09 +00:00
// take care about requested destination
2015-04-09 16:45:00 +00:00
m_Requests.RequestComplete (ident, r);
2016-02-17 20:36:55 +00:00
return updated;
2013-11-13 12:59:21 +00:00
}
2016-02-17 20:36:55 +00:00
bool NetDb::AddLeaseSet (const IdentHash& ident, const uint8_t * buf, int len,
2015-02-05 23:53:43 +00:00
std::shared_ptr<i2p::tunnel::InboundTunnel> from)
2013-11-13 12:59:21 +00:00
{
2016-07-15 17:52:55 +00:00
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
2016-02-17 20:36:55 +00:00
bool updated = false;
if (!from) // unsolicited LS must be received directly
2014-01-13 03:31:26 +00:00
{
auto it = m_LeaseSets.find(ident);
if (it != m_LeaseSets.end ())
{
2016-02-17 20:36:55 +00:00
if (it->second->IsNewer (buf, len))
2015-04-08 14:34:16 +00:00
{
2016-02-17 20:36:55 +00:00
it->second->Update (buf, len);
if (it->second->IsValid ())
{
2016-06-30 13:49:28 +00:00
LogPrint (eLogInfo, "NetDb: LeaseSet updated: ", ident.ToBase32());
2016-02-17 20:36:55 +00:00
updated = true;
}
else
{
2016-06-30 13:49:28 +00:00
LogPrint (eLogWarning, "NetDb: LeaseSet update failed: ", ident.ToBase32());
2016-02-17 20:36:55 +00:00
m_LeaseSets.erase (it);
}
}
else
2016-06-30 13:49:28 +00:00
LogPrint (eLogDebug, "NetDb: LeaseSet is older: ", ident.ToBase32());
}
else
{
2016-02-08 00:45:06 +00:00
auto leaseSet = std::make_shared<LeaseSet> (buf, len, false); // we don't need leases in netdb
2015-04-08 14:34:16 +00:00
if (leaseSet->IsValid ())
{
2016-06-30 13:49:28 +00:00
LogPrint (eLogInfo, "NetDb: LeaseSet added: ", ident.ToBase32());
2015-04-08 14:34:16 +00:00
m_LeaseSets[ident] = leaseSet;
2016-02-17 20:36:55 +00:00
updated = true;
2015-04-08 14:34:16 +00:00
}
else
2016-06-30 13:49:28 +00:00
LogPrint (eLogError, "NetDb: new LeaseSet validation failed: ", ident.ToBase32());
}
2014-01-13 03:31:26 +00:00
}
2016-02-17 20:36:55 +00:00
return updated;
2013-11-13 12:59:21 +00:00
}
std::shared_ptr<RouterInfo> NetDb::FindRouter (const IdentHash& ident) const
2013-11-13 12:59:21 +00:00
{
2014-11-21 18:29:19 +00:00
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
2013-11-29 12:52:09 +00:00
auto it = m_RouterInfos.find (ident);
2013-11-13 12:59:21 +00:00
if (it != m_RouterInfos.end ())
return it->second;
2013-11-13 12:59:21 +00:00
else
return nullptr;
}
2013-12-22 16:29:57 +00:00
2015-01-27 16:27:58 +00:00
std::shared_ptr<LeaseSet> NetDb::FindLeaseSet (const IdentHash& destination) const
2013-12-22 16:29:57 +00:00
{
2016-07-15 17:52:55 +00:00
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
2013-12-22 16:29:57 +00:00
auto it = m_LeaseSets.find (destination);
if (it != m_LeaseSets.end ())
return it->second;
else
return nullptr;
2014-01-29 18:36:20 +00:00
}
2015-11-03 14:15:49 +00:00
std::shared_ptr<RouterProfile> NetDb::FindRouterProfile (const IdentHash& ident) const
{
auto router = FindRouter (ident);
return router ? router->GetProfile () : nullptr;
}
2014-10-24 19:39:53 +00:00
void NetDb::SetUnreachable (const IdentHash& ident, bool unreachable)
{
auto it = m_RouterInfos.find (ident);
if (it != m_RouterInfos.end ())
return it->second->SetUnreachable (unreachable);
}
2015-01-19 18:57:37 +00:00
void NetDb::Reseed ()
{
if (!m_Reseeder)
{
m_Reseeder = new Reseeder ();
m_Reseeder->LoadCertificates (); // we need certificates for SU3 verification
}
2016-11-14 17:05:44 +00:00
// try reseeding from floodfill first if specified
std::string riPath;
if(i2p::config::GetOption("reseed.floodfill", riPath)) {
auto ri = std::make_shared<RouterInfo>(riPath);
if (ri->IsFloodfill()) {
const uint8_t * riData = ri->GetBuffer();
int riLen = ri->GetBufferLen();
if(!i2p::data::netdb.AddRouterInfo(riData, riLen)) {
// bad router info
LogPrint(eLogError, "NetDb: bad router info");
return;
}
m_FloodfillBootstrap = ri;
ReseedFromFloodfill(*ri);
// don't try reseed servers if trying to boostrap from floodfill
return;
}
}
2017-02-01 22:17:25 +00:00
2017-02-02 20:25:25 +00:00
m_Reseeder->Bootstrap ();
2015-01-19 18:57:37 +00:00
}
2016-11-14 17:05:44 +00:00
void NetDb::ReseedFromFloodfill(const RouterInfo & ri, int numRouters, int numFloodfills)
{
LogPrint(eLogInfo, "NetDB: reseeding from floodfill ", ri.GetIdentHashBase64());
std::vector<std::shared_ptr<i2p::I2NPMessage> > requests;
i2p::data::IdentHash ourIdent = i2p::context.GetIdentHash();
i2p::data::IdentHash ih = ri.GetIdentHash();
i2p::data::IdentHash randomIdent;
// make floodfill lookups
while(numFloodfills > 0) {
randomIdent.Randomize();
auto msg = i2p::CreateRouterInfoDatabaseLookupMsg(randomIdent, ourIdent, 0, false);
requests.push_back(msg);
numFloodfills --;
}
// make regular router lookups
while(numRouters > 0) {
randomIdent.Randomize();
auto msg = i2p::CreateRouterInfoDatabaseLookupMsg(randomIdent, ourIdent, 0, true);
requests.push_back(msg);
numRouters --;
}
// send them off
i2p::transport::transports.SendMessages(ih, requests);
}
2016-02-11 00:00:00 +00:00
bool NetDb::LoadRouterInfo (const std::string & path)
{
2016-02-11 00:00:00 +00:00
auto r = std::make_shared<RouterInfo>(path);
if (r->GetRouterIdentity () && !r->IsUnreachable () &&
2016-02-24 16:31:14 +00:00
(!r->UsesIntroducer () || m_LastLoad < r->GetTimestamp () + NETDB_INTRODUCEE_EXPIRATION_TIMEOUT*1000LL)) // 1 hour
2014-01-29 18:36:20 +00:00
{
2016-02-11 00:00:00 +00:00
r->DeleteBuffer ();
r->ClearProperties (); // properties are not used for regular routers
m_RouterInfos[r->GetIdentHash ()] = r;
2016-02-22 15:27:43 +00:00
if (r->IsFloodfill () && r->IsReachable ()) // floodfill must be reachable
2016-02-11 00:00:00 +00:00
m_Floodfills.push_back (r);
2016-02-22 15:27:43 +00:00
}
else
{
LogPrint(eLogWarning, "NetDb: RI from ", path, " is invalid. Delete");
2016-02-11 00:00:00 +00:00
i2p::fs::Remove(path);
2014-01-29 18:36:20 +00:00
}
2016-02-11 00:00:00 +00:00
return true;
}
2016-07-15 17:52:55 +00:00
void NetDb::VisitLeaseSets(LeaseSetVisitor v)
{
std::unique_lock<std::mutex> lock(m_LeaseSetsMutex);
for ( auto & entry : m_LeaseSets)
v(entry.first, entry.second);
}
2016-08-29 18:16:29 +00:00
void NetDb::VisitStoredRouterInfos(RouterInfoVisitor v)
{
m_Storage.Iterate([v] (const std::string & filename) {
2016-08-31 00:02:27 +00:00
auto ri = std::make_shared<i2p::data::RouterInfo>(filename);
2016-08-29 18:16:29 +00:00
v(ri);
});
}
void NetDb::VisitRouterInfos(RouterInfoVisitor v)
{
std::unique_lock<std::mutex> lock(m_RouterInfosMutex);
for ( const auto & item : m_RouterInfos )
2016-08-30 23:59:24 +00:00
v(item.second);
2016-08-29 18:16:29 +00:00
}
2016-08-30 19:54:53 +00:00
size_t NetDb::VisitRandomRouterInfos(RouterInfoFilter filter, RouterInfoVisitor v, size_t n)
{
std::vector<std::shared_ptr<const RouterInfo> > found;
const size_t max_iters_per_cyle = 3;
size_t iters = max_iters_per_cyle;
2016-09-01 19:54:48 +00:00
while(n > 0)
2016-08-30 19:54:53 +00:00
{
std::unique_lock<std::mutex> lock(m_RouterInfosMutex);
uint32_t idx = rand () % m_RouterInfos.size ();
uint32_t i = 0;
for (const auto & it : m_RouterInfos) {
if(i >= idx) // are we at the random start point?
{
// yes, check if we want this one
2016-08-30 23:59:24 +00:00
if(filter(it.second))
2016-08-30 19:54:53 +00:00
{
// we have a match
--n;
found.push_back(it.second);
// reset max iterations per cycle
iters = max_iters_per_cyle;
break;
}
}
else // not there yet
++i;
}
2016-09-01 19:54:48 +00:00
// we have enough
if(n == 0) break;
2016-08-30 19:54:53 +00:00
--iters;
// have we tried enough this cycle ?
if(!iters) {
// yes let's try the next cycle
--n;
iters = max_iters_per_cyle;
}
}
// visit the ones we found
size_t visited = 0;
for(const auto & ri : found ) {
2016-08-30 23:59:24 +00:00
v(ri);
2016-08-30 19:54:53 +00:00
++visited;
}
return visited;
}
2016-07-15 17:52:55 +00:00
2016-02-11 00:00:00 +00:00
void NetDb::Load ()
{
2014-01-31 18:08:33 +00:00
// make sure we cleanup netDb from previous attempts
m_RouterInfos.clear ();
2014-03-19 18:08:09 +00:00
m_Floodfills.clear ();
2014-01-31 18:08:33 +00:00
2016-02-11 00:00:00 +00:00
m_LastLoad = i2p::util::GetSecondsSinceEpoch();
std::vector<std::string> files;
m_Storage.Traverse(files);
2016-08-05 18:23:54 +00:00
for (const auto& path : files)
2016-02-11 00:00:00 +00:00
LoadRouterInfo(path);
LogPrint (eLogInfo, "NetDb: ", m_RouterInfos.size(), " routers loaded (", m_Floodfills.size (), " floodfils)");
2013-11-13 12:59:21 +00:00
}
void NetDb::SaveUpdated ()
2013-11-20 12:46:09 +00:00
{
2016-02-11 00:00:00 +00:00
int updatedCount = 0, deletedCount = 0;
2014-01-23 01:19:39 +00:00
auto total = m_RouterInfos.size ();
uint64_t expirationTimeout = NETDB_MAX_EXPIRATION_TIMEOUT*1000LL;
2016-02-11 00:00:00 +00:00
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch();
2016-02-24 16:31:14 +00:00
// routers don't expire if less than 90 or uptime is less than 1 hour
bool checkForExpiration = total > NETDB_MIN_ROUTERS && ts > (i2p::context.GetStartupTime () + 600)*1000LL; // 10 minutes
if (checkForExpiration && ts > (i2p::context.GetStartupTime () + 3600)*1000LL) // 1 hour
2016-02-24 16:31:14 +00:00
expirationTimeout = i2p::context.IsFloodfill () ? NETDB_FLOODFILL_EXPIRATION_TIMEOUT*1000LL :
NETDB_MIN_EXPIRATION_TIMEOUT*1000LL + (NETDB_MAX_EXPIRATION_TIMEOUT - NETDB_MIN_EXPIRATION_TIMEOUT)*1000LL*NETDB_MIN_ROUTERS/total;
2016-02-11 00:00:00 +00:00
2016-08-05 18:23:54 +00:00
for (auto& it: m_RouterInfos)
2013-12-22 16:29:57 +00:00
{
2016-02-11 00:00:00 +00:00
std::string ident = it.second->GetIdentHashBase64();
std::string path = m_Storage.Path(ident);
if (it.second->IsUpdated ())
{
2016-02-11 00:00:00 +00:00
it.second->SaveToFile (path);
2013-11-20 12:46:09 +00:00
it.second->SetUpdated (false);
2015-02-02 14:40:03 +00:00
it.second->SetUnreachable (false);
it.second->DeleteBuffer ();
2016-02-11 00:00:00 +00:00
updatedCount++;
continue;
2013-11-20 12:46:09 +00:00
}
2016-02-24 16:31:14 +00:00
// find & mark expired routers
if (it.second->UsesIntroducer ())
{
2016-02-24 16:31:14 +00:00
if (ts > it.second->GetTimestamp () + NETDB_INTRODUCEE_EXPIRATION_TIMEOUT*1000LL)
2014-08-19 15:01:11 +00:00
// RouterInfo expires after 1 hour if uses introducer
2016-02-24 16:31:14 +00:00
it.second->SetUnreachable (true);
2016-02-11 00:00:00 +00:00
}
2016-02-24 16:31:14 +00:00
else if (checkForExpiration && ts > it.second->GetTimestamp () + expirationTimeout)
it.second->SetUnreachable (true);
2016-02-11 00:00:00 +00:00
if (it.second->IsUnreachable ())
{
2016-02-11 00:00:00 +00:00
// delete RI file
m_Storage.Remove(ident);
2016-02-11 00:00:00 +00:00
deletedCount++;
if (total - deletedCount < NETDB_MIN_ROUTERS) checkForExpiration = false;
2016-02-11 00:00:00 +00:00
}
} // m_RouterInfos iteration
2016-02-11 00:00:00 +00:00
if (updatedCount > 0)
LogPrint (eLogInfo, "NetDb: saved ", updatedCount, " new/updated routers");
2013-12-22 16:29:57 +00:00
if (deletedCount > 0)
2014-11-21 18:29:19 +00:00
{
2016-02-11 00:00:00 +00:00
LogPrint (eLogInfo, "NetDb: deleting ", deletedCount, " unreachable routers");
2014-11-21 18:29:19 +00:00
// clean up RouterInfos table
{
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
for (auto it = m_RouterInfos.begin (); it != m_RouterInfos.end ();)
{
if (it->second->IsUnreachable ())
{
it->second->SaveProfile ();
it = m_RouterInfos.erase (it);
continue;
}
2016-08-05 18:23:54 +00:00
++it;
}
}
// clean up expired floodfiils
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
for (auto it = m_Floodfills.begin (); it != m_Floodfills.end ();)
if ((*it)->IsUnreachable ())
it = m_Floodfills.erase (it);
else
2016-08-05 18:23:54 +00:00
++it;
}
2014-11-21 18:29:19 +00:00
}
2013-11-20 12:46:09 +00:00
}
2015-01-14 21:11:09 +00:00
void NetDb::RequestDestination (const IdentHash& destination, RequestedDestination::RequestComplete requestComplete)
2014-01-03 02:22:48 +00:00
{
2015-04-09 16:45:00 +00:00
auto dest = m_Requests.CreateRequest (destination, false, requestComplete); // non-exploratory
if (!dest)
2015-02-03 21:14:33 +00:00
{
2016-01-18 00:00:00 +00:00
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already");
2015-04-09 16:45:00 +00:00
return;
2015-02-10 03:19:29 +00:00
}
2015-04-09 16:45:00 +00:00
2015-04-10 23:49:58 +00:00
auto floodfill = GetClosestFloodfill (destination, dest->GetExcludedPeers ());
if (floodfill)
transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
else
{
2016-01-18 00:00:00 +00:00
LogPrint (eLogError, "NetDb: ", destination.ToBase64(), " destination requested, but no floodfills found");
2015-04-09 16:45:00 +00:00
m_Requests.RequestComplete (destination, nullptr);
}
2013-11-13 12:59:21 +00:00
}
2016-11-14 17:05:44 +00:00
void NetDb::RequestDestinationFrom (const IdentHash& destination, const IdentHash & from, bool exploritory, RequestedDestination::RequestComplete requestComplete)
{
auto dest = m_Requests.CreateRequest (destination, exploritory, requestComplete); // non-exploratory
if (!dest)
{
LogPrint (eLogWarning, "NetDb: destination ", destination.ToBase64(), " is requested already");
return;
}
LogPrint(eLogInfo, "NetDb: destination ", destination.ToBase64(), " being requested directly from ", from.ToBase64());
// direct
transports.SendMessage (from, dest->CreateRequestMessage (nullptr, nullptr));
}
2013-12-22 16:29:57 +00:00
2015-07-04 01:27:40 +00:00
void NetDb::HandleDatabaseStoreMsg (std::shared_ptr<const I2NPMessage> m)
{
const uint8_t * buf = m->GetPayload ();
2015-01-02 04:00:33 +00:00
size_t len = m->GetSize ();
2015-04-12 20:59:59 +00:00
IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET);
if (ident.IsZero ())
{
2017-01-31 01:36:35 +00:00
LogPrint (eLogDebug, "NetDb: database store with zero ident, dropped");
2015-04-12 20:59:59 +00:00
return;
}
2015-01-03 02:11:40 +00:00
uint32_t replyToken = bufbe32toh (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET);
size_t offset = DATABASE_STORE_HEADER_SIZE;
if (replyToken)
2015-01-30 20:13:09 +00:00
{
auto deliveryStatus = CreateDeliveryStatusMsg (replyToken);
2015-01-30 20:13:09 +00:00
uint32_t tunnelID = bufbe32toh (buf + offset);
offset += 4;
2015-01-30 20:13:09 +00:00
if (!tunnelID) // send response directly
2015-06-24 14:45:58 +00:00
transports.SendMessage (buf + offset, deliveryStatus);
2015-01-30 20:13:09 +00:00
else
{
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = pool ? pool->GetNextOutboundTunnel () : nullptr;
if (outbound)
2015-06-24 14:45:58 +00:00
outbound->SendTunnelDataMsg (buf + offset, tunnelID, deliveryStatus);
2015-01-30 20:13:09 +00:00
else
2017-01-31 01:36:35 +00:00
LogPrint (eLogWarning, "NetDb: no outbound tunnels for DatabaseStore reply found");
2015-01-30 20:13:09 +00:00
}
offset += 32;
2015-01-30 20:13:09 +00:00
}
2016-06-30 17:15:36 +00:00
// we must send reply back before this check
if (ident == i2p::context.GetIdentHash ())
{
2017-01-31 01:36:35 +00:00
LogPrint (eLogDebug, "NetDb: database store with own RouterInfo received, dropped");
2016-06-30 17:15:36 +00:00
return;
}
2016-02-17 20:36:55 +00:00
size_t payloadOffset = offset;
bool updated = false;
2015-01-03 02:11:40 +00:00
if (buf[DATABASE_STORE_TYPE_OFFSET]) // type
2013-11-19 01:37:38 +00:00
{
2016-06-30 21:24:33 +00:00
LogPrint (eLogDebug, "NetDb: store request: LeaseSet for ", ident.ToBase32());
2016-02-17 20:36:55 +00:00
updated = AddLeaseSet (ident, buf + offset, len - offset, m->from);
}
else
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: store request: RouterInfo");
size_t size = bufbe16toh (buf + offset);
2015-02-03 01:15:49 +00:00
offset += 2;
if (size > 2048 || size > len - offset)
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogError, "NetDb: invalid RouterInfo length ", (int)size);
return;
2013-11-20 12:46:09 +00:00
}
2015-11-03 14:15:49 +00:00
uint8_t uncompressed[2048];
size_t uncompressedSize = m_Inflator.Inflate (buf + offset, size, uncompressed, 2048);
if (uncompressedSize && uncompressedSize < 2048)
2016-02-17 20:36:55 +00:00
updated = AddRouterInfo (ident, uncompressed, uncompressedSize);
else
{
2017-01-31 01:36:35 +00:00
LogPrint (eLogInfo, "NetDb: decompression failed ", uncompressedSize);
return;
}
2016-02-17 20:36:55 +00:00
}
if (replyToken && context.IsFloodfill () && updated)
{
// flood updated
auto floodMsg = NewI2NPShortMessage ();
uint8_t * payload = floodMsg->GetPayload ();
memcpy (payload, buf, 33); // key + type
htobe32buf (payload + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0); // zero reply token
2016-06-30 13:45:06 +00:00
size_t msgLen = len - payloadOffset;
2016-02-17 20:36:55 +00:00
floodMsg->len += DATABASE_STORE_HEADER_SIZE + msgLen;
if (floodMsg->len < floodMsg->maxLen)
{
memcpy (payload + DATABASE_STORE_HEADER_SIZE, buf + payloadOffset, msgLen);
floodMsg->FillI2NPMessageHeader (eI2NPDatabaseStore);
std::set<IdentHash> excluded;
2016-06-30 14:21:53 +00:00
excluded.insert (i2p::context.GetIdentHash ()); // don't flood to itself
2016-06-30 17:15:36 +00:00
excluded.insert (ident); // don't flood back
2016-06-30 14:21:53 +00:00
for (int i = 0; i < 3; i++)
2016-02-17 20:36:55 +00:00
{
2016-02-18 02:24:21 +00:00
auto floodfill = GetClosestFloodfill (ident, excluded);
2016-02-17 20:36:55 +00:00
if (floodfill)
2016-06-30 13:45:06 +00:00
{
auto h = floodfill->GetIdentHash();
2016-06-30 13:48:08 +00:00
LogPrint(eLogDebug, "NetDb: Flood lease set for ", ident.ToBase32(), " to ", h.ToBase64());
transports.SendMessage (h, CopyI2NPMessage(floodMsg));
excluded.insert (h);
2016-06-30 13:45:06 +00:00
}
2016-02-17 20:36:55 +00:00
else
2016-06-30 13:52:37 +00:00
break;
2016-02-17 20:36:55 +00:00
}
}
else
2016-06-30 13:45:06 +00:00
LogPrint (eLogError, "NetDb: Database store message is too long ", floodMsg->len);
}
2013-11-19 01:37:38 +00:00
}
2015-07-04 01:27:40 +00:00
void NetDb::HandleDatabaseSearchReplyMsg (std::shared_ptr<const I2NPMessage> msg)
{
2015-07-04 01:27:40 +00:00
const uint8_t * buf = msg->GetPayload ();
char key[48];
int l = i2p::data::ByteStreamToBase64 (buf, 32, key, 48);
key[l] = 0;
int num = buf[32]; // num
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: DatabaseSearchReply for ", key, " num=", num);
2015-04-09 16:45:00 +00:00
IdentHash ident (buf);
auto dest = m_Requests.FindRequest (ident);
if (dest)
2014-01-05 14:53:44 +00:00
{
bool deleteDest = true;
2014-01-05 14:53:44 +00:00
if (num > 0)
{
auto pool = i2p::tunnel::tunnels.GetExploratoryPool ();
2015-01-11 22:40:11 +00:00
auto outbound = pool ? pool->GetNextOutboundTunnel () : nullptr;
auto inbound = pool ? pool->GetNextInboundTunnel () : nullptr;
2014-10-15 00:52:40 +00:00
if (!dest->IsExploratory ())
{
// reply to our destination. Try other floodfills
2016-11-14 17:05:44 +00:00
if (outbound && inbound)
2014-10-15 00:52:40 +00:00
{
2015-02-12 16:40:42 +00:00
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
2014-10-15 00:52:40 +00:00
auto count = dest->GetExcludedPeers ().size ();
if (count < 7)
{
auto nextFloodfill = GetClosestFloodfill (dest->GetDestination (), dest->GetExcludedPeers ());
if (nextFloodfill)
{
// tell floodfill about us
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
nextFloodfill->GetIdentHash (), 0,
2015-11-03 14:15:49 +00:00
CreateDatabaseStoreMsg ()
});
2014-10-15 00:52:40 +00:00
// request destination
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: Try ", key, " at ", count, " floodfill ", nextFloodfill->GetIdentHash ().ToBase64 ());
2014-10-15 00:52:40 +00:00
auto msg = dest->CreateRequestMessage (nextFloodfill, inbound);
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
2015-06-22 19:47:45 +00:00
nextFloodfill->GetIdentHash (), 0, msg
2014-10-15 00:52:40 +00:00
});
deleteDest = false;
}
}
else
2015-12-18 04:03:07 +00:00
LogPrint (eLogWarning, "NetDb: ", key, " was not found on ", count, " floodfills");
2015-02-12 16:40:42 +00:00
if (msgs.size () > 0)
outbound->SendTunnelDataMsg (msgs);
2014-10-15 00:52:40 +00:00
}
}
if (deleteDest)
2014-10-15 00:52:40 +00:00
// no more requests for the destinationation. delete it
2015-04-09 16:45:00 +00:00
m_Requests.RequestComplete (ident, nullptr);
2014-01-05 14:53:44 +00:00
}
else
// no more requests for detination possible. delete it
2015-04-09 16:45:00 +00:00
m_Requests.RequestComplete (ident, nullptr);
2014-01-05 14:53:44 +00:00
}
2016-11-14 17:05:44 +00:00
else if(!m_FloodfillBootstrap)
2015-12-18 04:03:07 +00:00
LogPrint (eLogWarning, "NetDb: requested destination for ", key, " not found");
2015-01-10 14:07:07 +00:00
// try responses
for (int i = 0; i < num; i++)
{
2015-07-04 01:27:40 +00:00
const uint8_t * router = buf + 33 + i*32;
2015-01-10 14:07:07 +00:00
char peerHash[48];
int l1 = i2p::data::ByteStreamToBase64 (router, 32, peerHash, 48);
peerHash[l1] = 0;
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: ", i, ": ", peerHash);
2015-01-10 14:07:07 +00:00
auto r = FindRouter (router);
if (!r || i2p::util::GetMillisecondsSinceEpoch () > r->GetTimestamp () + 3600*1000LL)
{
// router with ident not found or too old (1 hour)
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: found new/outdated router. Requesting RouterInfo ...");
2016-11-14 17:05:44 +00:00
if(m_FloodfillBootstrap)
RequestDestinationFrom(router, m_FloodfillBootstrap->GetIdentHash(), true);
else
RequestDestination (router);
2015-01-10 14:07:07 +00:00
}
else
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: [:|||:]");
2014-08-10 13:04:17 +00:00
}
}
2015-07-04 01:27:40 +00:00
void NetDb::HandleDatabaseLookupMsg (std::shared_ptr<const I2NPMessage> msg)
{
2015-07-04 01:27:40 +00:00
const uint8_t * buf = msg->GetPayload ();
2015-04-12 20:59:59 +00:00
IdentHash ident (buf);
if (ident.IsZero ())
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogError, "NetDb: DatabaseLookup for zero ident. Ignored");
2015-04-12 20:59:59 +00:00
return;
}
char key[48];
int l = i2p::data::ByteStreamToBase64 (buf, 32, key, 48);
key[l] = 0;
IdentHash replyIdent(buf + 32);
2016-07-15 16:49:45 +00:00
uint8_t flag = buf[64];
2017-12-07 13:26:28 +00:00
LogPrint (eLogDebug, "NetDb: DatabaseLookup for ", key, " received flags=", (int)flag);
2015-02-03 03:34:55 +00:00
uint8_t lookupType = flag & DATABASE_LOOKUP_TYPE_FLAGS_MASK;
2016-06-29 18:57:42 +00:00
const uint8_t * excluded = buf + 65;
uint32_t replyTunnelID = 0;
2015-02-03 01:15:49 +00:00
if (flag & DATABASE_LOOKUP_DELIVERY_FLAG) //reply to tunnel
{
2016-07-15 16:49:45 +00:00
replyTunnelID = bufbe32toh (excluded);
excluded += 4;
}
uint16_t numExcluded = bufbe16toh (excluded);
excluded += 2;
if (numExcluded > 512)
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogWarning, "NetDb: number of excluded peers", numExcluded, " exceeds 512");
2016-07-15 16:49:45 +00:00
return;
}
2015-02-02 00:58:26 +00:00
2015-06-22 02:29:50 +00:00
std::shared_ptr<I2NPMessage> replyMsg;
2015-02-03 03:34:55 +00:00
if (lookupType == DATABASE_LOOKUP_TYPE_EXPLORATORY_LOOKUP)
2014-07-25 02:01:07 +00:00
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogInfo, "NetDb: exploratory close to ", key, " ", numExcluded, " excluded");
std::set<IdentHash> excludedRouters;
for (int i = 0; i < numExcluded; i++)
{
excludedRouters.insert (excluded);
excluded += 32;
}
2015-02-02 00:58:26 +00:00
std::vector<IdentHash> routers;
for (int i = 0; i < 3; i++)
{
2015-04-12 20:59:59 +00:00
auto r = GetClosestNonFloodfill (ident, excludedRouters);
2015-02-03 03:34:55 +00:00
if (r)
{
routers.push_back (r->GetIdentHash ());
excludedRouters.insert (r->GetIdentHash ());
}
2015-02-02 00:58:26 +00:00
}
2015-11-03 14:15:49 +00:00
replyMsg = CreateDatabaseSearchReply (ident, routers);
2015-02-03 03:34:55 +00:00
}
2014-07-31 16:59:43 +00:00
else
2015-02-03 03:34:55 +00:00
{
2015-04-12 19:54:28 +00:00
if (lookupType == DATABASE_LOOKUP_TYPE_ROUTERINFO_LOOKUP ||
lookupType == DATABASE_LOOKUP_TYPE_NORMAL_LOOKUP)
{
2015-04-12 20:59:59 +00:00
auto router = FindRouter (ident);
2015-04-12 19:54:28 +00:00
if (router)
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: requested RouterInfo ", key, " found");
2015-04-12 19:54:28 +00:00
router->LoadBuffer ();
if (router->GetBuffer ())
2015-11-03 14:15:49 +00:00
replyMsg = CreateDatabaseStoreMsg (router);
2015-04-12 19:54:28 +00:00
}
2015-02-03 03:34:55 +00:00
}
2015-04-12 19:54:28 +00:00
if (!replyMsg && (lookupType == DATABASE_LOOKUP_TYPE_LEASESET_LOOKUP ||
lookupType == DATABASE_LOOKUP_TYPE_NORMAL_LOOKUP))
2015-02-03 03:34:55 +00:00
{
2015-04-12 20:59:59 +00:00
auto leaseSet = FindLeaseSet (ident);
2016-06-29 18:56:00 +00:00
if (!leaseSet)
{
// no lease set found
2016-06-30 13:45:06 +00:00
LogPrint(eLogDebug, "NetDb: requested LeaseSet not found for ", ident.ToBase32());
2016-06-29 18:56:00 +00:00
}
2016-06-29 21:42:26 +00:00
else if (!leaseSet->IsExpired ()) // we don't send back our LeaseSets
2015-02-03 03:34:55 +00:00
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogDebug, "NetDb: requested LeaseSet ", key, " found");
2015-11-03 14:15:49 +00:00
replyMsg = CreateDatabaseStoreMsg (leaseSet);
2015-02-03 03:34:55 +00:00
}
}
2015-04-12 19:54:28 +00:00
2015-02-03 03:34:55 +00:00
if (!replyMsg)
2016-12-05 23:39:01 +00:00
{
std::set<IdentHash> excludedRouters;
const uint8_t * exclude_ident = excluded;
for (int i = 0; i < numExcluded; i++)
{
excludedRouters.insert (exclude_ident);
exclude_ident += 32;
2015-06-11 15:43:35 +00:00
}
2016-12-05 23:39:01 +00:00
auto closestFloodfills = GetClosestFloodfills (ident, 3, excludedRouters, true);
if (closestFloodfills.empty ())
LogPrint (eLogWarning, "NetDb: Requested ", key, " not found, ", numExcluded, " peers excluded");
2016-03-22 17:10:02 +00:00
replyMsg = CreateDatabaseSearchReply (ident, closestFloodfills);
}
2015-02-03 03:34:55 +00:00
}
excluded += numExcluded * 32;
if (replyMsg)
{
if (replyTunnelID)
{
// encryption might be used though tunnel only
2016-07-15 16:49:45 +00:00
if (flag & DATABASE_LOOKUP_ENCRYPTION_FLAG) // encrypted reply requested
{
2015-07-04 01:27:40 +00:00
const uint8_t * sessionKey = excluded;
2016-07-15 16:49:45 +00:00
const uint8_t numTags = excluded[32];
if (numTags)
{
2016-07-15 17:52:55 +00:00
const i2p::garlic::SessionTag sessionTag(excluded + 33); // take first tag
i2p::garlic::GarlicRoutingSession garlic (sessionKey, sessionTag);
replyMsg = garlic.WrapSingleMessage (replyMsg);
2016-07-15 16:49:45 +00:00
if(replyMsg == nullptr) LogPrint(eLogError, "NetDb: failed to wrap message");
}
2016-07-15 16:49:45 +00:00
else
LogPrint(eLogWarning, "NetDb: encrypted reply requested but no tags provided");
}
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr;
if (outbound)
outbound->SendTunnelDataMsg (replyIdent, replyTunnelID, replyMsg);
else
transports.SendMessage (replyIdent, i2p::CreateTunnelGatewayMsg (replyTunnelID, replyMsg));
}
else
transports.SendMessage (replyIdent, replyMsg);
}
}
2014-06-17 02:30:34 +00:00
void NetDb::Explore (int numDestinations)
{
2014-07-03 17:41:36 +00:00
// new requests
2014-06-17 02:30:34 +00:00
auto exploratoryPool = i2p::tunnel::tunnels.GetExploratoryPool ();
2015-01-10 21:08:13 +00:00
auto outbound = exploratoryPool ? exploratoryPool->GetNextOutboundTunnel () : nullptr;
auto inbound = exploratoryPool ? exploratoryPool->GetNextInboundTunnel () : nullptr;
2014-06-17 02:30:34 +00:00
bool throughTunnels = outbound && inbound;
uint8_t randomHash[32];
2014-06-17 02:30:34 +00:00
std::vector<i2p::tunnel::TunnelMessageBlock> msgs;
2015-12-18 04:03:07 +00:00
LogPrint (eLogInfo, "NetDb: exploring new ", numDestinations, " routers ...");
2014-06-17 02:30:34 +00:00
for (int i = 0; i < numDestinations; i++)
{
2015-11-03 14:15:49 +00:00
RAND_bytes (randomHash, 32);
2015-04-09 16:45:00 +00:00
auto dest = m_Requests.CreateRequest (randomHash, true); // exploratory
if (!dest)
{
2015-12-18 04:03:07 +00:00
LogPrint (eLogWarning, "NetDb: exploratory destination is requested already");
2015-04-09 16:45:00 +00:00
return;
2015-02-10 03:19:29 +00:00
}
2014-06-17 02:30:34 +00:00
auto floodfill = GetClosestFloodfill (randomHash, dest->GetExcludedPeers ());
2016-12-14 15:59:36 +00:00
if (floodfill)
2014-02-12 03:19:51 +00:00
{
if (i2p::transport::transports.IsConnected (floodfill->GetIdentHash ()))
throughTunnels = false;
2014-06-17 02:30:34 +00:00
if (throughTunnels)
{
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
floodfill->GetIdentHash (), 0,
2015-11-03 14:15:49 +00:00
CreateDatabaseStoreMsg () // tell floodfill about us
2014-06-17 02:30:34 +00:00
});
msgs.push_back (i2p::tunnel::TunnelMessageBlock
{
i2p::tunnel::eDeliveryTypeRouter,
floodfill->GetIdentHash (), 0,
2015-06-22 19:47:45 +00:00
dest->CreateRequestMessage (floodfill, inbound) // explore
2014-06-17 02:30:34 +00:00
});
}
else
i2p::transport::transports.SendMessage (floodfill->GetIdentHash (), dest->CreateRequestMessage (floodfill->GetIdentHash ()));
2013-11-19 01:37:38 +00:00
}
2014-02-12 03:19:51 +00:00
else
2015-04-09 16:45:00 +00:00
m_Requests.RequestComplete (randomHash, nullptr);
}
2014-06-17 02:30:34 +00:00
if (throughTunnels && msgs.size () > 0)
outbound->SendTunnelDataMsg (msgs);
2013-11-19 01:37:38 +00:00
}
2014-02-13 03:02:39 +00:00
void NetDb::Publish ()
{
2016-01-02 22:23:20 +00:00
i2p::context.UpdateStats (); // for floodfill
2014-02-13 03:02:39 +00:00
std::set<IdentHash> excluded; // TODO: fill up later
2015-01-29 02:01:16 +00:00
for (int i = 0; i < 2; i++)
2014-03-16 12:00:34 +00:00
{
auto floodfill = GetClosestFloodfill (i2p::context.GetRouterInfo ().GetIdentHash (), excluded);
if (floodfill)
{
2015-11-03 14:15:49 +00:00
uint32_t replyToken;
RAND_bytes ((uint8_t *)&replyToken, 4);
2015-12-18 04:03:07 +00:00
LogPrint (eLogInfo, "NetDb: Publishing our RouterInfo to ", i2p::data::GetIdentHashAbbreviation(floodfill->GetIdentHash ()), ". reply token=", replyToken);
2015-11-03 14:15:49 +00:00
transports.SendMessage (floodfill->GetIdentHash (), CreateDatabaseStoreMsg (i2p::context.GetSharedRouterInfo (), replyToken));
2014-03-16 12:00:34 +00:00
excluded.insert (floodfill->GetIdentHash ());
}
2014-02-13 03:02:39 +00:00
}
2015-02-10 03:19:29 +00:00
}
2013-11-19 01:37:38 +00:00
2014-11-20 21:20:02 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter () const
{
return GetRandomRouter (
2014-11-20 21:20:02 +00:00
[](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden ();
});
}
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const
2014-09-25 01:45:19 +00:00
{
return GetRandomRouter (
2014-11-20 21:20:02 +00:00
[compatibleWith](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router != compatibleWith &&
2014-10-02 18:43:42 +00:00
router->IsCompatible (*compatibleWith);
});
2014-09-25 01:45:19 +00:00
}
2016-12-02 16:17:22 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetRandomPeerTestRouter (bool v4only) const
2015-02-26 19:17:16 +00:00
{
return GetRandomRouter (
2016-12-02 16:17:22 +00:00
[v4only](std::shared_ptr<const RouterInfo> router)->bool
2015-02-26 19:17:16 +00:00
{
2016-12-02 16:17:22 +00:00
return !router->IsHidden () && router->IsPeerTesting () && router->IsSSU (v4only);
2015-02-26 19:17:16 +00:00
});
}
2015-02-27 02:05:35 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetRandomIntroducer () const
{
return GetRandomRouter (
[](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router->IsIntroducer ();
});
}
std::shared_ptr<const RouterInfo> NetDb::GetHighBandwidthRandomRouter (std::shared_ptr<const RouterInfo> compatibleWith) const
{
return GetRandomRouter (
2014-11-20 21:20:02 +00:00
[compatibleWith](std::shared_ptr<const RouterInfo> router)->bool
{
return !router->IsHidden () && router != compatibleWith &&
router->IsCompatible (*compatibleWith) &&
2015-05-04 17:01:27 +00:00
(router->GetCaps () & RouterInfo::eHighBandwidth);
});
}
2014-09-25 01:45:19 +00:00
template<typename Filter>
2014-11-20 21:20:02 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouter (Filter filter) const
2013-11-13 12:59:21 +00:00
{
2016-06-01 00:00:00 +00:00
if (m_RouterInfos.empty())
return 0;
2016-06-17 15:03:33 +00:00
uint32_t ind = rand () % m_RouterInfos.size ();
for (int j = 0; j < 2; j++)
2013-11-19 01:37:38 +00:00
{
uint32_t i = 0;
2014-11-21 18:29:19 +00:00
std::unique_lock<std::mutex> l(m_RouterInfosMutex);
2016-08-05 18:23:54 +00:00
for (const auto& it: m_RouterInfos)
{
if (i >= ind)
{
if (!it.second->IsUnreachable () && filter (it.second))
2014-11-20 21:20:02 +00:00
return it.second;
}
else
i++;
}
// we couldn't find anything, try second pass
ind = 0;
2013-11-19 01:37:38 +00:00
}
2014-03-19 18:08:09 +00:00
return nullptr; // seems we have too few routers
2013-11-13 12:59:21 +00:00
}
2014-09-25 01:45:19 +00:00
2015-07-04 01:27:40 +00:00
void NetDb::PostI2NPMsg (std::shared_ptr<const I2NPMessage> msg)
2013-11-20 12:46:09 +00:00
{
if (msg) m_Queue.Put (msg);
}
2014-01-04 02:24:20 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetClosestFloodfill (const IdentHash& destination,
const std::set<IdentHash>& excluded, bool closeThanUsOnly) const
2014-01-04 02:24:20 +00:00
{
std::shared_ptr<const RouterInfo> r;
2014-01-04 02:24:20 +00:00
XORMetric minMetric;
IdentHash destKey = CreateRoutingKey (destination);
if (closeThanUsOnly)
minMetric = destKey ^ i2p::context.GetIdentHash ();
else
minMetric.SetMax ();
2014-10-06 01:59:05 +00:00
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
2016-08-05 18:23:54 +00:00
for (const auto& it: m_Floodfills)
2014-01-04 02:24:20 +00:00
{
2015-04-10 23:49:58 +00:00
if (!it->IsUnreachable ())
2014-01-04 02:24:20 +00:00
{
XORMetric m = destKey ^ it->GetIdentHash ();
2015-04-10 23:49:58 +00:00
if (m < minMetric && !excluded.count (it->GetIdentHash ()))
2014-01-04 02:24:20 +00:00
{
minMetric = m;
r = it;
2014-01-04 02:24:20 +00:00
}
}
}
return r;
}
2014-01-22 20:32:50 +00:00
2015-06-11 15:43:35 +00:00
std::vector<IdentHash> NetDb::GetClosestFloodfills (const IdentHash& destination, size_t num,
std::set<IdentHash>& excluded, bool closeThanUsOnly) const
2015-04-10 20:15:13 +00:00
{
struct Sorted
{
std::shared_ptr<const RouterInfo> r;
XORMetric metric;
bool operator< (const Sorted& other) const { return metric < other.metric; };
};
std::set<Sorted> sorted;
IdentHash destKey = CreateRoutingKey (destination);
XORMetric ourMetric;
if (closeThanUsOnly) ourMetric = destKey ^ i2p::context.GetIdentHash ();
2015-04-10 20:15:13 +00:00
{
std::unique_lock<std::mutex> l(m_FloodfillsMutex);
2016-08-05 18:23:54 +00:00
for (const auto& it: m_Floodfills)
2015-04-10 20:15:13 +00:00
{
if (!it->IsUnreachable ())
{
XORMetric m = destKey ^ it->GetIdentHash ();
if (closeThanUsOnly && ourMetric < m) continue;
2015-04-10 20:15:13 +00:00
if (sorted.size () < num)
sorted.insert ({it, m});
else if (m < sorted.rbegin ()->metric)
{
sorted.insert ({it, m});
sorted.erase (std::prev (sorted.end ()));
}
}
}
}
std::vector<IdentHash> res;
size_t i = 0;
2016-08-05 18:23:54 +00:00
for (const auto& it: sorted)
2015-04-10 20:15:13 +00:00
{
if (i < num)
{
2016-08-05 18:23:54 +00:00
const auto& ident = it.r->GetIdentHash ();
2015-06-11 15:43:35 +00:00
if (!excluded.count (ident))
{
res.push_back (ident);
i++;
}
2015-04-10 20:15:13 +00:00
}
else
break;
}
return res;
}
2016-06-17 15:03:33 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetRandomRouterInFamily(const std::string & fam) const {
return GetRandomRouter(
[fam](std::shared_ptr<const RouterInfo> router)->bool
{
return router->IsFamily(fam);
});
}
2015-02-03 03:34:55 +00:00
std::shared_ptr<const RouterInfo> NetDb::GetClosestNonFloodfill (const IdentHash& destination,
const std::set<IdentHash>& excluded) const
{
std::shared_ptr<const RouterInfo> r;
XORMetric minMetric;
IdentHash destKey = CreateRoutingKey (destination);
minMetric.SetMax ();
// must be called from NetDb thread only
2016-08-05 18:23:54 +00:00
for (const auto& it: m_RouterInfos)
2015-02-03 03:34:55 +00:00
{
2015-04-10 23:49:58 +00:00
if (!it.second->IsFloodfill ())
2015-02-03 03:34:55 +00:00
{
XORMetric m = destKey ^ it.first;
2015-04-10 23:49:58 +00:00
if (m < minMetric && !excluded.count (it.first))
2015-02-03 03:34:55 +00:00
{
minMetric = m;
r = it.second;
}
}
}
return r;
}
2014-07-31 16:59:43 +00:00
void NetDb::ManageLeaseSets ()
{
2016-02-08 00:45:06 +00:00
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
2014-07-31 16:59:43 +00:00
for (auto it = m_LeaseSets.begin (); it != m_LeaseSets.end ();)
{
if (ts > it->second->GetExpirationTime () - LEASE_ENDDATE_THRESHOLD)
2014-07-31 16:59:43 +00:00
{
LogPrint (eLogInfo, "NetDb: LeaseSet ", it->second->GetIdentHash ().ToBase64 (), " expired");
2014-07-31 16:59:43 +00:00
it = m_LeaseSets.erase (it);
}
else
2016-08-05 18:23:54 +00:00
++it;
2014-07-31 16:59:43 +00:00
}
}
2013-11-13 12:59:21 +00:00
}
}