Browse Source

[style] clean trailing spaces and tabs

Signed-off-by: R4SAS <r4sas@i2pmail.org>
pull/1835/head
R4SAS 2 years ago
parent
commit
503f522cc3
Signed by: r4sas
GPG Key ID: 66F6C87B98EBCFE2
  1. 4
      daemon/Daemon.cpp
  2. 22
      libi2pd/Destination.cpp
  3. 4
      libi2pd/Destination.h
  4. 4
      libi2pd/Identity.cpp
  5. 8
      libi2pd/LeaseSet.cpp
  6. 42
      libi2pd/NTCP2.cpp
  7. 8
      libi2pd/NetDb.cpp
  8. 8
      libi2pd/NetDb.hpp
  9. 52
      libi2pd/RouterContext.cpp
  10. 48
      libi2pd/RouterInfo.cpp
  11. 2
      libi2pd/RouterInfo.h
  12. 16
      libi2pd/SSU2.cpp
  13. 6
      libi2pd/SSU2.h
  14. 52
      libi2pd/SSU2Session.cpp
  15. 22
      libi2pd/Streaming.cpp
  16. 4
      libi2pd/Streaming.h
  17. 2
      libi2pd/TransitTunnel.cpp
  18. 2
      libi2pd/TransportSession.h
  19. 4
      libi2pd/Transports.cpp
  20. 2
      libi2pd/Tunnel.h
  21. 10
      libi2pd/TunnelPool.cpp
  22. 20
      libi2pd_client/AddressBook.cpp
  23. 2
      libi2pd_client/UDPTunnel.cpp
  24. 2
      libi2pd_client/UDPTunnel.h

4
daemon/Daemon.cpp

@ -166,7 +166,7 @@ namespace util
i2p::transport::InitTransports (); i2p::transport::InitTransports ();
bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill); bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill);
if (isFloodfill) if (isFloodfill)
{ {
LogPrint(eLogInfo, "Daemon: Router configured as floodfill"); LogPrint(eLogInfo, "Daemon: Router configured as floodfill");
i2p::context.SetFloodfill (true); i2p::context.SetFloodfill (true);
@ -180,7 +180,7 @@ namespace util
if (isFloodfill && i2p::config::IsDefault ("limits.transittunnels")) if (isFloodfill && i2p::config::IsDefault ("limits.transittunnels"))
transitTunnels *= 2; // double default number of transit tunnels for floodfill transitTunnels *= 2; // double default number of transit tunnels for floodfill
SetMaxNumTransitTunnels (transitTunnels); SetMaxNumTransitTunnels (transitTunnels);
/* this section also honors 'floodfill' flag, if set above */ /* this section also honors 'floodfill' flag, if set above */
std::string bandwidth; i2p::config::GetOption("bandwidth", bandwidth); std::string bandwidth; i2p::config::GetOption("bandwidth", bandwidth);
if (bandwidth.length () > 0) if (bandwidth.length () > 0)

22
libi2pd/Destination.cpp

@ -1096,13 +1096,13 @@ namespace client
} }
auto leaseSet = FindLeaseSet (dest); auto leaseSet = FindLeaseSet (dest);
if (leaseSet) if (leaseSet)
{ {
auto stream = CreateStream (leaseSet, port); auto stream = CreateStream (leaseSet, port);
GetService ().post ([streamRequestComplete, stream]() GetService ().post ([streamRequestComplete, stream]()
{ {
streamRequestComplete(stream); streamRequestComplete(stream);
}); });
} }
else else
{ {
auto s = GetSharedFromThis (); auto s = GetSharedFromThis ();
@ -1135,8 +1135,8 @@ namespace client
}); });
} }
template<typename Dest> template<typename Dest>
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStreamSync (const Dest& dest, int port) std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStreamSync (const Dest& dest, int port)
{ {
std::shared_ptr<i2p::stream::Stream> stream; std::shared_ptr<i2p::stream::Stream> stream;
std::condition_variable streamRequestComplete; std::condition_variable streamRequestComplete;
@ -1152,18 +1152,18 @@ namespace client
dest, port); dest, port);
streamRequestComplete.wait (l); streamRequestComplete.wait (l);
return stream; return stream;
} }
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (const i2p::data::IdentHash& dest, int port) std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (const i2p::data::IdentHash& dest, int port)
{ {
return CreateStreamSync (dest, port); return CreateStreamSync (dest, port);
} }
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, int port) std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::BlindedPublicKey> dest, int port)
{ {
return CreateStreamSync (dest, port); return CreateStreamSync (dest, port);
} }
std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port) std::shared_ptr<i2p::stream::Stream> ClientDestination::CreateStream (std::shared_ptr<const i2p::data::LeaseSet> remote, int port)
{ {
if (m_StreamingDestination) if (m_StreamingDestination)

4
libi2pd/Destination.h

@ -284,9 +284,9 @@ namespace client
void PersistTemporaryKeys (EncryptionKey * keys, bool isSingleKey); void PersistTemporaryKeys (EncryptionKey * keys, bool isSingleKey);
void ReadAuthKey (const std::string& group, const std::map<std::string, std::string> * params); void ReadAuthKey (const std::string& group, const std::map<std::string, std::string> * params);
template<typename Dest> template<typename Dest>
std::shared_ptr<i2p::stream::Stream> CreateStreamSync (const Dest& dest, int port); std::shared_ptr<i2p::stream::Stream> CreateStreamSync (const Dest& dest, int port);
private: private:
i2p::data::PrivateKeys m_Keys; i2p::data::PrivateKeys m_Keys;

4
libi2pd/Identity.cpp

@ -64,7 +64,7 @@ namespace data
else else
for (int i = 0; i < 8; i++) // 256 bytes for (int i = 0; i < 8; i++) // 256 bytes
memcpy (m_StandardIdentity.publicKey + 32*i, randomPaddingBlock, 32); memcpy (m_StandardIdentity.publicKey + 32*i, randomPaddingBlock, 32);
} }
if (type != SIGNING_KEY_TYPE_DSA_SHA1) if (type != SIGNING_KEY_TYPE_DSA_SHA1)
{ {
size_t excessLen = 0; size_t excessLen = 0;
@ -717,7 +717,7 @@ namespace data
uint8_t publicKey[256]; uint8_t publicKey[256];
if (isDestination) if (isDestination)
RAND_bytes (keys.m_PrivateKey, 256); RAND_bytes (keys.m_PrivateKey, 256);
else else
GenerateCryptoKeyPair (cryptoType, keys.m_PrivateKey, publicKey); GenerateCryptoKeyPair (cryptoType, keys.m_PrivateKey, publicKey);
// identity // identity
keys.m_Public = std::make_shared<IdentityEx> (isDestination ? nullptr : publicKey, signingPublicKey, type, cryptoType); keys.m_Public = std::make_shared<IdentityEx> (isDestination ? nullptr : publicKey, signingPublicKey, type, cryptoType);

8
libi2pd/LeaseSet.cpp

@ -261,12 +261,12 @@ namespace data
{ {
LogPrint (eLogError, "LeaseSet: Buffer is too long ", len); LogPrint (eLogError, "LeaseSet: Buffer is too long ", len);
len = MAX_LS_BUFFER_SIZE; len = MAX_LS_BUFFER_SIZE;
} }
if (m_Buffer && len > m_BufferLen) if (m_Buffer && len > m_BufferLen)
{ {
delete[] m_Buffer; delete[] m_Buffer;
m_Buffer = nullptr; m_Buffer = nullptr;
} }
if (!m_Buffer) if (!m_Buffer)
m_Buffer = new uint8_t[len]; m_Buffer = new uint8_t[len];
m_BufferLen = len; m_BufferLen = len;

42
libi2pd/NTCP2.cpp

@ -379,11 +379,11 @@ namespace transport
} }
} }
void NTCP2Session::Close () void NTCP2Session::Close ()
{ {
m_Socket.close (); m_Socket.close ();
} }
void NTCP2Session::TerminateByTimeout () void NTCP2Session::TerminateByTimeout ()
{ {
SendTerminationAndTerminate (eNTCP2IdleTimeout); SendTerminationAndTerminate (eNTCP2IdleTimeout);
@ -401,7 +401,7 @@ namespace transport
SetTerminationTimeout (NTCP2_TERMINATION_TIMEOUT); SetTerminationTimeout (NTCP2_TERMINATION_TIMEOUT);
transports.PeerConnected (shared_from_this ()); transports.PeerConnected (shared_from_this ());
} }
void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce) void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce)
{ {
memset (nonce, 0, 4); memset (nonce, 0, 4);
@ -1058,10 +1058,10 @@ namespace transport
SendRouterInfo (); SendRouterInfo ();
} }
else else
{ {
SendQueue (); SendQueue ();
m_SendQueueSize = m_SendQueue.size (); m_SendQueueSize = m_SendQueue.size ();
} }
} }
} }
@ -1318,29 +1318,29 @@ namespace transport
if (!session) return false; if (!session) return false;
if (incoming) if (incoming)
m_PendingIncomingSessions.erase (session->GetRemoteEndpoint ().address ()); m_PendingIncomingSessions.erase (session->GetRemoteEndpoint ().address ());
if (!session->GetRemoteIdentity ()) if (!session->GetRemoteIdentity ())
{ {
LogPrint (eLogWarning, "NTCP2: Unknown identity for ", session->GetRemoteEndpoint ()); LogPrint (eLogWarning, "NTCP2: Unknown identity for ", session->GetRemoteEndpoint ());
session->Terminate (); session->Terminate ();
return false; return false;
} }
auto& ident = session->GetRemoteIdentity ()->GetIdentHash (); auto& ident = session->GetRemoteIdentity ()->GetIdentHash ();
auto it = m_NTCP2Sessions.find (ident); auto it = m_NTCP2Sessions.find (ident);
if (it != m_NTCP2Sessions.end ()) if (it != m_NTCP2Sessions.end ())
{ {
LogPrint (eLogWarning, "NTCP2: Session with ", ident.ToBase64 (), " already exists. ", incoming ? "Replaced" : "Dropped"); LogPrint (eLogWarning, "NTCP2: Session with ", ident.ToBase64 (), " already exists. ", incoming ? "Replaced" : "Dropped");
if (incoming) if (incoming)
{ {
// replace by new session // replace by new session
auto s = it->second; auto s = it->second;
m_NTCP2Sessions.erase (it); m_NTCP2Sessions.erase (it);
s->Terminate (); s->Terminate ();
} }
else else
{ {
session->Terminate (); session->Terminate ();
return false; return false;
} }
} }
m_NTCP2Sessions.emplace (ident, session); m_NTCP2Sessions.emplace (ident, session);
return true; return true;
@ -1438,19 +1438,19 @@ namespace transport
{ {
LogPrint (eLogDebug, "NTCP2: Connected from ", ep); LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
if (!i2p::util::net::IsInReservedRange(ep.address ())) if (!i2p::util::net::IsInReservedRange(ep.address ()))
{ {
if (conn) if (conn)
{ {
if (m_PendingIncomingSessions.emplace (ep.address (), conn).second) if (m_PendingIncomingSessions.emplace (ep.address (), conn).second)
{ {
conn->SetRemoteEndpoint (ep); conn->SetRemoteEndpoint (ep);
conn->ServerLogin (); conn->ServerLogin ();
conn = nullptr; conn = nullptr;
} }
else else
LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending"); LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending");
} }
} }
else else
LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ()); LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ());
} }
@ -1487,21 +1487,21 @@ namespace transport
if (!ec) if (!ec)
{ {
LogPrint (eLogDebug, "NTCP2: Connected from ", ep); LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
if (!i2p::util::net::IsInReservedRange(ep.address ()) || if (!i2p::util::net::IsInReservedRange(ep.address ()) ||
i2p::util::net::IsYggdrasilAddress (ep.address ())) i2p::util::net::IsYggdrasilAddress (ep.address ()))
{ {
if (conn) if (conn)
{ {
if (m_PendingIncomingSessions.emplace (ep.address (), conn).second) if (m_PendingIncomingSessions.emplace (ep.address (), conn).second)
{ {
conn->SetRemoteEndpoint (ep); conn->SetRemoteEndpoint (ep);
conn->ServerLogin (); conn->ServerLogin ();
conn = nullptr; conn = nullptr;
} }
else else
LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending"); LogPrint (eLogInfo, "NTCP2: Incoming session from ", ep.address (), " is already pending");
} }
} }
else else
LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ()); LogPrint (eLogError, "NTCP2: Incoming connection from invalid IP ", ep.address ());
} }

