Browse Source

[style] clean code

Signed-off-by: R4SAS <r4sas@i2pmail.org>
pull/1879/head
R4SAS 2 years ago
parent
commit
86fc12e395
Signed by: r4sas
GPG Key ID: 66F6C87B98EBCFE2
  1. 2
      libi2pd/Config.cpp
  2. 8
      libi2pd/Destination.cpp
  3. 14
      libi2pd/NTCP2.cpp
  4. 10
      libi2pd/NetDb.cpp
  5. 20
      libi2pd/Profiling.cpp
  6. 8
      libi2pd/Profiling.h
  7. 98
      libi2pd/RouterContext.cpp
  8. 2
      libi2pd/RouterContext.h
  9. 54
      libi2pd/RouterInfo.cpp
  10. 4
      libi2pd/SSU2.h
  11. 58
      libi2pd/SSU2Session.cpp
  12. 4
      libi2pd/SSU2Session.h
  13. 4
      libi2pd/TransportSession.h
  14. 32
      libi2pd/Transports.cpp
  15. 4
      libi2pd/Transports.h
  16. 14
      libi2pd/Tunnel.cpp
  17. 10
      libi2pd/Tunnel.h
  18. 4
      libi2pd/TunnelPool.h

2
libi2pd/Config.cpp

@ -45,7 +45,7 @@ namespace config {
("logclftime", bool_switch()->default_value(false), "Write full CLF-formatted date and time to log (default: disabled, write only time)") ("logclftime", bool_switch()->default_value(false), "Write full CLF-formatted date and time to log (default: disabled, write only time)")
("family", value<std::string>()->default_value(""), "Specify a family, router belongs to") ("family", value<std::string>()->default_value(""), "Specify a family, router belongs to")
("datadir", value<std::string>()->default_value(""), "Path to storage of i2pd data (RI, keys, peer profiles, ...)") ("datadir", value<std::string>()->default_value(""), "Path to storage of i2pd data (RI, keys, peer profiles, ...)")
("host", value<std::string>()->default_value(""), "External IP") ("host", value<std::string>()->default_value(""), "External IP")
("ifname", value<std::string>()->default_value(""), "Network interface to bind to") ("ifname", value<std::string>()->default_value(""), "Network interface to bind to")
("ifname4", value<std::string>()->default_value(""), "Network interface to bind to for ipv4") ("ifname4", value<std::string>()->default_value(""), "Network interface to bind to for ipv4")
("ifname6", value<std::string>()->default_value(""), "Network interface to bind to for ipv6") ("ifname6", value<std::string>()->default_value(""), "Network interface to bind to for ipv6")

8
libi2pd/Destination.cpp

@ -415,7 +415,7 @@ namespace client
{ {
LogPrint (eLogError, "Destination: Database store message is too long ", len); LogPrint (eLogError, "Destination: Database store message is too long ", len);
return; return;
} }
i2p::data::IdentHash key (buf + DATABASE_STORE_KEY_OFFSET); i2p::data::IdentHash key (buf + DATABASE_STORE_KEY_OFFSET);
std::shared_ptr<i2p::data::LeaseSet> leaseSet; std::shared_ptr<i2p::data::LeaseSet> leaseSet;
switch (buf[DATABASE_STORE_TYPE_OFFSET]) switch (buf[DATABASE_STORE_TYPE_OFFSET])
@ -786,7 +786,7 @@ namespace client
LogPrint (eLogWarning, "Destination: LeaseSet request for ", dest.ToBase32 (), " was not sent"); LogPrint (eLogWarning, "Destination: LeaseSet request for ", dest.ToBase32 (), " was not sent");
m_LeaseSetRequests.erase (ret.first); m_LeaseSetRequests.erase (ret.first);
if (requestComplete) requestComplete (nullptr); if (requestComplete) requestComplete (nullptr);
} }
} }
} }
else // duplicate else // duplicate
@ -1173,11 +1173,11 @@ namespace client
}, },
dest, port); dest, port);
while (!done) while (!done)
{ {
std::unique_lock<std::mutex> l(streamRequestCompleteMutex); std::unique_lock<std::mutex> l(streamRequestCompleteMutex);
if (!done) if (!done)
streamRequestComplete.wait (l); streamRequestComplete.wait (l);
} }
return stream; return stream;
} }

14
libi2pd/NTCP2.cpp

