i2pd/Transports.cpp

789 lines
23 KiB
C++
Raw Normal View History

2013-10-27 15:26:39 +00:00
#include "Log.h"
2015-11-03 14:15:49 +00:00
#include "Crypto.h"
2013-10-27 15:26:39 +00:00
#include "RouterContext.h"
#include "I2NPProtocol.h"
#include "NetDb.h"
#include "Transports.h"
#include "Config.h"
2016-11-01 17:57:25 +00:00
#ifdef WITH_EVENTS
2016-10-20 13:12:15 +00:00
#include "Event.h"
2016-11-01 16:16:18 +00:00
#include "util.h"
2016-11-01 17:57:25 +00:00
#endif
2013-10-27 15:26:39 +00:00
using namespace i2p::data;
namespace i2p
{
namespace transport
2013-10-27 15:26:39 +00:00
{
2014-10-20 19:19:56 +00:00
DHKeysPairSupplier::DHKeysPairSupplier (int size):
m_QueueSize (size), m_IsRunning (false), m_Thread (nullptr)
{
}
2014-04-04 20:29:40 +00:00
DHKeysPairSupplier::~DHKeysPairSupplier ()
{
Stop ();
}
void DHKeysPairSupplier::Start ()
{
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&DHKeysPairSupplier::Run, this));
}
void DHKeysPairSupplier::Stop ()
{
m_IsRunning = false;
m_Acquired.notify_one ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
}
void DHKeysPairSupplier::Run ()
{
while (m_IsRunning)
{
int num, total = 0;
while ((num = m_QueueSize - (int)m_Queue.size ()) > 0 && total < 20)
{
2014-04-04 20:29:40 +00:00
CreateDHKeysPairs (num);
total += num;
}
if (total >= 20)
{
LogPrint (eLogWarning, "Transports: ", total, " DH keys generated at the time");
std::this_thread::sleep_for (std::chrono::seconds(1)); // take a break
}
else
{
std::unique_lock<std::mutex> l(m_AcquiredMutex);
m_Acquired.wait (l); // wait for element gets aquired
}
2014-04-04 20:29:40 +00:00
}
}
void DHKeysPairSupplier::CreateDHKeysPairs (int num)
{
if (num > 0)
{
for (int i = 0; i < num; i++)
{
2015-11-03 14:15:49 +00:00
auto pair = std::make_shared<i2p::crypto::DHKeys> ();
pair->GenerateKeys ();
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_AcquiredMutex);
2014-04-04 20:29:40 +00:00
m_Queue.push (pair);
}
}
}
2015-11-03 14:15:49 +00:00
std::shared_ptr<i2p::crypto::DHKeys> DHKeysPairSupplier::Acquire ()
2014-04-04 20:29:40 +00:00
{
{
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_AcquiredMutex);
2016-01-28 03:09:35 +00:00
if (!m_Queue.empty ())
{
auto pair = m_Queue.front ();
m_Queue.pop ();
m_Acquired.notify_one ();
return pair;
}
2014-04-04 20:29:40 +00:00
}
2016-01-28 03:09:35 +00:00
// queue is empty, create new
auto pair = std::make_shared<i2p::crypto::DHKeys> ();
pair->GenerateKeys ();
return pair;
2014-04-04 20:29:40 +00:00
}
2015-11-03 14:15:49 +00:00
void DHKeysPairSupplier::Return (std::shared_ptr<i2p::crypto::DHKeys> pair)
{
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_AcquiredMutex);
m_Queue.push (pair);
}
2013-10-27 15:26:39 +00:00
Transports transports;
Transports::Transports ():
2016-11-13 14:14:05 +00:00
m_IsOnline (true), m_IsRunning (false), m_Thread (nullptr), m_Work (m_Service),
m_PeerCleanupTimer (m_Service), m_PeerTestTimer (m_Service),
2015-03-16 23:33:59 +00:00
m_NTCPServer (nullptr), m_SSUServer (nullptr), m_DHKeysPairSupplier (5), // 5 pre-generated keys
2015-03-17 19:19:38 +00:00
m_TotalSentBytes(0), m_TotalReceivedBytes(0), m_InBandwidth (0), m_OutBandwidth (0),
m_LastInBandwidthUpdateBytes (0), m_LastOutBandwidthUpdateBytes (0), m_LastBandwidthUpdateTime (0)
2013-10-27 15:26:39 +00:00
{
}
Transports::~Transports ()
{
Stop ();
}
2016-06-17 13:02:12 +00:00
void Transports::Start (bool enableNTCP, bool enableSSU)
2013-10-27 15:26:39 +00:00
{
2014-04-04 20:29:40 +00:00
m_DHKeysPairSupplier.Start ();
2013-12-29 15:48:57 +00:00
m_IsRunning = true;
2013-10-27 15:26:39 +00:00
m_Thread = new std::thread (std::bind (&Transports::Run, this));
// create acceptors
2016-03-21 17:02:51 +00:00
auto& addresses = context.GetRouterInfo ().GetAddresses ();
2016-08-08 22:53:37 +00:00
for (const auto& address : addresses)
2013-10-27 15:26:39 +00:00
{
if (!address) continue;
if (m_NTCPServer == nullptr && enableNTCP)
2016-06-13 15:34:44 +00:00
{
2016-01-28 02:54:42 +00:00
m_NTCPServer = new NTCPServer ();
2015-01-11 22:41:56 +00:00
m_NTCPServer->Start ();
2016-06-13 15:34:44 +00:00
if (!(m_NTCPServer->IsBoundV6() || m_NTCPServer->IsBoundV4())) {
/** failed to bind to NTCP */
LogPrint(eLogError, "Transports: failed to bind to TCP");
m_NTCPServer->Stop();
delete m_NTCPServer;
m_NTCPServer = nullptr;
}
2014-02-25 00:25:26 +00:00
}
2015-01-11 22:41:56 +00:00
2016-06-27 14:24:37 +00:00
if (address->transportStyle == RouterInfo::eTransportSSU)
2014-02-25 00:25:26 +00:00
{
if (m_SSUServer == nullptr && enableSSU)
2016-06-27 14:24:37 +00:00
{
if (address->host.is_v4())
m_SSUServer = new SSUServer (address->port);
else
m_SSUServer = new SSUServer (address->host, address->port);
2016-03-21 17:02:51 +00:00
LogPrint (eLogInfo, "Transports: Start listening UDP port ", address->port);
2016-06-13 15:34:44 +00:00
try {
m_SSUServer->Start ();
} catch ( std::exception & ex ) {
LogPrint(eLogError, "Transports: Failed to bind to UDP port", address->port);
delete m_SSUServer;
m_SSUServer = nullptr;
continue;
}
2014-02-25 00:25:26 +00:00
DetectExternalIP ();
2014-01-23 21:10:33 +00:00
}
else
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: SSU server already exists");
2014-01-23 21:10:33 +00:00
}
2013-10-27 15:26:39 +00:00
}
2015-02-11 19:45:25 +00:00
m_PeerCleanupTimer.expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
m_PeerCleanupTimer.async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
2016-11-13 14:14:05 +00:00
m_PeerTestTimer.expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
m_PeerTestTimer.async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
2013-10-27 15:26:39 +00:00
}
void Transports::Stop ()
{
2015-02-11 19:45:25 +00:00
m_PeerCleanupTimer.cancel ();
2016-11-13 14:14:05 +00:00
m_PeerTestTimer.cancel ();
2015-01-13 03:53:35 +00:00
m_Peers.clear ();
2014-01-23 21:10:33 +00:00
if (m_SSUServer)
{
m_SSUServer->Stop ();
delete m_SSUServer;
2014-09-22 17:28:46 +00:00
m_SSUServer = nullptr;
2014-04-09 01:56:34 +00:00
}
2015-01-11 22:41:56 +00:00
if (m_NTCPServer)
{
m_NTCPServer->Stop ();
delete m_NTCPServer;
m_NTCPServer = nullptr;
}
2014-01-23 21:10:33 +00:00
2014-04-04 20:29:40 +00:00
m_DHKeysPairSupplier.Stop ();
2013-12-29 15:48:57 +00:00
m_IsRunning = false;
2013-10-27 15:26:39 +00:00
m_Service.stop ();
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
2014-09-22 17:28:46 +00:00
m_Thread = nullptr;
2013-10-27 15:26:39 +00:00
}
}
2013-11-29 12:52:09 +00:00
void Transports::Run ()
{
2013-12-29 15:48:57 +00:00
while (m_IsRunning)
2013-11-29 12:52:09 +00:00
{
2013-12-29 15:48:57 +00:00
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: runtime exception: ", ex.what ());
2013-12-29 15:48:57 +00:00
}
2013-11-29 12:52:09 +00:00
}
}
2015-03-17 19:19:38 +00:00
void Transports::UpdateBandwidth ()
{
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
if (m_LastBandwidthUpdateTime > 0)
{
auto delta = ts - m_LastBandwidthUpdateTime;
if (delta > 0)
{
2015-03-17 23:04:58 +00:00
m_InBandwidth = (m_TotalReceivedBytes - m_LastInBandwidthUpdateBytes)*1000/delta; // per second
m_OutBandwidth = (m_TotalSentBytes - m_LastOutBandwidthUpdateBytes)*1000/delta; // per second
2015-03-17 19:19:38 +00:00
}
}
m_LastBandwidthUpdateTime = ts;
m_LastInBandwidthUpdateBytes = m_TotalReceivedBytes;
m_LastOutBandwidthUpdateBytes = m_TotalSentBytes;
}
bool Transports::IsBandwidthExceeded () const
{
auto limit = i2p::context.GetBandwidthLimit() * 1024; // convert to bytes
2016-01-03 03:17:04 +00:00
auto bw = std::max (m_InBandwidth, m_OutBandwidth);
return bw > limit;
}
2013-10-27 15:26:39 +00:00
2015-06-17 15:41:07 +00:00
void Transports::SendMessage (const i2p::data::IdentHash& ident, std::shared_ptr<i2p::I2NPMessage> msg)
{
2016-06-13 15:34:44 +00:00
SendMessages (ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > {msg });
2015-06-17 15:41:07 +00:00
}
void Transports::SendMessages (const i2p::data::IdentHash& ident, const std::vector<std::shared_ptr<i2p::I2NPMessage> >& msgs)
2015-01-21 02:05:57 +00:00
{
2016-11-01 17:57:25 +00:00
#ifdef WITH_EVENTS
2016-11-01 14:26:40 +00:00
EmitEvent({{"type" , "transport.sendmsg"}, {"ident", ident.ToBase64()}, {"number", std::to_string(msgs.size())}});
2016-11-01 17:57:25 +00:00
#endif
2015-01-21 02:05:57 +00:00
m_Service.post (std::bind (&Transports::PostMessages, this, ident, msgs));
}
2015-01-14 02:31:39 +00:00
2015-06-17 15:41:07 +00:00
void Transports::PostMessages (i2p::data::IdentHash ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > msgs)
2015-01-21 02:05:57 +00:00
{
if (ident == i2p::context.GetRouterInfo ().GetIdentHash ())
{
// we send it to ourself
2016-08-08 22:53:37 +00:00
for (auto& it: msgs)
2016-11-15 19:11:55 +00:00
m_LoopbackHandler.PutNextMessage (it);
m_LoopbackHandler.Flush ();
2015-01-21 02:05:57 +00:00
return;
}
if(RoutesRestricted() && ! IsRestrictedPeer(ident)) return;
2015-01-21 02:05:57 +00:00
auto it = m_Peers.find (ident);
if (it == m_Peers.end ())
{
2015-04-14 14:40:46 +00:00
bool connected = false;
try
{
auto r = netdb.FindRouter (ident);
2016-01-15 21:23:03 +00:00
{
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2016-01-15 21:23:03 +00:00
it = m_Peers.insert (std::pair<i2p::data::IdentHash, Peer>(ident, { 0, r, {},
i2p::util::GetSecondsSinceEpoch (), {} })).first;
}
2015-04-14 14:40:46 +00:00
connected = ConnectToPeer (ident, it->second);
}
catch (std::exception& ex)
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: PostMessages exception:", ex.what ());
2015-04-14 14:40:46 +00:00
}
2015-06-17 15:41:07 +00:00
if (!connected) return;
2015-01-21 02:05:57 +00:00
}
if (!it->second.sessions.empty ())
2015-06-17 15:41:07 +00:00
it->second.sessions.front ()->SendI2NPMessages (msgs);
2015-01-21 02:05:57 +00:00
else
{
2016-07-12 16:37:39 +00:00
if (it->second.delayedMessages.size () < MAX_NUM_DELAYED_MESSAGES)
{
2016-08-08 22:53:37 +00:00
for (auto& it1: msgs)
2016-07-12 16:37:39 +00:00
it->second.delayedMessages.push_back (it1);
}
else
{
LogPrint (eLogWarning, "Transports: delayed messages queue size exceeds ", MAX_NUM_DELAYED_MESSAGES);
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it);
}
2015-01-21 02:05:57 +00:00
}
}
2015-01-14 02:31:39 +00:00
bool Transports::ConnectToPeer (const i2p::data::IdentHash& ident, Peer& peer)
{
if (peer.router) // we have RI already
{
if (!peer.numAttempts) // NTCP
{
peer.numAttempts++;
2015-01-16 20:25:44 +00:00
auto address = peer.router->GetNTCPAddress (!context.SupportsV6 ());
2016-03-12 00:27:43 +00:00
if (address && m_NTCPServer)
2015-01-16 20:25:44 +00:00
{
2015-02-04 14:40:00 +00:00
#if BOOST_VERSION >= 104900
2015-01-16 20:25:44 +00:00
if (!address->host.is_unspecified ()) // we have address now
2015-02-04 14:40:00 +00:00
#else
boost::system::error_code ecode;
address->host.to_string (ecode);
if (!ecode)
#endif
2015-01-16 20:25:44 +00:00
{
if (!peer.router->UsesIntroducer () && !peer.router->IsUnreachable ())
{
auto s = std::make_shared<NTCPSession> (*m_NTCPServer, peer.router);
m_NTCPServer->Connect (address->host, address->port, s);
return true;
}
}
else // we don't have address
{
2015-01-17 04:01:40 +00:00
if (address->addressString.length () > 0) // trying to resolve
2015-01-16 20:25:44 +00:00
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogDebug, "Transports: Resolving NTCP ", address->addressString);
2015-01-16 20:25:44 +00:00
NTCPResolve (address->addressString, ident);
return true;
}
}
2014-02-11 00:27:55 +00:00
}
else
2016-06-13 15:34:44 +00:00
LogPrint (eLogDebug, "Transports: NTCP address is not present for ", i2p::data::GetIdentHashAbbreviation (ident), ", trying SSU");
2013-12-29 15:48:57 +00:00
}
if (peer.numAttempts == 1)// SSU
2014-01-19 15:05:54 +00:00
{
2015-01-14 02:31:39 +00:00
peer.numAttempts++;
if (m_SSUServer && peer.router->IsSSU (!context.SupportsV6 ()))
{
auto address = peer.router->GetSSUAddress (!context.SupportsV6 ());
#if BOOST_VERSION >= 104900
if (!address->host.is_unspecified ()) // we have address now
#else
boost::system::error_code ecode;
address->host.to_string (ecode);
if (!ecode)
#endif
2015-11-25 17:51:35 +00:00
{
m_SSUServer->CreateSession (peer.router, address->host, address->port);
2015-01-14 02:31:39 +00:00
return true;
2015-11-25 17:51:35 +00:00
}
2015-12-03 20:45:01 +00:00
else // we don't have address
{
if (address->addressString.length () > 0) // trying to resolve
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogDebug, "Transports: Resolving SSU ", address->addressString);
2015-12-03 20:45:01 +00:00
SSUResolve (address->addressString, ident);
return true;
}
}
2015-01-14 02:31:39 +00:00
}
2014-01-19 15:05:54 +00:00
}
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: No NTCP or SSU addresses available");
peer.Done ();
2016-07-12 16:37:39 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2015-01-14 02:31:39 +00:00
m_Peers.erase (ident);
return false;
}
else // otherwise request RI
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogInfo, "Transports: RouterInfo for ", ident.ToBase64 (), " not found, requested");
i2p::data::netdb.RequestDestination (ident, std::bind (
&Transports::RequestComplete, this, std::placeholders::_1, ident));
2013-10-27 15:26:39 +00:00
}
2015-01-14 02:31:39 +00:00
return true;
2013-10-27 15:26:39 +00:00
}
void Transports::RequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, const i2p::data::IdentHash& ident)
{
m_Service.post (std::bind (&Transports::HandleRequestComplete, this, r, ident));
}
void Transports::HandleRequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, i2p::data::IdentHash ident)
{
2015-01-14 02:31:39 +00:00
auto it = m_Peers.find (ident);
if (it != m_Peers.end ())
{
if (r)
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogDebug, "Transports: RouterInfo for ", ident.ToBase64 (), " found, Trying to connect");
2015-01-14 02:31:39 +00:00
it->second.router = r;
ConnectToPeer (ident, it->second);
}
else
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: RouterInfo not found, Failed to send messages");
2016-07-12 16:37:39 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2015-01-14 02:31:39 +00:00
m_Peers.erase (it);
}
}
}
2015-01-16 20:25:44 +00:00
2015-01-17 04:01:40 +00:00
void Transports::NTCPResolve (const std::string& addr, const i2p::data::IdentHash& ident)
2015-01-16 20:25:44 +00:00
{
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(m_Service);
2015-01-17 13:22:43 +00:00
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (addr, ""),
2015-01-16 20:25:44 +00:00
std::bind (&Transports::HandleNTCPResolve, this,
std::placeholders::_1, std::placeholders::_2, ident, resolver));
}
void Transports::HandleNTCPResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
2015-02-15 15:23:06 +00:00
i2p::data::IdentHash ident, std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
2015-01-16 20:25:44 +00:00
{
auto it1 = m_Peers.find (ident);
2015-02-15 15:23:06 +00:00
if (it1 != m_Peers.end ())
2015-01-16 20:25:44 +00:00
{
auto& peer = it1->second;
2015-02-15 15:23:06 +00:00
if (!ecode && peer.router)
2015-01-16 20:25:44 +00:00
{
2016-03-25 00:04:45 +00:00
while (it != boost::asio::ip::tcp::resolver::iterator())
{
auto address = (*it).endpoint ().address ();
LogPrint (eLogDebug, "Transports: ", (*it).host_name (), " has been resolved to ", address);
if (address.is_v4 () || context.SupportsV6 ())
{
2016-03-25 00:04:45 +00:00
auto addr = peer.router->GetNTCPAddress (); // TODO: take one we requested
if (addr)
{
auto s = std::make_shared<NTCPSession> (*m_NTCPServer, peer.router);
m_NTCPServer->Connect (address, addr->port, s);
return;
}
break;
}
else
LogPrint (eLogInfo, "Transports: NTCP ", address, " is not supported");
2016-03-25 00:14:58 +00:00
it++;
2015-01-16 20:25:44 +00:00
}
}
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: Unable to resolve NTCP address: ", ecode.message ());
2016-07-12 16:37:39 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2015-02-15 15:23:06 +00:00
m_Peers.erase (it1);
2015-01-16 20:25:44 +00:00
}
}
2015-12-03 20:45:01 +00:00
void Transports::SSUResolve (const std::string& addr, const i2p::data::IdentHash& ident)
{
auto resolver = std::make_shared<boost::asio::ip::tcp::resolver>(m_Service);
resolver->async_resolve (boost::asio::ip::tcp::resolver::query (addr, ""),
std::bind (&Transports::HandleSSUResolve, this,
std::placeholders::_1, std::placeholders::_2, ident, resolver));
}
void Transports::HandleSSUResolve (const boost::system::error_code& ecode, boost::asio::ip::tcp::resolver::iterator it,
i2p::data::IdentHash ident, std::shared_ptr<boost::asio::ip::tcp::resolver> resolver)
{
auto it1 = m_Peers.find (ident);
if (it1 != m_Peers.end ())
{
auto& peer = it1->second;
if (!ecode && peer.router)
{
2016-03-25 00:04:45 +00:00
while (it != boost::asio::ip::tcp::resolver::iterator())
{
auto address = (*it).endpoint ().address ();
LogPrint (eLogDebug, "Transports: ", (*it).host_name (), " has been resolved to ", address);
if (address.is_v4 () || context.SupportsV6 ())
{
2016-03-25 00:04:45 +00:00
auto addr = peer.router->GetSSUAddress (); // TODO: take one we requested
if (addr)
{
m_SSUServer->CreateSession (peer.router, address, addr->port);
return;
}
break;
}
2016-03-25 00:04:45 +00:00
else
LogPrint (eLogInfo, "Transports: SSU ", address, " is not supported");
2016-03-25 00:14:58 +00:00
it++;
2015-12-03 20:45:01 +00:00
}
}
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: Unable to resolve SSU address: ", ecode.message ());
2016-07-12 16:37:39 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2015-12-03 20:45:01 +00:00
m_Peers.erase (it1);
}
}
2014-11-24 17:26:11 +00:00
void Transports::CloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
{
if (!router) return;
2016-06-13 15:34:44 +00:00
m_Service.post (std::bind (&Transports::PostCloseSession, this, router));
}
2014-11-24 17:26:11 +00:00
void Transports::PostCloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
{
auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (router) : nullptr;
if (ssuSession) // try SSU first
{
m_SSUServer->DeleteSession (ssuSession);
2015-12-18 12:57:22 +00:00
LogPrint (eLogDebug, "Transports: SSU session closed");
}
auto ntcpSession = m_NTCPServer ? m_NTCPServer->FindNTCPSession(router->GetIdentHash()) : nullptr;
if (ntcpSession) // try deleting ntcp session too
{
ntcpSession->Terminate ();
LogPrint(eLogDebug, "Transports: NTCP session closed");
}
}
2014-02-09 02:06:40 +00:00
void Transports::DetectExternalIP ()
{
if (RoutesRestricted())
{
LogPrint(eLogInfo, "Transports: restricted routes enabled, not detecting ip");
i2p::context.SetStatus (eRouterStatusOK);
return;
}
2015-02-26 19:17:16 +00:00
if (m_SSUServer)
2014-02-09 02:06:40 +00:00
{
2016-11-01 14:26:40 +00:00
bool nat; i2p::config::GetOption("nat", nat);
if (nat)
i2p::context.SetStatus (eRouterStatusTesting);
2015-02-26 19:17:16 +00:00
for (int i = 0; i < 5; i++)
{
auto router = i2p::data::netdb.GetRandomPeerTestRouter ();
2016-06-13 15:34:44 +00:00
if (router && router->IsSSU (!context.SupportsV6 ()))
m_SSUServer->CreateSession (router, true); // peer test
2015-02-26 19:17:16 +00:00
else
{
// if not peer test capable routers found pick any
router = i2p::data::netdb.GetRandomRouter ();
if (router && router->IsSSU ())
2016-06-13 15:34:44 +00:00
m_SSUServer->CreateSession (router); // no peer test
2015-02-26 19:17:16 +00:00
}
}
}
else
2015-12-18 12:57:22 +00:00
LogPrint (eLogError, "Transports: Can't detect external IP. SSU is not available");
2014-02-09 02:06:40 +00:00
}
2015-11-03 14:15:49 +00:00
void Transports::PeerTest ()
{
if (RoutesRestricted()) return;
2015-11-03 14:15:49 +00:00
if (m_SSUServer)
2016-11-13 14:14:05 +00:00
{
2015-11-03 14:15:49 +00:00
bool statusChanged = false;
for (int i = 0; i < 5; i++)
{
auto router = i2p::data::netdb.GetRandomPeerTestRouter ();
2015-11-25 17:51:35 +00:00
if (router && router->IsSSU (!context.SupportsV6 ()))
2015-11-03 14:15:49 +00:00
{
if (!statusChanged)
{
statusChanged = true;
i2p::context.SetStatus (eRouterStatusTesting); // first time only
}
2016-06-13 15:34:44 +00:00
m_SSUServer->CreateSession (router, true); // peer test
2015-11-03 14:15:49 +00:00
}
}
}
}
std::shared_ptr<i2p::crypto::DHKeys> Transports::GetNextDHKeysPair ()
2014-04-04 17:30:13 +00:00
{
2014-04-04 20:29:40 +00:00
return m_DHKeysPairSupplier.Acquire ();
2014-04-04 17:30:13 +00:00
}
2015-11-03 14:15:49 +00:00
void Transports::ReuseDHKeysPair (std::shared_ptr<i2p::crypto::DHKeys> pair)
{
m_DHKeysPairSupplier.Return (pair);
}
2015-01-13 03:53:35 +00:00
void Transports::PeerConnected (std::shared_ptr<TransportSession> session)
{
m_Service.post([session, this]()
2016-06-13 15:34:44 +00:00
{
2016-02-01 19:19:54 +00:00
auto remoteIdentity = session->GetRemoteIdentity ();
if (!remoteIdentity) return;
auto ident = remoteIdentity->GetIdentHash ();
2016-11-01 14:26:40 +00:00
auto it = m_Peers.find (ident);
2015-01-13 03:53:35 +00:00
if (it != m_Peers.end ())
{
2016-11-01 17:57:25 +00:00
#ifdef WITH_EVENTS
2016-11-01 14:26:40 +00:00
EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "false"}});
2016-11-01 17:57:25 +00:00
#endif
2016-03-19 02:53:03 +00:00
bool sendDatabaseStore = true;
if (it->second.delayedMessages.size () > 0)
{
// check if first message is our DatabaseStore (publishing)
auto firstMsg = it->second.delayedMessages[0];
if (firstMsg && firstMsg->GetTypeID () == eI2NPDatabaseStore &&
2016-06-13 15:34:44 +00:00
i2p::data::IdentHash(firstMsg->GetPayload () + DATABASE_STORE_KEY_OFFSET) == i2p::context.GetIdentHash ())
2016-03-19 02:53:03 +00:00
sendDatabaseStore = false; // we have it in the list already
}
if (sendDatabaseStore)
session->SendI2NPMessages ({ CreateDatabaseStoreMsg () });
2016-08-04 14:26:50 +00:00
else
session->SetTerminationTimeout (10); // most likely it's publishing, no follow-up messages expected, set timeout to 10 seconds
it->second.sessions.push_back (session);
session->SendI2NPMessages (it->second.delayedMessages);
it->second.delayedMessages.clear ();
2015-01-13 03:53:35 +00:00
}
2015-01-14 02:31:39 +00:00
else // incoming connection
2016-01-15 21:23:03 +00:00
{
if(RoutesRestricted() && ! IsRestrictedPeer(ident)) {
// not trusted
LogPrint(eLogWarning, "Transports: closing untrusted inbound connection from ", ident.ToBase64());
session->Done();
return;
}
2016-11-01 17:57:25 +00:00
#ifdef WITH_EVENTS
2016-11-01 14:26:40 +00:00
EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "true"}});
2016-11-01 17:57:25 +00:00
#endif
2016-03-19 02:53:03 +00:00
session->SendI2NPMessages ({ CreateDatabaseStoreMsg () }); // send DatabaseStore
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.insert (std::make_pair (ident, Peer{ 0, nullptr, { session }, i2p::util::GetSecondsSinceEpoch (), {} }));
2016-01-15 21:23:03 +00:00
}
2016-11-01 14:26:40 +00:00
});
2015-01-13 03:53:35 +00:00
}
void Transports::PeerDisconnected (std::shared_ptr<TransportSession> session)
{
m_Service.post([session, this]()
2016-11-01 14:26:40 +00:00
{
2016-02-01 19:19:54 +00:00
auto remoteIdentity = session->GetRemoteIdentity ();
if (!remoteIdentity) return;
auto ident = remoteIdentity->GetIdentHash ();
2016-11-01 17:57:25 +00:00
#ifdef WITH_EVENTS
2016-11-01 14:26:40 +00:00
EmitEvent({{"type" , "transport.disconnected"}, {"ident", ident.ToBase64()}});
2016-11-01 17:57:25 +00:00
#endif
2015-01-13 03:53:35 +00:00
auto it = m_Peers.find (ident);
if (it != m_Peers.end ())
2015-01-14 02:31:39 +00:00
{
it->second.sessions.remove (session);
if (it->second.sessions.empty ()) // TODO: why?
{
if (it->second.delayedMessages.size () > 0)
ConnectToPeer (ident, it->second);
else
2016-01-15 21:23:03 +00:00
{
2016-07-12 16:37:39 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
m_Peers.erase (it);
2016-01-15 21:23:03 +00:00
}
}
2015-01-14 02:31:39 +00:00
}
2015-01-13 03:53:35 +00:00
});
}
2015-02-11 19:45:25 +00:00
bool Transports::IsConnected (const i2p::data::IdentHash& ident) const
2016-01-15 21:23:03 +00:00
{
std::unique_lock<std::mutex> l(m_PeersMutex);
auto it = m_Peers.find (ident);
return it != m_Peers.end ();
}
2015-02-11 19:45:25 +00:00
void Transports::HandlePeerCleanupTimer (const boost::system::error_code& ecode)
{
2015-02-12 03:48:26 +00:00
if (ecode != boost::asio::error::operation_aborted)
2015-02-11 19:45:25 +00:00
{
2015-02-12 03:48:26 +00:00
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_Peers.begin (); it != m_Peers.end (); )
2015-02-11 19:45:25 +00:00
{
if (it->second.sessions.empty () && ts > it->second.creationTime + SESSION_CREATION_TIMEOUT)
2015-02-12 03:48:26 +00:00
{
2015-12-18 12:57:22 +00:00
LogPrint (eLogWarning, "Transports: Session to peer ", it->first.ToBase64 (), " has not been created in ", SESSION_CREATION_TIMEOUT, " seconds");
2016-06-28 18:43:55 +00:00
auto profile = i2p::data::GetRouterProfile(it->first);
if (profile)
{
profile->TunnelNonReplied();
profile->Save();
}
2016-06-13 15:34:44 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
2015-02-12 03:48:26 +00:00
it = m_Peers.erase (it);
}
else
2016-08-08 22:53:37 +00:00
++it;
2015-02-11 19:45:25 +00:00
}
2015-03-17 19:19:38 +00:00
UpdateBandwidth (); // TODO: use separate timer(s) for it
2016-06-13 15:34:44 +00:00
if (i2p::context.GetStatus () == eRouterStatusTesting) // if still testing, repeat peer test
DetectExternalIP ();
2015-02-12 03:48:26 +00:00
m_PeerCleanupTimer.expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
m_PeerCleanupTimer.async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
}
2015-02-11 19:45:25 +00:00
}
2016-11-13 14:14:05 +00:00
void Transports::HandlePeerTestTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
PeerTest ();
m_PeerTestTimer.expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
m_PeerTestTimer.async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
}
}
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRandomPeer () const
{
2016-06-01 00:00:00 +00:00
if (m_Peers.empty ()) return nullptr;
2016-01-15 21:23:03 +00:00
std::unique_lock<std::mutex> l(m_PeersMutex);
auto it = m_Peers.begin ();
2015-11-03 14:15:49 +00:00
std::advance (it, rand () % m_Peers.size ());
return it != m_Peers.end () ? it->second.router : nullptr;
}
2016-11-01 14:26:40 +00:00
void Transports::RestrictRoutesToFamilies(std::set<std::string> families)
{
std::lock_guard<std::mutex> lock(m_FamilyMutex);
m_TrustedFamilies.clear();
for ( const auto& fam : families )
m_TrustedFamilies.push_back(fam);
}
2016-06-17 15:03:33 +00:00
void Transports::RestrictRoutesToRouters(std::set<i2p::data::IdentHash> routers)
{
std::unique_lock<std::mutex> lock(m_TrustedRoutersMutex);
m_TrustedRouters.clear();
for (const auto & ri : routers )
m_TrustedRouters.push_back(ri);
}
2016-11-01 14:26:40 +00:00
bool Transports::RoutesRestricted() const {
std::unique_lock<std::mutex> famlock(m_FamilyMutex);
std::unique_lock<std::mutex> routerslock(m_TrustedRoutersMutex);
2016-11-01 14:26:40 +00:00
return m_TrustedFamilies.size() > 0 || m_TrustedRouters.size() > 0;
}
2016-06-17 15:03:33 +00:00
2016-11-01 14:26:40 +00:00
/** XXX: if routes are not restricted this dies */
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRestrictedPeer() const
{
{
std::lock_guard<std::mutex> l(m_FamilyMutex);
std::string fam;
auto sz = m_TrustedFamilies.size();
if(sz > 1)
{
auto it = m_TrustedFamilies.begin ();
std::advance(it, rand() % sz);
fam = *it;
boost::to_lower(fam);
}
else if (sz == 1)
{
fam = m_TrustedFamilies[0];
}
if (fam.size())
return i2p::data::netdb.GetRandomRouterInFamily(fam);
}
{
std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
auto sz = m_TrustedRouters.size();
if (sz)
{
if(sz == 1)
return i2p::data::netdb.FindRouter(m_TrustedRouters[0]);
auto it = m_TrustedRouters.begin();
std::advance(it, rand() % sz);
return i2p::data::netdb.FindRouter(*it);
}
}
return nullptr;
2016-11-01 14:26:40 +00:00
}
bool Transports::IsRestrictedPeer(const i2p::data::IdentHash & ih) const
{
{
std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
for (const auto & r : m_TrustedRouters )
if ( r == ih ) return true;
}
{
std::unique_lock<std::mutex> l(m_FamilyMutex);
auto ri = i2p::data::netdb.FindRouter(ih);
for (const auto & fam : m_TrustedFamilies)
if(ri->IsFamily(fam)) return true;
}
return false;
}
2013-10-27 15:26:39 +00:00
}
}