8
libi2pd/NetDb.cpp

@ -658,8 +658,8 @@ namespace data
m_RouterInfoBuffersPool.CleanUpMt (); m_RouterInfoBuffersPool.CleanUpMt ();
m_RouterInfoAddressesPool.CleanUpMt (); m_RouterInfoAddressesPool.CleanUpMt ();
m_RouterInfoAddressVectorsPool.CleanUpMt (); m_RouterInfoAddressVectorsPool.CleanUpMt ();
if (updatedCount > 0) if (updatedCount > 0)
LogPrint (eLogInfo, "NetDb: Saved ", updatedCount, " new/updated routers"); LogPrint (eLogInfo, "NetDb: Saved ", updatedCount, " new/updated routers");
if (deletedCount > 0) if (deletedCount > 0)
@ -763,7 +763,7 @@ namespace data
{ {
LogPrint (eLogError, "NetDb: Database store msg is too short ", len, ". Dropped"); LogPrint (eLogError, "NetDb: Database store msg is too short ", len, ". Dropped");
return; return;
} }
IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET); IdentHash ident (buf + DATABASE_STORE_KEY_OFFSET);
if (ident.IsZero ()) if (ident.IsZero ())
{ {
@ -778,7 +778,7 @@ namespace data
{ {
LogPrint (eLogError, "NetDb: Database store msg with reply token is too short ", len, ". Dropped"); LogPrint (eLogError, "NetDb: Database store msg with reply token is too short ", len, ". Dropped");
return; return;
} }
auto deliveryStatus = CreateDeliveryStatusMsg (replyToken); auto deliveryStatus = CreateDeliveryStatusMsg (replyToken);
uint32_t tunnelID = bufbe32toh (buf + offset); uint32_t tunnelID = bufbe32toh (buf + offset);
offset += 4; offset += 4;

8
libi2pd/NetDb.hpp

@ -126,11 +126,11 @@ namespace data
std::shared_ptr<RouterInfo::Buffer> NewRouterInfoBuffer () { return m_RouterInfoBuffersPool.AcquireSharedMt (); }; std::shared_ptr<RouterInfo::Buffer> NewRouterInfoBuffer () { return m_RouterInfoBuffersPool.AcquireSharedMt (); };
void PopulateRouterInfoBuffer (std::shared_ptr<RouterInfo> r); void PopulateRouterInfoBuffer (std::shared_ptr<RouterInfo> r);
std::shared_ptr<RouterInfo::Address> NewRouterInfoAddress () { return m_RouterInfoAddressesPool.AcquireSharedMt (); }; std::shared_ptr<RouterInfo::Address> NewRouterInfoAddress () { return m_RouterInfoAddressesPool.AcquireSharedMt (); };
boost::shared_ptr<RouterInfo::Addresses> NewRouterInfoAddresses () boost::shared_ptr<RouterInfo::Addresses> NewRouterInfoAddresses ()
{ {
return boost::shared_ptr<RouterInfo::Addresses>(m_RouterInfoAddressVectorsPool.AcquireMt (), return boost::shared_ptr<RouterInfo::Addresses>(m_RouterInfoAddressVectorsPool.AcquireMt (),
std::bind <void (i2p::util::MemoryPoolMt<RouterInfo::Addresses>::*)(RouterInfo::Addresses *)> std::bind <void (i2p::util::MemoryPoolMt<RouterInfo::Addresses>::*)(RouterInfo::Addresses *)>
(&i2p::util::MemoryPoolMt<RouterInfo::Addresses>::ReleaseMt, (&i2p::util::MemoryPoolMt<RouterInfo::Addresses>::ReleaseMt,
&m_RouterInfoAddressVectorsPool, std::placeholders::_1)); &m_RouterInfoAddressVectorsPool, std::placeholders::_1));
}; };
std::shared_ptr<Lease> NewLease (const Lease& lease) { return m_LeasesPool.AcquireSharedMt (lease); }; std::shared_ptr<Lease> NewLease (const Lease& lease) { return m_LeasesPool.AcquireSharedMt (lease); };

52
libi2pd/RouterContext.cpp

@ -254,7 +254,7 @@ namespace i2p
} }
} }
} }
void RouterContext::SetStatusV6 (RouterStatus status) void RouterContext::SetStatusV6 (RouterStatus status)
{ {
if (status != m_StatusV6) if (status != m_StatusV6)
@ -274,7 +274,7 @@ namespace i2p
} }
} }
} }
void RouterContext::UpdatePort (int port) void RouterContext::UpdatePort (int port)
{ {
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
@ -342,7 +342,7 @@ namespace i2p
else else
it.reset (); it.reset ();
updated = true; updated = true;
} }
} }
if (enable && !found) if (enable && !found)
{ {
@ -444,13 +444,13 @@ namespace i2p
{ {
addr->host = host; addr->host = host;
updated = true; updated = true;
} }
addr = (*addresses)[i2p::data::RouterInfo::eSSU2V4Idx]; addr = (*addresses)[i2p::data::RouterInfo::eSSU2V4Idx];
if (addr && addr->host != host) if (addr && addr->host != host)
{ {
addr->host = host; addr->host = host;
updated = true; updated = true;
} }
} }
else if (host.is_v6 ()) else if (host.is_v6 ())
{ {
@ -459,7 +459,7 @@ namespace i2p
{ {
addr->host = host; addr->host = host;
updated = true; updated = true;
} }
addr = (*addresses)[i2p::data::RouterInfo::eSSU2V6Idx]; addr = (*addresses)[i2p::data::RouterInfo::eSSU2V6Idx];
if (addr && (addr->host != host || !addr->ssu->mtu)) if (addr && (addr->host != host || !addr->ssu->mtu))
{ {
@ -479,11 +479,11 @@ namespace i2p
} }
addr->ssu->mtu = mtu; addr->ssu->mtu = mtu;
} }
} }
updated = true; updated = true;
} }
} }
auto ts = i2p::util::GetSecondsSinceEpoch (); auto ts = i2p::util::GetSecondsSinceEpoch ();
if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL) if (updated || ts > m_LastUpdateTime + ROUTER_INFO_UPDATE_INTERVAL)
UpdateRouterInfo (); UpdateRouterInfo ();
@ -510,7 +510,7 @@ namespace i2p
{ {
addr->ssu->introducers.clear (); addr->ssu->introducers.clear ();
UpdateRouterInfo (); UpdateRouterInfo ();
} }
} }
void RouterContext::SetFloodfill (bool floodfill) void RouterContext::SetFloodfill (bool floodfill)
@ -626,8 +626,8 @@ namespace i2p
uint16_t port = 0; uint16_t port = 0;
// delete previous introducers // delete previous introducers
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
if (addresses) if (addresses)
{ {
for (auto& addr : *addresses) for (auto& addr : *addresses)
if (addr && addr->ssu && ((v4 && addr->IsV4 ()) || (v6 && addr->IsV6 ()))) if (addr && addr->ssu && ((v4 && addr->IsV4 ()) || (v6 && addr->IsV6 ())))
{ {
@ -636,7 +636,7 @@ namespace i2p
addr->ssu->introducers.clear (); addr->ssu->introducers.clear ();
port = addr->port; port = addr->port;
} }
} }
// unpublish NTCP2 addreeses // unpublish NTCP2 addreeses
bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2); bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2);
if (ntcp2) if (ntcp2)
@ -662,8 +662,8 @@ namespace i2p
// delete previous introducers // delete previous introducers
bool isSSU2Published; i2p::config::GetOption ("ssu2.published", isSSU2Published); bool isSSU2Published; i2p::config::GetOption ("ssu2.published", isSSU2Published);
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
if (addresses) if (addresses)
{ {
for (auto& addr : *addresses) for (auto& addr : *addresses)
if (addr && addr->ssu && isSSU2Published && ((v4 && addr->IsV4 ()) || (v6 && addr->IsV6 ()))) if (addr && addr->ssu && isSSU2Published && ((v4 && addr->IsV4 ()) || (v6 && addr->IsV6 ())))
{ {
@ -672,7 +672,7 @@ namespace i2p
addr->ssu->introducers.clear (); addr->ssu->introducers.clear ();
if (addr->port) port = addr->port; if (addr->port) port = addr->port;
} }
} }
// publish NTCP2 // publish NTCP2
bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2); bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2);
if (ntcp2) if (ntcp2)
@ -698,7 +698,7 @@ namespace i2p
bool foundNTCP2 = false, foundSSU2 = false; bool foundNTCP2 = false, foundSSU2 = false;
uint16_t port = 0; uint16_t port = 0;
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
if (addresses) if (addresses)
{ {
for (auto& addr: *addresses) for (auto& addr: *addresses)
{ {
@ -781,7 +781,7 @@ namespace i2p
std::string host = "127.0.0.1"; std::string host = "127.0.0.1";
uint16_t port = 0; uint16_t port = 0;
auto addresses = m_RouterInfo.GetAddresses (); auto addresses = m_RouterInfo.GetAddresses ();
if (addresses) if (addresses)
{ {
for (auto& addr: *addresses) for (auto& addr: *addresses)
{ {
@ -800,7 +800,7 @@ namespace i2p
} }
if (addr && addr->port) port = addr->port; if (addr && addr->port) port = addr->port;
} }
} }
if (!port) if (!port)
{ {
i2p::config::GetOption("port", port); i2p::config::GetOption("port", port);
@ -858,17 +858,17 @@ namespace i2p
uint16_t port = 0; uint16_t port = 0;
i2p::config::GetOption ("ntcp2.port", port); i2p::config::GetOption ("ntcp2.port", port);
if (!port) i2p::config::GetOption("port", port); if (!port) i2p::config::GetOption("port", port);
if (!port) if (!port)
{ {
for (auto& addr: *addresses) for (auto& addr: *addresses)
{ {
if (addr && addr->port) if (addr && addr->port)
{ {
port = addr->port; port = addr->port;
break; break;
} }
} }
} }
if (!port) port = SelectRandomPort (); if (!port) port = SelectRandomPort ();
m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, host, port); m_RouterInfo.AddNTCP2Address (m_NTCP2Keys->staticPublicKey, m_NTCP2Keys->iv, host, port);
} }
@ -885,7 +885,7 @@ namespace i2p
for (auto& addr: *addresses) for (auto& addr: *addresses)
{ {
if (addr && addr->ssu && ((v4 && addr->IsV4 ()) || (!v4 && addr->IsV6 ()))) if (addr && addr->ssu && ((v4 && addr->IsV4 ()) || (!v4 && addr->IsV6 ())))
{ {
addr->ssu->mtu = mtu; addr->ssu->mtu = mtu;
LogPrint (eLogDebug, "Router: MTU for ", v4 ? "ipv4" : "ipv6", " address ", addr->host.to_string(), " is set to ", mtu); LogPrint (eLogDebug, "Router: MTU for ", v4 ? "ipv4" : "ipv6", " address ", addr->host.to_string(), " is set to ", mtu);
} }

48
libi2pd/RouterInfo.cpp

@ -329,9 +329,9 @@ namespace data
} }
Introducer& introducer = address->ssu->introducers.at (index); Introducer& introducer = address->ssu->introducers.at (index);
if (!strcmp (key, "ihost")) if (!strcmp (key, "ihost"))
introducer.isH = false; // SSU1 introducer.isH = false; // SSU1
else if (!strcmp (key, "iport")) else if (!strcmp (key, "iport"))
introducer.isH = false; // SSU1 introducer.isH = false; // SSU1
else if (!strcmp (key, "itag")) else if (!strcmp (key, "itag"))
{ {
try try
@ -344,10 +344,10 @@ namespace data
} }
} }
else if (!strcmp (key, "ih")) else if (!strcmp (key, "ih"))
{ {
Base64ToByteStream (value, strlen (value), introducer.iH, 32); Base64ToByteStream (value, strlen (value), introducer.iH, 32);
introducer.isH = true; introducer.isH = true;
} }
else if (!strcmp (key, "iexp")) else if (!strcmp (key, "iexp"))
{ {
try try
@ -421,7 +421,7 @@ namespace data
for (uint8_t i = 0; i < eNumTransports; i++) for (uint8_t i = 0; i < eNumTransports; i++)
if ((1 << i) & supportedTransports) if ((1 << i) & supportedTransports)
(*addresses)[i] = address; (*addresses)[i] = address;
} }
m_SupportedTransports |= supportedTransports; m_SupportedTransports |= supportedTransports;
} }
} }
@ -647,11 +647,11 @@ namespace data
(*m_Addresses)[eNTCP2V6MeshIdx] = addr; (*m_Addresses)[eNTCP2V6MeshIdx] = addr;
} }
else else
{ {
m_SupportedTransports |= eNTCP2V6; m_SupportedTransports |= eNTCP2V6;
if (addr->published) m_ReachableTransports |= eNTCP2V6; if (addr->published) m_ReachableTransports |= eNTCP2V6;
(*m_Addresses)[eNTCP2V6Idx] = addr; (*m_Addresses)[eNTCP2V6Idx] = addr;
} }
} }
} }
@ -666,13 +666,13 @@ namespace data
addr->ssu->mtu = 0; addr->ssu->mtu = 0;
memcpy (addr->s, staticKey, 32); memcpy (addr->s, staticKey, 32);
memcpy (addr->i, introKey, 32); memcpy (addr->i, introKey, 32);
if (addr->IsV4 ()) if (addr->IsV4 ())
{ {
m_SupportedTransports |= eSSU2V4; m_SupportedTransports |= eSSU2V4;
(*m_Addresses)[eSSU2V4Idx] = addr; (*m_Addresses)[eSSU2V4Idx] = addr;
} }
if (addr->IsV6 ()) if (addr->IsV6 ())
{ {
m_SupportedTransports |= eSSU2V6; m_SupportedTransports |= eSSU2V6;
(*m_Addresses)[eSSU2V6Idx] = addr; (*m_Addresses)[eSSU2V6Idx] = addr;
} }
@ -747,13 +747,13 @@ namespace data
if ((*m_Addresses)[eNTCP2V6Idx]->IsV4 ()) if ((*m_Addresses)[eNTCP2V6Idx]->IsV4 ())
(*m_Addresses)[eNTCP2V6Idx]->caps &= ~AddressCaps::eV6; (*m_Addresses)[eNTCP2V6Idx]->caps &= ~AddressCaps::eV6;
(*m_Addresses)[eNTCP2V6Idx].reset (); (*m_Addresses)[eNTCP2V6Idx].reset ();
} }
if ((*m_Addresses)[eSSU2V6Idx]) if ((*m_Addresses)[eSSU2V6Idx])
{ {
if ((*m_Addresses)[eSSU2V6Idx]->IsV4 ()) if ((*m_Addresses)[eSSU2V6Idx]->IsV4 ())
(*m_Addresses)[eSSU2V6Idx]->caps &= ~AddressCaps::eV6; (*m_Addresses)[eSSU2V6Idx]->caps &= ~AddressCaps::eV6;
(*m_Addresses)[eSSU2V6Idx].reset (); (*m_Addresses)[eSSU2V6Idx].reset ();
} }
UpdateSupportedTransports (); UpdateSupportedTransports ();
} }
} }
@ -767,13 +767,13 @@ namespace data
if ((*m_Addresses)[eNTCP2V4Idx]->IsV6 ()) if ((*m_Addresses)[eNTCP2V4Idx]->IsV6 ())
(*m_Addresses)[eNTCP2V4Idx]->caps &= ~AddressCaps::eV4; (*m_Addresses)[eNTCP2V4Idx]->caps &= ~AddressCaps::eV4;
(*m_Addresses)[eNTCP2V4Idx].reset (); (*m_Addresses)[eNTCP2V4Idx].reset ();
} }
if ((*m_Addresses)[eSSU2V4Idx]) if ((*m_Addresses)[eSSU2V4Idx])
{ {
if ((*m_Addresses)[eSSU2V4Idx]->IsV6 ()) if ((*m_Addresses)[eSSU2V4Idx]->IsV6 ())
(*m_Addresses)[eSSU2V4Idx]->caps &= ~AddressCaps::eV4; (*m_Addresses)[eSSU2V4Idx]->caps &= ~AddressCaps::eV4;
(*m_Addresses)[eSSU2V4Idx].reset (); (*m_Addresses)[eSSU2V4Idx].reset ();
} }
UpdateSupportedTransports (); UpdateSupportedTransports ();
} }
} }
@ -829,8 +829,8 @@ namespace data
#else #else
return m_Addresses; return m_Addresses;
#endif #endif
} }
template<typename Filter> template<typename Filter>
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetAddress (Filter filter) const std::shared_ptr<const RouterInfo::Address> RouterInfo::GetAddress (Filter filter) const
{ {
@ -862,7 +862,7 @@ namespace data
auto addr = (*GetAddresses ())[isV6 ? eSSU2V6Idx : eSSU2V4Idx]; auto addr = (*GetAddresses ())[isV6 ? eSSU2V6Idx : eSSU2V4Idx];
if (addr && !memcmp (addr->s, key, 32)) if (addr && !memcmp (addr->s, key, 32))
return addr; return addr;
return nullptr; return nullptr;
} }
std::shared_ptr<const RouterInfo::Address> RouterInfo::GetPublishedNTCP2V4Address () const std::shared_ptr<const RouterInfo::Address> RouterInfo::GetPublishedNTCP2V4Address () const
@ -1037,7 +1037,7 @@ namespace data
{ {
auto addresses = GetAddresses (); auto addresses = GetAddresses ();
if (!addresses) return; if (!addresses) return;
uint64_t ts = htobe64 (GetTimestamp ()); uint64_t ts = htobe64 (GetTimestamp ());
s.write ((const char *)&ts, sizeof (ts)); s.write ((const char *)&ts, sizeof (ts));
// addresses // addresses
@ -1049,7 +1049,7 @@ namespace data
if (idx == eNTCP2V6Idx && addr_ptr == (*addresses)[eNTCP2V4Idx]) continue; if (idx == eNTCP2V6Idx && addr_ptr == (*addresses)[eNTCP2V4Idx]) continue;
if (idx == eSSU2V6Idx && addr_ptr == (*addresses)[eSSU2V4Idx]) continue; if (idx == eSSU2V6Idx && addr_ptr == (*addresses)[eSSU2V4Idx]) continue;
numAddresses++; numAddresses++;
} }
s.write ((char *)&numAddresses, sizeof (numAddresses)); s.write ((char *)&numAddresses, sizeof (numAddresses));
for (size_t idx = 0; idx < addresses->size(); idx++) for (size_t idx = 0; idx < addresses->size(); idx++)
{ {
@ -1154,7 +1154,7 @@ namespace data
i = 0; i = 0;
for (const auto& introducer: address.ssu->introducers) for (const auto& introducer: address.ssu->introducers)
{ {
WriteString ("ih" + boost::lexical_cast<std::string>(i), properties); WriteString ("ih" + boost::lexical_cast<std::string>(i), properties);
properties << '='; properties << '=';
char value[64]; char value[64];
size_t l = ByteStreamToBase64 (introducer.iH, 32, value, 64); size_t l = ByteStreamToBase64 (introducer.iH, 32, value, 64);
@ -1174,7 +1174,7 @@ namespace data
} }
} }
} }
if (address.transportStyle == eTransportSSU2) if (address.transportStyle == eTransportSSU2)
{ {
// write mtu // write mtu

2
libi2pd/RouterInfo.h

@ -71,7 +71,7 @@ namespace data
}; };
#define TransportBit(tr) e##tr = (1 << e##tr##Idx) #define TransportBit(tr) e##tr = (1 << e##tr##Idx)
enum SupportedTransports enum SupportedTransports
{ {
TransportBit(NTCP2V4), // 0x01 TransportBit(NTCP2V4), // 0x01

16
libi2pd/SSU2.cpp

@ -173,7 +173,7 @@ namespace transport
mtu = i2p::util::net::GetMTU (localAddress); mtu = i2p::util::net::GetMTU (localAddress);
if (mtu > maxMTU) mtu = maxMTU; if (mtu > maxMTU) mtu = maxMTU;
} }
else else
if (mtu > (int)SSU2_MAX_PACKET_SIZE) mtu = SSU2_MAX_PACKET_SIZE; if (mtu > (int)SSU2_MAX_PACKET_SIZE) mtu = SSU2_MAX_PACKET_SIZE;
if (mtu < (int)SSU2_MIN_PACKET_SIZE) mtu = SSU2_MIN_PACKET_SIZE; if (mtu < (int)SSU2_MIN_PACKET_SIZE) mtu = SSU2_MIN_PACKET_SIZE;
i2p::context.SetMTU (mtu, false); i2p::context.SetMTU (mtu, false);
@ -876,7 +876,7 @@ namespace transport
{ {
// token expired // token expired
m_OutgoingTokens.erase (it); m_OutgoingTokens.erase (it);
return 0; return 0;
} }
return it->second.first; return it->second.first;
} }
@ -1210,9 +1210,9 @@ namespace transport
{ {
if (!m_ProxyEndpoint) return; if (!m_ProxyEndpoint) return;
m_UDPAssociateSocket.reset (new boost::asio::ip::tcp::socket (m_ReceiveService.GetService ())); m_UDPAssociateSocket.reset (new boost::asio::ip::tcp::socket (m_ReceiveService.GetService ()));
m_UDPAssociateSocket->async_connect (*m_ProxyEndpoint, m_UDPAssociateSocket->async_connect (*m_ProxyEndpoint,
[this] (const boost::system::error_code& ecode) [this] (const boost::system::error_code& ecode)
{ {
if (ecode) if (ecode)
{ {
LogPrint (eLogError, "SSU2: Can't connect to proxy ", *m_ProxyEndpoint, " ", ecode.message ()); LogPrint (eLogError, "SSU2: Can't connect to proxy ", *m_ProxyEndpoint, " ", ecode.message ());
@ -1227,7 +1227,7 @@ namespace transport
void SSU2Server::HandshakeWithProxy () void SSU2Server::HandshakeWithProxy ()
{ {
if (!m_UDPAssociateSocket) return; if (!m_UDPAssociateSocket) return;
m_UDPRequestHeader[0] = SOCKS5_VER; m_UDPRequestHeader[0] = SOCKS5_VER;
m_UDPRequestHeader[1] = 1; // 1 method m_UDPRequestHeader[1] = 1; // 1 method
m_UDPRequestHeader[2] = 0; // no authentication m_UDPRequestHeader[2] = 0; // no authentication
boost::asio::async_write (*m_UDPAssociateSocket, boost::asio::buffer (m_UDPRequestHeader, 3), boost::asio::transfer_all(), boost::asio::async_write (*m_UDPAssociateSocket, boost::asio::buffer (m_UDPRequestHeader, 3), boost::asio::transfer_all(),
@ -1274,8 +1274,8 @@ namespace transport
void SSU2Server::SendUDPAssociateRequest () void SSU2Server::SendUDPAssociateRequest ()
{ {
if (!m_UDPAssociateSocket) return; if (!m_UDPAssociateSocket) return;
m_UDPRequestHeader[0] = SOCKS5_VER; m_UDPRequestHeader[0] = SOCKS5_VER;
m_UDPRequestHeader[1] = SOCKS5_CMD_UDP_ASSOCIATE; m_UDPRequestHeader[1] = SOCKS5_CMD_UDP_ASSOCIATE;
m_UDPRequestHeader[2] = 0; // RSV m_UDPRequestHeader[2] = 0; // RSV
m_UDPRequestHeader[3] = SOCKS5_ATYP_IPV4; // TODO: implement ipv6 proxy m_UDPRequestHeader[3] = SOCKS5_ATYP_IPV4; // TODO: implement ipv6 proxy
memset (m_UDPRequestHeader + 4, 0, 6); // address and port all zeros memset (m_UDPRequestHeader + 4, 0, 6); // address and port all zeros
@ -1374,7 +1374,7 @@ namespace transport
LogPrint(eLogInfo, "SSU2: Reconnecting to proxy"); LogPrint(eLogInfo, "SSU2: Reconnecting to proxy");
ConnectToProxy (); ConnectToProxy ();
} }
}); });
} }
bool SSU2Server::SetProxy (const std::string& address, uint16_t port) bool SSU2Server::SetProxy (const std::string& address, uint16_t port)

6
libi2pd/SSU2.h

@ -30,7 +30,7 @@ namespace transport
const int SSU2_TO_INTRODUCER_SESSION_EXPIRATION = 4800; // 80 minutes const int SSU2_TO_INTRODUCER_SESSION_EXPIRATION = 4800; // 80 minutes
const int SSU2_KEEP_ALIVE_INTERVAL = 30; // in seconds const int SSU2_KEEP_ALIVE_INTERVAL = 30; // in seconds
const int SSU2_PROXY_CONNECT_RETRY_TIMEOUT = 30; // in seconds const int SSU2_PROXY_CONNECT_RETRY_TIMEOUT = 30; // in seconds
class SSU2Server: private i2p::util::RunnableServiceWithWork class SSU2Server: private i2p::util::RunnableServiceWithWork
{ {
struct Packet struct Packet
@ -132,7 +132,7 @@ namespace transport
void SendUDPAssociateRequest (); void SendUDPAssociateRequest ();
void ReadUDPAssociateReply (); void ReadUDPAssociateReply ();
void ReadUDPAssociateSocket (); // handle if closed by peer void ReadUDPAssociateSocket (); // handle if closed by peer
private: private:
ReceiveService m_ReceiveService; ReceiveService m_ReceiveService;
@ -160,7 +160,7 @@ namespace transport
std::unique_ptr<boost::asio::ip::tcp::socket> m_UDPAssociateSocket; std::unique_ptr<boost::asio::ip::tcp::socket> m_UDPAssociateSocket;
std::unique_ptr<boost::asio::ip::udp::endpoint> m_ProxyRelayEndpoint; std::unique_ptr<boost::asio::ip::udp::endpoint> m_ProxyRelayEndpoint;
std::unique_ptr<boost::asio::deadline_timer> m_ProxyConnectRetryTimer; std::unique_ptr<boost::asio::deadline_timer> m_ProxyConnectRetryTimer;
public: public:
// for HTTP/I2PControl // for HTTP/I2PControl

52
libi2pd/SSU2Session.cpp

@ -96,7 +96,7 @@ namespace transport
// timeout expired // timeout expired
if (m_State == eSSU2SessionStateIntroduced) // WaitForIntroducer if (m_State == eSSU2SessionStateIntroduced) // WaitForIntroducer
LogPrint (eLogWarning, "SSU2: Session was not introduced after ", SSU2_CONNECT_TIMEOUT, " seconds"); LogPrint (eLogWarning, "SSU2: Session was not introduced after ", SSU2_CONNECT_TIMEOUT, " seconds");
else else
LogPrint (eLogWarning, "SSU2: Session with ", m_RemoteEndpoint, " was not established after ", SSU2_CONNECT_TIMEOUT, " seconds"); LogPrint (eLogWarning, "SSU2: Session with ", m_RemoteEndpoint, " was not established after ", SSU2_CONNECT_TIMEOUT, " seconds");
Terminate (); Terminate ();
} }
@ -530,7 +530,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: PeerTest message too short ", len); LogPrint (eLogWarning, "SSU2: PeerTest message too short ", len);
break; break;
} }
const uint8_t nonce[12] = {0}; const uint8_t nonce[12] = {0};
uint64_t headerX[2]; uint64_t headerX[2];
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX); i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
@ -618,7 +618,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: SessionRequest message too short ", len); LogPrint (eLogWarning, "SSU2: SessionRequest message too short ", len);
return; return;
} }
const uint8_t nonce[12] = {0}; const uint8_t nonce[12] = {0};
uint8_t headerX[48]; uint8_t headerX[48];
i2p::crypto::ChaCha20 (buf + 16, 48, i2p::context.GetSSU2IntroKey (), nonce, headerX); i2p::crypto::ChaCha20 (buf + 16, 48, i2p::context.GetSSU2IntroKey (), nonce, headerX);
@ -889,7 +889,7 @@ namespace transport
LogPrint (eLogWarning, "SSU2: SessionConfirmed fragment too short ", len); LogPrint (eLogWarning, "SSU2: SessionConfirmed fragment too short ", len);
if (m_SessionConfirmedFragment) m_SessionConfirmedFragment.reset (nullptr); if (m_SessionConfirmedFragment) m_SessionConfirmedFragment.reset (nullptr);
return false; return false;
} }
if (!(header.h.flags[0] & 0xF0)) if (!(header.h.flags[0] & 0xF0))
{ {
// first fragment // first fragment
@ -942,7 +942,7 @@ namespace transport
LogPrint (eLogWarning, "SSU2: SessionConfirmed message too short ", len); LogPrint (eLogWarning, "SSU2: SessionConfirmed message too short ", len);
if (m_SessionConfirmedFragment) m_SessionConfirmedFragment.reset (nullptr); if (m_SessionConfirmedFragment) m_SessionConfirmedFragment.reset (nullptr);
return false; return false;
} }
// KDF for Session Confirmed part 1 // KDF for Session Confirmed part 1
m_NoiseState->MixHash (header.buf, 16); // h = SHA256(h || header) m_NoiseState->MixHash (header.buf, 16); // h = SHA256(h || header)
// decrypt part1 // decrypt part1
@ -1155,7 +1155,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: Retry message too short ", len); LogPrint (eLogWarning, "SSU2: Retry message too short ", len);
return false; return false;
} }
uint8_t nonce[12] = {0}; uint8_t nonce[12] = {0};
uint64_t headerX[2]; // sourceConnID, token uint64_t headerX[2]; // sourceConnID, token
i2p::crypto::ChaCha20 (buf + 16, 16, m_Address->i, nonce, (uint8_t *)headerX); i2p::crypto::ChaCha20 (buf + 16, 16, m_Address->i, nonce, (uint8_t *)headerX);
@ -1244,7 +1244,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: HolePunch message too short ", len); LogPrint (eLogWarning, "SSU2: HolePunch message too short ", len);
return false; return false;
} }
uint8_t nonce[12] = {0}; uint8_t nonce[12] = {0};
uint64_t headerX[2]; // sourceConnID, token uint64_t headerX[2]; // sourceConnID, token
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX); i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
@ -1320,7 +1320,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: PeerTest message too short ", len); LogPrint (eLogWarning, "SSU2: PeerTest message too short ", len);
return false; return false;
} }
uint8_t nonce[12] = {0}; uint8_t nonce[12] = {0};
uint64_t headerX[2]; // sourceConnID, token uint64_t headerX[2]; // sourceConnID, token
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX); i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
@ -1392,7 +1392,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "SSU2: Data message too short ", len); LogPrint (eLogWarning, "SSU2: Data message too short ", len);
return; return;
} }
uint8_t payload[SSU2_MAX_PACKET_SIZE]; uint8_t payload[SSU2_MAX_PACKET_SIZE];
size_t payloadSize = len - 32; size_t payloadSize = len - 32;
uint32_t packetNum = be32toh (header.h.packetNum); uint32_t packetNum = be32toh (header.h.packetNum);
@ -1465,19 +1465,19 @@ namespace transport
m_IsDataReceived = true; m_IsDataReceived = true;
break; break;
case eSSU2BlkTermination: case eSSU2BlkTermination:
{ {
uint8_t rsn = buf[11]; // reason uint8_t rsn = buf[11]; // reason
LogPrint (eLogDebug, "SSU2: Termination reason=", (int)rsn); LogPrint (eLogDebug, "SSU2: Termination reason=", (int)rsn);
if (IsEstablished () && rsn != eSSU2TerminationReasonTerminationReceived) if (IsEstablished () && rsn != eSSU2TerminationReasonTerminationReceived)
RequestTermination (eSSU2TerminationReasonTerminationReceived); RequestTermination (eSSU2TerminationReasonTerminationReceived);
else if (m_State != eSSU2SessionStateTerminated) else if (m_State != eSSU2SessionStateTerminated)
{ {
if (m_State == eSSU2SessionStateClosing && rsn == eSSU2TerminationReasonTerminationReceived) if (m_State == eSSU2SessionStateClosing && rsn == eSSU2TerminationReasonTerminationReceived)
m_State = eSSU2SessionStateClosingConfirmed; m_State = eSSU2SessionStateClosingConfirmed;
Done (); Done ();
} }
break; break;
} }
case eSSU2BlkRelayRequest: case eSSU2BlkRelayRequest:
LogPrint (eLogDebug, "SSU2: RelayRequest"); LogPrint (eLogDebug, "SSU2: RelayRequest");
HandleRelayRequest (buf + offset, size); HandleRelayRequest (buf + offset, size);
@ -1667,13 +1667,13 @@ namespace transport
LogPrint (eLogInfo, "SSU2: Our port ", ep.port (), " received from ", m_RemoteEndpoint, " is different from ", m_Server.GetPort (isV4)); LogPrint (eLogInfo, "SSU2: Our port ", ep.port (), " received from ", m_RemoteEndpoint, " is different from ", m_Server.GetPort (isV4));
if (isV4) if (isV4)
{ {
if (i2p::context.GetStatus () == eRouterStatusTesting || if (i2p::context.GetStatus () == eRouterStatusTesting ||
m_State == eSSU2SessionStatePeerTest) m_State == eSSU2SessionStatePeerTest)
{ {
i2p::context.SetStatus (eRouterStatusFirewalled); i2p::context.SetStatus (eRouterStatusFirewalled);
i2p::context.SetError (eRouterErrorSymmetricNAT); i2p::context.SetError (eRouterErrorSymmetricNAT);
m_Server.RescheduleIntroducersUpdateTimer (); m_Server.RescheduleIntroducersUpdateTimer ();
} }
} }
else else
{ {
@ -1683,7 +1683,7 @@ namespace transport
i2p::context.SetStatusV6 (eRouterStatusFirewalled); i2p::context.SetStatusV6 (eRouterStatusFirewalled);
i2p::context.SetErrorV6 (eRouterErrorSymmetricNAT); i2p::context.SetErrorV6 (eRouterErrorSymmetricNAT);
m_Server.RescheduleIntroducersUpdateTimerV6 (); m_Server.RescheduleIntroducersUpdateTimerV6 ();
} }
} }
} }
else else
@ -1691,20 +1691,20 @@ namespace transport
if (isV4) if (isV4)
{ {
if (i2p::context.GetError () == eRouterErrorSymmetricNAT) if (i2p::context.GetError () == eRouterErrorSymmetricNAT)
{ {
if (m_State == eSSU2SessionStatePeerTest) if (m_State == eSSU2SessionStatePeerTest)
i2p::context.SetStatus (eRouterStatusOK); i2p::context.SetStatus (eRouterStatusOK);
i2p::context.SetError (eRouterErrorNone); i2p::context.SetError (eRouterErrorNone);
} }
} }
else else
{ {
if (i2p::context.GetErrorV6 () == eRouterErrorSymmetricNAT) if (i2p::context.GetErrorV6 () == eRouterErrorSymmetricNAT)
{ {
if (m_State == eSSU2SessionStatePeerTest) if (m_State == eSSU2SessionStatePeerTest)
i2p::context.SetStatusV6 (eRouterStatusOK); i2p::context.SetStatusV6 (eRouterStatusOK);
i2p::context.SetErrorV6 (eRouterErrorNone); i2p::context.SetErrorV6 (eRouterErrorNone);
} }
} }
} }
} }
@ -1913,10 +1913,10 @@ namespace transport
{ {
LogPrint (eLogDebug, "SSU2: RelayIntro attempt ", attempts + 1); LogPrint (eLogDebug, "SSU2: RelayIntro attempt ", attempts + 1);
s->HandleRelayIntro (vec->data (), vec->size (), attempts + 1); s->HandleRelayIntro (vec->data (), vec->size (), attempts + 1);
}); });
return; return;
} }
else else
{ {
LogPrint (eLogWarning, "SSU2: RelayIntro unknown router to introduce"); LogPrint (eLogWarning, "SSU2: RelayIntro unknown router to introduce");
code = eSSU2RelayResponseCodeCharlieAliceIsUnknown; code = eSSU2RelayResponseCodeCharlieAliceIsUnknown;

22
libi2pd/Streaming.cpp

@ -495,27 +495,27 @@ namespace stream
timeout); timeout);
if (!done) if (!done)
{ std::unique_lock<std::mutex> l(newDataReceivedMutex); { std::unique_lock<std::mutex> l(newDataReceivedMutex);
if (!done && newDataReceived.wait_for (l, std::chrono::seconds (timeout)) == std::cv_status::timeout) if (!done && newDataReceived.wait_for (l, std::chrono::seconds (timeout)) == std::cv_status::timeout)
ret = 0; ret = 0;
} }
if (!done) if (!done)
{ {
// make sure that AsycReceive complete // make sure that AsycReceive complete
auto s = shared_from_this(); auto s = shared_from_this();
m_Service.post ([s]() m_Service.post ([s]()
{ {
s->m_ReceiveTimer.cancel (); s->m_ReceiveTimer.cancel ();
}); });
int i = 0; int i = 0;
while (!done && i < 100) // 1 sec while (!done && i < 100) // 1 sec
{ {
std::this_thread::sleep_for (std::chrono::milliseconds(10)); std::this_thread::sleep_for (std::chrono::milliseconds(10));
i++; i++;
} }
} }
return ret; return ret;
} }
size_t Stream::Send (const uint8_t * buf, size_t len) size_t Stream::Send (const uint8_t * buf, size_t len)
{ {
AsyncSend (buf, len, nullptr); AsyncSend (buf, len, nullptr);
@ -1396,11 +1396,11 @@ namespace stream
}); });
if (timeout) if (timeout)
streamAccept.wait_for (l, std::chrono::seconds (timeout)); streamAccept.wait_for (l, std::chrono::seconds (timeout));
else else
streamAccept.wait (l); streamAccept.wait (l);
return stream; return stream;
} }
void StreamingDestination::HandlePendingIncomingTimer (const boost::system::error_code& ecode) void StreamingDestination::HandlePendingIncomingTimer (const boost::system::error_code& ecode)
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)