@ -693,8 +693,8 @@ namespace transport
SendTerminationAndTerminate (eNTCP2Message3Error); SendTerminationAndTerminate (eNTCP2Message3Error);
return; return;
} }
auto addr = m_RemoteEndpoint.address ().is_v4 () ? ri.GetNTCP2V4Address () : auto addr = m_RemoteEndpoint.address ().is_v4 () ? ri.GetNTCP2V4Address () :
(i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? ri.GetYggdrasilAddress () : ri.GetNTCP2V6Address ()); (i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? ri.GetYggdrasilAddress () : ri.GetNTCP2V6Address ());
if (!addr || memcmp (m_Establisher->m_RemoteStaticKey, addr->s, 32)) if (!addr || memcmp (m_Establisher->m_RemoteStaticKey, addr->s, 32))
{ {
LogPrint (eLogError, "NTCP2: Wrong static key in SessionConfirmed"); LogPrint (eLogError, "NTCP2: Wrong static key in SessionConfirmed");
@ -703,13 +703,13 @@ namespace transport
} }
if (addr->IsPublishedNTCP2 () && m_RemoteEndpoint.address () != addr->host && if (addr->IsPublishedNTCP2 () && m_RemoteEndpoint.address () != addr->host &&
(!m_RemoteEndpoint.address ().is_v6 () || (i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? (!m_RemoteEndpoint.address ().is_v6 () || (i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ?
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data () + 1, addr->host.to_v6 ().to_bytes ().data () + 1, 7) : // from the same yggdrasil subnet memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data () + 1, addr->host.to_v6 ().to_bytes ().data () + 1, 7) : // from the same yggdrasil subnet
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), addr->host.to_v6 ().to_bytes ().data (), 8)))) // temporary address memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), addr->host.to_v6 ().to_bytes ().data (), 8)))) // temporary address
{ {
LogPrint (eLogError, "NTCP2: Host mismatch between published address ", addr->host, " and actual endpoint ", m_RemoteEndpoint.address ()); LogPrint (eLogError, "NTCP2: Host mismatch between published address ", addr->host, " and actual endpoint ", m_RemoteEndpoint.address ());
Terminate (); Terminate ();
return; return;
} }
i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice
// TODO: process options // TODO: process options
@ -884,7 +884,7 @@ namespace transport
switch (blk) switch (blk)
{ {
case eNTCP2BlkDateTime: case eNTCP2BlkDateTime:
{ {
LogPrint (eLogDebug, "NTCP2: Datetime"); LogPrint (eLogDebug, "NTCP2: Datetime");
if (m_IsEstablished) if (m_IsEstablished)
{ {
@ -894,8 +894,8 @@ namespace transport
{ {
LogPrint (eLogWarning, "NTCP2: Established session time difference ", (int)(ts - tsA), " exceeds clock skew"); LogPrint (eLogWarning, "NTCP2: Established session time difference ", (int)(ts - tsA), " exceeds clock skew");
SendTerminationAndTerminate (eNTCP2ClockSkew); SendTerminationAndTerminate (eNTCP2ClockSkew);
} }
} }
break; break;
} }
case eNTCP2BlkOptions: case eNTCP2BlkOptions:

10
libi2pd/NetDb.cpp

@ -430,15 +430,15 @@ namespace data
{ {
auto it = m_RouterInfos.find (ident); auto it = m_RouterInfos.find (ident);
if (it != m_RouterInfos.end ()) if (it != m_RouterInfos.end ())
{ {
it->second->SetUnreachable (unreachable); it->second->SetUnreachable (unreachable);
if (unreachable) if (unreachable)
{ {
auto profile = it->second->GetProfile (); auto profile = it->second->GetProfile ();
if (profile) if (profile)
profile->Unreachable (); profile->Unreachable ();
} }
} }
} }
void NetDb::Reseed () void NetDb::Reseed ()
@ -824,7 +824,7 @@ namespace data
{ {
LogPrint (eLogError, "NetDb: Database store message is too long ", len); LogPrint (eLogError, "NetDb: Database store message is too long ", len);
return; return;
} }
if (!m->from) // unsolicited LS must be received directly if (!m->from) // unsolicited LS must be received directly
{ {
if (storeType == NETDB_STORE_TYPE_LEASESET) // 1 if (storeType == NETDB_STORE_TYPE_LEASESET) // 1

20
libi2pd/Profiling.cpp

@ -136,15 +136,15 @@ namespace data
{ {
UpdateTime (); UpdateTime ();
if (ret > 0) if (ret > 0)
{ {
m_NumTunnelsDeclined++; m_NumTunnelsDeclined++;
m_LastDeclineTime = i2p::util::GetSecondsSinceEpoch (); m_LastDeclineTime = i2p::util::GetSecondsSinceEpoch ();
} }
else else
{ {
m_NumTunnelsAgreed++; m_NumTunnelsAgreed++;
m_LastDeclineTime = 0; m_LastDeclineTime = 0;
} }
} }
void RouterProfile::TunnelNonReplied () void RouterProfile::TunnelNonReplied ()
@ -158,8 +158,8 @@ namespace data
void RouterProfile::Unreachable () void RouterProfile::Unreachable ()
{ {
m_LastUnreachableTime = i2p::util::GetSecondsSinceEpoch (); m_LastUnreachableTime = i2p::util::GetSecondsSinceEpoch ();
} }
bool RouterProfile::IsLowPartcipationRate () const bool RouterProfile::IsLowPartcipationRate () const
{ {
return 4*m_NumTunnelsAgreed < m_NumTunnelsDeclined; // < 20% rate return 4*m_NumTunnelsAgreed < m_NumTunnelsDeclined; // < 20% rate
@ -179,8 +179,8 @@ namespace data
ts + PEER_PROFILE_DECLINED_RECENTLY_INTERVAL < m_LastDeclineTime) ts + PEER_PROFILE_DECLINED_RECENTLY_INTERVAL < m_LastDeclineTime)
m_LastDeclineTime = 0; m_LastDeclineTime = 0;
return (bool)m_LastDeclineTime; return (bool)m_LastDeclineTime;
} }
bool RouterProfile::IsBad () bool RouterProfile::IsBad ()
{ {
if (IsDeclinedRecently () || IsUnreachable ()) return true; if (IsDeclinedRecently () || IsUnreachable ()) return true;
@ -205,8 +205,8 @@ namespace data
ts + PEER_PROFILE_UNREACHABLE_INTERVAL < m_LastUnreachableTime) ts + PEER_PROFILE_UNREACHABLE_INTERVAL < m_LastUnreachableTime)
m_LastUnreachableTime = 0; m_LastUnreachableTime = 0;
return (bool)m_LastUnreachableTime; return (bool)m_LastUnreachableTime;
} }
std::shared_ptr<RouterProfile> GetRouterProfile (const IdentHash& identHash) std::shared_ptr<RouterProfile> GetRouterProfile (const IdentHash& identHash)
{ {
auto profile = std::make_shared<RouterProfile> (); auto profile = std::make_shared<RouterProfile> ();

8
libi2pd/Profiling.h

@ -33,8 +33,8 @@ namespace data
const int PEER_PROFILE_AUTOCLEAN_TIMEOUT = 24 * 3600; // in seconds (1 day) const int PEER_PROFILE_AUTOCLEAN_TIMEOUT = 24 * 3600; // in seconds (1 day)
const int PEER_PROFILE_AUTOCLEAN_VARIANCE = 3 * 3600; // in seconds (3 hours) const int PEER_PROFILE_AUTOCLEAN_VARIANCE = 3 * 3600; // in seconds (3 hours)
const int PEER_PROFILE_DECLINED_RECENTLY_INTERVAL = 150; // in seconds (2.5 minutes) const int PEER_PROFILE_DECLINED_RECENTLY_INTERVAL = 150; // in seconds (2.5 minutes)
const int PEER_PROFILE_UNREACHABLE_INTERVAL = 2*3600; // on seconds (2 hours) const int PEER_PROFILE_UNREACHABLE_INTERVAL = 2*3600; // on seconds (2 hours)
class RouterProfile class RouterProfile
{ {
public: public:
@ -47,12 +47,12 @@ namespace data
bool IsBad (); bool IsBad ();
bool IsUnreachable (); bool IsUnreachable ();
void TunnelBuildResponse (uint8_t ret); void TunnelBuildResponse (uint8_t ret);
void TunnelNonReplied (); void TunnelNonReplied ();
void Unreachable (); void Unreachable ();
private: private:
boost::posix_time::ptime GetTime () const; boost::posix_time::ptime GetTime () const;

98
libi2pd/RouterContext.cpp

@ -88,7 +88,7 @@ namespace i2p
uint8_t caps = 0; uint8_t caps = 0;
if (ipv4) if (ipv4)
{ {
std::string host; std::string host;
if (!nat) if (!nat)
// we have no NAT so set external address from local address // we have no NAT so set external address from local address
i2p::config::GetOption("address4", host); i2p::config::GetOption("address4", host);
@ -99,15 +99,15 @@ namespace i2p
uint16_t ntcp2Port; i2p::config::GetOption ("ntcp2.port", ntcp2Port); uint16_t ntcp2Port; i2p::config::GetOption ("ntcp2.port", ntcp2Port);
if (!ntcp2Port) ntcp2Port = port; if (!ntcp2Port) ntcp2Port = port;
if (ntcp2Published && ntcp2Port) if (ntcp2Published && ntcp2Port)
{ {
boost::asio::ip::address addr; boost::asio::ip::address addr;
if (!host.empty ()) if (!host.empty ())
addr = boost::asio::ip::address::from_string (host); addr = boost::asio::ip::address::from_string (host);
if (!addr.is_v4()) if (!addr.is_v4())
addr = boost::asio::ip::address_v4 (); addr = boost::asio::ip::address_v4 ();
routerInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port); routerInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port);
} }
else else
{ {
// add non-published NTCP2 address // add non-published NTCP2 address
uint8_t addressCaps = i2p::data::RouterInfo::AddressCaps::eV4; uint8_t addressCaps = i2p::data::RouterInfo::AddressCaps::eV4;
@ -120,14 +120,14 @@ namespace i2p
uint16_t ssu2Port; i2p::config::GetOption ("ssu2.port", ssu2Port); uint16_t ssu2Port; i2p::config::GetOption ("ssu2.port", ssu2Port);
if (!ssu2Port) ssu2Port = port; if (!ssu2Port) ssu2Port = port;
if (ssu2Published && ssu2Port) if (ssu2Published && ssu2Port)
{ {
boost::asio::ip::address addr; boost::asio::ip::address addr;
if (!host.empty ()) if (!host.empty ())
addr = boost::asio::ip::address::from_string (host); addr = boost::asio::ip::address::from_string (host);
if (!addr.is_v4()) if (!addr.is_v4())
addr = boost::asio::ip::address_v4 (); addr = boost::asio::ip::address_v4 ();
routerInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port); routerInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port);
} }
else else
{ {
uint8_t addressCaps = i2p::data::RouterInfo::AddressCaps::eV4; uint8_t addressCaps = i2p::data::RouterInfo::AddressCaps::eV4;
@ -138,7 +138,7 @@ namespace i2p
} }
if (ipv6) if (ipv6)
{ {
std::string host; i2p::config::GetOption("address6", host); std::string host; i2p::config::GetOption("address6", host);
if (host.empty () && !ipv4) i2p::config::GetOption("host", host); // use host for ipv6 only if ipv4 is not presented if (host.empty () && !ipv4) i2p::config::GetOption("host", host); // use host for ipv6 only if ipv4 is not presented
if (ntcp2) if (ntcp2)
@ -255,7 +255,7 @@ namespace i2p
break; break;
case eRouterStatusTesting: case eRouterStatusTesting:
m_Error = eRouterErrorNone; m_Error = eRouterErrorNone;
break; break;
default: default:
; ;
} }
@ -277,7 +277,7 @@ namespace i2p
break; break;
case eRouterStatusTesting: case eRouterStatusTesting:
m_ErrorV6 = eRouterErrorNone; m_ErrorV6 = eRouterErrorNone;
break; break;
default: default:
; ;
} }
@ -309,8 +309,8 @@ namespace i2p
if (port) address->port = port; if (port) address->port = port;
address->published = publish; address->published = publish;
memcpy (address->i, m_NTCP2Keys->iv, 16); memcpy (address->i, m_NTCP2Keys->iv, 16);
} }
void RouterContext::PublishNTCP2Address (int port, bool publish, bool v4, bool v6, bool ygg) void RouterContext::PublishNTCP2Address (int port, bool publish, bool v4, bool v6, bool ygg)
{ {
if (!m_NTCP2Keys) return; if (!m_NTCP2Keys) return;
@ -324,8 +324,8 @@ namespace i2p
{ {
PublishNTCP2Address (addr, port, publish); PublishNTCP2Address (addr, port, publish);
updated = true; updated = true;
} }
} }
if (v6) if (v6)
{ {
auto addr = (*addresses)[i2p::data::RouterInfo::eNTCP2V6Idx]; auto addr = (*addresses)[i2p::data::RouterInfo::eNTCP2V6Idx];
@ -333,7 +333,7 @@ namespace i2p
{ {
PublishNTCP2Address (addr, port, publish); PublishNTCP2Address (addr, port, publish);
updated = true; updated = true;
} }
} }
if (ygg) if (ygg)
{ {
@ -342,9 +342,9 @@ namespace i2p
{ {
PublishNTCP2Address (addr, port, publish); PublishNTCP2Address (addr, port, publish);
updated = true; updated = true;
} }
} }
if (updated) if (updated)
UpdateRouterInfo (); UpdateRouterInfo ();
} }
@ -362,8 +362,8 @@ namespace i2p
memcpy (it->i, m_NTCP2Keys->iv, 16); memcpy (it->i, m_NTCP2Keys->iv, 16);
} }
} }
} }
void RouterContext::PublishSSU2Address (int port, bool publish, bool v4, bool v6) void RouterContext::PublishSSU2Address (int port, bool publish, bool v4, bool v6)
{ {
if (!m_SSU2Keys) return; if (!m_SSU2Keys) return;
@ -413,8 +413,8 @@ namespace i2p
it->i = m_SSU2Keys->intro; it->i = m_SSU2Keys->intro;
} }
} }
} }
void RouterContext::UpdateAddress (const boost::asio::ip::address& host) void RouterContext::UpdateAddress (const boost::asio::ip::address& host)
{ {
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
@ -727,11 +727,11 @@ namespace i2p
{ {
auto addr = boost::asio::ip::address::from_string (ntcp2Host); auto addr = boost::asio::ip::address::from_string (ntcp2Host);
if (addr.is_v6 ()) if (addr.is_v6 ())
{ {
m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port); m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port);
added = true; added = true;
} }
} }
} }
if (!added) if (!added)
m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, ntcp2Port, i2p::data::RouterInfo::eV6); m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, ntcp2Port, i2p::data::RouterInfo::eV6);
@ -753,15 +753,15 @@ namespace i2p
{ {
std::string host; i2p::config::GetOption("host", host); std::string host; i2p::config::GetOption("host", host);
if (!host.empty ()) if (!host.empty ())
{ {
auto addr = boost::asio::ip::address::from_string (host); auto addr = boost::asio::ip::address::from_string (host);
if (addr.is_v6 ()) if (addr.is_v6 ())
{ {
m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port); m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port);
added = true; added = true;
} }
} }
} }
if (!added) if (!added)
m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, ssu2Port, i2p::data::RouterInfo::eV6); m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, ssu2Port, i2p::data::RouterInfo::eV6);
} }
@ -819,18 +819,18 @@ namespace i2p
bool added = false; bool added = false;
bool ntcp2Published; i2p::config::GetOption("ntcp2.published", ntcp2Published); bool ntcp2Published; i2p::config::GetOption("ntcp2.published", ntcp2Published);
if (ntcp2Published && ntcp2Port) if (ntcp2Published && ntcp2Port)
{ {
std::string host; i2p::config::GetOption("host", host); std::string host; i2p::config::GetOption("host", host);
if (!host.empty ()) if (!host.empty ())
{ {
auto addr = boost::asio::ip::address::from_string (host); auto addr = boost::asio::ip::address::from_string (host);
if (addr.is_v4 ()) if (addr.is_v4 ())
{ {
m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port); m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, addr, ntcp2Port);
added = true; added = true;
} }
} }
} }
if (!added) if (!added)
m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, ntcp2Port, i2p::data::RouterInfo::eV4); m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, ntcp2Port, i2p::data::RouterInfo::eV4);
} }
@ -849,18 +849,18 @@ namespace i2p
bool ssu2Published; i2p::config::GetOption("ssu2.published", ssu2Published); bool ssu2Published; i2p::config::GetOption("ssu2.published", ssu2Published);
std::string host; i2p::config::GetOption("host", host); std::string host; i2p::config::GetOption("host", host);
if (ssu2Published && ssu2Port) if (ssu2Published && ssu2Port)
{ {
std::string host; i2p::config::GetOption("host", host); std::string host; i2p::config::GetOption("host", host);
if (!host.empty ()) if (!host.empty ())
{ {
auto addr = boost::asio::ip::address::from_string (host); auto addr = boost::asio::ip::address::from_string (host);
if (addr.is_v4 ()) if (addr.is_v4 ())
{ {
m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port); m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, addr, ssu2Port);
added = true; added = true;
} }
} }
} }
if (!added) if (!added)
m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, ssu2Port, i2p::data::RouterInfo::eV4); m_RouterInfo.AddSSU2Address (m_SSU2Keys->staticPublicKey, m_SSU2Keys->intro, ssu2Port, i2p::data::RouterInfo::eV4);
} }
@ -933,7 +933,7 @@ namespace i2p
{ {
addr->host = host; addr->host = host;
UpdateRouterInfo (); UpdateRouterInfo ();
} }
} }
void RouterContext::UpdateStats () void RouterContext::UpdateStats ()
@ -1034,28 +1034,28 @@ namespace i2p
if (IsUnreachable ()) if (IsUnreachable ())
SetReachable (true, true); // we assume reachable until we discover firewall through peer tests SetReachable (true, true); // we assume reachable until we discover firewall through peer tests
bool updated = false; bool updated = false;
// create new NTCP2 keys if required // create new NTCP2 keys if required
bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2); bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2);
bool ygg; i2p::config::GetOption("meshnets.yggdrasil", ygg); bool ygg; i2p::config::GetOption("meshnets.yggdrasil", ygg);
if ((ntcp2 || ygg) && !m_NTCP2Keys) if ((ntcp2 || ygg) && !m_NTCP2Keys)
{ {
NewNTCP2Keys (); NewNTCP2Keys ();
UpdateNTCP2Keys (); UpdateNTCP2Keys ();
updated = true; updated = true;
} }
// create new SSU2 keys if required // create new SSU2 keys if required
bool ssu2; i2p::config::GetOption("ssu2.enabled", ssu2); bool ssu2; i2p::config::GetOption("ssu2.enabled", ssu2);
if (ssu2 && !m_SSU2Keys) if (ssu2 && !m_SSU2Keys)
{ {
NewSSU2Keys (); NewSSU2Keys ();
UpdateSSU2Keys (); UpdateSSU2Keys ();
updated = true; updated = true;
} }
if (updated) if (updated)
UpdateRouterInfo (); UpdateRouterInfo ();
return true; return true;
} }
@ -1087,7 +1087,7 @@ namespace i2p
// TODO: implement // TODO: implement
LogPrint (eLogWarning, "Router: garlic message in garlic clove. Dropped"); LogPrint (eLogWarning, "Router: garlic message in garlic clove. Dropped");
return false; return false;
} }
auto msg = CreateI2NPMessage (typeID, payload, len, msgID); auto msg = CreateI2NPMessage (typeID, payload, len, msgID);
if (!msg) return false; if (!msg) return false;
i2p::HandleI2NPMessage (msg); i2p::HandleI2NPMessage (msg);

