i2pd/libi2pd/SSU.cpp

961 lines
30 KiB
C++
Raw Normal View History

/*
2021-03-29 22:16:39 +03:00
* Copyright (c) 2013-2021, 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
*/
2014-01-29 01:49:54 +04:00
#include <string.h>
2014-01-24 01:10:33 +04:00
#include "Log.h"
2014-01-30 01:49:53 +04:00
#include "Timestamp.h"
2014-01-29 01:49:54 +04:00
#include "RouterContext.h"
#include "NetDb.hpp"
2014-01-24 01:10:33 +04:00
#include "SSU.h"
#include "util.h"
2014-01-24 01:10:33 +04:00
#ifdef _WIN32
#include <boost/winapi/error_codes.hpp>
#endif
2014-01-24 01:10:33 +04:00
namespace i2p
{
namespace transport
2014-01-24 01:10:33 +04:00
{
2016-06-27 17:24:37 +03:00
SSUServer::SSUServer (int port):
2021-02-28 00:13:12 +03:00
m_IsRunning(false), m_Thread (nullptr),
m_ReceiversThread (nullptr), m_ReceiversThreadV6 (nullptr), m_Work (m_Service),
2017-01-19 23:47:01 +03:00
m_ReceiversWork (m_ReceiversService), m_ReceiversWorkV6 (m_ReceiversServiceV6),
2018-01-06 06:48:51 +03:00
m_Endpoint (boost::asio::ip::udp::v4 (), port), m_EndpointV6 (boost::asio::ip::udp::v6 (), port),
m_Socket (m_ReceiversService), m_SocketV6 (m_ReceiversServiceV6),
2021-04-21 03:02:30 +03:00
m_IntroducersUpdateTimer (m_Service), m_IntroducersUpdateTimerV6 (m_Service),
m_PeerTestsCleanupTimer (m_Service), m_TerminationTimer (m_Service), m_TerminationTimerV6 (m_Service)
2014-01-24 01:10:33 +04:00
{
}
2018-01-06 06:48:51 +03:00
2014-01-25 01:30:07 +04:00
SSUServer::~SSUServer ()
{
}
2016-12-01 05:14:10 +03:00
void SSUServer::OpenSocket ()
{
try
2020-05-05 16:35:41 +03:00
{
m_Socket.open (boost::asio::ip::udp::v4());
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
m_Socket.bind (m_Endpoint);
LogPrint (eLogInfo, "SSU: Start listening v4 port ", m_Endpoint.port());
}
catch ( std::exception & ex )
2020-05-05 16:35:41 +03:00
{
LogPrint (eLogError, "SSU: failed to bind to v4 port ", m_Endpoint.port(), ": ", ex.what());
2020-05-05 16:35:41 +03:00
ThrowFatal ("Unable to start IPv4 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ());
}
2016-12-01 05:14:10 +03:00
}
2018-01-06 06:48:51 +03:00
2016-12-01 05:14:10 +03:00
void SSUServer::OpenSocketV6 ()
{
try
2020-05-05 16:35:41 +03:00
{
m_SocketV6.open (boost::asio::ip::udp::v6());
m_SocketV6.set_option (boost::asio::ip::v6_only (true));
m_SocketV6.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
m_SocketV6.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
m_SocketV6.bind (m_EndpointV6);
LogPrint (eLogInfo, "SSU: Start listening v6 port ", m_EndpointV6.port());
}
catch ( std::exception & ex )
2020-05-05 16:35:41 +03:00
{
LogPrint (eLogError, "SSU: failed to bind to v6 port ", m_EndpointV6.port(), ": ", ex.what());
2020-05-05 16:35:41 +03:00
ThrowFatal ("Unable to start IPv6 SSU transport at port ", m_Endpoint.port(), ": ", ex.what ());
}
2018-01-06 06:48:51 +03:00
}
2014-01-24 01:10:33 +04:00
void SSUServer::Start ()
{
2014-04-20 04:45:41 +04:00
m_IsRunning = true;
2021-02-28 00:13:12 +03:00
m_Thread = new std::thread (std::bind (&SSUServer::Run, this));
if (context.SupportsV4 ())
2016-06-27 17:24:37 +03:00
{
2021-02-28 00:13:12 +03:00
OpenSocket ();
m_ReceiversThread = new std::thread (std::bind (&SSUServer::RunReceivers, this));
2016-06-27 17:24:37 +03:00
m_ReceiversService.post (std::bind (&SSUServer::Receive, this));
2018-01-06 06:48:51 +03:00
ScheduleTermination ();
2021-04-21 03:02:30 +03:00
ScheduleIntroducersUpdateTimer (); // wait for 30 seconds and decide if we need introducers
2016-06-27 17:24:37 +03:00
}
2014-10-29 22:02:48 +03:00
if (context.SupportsV6 ())
2018-01-06 06:48:51 +03:00
{
2021-02-28 00:13:12 +03:00
OpenSocketV6 ();
2017-01-19 23:47:01 +03:00
m_ReceiversThreadV6 = new std::thread (std::bind (&SSUServer::RunReceiversV6, this));
2018-01-06 06:48:51 +03:00
m_ReceiversServiceV6.post (std::bind (&SSUServer::ReceiveV6, this));
ScheduleTerminationV6 ();
2021-04-21 03:02:30 +03:00
ScheduleIntroducersUpdateTimerV6 (); // wait for 30 seconds and decide if we need introducers
}
2018-01-06 06:48:51 +03:00
SchedulePeerTestsCleanupTimer ();
2014-01-24 01:10:33 +04:00
}
void SSUServer::Stop ()
{
2014-02-11 04:27:55 +04:00
DeleteAllSessions ();
2014-04-20 04:45:41 +04:00
m_IsRunning = false;
2016-08-24 19:34:18 +03:00
m_TerminationTimer.cancel ();
2018-01-06 07:01:44 +03:00
m_TerminationTimerV6.cancel ();
2021-04-21 03:02:30 +03:00
m_IntroducersUpdateTimer.cancel ();
m_IntroducersUpdateTimerV6.cancel ();
2014-04-20 04:45:41 +04:00
m_Service.stop ();
2014-01-24 01:10:33 +04:00
m_Socket.close ();
m_SocketV6.close ();
2015-02-09 05:12:38 +03:00
m_ReceiversService.stop ();
2017-01-19 23:47:01 +03:00
m_ReceiversServiceV6.stop ();
2015-02-09 04:28:18 +03:00
if (m_ReceiversThread)
2018-01-06 06:48:51 +03:00
{
m_ReceiversThread->join ();
2015-02-09 04:28:18 +03:00
delete m_ReceiversThread;
m_ReceiversThread = nullptr;
}
2017-01-19 23:47:01 +03:00
if (m_ReceiversThreadV6)
2018-01-06 06:48:51 +03:00
{
m_ReceiversThreadV6->join ();
2017-01-19 23:47:01 +03:00
delete m_ReceiversThreadV6;
m_ReceiversThreadV6 = nullptr;
}
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
2014-01-24 01:10:33 +04:00
}
2018-01-06 06:48:51 +03:00
void SSUServer::Run ()
{
i2p::util::SetThreadName("SSU");
2014-04-20 04:45:41 +04:00
while (m_IsRunning)
{
try
2018-01-06 06:48:51 +03:00
{
2014-04-20 04:45:41 +04:00
m_Service.run ();
}
catch (std::exception& ex)
{
2015-12-18 16:46:56 +03:00
LogPrint (eLogError, "SSU: server runtime exception: ", ex.what ());
2018-01-06 06:48:51 +03:00
}
}
2014-04-20 04:45:41 +04:00
}
2018-01-06 06:48:51 +03:00
void SSUServer::RunReceivers ()
{
i2p::util::SetThreadName("SSUv4");
2015-02-09 04:28:18 +03:00
while (m_IsRunning)
{
try
2018-01-06 06:48:51 +03:00
{
2015-02-09 04:28:18 +03:00
m_ReceiversService.run ();
}
catch (std::exception& ex)
{
2015-12-18 16:46:56 +03:00
LogPrint (eLogError, "SSU: receivers runtime exception: ", ex.what ());
if (m_IsRunning)
{
// restart socket
m_Socket.close ();
OpenSocket ();
Receive ();
}
2018-01-06 06:48:51 +03:00
}
}
}
void SSUServer::RunReceiversV6 ()
{
i2p::util::SetThreadName("SSUv6");
2017-01-19 23:47:01 +03:00
while (m_IsRunning)
{
try
2018-01-06 06:48:51 +03:00
{
2017-01-19 23:47:01 +03:00
m_ReceiversServiceV6.run ();
}
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: v6 receivers runtime exception: ", ex.what ());
if (m_IsRunning)
{
m_SocketV6.close ();
OpenSocketV6 ();
ReceiveV6 ();
}
2018-01-06 06:48:51 +03:00
}
}
}
2017-01-19 23:47:01 +03:00
2021-02-28 00:13:12 +03:00
void SSUServer::SetLocalAddress (const boost::asio::ip::address& localAddress)
{
if (localAddress.is_v6 ())
m_EndpointV6.address (localAddress);
else if (localAddress.is_v4 ())
m_Endpoint.address (localAddress);
}
2016-12-31 01:53:54 +03:00
void SSUServer::AddRelay (uint32_t tag, std::shared_ptr<SSUSession> relay)
2014-04-16 23:54:28 +04:00
{
m_Relays[tag] = relay;
2018-01-06 06:48:51 +03:00
}
2014-04-16 23:54:28 +04:00
2016-12-30 06:06:33 +03:00
void SSUServer::RemoveRelay (uint32_t tag)
{
m_Relays.erase (tag);
2018-01-06 06:48:51 +03:00
}
2014-11-24 20:26:11 +03:00
std::shared_ptr<SSUSession> SSUServer::FindRelaySession (uint32_t tag)
2014-04-16 23:54:28 +04:00
{
auto it = m_Relays.find (tag);
if (it != m_Relays.end ())
2018-01-06 06:48:51 +03:00
{
2016-12-31 01:53:54 +03:00
if (it->second->GetState () == eSessionStateEstablished)
return it->second;
else
2018-01-06 06:48:51 +03:00
m_Relays.erase (it);
}
2014-04-16 23:54:28 +04:00
return nullptr;
}
2014-06-10 18:39:29 +04:00
void SSUServer::Send (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to)
2014-01-29 01:49:54 +04:00
{
boost::system::error_code ec;
2018-01-06 06:48:51 +03:00
if (to.protocol () == boost::asio::ip::udp::v4())
m_Socket.send_to (boost::asio::buffer (buf, len), to, 0, ec);
2014-10-30 01:46:35 +03:00
else
m_SocketV6.send_to (boost::asio::buffer (buf, len), to, 0, ec);
if (ec)
{
LogPrint (eLogError, "SSU: send exception: ", ec.message (), " while trying to send data to ", to.address (), ":", to.port (), " (length: ", len, ")");
}
2018-01-06 06:48:51 +03:00
}
2014-01-29 01:49:54 +04:00
2014-01-24 01:10:33 +04:00
void SSUServer::Receive ()
{
2017-01-19 17:58:55 +03:00
SSUPacket * packet = new SSUPacket ();
2015-02-09 04:28:18 +03:00
m_Socket.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from,
2018-01-06 06:48:51 +03:00
std::bind (&SSUServer::HandleReceivedFrom, this, std::placeholders::_1, std::placeholders::_2, packet));
2014-01-24 01:10:33 +04:00
}
2014-10-29 22:02:48 +03:00
void SSUServer::ReceiveV6 ()
{
2017-01-19 17:58:55 +03:00
SSUPacket * packet = new SSUPacket ();
2015-02-09 04:28:18 +03:00
m_SocketV6.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from,
2018-01-06 06:48:51 +03:00
std::bind (&SSUServer::HandleReceivedFromV6, this, std::placeholders::_1, std::placeholders::_2, packet));
}
2014-10-29 22:02:48 +03:00
2015-02-09 04:28:18 +03:00
void SSUServer::HandleReceivedFrom (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
2014-01-24 01:10:33 +04:00
{
if (!ecode
|| ecode == boost::asio::error::connection_refused
|| ecode == boost::asio::error::connection_reset
|| ecode == boost::asio::error::network_unreachable
|| ecode == boost::asio::error::host_unreachable
#ifdef _WIN32 // windows can throw WinAPI error, which is not handled by ASIO
|| ecode.value() == boost::winapi::ERROR_CONNECTION_REFUSED_
|| ecode.value() == boost::winapi::ERROR_NETWORK_UNREACHABLE_
|| ecode.value() == boost::winapi::ERROR_HOST_UNREACHABLE_
#endif
)
// just try continue reading when received ICMP response otherwise socket can crash,
// but better to find out which host were sent it and mark that router as unreachable
2014-01-24 01:10:33 +04:00
{
2015-02-09 04:28:18 +03:00
packet->len = bytes_transferred;
2015-02-09 19:53:11 +03:00
std::vector<SSUPacket *> packets;
packets.push_back (packet);
2015-02-15 01:20:21 +03:00
boost::system::error_code ec;
size_t moreBytes = m_Socket.available(ec);
2016-12-02 03:24:15 +03:00
if (!ec)
2018-01-06 06:48:51 +03:00
{
2016-12-02 03:24:15 +03:00
while (moreBytes && packets.size () < 25)
{
2017-01-19 17:58:55 +03:00
packet = new SSUPacket ();
2016-12-02 03:24:15 +03:00
packet->len = m_Socket.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from, 0, ec);
if (!ec)
2018-01-06 06:48:51 +03:00
{
2016-12-02 03:24:15 +03:00
packets.push_back (packet);
moreBytes = m_Socket.available(ec);
if (ec) break;
}
else
{
LogPrint (eLogError, "SSU: receive_from error: code ", ec.value(), ": ", ec.message ());
2017-01-19 17:58:55 +03:00
delete packet;
2016-12-02 03:24:15 +03:00
break;
2018-01-06 06:48:51 +03:00
}
2016-12-02 03:24:15 +03:00
}
2018-01-06 06:48:51 +03:00
}
2015-02-09 19:53:11 +03:00
2015-12-01 03:45:57 +03:00
m_Service.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_Sessions));
2014-01-24 01:10:33 +04:00
Receive ();
}
else
2018-01-06 06:48:51 +03:00
{
2015-02-09 04:28:18 +03:00
delete packet;
2016-11-30 22:51:26 +03:00
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "SSU: receive error: code ", ecode.value(), ": ", ecode.message ());
2016-12-01 05:14:10 +03:00
m_Socket.close ();
OpenSocket ();
2016-11-30 22:51:26 +03:00
Receive ();
}
2018-01-06 06:48:51 +03:00
}
2014-01-24 01:10:33 +04:00
}
2014-01-29 01:49:54 +04:00
2015-02-09 04:28:18 +03:00
void SSUServer::HandleReceivedFromV6 (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
2014-10-29 22:02:48 +03:00
{
if (!ecode
|| ecode == boost::asio::error::connection_refused
|| ecode == boost::asio::error::connection_reset
|| ecode == boost::asio::error::network_unreachable
|| ecode == boost::asio::error::host_unreachable
#ifdef _WIN32 // windows can throw WinAPI error, which is not handled by ASIO
|| ecode.value() == boost::winapi::ERROR_CONNECTION_REFUSED_
|| ecode.value() == boost::winapi::ERROR_NETWORK_UNREACHABLE_
|| ecode.value() == boost::winapi::ERROR_HOST_UNREACHABLE_
#endif
)
// just try continue reading when received ICMP response otherwise socket can crash,
// but better to find out which host were sent it and mark that router as unreachable
2014-10-29 22:02:48 +03:00
{
2015-02-09 04:28:18 +03:00
packet->len = bytes_transferred;
2015-02-09 19:53:11 +03:00
std::vector<SSUPacket *> packets;
packets.push_back (packet);
2016-12-02 03:24:15 +03:00
boost::system::error_code ec;
size_t moreBytes = m_SocketV6.available (ec);
if (!ec)
2015-02-09 19:53:11 +03:00
{
2016-12-02 03:24:15 +03:00
while (moreBytes && packets.size () < 25)
{
2017-01-19 17:58:55 +03:00
packet = new SSUPacket ();
2016-12-02 03:24:15 +03:00
packet->len = m_SocketV6.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from, 0, ec);
if (!ec)
{
packets.push_back (packet);
moreBytes = m_SocketV6.available(ec);
if (ec) break;
}
else
{
LogPrint (eLogError, "SSU: v6 receive_from error: code ", ec.value(), ": ", ec.message ());
2017-01-19 17:58:55 +03:00
delete packet;
2016-12-02 03:24:15 +03:00
break;
2018-01-06 06:48:51 +03:00
}
2016-12-02 03:24:15 +03:00
}
2015-02-09 19:53:11 +03:00
}
2018-01-06 06:48:51 +03:00
m_Service.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_SessionsV6));
2014-10-29 22:02:48 +03:00
ReceiveV6 ();
}
else
2018-01-06 06:48:51 +03:00
{
2017-01-19 17:58:55 +03:00
delete packet;
2016-11-30 22:51:26 +03:00
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint (eLogError, "SSU: v6 receive error: code ", ecode.value(), ": ", ecode.message ());
2016-12-01 05:14:10 +03:00
m_SocketV6.close ();
OpenSocketV6 ();
2016-11-30 22:51:26 +03:00
ReceiveV6 ();
}
2018-01-06 06:48:51 +03:00
}
2014-10-29 22:02:48 +03:00
}
2018-01-06 06:48:51 +03:00
void SSUServer::HandleReceivedPackets (std::vector<SSUPacket *> packets,
2015-12-01 03:45:57 +03:00
std::map<boost::asio::ip::udp::endpoint, std::shared_ptr<SSUSession> > * sessions)
2014-10-29 22:02:48 +03:00
{
if (!m_IsRunning) return;
2018-01-06 06:48:51 +03:00
std::shared_ptr<SSUSession> session;
2016-08-09 01:53:37 +03:00
for (auto& packet: packets)
2014-10-29 22:02:48 +03:00
{
2015-04-18 20:55:15 +03:00
try
2018-01-06 06:48:51 +03:00
{
2015-04-18 20:55:15 +03:00
if (!session || session->GetRemoteEndpoint () != packet->from) // we received packet for other session than previous
2015-02-09 19:53:11 +03:00
{
if (session)
{
session->FlushData ();
session = nullptr;
}
2015-12-01 03:45:57 +03:00
auto it = sessions->find (packet->from);
if (it != sessions->end ())
2015-04-18 20:55:15 +03:00
session = it->second;
2021-03-29 22:16:39 +03:00
if (!session && packet->len > 0)
{
2015-04-18 20:55:15 +03:00
session = std::make_shared<SSUSession> (*this, packet->from);
session->WaitForConnect ();
2015-12-01 03:45:57 +03:00
(*sessions)[packet->from] = session;
2016-06-27 16:00:00 +03:00
LogPrint (eLogDebug, "SSU: new session from ", packet->from.address ().to_string (), ":", packet->from.port (), " created");
2015-04-18 20:55:15 +03:00
}
}
2021-03-29 22:50:33 +03:00
if (session)
session->ProcessNextMessage (packet->buf, packet->len, packet->from);
2018-01-06 06:48:51 +03:00
}
2015-04-18 20:55:15 +03:00
catch (std::exception& ex)
{
LogPrint (eLogError, "SSU: HandleReceivedPackets ", ex.what ());
if (session) session->FlushData ();
session = nullptr;
2018-01-06 06:48:51 +03:00
}
2017-01-19 17:58:55 +03:00
delete packet;
2014-10-29 22:02:48 +03:00
}
2015-02-15 22:17:55 +03:00
if (session) session->FlushData ();
2014-10-29 22:02:48 +03:00
}
2014-11-24 20:26:11 +03:00
std::shared_ptr<SSUSession> SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e) const
2014-04-16 23:54:28 +04:00
{
2018-01-06 06:48:51 +03:00
auto& sessions = e.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
auto it = sessions.find (e);
if (it != sessions.end ())
2014-03-26 05:17:03 +04:00
return it->second;
else
return nullptr;
2014-04-16 23:54:28 +04:00
}
2018-01-06 06:48:51 +03:00
2021-04-04 17:36:22 +03:00
bool SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest, bool v4only)
{
2016-12-02 19:17:22 +03:00
auto address = router->GetSSUAddress (v4only || !context.SupportsV6 ());
if (address)
2021-04-04 17:36:22 +03:00
return CreateSession (router, address, peerTest);
else
2015-12-18 16:46:56 +03:00
LogPrint (eLogWarning, "SSU: Router ", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), " doesn't have SSU address");
2021-04-04 17:36:22 +03:00
return false;
}
2018-01-06 06:48:51 +03:00
2021-04-04 17:36:22 +03:00
bool SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router,
2021-02-23 05:04:26 +03:00
std::shared_ptr<const i2p::data::RouterInfo::Address> address, bool peerTest)
2014-01-29 01:49:54 +04:00
{
2021-02-23 05:04:26 +03:00
if (router && address)
2014-01-29 01:49:54 +04:00
{
if (address->UsesIntroducer ())
m_Service.post (std::bind (&SSUServer::CreateSessionThroughIntroducer, this, router, address, peerTest)); // always V4 thread
else
2014-01-29 01:49:54 +04:00
{
2021-04-23 02:32:47 +03:00
if (address->host.is_unspecified () || !address->port) return false;
2021-02-23 05:04:26 +03:00
boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
m_Service.post (std::bind (&SSUServer::CreateDirectSession, this, router, remoteEndpoint, peerTest));
}
}
2021-04-04 17:36:22 +03:00
else
return false;
return true;
}
2015-11-29 17:10:49 +03:00
void SSUServer::CreateDirectSession (std::shared_ptr<const i2p::data::RouterInfo> router, boost::asio::ip::udp::endpoint remoteEndpoint, bool peerTest)
2018-01-06 06:48:51 +03:00
{
auto& sessions = remoteEndpoint.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
auto it = sessions.find (remoteEndpoint);
if (it != sessions.end ())
2018-01-06 06:48:51 +03:00
{
2015-11-29 17:10:49 +03:00
auto session = it->second;
if (peerTest && session->GetState () == eSessionStateEstablished)
session->SendPeerTest ();
2018-01-06 06:48:51 +03:00
}
2015-11-29 17:10:49 +03:00
else
{
2018-01-06 06:48:51 +03:00
// otherwise create new session
2015-11-29 17:10:49 +03:00
auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
sessions[remoteEndpoint] = session;
2018-01-06 06:48:51 +03:00
// connect
2016-06-27 16:00:00 +03:00
LogPrint (eLogDebug, "SSU: Creating new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), "] ",
2015-11-29 17:10:49 +03:00
remoteEndpoint.address ().to_string (), ":", remoteEndpoint.port ());
session->Connect ();
}
}
2018-01-06 06:48:51 +03:00
void SSUServer::CreateSessionThroughIntroducer (std::shared_ptr<const i2p::data::RouterInfo> router,
std::shared_ptr<const i2p::data::RouterInfo::Address> address, bool peerTest)
{
if (router && address && address->UsesIntroducer ())
{
if (address->IsV4 () && !i2p::context.SupportsV4 ()) return;
if (address->IsV6 () && !i2p::context.SupportsV6 ()) return;
if (!address->host.is_unspecified () && address->port)
{
// we rarely come here
auto& sessions = address->host.is_v6 () ? m_SessionsV6 : m_Sessions;
boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
auto it = sessions.find (remoteEndpoint);
// check if session is presented already
if (it != sessions.end ())
2018-01-06 06:48:51 +03:00
{
auto session = it->second;
if (peerTest && session->GetState () == eSessionStateEstablished)
session->SendPeerTest ();
2018-01-06 06:48:51 +03:00
return;
}
}
// create new session
int numIntroducers = address->ssu->introducers.size ();
if (numIntroducers > 0)
{
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
std::shared_ptr<SSUSession> introducerSession;
const i2p::data::RouterInfo::Introducer * introducer = nullptr;
// we might have a session to introducer already
2021-04-06 01:22:48 +03:00
auto offset = rand ();
for (int i = 0; i < numIntroducers; i++)
{
2021-04-06 01:22:48 +03:00
auto intr = &(address->ssu->introducers[(offset + i)%numIntroducers]);
2021-04-04 17:36:22 +03:00
if (!intr->iPort) continue; // skip invalid introducer
if (intr->iExp > 0 && ts > intr->iExp) continue; // skip expired introducer
boost::asio::ip::udp::endpoint ep (intr->iHost, intr->iPort);
if (ep.address ().is_v4 () && address->IsV4 ()) // ipv4
2014-02-22 01:13:36 +04:00
{
if (!introducer) introducer = intr;
auto it = m_Sessions.find (ep);
if (it != m_Sessions.end ())
2018-01-06 06:48:51 +03:00
{
introducerSession = it->second;
break;
2015-12-01 17:21:02 +03:00
}
2014-02-22 01:13:36 +04:00
}
if (ep.address ().is_v6 () && address->IsV6 ()) // ipv6
{
if (!introducer) introducer = intr;
auto it = m_SessionsV6.find (ep);
if (it != m_SessionsV6.end ())
{
introducerSession = it->second;
break;
}
}
}
if (!introducer)
{
LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no compatibe non-expired introducers presented");
return;
}
if (introducerSession) // session found
LogPrint (eLogWarning, "SSU: Session to introducer already exists");
else // create new
{
LogPrint (eLogDebug, "SSU: Creating new session to introducer ", introducer->iHost);
boost::asio::ip::udp::endpoint introducerEndpoint (introducer->iHost, introducer->iPort);
introducerSession = std::make_shared<SSUSession> (*this, introducerEndpoint, router);
if (introducerEndpoint.address ().is_v4 ())
m_Sessions[introducerEndpoint] = introducerSession;
else if (introducerEndpoint.address ().is_v6 ())
m_SessionsV6[introducerEndpoint] = introducerSession;
}
if (!address->host.is_unspecified () && address->port)
{
// create session
boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
if (address->host.is_v4 ())
m_Sessions[remoteEndpoint] = session;
else if (address->host.is_v6 ())
m_SessionsV6[remoteEndpoint] = session;
// introduce
LogPrint (eLogInfo, "SSU: Introduce new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()),
"] through introducer ", introducer->iHost, ":", introducer->iPort);
session->WaitForIntroduction ();
if ((address->host.is_v4 () && i2p::context.GetStatus () == eRouterStatusFirewalled) ||
(address->host.is_v6 () && i2p::context.GetStatusV6 () == eRouterStatusFirewalled))
{
uint8_t buf[1];
Send (buf, 0, remoteEndpoint); // send HolePunch
}
2014-01-29 01:49:54 +04:00
}
introducerSession->Introduce (*introducer, router);
2014-01-29 01:49:54 +04:00
}
else
LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no introducers present");
2014-01-29 01:49:54 +04:00
}
}
2014-02-09 06:06:40 +04:00
2014-11-24 20:26:11 +03:00
void SSUServer::DeleteSession (std::shared_ptr<SSUSession> session)
2014-02-09 06:06:40 +04:00
{
if (session)
{
session->Close ();
auto& ep = session->GetRemoteEndpoint ();
if (ep.address ().is_v6 ())
m_SessionsV6.erase (ep);
else
m_Sessions.erase (ep);
2018-01-06 06:48:51 +03:00
}
}
2014-02-09 06:06:40 +04:00
void SSUServer::DeleteAllSessions ()
{
2016-08-09 01:53:37 +03:00
for (auto& it: m_Sessions)
2014-02-09 06:06:40 +04:00
it.second->Close ();
m_Sessions.clear ();
2016-08-09 01:53:37 +03:00
for (auto& it: m_SessionsV6)
it.second->Close ();
m_SessionsV6.clear ();
2014-02-22 01:13:36 +04:00
}
2014-09-04 00:49:48 +04:00
template<typename Filter>
std::shared_ptr<SSUSession> SSUServer::GetRandomV4Session (Filter filter) // v4 only
2014-09-04 00:49:48 +04:00
{
2014-11-24 20:26:11 +03:00
std::vector<std::shared_ptr<SSUSession> > filteredSessions;
2016-08-09 01:53:37 +03:00
for (const auto& s :m_Sessions)
2014-09-04 00:49:48 +04:00
if (filter (s.second)) filteredSessions.push_back (s.second);
if (filteredSessions.size () > 0)
{
2015-11-03 17:15:49 +03:00
auto ind = rand () % filteredSessions.size ();
2014-09-04 00:49:48 +04:00
return filteredSessions[ind];
}
2018-01-06 06:48:51 +03:00
return nullptr;
2014-09-04 00:49:48 +04:00
}
std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV4Session (std::shared_ptr<const SSUSession> excluded) // v4 only
2014-09-04 00:49:48 +04:00
{
return GetRandomV4Session (
2018-01-06 06:48:51 +03:00
[excluded](std::shared_ptr<SSUSession> session)->bool
{
return session->GetState () == eSessionStateEstablished && session != excluded;
}
);
}
template<typename Filter>
std::shared_ptr<SSUSession> SSUServer::GetRandomV6Session (Filter filter) // v6 only
{
std::vector<std::shared_ptr<SSUSession> > filteredSessions;
2016-08-09 01:53:37 +03:00
for (const auto& s :m_SessionsV6)
if (filter (s.second)) filteredSessions.push_back (s.second);
if (filteredSessions.size () > 0)
{
auto ind = rand () % filteredSessions.size ();
return filteredSessions[ind];
}
2018-01-06 06:48:51 +03:00
return nullptr;
}
std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV6Session (std::shared_ptr<const SSUSession> excluded) // v6 only
{
return GetRandomV6Session (
2018-01-06 06:48:51 +03:00
[excluded](std::shared_ptr<SSUSession> session)->bool
{
return session->GetState () == eSessionStateEstablished && session != excluded;
2014-09-06 00:35:02 +04:00
}
);
2014-09-06 00:35:02 +04:00
}
std::list<std::shared_ptr<SSUSession> > SSUServer::FindIntroducers (int maxNumIntroducers,
bool v4, std::set<i2p::data::IdentHash>& excluded)
2014-09-06 00:35:02 +04:00
{
2014-09-09 21:45:12 +04:00
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
2021-04-21 22:41:04 +03:00
std::list<std::shared_ptr<SSUSession> > ret;
const auto& sessions = v4 ? m_Sessions : m_SessionsV6;
for (const auto& s : sessions)
{
if (s.second->GetRelayTag () && s.second->GetState () == eSessionStateEstablished &&
ts < s.second->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_EXPIRATION)
2021-04-21 22:41:04 +03:00
ret.push_back (s.second);
2021-04-25 17:57:31 +03:00
else if (s.second->GetRemoteIdentity ())
excluded.insert (s.second->GetRemoteIdentity ()->GetIdentHash ());
2021-04-21 22:41:04 +03:00
}
if ((int)ret.size () > maxNumIntroducers)
2014-09-06 00:35:02 +04:00
{
2021-04-21 22:41:04 +03:00
// 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);
}
}
2014-09-06 00:35:02 +04:00
return ret;
2014-09-04 00:49:48 +04:00
}
2014-09-07 04:43:20 +04:00
void SSUServer::RescheduleIntroducersUpdateTimer ()
{
m_IntroducersUpdateTimer.cancel ();
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL/2));
m_IntroducersUpdateTimer.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
2021-04-21 03:02:30 +03:00
this, std::placeholders::_1, true));
}
2014-09-07 04:43:20 +04:00
void SSUServer::ScheduleIntroducersUpdateTimer ()
{
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
2014-11-24 20:26:11 +03:00
m_IntroducersUpdateTimer.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
2021-04-21 03:02:30 +03:00
this, std::placeholders::_1, true));
2014-09-07 04:43:20 +04:00
}
2021-04-21 03:02:30 +03:00
void SSUServer::RescheduleIntroducersUpdateTimerV6 ()
{
m_IntroducersUpdateTimerV6.cancel ();
m_IntroducersUpdateTimerV6.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL/2));
m_IntroducersUpdateTimerV6.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, false));
}
void SSUServer::ScheduleIntroducersUpdateTimerV6 ()
{
m_IntroducersUpdateTimerV6.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
m_IntroducersUpdateTimerV6.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
this, std::placeholders::_1, false));
}
void SSUServer::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode, bool v4)
2014-09-07 04:43:20 +04:00
{
if (ecode != boost::asio::error::operation_aborted)
2014-09-07 04:43:20 +04:00
{
// timeout expired
2021-04-21 03:02:30 +03:00
if (v4)
{
2021-04-21 03:02:30 +03:00
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;
}
}
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
2021-04-21 03:02:30 +03:00
if (!i2p::context.IsUnreachable () || !v4) i2p::context.SetUnreachable (v4, !v4);
2014-09-07 04:43:20 +04:00
std::list<boost::asio::ip::udp::endpoint> newList;
2014-09-09 16:03:05 +04:00
size_t numIntroducers = 0;
2014-09-09 21:45:12 +04:00
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
2021-04-21 03:02:30 +03:00
auto& introducers = v4 ? m_Introducers : m_IntroducersV6;
for (const auto& it : introducers)
2018-01-06 06:48:51 +03:00
{
2014-09-07 04:43:20 +04:00
auto session = FindSession (it);
if (session)
2014-09-07 04:43:20 +04:00
{
if (ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_EXPIRATION)
session->SendKeepAlive ();
if (ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION)
{
newList.push_back (it);
numIntroducers++;
}
else
session = nullptr;
2014-09-07 04:43:20 +04:00
}
if (!session)
2014-09-07 04:43:20 +04:00
i2p::context.RemoveIntroducer (it);
}
2021-04-24 18:11:12 +03:00
std::set<i2p::data::IdentHash> excluded;
2014-09-09 05:53:55 +04:00
if (numIntroducers < SSU_MAX_NUM_INTRODUCERS)
2014-09-07 04:43:20 +04:00
{
// create new
auto sessions = FindIntroducers (SSU_MAX_NUM_INTRODUCERS, v4, excluded); // try to find if duplicates
if (sessions.empty () && !introducers.empty ())
{
// bump creation time for previous introducers if no new sessions found
LogPrint (eLogDebug, "SSU: no new introducers found. Trying to reuse existing");
for (const auto& it : introducers)
{
auto session = FindSession (it);
if (session)
session->SetCreationTime (session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION);
}
// try again
excluded.clear ();
sessions = FindIntroducers (SSU_MAX_NUM_INTRODUCERS, v4, excluded);
}
2021-04-21 03:02:30 +03:00
for (const auto& it1: sessions)
2014-09-07 04:43:20 +04:00
{
2016-08-09 01:53:37 +03:00
const auto& ep = it1->GetRemoteEndpoint ();
i2p::data::RouterInfo::Introducer introducer;
introducer.iHost = ep.address ();
introducer.iPort = ep.port ();
introducer.iTag = it1->GetRelayTag ();
introducer.iKey = it1->GetIntroKey ();
introducer.iExp = it1->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_EXPIRATION;
2016-08-09 01:53:37 +03:00
if (i2p::context.AddIntroducer (introducer))
2014-09-07 04:43:20 +04:00
{
2016-08-09 01:53:37 +03:00
newList.push_back (ep);
if (newList.size () >= SSU_MAX_NUM_INTRODUCERS) break;
}
2021-04-25 17:57:31 +03:00
if (it1->GetRemoteIdentity ())
excluded.insert (it1->GetRemoteIdentity ()->GetIdentHash ());
2016-08-09 01:53:37 +03:00
}
2018-01-06 06:48:51 +03:00
}
2021-04-21 03:02:30 +03:00
introducers = newList;
if (introducers.size () < SSU_MAX_NUM_INTRODUCERS)
2015-02-27 05:05:35 +03:00
{
2021-04-21 03:02:30 +03:00
for (auto i = introducers.size (); i < SSU_MAX_NUM_INTRODUCERS; i++)
{
2021-04-24 18:11:12 +03:00
auto introducer = i2p::data::netdb.GetRandomIntroducer (v4, excluded);
if (introducer)
{
2021-04-21 15:16:13 +03:00
auto address = v4 ? introducer->GetSSUAddress (true) : introducer->GetSSUV6Address ();
2021-04-23 02:32:47 +03:00
if (address && !address->host.is_unspecified () && address->port)
{
boost::asio::ip::udp::endpoint ep (address->host, address->port);
2021-04-21 03:02:30 +03:00
if (std::find (introducers.begin (), introducers.end (), ep) == introducers.end ()) // not connected yet
{
CreateDirectSession (introducer, ep, false);
2021-04-24 18:11:12 +03:00
excluded.insert (introducer->GetIdentHash ());
}
}
}
else
{
LogPrint (eLogDebug, "SSU: can't find more introducers");
break;
}
}
2018-01-06 06:48:51 +03:00
}
2021-04-21 03:02:30 +03:00
if (v4)
ScheduleIntroducersUpdateTimer ();
else
ScheduleIntroducersUpdateTimerV6 ();
2018-01-06 06:48:51 +03:00
}
2015-02-25 23:26:06 +03:00
}
2015-03-26 23:10:52 +03:00
void SSUServer::NewPeerTest (uint32_t nonce, PeerTestParticipant role, std::shared_ptr<SSUSession> session)
2015-02-25 23:26:06 +03:00
{
2015-03-26 23:10:52 +03:00
m_PeerTests[nonce] = { i2p::util::GetMillisecondsSinceEpoch (), role, session };
2015-02-25 23:26:06 +03:00
}
2015-02-26 05:56:51 +03:00
PeerTestParticipant SSUServer::GetPeerTestParticipant (uint32_t nonce)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
return it->second.role;
else
return ePeerTestParticipantUnknown;
2018-01-06 06:48:51 +03:00
}
2015-02-26 05:56:51 +03:00
2015-03-26 23:10:52 +03:00
std::shared_ptr<SSUSession> SSUServer::GetPeerTestSession (uint32_t nonce)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
return it->second.session;
else
return nullptr;
}
2015-02-26 05:56:51 +03:00
void SSUServer::UpdatePeerTest (uint32_t nonce, PeerTestParticipant role)
{
auto it = m_PeerTests.find (nonce);
if (it != m_PeerTests.end ())
it->second.role = role;
2018-01-06 06:48:51 +03:00
}
2015-02-26 05:56:51 +03:00
void SSUServer::RemovePeerTest (uint32_t nonce)
2015-02-25 23:26:06 +03:00
{
m_PeerTests.erase (nonce);
2018-01-06 06:48:51 +03:00
}
2015-02-26 22:54:28 +03:00
void SSUServer::SchedulePeerTestsCleanupTimer ()
{
m_PeerTestsCleanupTimer.expires_from_now (boost::posix_time::seconds(SSU_PEER_TEST_TIMEOUT));
m_PeerTestsCleanupTimer.async_wait (std::bind (&SSUServer::HandlePeerTestsCleanupTimer,
2018-01-06 06:48:51 +03:00
this, std::placeholders::_1));
2015-02-26 22:54:28 +03:00
}
void SSUServer::HandlePeerTestsCleanupTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
2018-01-06 06:48:51 +03:00
int numDeleted = 0;
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
2015-02-26 22:54:28 +03:00
for (auto it = m_PeerTests.begin (); it != m_PeerTests.end ();)
{
if (ts > it->second.creationTime + SSU_PEER_TEST_TIMEOUT*1000LL)
{
numDeleted++;
it = m_PeerTests.erase (it);
}
else
2016-08-09 01:53:37 +03:00
++it;
2015-02-26 22:54:28 +03:00
}
if (numDeleted > 0)
2015-12-18 16:46:56 +03:00
LogPrint (eLogDebug, "SSU: ", numDeleted, " peer tests have been expired");
2015-02-26 22:54:28 +03:00
SchedulePeerTestsCleanupTimer ();
}
}
void SSUServer::ScheduleTermination ()
{
m_TerminationTimer.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
m_TerminationTimer.async_wait (std::bind (&SSUServer::HandleTerminationTimer,
this, std::placeholders::_1));
}
void SSUServer::HandleTerminationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
2018-01-06 06:48:51 +03:00
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto& it: m_Sessions)
2018-01-06 07:01:44 +03:00
if (it.second->IsTerminationTimeoutExpired (ts))
{
auto session = it.second;
if (it.first != session->GetRemoteEndpoint ())
LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first, " adjusted");
2018-01-06 06:48:51 +03:00
m_Service.post ([session]
{
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed ();
2018-01-06 06:48:51 +03:00
});
}
2018-01-06 06:48:51 +03:00
ScheduleTermination ();
}
}
void SSUServer::ScheduleTerminationV6 ()
{
m_TerminationTimerV6.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
m_TerminationTimerV6.async_wait (std::bind (&SSUServer::HandleTerminationTimerV6,
this, std::placeholders::_1));
}
void SSUServer::HandleTerminationTimerV6 (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
2018-01-06 06:48:51 +03:00
{
auto ts = i2p::util::GetSecondsSinceEpoch ();
for (auto& it: m_SessionsV6)
2018-01-06 07:01:44 +03:00
if (it.second->IsTerminationTimeoutExpired (ts))
{
auto session = it.second;
if (it.first != session->GetRemoteEndpoint ())
LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first);
m_Service.post ([session]
2018-01-06 06:48:51 +03:00
{
LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
session->Failed ();
2018-01-06 06:48:51 +03:00
});
}
2018-01-06 06:48:51 +03:00
ScheduleTerminationV6 ();
}
}
2014-01-24 01:10:33 +04:00
}
}