4
libi2pd/Streaming.h

@ -186,7 +186,7 @@ namespace stream
void AsyncReceive (const Buffer& buffer, ReceiveHandler handler, int timeout = 0); void AsyncReceive (const Buffer& buffer, ReceiveHandler handler, int timeout = 0);
size_t ReadSome (uint8_t * buf, size_t len) { return ConcatenatePackets (buf, len); }; size_t ReadSome (uint8_t * buf, size_t len) { return ConcatenatePackets (buf, len); };
size_t Receive (uint8_t * buf, size_t len, int timeout); size_t Receive (uint8_t * buf, size_t len, int timeout);
void AsyncClose() { m_Service.post(std::bind(&Stream::Close, shared_from_this())); }; void AsyncClose() { m_Service.post(std::bind(&Stream::Close, shared_from_this())); };
/** only call close from destination thread, use Stream::AsyncClose for other threads */ /** only call close from destination thread, use Stream::AsyncClose for other threads */
@ -280,7 +280,7 @@ namespace stream
void AcceptOnce (const Acceptor& acceptor); void AcceptOnce (const Acceptor& acceptor);
void AcceptOnceAcceptor (std::shared_ptr<Stream> stream, Acceptor acceptor, Acceptor prev); void AcceptOnceAcceptor (std::shared_ptr<Stream> stream, Acceptor acceptor, Acceptor prev);
std::shared_ptr<Stream> AcceptStream (int timeout = 0); // sync std::shared_ptr<Stream> AcceptStream (int timeout = 0); // sync
std::shared_ptr<i2p::client::ClientDestination> GetOwner () const { return m_Owner; }; std::shared_ptr<i2p::client::ClientDestination> GetOwner () const { return m_Owner; };
void SetOwner (std::shared_ptr<i2p::client::ClientDestination> owner) { m_Owner = owner; }; void SetOwner (std::shared_ptr<i2p::client::ClientDestination> owner) { m_Owner = owner; };
uint16_t GetLocalPort () const { return m_LocalPort; }; uint16_t GetLocalPort () const { return m_LocalPort; };