2
libi2pd/RouterContext.h

@ -181,7 +181,7 @@ namespace garlic
void SaveKeys (); void SaveKeys ();
uint16_t SelectRandomPort () const; uint16_t SelectRandomPort () const;
void PublishNTCP2Address (std::shared_ptr<i2p::data::RouterInfo::Address> address, int port, bool publish) const; void PublishNTCP2Address (std::shared_ptr<i2p::data::RouterInfo::Address> address, int port, bool publish) const;
bool DecryptECIESTunnelBuildRecord (const uint8_t * encrypted, uint8_t * data, size_t clearTextSize); bool DecryptECIESTunnelBuildRecord (const uint8_t * encrypted, uint8_t * data, size_t clearTextSize);
private: private:

54
libi2pd/RouterInfo.cpp

@ -252,15 +252,15 @@ namespace data
{ {
boost::system::error_code ecode; boost::system::error_code ecode;
address->host = boost::asio::ip::address::from_string (value, ecode); address->host = boost::asio::ip::address::from_string (value, ecode);
if (!ecode && !address->host.is_unspecified ()) if (!ecode && !address->host.is_unspecified ())
{ {
if (!i2p::util::net::IsInReservedRange (address->host) || if (!i2p::util::net::IsInReservedRange (address->host) ||
i2p::util::net::IsYggdrasilAddress (address->host)) i2p::util::net::IsYggdrasilAddress (address->host))
isHost = true; isHost = true;
else else
// we consider such address as invalid // we consider such address as invalid
address->transportStyle = eTransportUnknown; address->transportStyle = eTransportUnknown;
} }
} }
else if (!strcmp (key, "port")) else if (!strcmp (key, "port"))
{ {
@ -648,8 +648,8 @@ namespace data
m_SupportedTransports |= eNTCP2V6; m_SupportedTransports |= eNTCP2V6;
(*m_Addresses)[eNTCP2V6Idx] = addr; (*m_Addresses)[eNTCP2V6Idx] = addr;
} }
} }
void RouterInfo::AddNTCP2Address (const uint8_t * staticKey, const uint8_t * iv, void RouterInfo::AddNTCP2Address (const uint8_t * staticKey, const uint8_t * iv,
const boost::asio::ip::address& host, int port) const boost::asio::ip::address& host, int port)
{ {
@ -688,20 +688,20 @@ namespace data
void RouterInfo::RemoveNTCP2Address (bool v4) void RouterInfo::RemoveNTCP2Address (bool v4)
{ {
if (v4) if (v4)
{ {
if ((*m_Addresses)[eNTCP2V6Idx]) if ((*m_Addresses)[eNTCP2V6Idx])
(*m_Addresses)[eNTCP2V6Idx]->caps &= ~AddressCaps::eV4; (*m_Addresses)[eNTCP2V6Idx]->caps &= ~AddressCaps::eV4;
(*m_Addresses)[eNTCP2V4Idx].reset (); (*m_Addresses)[eNTCP2V4Idx].reset ();
} }
else else
{ {
if ((*m_Addresses)[eNTCP2V4Idx]) if ((*m_Addresses)[eNTCP2V4Idx])
(*m_Addresses)[eNTCP2V4Idx]->caps &= ~AddressCaps::eV6; (*m_Addresses)[eNTCP2V4Idx]->caps &= ~AddressCaps::eV6;
(*m_Addresses)[eNTCP2V6Idx].reset (); (*m_Addresses)[eNTCP2V6Idx].reset ();
} }
UpdateSupportedTransports (); UpdateSupportedTransports ();
} }
void RouterInfo::AddSSU2Address (const uint8_t * staticKey, const uint8_t * introKey, int port, uint8_t caps) void RouterInfo::AddSSU2Address (const uint8_t * staticKey, const uint8_t * introKey, int port, uint8_t caps)
{ {
auto addr = std::make_shared<Address>(); auto addr = std::make_shared<Address>();
@ -756,20 +756,20 @@ namespace data
void RouterInfo::RemoveSSU2Address (bool v4) void RouterInfo::RemoveSSU2Address (bool v4)
{ {
if (v4) if (v4)
{ {
if ((*m_Addresses)[eSSU2V6Idx]) if ((*m_Addresses)[eSSU2V6Idx])
(*m_Addresses)[eSSU2V6Idx]->caps &= ~AddressCaps::eV4; (*m_Addresses)[eSSU2V6Idx]->caps &= ~AddressCaps::eV4;
(*m_Addresses)[eSSU2V4Idx].reset (); (*m_Addresses)[eSSU2V4Idx].reset ();
} }
else else
{ {
if ((*m_Addresses)[eSSU2V4Idx]) if ((*m_Addresses)[eSSU2V4Idx])
(*m_Addresses)[eSSU2V4Idx]->caps &= ~AddressCaps::eV6; (*m_Addresses)[eSSU2V4Idx]->caps &= ~AddressCaps::eV6;
(*m_Addresses)[eSSU2V6Idx].reset (); (*m_Addresses)[eSSU2V6Idx].reset ();
} }
UpdateSupportedTransports (); UpdateSupportedTransports ();
} }
bool RouterInfo::IsNTCP2 (bool v4only) const bool RouterInfo::IsNTCP2 (bool v4only) const
{ {
if (v4only) if (v4only)
@ -919,7 +919,7 @@ namespace data
{ {
return (*GetAddresses ())[eNTCP2V6Idx]; return (*GetAddresses ())[eNTCP2V6Idx];
} }
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetPublishedNTCP2V4Address () const std::shared_ptr<const RouterInfo::Address> RouterInfo::GetPublishedNTCP2V4Address () const
{ {
auto addr = (*GetAddresses ())[eNTCP2V4Idx]; auto addr = (*GetAddresses ())[eNTCP2V4Idx];
@ -1032,13 +1032,13 @@ namespace data
std::shared_ptr<RouterInfo::Address> RouterInfo::NewAddress () const std::shared_ptr<RouterInfo::Address> RouterInfo::NewAddress () const
{ {
return netdb.NewRouterInfoAddress (); return netdb.NewRouterInfoAddress ();
} }
boost::shared_ptr<RouterInfo::Addresses> RouterInfo::NewAddresses () const boost::shared_ptr<RouterInfo::Addresses> RouterInfo::NewAddresses () const
{ {
return netdb.NewRouterInfoAddresses (); return netdb.NewRouterInfoAddresses ();
} }
void RouterInfo::RefreshTimestamp () void RouterInfo::RefreshTimestamp ()
{ {
m_Timestamp = i2p::util::GetMillisecondsSinceEpoch (); m_Timestamp = i2p::util::GetMillisecondsSinceEpoch ();
@ -1324,12 +1324,12 @@ namespace data
{ {
return std::make_shared<Address> (); return std::make_shared<Address> ();
} }
boost::shared_ptr<RouterInfo::Addresses> LocalRouterInfo::NewAddresses () const boost::shared_ptr<RouterInfo::Addresses> LocalRouterInfo::NewAddresses () const
{ {
return boost::make_shared<Addresses> (); return boost::make_shared<Addresses> ();
} }
bool LocalRouterInfo::AddSSU2Introducer (const Introducer& introducer, bool v4) bool LocalRouterInfo::AddSSU2Introducer (const Introducer& introducer, bool v4)
{ {
auto addresses = GetAddresses (); auto addresses = GetAddresses ();

4
libi2pd/SSU2.h

@ -100,7 +100,7 @@ namespace transport
i2p::util::MemoryPool<SSU2SentPacket>& GetSentPacketsPool () { return m_SentPacketsPool; }; i2p::util::MemoryPool<SSU2SentPacket>& GetSentPacketsPool () { return m_SentPacketsPool; };
i2p::util::MemoryPool<SSU2IncompleteMessage>& GetIncompleteMessagesPool () { return m_IncompleteMessagesPool; }; i2p::util::MemoryPool<SSU2IncompleteMessage>& GetIncompleteMessagesPool () { return m_IncompleteMessagesPool; };
i2p::util::MemoryPool<SSU2IncompleteMessage::Fragment>& GetFragmentsPool () { return m_FragmentsPool; }; i2p::util::MemoryPool<SSU2IncompleteMessage::Fragment>& GetFragmentsPool () { return m_FragmentsPool; };
private: private:
boost::asio::ip::udp::socket& OpenSocket (const boost::asio::ip::udp::endpoint& localEndpoint); boost::asio::ip::udp::socket& OpenSocket (const boost::asio::ip::udp::endpoint& localEndpoint);
@ -116,7 +116,7 @@ namespace transport
void ScheduleCleanup (); void ScheduleCleanup ();
void HandleCleanupTimer (const boost::system::error_code& ecode); void HandleCleanupTimer (const boost::system::error_code& ecode);
void ScheduleResend (bool more); void ScheduleResend (bool more);
void HandleResendTimer (const boost::system::error_code& ecode); void HandleResendTimer (const boost::system::error_code& ecode);

58
libi2pd/SSU2Session.cpp

@ -36,34 +36,34 @@ namespace transport
{ {
bool isLast = false; bool isLast = false;
while (outOfSequenceFragments) while (outOfSequenceFragments)
{ {
if (outOfSequenceFragments->fragmentNum == nextFragmentNum) if (outOfSequenceFragments->fragmentNum == nextFragmentNum)
{ {
AttachNextFragment (outOfSequenceFragments->buf, outOfSequenceFragments->len); AttachNextFragment (outOfSequenceFragments->buf, outOfSequenceFragments->len);
isLast = outOfSequenceFragments->isLast; isLast = outOfSequenceFragments->isLast;
if (isLast) if (isLast)
outOfSequenceFragments = nullptr; outOfSequenceFragments = nullptr;
else else
outOfSequenceFragments = outOfSequenceFragments->next; outOfSequenceFragments = outOfSequenceFragments->next;
} }
else else
break; break;
} }
return isLast; return isLast;
} }
void SSU2IncompleteMessage::AddOutOfSequenceFragment (std::shared_ptr<SSU2IncompleteMessage::Fragment> fragment) void SSU2IncompleteMessage::AddOutOfSequenceFragment (std::shared_ptr<SSU2IncompleteMessage::Fragment> fragment)
{ {
if (!fragment || !fragment->fragmentNum) return; // fragment 0 not allowed if (!fragment || !fragment->fragmentNum) return; // fragment 0 not allowed
if (fragment->fragmentNum < nextFragmentNum) return; // already processed if (fragment->fragmentNum < nextFragmentNum) return; // already processed
if (!outOfSequenceFragments) if (!outOfSequenceFragments)
outOfSequenceFragments = fragment; outOfSequenceFragments = fragment;
else else
{ {
auto frag = outOfSequenceFragments; auto frag = outOfSequenceFragments;
std::shared_ptr<Fragment> prev; std::shared_ptr<Fragment> prev;
do do
{ {
if (fragment->fragmentNum < frag->fragmentNum) break; // found if (fragment->fragmentNum < frag->fragmentNum) break; // found
if (fragment->fragmentNum == frag->fragmentNum) return; // duplicate if (fragment->fragmentNum == frag->fragmentNum) return; // duplicate
prev = frag; frag = frag->next; prev = frag; frag = frag->next;
@ -71,13 +71,13 @@ namespace transport
while (frag); while (frag);
fragment->next = frag; fragment->next = frag;
if (prev) if (prev)
prev->next = fragment; prev->next = fragment;
else else
outOfSequenceFragments = fragment; outOfSequenceFragments = fragment;
} }
lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch (); lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch ();
} }
SSU2Session::SSU2Session (SSU2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter, SSU2Session::SSU2Session (SSU2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter,
std::shared_ptr<const i2p::data::RouterInfo::Address> addr): std::shared_ptr<const i2p::data::RouterInfo::Address> addr):
TransportSession (in_RemoteRouter, SSU2_CONNECT_TIMEOUT), TransportSession (in_RemoteRouter, SSU2_CONNECT_TIMEOUT),
@ -1041,20 +1041,20 @@ namespace transport
LogPrint (eLogError, "SSU2: SessionConfirmed malformed RouterInfo block"); LogPrint (eLogError, "SSU2: SessionConfirmed malformed RouterInfo block");
return false; return false;
} }
m_Address = m_RemoteEndpoint.address ().is_v6 () ? ri->GetSSU2V6Address () : ri->GetSSU2V4Address (); m_Address = m_RemoteEndpoint.address ().is_v6 () ? ri->GetSSU2V6Address () : ri->GetSSU2V4Address ();
if (!m_Address || memcmp (S, m_Address->s, 32)) if (!m_Address || memcmp (S, m_Address->s, 32))
{ {
LogPrint (eLogError, "SSU2: Wrong static key in SessionConfirmed from ", i2p::data::GetIdentHashAbbreviation (ri->GetIdentHash ())); LogPrint (eLogError, "SSU2: Wrong static key in SessionConfirmed from ", i2p::data::GetIdentHashAbbreviation (ri->GetIdentHash ()));
return false; return false;
} }
if (m_Address->published && m_RemoteEndpoint.address () != m_Address->host && if (m_Address->published && m_RemoteEndpoint.address () != m_Address->host &&
(!m_RemoteEndpoint.address ().is_v6 () || (!m_RemoteEndpoint.address ().is_v6 () ||
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), m_Address->host.to_v6 ().to_bytes ().data (), 8))) // temporary address memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), m_Address->host.to_v6 ().to_bytes ().data (), 8))) // temporary address
{ {
LogPrint (eLogError, "SSU2: Host mismatch between published address ", m_Address->host, LogPrint (eLogError, "SSU2: Host mismatch between published address ", m_Address->host,
" and actual endpoint ", m_RemoteEndpoint.address (), " from ", i2p::data::GetIdentHashAbbreviation (ri->GetIdentHash ())); " and actual endpoint ", m_RemoteEndpoint.address (), " from ", i2p::data::GetIdentHashAbbreviation (ri->GetIdentHash ()));
return false; return false;
} }
// update RouterInfo in netdb // update RouterInfo in netdb
ri = i2p::data::netdb.AddRouterInfo (ri->GetBuffer (), ri->GetBufferLen ()); // ri points to one from netdb now ri = i2p::data::netdb.AddRouterInfo (ri->GetBuffer (), ri->GetBufferLen ()); // ri points to one from netdb now
if (!ri) if (!ri)
@ -1617,7 +1617,7 @@ namespace transport
{ {
case eSSU2SessionStateSessionRequestReceived: case eSSU2SessionStateSessionRequestReceived:
case eSSU2SessionStateTokenRequestReceived: case eSSU2SessionStateTokenRequestReceived:
case eSSU2SessionStateEstablished: case eSSU2SessionStateEstablished:
if (std::abs (offset) > SSU2_CLOCK_SKEW) if (std::abs (offset) > SSU2_CLOCK_SKEW)
m_TerminationReason = eSSU2TerminationReasonClockSkew; m_TerminationReason = eSSU2TerminationReasonClockSkew;
break; break;
@ -1804,7 +1804,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: Invalid follow-on fragment num ", fragmentNum); LogPrint (eLogWarning, "SSU2: Invalid follow-on fragment num ", fragmentNum);
return; return;
} }
bool isLast = buf[0] & 0x01; bool isLast = buf[0] & 0x01;
uint32_t msgID; memcpy (&msgID, buf + 1, 4); uint32_t msgID; memcpy (&msgID, buf + 1, 4);
auto it = m_IncompleteMessages.find (msgID); auto it = m_IncompleteMessages.find (msgID);
@ -2307,21 +2307,21 @@ namespace transport
} }
void SSU2Session::HandleI2NPMsg (std::shared_ptr<I2NPMessage>&& msg) void SSU2Session::HandleI2NPMsg (std::shared_ptr<I2NPMessage>&& msg)
{ {
if (!msg) return; if (!msg) return;
uint32_t msgID = msg->GetMsgID (); uint32_t msgID = msg->GetMsgID ();
if (!msg->IsExpired ()) if (!msg->IsExpired ())
{ {
// m_LastActivityTimestamp is updated in ProcessData before // m_LastActivityTimestamp is updated in ProcessData before
if (m_ReceivedI2NPMsgIDs.emplace (msgID, (uint32_t)m_LastActivityTimestamp).second) if (m_ReceivedI2NPMsgIDs.emplace (msgID, (uint32_t)m_LastActivityTimestamp).second)
m_Handler.PutNextMessage (std::move (msg)); m_Handler.PutNextMessage (std::move (msg));
else else
LogPrint (eLogDebug, "SSU2: Message ", msgID, " already received"); LogPrint (eLogDebug, "SSU2: Message ", msgID, " already received");
} }
else else
LogPrint (eLogDebug, "SSU2: Message ", msgID, " expired"); LogPrint (eLogDebug, "SSU2: Message ", msgID, " expired");
} }
bool SSU2Session::ExtractEndpoint (const uint8_t * buf, size_t size, boost::asio::ip::udp::endpoint& ep) bool SSU2Session::ExtractEndpoint (const uint8_t * buf, size_t size, boost::asio::ip::udp::endpoint& ep)
{ {
if (size < 2) return false; if (size < 2) return false;
@ -2473,7 +2473,7 @@ namespace transport
acnt++; acnt++;
if (acnt >= SSU2_MAX_NUM_ACK_PACKETS) if (acnt >= SSU2_MAX_NUM_ACK_PACKETS)
break; break;
else else
it++; it++;
} }
// ranges // ranges
@ -2499,8 +2499,8 @@ namespace transport
numRanges++; numRanges++;
} }
} }
int numPackets = acnt + numRanges*SSU2_MAX_NUM_ACNT; int numPackets = acnt + numRanges*SSU2_MAX_NUM_ACNT;
while (it != m_OutOfSequencePackets.rend () && while (it != m_OutOfSequencePackets.rend () &&
numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS) numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS)
{ {
if (lastNum - (*it) > SSU2_MAX_NUM_ACNT) if (lastNum - (*it) > SSU2_MAX_NUM_ACNT)
@ -2786,7 +2786,7 @@ namespace transport
while (it != m_OutOfSequencePackets.end ()) while (it != m_OutOfSequencePackets.end ())
{ {
if (*it == packetNum + 1) if (*it == packetNum + 1)
{ {
packetNum++; packetNum++;
it++; it++;
} }
@ -2794,7 +2794,7 @@ namespace transport
break; break;
} }
m_OutOfSequencePackets.erase (m_OutOfSequencePackets.begin (), it); m_OutOfSequencePackets.erase (m_OutOfSequencePackets.begin (), it);
} }
} }
m_ReceivePacketNum = packetNum; m_ReceivePacketNum = packetNum;
} }
@ -2881,7 +2881,7 @@ namespace transport
if (!m_OutOfSequencePackets.empty ()) if (!m_OutOfSequencePackets.empty ())
{ {
int ranges = 0; int ranges = 0;
while (ranges < 8 && !m_OutOfSequencePackets.empty () && while (ranges < 8 && !m_OutOfSequencePackets.empty () &&
(m_OutOfSequencePackets.size () > 2*SSU2_MAX_NUM_ACK_RANGES || (m_OutOfSequencePackets.size () > 2*SSU2_MAX_NUM_ACK_RANGES ||
*m_OutOfSequencePackets.rbegin () > m_ReceivePacketNum + SSU2_MAX_NUM_ACK_PACKETS)) *m_OutOfSequencePackets.rbegin () > m_ReceivePacketNum + SSU2_MAX_NUM_ACK_PACKETS))
{ {
@ -2895,10 +2895,10 @@ namespace transport
ranges++; ranges++;
} }
else else
{ {
LogPrint (eLogError, "SSU2: Out of sequence packet ", packet, " is less than last received ", m_ReceivePacketNum); LogPrint (eLogError, "SSU2: Out of sequence packet ", packet, " is less than last received ", m_ReceivePacketNum);
break; break;
} }
} }
if (m_OutOfSequencePackets.size () > 255*4) if (m_OutOfSequencePackets.size () > 255*4)
{ {

4
libi2pd/SSU2Session.h

@ -52,7 +52,7 @@ namespace transport
const int SSU2_MAX_NUM_ACK_PACKETS = 510; // 2*255 ack + nack const int SSU2_MAX_NUM_ACK_PACKETS = 510; // 2*255 ack + nack
const int SSU2_MAX_NUM_ACK_RANGES = 32; // to send const int SSU2_MAX_NUM_ACK_RANGES = 32; // to send
const uint8_t SSU2_MAX_NUM_FRAGMENTS = 64; const uint8_t SSU2_MAX_NUM_FRAGMENTS = 64;
// flags // flags
const uint8_t SSU2_FLAG_IMMEDIATE_ACK_REQUESTED = 0x01; const uint8_t SSU2_FLAG_IMMEDIATE_ACK_REQUESTED = 0x01;
@ -317,7 +317,7 @@ namespace transport
void HandleRelayResponse (const uint8_t * buf, size_t len); void HandleRelayResponse (const uint8_t * buf, size_t len);
void HandlePeerTest (const uint8_t * buf, size_t len); void HandlePeerTest (const uint8_t * buf, size_t len);
void HandleI2NPMsg (std::shared_ptr<I2NPMessage>&& msg); void HandleI2NPMsg (std::shared_ptr<I2NPMessage>&& msg);
size_t CreateAddressBlock (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& ep); size_t CreateAddressBlock (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& ep);
size_t CreateRouterInfoBlock (uint8_t * buf, size_t len, std::shared_ptr<const i2p::data::RouterInfo> r); size_t CreateRouterInfoBlock (uint8_t * buf, size_t len, std::shared_ptr<const i2p::data::RouterInfo> r);
size_t CreateAckBlock (uint8_t * buf, size_t len); size_t CreateAckBlock (uint8_t * buf, size_t len);

4
libi2pd/TransportSession.h

@ -107,9 +107,9 @@ namespace transport
int GetTerminationTimeout () const { return m_TerminationTimeout; }; int GetTerminationTimeout () const { return m_TerminationTimeout; };
void SetTerminationTimeout (int terminationTimeout) { m_TerminationTimeout = terminationTimeout; }; void SetTerminationTimeout (int terminationTimeout) { m_TerminationTimeout = terminationTimeout; };
bool IsTerminationTimeoutExpired (uint64_t ts) const bool IsTerminationTimeoutExpired (uint64_t ts) const
{ {
return ts >= m_LastActivityTimestamp + GetTerminationTimeout () || return ts >= m_LastActivityTimestamp + GetTerminationTimeout () ||
ts + GetTerminationTimeout () < m_LastActivityTimestamp; ts + GetTerminationTimeout () < m_LastActivityTimestamp;
}; };
uint32_t GetCreationTime () const { return m_CreationTime; }; uint32_t GetCreationTime () const { return m_CreationTime; };

32
libi2pd/Transports.cpp

@ -831,12 +831,12 @@ namespace transport
std::advance (it, inds[0]); std::advance (it, inds[0]);
// try random peer // try random peer
if (it != m_Peers.end () && filter (it->second)) if (it != m_Peers.end () && filter (it->second))
{ {
ident = it->first; ident = it->first;
found = true; found = true;
} }
else else
{ {
// try some peers around // try some peers around
auto it1 = m_Peers.begin (); auto it1 = m_Peers.begin ();
if (inds[0]) if (inds[0])
@ -859,48 +859,48 @@ namespace transport
while (it != it2 && it != m_Peers.end ()) while (it != it2 && it != m_Peers.end ())
{ {
if (filter (it->second)) if (filter (it->second))
{ {
ident = it->first; ident = it->first;
found = true; found = true;
break; break;
} }
it++; it++;
} }
if (!found) if (!found)
{ {
// still not found, try from the beginning // still not found, try from the beginning
it = m_Peers.begin (); it = m_Peers.begin ();
while (it != it1 && it != m_Peers.end ()) while (it != it1 && it != m_Peers.end ())
{ {
if (filter (it->second)) if (filter (it->second))
{ {
ident = it->first; ident = it->first;
found = true; found = true;
break; break;
} }
it++; it++;
} }
if (!found) if (!found)
{ {
// still not found, try to the beginning // still not found, try to the beginning
it = it2; it = it2;
while (it != m_Peers.end ()) while (it != m_Peers.end ())
{ {
if (filter (it->second)) if (filter (it->second))
{ {
ident = it->first; ident = it->first;
found = true; found = true;
break; break;
} }
it++; it++;
} }
} }
} }
} }
} }
return found ? i2p::data::netdb.FindRouter (ident) : nullptr; return found ? i2p::data::netdb.FindRouter (ident) : nullptr;
} }
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRandomPeer (bool isHighBandwidth) const std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRandomPeer (bool isHighBandwidth) const
{ {
return GetRandomPeer ( return GetRandomPeer (

4
libi2pd/Transports.h

@ -94,7 +94,7 @@ namespace transport
router = r; router = r;
if (router) if (router)
isHighBandwidth = router->IsHighBandwidth (); isHighBandwidth = router->IsHighBandwidth ();
} }
}; };
const uint64_t SESSION_CREATION_TIMEOUT = 15; // in seconds const uint64_t SESSION_CREATION_TIMEOUT = 15; // in seconds
@ -176,7 +176,7 @@ namespace transport
template<typename Filter> template<typename Filter>
std::shared_ptr<const i2p::data::RouterInfo> GetRandomPeer (Filter filter) const; std::shared_ptr<const i2p::data::RouterInfo> GetRandomPeer (Filter filter) const;
private: private:
volatile bool m_IsOnline; volatile bool m_IsOnline;

