i2pd/libi2pd/TunnelPool.cpp

880 lines
27 KiB
C++
Raw Normal View History

/*
2024-02-02 03:38:12 +03:00
* Copyright (c) 2013-2024, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
2015-06-10 22:32:55 +03:00
#include <algorithm>
2014-03-18 00:50:03 +04:00
#include "I2PEndian.h"
2015-11-03 17:15:49 +03:00
#include "Crypto.h"
2014-03-14 20:35:02 +04:00
#include "Tunnel.h"
#include "NetDb.hpp"
2014-03-15 04:24:12 +04:00
#include "Timestamp.h"
2014-03-18 00:50:03 +04:00
#include "Garlic.h"
2024-02-22 03:46:29 +03:00
#include "ECIESX25519AEADRatchetSession.h"
#include "Transports.h"
2015-11-03 17:15:49 +03:00
#include "Log.h"
2016-11-01 17:26:40 +03:00
#include "Tunnel.h"
2014-03-14 20:35:02 +04:00
#include "TunnelPool.h"
2016-10-20 19:14:32 +03:00
#include "Destination.h"
2014-03-14 20:35:02 +04:00
namespace i2p
{
namespace tunnel
{
2021-07-23 03:58:35 +03:00
void Path::Add (std::shared_ptr<const i2p::data::RouterInfo> r)
{
if (r)
{
2021-07-23 03:58:35 +03:00
peers.push_back (r->GetRouterIdentity ());
if (r->GetVersion () < i2p::data::NETDB_MIN_SHORT_TUNNEL_BUILD_VERSION ||
r->GetRouterIdentity ()->GetCryptoKeyType () != i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)
2021-07-23 03:58:35 +03:00
isShort = false;
}
}
2021-07-23 03:58:35 +03:00
void Path::Reverse ()
{
std::reverse (peers.begin (), peers.end ());
}
TunnelPool::TunnelPool (int numInboundHops, int numOutboundHops, int numInboundTunnels,
int numOutboundTunnels, int inboundVariance, int outboundVariance):
m_NumInboundHops (numInboundHops), m_NumOutboundHops (numOutboundHops),
m_NumInboundTunnels (numInboundTunnels), m_NumOutboundTunnels (numOutboundTunnels),
m_InboundVariance (inboundVariance), m_OutboundVariance (outboundVariance),
2024-02-15 05:35:41 +03:00
m_IsActive (true), m_CustomPeerSelector(nullptr), m_Rng(m_Rd())
2014-03-14 20:35:02 +04:00
{
if (m_NumInboundTunnels > TUNNEL_POOL_MAX_INBOUND_TUNNELS_QUANTITY)
m_NumInboundTunnels = TUNNEL_POOL_MAX_INBOUND_TUNNELS_QUANTITY;
if (m_NumOutboundTunnels > TUNNEL_POOL_MAX_OUTBOUND_TUNNELS_QUANTITY)
m_NumOutboundTunnels = TUNNEL_POOL_MAX_OUTBOUND_TUNNELS_QUANTITY;
if (m_InboundVariance < 0 && m_NumInboundHops + m_InboundVariance <= 0)
m_InboundVariance = m_NumInboundHops ? -m_NumInboundHops + 1 : 0;
if (m_OutboundVariance < 0 && m_NumOutboundHops + m_OutboundVariance <= 0)
m_OutboundVariance = m_NumOutboundHops ? -m_NumOutboundHops + 1 : 0;
if (m_InboundVariance > 0 && m_NumInboundHops + m_InboundVariance > STANDARD_NUM_RECORDS)
m_InboundVariance = (m_NumInboundHops < STANDARD_NUM_RECORDS) ? STANDARD_NUM_RECORDS - m_NumInboundHops : 0;
if (m_OutboundVariance > 0 && m_NumOutboundHops + m_OutboundVariance > STANDARD_NUM_RECORDS)
m_OutboundVariance = (m_NumOutboundHops < STANDARD_NUM_RECORDS) ? STANDARD_NUM_RECORDS - m_NumOutboundHops : 0;
m_NextManageTime = i2p::util::GetSecondsSinceEpoch () + rand () % TUNNEL_POOL_MANAGE_INTERVAL;
2014-03-14 20:35:02 +04:00
}
TunnelPool::~TunnelPool ()
2014-10-11 17:47:24 +04:00
{
DetachTunnels ();
}
2015-06-10 22:32:55 +03:00
void TunnelPool::SetExplicitPeers (std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers)
{
m_ExplicitPeers = explicitPeers;
if (m_ExplicitPeers)
{
int size = m_ExplicitPeers->size ();
if (m_NumInboundHops > size)
2015-06-10 22:32:55 +03:00
{
m_NumInboundHops = size;
2022-11-25 23:37:52 +03:00
LogPrint (eLogInfo, "Tunnels: Inbound tunnel length has been adjusted to ", size, " for explicit peers");
}
if (m_NumOutboundHops > size)
2015-06-10 22:32:55 +03:00
{
m_NumOutboundHops = size;
2022-11-25 23:37:52 +03:00
LogPrint (eLogInfo, "Tunnels: Outbound tunnel length has been adjusted to ", size, " for explicit peers");
}
2015-06-10 22:32:55 +03:00
m_NumInboundTunnels = 1;
m_NumOutboundTunnels = 1;
}
2015-06-10 22:32:55 +03:00
}
2014-10-11 17:47:24 +04:00
void TunnelPool::DetachTunnels ()
2014-03-14 20:35:02 +04:00
{
2014-10-06 20:50:36 +04:00
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
2016-08-10 01:16:24 +03:00
for (auto& it: m_InboundTunnels)
2014-10-06 20:50:36 +04:00
it->SetTunnelPool (nullptr);
m_InboundTunnels.clear ();
2014-10-06 20:50:36 +04:00
}
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
2016-08-10 01:16:24 +03:00
for (auto& it: m_OutboundTunnels)
2014-10-06 20:50:36 +04:00
it->SetTunnelPool (nullptr);
m_OutboundTunnels.clear ();
2014-10-06 20:50:36 +04:00
}
{
std::unique_lock<std::mutex> l(m_TestsMutex);
m_Tests.clear ();
}
}
bool TunnelPool::Reconfigure(int inHops, int outHops, int inQuant, int outQuant)
{
2018-01-02 19:34:58 +03:00
if( inHops >= 0 && outHops >= 0 && inQuant > 0 && outQuant > 0)
{
m_NumInboundHops = inHops;
m_NumOutboundHops = outHops;
m_NumInboundTunnels = inQuant;
m_NumOutboundTunnels = outQuant;
return true;
}
return false;
}
2015-01-27 22:55:46 +03:00
void TunnelPool::TunnelCreated (std::shared_ptr<InboundTunnel> createdTunnel)
{
if (!m_IsActive) return;
2014-10-03 18:35:11 +04:00
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
if (createdTunnel->IsRecreated ())
{
// find and mark old tunnel as expired
createdTunnel->SetRecreated (false);
for (auto& it: m_InboundTunnels)
if (it->IsRecreated () && it->GetNextIdentHash () == createdTunnel->GetNextIdentHash ())
{
it->SetState (eTunnelStateExpiring);
break;
}
}
2014-10-03 18:35:11 +04:00
m_InboundTunnels.insert (createdTunnel);
}
2014-12-16 05:24:01 +03:00
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated ();
}
2015-01-27 22:55:46 +03:00
void TunnelPool::TunnelExpired (std::shared_ptr<InboundTunnel> expiredTunnel)
2014-03-15 05:22:59 +04:00
{
2014-03-18 16:15:43 +04:00
if (expiredTunnel)
2016-10-20 19:14:32 +03:00
{
2014-03-18 16:15:43 +04:00
expiredTunnel->SetTunnelPool (nullptr);
{
std::unique_lock<std::mutex> l(m_TestsMutex);
for (auto& it: m_Tests)
if (it.second.second == expiredTunnel) it.second.second = nullptr;
}
2014-10-03 18:35:11 +04:00
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
2014-10-03 18:35:11 +04:00
m_InboundTunnels.erase (expiredTunnel);
}
}
2014-03-17 00:03:20 +04:00
2015-01-27 22:55:46 +03:00
void TunnelPool::TunnelCreated (std::shared_ptr<OutboundTunnel> createdTunnel)
2014-03-17 00:03:20 +04:00
{
if (!m_IsActive) return;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.insert (createdTunnel);
}
2014-03-17 00:03:20 +04:00
}
2015-01-27 22:55:46 +03:00
void TunnelPool::TunnelExpired (std::shared_ptr<OutboundTunnel> expiredTunnel)
2014-03-17 00:03:20 +04:00
{
2014-03-18 16:15:43 +04:00
if (expiredTunnel)
2014-03-21 23:54:55 +04:00
{
2014-03-18 16:15:43 +04:00
expiredTunnel->SetTunnelPool (nullptr);
{
std::unique_lock<std::mutex> l(m_TestsMutex);
for (auto& it: m_Tests)
if (it.second.first == expiredTunnel) it.second.first = nullptr;
}
2014-10-03 18:35:11 +04:00
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
2014-10-03 18:35:11 +04:00
m_OutboundTunnels.erase (expiredTunnel);
2014-03-21 23:54:55 +04:00
}
2014-03-17 00:03:20 +04:00
}
2015-01-27 22:55:46 +03:00
std::vector<std::shared_ptr<InboundTunnel> > TunnelPool::GetInboundTunnels (int num) const
{
2015-01-27 22:55:46 +03:00
std::vector<std::shared_ptr<InboundTunnel> > v;
int i = 0;
std::shared_ptr<InboundTunnel> slowTunnel;
2014-10-03 18:35:11 +04:00
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
2016-08-10 01:16:24 +03:00
for (const auto& it : m_InboundTunnels)
{
if (i >= num) break;
2014-08-28 05:53:44 +04:00
if (it->IsEstablished ())
2014-03-21 23:54:55 +04:00
{
if (it->IsSlow () && !slowTunnel)
slowTunnel = it;
else
{
v.push_back (it);
i++;
}
}
}
if (slowTunnel && (int)v.size () < (num/2+1))
v.push_back (slowTunnel);
return v;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNextOutboundTunnel (std::shared_ptr<OutboundTunnel> excluded,
i2p::data::RouterInfo::CompatibleTransports compatible) const
2014-03-17 00:03:20 +04:00
{
2016-11-15 18:46:58 +03:00
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
return GetNextTunnel (m_OutboundTunnels, excluded, compatible);
}
std::shared_ptr<InboundTunnel> TunnelPool::GetNextInboundTunnel (std::shared_ptr<InboundTunnel> excluded,
i2p::data::RouterInfo::CompatibleTransports compatible) const
{
2016-11-15 18:46:58 +03:00
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
return GetNextTunnel (m_InboundTunnels, excluded, compatible);
}
template<class TTunnels>
typename TTunnels::value_type TunnelPool::GetNextTunnel (TTunnels& tunnels,
typename TTunnels::value_type excluded, i2p::data::RouterInfo::CompatibleTransports compatible) const
{
if (tunnels.empty ()) return nullptr;
2015-11-03 17:15:49 +03:00
uint32_t ind = rand () % (tunnels.size ()/2 + 1), i = 0;
2021-06-04 19:16:50 +03:00
bool skipped = false;
2014-08-28 06:21:29 +04:00
typename TTunnels::value_type tunnel = nullptr;
2016-08-10 01:16:24 +03:00
for (const auto& it: tunnels)
{
if (it->IsEstablished () && it != excluded && (compatible & it->GetFarEndTransports ()))
2014-08-28 06:21:29 +04:00
{
if (it->IsSlow () || (HasLatencyRequirement() && it->LatencyIsKnown() &&
!it->LatencyFitsRange(m_MinLatency, m_MaxLatency)))
2021-06-04 19:16:50 +03:00
{
i++; skipped = true;
2016-11-15 18:46:58 +03:00
continue;
}
2014-08-28 06:21:29 +04:00
tunnel = it;
i++;
}
2014-08-29 15:44:12 +04:00
if (i > ind && tunnel) break;
}
if (!tunnel && skipped)
2021-06-04 19:16:50 +03:00
{
2016-11-15 19:27:00 +03:00
ind = rand () % (tunnels.size ()/2 + 1), i = 0;
for (const auto& it: tunnels)
{
2016-11-15 19:27:00 +03:00
if (it->IsEstablished () && it != excluded)
{
tunnel = it;
i++;
2016-11-15 19:27:00 +03:00
}
if (i > ind && tunnel) break;
}
}
if (!tunnel && excluded && excluded->IsEstablished ()) tunnel = excluded;
2014-08-28 06:21:29 +04:00
return tunnel;
}
std::pair<std::shared_ptr<OutboundTunnel>, bool> TunnelPool::GetNewOutboundTunnel (std::shared_ptr<OutboundTunnel> old) const
{
if (old && old->IsEstablished ()) return std::make_pair(old, false);
std::shared_ptr<OutboundTunnel> tunnel;
bool freshTunnel = false;
if (old)
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
2016-08-10 01:16:24 +03:00
for (const auto& it: m_OutboundTunnels)
2015-11-03 17:15:49 +03:00
if (it->IsEstablished () && old->GetEndpointIdentHash () == it->GetEndpointIdentHash ())
2015-04-17 18:36:42 +03:00
{
tunnel = it;
2015-04-17 18:36:42 +03:00
break;
}
}
if (!tunnel)
{
tunnel = GetNextOutboundTunnel ();
freshTunnel = true;
}
return std::make_pair(tunnel, freshTunnel);
}
void TunnelPool::CreateTunnels ()
{
2014-08-28 05:53:44 +04:00
int num = 0;
2014-10-03 18:35:11 +04:00
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
2016-08-10 01:16:24 +03:00
for (const auto& it : m_OutboundTunnels)
2014-10-03 18:35:11 +04:00
if (it->IsEstablished ()) num++;
}
num = m_NumOutboundTunnels - num;
if (num > 0)
{
if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS;
for (int i = 0; i < num; i++)
CreateOutboundTunnel ();
}
2016-11-16 18:59:11 +03:00
num = 0;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
2016-11-16 18:59:11 +03:00
for (const auto& it : m_InboundTunnels)
if (it->IsEstablished ()) num++;
}
if (!num && !m_OutboundTunnels.empty () && m_NumOutboundHops > 0 &&
m_NumInboundHops == m_NumOutboundHops)
{
for (auto it: m_OutboundTunnels)
{
2024-01-04 22:35:25 +03:00
// try to create inbound tunnel through the same path as successive outbound
CreatePairedInboundTunnel (it);
num++;
if (num >= m_NumInboundTunnels) break;
}
}
num = m_NumInboundTunnels - num;
if (num > 0)
{
if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS;
for (int i = 0; i < num; i++)
CreateInboundTunnel ();
}
if (num < m_NumInboundTunnels && m_NumInboundHops <= 0 && m_LocalDestination) // zero hops IB
2016-11-16 18:59:11 +03:00
m_LocalDestination->SetLeaseSetUpdated (); // update LeaseSet immediately
}
2014-03-18 00:50:03 +04:00
void TunnelPool::TestTunnels ()
{
decltype(m_Tests) tests;
{
std::unique_lock<std::mutex> l(m_TestsMutex);
2016-08-10 01:16:24 +03:00
tests.swap(m_Tests);
}
2016-08-10 01:16:24 +03:00
for (auto& it: tests)
2014-03-18 00:50:03 +04:00
{
LogPrint (eLogWarning, "Tunnels: Test of tunnel ", it.first, " failed");
2014-07-27 04:56:42 +04:00
// if test failed again with another tunnel we consider it failed
2014-07-10 05:43:33 +04:00
if (it.second.first)
{
2014-07-27 04:56:42 +04:00
if (it.second.first->GetState () == eTunnelStateTestFailed)
{
2014-07-27 04:56:42 +04:00
it.second.first->SetState (eTunnelStateFailed);
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
if (m_OutboundTunnels.size () > 1 || m_NumOutboundTunnels <= 1) // don't fail last tunnel
2024-02-23 19:37:09 +03:00
m_OutboundTunnels.erase (it.second.first);
else
it.second.first->SetState (eTunnelStateTestFailed);
2014-07-27 04:56:42 +04:00
}
else if (it.second.first->GetState () != eTunnelStateExpiring)
2014-07-27 04:56:42 +04:00
it.second.first->SetState (eTunnelStateTestFailed);
}
2014-07-10 05:43:33 +04:00
if (it.second.second)
{
2014-07-27 04:56:42 +04:00
if (it.second.second->GetState () == eTunnelStateTestFailed)
{
2014-07-27 04:56:42 +04:00
it.second.second->SetState (eTunnelStateFailed);
2014-10-03 18:35:11 +04:00
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
if (m_InboundTunnels.size () > 1 || m_NumInboundTunnels <= 1) // don't fail last tunnel
2024-02-23 19:37:09 +03:00
m_InboundTunnels.erase (it.second.second);
else
2024-02-24 02:06:31 +03:00
it.second.second->SetState (eTunnelStateTestFailed);
2014-10-03 18:35:11 +04:00
}
2014-12-16 05:24:01 +03:00
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated ();
}
else if (it.second.second->GetState () != eTunnelStateExpiring)
2014-07-27 04:56:42 +04:00
it.second.second->SetState (eTunnelStateTestFailed);
}
2014-03-18 00:50:03 +04:00
}
// new tests
if (!m_LocalDestination) return;
2024-02-02 03:38:12 +03:00
std::vector<std::pair<std::shared_ptr<OutboundTunnel>, std::shared_ptr<InboundTunnel> > > newTests;
std::vector<std::shared_ptr<OutboundTunnel> > outboundTunnels;
2014-03-18 00:50:03 +04:00
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto& it: m_OutboundTunnels)
if (it->IsEstablished ())
outboundTunnels.push_back (it);
}
2024-02-15 05:35:41 +03:00
std::shuffle (outboundTunnels.begin(), outboundTunnels.end(), m_Rng);
std::vector<std::shared_ptr<InboundTunnel> > inboundTunnels;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto& it: m_InboundTunnels)
if (it->IsEstablished ())
inboundTunnels.push_back (it);
}
2024-02-15 05:35:41 +03:00
std::shuffle (inboundTunnels.begin(), inboundTunnels.end(), m_Rng);
auto it1 = outboundTunnels.begin ();
auto it2 = inboundTunnels.begin ();
while (it1 != outboundTunnels.end () && it2 != inboundTunnels.end ())
{
newTests.push_back(std::make_pair (*it1, *it2));
++it1; ++it2;
}
bool isECIES = m_LocalDestination->SupportsEncryptionType (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD);
2024-02-02 03:38:12 +03:00
for (auto& it: newTests)
{
uint32_t msgID;
RAND_bytes ((uint8_t *)&msgID, 4);
{
2024-02-02 03:38:12 +03:00
std::unique_lock<std::mutex> l(m_TestsMutex);
m_Tests[msgID] = it;
2014-03-22 02:26:11 +04:00
}
auto msg = CreateTunnelTestMsg (msgID);
2024-02-02 03:38:12 +03:00
auto outbound = it.first;
auto s = shared_from_this ();
msg->onDrop = [msgID, outbound, s]()
{
2024-02-02 03:38:12 +03:00
// if test msg dropped locally it's outbound tunnel to blame
outbound->SetState (eTunnelStateFailed);
{
std::unique_lock<std::mutex> l(s->m_TestsMutex);
s->m_Tests.erase (msgID);
}
{
std::unique_lock<std::mutex> l(s->m_OutboundTunnelsMutex);
s->m_OutboundTunnels.erase (outbound);
}
};
// encrypt
if (isECIES)
2024-02-22 03:46:29 +03:00
{
uint8_t key[32]; RAND_bytes (key, 32);
uint64_t tag; RAND_bytes ((uint8_t *)&tag, 8);
m_LocalDestination->SubmitECIESx25519Key (key, tag);
msg = i2p::garlic::WrapECIESX25519Message (msg, key, tag);
}
else
{
uint8_t key[32], tag[32];
RAND_bytes (key, 32); RAND_bytes (tag, 32);
m_LocalDestination->SubmitSessionKey (key, tag);
i2p::garlic::ElGamalAESSession garlic (key, tag);
msg = garlic.WrapSingleMessage (msg);
2024-02-22 03:46:29 +03:00
}
2024-02-02 03:38:12 +03:00
outbound->SendTunnelDataMsgTo (it.second->GetNextIdentHash (), it.second->GetNextTunnelID (), msg);
}
2014-03-18 00:50:03 +04:00
}
void TunnelPool::ManageTunnels (uint64_t ts)
{
2022-04-27 04:02:39 +03:00
if (ts > m_NextManageTime || ts + 2*TUNNEL_POOL_MANAGE_INTERVAL < m_NextManageTime) // in case if clock was adjusted
{
CreateTunnels ();
TestTunnels ();
m_NextManageTime = ts + TUNNEL_POOL_MANAGE_INTERVAL + (rand () % TUNNEL_POOL_MANAGE_INTERVAL)/2;
}
}
2015-06-16 17:14:14 +03:00
void TunnelPool::ProcessGarlicMessage (std::shared_ptr<I2NPMessage> msg)
2014-12-16 05:24:01 +03:00
{
if (m_LocalDestination)
m_LocalDestination->ProcessGarlicMessage (msg);
else
LogPrint (eLogWarning, "Tunnels: Local destination doesn't exist, dropped");
}
2015-06-16 17:14:14 +03:00
void TunnelPool::ProcessDeliveryStatus (std::shared_ptr<I2NPMessage> msg)
2014-03-18 00:50:03 +04:00
{
if (m_LocalDestination)
m_LocalDestination->ProcessDeliveryStatusMessage (msg);
else
LogPrint (eLogWarning, "Tunnels: Local destination doesn't exist, dropped");
2024-02-27 11:15:15 +03:00
}
void TunnelPool::ProcessTunnelTest (std::shared_ptr<I2NPMessage> msg)
{
const uint8_t * buf = msg->GetPayload ();
uint32_t msgID = bufbe32toh (buf);
buf += 4;
uint64_t timestamp = bufbe64toh (buf);
ProcessTunnelTest (msgID, timestamp);
2024-02-22 03:46:29 +03:00
}
bool TunnelPool::ProcessTunnelTest (uint32_t msgID, uint64_t timestamp)
2024-02-22 03:46:29 +03:00
{
decltype(m_Tests)::mapped_type test;
bool found = false;
{
std::unique_lock<std::mutex> l(m_TestsMutex);
auto it = m_Tests.find (msgID);
if (it != m_Tests.end ())
{
found = true;
test = it->second;
m_Tests.erase (it);
}
}
if (found)
2014-03-18 00:50:03 +04:00
{
2024-02-27 20:33:07 +03:00
int dlt = (uint64_t)i2p::util::GetMonotonicMicroseconds () - (int64_t)timestamp;
2024-02-27 11:15:15 +03:00
LogPrint (eLogDebug, "Tunnels: Test of ", msgID, " successful. ", dlt, " microseconds");
if (dlt < 0) dlt = 0; // should not happen
int numHops = 0;
if (test.first) numHops += test.first->GetNumHops ();
if (test.second) numHops += test.second->GetNumHops ();
2020-11-16 20:56:22 +03:00
// restore from test failed state if any
if (test.first)
{
if (test.first->GetState () != eTunnelStateExpiring)
2020-11-16 20:56:22 +03:00
test.first->SetState (eTunnelStateEstablished);
// update latency
2024-02-25 23:57:57 +03:00
int latency = 0;
if (numHops) latency = dlt*test.first->GetNumHops ()/numHops;
if (!latency) latency = dlt/2;
2024-02-27 11:15:15 +03:00
test.first->AddLatencySample (latency);
}
2020-11-16 20:56:22 +03:00
if (test.second)
{
if (test.second->GetState () != eTunnelStateExpiring)
2020-11-16 20:56:22 +03:00
test.second->SetState (eTunnelStateEstablished);
// update latency
2024-02-25 23:57:57 +03:00
int latency = 0;
if (numHops) latency = dlt*test.second->GetNumHops ()/numHops;
if (!latency) latency = dlt/2;
2024-02-27 11:15:15 +03:00
test.second->AddLatencySample (latency);
}
2014-03-18 00:50:03 +04:00
}
2024-02-22 03:46:29 +03:00
return found;
}
bool TunnelPool::IsExploratory () const
{
return i2p::tunnel::tunnels.GetExploratoryPool () == shared_from_this ();
}
2023-07-11 20:16:35 +03:00
std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop,
bool reverse, bool endpoint) const
{
bool tryHighBandwidth = !IsExploratory ();
std::shared_ptr<const i2p::data::RouterInfo> hop;
for (int i = 0; i < TUNNEL_POOL_MAX_HOP_SELECTION_ATTEMPTS; i++)
{
hop = tryHighBandwidth ?
i2p::data::netdb.GetHighBandwidthRandomRouter (prevHop, reverse, endpoint) :
i2p::data::netdb.GetRandomRouter (prevHop, reverse, endpoint);
if (hop)
{
if (!hop->GetProfile ()->IsBad ())
break;
}
else if (tryHighBandwidth)
tryHighBandwidth = false;
else
return nullptr;
}
return hop;
}
bool TunnelPool::StandardSelectPeers(Path & path, int numHops, bool inbound, SelectHopFunc nextHop)
{
2021-03-16 22:23:00 +03:00
int start = 0;
2021-07-14 21:46:56 +03:00
std::shared_ptr<const i2p::data::RouterInfo> prevHop = i2p::context.GetSharedRouterInfo ();
if(i2p::transport::transports.RoutesRestricted())
{
/** if routes are restricted prepend trusted first hop */
auto hop = i2p::transport::transports.GetRestrictedPeer();
if(!hop) return false;
2021-07-23 03:58:35 +03:00
path.Add (hop);
prevHop = hop;
2021-03-16 22:23:00 +03:00
start++;
}
else if (i2p::transport::transports.GetNumPeers () > 100 ||
(inbound && i2p::transport::transports.GetNumPeers () > 25))
{
2023-02-04 01:32:43 +03:00
auto r = i2p::transport::transports.GetRandomPeer (!IsExploratory ());
if (r && r->IsECIES () && !r->GetProfile ()->IsBad () &&
(numHops > 1 || (r->IsV4 () && (!inbound || r->IsPublished (true))))) // first inbound must be published ipv4
2017-04-08 22:15:59 +03:00
{
prevHop = r;
2021-07-23 03:58:35 +03:00
path.Add (r);
2021-03-16 22:23:00 +03:00
start++;
2017-04-08 22:15:59 +03:00
}
}
2021-03-16 22:23:00 +03:00
for(int i = start; i < numHops; i++ )
{
2023-07-11 20:16:35 +03:00
auto hop = nextHop (prevHop, inbound, i == numHops - 1);
if (!hop && !i) // if no suitable peer found for first hop, try already connected
{
LogPrint (eLogInfo, "Tunnels: Can't select first hop for a tunnel. Trying already connected");
hop = i2p::transport::transports.GetRandomPeer (false);
2021-09-05 16:08:29 +03:00
if (hop && !hop->IsECIES ()) hop = nullptr;
}
2015-04-03 17:02:45 +03:00
if (!hop)
{
2015-12-18 14:48:22 +03:00
LogPrint (eLogError, "Tunnels: Can't select next hop for ", prevHop->GetIdentHashBase64 ());
return false;
}
prevHop = hop;
2021-07-23 03:58:35 +03:00
path.Add (hop);
2016-06-17 18:03:33 +03:00
}
2021-11-06 22:44:56 +03:00
path.farEndTransports = prevHop->GetCompatibleTransports (inbound); // last hop
return true;
}
2021-07-23 03:58:35 +03:00
bool TunnelPool::SelectPeers (Path& path, bool isInbound)
{
// explicit peers in use
if (m_ExplicitPeers) return SelectExplicitPeers (path, isInbound);
// calculate num hops
int numHops;
if (isInbound)
{
numHops = m_NumInboundHops;
if (m_InboundVariance)
{
int offset = rand () % (std::abs (m_InboundVariance) + 1);
if (m_InboundVariance < 0) offset = -offset;
numHops += offset;
}
}
else
{
numHops = m_NumOutboundHops;
if (m_OutboundVariance)
{
int offset = rand () % (std::abs (m_OutboundVariance) + 1);
if (m_OutboundVariance < 0) offset = -offset;
numHops += offset;
}
}
// peers is empty
if (numHops <= 0) return true;
// custom peer selector in use ?
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
if (m_CustomPeerSelector)
2021-07-23 03:58:35 +03:00
return m_CustomPeerSelector->SelectPeers(path, numHops, isInbound);
}
2023-07-11 20:16:35 +03:00
return StandardSelectPeers(path, numHops, isInbound, std::bind(&TunnelPool::SelectNextHop, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
}
2021-07-23 03:58:35 +03:00
bool TunnelPool::SelectExplicitPeers (Path& path, bool isInbound)
2015-06-10 22:32:55 +03:00
{
2023-07-19 16:38:04 +03:00
if (!m_ExplicitPeers->size ()) return false;
int numHops = isInbound ? m_NumInboundHops : m_NumOutboundHops;
2021-07-29 02:08:55 +03:00
if (numHops > (int)m_ExplicitPeers->size ()) numHops = m_ExplicitPeers->size ();
for (int i = 0; i < numHops; i++)
2015-06-10 22:32:55 +03:00
{
2021-07-29 02:08:55 +03:00
auto& ident = (*m_ExplicitPeers)[i];
2015-06-10 22:32:55 +03:00
auto r = i2p::data::netdb.FindRouter (ident);
if (r)
{
if (r->IsECIES ())
{
path.Add (r);
if (i == numHops - 1)
path.farEndTransports = r->GetCompatibleTransports (isInbound);
}
else
{
LogPrint (eLogError, "Tunnels: ElGamal router ", ident.ToBase64 (), " is not supported");
return false;
}
}
2015-06-10 22:32:55 +03:00
else
{
2015-12-18 14:48:22 +03:00
LogPrint (eLogInfo, "Tunnels: Can't find router for ", ident.ToBase64 ());
2015-06-10 22:32:55 +03:00
i2p::data::netdb.RequestDestination (ident);
return false;
}
}
return true;
}
void TunnelPool::CreateInboundTunnel ()
{
2015-12-18 14:48:22 +03:00
LogPrint (eLogDebug, "Tunnels: Creating destination inbound tunnel...");
2021-07-23 03:58:35 +03:00
Path path;
if (SelectPeers (path, true))
{
2021-11-06 22:44:56 +03:00
auto outboundTunnel = GetNextOutboundTunnel (nullptr, path.farEndTransports);
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel ();
2016-06-30 04:37:17 +03:00
std::shared_ptr<TunnelConfig> config;
if (m_NumInboundHops > 0)
{
2021-07-23 03:58:35 +03:00
path.Reverse ();
config = std::make_shared<TunnelConfig> (path.peers, path.isShort, path.farEndTransports);
}
2021-07-21 20:08:12 +03:00
auto tunnel = tunnels.CreateInboundTunnel (config, shared_from_this (), outboundTunnel);
if (tunnel->IsEstablished ()) // zero hops
TunnelCreated (tunnel);
}
else
2015-12-18 14:48:22 +03:00
LogPrint (eLogError, "Tunnels: Can't create inbound tunnel, no peers available");
2014-03-14 20:35:02 +04:00
}
2014-03-17 00:03:20 +04:00
2015-01-27 22:55:46 +03:00
void TunnelPool::RecreateInboundTunnel (std::shared_ptr<InboundTunnel> tunnel)
2014-08-09 06:44:33 +04:00
{
2021-06-02 21:45:21 +03:00
if (IsExploratory () || tunnel->IsSlow ()) // always create new exploratory tunnel or if slow
{
CreateInboundTunnel ();
return;
}
2021-11-06 22:44:56 +03:00
auto outboundTunnel = GetNextOutboundTunnel (nullptr, tunnel->GetFarEndTransports ());
2014-08-09 06:44:33 +04:00
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel ();
2015-12-18 14:48:22 +03:00
LogPrint (eLogDebug, "Tunnels: Re-creating destination inbound tunnel...");
std::shared_ptr<TunnelConfig> config;
if (m_NumInboundHops > 0)
{
auto peers = tunnel->GetPeers();
if (peers.size ()&& ValidatePeers (peers))
config = std::make_shared<TunnelConfig>(tunnel->GetPeers (),
tunnel->IsShortBuildMessage (), tunnel->GetFarEndTransports ());
}
2021-07-21 20:08:12 +03:00
if (!m_NumInboundHops || config)
{
2021-07-21 20:08:12 +03:00
auto newTunnel = tunnels.CreateInboundTunnel (config, shared_from_this(), outboundTunnel);
if (newTunnel->IsEstablished ()) // zero hops
TunnelCreated (newTunnel);
else
newTunnel->SetRecreated (true);
}
}
2014-03-17 00:03:20 +04:00
void TunnelPool::CreateOutboundTunnel ()
{
2021-11-06 22:44:56 +03:00
LogPrint (eLogDebug, "Tunnels: Creating destination outbound tunnel...");
Path path;
if (SelectPeers (path, false))
{
2021-11-06 22:44:56 +03:00
auto inboundTunnel = GetNextInboundTunnel (nullptr, path.farEndTransports);
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel ();
if (!inboundTunnel)
{
2021-11-06 22:44:56 +03:00
LogPrint (eLogError, "Tunnels: Can't create outbound tunnel, no inbound tunnels found");
return;
}
2021-11-06 22:44:56 +03:00
if (m_LocalDestination && !m_LocalDestination->SupportsEncryptionType (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD))
path.isShort = false; // because can't handle ECIES encrypted reply
2021-11-06 22:44:56 +03:00
std::shared_ptr<TunnelConfig> config;
if (m_NumOutboundHops > 0)
config = std::make_shared<TunnelConfig>(path.peers, inboundTunnel->GetNextTunnelID (),
2021-11-06 22:44:56 +03:00
inboundTunnel->GetNextIdentHash (), path.isShort, path.farEndTransports);
std::shared_ptr<OutboundTunnel> tunnel;
if (path.isShort)
{
// TODO: implement it better
tunnel = tunnels.CreateOutboundTunnel (config, inboundTunnel->GetTunnelPool ());
tunnel->SetTunnelPool (shared_from_this ());
}
else
2021-11-06 22:44:56 +03:00
tunnel = tunnels.CreateOutboundTunnel (config, shared_from_this ());
if (tunnel && tunnel->IsEstablished ()) // zero hops
TunnelCreated (tunnel);
}
2014-09-14 15:50:01 +04:00
else
2021-11-06 22:44:56 +03:00
LogPrint (eLogError, "Tunnels: Can't create outbound tunnel, no peers available");
}
2015-01-27 22:55:46 +03:00
void TunnelPool::RecreateOutboundTunnel (std::shared_ptr<OutboundTunnel> tunnel)
2014-08-09 06:44:33 +04:00
{
2021-06-02 21:45:21 +03:00
if (IsExploratory () || tunnel->IsSlow ()) // always create new exploratory tunnel or if slow
{
CreateOutboundTunnel ();
return;
}
2021-11-06 22:44:56 +03:00
auto inboundTunnel = GetNextInboundTunnel (nullptr, tunnel->GetFarEndTransports ());
2014-08-09 06:44:33 +04:00
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel ();
2014-09-14 15:50:01 +04:00
if (inboundTunnel)
{
2015-12-18 14:48:22 +03:00
LogPrint (eLogDebug, "Tunnels: Re-creating destination outbound tunnel...");
std::shared_ptr<TunnelConfig> config;
if (m_NumOutboundHops > 0)
{
auto peers = tunnel->GetPeers();
if (peers.size () && ValidatePeers (peers))
config = std::make_shared<TunnelConfig>(peers, inboundTunnel->GetNextTunnelID (),
inboundTunnel->GetNextIdentHash (), inboundTunnel->IsShortBuildMessage (), tunnel->GetFarEndTransports ());
}
2020-12-05 16:26:21 +03:00
if (!m_NumOutboundHops || config)
{
2021-07-21 20:08:12 +03:00
auto newTunnel = tunnels.CreateOutboundTunnel (config, shared_from_this ());
if (newTunnel->IsEstablished ()) // zero hops
TunnelCreated (newTunnel);
}
}
2014-09-14 15:50:01 +04:00
else
2015-12-18 14:48:22 +03:00
LogPrint (eLogDebug, "Tunnels: Can't re-create outbound tunnel, no inbound tunnels found");
}
void TunnelPool::CreatePairedInboundTunnel (std::shared_ptr<OutboundTunnel> outboundTunnel)
{
2015-12-18 14:48:22 +03:00
LogPrint (eLogDebug, "Tunnels: Creating paired inbound tunnel...");
2020-12-05 16:26:21 +03:00
auto tunnel = tunnels.CreateInboundTunnel (
m_NumOutboundHops > 0 ? std::make_shared<TunnelConfig>(outboundTunnel->GetInvertedPeers (),
outboundTunnel->IsShortBuildMessage ()) : nullptr,
shared_from_this (), outboundTunnel);
2020-12-05 16:26:21 +03:00
if (tunnel->IsEstablished ()) // zero hops
TunnelCreated (tunnel);
}
void TunnelPool::SetCustomPeerSelector(ITunnelPeerSelector * selector)
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
m_CustomPeerSelector = selector;
}
void TunnelPool::UnsetCustomPeerSelector()
{
SetCustomPeerSelector(nullptr);
}
bool TunnelPool::HasCustomPeerSelector()
{
std::lock_guard<std::mutex> lock(m_CustomPeerSelectorMutex);
return m_CustomPeerSelector != nullptr;
}
2016-11-15 18:20:09 +03:00
bool TunnelPool::ValidatePeers (std::vector<std::shared_ptr<const i2p::data::IdentityEx> >& peers) const
{
bool highBandwidth = !IsExploratory ();
for (auto it: peers)
{
auto r = i2p::data::netdb.FindRouter (it->GetIdentHash ());
if (r)
{
if (r->IsHighCongestion (highBandwidth)) return false;
it = r->GetIdentity (); // use identity from updated RouterInfo
}
}
return true;
}
2016-11-15 18:20:09 +03:00
std::shared_ptr<InboundTunnel> TunnelPool::GetLowestLatencyInboundTunnel(std::shared_ptr<InboundTunnel> exclude) const
{
std::shared_ptr<InboundTunnel> tun = nullptr;
std::unique_lock<std::mutex> lock(m_InboundTunnelsMutex);
int min = 1000000;
2016-11-15 18:20:09 +03:00
for (const auto & itr : m_InboundTunnels) {
if(!itr->LatencyIsKnown()) continue;
auto l = itr->GetMeanLatency();
if (l >= min) continue;
tun = itr;
if(tun == exclude) continue;
min = l;
}
return tun;
}
2016-11-15 18:20:09 +03:00
std::shared_ptr<OutboundTunnel> TunnelPool::GetLowestLatencyOutboundTunnel(std::shared_ptr<OutboundTunnel> exclude) const
{
std::shared_ptr<OutboundTunnel> tun = nullptr;
std::unique_lock<std::mutex> lock(m_OutboundTunnelsMutex);
int min = 1000000;
2016-11-15 18:20:09 +03:00
for (const auto & itr : m_OutboundTunnels) {
if(!itr->LatencyIsKnown()) continue;
auto l = itr->GetMeanLatency();
if (l >= min) continue;
tun = itr;
if(tun == exclude) continue;
min = l;
}
return tun;
}
2014-03-14 20:35:02 +04:00
}
}