2
libi2pd/TransitTunnel.cpp

@ -33,7 +33,7 @@ namespace tunnel
{ {
m_Encryption.reset (new i2p::crypto::TunnelEncryption); m_Encryption.reset (new i2p::crypto::TunnelEncryption);
m_Encryption->SetKeys (m_LayerKey, m_IVKey); m_Encryption->SetKeys (m_LayerKey, m_IVKey);
} }
m_Encryption->Encrypt (in->GetPayload () + 4, out->GetPayload () + 4); m_Encryption->Encrypt (in->GetPayload () + 4, out->GetPayload () + 4);
i2p::transport::transports.UpdateTotalTransitTransmittedBytes (TUNNEL_DATA_MSG_SIZE); i2p::transport::transports.UpdateTotalTransitTransmittedBytes (TUNNEL_DATA_MSG_SIZE);
} }

2
libi2pd/TransportSession.h

@ -116,7 +116,7 @@ namespace transport
virtual void SendLocalRouterInfo (bool update = false) { SendI2NPMessages ({ CreateDatabaseStoreMsg () }); }; virtual void SendLocalRouterInfo (bool update = false) { SendI2NPMessages ({ CreateDatabaseStoreMsg () }); };
virtual void SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs) = 0; virtual void SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs) = 0;
virtual bool IsEstablished () const = 0; virtual bool IsEstablished () const = 0;
protected: protected:
std::shared_ptr<const i2p::data::IdentityEx> m_RemoteIdentity; std::shared_ptr<const i2p::data::IdentityEx> m_RemoteIdentity;