14
libi2pd/Tunnel.cpp

@ -334,7 +334,7 @@ namespace tunnel
Tunnels::Tunnels (): m_IsRunning (false), m_Thread (nullptr), Tunnels::Tunnels (): m_IsRunning (false), m_Thread (nullptr),
m_TotalNumSuccesiveTunnelCreations (0), m_TotalNumFailedTunnelCreations (0), // for normal avarage m_TotalNumSuccesiveTunnelCreations (0), m_TotalNumFailedTunnelCreations (0), // for normal avarage
m_TunnelCreationSuccessRate (TCSR_START_VALUE), m_TunnelCreationAttemptsNum(0) m_TunnelCreationSuccessRate (TCSR_START_VALUE), m_TunnelCreationAttemptsNum(0)
{ {
} }
Tunnels::~Tunnels () Tunnels::~Tunnels ()
@ -439,11 +439,11 @@ namespace tunnel
if (m_Tunnels.emplace (tunnel->GetTunnelID (), tunnel).second) if (m_Tunnels.emplace (tunnel->GetTunnelID (), tunnel).second)
m_TransitTunnels.push_back (tunnel); m_TransitTunnels.push_back (tunnel);
else else
{ {
LogPrint (eLogError, "Tunnel: Tunnel with id ", tunnel->GetTunnelID (), " already exists"); LogPrint (eLogError, "Tunnel: Tunnel with id ", tunnel->GetTunnelID (), " already exists");
return false; return false;
} }
return true; return true;
} }
void Tunnels::Start () void Tunnels::Start ()
@ -538,13 +538,13 @@ namespace tunnel
{ {
uint64_t ts = i2p::util::GetSecondsSinceEpoch (); uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
if (ts - lastTs >= TUNNEL_MANAGE_INTERVAL || // manage tunnels every 15 seconds if (ts - lastTs >= TUNNEL_MANAGE_INTERVAL || // manage tunnels every 15 seconds
ts + TUNNEL_MANAGE_INTERVAL < lastTs) ts + TUNNEL_MANAGE_INTERVAL < lastTs)
{ {
ManageTunnels (ts); ManageTunnels (ts);
lastTs = ts; lastTs = ts;
} }
if (ts - lastPoolsTs >= TUNNEL_POOLS_MANAGE_INTERVAL || // manage pools every 5 secondsts if (ts - lastPoolsTs >= TUNNEL_POOLS_MANAGE_INTERVAL || // manage pools every 5 secondsts
ts + TUNNEL_POOLS_MANAGE_INTERVAL < lastPoolsTs) ts + TUNNEL_POOLS_MANAGE_INTERVAL < lastPoolsTs)
{ {
ManageTunnelPools (ts); ManageTunnelPools (ts);
lastPoolsTs = ts; lastPoolsTs = ts;

10
libi2pd/Tunnel.h

@ -254,7 +254,7 @@ namespace tunnel
std::shared_ptr<ZeroHopsOutboundTunnel> CreateZeroHopsOutboundTunnel (std::shared_ptr<TunnelPool> pool); std::shared_ptr<ZeroHopsOutboundTunnel> CreateZeroHopsOutboundTunnel (std::shared_ptr<TunnelPool> pool);
// Calculating of tunnel creation success rate // Calculating of tunnel creation success rate
void SuccesiveTunnelCreation() void SuccesiveTunnelCreation()
{ {
// total TCSR // total TCSR
m_TotalNumSuccesiveTunnelCreations++; m_TotalNumSuccesiveTunnelCreations++;
@ -263,14 +263,14 @@ namespace tunnel
m_TunnelCreationSuccessRate = alpha * 1 + (1 - alpha) * m_TunnelCreationSuccessRate; m_TunnelCreationSuccessRate = alpha * 1 + (1 - alpha) * m_TunnelCreationSuccessRate;
} }
void FailedTunnelCreation() void FailedTunnelCreation()
{ {
m_TotalNumFailedTunnelCreations++; m_TotalNumFailedTunnelCreations++;
double alpha = TCSR_SMOOTHING_CONSTANT + (1 - TCSR_SMOOTHING_CONSTANT)/++m_TunnelCreationAttemptsNum; double alpha = TCSR_SMOOTHING_CONSTANT + (1 - TCSR_SMOOTHING_CONSTANT)/++m_TunnelCreationAttemptsNum;
m_TunnelCreationSuccessRate = alpha * 0 + (1 - alpha) * m_TunnelCreationSuccessRate; m_TunnelCreationSuccessRate = alpha * 0 + (1 - alpha) * m_TunnelCreationSuccessRate;
} }
private: private:
bool m_IsRunning; bool m_IsRunning;
@ -288,7 +288,7 @@ namespace tunnel
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE> > m_I2NPTunnelEndpointMessagesMemoryPool; i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE> > m_I2NPTunnelEndpointMessagesMemoryPool;
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_MESSAGE_SIZE> > m_I2NPTunnelMessagesMemoryPool; i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_MESSAGE_SIZE> > m_I2NPTunnelMessagesMemoryPool;
// count of tunnels for total TCSR algorithm // count of tunnels for total TCSR algorithm
int m_TotalNumSuccesiveTunnelCreations, m_TotalNumFailedTunnelCreations; int m_TotalNumSuccesiveTunnelCreations, m_TotalNumFailedTunnelCreations;
double m_TunnelCreationSuccessRate; double m_TunnelCreationSuccessRate;
int m_TunnelCreationAttemptsNum; int m_TunnelCreationAttemptsNum;

4
libi2pd/TunnelPool.h

@ -56,7 +56,7 @@ namespace tunnel
class TunnelPool: public std::enable_shared_from_this<TunnelPool> // per local destination class TunnelPool: public std::enable_shared_from_this<TunnelPool> // per local destination
{ {
typedef std::function<std::shared_ptr<const i2p::data::RouterInfo>(std::shared_ptr<const i2p::data::RouterInfo>, bool)> SelectHopFunc; typedef std::function<std::shared_ptr<const i2p::data::RouterInfo>(std::shared_ptr<const i2p::data::RouterInfo>, bool)> SelectHopFunc;
public: public:
TunnelPool (int numInboundHops, int numOutboundHops, int numInboundTunnels, TunnelPool (int numInboundHops, int numOutboundHops, int numInboundTunnels,
@ -114,7 +114,7 @@ namespace tunnel
// for overriding tunnel peer selection // for overriding tunnel peer selection
std::shared_ptr<const i2p::data::RouterInfo> SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop, bool reverse) const; std::shared_ptr<const i2p::data::RouterInfo> SelectNextHop (std::shared_ptr<const i2p::data::RouterInfo> prevHop, bool reverse) const;
bool StandardSelectPeers(Path & path, int numHops, bool inbound, SelectHopFunc nextHop); bool StandardSelectPeers(Path & path, int numHops, bool inbound, SelectHopFunc nextHop);
private: private:
void TestTunnels (); void TestTunnels ();

Loading…
Cancel
Save