i2pd/libi2pd/SSU2.cpp

1012 lines
30 KiB
C++
Raw Normal View History

2022-02-04 23:01:18 +03:00
/*
* Copyright (c) 2022, The PurpleI2P Project
2022-02-04 23:01:18 +03:00
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <random>
2022-03-01 05:46:00 +03:00
#include "Log.h"
2022-02-28 04:15:14 +03:00
#include "RouterContext.h"
2022-02-05 23:58:39 +03:00
#include "Transports.h"
2022-03-23 21:06:55 +03:00
#include "NetDb.hpp"
2022-06-06 02:33:36 +03:00
#include "Config.h"
2022-02-04 23:01:18 +03:00
#include "SSU2.h"
namespace i2p
{
namespace transport
2022-06-06 02:33:36 +03:00
{
2022-03-12 00:17:44 +03:00
SSU2Server::SSU2Server ():
RunnableServiceWithWork ("SSU2"), m_ReceiveService ("SSU2r"),
m_SocketV4 (m_ReceiveService.GetService ()), m_SocketV6 (m_ReceiveService.GetService ()),
m_AddressV4 (boost::asio::ip::address_v4()), m_AddressV6 (boost::asio::ip::address_v6()),
2022-07-21 04:55:48 +03:00
m_TerminationTimer (GetService ()), m_ResendTimer (GetService ()),
m_IntroducersUpdateTimer (GetService ()), m_IntroducersUpdateTimerV6 (GetService ()),
m_IsPublished (true)
2022-03-01 05:46:00 +03:00
{
}
2022-03-12 00:17:44 +03:00
void SSU2Server::Start ()
{
if (!IsRunning ())
{
StartIOService ();
2022-07-21 04:55:48 +03:00
i2p::config::GetOption ("ssu2.published", m_IsPublished);
bool found = false;
2022-03-12 00:17:44 +03:00
auto& addresses = i2p::context.GetRouterInfo ().GetAddresses ();
for (const auto& address: addresses)
{
if (!address) continue;
2022-03-14 04:34:11 +03:00
if (address->transportStyle == i2p::data::RouterInfo::eTransportSSU2)
2022-03-12 00:17:44 +03:00
{
2022-03-18 01:45:14 +03:00
auto port = address->port;
2022-03-14 04:34:11 +03:00
if (!port)
{
uint16_t ssu2Port; i2p::config::GetOption ("ssu2.port", ssu2Port);
if (ssu2Port) port = ssu2Port;
else
{
uint16_t p; i2p::config::GetOption ("port", p);
if (p) port = p;
}
}
2022-03-14 04:34:11 +03:00
if (port)
{
2022-03-18 01:45:14 +03:00
if (address->IsV4 ())
2022-04-05 23:14:13 +03:00
{
found = true;
OpenSocket (boost::asio::ip::udp::endpoint (m_AddressV4, port));
m_ReceiveService.GetService ().post(
[this]()
{
2022-04-05 23:14:13 +03:00
Receive (m_SocketV4);
});
2022-07-21 04:55:48 +03:00
ScheduleIntroducersUpdateTimer (); // wait for 30 seconds and decide if we need introducers
}
2022-03-18 01:45:14 +03:00
if (address->IsV6 ())
{
found = true;
OpenSocket (boost::asio::ip::udp::endpoint (m_AddressV6, port));
m_ReceiveService.GetService ().post(
[this]()
{
2022-04-05 23:14:13 +03:00
Receive (m_SocketV6);
});
2022-07-21 04:55:48 +03:00
ScheduleIntroducersUpdateTimerV6 (); // wait for 30 seconds and decide if we need introducers
}
}
2022-03-14 04:34:11 +03:00
else
2022-03-18 01:45:14 +03:00
LogPrint (eLogError, "SSU2: Can't start server because port not specified");
2022-03-12 00:17:44 +03:00
}
2022-03-19 03:21:31 +03:00
}
if (found)
m_ReceiveService.Start ();
2022-03-19 03:21:31 +03:00
ScheduleTermination ();
}
2022-03-12 00:17:44 +03:00
}
2022-03-12 00:17:44 +03:00
void SSU2Server::Stop ()
{
2022-07-27 01:46:05 +03:00
if (IsRunning ())
{
m_TerminationTimer.cancel ();
m_ResendTimer.cancel ();
m_IntroducersUpdateTimer.cancel ();
m_IntroducersUpdateTimerV6.cancel ();
}
auto sessions = m_Sessions;
for (auto& it: sessions)
2022-07-11 00:13:25 +03:00
{
it.second->RequestTermination (eSSU2TerminationReasonRouterShutdown);
2022-06-10 19:50:55 +03:00
it.second->Done ();
2022-07-11 00:13:25 +03:00
}
if (context.SupportsV4 () || context.SupportsV6 ())
m_ReceiveService.Stop ();
2022-06-10 19:50:55 +03:00
m_SocketV4.close ();
m_SocketV6.close ();
2022-03-12 00:17:44 +03:00
StopIOService ();
2022-07-27 01:46:05 +03:00
m_Sessions.clear ();
m_SessionsByRouterHash.clear ();
m_PendingOutgoingSessions.clear ();
m_Relays.clear ();
m_Introducers.clear ();
m_IntroducersV6.clear ();
}
2022-03-15 02:25:59 +03:00
void SSU2Server::SetLocalAddress (const boost::asio::ip::address& localAddress)
{
if (localAddress.is_unspecified ()) return;
if (localAddress.is_v4 ())
{
m_AddressV4 = localAddress;
int mtu = i2p::util::net::GetMTU (localAddress);
if (mtu < (int)SSU2_MIN_PACKET_SIZE) mtu = SSU2_MIN_PACKET_SIZE;
if (mtu > (int)SSU2_MAX_PACKET_SIZE) mtu = SSU2_MAX_PACKET_SIZE;
i2p::context.SetMTU (mtu, true);
}
else if (localAddress.is_v6 ())
{
m_AddressV6 = localAddress;
int maxMTU = i2p::util::net::GetMaxMTU (localAddress.to_v6 ());
int mtu = i2p::util::net::GetMTU (localAddress);
if (mtu > maxMTU) mtu = maxMTU;
if (mtu < (int)SSU2_MIN_PACKET_SIZE) mtu = SSU2_MIN_PACKET_SIZE;
i2p::context.SetMTU (mtu, false);
}
}
bool SSU2Server::IsSupported (const boost::asio::ip::address& addr) const
{
if (addr.is_v4 ())
{
if (m_SocketV4.is_open ())
return true;
}
else if (addr.is_v6 ())
{
if (m_SocketV6.is_open ())
return true;
}
return false;
}
2022-03-18 01:45:14 +03:00
boost::asio::ip::udp::socket& SSU2Server::OpenSocket (const boost::asio::ip::udp::endpoint& localEndpoint)
2022-03-01 05:46:00 +03:00
{
2022-04-05 23:14:13 +03:00
boost::asio::ip::udp::socket& socket = localEndpoint.address ().is_v6 () ? m_SocketV6 : m_SocketV4;
2022-03-01 05:46:00 +03:00
try
{
2022-03-18 01:45:14 +03:00
socket.open (localEndpoint.protocol ());
if (localEndpoint.address ().is_v6 ())
socket.set_option (boost::asio::ip::v6_only (true));
socket.set_option (boost::asio::socket_base::receive_buffer_size (SSU2_SOCKET_RECEIVE_BUFFER_SIZE));
socket.set_option (boost::asio::socket_base::send_buffer_size (SSU2_SOCKET_SEND_BUFFER_SIZE));
socket.bind (localEndpoint);
LogPrint (eLogInfo, "SSU2: Start listening on ", localEndpoint);
2022-03-01 05:46:00 +03:00
}
catch (std::exception& ex )
{
LogPrint (eLogError, "SSU2: Failed to bind to ", localEndpoint, ": ", ex.what());
2022-03-18 01:45:14 +03:00
ThrowFatal ("Unable to start SSU2 transport on ", localEndpoint, ": ", ex.what ());
2022-03-01 05:46:00 +03:00
}
2022-03-18 01:45:14 +03:00
return socket;
2022-03-01 05:46:00 +03:00
}
2022-03-18 01:45:14 +03:00
void SSU2Server::Receive (boost::asio::ip::udp::socket& socket)
2022-03-15 02:25:59 +03:00
{
Packet * packet = m_PacketsPool.AcquireMt ();
2022-07-10 00:05:23 +03:00
socket.async_receive_from (boost::asio::buffer (packet->buf, SSU2_MAX_PACKET_SIZE), packet->from,
2022-03-18 01:45:14 +03:00
std::bind (&SSU2Server::HandleReceivedFrom, this, std::placeholders::_1, std::placeholders::_2, packet, std::ref (socket)));
2022-03-15 02:25:59 +03:00
}
void SSU2Server::HandleReceivedFrom (const boost::system::error_code& ecode, size_t bytes_transferred,
2022-03-18 01:45:14 +03:00
Packet * packet, boost::asio::ip::udp::socket& socket)
2022-03-15 02:25:59 +03:00
{
if (!ecode)
{
2022-03-26 23:35:07 +03:00
i2p::transport::transports.UpdateReceivedBytes (bytes_transferred);
2022-03-15 02:25:59 +03:00
packet->len = bytes_transferred;
2022-04-12 18:42:51 +03:00
boost::system::error_code ec;
size_t moreBytes = socket.available (ec);
2022-04-13 19:33:59 +03:00
if (!ec && moreBytes)
2022-04-12 18:42:51 +03:00
{
2022-04-13 19:33:59 +03:00
std::vector<Packet *> packets;
packets.push_back (packet);
2022-04-12 18:42:51 +03:00
while (moreBytes && packets.size () < 32)
{
packet = m_PacketsPool.AcquireMt ();
2022-07-15 03:12:27 +03:00
packet->len = socket.receive_from (boost::asio::buffer (packet->buf, SSU2_MAX_PACKET_SIZE), packet->from, 0, ec);
2022-04-12 18:42:51 +03:00
if (!ec)
{
i2p::transport::transports.UpdateReceivedBytes (packet->len);
packets.push_back (packet);
moreBytes = socket.available(ec);
if (ec) break;
}
else
{
LogPrint (eLogError, "SSU2: receive_from error: code ", ec.value(), ": ", ec.message ());
m_PacketsPool.ReleaseMt (packet);
break;
}
}
2022-04-13 19:33:59 +03:00
GetService ().post (std::bind (&SSU2Server::HandleReceivedPackets, this, packets));
}
2022-04-13 19:33:59 +03:00
else
GetService ().post (std::bind (&SSU2Server::HandleReceivedPacket, this, packet));
2022-03-18 01:45:14 +03:00
Receive (socket);
2022-03-15 02:25:59 +03:00
}
else
{
m_PacketsPool.ReleaseMt (packet);
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "SSU2: Receive error: code ", ecode.value(), ": ", ecode.message ());
2022-03-18 01:45:14 +03:00
auto ep = socket.local_endpoint ();
socket.close ();
OpenSocket (ep);
Receive (socket);
2022-03-15 02:25:59 +03:00
}
}
}
2022-04-05 23:14:13 +03:00
2022-04-13 19:33:59 +03:00
void SSU2Server::HandleReceivedPacket (Packet * packet)
{
if (packet)
{
ProcessNextPacket (packet->buf, packet->len, packet->from);
m_PacketsPool.ReleaseMt (packet);
2022-07-26 01:46:25 +03:00
if (m_LastSession && m_LastSession->GetState () != eSSU2SessionStateTerminated)
m_LastSession->FlushData ();
}
}
2022-04-13 19:33:59 +03:00
void SSU2Server::HandleReceivedPackets (std::vector<Packet *> packets)
2022-04-05 23:14:13 +03:00
{
2022-04-12 18:42:51 +03:00
for (auto& packet: packets)
2022-04-05 23:14:13 +03:00
ProcessNextPacket (packet->buf, packet->len, packet->from);
2022-04-12 18:42:51 +03:00
m_PacketsPool.ReleaseMt (packets);
2022-07-26 01:46:25 +03:00
if (m_LastSession && m_LastSession->GetState () != eSSU2SessionStateTerminated)
m_LastSession->FlushData ();
}
2022-03-27 23:39:58 +03:00
void SSU2Server::AddSession (std::shared_ptr<SSU2Session> session)
2022-02-28 04:15:14 +03:00
{
2022-03-27 23:39:58 +03:00
if (session)
{
2022-03-27 23:39:58 +03:00
m_Sessions.emplace (session->GetConnID (), session);
2022-04-28 20:11:51 +03:00
AddSessionByRouterHash (session);
}
}
2022-02-28 04:15:14 +03:00
2022-03-27 23:39:58 +03:00
void SSU2Server::RemoveSession (uint64_t connID)
2022-03-01 05:46:00 +03:00
{
2022-04-28 20:11:51 +03:00
auto it = m_Sessions.find (connID);
if (it != m_Sessions.end ())
{
2022-04-28 20:11:51 +03:00
auto ident = it->second->GetRemoteIdentity ();
if (ident)
m_SessionsByRouterHash.erase (ident->GetIdentHash ());
2022-07-09 02:06:09 +03:00
if (m_LastSession == it->second)
m_LastSession = nullptr;
2022-04-28 20:11:51 +03:00
m_Sessions.erase (it);
}
}
void SSU2Server::AddSessionByRouterHash (std::shared_ptr<SSU2Session> session)
2022-04-28 20:11:51 +03:00
{
if (session)
{
2022-04-28 20:11:51 +03:00
auto ident = session->GetRemoteIdentity ();
if (ident)
{
auto ret = m_SessionsByRouterHash.emplace (ident->GetIdentHash (), session);
if (!ret.second)
{
// session already exists
LogPrint (eLogWarning, "SSU2: Session to ", ident->GetIdentHash ().ToBase64 (), " already exists");
2022-04-28 20:11:51 +03:00
// terminate existing
GetService ().post (std::bind (&SSU2Session::RequestTermination, ret.first->second, eSSU2TerminationReasonReplacedByNewSession));
2022-04-28 20:11:51 +03:00
// update session
ret.first->second = session;
}
}
}
}
bool SSU2Server::AddPendingOutgoingSession (std::shared_ptr<SSU2Session> session)
2022-03-27 23:39:58 +03:00
{
if (!session) return false;
return m_PendingOutgoingSessions.emplace (session->GetRemoteEndpoint (), session).second;
2022-03-01 05:46:00 +03:00
}
std::shared_ptr<SSU2Session> SSU2Server::FindSession (const i2p::data::IdentHash& ident) const
{
auto it = m_SessionsByRouterHash.find (ident);
if (it != m_SessionsByRouterHash.end ())
return it->second;
return nullptr;
}
2022-06-10 01:04:37 +03:00
std::shared_ptr<SSU2Session> SSU2Server::FindPendingOutgoingSession (const boost::asio::ip::udp::endpoint& ep) const
{
auto it = m_PendingOutgoingSessions.find (ep);
if (it != m_PendingOutgoingSessions.end ())
return it->second;
return nullptr;
}
void SSU2Server::RemovePendingOutgoingSession (const boost::asio::ip::udp::endpoint& ep)
{
m_PendingOutgoingSessions.erase (ep);
}
std::shared_ptr<SSU2Session> SSU2Server::GetRandomSession (
i2p::data::RouterInfo::CompatibleTransports remoteTransports, const i2p::data::IdentHash& excluded) const
2022-06-10 01:04:37 +03:00
{
if (m_Sessions.empty ()) return nullptr;
uint16_t ind;
RAND_bytes ((uint8_t *)&ind, sizeof (ind));
ind %= m_Sessions.size ();
auto it = m_Sessions.begin ();
std::advance (it, ind);
while (it != m_Sessions.end ())
{
if ((it->second->GetRemoteTransports () & remoteTransports) &&
it->second->GetRemoteIdentity ()->GetIdentHash () != excluded)
2022-06-10 01:04:37 +03:00
return it->second;
it++;
}
// not found, try from begining
it = m_Sessions.begin ();
while (it != m_Sessions.end () && ind)
{
if ((it->second->GetRemoteTransports () & remoteTransports) &&
it->second->GetRemoteIdentity ()->GetIdentHash () != excluded)
2022-06-10 01:04:37 +03:00
return it->second;
it++; ind--;
}
return nullptr;
}
void SSU2Server::AddRelay (uint32_t tag, std::shared_ptr<SSU2Session> relay)
{
m_Relays.emplace (tag, relay);
}
void SSU2Server::RemoveRelay (uint32_t tag)
{
m_Relays.erase (tag);
}
std::shared_ptr<SSU2Session> SSU2Server::FindRelaySession (uint32_t tag)
{
auto it = m_Relays.find (tag);
if (it != m_Relays.end ())
{
if (it->second->IsEstablished ())
return it->second;
else
m_Relays.erase (it);
}
return nullptr;
}
2022-03-01 05:46:00 +03:00
void SSU2Server::ProcessNextPacket (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
2022-02-28 04:15:14 +03:00
{
if (len < 24) return;
2022-03-05 05:51:40 +03:00
uint64_t connID;
2022-02-28 04:15:14 +03:00
memcpy (&connID, buf, 8);
2022-03-05 05:51:40 +03:00
connID ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), buf + (len - 24));
if (!m_LastSession || m_LastSession->GetConnID () != connID)
2022-02-28 04:15:14 +03:00
{
2022-04-12 18:42:51 +03:00
if (m_LastSession) m_LastSession->FlushData ();
auto it = m_Sessions.find (connID);
if (it != m_Sessions.end ())
m_LastSession = it->second;
else
m_LastSession = nullptr;
}
if (m_LastSession)
{
2022-05-12 00:48:25 +03:00
switch (m_LastSession->GetState ())
{
case eSSU2SessionStateEstablished:
case eSSU2SessionStateSessionConfirmedSent:
2022-05-12 00:48:25 +03:00
m_LastSession->ProcessData (buf, len);
break;
case eSSU2SessionStateSessionCreatedSent:
if (!m_LastSession->ProcessSessionConfirmed (buf, len))
{
2022-07-27 02:56:30 +03:00
m_LastSession->Done ();
m_LastSession = nullptr;
}
break;
2022-05-12 00:48:25 +03:00
case eSSU2SessionStateIntroduced:
if (m_LastSession->GetRemoteEndpoint ().address ().is_unspecified ())
m_LastSession->SetRemoteEndpoint (senderEndpoint);
if (m_LastSession->GetRemoteEndpoint () == senderEndpoint)
m_LastSession->ProcessHolePunch (buf, len);
else
{
LogPrint (eLogWarning, "SSU2: HolePunch endpoint ", senderEndpoint,
" doesn't match RelayResponse ", m_LastSession->GetRemoteEndpoint ());
2022-07-27 02:56:30 +03:00
m_LastSession->Done ();
m_LastSession = nullptr;
}
2022-05-12 00:48:25 +03:00
break;
case eSSU2SessionStatePeerTest:
m_LastSession->SetRemoteEndpoint (senderEndpoint);
m_LastSession->ProcessPeerTest (buf, len);
break;
2022-07-09 02:06:09 +03:00
case eSSU2SessionStateClosing:
2022-07-26 01:46:25 +03:00
m_LastSession->ProcessData (buf, len); // we might receive termintaion block
if (m_LastSession && m_LastSession->GetState () != eSSU2SessionStateTerminated)
m_LastSession->RequestTermination (eSSU2TerminationReasonIdleTimeout); // send termination again
2022-07-09 02:06:09 +03:00
break;
2022-06-27 04:35:26 +03:00
case eSSU2SessionStateTerminated:
m_LastSession = nullptr;
break;
2022-05-12 00:48:25 +03:00
default:
LogPrint (eLogWarning, "SSU2: Invalid session state ", (int)m_LastSession->GetState ());
}
}
else
2022-03-01 05:46:00 +03:00
{
2022-03-20 22:10:18 +03:00
// check pending sessions if it's SessionCreated or Retry
2022-03-01 05:46:00 +03:00
auto it1 = m_PendingOutgoingSessions.find (senderEndpoint);
if (it1 != m_PendingOutgoingSessions.end ())
{
if (it1->second->GetState () == eSSU2SessionStateSessionRequestSent &&
it1->second->ProcessSessionCreated (buf, len))
m_PendingOutgoingSessions.erase (it1); // we are done with that endpoint
else
it1->second->ProcessRetry (buf, len);
2022-03-01 05:46:00 +03:00
}
else
{
// assume new incoming session
2022-03-06 02:39:27 +03:00
auto session = std::make_shared<SSU2Session> (*this);
2022-03-09 05:33:21 +03:00
session->SetRemoteEndpoint (senderEndpoint);
2022-03-24 04:48:41 +03:00
session->ProcessFirstIncomingMessage (connID, buf, len);
}
}
}
2022-03-01 05:46:00 +03:00
void SSU2Server::Send (const uint8_t * header, size_t headerLen, const uint8_t * payload, size_t payloadLen,
2022-03-26 23:35:07 +03:00
const boost::asio::ip::udp::endpoint& to)
{
std::vector<boost::asio::const_buffer> bufs
{
boost::asio::buffer (header, headerLen),
boost::asio::buffer (payload, payloadLen)
};
boost::system::error_code ec;
if (to.address ().is_v6 ())
m_SocketV6.send_to (bufs, to, 0, ec);
else
2022-04-05 23:14:13 +03:00
m_SocketV4.send_to (bufs, to, 0, ec);
if (!ec)
2022-04-22 22:03:49 +03:00
i2p::transport::transports.UpdateSentBytes (headerLen + payloadLen);
else
LogPrint (eLogError, "SSU2: Send exception: ", ec.message (), " to ", to);
}
void SSU2Server::Send (const uint8_t * header, size_t headerLen, const uint8_t * headerX, size_t headerXLen,
2022-03-01 05:46:00 +03:00
const uint8_t * payload, size_t payloadLen, const boost::asio::ip::udp::endpoint& to)
{
std::vector<boost::asio::const_buffer> bufs
{
boost::asio::buffer (header, headerLen),
boost::asio::buffer (headerX, headerXLen),
boost::asio::buffer (payload, payloadLen)
};
boost::system::error_code ec;
if (to.address ().is_v6 ())
m_SocketV6.send_to (bufs, to, 0, ec);
else
2022-04-05 23:14:13 +03:00
m_SocketV4.send_to (bufs, to, 0, ec);
2022-04-22 22:03:49 +03:00
if (!ec)
i2p::transport::transports.UpdateSentBytes (headerLen + headerXLen + payloadLen);
else
2022-04-22 22:03:49 +03:00
LogPrint (eLogError, "SSU2: Send exception: ", ec.message (), " to ", to);
2022-05-04 20:58:06 +03:00
}
2022-03-17 04:11:48 +03:00
bool SSU2Server::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router,
std::shared_ptr<const i2p::data::RouterInfo::Address> address, bool peerTest)
2022-03-17 04:11:48 +03:00
{
if (router && address)
{
2022-07-23 21:32:16 +03:00
// check if no session
auto it = m_SessionsByRouterHash.find (router->GetIdentHash ());
if (it != m_SessionsByRouterHash.end ())
{
// session with router found, trying to send peer test if requested
if (peerTest && it->second->IsEstablished ())
{
auto session = it->second;
GetService ().post ([session]() { session->SendPeerTest (); });
}
return false;
}
// check is no pending session
bool isValidEndpoint = !address->host.is_unspecified () && address->port;
if (isValidEndpoint)
{
2022-07-07 02:33:02 +03:00
if (i2p::util::net::IsInReservedRange(address->host)) return false;
auto s = FindPendingOutgoingSession (boost::asio::ip::udp::endpoint (address->host, address->port));
if (s)
{
if (peerTest)
{
// if peer test requested add it to the list for pending session
auto onEstablished = s->GetOnEstablished ();
if (onEstablished)
s->SetOnEstablished ([s, onEstablished]()
{
onEstablished ();
s->SendPeerTest ();
});
else
s->SetOnEstablished ([s]() { s->SendPeerTest (); });
}
return false;
}
}
auto session = std::make_shared<SSU2Session> (*this, router, address);
if (peerTest)
session->SetOnEstablished ([session]() {session->SendPeerTest (); });
if (address->UsesIntroducer ())
GetService ().post (std::bind (&SSU2Server::ConnectThroughIntroducer, this, session));
else if (isValidEndpoint) // we can't connect without endpoint
GetService ().post ([session]() { session->Connect (); });
else
return false;
}
2022-03-17 04:11:48 +03:00
else
return false;
return true;
}
2022-03-19 03:21:31 +03:00
void SSU2Server::ConnectThroughIntroducer (std::shared_ptr<SSU2Session> session)
2022-05-01 17:33:25 +03:00
{
if (!session) return;
auto address = session->GetAddress ();
if (!address) return;
2022-06-19 23:40:03 +03:00
session->WaitForIntroduction ();
2022-05-01 17:33:25 +03:00
// try to find existing session first
for (auto& it: address->ssu->introducers)
{
auto it1 = m_SessionsByRouterHash.find (it.iKey);
if (it1 != m_SessionsByRouterHash.end ())
{
it1->second->Introduce (session, it.iTag);
return;
}
}
2022-05-01 17:33:25 +03:00
// we have to start a new session to an introducer
2022-06-24 01:23:25 +03:00
auto ts = i2p::util::GetSecondsSinceEpoch ();
2022-05-01 17:33:25 +03:00
std::shared_ptr<i2p::data::RouterInfo> r;
uint32_t relayTag = 0;
if (!address->ssu->introducers.empty ())
{
std::vector<int> indicies;
for (int i = 0; i < (int)address->ssu->introducers.size (); i++) indicies.push_back(i);
if (indicies.size () > 1)
std::shuffle (indicies.begin(), indicies.end(), std::mt19937(std::random_device()()));
for (auto i: indicies)
{
const auto& introducer = address->ssu->introducers[indicies[i]];
if (introducer.iTag && ts < introducer.iExp)
{
r = i2p::data::netdb.FindRouter (introducer.iKey);
if (r && r->IsReachableFrom (i2p::context.GetRouterInfo ()))
{
relayTag = introducer.iTag;
if (relayTag) break;
}
}
}
}
2022-05-01 17:33:25 +03:00
if (r)
{
if (relayTag)
{
// introducer and tag found connect to it through SSU2
2022-05-01 17:33:25 +03:00
auto addr = address->IsV6 () ? r->GetSSU2V6Address () : r->GetSSU2V4Address ();
if (addr)
{
bool isValidEndpoint = !addr->host.is_unspecified () && addr->port &&
!i2p::util::net::IsInReservedRange(addr->host);
if (isValidEndpoint)
{
auto s = FindPendingOutgoingSession (boost::asio::ip::udp::endpoint (addr->host, addr->port));
if (!s)
{
s = std::make_shared<SSU2Session> (*this, r, addr);
s->SetOnEstablished ([session, s, relayTag]() { s->Introduce (session, relayTag); });
s->Connect ();
}
else
2022-05-01 17:33:25 +03:00
{
auto onEstablished = s->GetOnEstablished ();
if (onEstablished)
s->SetOnEstablished ([session, s, relayTag, onEstablished]()
{
onEstablished ();
s->Introduce (session, relayTag);
});
else
s->SetOnEstablished ([session, s, relayTag]() {s->Introduce (session, relayTag); });
}
}
}
}
2022-05-01 17:33:25 +03:00
}
else
{
// introducers not found, try to request them
for (auto& it: address->ssu->introducers)
2022-06-24 01:23:25 +03:00
if (it.iTag && ts < it.iExp)
i2p::data::netdb.RequestDestination (it.iKey);
}
}
2022-06-02 04:51:02 +03:00
bool SSU2Server::StartPeerTest (std::shared_ptr<const i2p::data::RouterInfo> router, bool v4)
{
if (!router) return false;
auto addr = v4 ? router->GetSSU2V4Address () : router->GetSSU2V6Address ();
if (!addr) return false;
auto it = m_SessionsByRouterHash.find (router->GetIdentHash ());
if (it != m_SessionsByRouterHash.end ())
{
auto s = it->second;
if (it->second->IsEstablished ())
GetService ().post ([s]() { s->SendPeerTest (); });
else
s->SetOnEstablished ([s]() { s->SendPeerTest (); });
return true;
}
else
CreateSession (router, addr, true);
2022-06-02 04:51:02 +03:00
return true;
}
2022-03-19 03:21:31 +03:00
void SSU2Server::ScheduleTermination ()
{
m_TerminationTimer.expires_from_now (boost::posix_time::seconds(SSU2_TERMINATION_CHECK_TIMEOUT));
m_TerminationTimer.async_wait (std::bind (&SSU2Server::HandleTerminationTimer,
this, std::placeholders::_1));
}
void SSU2Server::HandleTerminationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto it = m_PendingOutgoingSessions.begin (); it != m_PendingOutgoingSessions.end ();)
{
if (it->second->IsTerminationTimeoutExpired (ts))
{
//it->second->Terminate ();
it = m_PendingOutgoingSessions.erase (it);
2022-03-19 03:21:31 +03:00
}
else
it++;
}
2022-07-09 02:06:09 +03:00
for (auto it: m_Sessions)
2022-03-19 03:21:31 +03:00
{
2022-07-09 02:06:09 +03:00
auto state = it.second->GetState ();
if (state == eSSU2SessionStateTerminated || state == eSSU2SessionStateClosing)
2022-07-27 02:56:30 +03:00
it.second->Done ();
2022-07-09 02:06:09 +03:00
else if (it.second->IsTerminationTimeoutExpired (ts))
2022-03-19 03:21:31 +03:00
{
2022-07-09 02:06:09 +03:00
if (it.second->IsEstablished ())
2022-07-10 00:05:23 +03:00
it.second->RequestTermination (eSSU2TerminationReasonIdleTimeout);
2022-07-09 02:06:09 +03:00
else
2022-07-27 02:56:30 +03:00
it.second->Done ();
2022-03-19 03:21:31 +03:00
}
else
2022-07-09 02:06:09 +03:00
it.second->CleanUp (ts);
2022-03-19 03:21:31 +03:00
}
2022-03-24 02:13:44 +03:00
2022-07-24 23:44:02 +03:00
for (auto it = m_SessionsByRouterHash.begin (); it != m_SessionsByRouterHash.begin ();)
{
if (it->second && it->second->GetState () == eSSU2SessionStateTerminated)
it = m_SessionsByRouterHash.erase (it);
else
it++;
}
for (auto it = m_Relays.begin (); it != m_Relays.begin ();)
{
if (it->second && it->second->GetState () == eSSU2SessionStateTerminated)
it = m_Relays.erase (it);
else
it++;
}
2022-03-24 02:13:44 +03:00
for (auto it = m_IncomingTokens.begin (); it != m_IncomingTokens.end (); )
{
if (ts > it->second.second)
it = m_IncomingTokens.erase (it);
2022-03-24 02:13:44 +03:00
else
it++;
}
for (auto it = m_OutgoingTokens.begin (); it != m_OutgoingTokens.end (); )
{
if (ts > it->second.second)
it = m_OutgoingTokens.erase (it);
2022-03-24 02:13:44 +03:00
else
it++;
}
2022-07-24 23:44:02 +03:00
m_PacketsPool.CleanUpMt ();
2022-03-19 03:21:31 +03:00
ScheduleTermination ();
}
2022-03-24 02:13:44 +03:00
}
2022-03-31 22:35:55 +03:00
void SSU2Server::ScheduleResend ()
{
2022-07-29 02:30:08 +03:00
m_ResendTimer.expires_from_now (boost::posix_time::milliseconds(SSU2_RESEND_CHECK_TIMEOUT));
2022-03-31 22:35:55 +03:00
m_ResendTimer.async_wait (std::bind (&SSU2Server::HandleResendTimer,
this, std::placeholders::_1));
}
2022-03-31 22:35:55 +03:00
void SSU2Server::HandleResendTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
2022-07-29 02:30:08 +03:00
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
2022-03-31 22:35:55 +03:00
for (auto it: m_Sessions)
it.second->Resend (ts);
for (auto it: m_PendingOutgoingSessions)
it.second->Resend (ts);
2022-03-31 22:35:55 +03:00
ScheduleResend ();
}
}
2022-03-24 02:13:44 +03:00
void SSU2Server::UpdateOutgoingToken (const boost::asio::ip::udp::endpoint& ep, uint64_t token, uint32_t exp)
{
m_OutgoingTokens[ep] = {token, exp};
}
2022-03-24 02:13:44 +03:00
uint64_t SSU2Server::FindOutgoingToken (const boost::asio::ip::udp::endpoint& ep) const
2022-03-24 02:13:44 +03:00
{
auto it = m_OutgoingTokens.find (ep);
if (it != m_OutgoingTokens.end ())
2022-06-19 15:52:47 +03:00
{
if (i2p::util::GetSecondsSinceEpoch () + SSU2_TOKEN_EXPIRATION_THRESHOLD > it->second.second)
return 0; // token expired
2022-03-24 02:13:44 +03:00
return it->second.first;
2022-06-19 15:52:47 +03:00
}
2022-03-24 02:13:44 +03:00
return 0;
}
2022-03-24 04:48:41 +03:00
uint64_t SSU2Server::GetIncomingToken (const boost::asio::ip::udp::endpoint& ep)
2022-03-24 04:48:41 +03:00
{
auto it = m_IncomingTokens.find (ep);
if (it != m_IncomingTokens.end ())
return it->second.first;
2022-03-24 04:48:41 +03:00
uint64_t token;
RAND_bytes ((uint8_t *)&token, 8);
m_IncomingTokens.emplace (ep, std::make_pair (token, i2p::util::GetSecondsSinceEpoch () + SSU2_TOKEN_EXPIRATION_TIMEOUT));
return token;
}
std::pair<uint64_t, uint32_t> SSU2Server::NewIncomingToken (const boost::asio::ip::udp::endpoint& ep)
{
m_IncomingTokens.erase (ep); // drop previous
uint64_t token;
RAND_bytes ((uint8_t *)&token, 8);
auto ret = std::make_pair (token, i2p::util::GetSecondsSinceEpoch () + SSU2_NEXT_TOKEN_EXPIRATION_TIMEOUT);
2022-06-14 00:55:41 +03:00
m_IncomingTokens.emplace (ep, ret);
return ret;
}
2022-07-11 00:13:25 +03:00
std::list<std::shared_ptr<SSU2Session> > SSU2Server::FindIntroducers (int maxNumIntroducers,
bool v4, const std::set<i2p::data::IdentHash>& excluded) const
{
std::list<std::shared_ptr<SSU2Session> > ret;
for (const auto& s : m_Sessions)
{
2022-07-30 01:27:21 +03:00
if (s.second->IsEstablished () && (s.second->GetRelayTag () && s.second->IsOutgoing ()) &&
2022-07-11 00:13:25 +03:00
!excluded.count (s.second->GetRemoteIdentity ()->GetIdentHash ()) &&
2022-07-11 11:16:07 +03:00
((v4 && (s.second->GetRemoteTransports () & i2p::data::RouterInfo::eSSU2V4)) ||
(!v4 && (s.second->GetRemoteTransports () & i2p::data::RouterInfo::eSSU2V6))))
2022-07-11 00:13:25 +03:00
ret.push_back (s.second);
}
if ((int)ret.size () > maxNumIntroducers)
{
// shink ret randomly
int sz = ret.size () - maxNumIntroducers;
for (int i = 0; i < sz; i++)
{
auto ind = rand () % ret.size ();
auto it = ret.begin ();
std::advance (it, ind);
ret.erase (it);
}
}
return ret;
}
void SSU2Server::UpdateIntroducers (bool v4)
{
2022-07-20 01:38:58 +03:00
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
std::list<i2p::data::IdentHash> newList;
2022-07-11 00:13:25 +03:00
auto& introducers = v4 ? m_Introducers : m_IntroducersV6;
2022-07-20 01:38:58 +03:00
std::set<i2p::data::IdentHash> excluded;
2022-07-11 00:13:25 +03:00
for (const auto& it : introducers)
{
std::shared_ptr<SSU2Session> session;
auto it1 = m_SessionsByRouterHash.find (it);
if (it1 != m_SessionsByRouterHash.end ())
2022-07-23 21:32:16 +03:00
{
session = it1->second;
2022-07-23 21:32:16 +03:00
excluded.insert (it);
}
if (session && session->IsEstablished ())
2022-07-11 00:13:25 +03:00
{
if (ts < session->GetCreationTime () + SSU2_TO_INTRODUCER_SESSION_EXPIRATION)
session->SendKeepAlive ();
if (ts < session->GetCreationTime () + SSU2_TO_INTRODUCER_SESSION_DURATION)
2022-07-20 01:38:58 +03:00
newList.push_back (it);
else
session = nullptr;
2022-07-11 00:13:25 +03:00
}
if (!session)
i2p::context.RemoveSSU2Introducer (it, v4);
2022-07-11 00:13:25 +03:00
}
if (newList.size () < SSU2_MAX_NUM_INTRODUCERS)
{
2022-07-20 01:38:58 +03:00
auto sessions = FindIntroducers (SSU2_MAX_NUM_INTRODUCERS - newList.size (), v4, excluded);
if (sessions.empty () && !introducers.empty ())
{
// bump creation time for previous introducers if no new sessions found
LogPrint (eLogDebug, "SSU2: No new introducers found. Trying to reuse existing");
for (auto& it : introducers)
{
auto it1 = m_SessionsByRouterHash.find (it);
if (it1 != m_SessionsByRouterHash.end ())
2022-07-23 21:32:16 +03:00
{
auto session = it1->second;
if (session->IsEstablished ())
{
session->SetCreationTime (session->GetCreationTime () + SSU2_TO_INTRODUCER_SESSION_DURATION);
if (std::find (newList.begin (), newList.end (), it) == newList.end ())
newList.push_back (it);
}
}
}
2022-07-20 01:38:58 +03:00
}
2022-07-11 00:13:25 +03:00
for (const auto& it : sessions)
{
i2p::data::RouterInfo::Introducer introducer;
introducer.iTag = it->GetRelayTag ();
introducer.iKey = it->GetRemoteIdentity ()->GetIdentHash ();
introducer.iExp = it->GetCreationTime () + SSU2_TO_INTRODUCER_SESSION_EXPIRATION;
excluded.insert (it->GetRemoteIdentity ()->GetIdentHash ());
if (i2p::context.AddSSU2Introducer (introducer, v4))
{
LogPrint (eLogDebug, "SSU2: Introducer added ", it->GetRelayTag (), " at ",
i2p::data::GetIdentHashAbbreviation (it->GetRemoteIdentity ()->GetIdentHash ()));
newList.push_back (it->GetRemoteIdentity ()->GetIdentHash ());
if (newList.size () >= SSU2_MAX_NUM_INTRODUCERS) break;
}
2022-07-11 00:13:25 +03:00
}
}
introducers = newList;
2022-07-20 01:38:58 +03:00
if (introducers.size () < SSU2_MAX_NUM_INTRODUCERS)
{
for (auto i = introducers.size (); i < SSU2_MAX_NUM_INTRODUCERS; i++)
{
auto introducer = i2p::data::netdb.GetRandomSSU2Introducer (v4, excluded);
if (introducer)
{
auto address = v4 ? introducer->GetSSU2V4Address () : introducer->GetSSU2V6Address ();
if (address)
{
CreateSession (introducer, address);
excluded.insert (introducer->GetIdentHash ());
}
}
else
{
LogPrint (eLogDebug, "SSU2: Can't find more introducers");
break;
}
}
}
2022-07-21 04:55:48 +03:00
}
void SSU2Server::ScheduleIntroducersUpdateTimer ()
{
if (m_IsPublished)
{
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU2_KEEP_ALIVE_INTERVAL));
m_IntroducersUpdateTimer.async_wait (std::bind (&SSU2Server::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, true));
}
}
void SSU2Server::RescheduleIntroducersUpdateTimer ()
{
if (m_IsPublished)
{
m_IntroducersUpdateTimer.cancel ();
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU2_KEEP_ALIVE_INTERVAL/2));
m_IntroducersUpdateTimer.async_wait (std::bind (&SSU2Server::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, true));
}
}
void SSU2Server::ScheduleIntroducersUpdateTimerV6 ()
{
if (m_IsPublished)
{
m_IntroducersUpdateTimerV6.expires_from_now (boost::posix_time::seconds(SSU2_KEEP_ALIVE_INTERVAL));
m_IntroducersUpdateTimerV6.async_wait (std::bind (&SSU2Server::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, false));
}
}
void SSU2Server::RescheduleIntroducersUpdateTimerV6 ()
{
if (m_IsPublished)
{
m_IntroducersUpdateTimerV6.cancel ();
m_IntroducersUpdateTimerV6.expires_from_now (boost::posix_time::seconds(SSU2_KEEP_ALIVE_INTERVAL/2));
m_IntroducersUpdateTimerV6.async_wait (std::bind (&SSU2Server::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, false));
}
}
void SSU2Server::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode, bool v4)
{
if (ecode != boost::asio::error::operation_aborted)
{
// timeout expired
if (v4)
{
if (i2p::context.GetStatus () == eRouterStatusTesting)
{
// we still don't know if we need introducers
ScheduleIntroducersUpdateTimer ();
return;
}
if (i2p::context.GetStatus () != eRouterStatusFirewalled)
{
// we don't need introducers
m_Introducers.clear ();
return;
}
// we are firewalled
auto addr = i2p::context.GetRouterInfo ().GetSSU2V4Address ();
if (addr && addr->ssu && addr->ssu->introducers.empty ())
i2p::context.SetUnreachableSSU2 (true, false); // v4
2022-07-21 04:55:48 +03:00
UpdateIntroducers (true);
ScheduleIntroducersUpdateTimer ();
}
else
{
if (i2p::context.GetStatusV6 () == eRouterStatusTesting)
{
// we still don't know if we need introducers
ScheduleIntroducersUpdateTimerV6 ();
return;
}
if (i2p::context.GetStatusV6 () != eRouterStatusFirewalled)
{
// we don't need introducers
m_IntroducersV6.clear ();
return;
}
// we are firewalled
auto addr = i2p::context.GetRouterInfo ().GetSSU2V6Address ();
if (addr && addr->ssu && addr->ssu->introducers.empty ())
i2p::context.SetUnreachableSSU2 (false, true); // v6
2022-07-21 04:55:48 +03:00
UpdateIntroducers (false);
ScheduleIntroducersUpdateTimerV6 ();
}
}
2022-07-11 00:13:25 +03:00
}
2022-02-04 23:01:18 +03:00
}
}