4
libi2pd/Transports.cpp

@ -823,8 +823,8 @@ namespace transport
std::unique_lock<std::mutex> l(m_PeersMutex); std::unique_lock<std::mutex> l(m_PeersMutex);
auto it = m_Peers.begin (); auto it = m_Peers.begin ();
std::advance (it, rand () % m_Peers.size ()); std::advance (it, rand () % m_Peers.size ());
if (it == m_Peers.end () || it->second.router || it->second.sessions.empty () || if (it == m_Peers.end () || it->second.router || it->second.sessions.empty () ||
it->second.sessions.front ()->GetSendQueueSize () > PEER_ROUTER_INFO_OVERLOAD_QUEUE_SIZE) it->second.sessions.front ()->GetSendQueueSize () > PEER_ROUTER_INFO_OVERLOAD_QUEUE_SIZE)
return nullptr; // not connected or overloaded return nullptr; // not connected or overloaded
ident = it->first; ident = it->first;
} }

2
libi2pd/Tunnel.h

@ -44,7 +44,7 @@ namespace tunnel
const int TUNNEL_MANAGE_INTERVAL = 15; // in seconds const int TUNNEL_MANAGE_INTERVAL = 15; // in seconds
const int TUNNEL_POOLS_MANAGE_INTERVAL = 5; // in seconds const int TUNNEL_POOLS_MANAGE_INTERVAL = 5; // in seconds
const int TUNNEL_MEMORY_POOL_MANAGE_INTERVAL = 120; // in seconds const int TUNNEL_MEMORY_POOL_MANAGE_INTERVAL = 120; // in seconds
const size_t I2NP_TUNNEL_MESSAGE_SIZE = TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + 34; // reserved for alignment and NTCP 16 + 6 + 12 const size_t I2NP_TUNNEL_MESSAGE_SIZE = TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + 34; // reserved for alignment and NTCP 16 + 6 + 12
const size_t I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE = 2*TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE + 28; // reserved for alignment and NTCP 16 + 6 + 6 const size_t I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE = 2*TUNNEL_DATA_MSG_SIZE + I2NP_HEADER_SIZE + TUNNEL_GATEWAY_HEADER_SIZE + 28; // reserved for alignment and NTCP 16 + 6 + 6

