Transports.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. #include "Log.h"
  2. #include "Crypto.h"
  3. #include "RouterContext.h"
  4. #include "I2NPProtocol.h"
  5. #include "NetDb.hpp"
  6. #include "Transports.h"
  7. #include "Config.h"
  8. #include "HTTP.h"
  9. #ifdef WITH_EVENTS
  10. #include "Event.h"
  11. #include "util.h"
  12. #endif
  13. using namespace i2p::data;
  14. namespace i2p
  15. {
  16. namespace transport
  17. {
  18. DHKeysPairSupplier::DHKeysPairSupplier (int size):
  19. m_QueueSize (size), m_IsRunning (false), m_Thread (nullptr)
  20. {
  21. }
  22. DHKeysPairSupplier::~DHKeysPairSupplier ()
  23. {
  24. Stop ();
  25. }
  26. void DHKeysPairSupplier::Start ()
  27. {
  28. m_IsRunning = true;
  29. m_Thread = new std::thread (std::bind (&DHKeysPairSupplier::Run, this));
  30. }
  31. void DHKeysPairSupplier::Stop ()
  32. {
  33. {
  34. std::unique_lock<std::mutex> l(m_AcquiredMutex);
  35. m_IsRunning = false;
  36. m_Acquired.notify_one ();
  37. }
  38. if (m_Thread)
  39. {
  40. m_Thread->join ();
  41. delete m_Thread;
  42. m_Thread = 0;
  43. }
  44. }
  45. void DHKeysPairSupplier::Run ()
  46. {
  47. while (m_IsRunning)
  48. {
  49. int num, total = 0;
  50. while ((num = m_QueueSize - (int)m_Queue.size ()) > 0 && total < 10)
  51. {
  52. CreateDHKeysPairs (num);
  53. total += num;
  54. }
  55. if (total >= 10)
  56. {
  57. LogPrint (eLogWarning, "Transports: ", total, " DH keys generated at the time");
  58. std::this_thread::sleep_for (std::chrono::seconds(1)); // take a break
  59. }
  60. else
  61. {
  62. std::unique_lock<std::mutex> l(m_AcquiredMutex);
  63. if (!m_IsRunning) break;
  64. m_Acquired.wait (l); // wait for element gets acquired
  65. }
  66. }
  67. }
  68. void DHKeysPairSupplier::CreateDHKeysPairs (int num)
  69. {
  70. if (num > 0)
  71. {
  72. for (int i = 0; i < num; i++)
  73. {
  74. auto pair = std::make_shared<i2p::crypto::DHKeys> ();
  75. pair->GenerateKeys ();
  76. std::unique_lock<std::mutex> l(m_AcquiredMutex);
  77. m_Queue.push (pair);
  78. }
  79. }
  80. }
  81. std::shared_ptr<i2p::crypto::DHKeys> DHKeysPairSupplier::Acquire ()
  82. {
  83. {
  84. std::unique_lock<std::mutex> l(m_AcquiredMutex);
  85. if (!m_Queue.empty ())
  86. {
  87. auto pair = m_Queue.front ();
  88. m_Queue.pop ();
  89. m_Acquired.notify_one ();
  90. return pair;
  91. }
  92. }
  93. // queue is empty, create new
  94. auto pair = std::make_shared<i2p::crypto::DHKeys> ();
  95. pair->GenerateKeys ();
  96. return pair;
  97. }
  98. void DHKeysPairSupplier::Return (std::shared_ptr<i2p::crypto::DHKeys> pair)
  99. {
  100. if (pair)
  101. {
  102. std::unique_lock<std::mutex>l(m_AcquiredMutex);
  103. if ((int)m_Queue.size () < 2*m_QueueSize)
  104. m_Queue.push (pair);
  105. }
  106. else
  107. LogPrint(eLogError, "Transports: return null DHKeys");
  108. }
  109. Transports transports;
  110. Transports::Transports ():
  111. m_IsOnline (true), m_IsRunning (false), m_IsNAT (true), m_Thread (nullptr), m_Service (nullptr),
  112. m_Work (nullptr), m_PeerCleanupTimer (nullptr), m_PeerTestTimer (nullptr),
  113. m_NTCPServer (nullptr), m_SSUServer (nullptr), m_NTCP2Server (nullptr),
  114. m_DHKeysPairSupplier (5), // 5 pre-generated keys
  115. m_TotalSentBytes(0), m_TotalReceivedBytes(0), m_TotalTransitTransmittedBytes (0),
  116. m_InBandwidth (0), m_OutBandwidth (0), m_TransitBandwidth(0),
  117. m_LastInBandwidthUpdateBytes (0), m_LastOutBandwidthUpdateBytes (0),
  118. m_LastTransitBandwidthUpdateBytes (0), m_LastBandwidthUpdateTime (0)
  119. {
  120. }
  121. Transports::~Transports ()
  122. {
  123. Stop ();
  124. if (m_Service)
  125. {
  126. delete m_PeerCleanupTimer; m_PeerCleanupTimer = nullptr;
  127. delete m_PeerTestTimer; m_PeerTestTimer = nullptr;
  128. delete m_Work; m_Work = nullptr;
  129. delete m_Service; m_Service = nullptr;
  130. }
  131. }
  132. void Transports::Start (bool enableNTCP, bool enableSSU)
  133. {
  134. if (!m_Service)
  135. {
  136. m_Service = new boost::asio::io_service ();
  137. m_Work = new boost::asio::io_service::work (*m_Service);
  138. m_PeerCleanupTimer = new boost::asio::deadline_timer (*m_Service);
  139. m_PeerTestTimer = new boost::asio::deadline_timer (*m_Service);
  140. }
  141. i2p::config::GetOption("nat", m_IsNAT);
  142. m_DHKeysPairSupplier.Start ();
  143. m_IsRunning = true;
  144. m_Thread = new std::thread (std::bind (&Transports::Run, this));
  145. std::string ntcpproxy; i2p::config::GetOption("ntcpproxy", ntcpproxy);
  146. i2p::http::URL proxyurl;
  147. uint16_t softLimit, hardLimit, threads;
  148. i2p::config::GetOption("limits.ntcpsoft", softLimit);
  149. i2p::config::GetOption("limits.ntcphard", hardLimit);
  150. i2p::config::GetOption("limits.ntcpthreads", threads);
  151. if(softLimit > 0 && hardLimit > 0 && softLimit >= hardLimit)
  152. {
  153. LogPrint(eLogError, "ntcp soft limit must be less than ntcp hard limit");
  154. return;
  155. }
  156. if(ntcpproxy.size() && enableNTCP)
  157. {
  158. if(proxyurl.parse(ntcpproxy))
  159. {
  160. if(proxyurl.schema == "socks" || proxyurl.schema == "http")
  161. {
  162. m_NTCPServer = new NTCPServer(threads);
  163. m_NTCPServer->SetSessionLimits(softLimit, hardLimit);
  164. NTCPServer::ProxyType proxytype = NTCPServer::eSocksProxy;
  165. if (proxyurl.schema == "http")
  166. proxytype = NTCPServer::eHTTPProxy;
  167. m_NTCPServer->UseProxy(proxytype, proxyurl.host, proxyurl.port) ;
  168. m_NTCPServer->Start();
  169. if(!m_NTCPServer->NetworkIsReady())
  170. {
  171. LogPrint(eLogError, "Transports: NTCP failed to start with proxy");
  172. m_NTCPServer->Stop();
  173. delete m_NTCPServer;
  174. m_NTCPServer = nullptr;
  175. }
  176. }
  177. else
  178. LogPrint(eLogError, "Transports: unsupported NTCP proxy URL ", ntcpproxy);
  179. }
  180. else
  181. LogPrint(eLogError, "Transports: invalid NTCP proxy url ", ntcpproxy);
  182. return;
  183. }
  184. // create NTCP2. TODO: move to acceptor
  185. bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2);
  186. if (ntcp2)
  187. {
  188. m_NTCP2Server = new NTCP2Server ();
  189. m_NTCP2Server->Start ();
  190. }
  191. // create acceptors
  192. auto& addresses = context.GetRouterInfo ().GetAddresses ();
  193. for (const auto& address : addresses)
  194. {
  195. if (!address) continue;
  196. if (m_NTCPServer == nullptr && enableNTCP)
  197. {
  198. m_NTCPServer = new NTCPServer (threads);
  199. m_NTCPServer->SetSessionLimits(softLimit, hardLimit);
  200. m_NTCPServer->Start ();
  201. if (!(m_NTCPServer->IsBoundV6() || m_NTCPServer->IsBoundV4())) {
  202. /** failed to bind to NTCP */
  203. LogPrint(eLogError, "Transports: failed to bind to TCP");
  204. m_NTCPServer->Stop();
  205. delete m_NTCPServer;
  206. m_NTCPServer = nullptr;
  207. }
  208. }
  209. if (address->transportStyle == RouterInfo::eTransportSSU)
  210. {
  211. if (m_SSUServer == nullptr && enableSSU)
  212. {
  213. if (address->host.is_v4())
  214. m_SSUServer = new SSUServer (address->port);
  215. else
  216. m_SSUServer = new SSUServer (address->host, address->port);
  217. LogPrint (eLogInfo, "Transports: Start listening UDP port ", address->port);
  218. try {
  219. m_SSUServer->Start ();
  220. } catch ( std::exception & ex ) {
  221. LogPrint(eLogError, "Transports: Failed to bind to UDP port", address->port);
  222. delete m_SSUServer;
  223. m_SSUServer = nullptr;
  224. continue;
  225. }
  226. DetectExternalIP ();
  227. }
  228. else
  229. LogPrint (eLogError, "Transports: SSU server already exists");
  230. }
  231. }
  232. m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
  233. m_PeerCleanupTimer->async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
  234. if (m_IsNAT)
  235. {
  236. m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
  237. m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
  238. }
  239. }
  240. void Transports::Stop ()
  241. {
  242. if (m_PeerCleanupTimer) m_PeerCleanupTimer->cancel ();
  243. if (m_PeerTestTimer) m_PeerTestTimer->cancel ();
  244. m_Peers.clear ();
  245. if (m_SSUServer)
  246. {
  247. m_SSUServer->Stop ();
  248. delete m_SSUServer;
  249. m_SSUServer = nullptr;
  250. }
  251. if (m_NTCPServer)
  252. {
  253. m_NTCPServer->Stop ();
  254. delete m_NTCPServer;
  255. m_NTCPServer = nullptr;
  256. }
  257. if (m_NTCP2Server)
  258. {
  259. m_NTCP2Server->Stop ();
  260. delete m_NTCP2Server;
  261. m_NTCP2Server = nullptr;
  262. }
  263. m_DHKeysPairSupplier.Stop ();
  264. m_IsRunning = false;
  265. if (m_Service) m_Service->stop ();
  266. if (m_Thread)
  267. {
  268. m_Thread->join ();
  269. delete m_Thread;
  270. m_Thread = nullptr;
  271. }
  272. }
  273. void Transports::Run ()
  274. {
  275. while (m_IsRunning && m_Service)
  276. {
  277. try
  278. {
  279. m_Service->run ();
  280. }
  281. catch (std::exception& ex)
  282. {
  283. LogPrint (eLogError, "Transports: runtime exception: ", ex.what ());
  284. }
  285. }
  286. }
  287. void Transports::UpdateBandwidth ()
  288. {
  289. uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
  290. if (m_LastBandwidthUpdateTime > 0)
  291. {
  292. auto delta = ts - m_LastBandwidthUpdateTime;
  293. if (delta > 0)
  294. {
  295. m_InBandwidth = (m_TotalReceivedBytes - m_LastInBandwidthUpdateBytes)*1000/delta; // per second
  296. m_OutBandwidth = (m_TotalSentBytes - m_LastOutBandwidthUpdateBytes)*1000/delta; // per second
  297. m_TransitBandwidth = (m_TotalTransitTransmittedBytes - m_LastTransitBandwidthUpdateBytes)*1000/delta;
  298. }
  299. }
  300. m_LastBandwidthUpdateTime = ts;
  301. m_LastInBandwidthUpdateBytes = m_TotalReceivedBytes;
  302. m_LastOutBandwidthUpdateBytes = m_TotalSentBytes;
  303. m_LastTransitBandwidthUpdateBytes = m_TotalTransitTransmittedBytes;
  304. }
  305. bool Transports::IsBandwidthExceeded () const
  306. {
  307. auto limit = i2p::context.GetBandwidthLimit() * 1024; // convert to bytes
  308. auto bw = std::max (m_InBandwidth, m_OutBandwidth);
  309. return bw > limit;
  310. }
  311. bool Transports::IsTransitBandwidthExceeded () const
  312. {
  313. auto limit = i2p::context.GetTransitBandwidthLimit() * 1024; // convert to bytes
  314. return m_TransitBandwidth > limit;
  315. }
  316. void Transports::SendMessage (const i2p::data::IdentHash& ident, std::shared_ptr<i2p::I2NPMessage> msg)
  317. {
  318. SendMessages (ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > {msg });
  319. }
  320. void Transports::SendMessages (const i2p::data::IdentHash& ident, const std::vector<std::shared_ptr<i2p::I2NPMessage> >& msgs)
  321. {
  322. #ifdef WITH_EVENTS
  323. QueueIntEvent("transport.send", ident.ToBase64(), msgs.size());
  324. #endif
  325. m_Service->post (std::bind (&Transports::PostMessages, this, ident, msgs));
  326. }
  327. void Transports::PostMessages (i2p::data::IdentHash ident, std::vector<std::shared_ptr<i2p::I2NPMessage> > msgs)
  328. {
  329. if (ident == i2p::context.GetRouterInfo ().GetIdentHash ())
  330. {
  331. // we send it to ourself
  332. for (auto& it: msgs)
  333. m_LoopbackHandler.PutNextMessage (it);
  334. m_LoopbackHandler.Flush ();
  335. return;
  336. }
  337. if(RoutesRestricted() && ! IsRestrictedPeer(ident)) return;
  338. auto it = m_Peers.find (ident);
  339. if (it == m_Peers.end ())
  340. {
  341. bool connected = false;
  342. try
  343. {
  344. auto r = netdb.FindRouter (ident);
  345. {
  346. std::unique_lock<std::mutex> l(m_PeersMutex);
  347. it = m_Peers.insert (std::pair<i2p::data::IdentHash, Peer>(ident, { 0, r, {},
  348. i2p::util::GetSecondsSinceEpoch (), {} })).first;
  349. }
  350. connected = ConnectToPeer (ident, it->second);
  351. }
  352. catch (std::exception& ex)
  353. {
  354. LogPrint (eLogError, "Transports: PostMessages exception:", ex.what ());
  355. }
  356. if (!connected) return;
  357. }
  358. if (!it->second.sessions.empty ())
  359. it->second.sessions.front ()->SendI2NPMessages (msgs);
  360. else
  361. {
  362. if (it->second.delayedMessages.size () < MAX_NUM_DELAYED_MESSAGES)
  363. {
  364. for (auto& it1: msgs)
  365. it->second.delayedMessages.push_back (it1);
  366. }
  367. else
  368. {
  369. LogPrint (eLogWarning, "Transports: delayed messages queue size exceeds ", MAX_NUM_DELAYED_MESSAGES);
  370. std::unique_lock<std::mutex> l(m_PeersMutex);
  371. m_Peers.erase (it);
  372. }
  373. }
  374. }
  375. bool Transports::ConnectToPeer (const i2p::data::IdentHash& ident, Peer& peer)
  376. {
  377. if (peer.router) // we have RI already
  378. {
  379. if (!peer.numAttempts) // NTCP2
  380. {
  381. peer.numAttempts++;
  382. if (m_NTCP2Server) // we support NTCP2
  383. {
  384. // NTCP2 have priority over NTCP
  385. auto address = peer.router->GetNTCP2Address (true, !context.SupportsV6 ()); // published only
  386. if (address)
  387. {
  388. auto s = std::make_shared<NTCP2Session> (*m_NTCP2Server, peer.router);
  389. m_NTCP2Server->Connect (address->host, address->port, s);
  390. return true;
  391. }
  392. }
  393. }
  394. if (peer.numAttempts == 1) // NTCP1
  395. {
  396. peer.numAttempts++;
  397. auto address = peer.router->GetNTCPAddress (!context.SupportsV6 ());
  398. if (address && m_NTCPServer)
  399. {
  400. if (!peer.router->UsesIntroducer () && !peer.router->IsUnreachable ())
  401. {
  402. if(!m_NTCPServer->ShouldLimit())
  403. {
  404. auto s = std::make_shared<NTCPSession> (*m_NTCPServer, peer.router);
  405. if(m_NTCPServer->UsingProxy())
  406. {
  407. NTCPServer::RemoteAddressType remote = NTCPServer::eIP4Address;
  408. std::string addr = address->host.to_string();
  409. if(address->host.is_v6())
  410. remote = NTCPServer::eIP6Address;
  411. m_NTCPServer->ConnectWithProxy(addr, address->port, remote, s);
  412. }
  413. else
  414. m_NTCPServer->Connect (address->host, address->port, s);
  415. return true;
  416. }
  417. else
  418. {
  419. LogPrint(eLogWarning, "Transports: NTCP Limit hit falling back to SSU");
  420. }
  421. }
  422. }
  423. else
  424. LogPrint (eLogDebug, "Transports: NTCP address is not present for ", i2p::data::GetIdentHashAbbreviation (ident), ", trying SSU");
  425. }
  426. if (peer.numAttempts == 2)// SSU
  427. {
  428. peer.numAttempts++;
  429. if (m_SSUServer && peer.router->IsSSU (!context.SupportsV6 ()))
  430. {
  431. auto address = peer.router->GetSSUAddress (!context.SupportsV6 ());
  432. m_SSUServer->CreateSession (peer.router, address->host, address->port);
  433. return true;
  434. }
  435. }
  436. LogPrint (eLogInfo, "Transports: No NTCP or SSU addresses available");
  437. peer.Done ();
  438. std::unique_lock<std::mutex> l(m_PeersMutex);
  439. m_Peers.erase (ident);
  440. return false;
  441. }
  442. else // otherwise request RI
  443. {
  444. LogPrint (eLogInfo, "Transports: RouterInfo for ", ident.ToBase64 (), " not found, requested");
  445. i2p::data::netdb.RequestDestination (ident, std::bind (
  446. &Transports::RequestComplete, this, std::placeholders::_1, ident));
  447. }
  448. return true;
  449. }
  450. void Transports::RequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, const i2p::data::IdentHash& ident)
  451. {
  452. m_Service->post (std::bind (&Transports::HandleRequestComplete, this, r, ident));
  453. }
  454. void Transports::HandleRequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, i2p::data::IdentHash ident)
  455. {
  456. auto it = m_Peers.find (ident);
  457. if (it != m_Peers.end ())
  458. {
  459. if (r)
  460. {
  461. LogPrint (eLogDebug, "Transports: RouterInfo for ", ident.ToBase64 (), " found, Trying to connect");
  462. it->second.router = r;
  463. ConnectToPeer (ident, it->second);
  464. }
  465. else
  466. {
  467. LogPrint (eLogWarning, "Transports: RouterInfo not found, Failed to send messages");
  468. std::unique_lock<std::mutex> l(m_PeersMutex);
  469. m_Peers.erase (it);
  470. }
  471. }
  472. }
  473. void Transports::CloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
  474. {
  475. if (!router) return;
  476. m_Service->post (std::bind (&Transports::PostCloseSession, this, router));
  477. }
  478. void Transports::PostCloseSession (std::shared_ptr<const i2p::data::RouterInfo> router)
  479. {
  480. auto ssuSession = m_SSUServer ? m_SSUServer->FindSession (router) : nullptr;
  481. if (ssuSession) // try SSU first
  482. {
  483. m_SSUServer->DeleteSession (ssuSession);
  484. LogPrint (eLogDebug, "Transports: SSU session closed");
  485. }
  486. auto ntcpSession = m_NTCPServer ? m_NTCPServer->FindNTCPSession(router->GetIdentHash()) : nullptr;
  487. if (ntcpSession) // try deleting ntcp session too
  488. {
  489. ntcpSession->Terminate ();
  490. LogPrint(eLogDebug, "Transports: NTCP session closed");
  491. }
  492. }
  493. void Transports::DetectExternalIP ()
  494. {
  495. if (RoutesRestricted())
  496. {
  497. LogPrint(eLogInfo, "Transports: restricted routes enabled, not detecting ip");
  498. i2p::context.SetStatus (eRouterStatusOK);
  499. return;
  500. }
  501. if (m_SSUServer)
  502. {
  503. bool isv4 = i2p::context.SupportsV4 ();
  504. if (m_IsNAT && isv4)
  505. i2p::context.SetStatus (eRouterStatusTesting);
  506. for (int i = 0; i < 5; i++)
  507. {
  508. auto router = i2p::data::netdb.GetRandomPeerTestRouter (isv4); // v4 only if v4
  509. if (router)
  510. m_SSUServer->CreateSession (router, true, isv4); // peer test
  511. else
  512. {
  513. // if not peer test capable routers found pick any
  514. router = i2p::data::netdb.GetRandomRouter ();
  515. if (router && router->IsSSU ())
  516. m_SSUServer->CreateSession (router); // no peer test
  517. }
  518. }
  519. if (i2p::context.SupportsV6 ())
  520. {
  521. // try to connect to few v6 addresses to get our address back
  522. for (int i = 0; i < 3; i++)
  523. {
  524. auto router = i2p::data::netdb.GetRandomSSUV6Router ();
  525. if (router)
  526. {
  527. auto addr = router->GetSSUV6Address ();
  528. if (addr)
  529. m_SSUServer->GetServiceV6 ().post ([this, router, addr]
  530. {
  531. m_SSUServer->CreateDirectSession (router, { addr->host, (uint16_t)addr->port }, false);
  532. });
  533. }
  534. }
  535. }
  536. }
  537. else
  538. LogPrint (eLogError, "Transports: Can't detect external IP. SSU is not available");
  539. }
  540. void Transports::PeerTest ()
  541. {
  542. if (RoutesRestricted() || !i2p::context.SupportsV4 ()) return;
  543. if (m_SSUServer)
  544. {
  545. bool statusChanged = false;
  546. for (int i = 0; i < 5; i++)
  547. {
  548. auto router = i2p::data::netdb.GetRandomPeerTestRouter (true); // v4 only
  549. if (router)
  550. {
  551. if (!statusChanged)
  552. {
  553. statusChanged = true;
  554. i2p::context.SetStatus (eRouterStatusTesting); // first time only
  555. }
  556. m_SSUServer->CreateSession (router, true, true); // peer test v4
  557. }
  558. }
  559. if (!statusChanged)
  560. LogPrint (eLogWarning, "Can't find routers for peer test");
  561. }
  562. }
  563. std::shared_ptr<i2p::crypto::DHKeys> Transports::GetNextDHKeysPair ()
  564. {
  565. return m_DHKeysPairSupplier.Acquire ();
  566. }
  567. void Transports::ReuseDHKeysPair (std::shared_ptr<i2p::crypto::DHKeys> pair)
  568. {
  569. m_DHKeysPairSupplier.Return (pair);
  570. }
  571. void Transports::PeerConnected (std::shared_ptr<TransportSession> session)
  572. {
  573. m_Service->post([session, this]()
  574. {
  575. auto remoteIdentity = session->GetRemoteIdentity ();
  576. if (!remoteIdentity) return;
  577. auto ident = remoteIdentity->GetIdentHash ();
  578. auto it = m_Peers.find (ident);
  579. if (it != m_Peers.end ())
  580. {
  581. #ifdef WITH_EVENTS
  582. EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "false"}});
  583. #endif
  584. bool sendDatabaseStore = true;
  585. if (it->second.delayedMessages.size () > 0)
  586. {
  587. // check if first message is our DatabaseStore (publishing)
  588. auto firstMsg = it->second.delayedMessages[0];
  589. if (firstMsg && firstMsg->GetTypeID () == eI2NPDatabaseStore &&
  590. i2p::data::IdentHash(firstMsg->GetPayload () + DATABASE_STORE_KEY_OFFSET) == i2p::context.GetIdentHash ())
  591. sendDatabaseStore = false; // we have it in the list already
  592. }
  593. if (sendDatabaseStore)
  594. session->SendLocalRouterInfo ();
  595. else
  596. session->SetTerminationTimeout (10); // most likely it's publishing, no follow-up messages expected, set timeout to 10 seconds
  597. it->second.sessions.push_back (session);
  598. session->SendI2NPMessages (it->second.delayedMessages);
  599. it->second.delayedMessages.clear ();
  600. }
  601. else // incoming connection
  602. {
  603. if(RoutesRestricted() && ! IsRestrictedPeer(ident)) {
  604. // not trusted
  605. LogPrint(eLogWarning, "Transports: closing untrusted inbound connection from ", ident.ToBase64());
  606. session->Done();
  607. return;
  608. }
  609. #ifdef WITH_EVENTS
  610. EmitEvent({{"type" , "transport.connected"}, {"ident", ident.ToBase64()}, {"inbound", "true"}});
  611. #endif
  612. session->SendI2NPMessages ({ CreateDatabaseStoreMsg () }); // send DatabaseStore
  613. std::unique_lock<std::mutex> l(m_PeersMutex);
  614. m_Peers.insert (std::make_pair (ident, Peer{ 0, nullptr, { session }, i2p::util::GetSecondsSinceEpoch (), {} }));
  615. }
  616. });
  617. }
  618. void Transports::PeerDisconnected (std::shared_ptr<TransportSession> session)
  619. {
  620. m_Service->post([session, this]()
  621. {
  622. auto remoteIdentity = session->GetRemoteIdentity ();
  623. if (!remoteIdentity) return;
  624. auto ident = remoteIdentity->GetIdentHash ();
  625. #ifdef WITH_EVENTS
  626. EmitEvent({{"type" , "transport.disconnected"}, {"ident", ident.ToBase64()}});
  627. #endif
  628. auto it = m_Peers.find (ident);
  629. if (it != m_Peers.end ())
  630. {
  631. it->second.sessions.remove (session);
  632. if (it->second.sessions.empty ()) // TODO: why?
  633. {
  634. if (it->second.delayedMessages.size () > 0)
  635. ConnectToPeer (ident, it->second);
  636. else
  637. {
  638. std::unique_lock<std::mutex> l(m_PeersMutex);
  639. m_Peers.erase (it);
  640. }
  641. }
  642. }
  643. });
  644. }
  645. bool Transports::IsConnected (const i2p::data::IdentHash& ident) const
  646. {
  647. std::unique_lock<std::mutex> l(m_PeersMutex);
  648. auto it = m_Peers.find (ident);
  649. return it != m_Peers.end ();
  650. }
  651. void Transports::HandlePeerCleanupTimer (const boost::system::error_code& ecode)
  652. {
  653. if (ecode != boost::asio::error::operation_aborted)
  654. {
  655. auto ts = i2p::util::GetSecondsSinceEpoch ();
  656. for (auto it = m_Peers.begin (); it != m_Peers.end (); )
  657. {
  658. if (it->second.sessions.empty () && ts > it->second.creationTime + SESSION_CREATION_TIMEOUT)
  659. {
  660. LogPrint (eLogWarning, "Transports: Session to peer ", it->first.ToBase64 (), " has not been created in ", SESSION_CREATION_TIMEOUT, " seconds");
  661. auto profile = i2p::data::GetRouterProfile(it->first);
  662. if (profile)
  663. {
  664. profile->TunnelNonReplied();
  665. }
  666. std::unique_lock<std::mutex> l(m_PeersMutex);
  667. it = m_Peers.erase (it);
  668. }
  669. else
  670. ++it;
  671. }
  672. UpdateBandwidth (); // TODO: use separate timer(s) for it
  673. if (i2p::context.GetStatus () == eRouterStatusTesting) // if still testing, repeat peer test
  674. DetectExternalIP ();
  675. m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(5*SESSION_CREATION_TIMEOUT));
  676. m_PeerCleanupTimer->async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
  677. }
  678. }
  679. void Transports::HandlePeerTestTimer (const boost::system::error_code& ecode)
  680. {
  681. if (ecode != boost::asio::error::operation_aborted)
  682. {
  683. PeerTest ();
  684. m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
  685. m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
  686. }
  687. }
  688. std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRandomPeer () const
  689. {
  690. if (m_Peers.empty ()) return nullptr;
  691. std::unique_lock<std::mutex> l(m_PeersMutex);
  692. auto it = m_Peers.begin ();
  693. std::advance (it, rand () % m_Peers.size ());
  694. return it != m_Peers.end () ? it->second.router : nullptr;
  695. }
  696. void Transports::RestrictRoutesToFamilies(std::set<std::string> families)
  697. {
  698. std::lock_guard<std::mutex> lock(m_FamilyMutex);
  699. m_TrustedFamilies.clear();
  700. for ( const auto& fam : families )
  701. m_TrustedFamilies.push_back(fam);
  702. }
  703. void Transports::RestrictRoutesToRouters(std::set<i2p::data::IdentHash> routers)
  704. {
  705. std::unique_lock<std::mutex> lock(m_TrustedRoutersMutex);
  706. m_TrustedRouters.clear();
  707. for (const auto & ri : routers )
  708. m_TrustedRouters.push_back(ri);
  709. }
  710. bool Transports::RoutesRestricted() const {
  711. std::unique_lock<std::mutex> famlock(m_FamilyMutex);
  712. std::unique_lock<std::mutex> routerslock(m_TrustedRoutersMutex);
  713. return m_TrustedFamilies.size() > 0 || m_TrustedRouters.size() > 0;
  714. }
  715. /** XXX: if routes are not restricted this dies */
  716. std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRestrictedPeer() const
  717. {
  718. {
  719. std::lock_guard<std::mutex> l(m_FamilyMutex);
  720. std::string fam;
  721. auto sz = m_TrustedFamilies.size();
  722. if(sz > 1)
  723. {
  724. auto it = m_TrustedFamilies.begin ();
  725. std::advance(it, rand() % sz);
  726. fam = *it;
  727. boost::to_lower(fam);
  728. }
  729. else if (sz == 1)
  730. {
  731. fam = m_TrustedFamilies[0];
  732. }
  733. if (fam.size())
  734. return i2p::data::netdb.GetRandomRouterInFamily(fam);
  735. }
  736. {
  737. std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
  738. auto sz = m_TrustedRouters.size();
  739. if (sz)
  740. {
  741. if(sz == 1)
  742. return i2p::data::netdb.FindRouter(m_TrustedRouters[0]);
  743. auto it = m_TrustedRouters.begin();
  744. std::advance(it, rand() % sz);
  745. return i2p::data::netdb.FindRouter(*it);
  746. }
  747. }
  748. return nullptr;
  749. }
  750. bool Transports::IsRestrictedPeer(const i2p::data::IdentHash & ih) const
  751. {
  752. {
  753. std::unique_lock<std::mutex> l(m_TrustedRoutersMutex);
  754. for (const auto & r : m_TrustedRouters )
  755. if ( r == ih ) return true;
  756. }
  757. {
  758. std::unique_lock<std::mutex> l(m_FamilyMutex);
  759. auto ri = i2p::data::netdb.FindRouter(ih);
  760. for (const auto & fam : m_TrustedFamilies)
  761. if(ri->IsFamily(fam)) return true;
  762. }
  763. return false;
  764. }
  765. }
  766. }