SSU.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. #include <string.h>
  2. #include <boost/bind.hpp>
  3. #include "Log.h"
  4. #include "Timestamp.h"
  5. #include "RouterContext.h"
  6. #include "NetDb.hpp"
  7. #include "SSU.h"
  8. namespace i2p
  9. {
  10. namespace transport
  11. {
  12. SSUServer::SSUServer (const boost::asio::ip::address & addr, int port):
  13. m_OnlyV6(true), m_IsRunning(false),
  14. m_Thread (nullptr), m_ThreadV6 (nullptr), m_ReceiversThread (nullptr),
  15. m_ReceiversThreadV6 (nullptr), m_Work (m_Service), m_WorkV6 (m_ServiceV6),
  16. m_ReceiversWork (m_ReceiversService), m_ReceiversWorkV6 (m_ReceiversServiceV6),
  17. m_EndpointV6 (addr, port), m_Socket (m_ReceiversService, m_Endpoint),
  18. m_SocketV6 (m_ReceiversServiceV6), m_IntroducersUpdateTimer (m_Service),
  19. m_PeerTestsCleanupTimer (m_Service), m_TerminationTimer (m_Service),
  20. m_TerminationTimerV6 (m_ServiceV6)
  21. {
  22. OpenSocketV6 ();
  23. }
  24. SSUServer::SSUServer (int port):
  25. m_OnlyV6(false), m_IsRunning(false),
  26. m_Thread (nullptr), m_ThreadV6 (nullptr), m_ReceiversThread (nullptr),
  27. m_ReceiversThreadV6 (nullptr), m_Work (m_Service), m_WorkV6 (m_ServiceV6),
  28. m_ReceiversWork (m_ReceiversService), m_ReceiversWorkV6 (m_ReceiversServiceV6),
  29. m_Endpoint (boost::asio::ip::udp::v4 (), port), m_EndpointV6 (boost::asio::ip::udp::v6 (), port),
  30. m_Socket (m_ReceiversService), m_SocketV6 (m_ReceiversServiceV6),
  31. m_IntroducersUpdateTimer (m_Service), m_PeerTestsCleanupTimer (m_Service),
  32. m_TerminationTimer (m_Service), m_TerminationTimerV6 (m_ServiceV6)
  33. {
  34. OpenSocket ();
  35. if (context.SupportsV6 ())
  36. OpenSocketV6 ();
  37. }
  38. SSUServer::~SSUServer ()
  39. {
  40. }
  41. void SSUServer::OpenSocket ()
  42. {
  43. m_Socket.open (boost::asio::ip::udp::v4());
  44. m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
  45. m_Socket.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
  46. m_Socket.bind (m_Endpoint);
  47. }
  48. void SSUServer::OpenSocketV6 ()
  49. {
  50. m_SocketV6.open (boost::asio::ip::udp::v6());
  51. m_SocketV6.set_option (boost::asio::ip::v6_only (true));
  52. m_SocketV6.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
  53. m_SocketV6.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
  54. m_SocketV6.bind (m_EndpointV6);
  55. }
  56. void SSUServer::Start ()
  57. {
  58. m_IsRunning = true;
  59. if (!m_OnlyV6)
  60. {
  61. m_ReceiversThread = new std::thread (std::bind (&SSUServer::RunReceivers, this));
  62. m_Thread = new std::thread (std::bind (&SSUServer::Run, this));
  63. m_ReceiversService.post (std::bind (&SSUServer::Receive, this));
  64. ScheduleTermination ();
  65. }
  66. if (context.SupportsV6 ())
  67. {
  68. m_ReceiversThreadV6 = new std::thread (std::bind (&SSUServer::RunReceiversV6, this));
  69. m_ThreadV6 = new std::thread (std::bind (&SSUServer::RunV6, this));
  70. m_ReceiversServiceV6.post (std::bind (&SSUServer::ReceiveV6, this));
  71. ScheduleTerminationV6 ();
  72. }
  73. SchedulePeerTestsCleanupTimer ();
  74. ScheduleIntroducersUpdateTimer (); // wait for 30 seconds and decide if we need introducers
  75. }
  76. void SSUServer::Stop ()
  77. {
  78. DeleteAllSessions ();
  79. m_IsRunning = false;
  80. m_TerminationTimer.cancel ();
  81. m_TerminationTimerV6.cancel ();
  82. m_Service.stop ();
  83. m_Socket.close ();
  84. m_ServiceV6.stop ();
  85. m_SocketV6.close ();
  86. m_ReceiversService.stop ();
  87. m_ReceiversServiceV6.stop ();
  88. if (m_ReceiversThread)
  89. {
  90. m_ReceiversThread->join ();
  91. delete m_ReceiversThread;
  92. m_ReceiversThread = nullptr;
  93. }
  94. if (m_Thread)
  95. {
  96. m_Thread->join ();
  97. delete m_Thread;
  98. m_Thread = nullptr;
  99. }
  100. if (m_ReceiversThreadV6)
  101. {
  102. m_ReceiversThreadV6->join ();
  103. delete m_ReceiversThreadV6;
  104. m_ReceiversThreadV6 = nullptr;
  105. }
  106. if (m_ThreadV6)
  107. {
  108. m_ThreadV6->join ();
  109. delete m_ThreadV6;
  110. m_ThreadV6 = nullptr;
  111. }
  112. }
  113. void SSUServer::Run ()
  114. {
  115. while (m_IsRunning)
  116. {
  117. try
  118. {
  119. m_Service.run ();
  120. }
  121. catch (std::exception& ex)
  122. {
  123. LogPrint (eLogError, "SSU: server runtime exception: ", ex.what ());
  124. }
  125. }
  126. }
  127. void SSUServer::RunV6 ()
  128. {
  129. while (m_IsRunning)
  130. {
  131. try
  132. {
  133. m_ServiceV6.run ();
  134. }
  135. catch (std::exception& ex)
  136. {
  137. LogPrint (eLogError, "SSU: v6 server runtime exception: ", ex.what ());
  138. }
  139. }
  140. }
  141. void SSUServer::RunReceivers ()
  142. {
  143. while (m_IsRunning)
  144. {
  145. try
  146. {
  147. m_ReceiversService.run ();
  148. }
  149. catch (std::exception& ex)
  150. {
  151. LogPrint (eLogError, "SSU: receivers runtime exception: ", ex.what ());
  152. }
  153. }
  154. }
  155. void SSUServer::RunReceiversV6 ()
  156. {
  157. while (m_IsRunning)
  158. {
  159. try
  160. {
  161. m_ReceiversServiceV6.run ();
  162. }
  163. catch (std::exception& ex)
  164. {
  165. LogPrint (eLogError, "SSU: v6 receivers runtime exception: ", ex.what ());
  166. }
  167. }
  168. }
  169. void SSUServer::AddRelay (uint32_t tag, std::shared_ptr<SSUSession> relay)
  170. {
  171. m_Relays[tag] = relay;
  172. }
  173. void SSUServer::RemoveRelay (uint32_t tag)
  174. {
  175. m_Relays.erase (tag);
  176. }
  177. std::shared_ptr<SSUSession> SSUServer::FindRelaySession (uint32_t tag)
  178. {
  179. auto it = m_Relays.find (tag);
  180. if (it != m_Relays.end ())
  181. {
  182. if (it->second->GetState () == eSessionStateEstablished)
  183. return it->second;
  184. else
  185. m_Relays.erase (it);
  186. }
  187. return nullptr;
  188. }
  189. void SSUServer::Send (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to)
  190. {
  191. if (to.protocol () == boost::asio::ip::udp::v4())
  192. m_Socket.send_to (boost::asio::buffer (buf, len), to);
  193. else
  194. m_SocketV6.send_to (boost::asio::buffer (buf, len), to);
  195. }
  196. void SSUServer::Receive ()
  197. {
  198. SSUPacket * packet = new SSUPacket ();
  199. m_Socket.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from,
  200. std::bind (&SSUServer::HandleReceivedFrom, this, std::placeholders::_1, std::placeholders::_2, packet));
  201. }
  202. void SSUServer::ReceiveV6 ()
  203. {
  204. SSUPacket * packet = new SSUPacket ();
  205. m_SocketV6.async_receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from,
  206. std::bind (&SSUServer::HandleReceivedFromV6, this, std::placeholders::_1, std::placeholders::_2, packet));
  207. }
  208. void SSUServer::HandleReceivedFrom (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
  209. {
  210. if (!ecode)
  211. {
  212. packet->len = bytes_transferred;
  213. std::vector<SSUPacket *> packets;
  214. packets.push_back (packet);
  215. boost::system::error_code ec;
  216. size_t moreBytes = m_Socket.available(ec);
  217. if (!ec)
  218. {
  219. while (moreBytes && packets.size () < 25)
  220. {
  221. packet = new SSUPacket ();
  222. packet->len = m_Socket.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V4), packet->from, 0, ec);
  223. if (!ec)
  224. {
  225. packets.push_back (packet);
  226. moreBytes = m_Socket.available(ec);
  227. if (ec) break;
  228. }
  229. else
  230. {
  231. LogPrint (eLogError, "SSU: receive_from error: ", ec.message ());
  232. delete packet;
  233. break;
  234. }
  235. }
  236. }
  237. m_Service.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_Sessions));
  238. Receive ();
  239. }
  240. else
  241. {
  242. delete packet;
  243. if (ecode != boost::asio::error::operation_aborted)
  244. {
  245. LogPrint (eLogError, "SSU: receive error: ", ecode.message ());
  246. m_Socket.close ();
  247. OpenSocket ();
  248. Receive ();
  249. }
  250. }
  251. }
  252. void SSUServer::HandleReceivedFromV6 (const boost::system::error_code& ecode, std::size_t bytes_transferred, SSUPacket * packet)
  253. {
  254. if (!ecode)
  255. {
  256. packet->len = bytes_transferred;
  257. std::vector<SSUPacket *> packets;
  258. packets.push_back (packet);
  259. boost::system::error_code ec;
  260. size_t moreBytes = m_SocketV6.available (ec);
  261. if (!ec)
  262. {
  263. while (moreBytes && packets.size () < 25)
  264. {
  265. packet = new SSUPacket ();
  266. packet->len = m_SocketV6.receive_from (boost::asio::buffer (packet->buf, SSU_MTU_V6), packet->from, 0, ec);
  267. if (!ec)
  268. {
  269. packets.push_back (packet);
  270. moreBytes = m_SocketV6.available(ec);
  271. if (ec) break;
  272. }
  273. else
  274. {
  275. LogPrint (eLogError, "SSU: v6 receive_from error: ", ec.message ());
  276. delete packet;
  277. break;
  278. }
  279. }
  280. }
  281. m_ServiceV6.post (std::bind (&SSUServer::HandleReceivedPackets, this, packets, &m_SessionsV6));
  282. ReceiveV6 ();
  283. }
  284. else
  285. {
  286. delete packet;
  287. if (ecode != boost::asio::error::operation_aborted)
  288. {
  289. LogPrint (eLogError, "SSU: v6 receive error: ", ecode.message ());
  290. m_SocketV6.close ();
  291. OpenSocketV6 ();
  292. ReceiveV6 ();
  293. }
  294. }
  295. }
  296. void SSUServer::HandleReceivedPackets (std::vector<SSUPacket *> packets,
  297. std::map<boost::asio::ip::udp::endpoint, std::shared_ptr<SSUSession> > * sessions)
  298. {
  299. std::shared_ptr<SSUSession> session;
  300. for (auto& packet: packets)
  301. {
  302. try
  303. {
  304. if (!session || session->GetRemoteEndpoint () != packet->from) // we received packet for other session than previous
  305. {
  306. if (session)
  307. {
  308. session->FlushData ();
  309. session = nullptr;
  310. }
  311. auto it = sessions->find (packet->from);
  312. if (it != sessions->end ())
  313. session = it->second;
  314. if (!session)
  315. {
  316. session = std::make_shared<SSUSession> (*this, packet->from);
  317. session->WaitForConnect ();
  318. (*sessions)[packet->from] = session;
  319. LogPrint (eLogDebug, "SSU: new session from ", packet->from.address ().to_string (), ":", packet->from.port (), " created");
  320. }
  321. }
  322. session->ProcessNextMessage (packet->buf, packet->len, packet->from);
  323. }
  324. catch (std::exception& ex)
  325. {
  326. LogPrint (eLogError, "SSU: HandleReceivedPackets ", ex.what ());
  327. if (session) session->FlushData ();
  328. session = nullptr;
  329. }
  330. delete packet;
  331. }
  332. if (session) session->FlushData ();
  333. }
  334. std::shared_ptr<SSUSession> SSUServer::FindSession (std::shared_ptr<const i2p::data::RouterInfo> router) const
  335. {
  336. if (!router) return nullptr;
  337. auto address = router->GetSSUAddress (true); // v4 only
  338. if (!address) return nullptr;
  339. auto session = FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
  340. if (session || !context.SupportsV6 ())
  341. return session;
  342. // try v6
  343. address = router->GetSSUV6Address ();
  344. if (!address) return nullptr;
  345. return FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
  346. }
  347. std::shared_ptr<SSUSession> SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e) const
  348. {
  349. auto& sessions = e.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
  350. auto it = sessions.find (e);
  351. if (it != sessions.end ())
  352. return it->second;
  353. else
  354. return nullptr;
  355. }
  356. void SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest, bool v4only)
  357. {
  358. auto address = router->GetSSUAddress (v4only || !context.SupportsV6 ());
  359. if (address)
  360. CreateSession (router, address->host, address->port, peerTest);
  361. else
  362. LogPrint (eLogWarning, "SSU: Router ", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), " doesn't have SSU address");
  363. }
  364. void SSUServer::CreateSession (std::shared_ptr<const i2p::data::RouterInfo> router,
  365. const boost::asio::ip::address& addr, int port, bool peerTest)
  366. {
  367. if (router)
  368. {
  369. if (router->UsesIntroducer ())
  370. m_Service.post (std::bind (&SSUServer::CreateSessionThroughIntroducer, this, router, peerTest)); // always V4 thread
  371. else
  372. {
  373. boost::asio::ip::udp::endpoint remoteEndpoint (addr, port);
  374. auto& s = addr.is_v6 () ? m_ServiceV6 : m_Service;
  375. s.post (std::bind (&SSUServer::CreateDirectSession, this, router, remoteEndpoint, peerTest));
  376. }
  377. }
  378. }
  379. void SSUServer::CreateDirectSession (std::shared_ptr<const i2p::data::RouterInfo> router, boost::asio::ip::udp::endpoint remoteEndpoint, bool peerTest)
  380. {
  381. auto& sessions = remoteEndpoint.address ().is_v6 () ? m_SessionsV6 : m_Sessions;
  382. auto it = sessions.find (remoteEndpoint);
  383. if (it != sessions.end ())
  384. {
  385. auto session = it->second;
  386. if (peerTest && session->GetState () == eSessionStateEstablished)
  387. session->SendPeerTest ();
  388. }
  389. else
  390. {
  391. // otherwise create new session
  392. auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
  393. sessions[remoteEndpoint] = session;
  394. // connect
  395. LogPrint (eLogDebug, "SSU: Creating new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), "] ",
  396. remoteEndpoint.address ().to_string (), ":", remoteEndpoint.port ());
  397. session->Connect ();
  398. }
  399. }
  400. void SSUServer::CreateSessionThroughIntroducer (std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest)
  401. {
  402. if (router && router->UsesIntroducer ())
  403. {
  404. auto address = router->GetSSUAddress (true); // v4 only for now
  405. if (address)
  406. {
  407. boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
  408. auto it = m_Sessions.find (remoteEndpoint);
  409. // check if session is presented already
  410. if (it != m_Sessions.end ())
  411. {
  412. auto session = it->second;
  413. if (peerTest && session->GetState () == eSessionStateEstablished)
  414. session->SendPeerTest ();
  415. return;
  416. }
  417. // create new session
  418. int numIntroducers = address->ssu->introducers.size ();
  419. if (numIntroducers > 0)
  420. {
  421. uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
  422. std::shared_ptr<SSUSession> introducerSession;
  423. const i2p::data::RouterInfo::Introducer * introducer = nullptr;
  424. // we might have a session to introducer already
  425. for (int i = 0; i < numIntroducers; i++)
  426. {
  427. auto intr = &(address->ssu->introducers[i]);
  428. if (intr->iExp > 0 && ts > intr->iExp) continue; // skip expired introducer
  429. boost::asio::ip::udp::endpoint ep (intr->iHost, intr->iPort);
  430. if (ep.address ().is_v4 ()) // ipv4 only
  431. {
  432. if (!introducer) introducer = intr; // we pick first one for now
  433. it = m_Sessions.find (ep);
  434. if (it != m_Sessions.end ())
  435. {
  436. introducerSession = it->second;
  437. break;
  438. }
  439. }
  440. }
  441. if (!introducer)
  442. {
  443. LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no ipv4 non-expired introducers presented");
  444. return;
  445. }
  446. if (introducerSession) // session found
  447. LogPrint (eLogWarning, "SSU: Session to introducer already exists");
  448. else // create new
  449. {
  450. LogPrint (eLogDebug, "SSU: Creating new session to introducer ", introducer->iHost);
  451. boost::asio::ip::udp::endpoint introducerEndpoint (introducer->iHost, introducer->iPort);
  452. introducerSession = std::make_shared<SSUSession> (*this, introducerEndpoint, router);
  453. m_Sessions[introducerEndpoint] = introducerSession;
  454. }
  455. #if BOOST_VERSION >= 104900
  456. if (!address->host.is_unspecified () && address->port)
  457. #endif
  458. {
  459. // create session
  460. auto session = std::make_shared<SSUSession> (*this, remoteEndpoint, router, peerTest);
  461. m_Sessions[remoteEndpoint] = session;
  462. // introduce
  463. LogPrint (eLogInfo, "SSU: Introduce new session to [", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()),
  464. "] through introducer ", introducer->iHost, ":", introducer->iPort);
  465. session->WaitForIntroduction ();
  466. if (i2p::context.GetRouterInfo ().UsesIntroducer ()) // if we are unreachable
  467. {
  468. uint8_t buf[1];
  469. Send (buf, 0, remoteEndpoint); // send HolePunch
  470. }
  471. }
  472. introducerSession->Introduce (*introducer, router);
  473. }
  474. else
  475. LogPrint (eLogWarning, "SSU: Can't connect to unreachable router and no introducers present");
  476. }
  477. else
  478. LogPrint (eLogWarning, "SSU: Router ", i2p::data::GetIdentHashAbbreviation (router->GetIdentHash ()), " doesn't have SSU address");
  479. }
  480. }
  481. void SSUServer::DeleteSession (std::shared_ptr<SSUSession> session)
  482. {
  483. if (session)
  484. {
  485. session->Close ();
  486. auto& ep = session->GetRemoteEndpoint ();
  487. if (ep.address ().is_v6 ())
  488. m_SessionsV6.erase (ep);
  489. else
  490. m_Sessions.erase (ep);
  491. }
  492. }
  493. void SSUServer::DeleteAllSessions ()
  494. {
  495. for (auto& it: m_Sessions)
  496. it.second->Close ();
  497. m_Sessions.clear ();
  498. for (auto& it: m_SessionsV6)
  499. it.second->Close ();
  500. m_SessionsV6.clear ();
  501. }
  502. template<typename Filter>
  503. std::shared_ptr<SSUSession> SSUServer::GetRandomV4Session (Filter filter) // v4 only
  504. {
  505. std::vector<std::shared_ptr<SSUSession> > filteredSessions;
  506. for (const auto& s :m_Sessions)
  507. if (filter (s.second)) filteredSessions.push_back (s.second);
  508. if (filteredSessions.size () > 0)
  509. {
  510. auto ind = rand () % filteredSessions.size ();
  511. return filteredSessions[ind];
  512. }
  513. return nullptr;
  514. }
  515. std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV4Session (std::shared_ptr<const SSUSession> excluded) // v4 only
  516. {
  517. return GetRandomV4Session (
  518. [excluded](std::shared_ptr<SSUSession> session)->bool
  519. {
  520. return session->GetState () == eSessionStateEstablished && session != excluded;
  521. }
  522. );
  523. }
  524. template<typename Filter>
  525. std::shared_ptr<SSUSession> SSUServer::GetRandomV6Session (Filter filter) // v6 only
  526. {
  527. std::vector<std::shared_ptr<SSUSession> > filteredSessions;
  528. for (const auto& s :m_SessionsV6)
  529. if (filter (s.second)) filteredSessions.push_back (s.second);
  530. if (filteredSessions.size () > 0)
  531. {
  532. auto ind = rand () % filteredSessions.size ();
  533. return filteredSessions[ind];
  534. }
  535. return nullptr;
  536. }
  537. std::shared_ptr<SSUSession> SSUServer::GetRandomEstablishedV6Session (std::shared_ptr<const SSUSession> excluded) // v6 only
  538. {
  539. return GetRandomV6Session (
  540. [excluded](std::shared_ptr<SSUSession> session)->bool
  541. {
  542. return session->GetState () == eSessionStateEstablished && session != excluded;
  543. }
  544. );
  545. }
  546. std::set<SSUSession *> SSUServer::FindIntroducers (int maxNumIntroducers)
  547. {
  548. uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
  549. std::set<SSUSession *> ret;
  550. for (int i = 0; i < maxNumIntroducers; i++)
  551. {
  552. auto session = GetRandomV4Session (
  553. [&ret, ts](std::shared_ptr<SSUSession> session)->bool
  554. {
  555. return session->GetRelayTag () && !ret.count (session.get ()) &&
  556. session->GetState () == eSessionStateEstablished &&
  557. ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION;
  558. }
  559. );
  560. if (session)
  561. {
  562. ret.insert (session.get ());
  563. break;
  564. }
  565. }
  566. return ret;
  567. }
  568. void SSUServer::ScheduleIntroducersUpdateTimer ()
  569. {
  570. m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
  571. m_IntroducersUpdateTimer.async_wait (std::bind (&SSUServer::HandleIntroducersUpdateTimer,
  572. this, std::placeholders::_1));
  573. }
  574. void SSUServer::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode)
  575. {
  576. if (ecode != boost::asio::error::operation_aborted)
  577. {
  578. // timeout expired
  579. if (i2p::context.GetStatus () == eRouterStatusTesting)
  580. {
  581. // we still don't know if we need introducers
  582. ScheduleIntroducersUpdateTimer ();
  583. return;
  584. }
  585. if (i2p::context.GetStatus () == eRouterStatusOK) return; // we don't need introducers anymore
  586. // we are firewalled
  587. if (!i2p::context.IsUnreachable ()) i2p::context.SetUnreachable ();
  588. std::list<boost::asio::ip::udp::endpoint> newList;
  589. size_t numIntroducers = 0;
  590. uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
  591. for (const auto& it : m_Introducers)
  592. {
  593. auto session = FindSession (it);
  594. if (session && ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION)
  595. {
  596. session->SendKeepAlive ();
  597. newList.push_back (it);
  598. numIntroducers++;
  599. }
  600. else
  601. i2p::context.RemoveIntroducer (it);
  602. }
  603. if (numIntroducers < SSU_MAX_NUM_INTRODUCERS)
  604. {
  605. // create new
  606. auto introducers = FindIntroducers (SSU_MAX_NUM_INTRODUCERS);
  607. for (const auto& it1: introducers)
  608. {
  609. const auto& ep = it1->GetRemoteEndpoint ();
  610. i2p::data::RouterInfo::Introducer introducer;
  611. introducer.iHost = ep.address ();
  612. introducer.iPort = ep.port ();
  613. introducer.iTag = it1->GetRelayTag ();
  614. introducer.iKey = it1->GetIntroKey ();
  615. if (i2p::context.AddIntroducer (introducer))
  616. {
  617. newList.push_back (ep);
  618. if (newList.size () >= SSU_MAX_NUM_INTRODUCERS) break;
  619. }
  620. }
  621. }
  622. m_Introducers = newList;
  623. if (m_Introducers.size () < SSU_MAX_NUM_INTRODUCERS)
  624. {
  625. auto introducer = i2p::data::netdb.GetRandomIntroducer ();
  626. if (introducer)
  627. CreateSession (introducer);
  628. }
  629. ScheduleIntroducersUpdateTimer ();
  630. }
  631. }
  632. void SSUServer::NewPeerTest (uint32_t nonce, PeerTestParticipant role, std::shared_ptr<SSUSession> session)
  633. {
  634. m_PeerTests[nonce] = { i2p::util::GetMillisecondsSinceEpoch (), role, session };
  635. }
  636. PeerTestParticipant SSUServer::GetPeerTestParticipant (uint32_t nonce)
  637. {
  638. auto it = m_PeerTests.find (nonce);
  639. if (it != m_PeerTests.end ())
  640. return it->second.role;
  641. else
  642. return ePeerTestParticipantUnknown;
  643. }
  644. std::shared_ptr<SSUSession> SSUServer::GetPeerTestSession (uint32_t nonce)
  645. {
  646. auto it = m_PeerTests.find (nonce);
  647. if (it != m_PeerTests.end ())
  648. return it->second.session;
  649. else
  650. return nullptr;
  651. }
  652. void SSUServer::UpdatePeerTest (uint32_t nonce, PeerTestParticipant role)
  653. {
  654. auto it = m_PeerTests.find (nonce);
  655. if (it != m_PeerTests.end ())
  656. it->second.role = role;
  657. }
  658. void SSUServer::RemovePeerTest (uint32_t nonce)
  659. {
  660. m_PeerTests.erase (nonce);
  661. }
  662. void SSUServer::SchedulePeerTestsCleanupTimer ()
  663. {
  664. m_PeerTestsCleanupTimer.expires_from_now (boost::posix_time::seconds(SSU_PEER_TEST_TIMEOUT));
  665. m_PeerTestsCleanupTimer.async_wait (std::bind (&SSUServer::HandlePeerTestsCleanupTimer,
  666. this, std::placeholders::_1));
  667. }
  668. void SSUServer::HandlePeerTestsCleanupTimer (const boost::system::error_code& ecode)
  669. {
  670. if (ecode != boost::asio::error::operation_aborted)
  671. {
  672. int numDeleted = 0;
  673. uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
  674. for (auto it = m_PeerTests.begin (); it != m_PeerTests.end ();)
  675. {
  676. if (ts > it->second.creationTime + SSU_PEER_TEST_TIMEOUT*1000LL)
  677. {
  678. numDeleted++;
  679. it = m_PeerTests.erase (it);
  680. }
  681. else
  682. ++it;
  683. }
  684. if (numDeleted > 0)
  685. LogPrint (eLogDebug, "SSU: ", numDeleted, " peer tests have been expired");
  686. SchedulePeerTestsCleanupTimer ();
  687. }
  688. }
  689. void SSUServer::ScheduleTermination ()
  690. {
  691. m_TerminationTimer.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
  692. m_TerminationTimer.async_wait (std::bind (&SSUServer::HandleTerminationTimer,
  693. this, std::placeholders::_1));
  694. }
  695. void SSUServer::HandleTerminationTimer (const boost::system::error_code& ecode)
  696. {
  697. if (ecode != boost::asio::error::operation_aborted)
  698. {
  699. auto ts = i2p::util::GetSecondsSinceEpoch ();
  700. for (auto& it: m_Sessions)
  701. if (it.second->IsTerminationTimeoutExpired (ts))
  702. {
  703. auto session = it.second;
  704. if (it.first != session->GetRemoteEndpoint ())
  705. LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first, " adjusted");
  706. m_Service.post ([session]
  707. {
  708. LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
  709. session->Failed ();
  710. });
  711. }
  712. ScheduleTermination ();
  713. }
  714. }
  715. void SSUServer::ScheduleTerminationV6 ()
  716. {
  717. m_TerminationTimerV6.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_CHECK_TIMEOUT));
  718. m_TerminationTimerV6.async_wait (std::bind (&SSUServer::HandleTerminationTimerV6,
  719. this, std::placeholders::_1));
  720. }
  721. void SSUServer::HandleTerminationTimerV6 (const boost::system::error_code& ecode)
  722. {
  723. if (ecode != boost::asio::error::operation_aborted)
  724. {
  725. auto ts = i2p::util::GetSecondsSinceEpoch ();
  726. for (auto& it: m_SessionsV6)
  727. if (it.second->IsTerminationTimeoutExpired (ts))
  728. {
  729. auto session = it.second;
  730. if (it.first != session->GetRemoteEndpoint ())
  731. LogPrint (eLogWarning, "SSU: remote endpoint ", session->GetRemoteEndpoint (), " doesn't match key ", it.first);
  732. m_ServiceV6.post ([session]
  733. {
  734. LogPrint (eLogWarning, "SSU: no activity with ", session->GetRemoteEndpoint (), " for ", session->GetTerminationTimeout (), " seconds");
  735. session->Failed ();
  736. });
  737. }
  738. ScheduleTerminationV6 ();
  739. }
  740. }
  741. }
  742. }