10
libi2pd/TunnelPool.cpp

@ -284,12 +284,12 @@ namespace tunnel
} }
num = m_NumOutboundTunnels - num; num = m_NumOutboundTunnels - num;
if (num > 0) if (num > 0)
{ {
if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS; if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS;
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++)
CreateOutboundTunnel (); CreateOutboundTunnel ();
} }
num = 0; num = 0;
{ {
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex); std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
@ -307,12 +307,12 @@ namespace tunnel
} }
num = m_NumInboundTunnels - num; num = m_NumInboundTunnels - num;
if (num > 0) if (num > 0)
{ {
if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS; if (num > TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS) num = TUNNEL_POOL_MAX_NUM_BUILD_REQUESTS;
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++)
CreateInboundTunnel (); CreateInboundTunnel ();
} }
if (num < m_NumInboundTunnels && m_NumInboundHops <= 0 && m_LocalDestination) // zero hops IB if (num < m_NumInboundTunnels && m_NumInboundHops <= 0 && m_LocalDestination) // zero hops IB
m_LocalDestination->SetLeaseSetUpdated (); // update LeaseSet immediately m_LocalDestination->SetLeaseSetUpdated (); // update LeaseSet immediately
} }

20
libi2pd_client/AddressBook.cpp

@ -833,7 +833,7 @@ namespace client
} }
else else
m_Ident = addr->identHash; m_Ident = addr->identHash;
// save url parts for later use // save url parts for later use
std::string dest_host = url.host; std::string dest_host = url.host;
int dest_port = url.port ? url.port : 80; int dest_port = url.port ? url.port : 80;
// try to create stream to addressbook site // try to create stream to addressbook site
@ -842,13 +842,13 @@ namespace client
{ {
LogPrint (eLogError, "Addressbook: LeaseSet for address ", url.host, " not found"); LogPrint (eLogError, "Addressbook: LeaseSet for address ", url.host, " not found");
return false; return false;
} }
if (m_Etag.empty() && m_LastModified.empty()) if (m_Etag.empty() && m_LastModified.empty())
{ {
m_Book.GetEtag (m_Ident, m_Etag, m_LastModified); m_Book.GetEtag (m_Ident, m_Etag, m_LastModified);
LogPrint (eLogDebug, "Addressbook: Loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified); LogPrint (eLogDebug, "Addressbook: Loaded for ", url.host, ": ETag: ", m_Etag, ", Last-Modified: ", m_LastModified);
} }
// create http request & send it // create http request & send it
i2p::http::HTTPReq req; i2p::http::HTTPReq req;
req.AddHeader("Host", dest_host); req.AddHeader("Host", dest_host);
req.AddHeader("User-Agent", "Wget/1.11.4"); req.AddHeader("User-Agent", "Wget/1.11.4");
@ -859,7 +859,7 @@ namespace client
req.AddHeader("If-None-Match", m_Etag); req.AddHeader("If-None-Match", m_Etag);
if (!m_LastModified.empty()) if (!m_LastModified.empty())
req.AddHeader("If-Modified-Since", m_LastModified); req.AddHeader("If-Modified-Since", m_LastModified);
// convert url to relative // convert url to relative
url.schema = ""; url.schema = "";
url.host = ""; url.host = "";
req.uri = url.to_string(); req.uri = url.to_string();
@ -878,7 +878,7 @@ namespace client
{ {
response.append ((char *)recv_buf, received); response.append ((char *)recv_buf, received);
if (!stream->IsOpen ()) end = true; if (!stream->IsOpen ()) end = true;
} }
else if (!stream->IsOpen ()) else if (!stream->IsOpen ())
end = true; end = true;
else else
@ -886,12 +886,12 @@ namespace client
LogPrint (eLogError, "Addressbook: Subscriptions request timeout expired"); LogPrint (eLogError, "Addressbook: Subscriptions request timeout expired");
numAttempts++; numAttempts++;
if (numAttempts > 5) end = true; if (numAttempts > 5) end = true;
} }
} }
// process remaining buffer // process remaining buffer
while (size_t len = stream->ReadSome (recv_buf, sizeof(recv_buf))) while (size_t len = stream->ReadSome (recv_buf, sizeof(recv_buf)))
response.append ((char *)recv_buf, len); response.append ((char *)recv_buf, len);
// parse response // parse response
i2p::http::HTTPRes res; i2p::http::HTTPRes res;
int res_head_len = res.parse(response); int res_head_len = res.parse(response);
if (res_head_len < 0) if (res_head_len < 0)
@ -904,7 +904,7 @@ namespace client
LogPrint(eLogError, "Addressbook: Incomplete http response from ", dest_host, ", interrupted by timeout"); LogPrint(eLogError, "Addressbook: Incomplete http response from ", dest_host, ", interrupted by timeout");
return false; return false;
} }
// assert: res_head_len > 0 // assert: res_head_len > 0
response.erase(0, res_head_len); response.erase(0, res_head_len);
if (res.code == 304) if (res.code == 304)
{ {
@ -927,7 +927,7 @@ namespace client
LogPrint(eLogError, "Addressbook: Response size mismatch, expected: ", len, ", got: ", response.length(), "bytes"); LogPrint(eLogError, "Addressbook: Response size mismatch, expected: ", len, ", got: ", response.length(), "bytes");
return false; return false;
} }
// assert: res.code == 200 // assert: res.code == 200
auto it = res.headers.find("ETag"); auto it = res.headers.find("ETag");
if (it != res.headers.end()) m_Etag = it->second; if (it != res.headers.end()) m_Etag = it->second;
it = res.headers.find("Last-Modified"); it = res.headers.find("Last-Modified");

2
libi2pd_client/UDPTunnel.cpp

@ -372,6 +372,6 @@ namespace client
else else
LogPrint (eLogWarning, "UDP Client: Not tracking udp session using port ", (int) toPort); LogPrint (eLogWarning, "UDP Client: Not tracking udp session using port ", (int) toPort);
} }
} }
} }

2
libi2pd_client/UDPTunnel.h

@ -180,7 +180,7 @@ namespace client
bool isUpdated; // transient, used during reload only bool isUpdated; // transient, used during reload only
}; };
} }
} }

Loading…
Cancel
Save