Compare commits

...

12 Commits

Author SHA1 Message Date
Pratik B.
13d9c6530c Merge 17399da399 into 7e3d9649de 2025-02-21 13:05:10 -06:00
orignal
7e3d9649de use plain buffer instead stream for SignedData 2025-02-20 22:04:58 -05:00
orignal
9ba016259d use plain buffer instead stream for SignedData 2025-02-20 21:59:24 -05:00
orignal
7791b3952e check RelayRequest, RelayIntro, RelayResponse buffer size. Use assign instead memcpy 2025-02-20 16:53:49 -05:00
orignal
b97f09cc95 const ExtractString and ExtractMapping 2025-02-19 18:51:54 -05:00
orignal
aedf59d11a fixed typo 2025-02-19 13:38:47 -05:00
orignal
d09367d686 always pass RouterInfo param values as string_view 2025-02-19 11:08:47 -05:00
orignal
70f99ccc21 update router caps 2025-02-18 21:49:07 -05:00
orignal
ef72ba3f34 parse RouterInfo from buffer 2025-02-18 21:11:59 -05:00
orignal
251605e2b8 Fix the calculation of the window drop size 2025-02-18 20:22:18 -05:00
orignal
fa2178ca3e set max padding size to 32 bytes 2025-02-17 15:08:22 -05:00
imdef
17399da399 Added example docker-compose.yml 2024-09-25 16:55:29 +00:00
11 changed files with 220 additions and 182 deletions

View File

@@ -0,0 +1,13 @@
services:
i2pd:
container_name: i2pd2
image: purplei2p/i2pd
#optional
entrypoint: ["./entrypoint.sh", "--loglevel error"]
ports:
- 127.0.0.1:7656:7656
- 127.0.0.1:7070:7070
- 127.0.0.1:4444:4444
volumes:
- /path/to/i2pd/data:/home/i2pd/data # make sure data directory and it's contents are owned by 100:65533
- /path/to/i2pd/i2pd_certificates:/i2pd_certificates # make sure i2pd_certificates is owned by root:root and 755 permissions on the directory

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 2013-2024, The PurpleI2P Project
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
@@ -90,10 +90,10 @@ namespace data
}
bool Families::VerifyFamily (const std::string& family, const IdentHash& ident,
const char * signature, const char * key) const
std::string_view signature, const char * key) const
{
uint8_t buf[100], signatureBuf[64];
size_t len = family.length (), signatureLen = strlen (signature);
size_t len = family.length ();
if (len + 32 > 100)
{
LogPrint (eLogError, "Family: ", family, " is too long");
@@ -105,7 +105,7 @@ namespace data
memcpy (buf, family.c_str (), len);
memcpy (buf + len, (const uint8_t *)ident, 32);
len += 32;
auto signatureBufLen = Base64ToByteStream (signature, signatureLen, signatureBuf, 64);
auto signatureBufLen = Base64ToByteStream (signature.data (), signature.length (), signatureBuf, 64);
if (signatureBufLen)
{
EVP_MD_CTX * ctx = EVP_MD_CTX_create ();

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 2013-2024, The PurpleI2P Project
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
@@ -11,6 +11,7 @@
#include <map>
#include <string>
#include <string_view>
#include <memory>
#include <openssl/evp.h>
#include "Identity.h"
@@ -28,7 +29,7 @@ namespace data
~Families ();
void LoadCertificates ();
bool VerifyFamily (const std::string& family, const IdentHash& ident,
const char * signature, const char * key = nullptr) const;
std::string_view signature, const char * key = nullptr) const;
FamilyID GetFamilyID (const std::string& family) const;
private:

View File

@@ -11,6 +11,7 @@
#include "I2PEndian.h"
#include <fstream>
#include <memory>
#include <charconv>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp> // for boost::to_lower
#ifndef __cpp_lib_atomic_shared_ptr
@@ -106,8 +107,7 @@ namespace data
// skip identity
size_t identityLen = m_RouterIdentity->GetFullLen ();
// read new RI
std::stringstream str (std::string ((char *)buf + identityLen, len - identityLen));
ReadFromStream (str);
ReadFromBuffer (buf + identityLen, len - identityLen);
if (!m_IsUnreachable)
UpdateBuffer (buf, len); // save buffer
// don't delete buffer until saved to the file
@@ -195,39 +195,34 @@ namespace data
}
}
// parse RI
std::stringstream str;
str.write ((const char *)m_Buffer->data () + identityLen, bufferLen - identityLen);
ReadFromStream (str);
if (!str)
if (!ReadFromBuffer (m_Buffer->data () + identityLen, bufferLen - identityLen))
{
LogPrint (eLogError, "RouterInfo: Malformed message");
m_IsUnreachable = true;
}
}
}
void RouterInfo::ReadFromStream (std::istream& s)
bool RouterInfo::ReadFromBuffer (const uint8_t * buf, size_t len)
{
if (!s) return;
if (len < 9) return false;
m_Caps = 0; m_Congestion = eLowCongestion;
s.read ((char *)&m_Timestamp, sizeof (m_Timestamp));
m_Timestamp = be64toh (m_Timestamp);
m_Timestamp = bufbe64toh (buf);
size_t offset = 8; // timestamp
// read addresses
auto addresses = NewAddresses ();
uint8_t numAddresses;
s.read ((char *)&numAddresses, sizeof (numAddresses));
uint8_t numAddresses = buf[offset]; offset++;
for (int i = 0; i < numAddresses; i++)
{
if (offset + 9 > len) return false; // 1 byte cost + 8 bytes date
uint8_t supportedTransports = 0;
auto address = NewAddress ();
uint8_t cost; // ignore
s.read ((char *)&cost, sizeof (cost));
s.read ((char *)&address->date, sizeof (address->date));
offset++; // cost, ignore
address->date = bufbe64toh (buf + offset); offset += 8; // date
bool isHost = false, isStaticKey = false, isV2 = false, isIntroKey = false;
char transportStyle[6];
ReadString (transportStyle, 6, s);
if (!strncmp (transportStyle, "NTCP", 4)) // NTCP or NTCP2
auto transportStyle = ExtractString (buf + offset, len - offset); offset += transportStyle.length () + 1;
if (!transportStyle.compare (0, 4, "NTCP")) // NTCP or NTCP2
address->transportStyle = eTransportNTCP2;
else if (!strncmp (transportStyle, "SSU", 3)) // SSU or SSU2
else if (!transportStyle.compare (0, 3, "SSU")) // SSU or SSU2
{
address->transportStyle = eTransportSSU2;
address->ssu.reset (new SSUExt ());
@@ -237,24 +232,22 @@ namespace data
address->transportStyle = eTransportUnknown;
address->caps = 0;
address->port = 0;
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size)); if (!s) return;
size = be16toh (size);
if (offset + 2 > len) return false;
uint16_t size = bufbe16toh (buf + offset); offset += 2; // size
if (offset + size >= len) return false;
if (address->transportStyle == eTransportUnknown)
{
// skip unknown address
s.seekg (size, std::ios_base::cur);
if (s) continue; else return;
offset += size;
continue;
}
size_t r = 0;
while (r < size)
{
char key[255], value[255];
r += ReadString (key, 255, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, 255, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!s) return;
if (!strcmp (key, "host"))
auto [key, value, sz] = ExtractParam (buf + offset, len - offset);
r += sz; offset += sz;
if (key.empty ()) continue;
if (key == "host")
{
boost::system::error_code ecode;
address->host = boost::asio::ip::make_address (value, ecode);
@@ -268,7 +261,7 @@ namespace data
address->transportStyle = eTransportUnknown;
}
}
else if (!strcmp (key, "port"))
else if (key == "port")
{
try
{
@@ -279,7 +272,7 @@ namespace data
LogPrint (eLogWarning, "RouterInfo: 'port' exception ", ex.what ());
}
}
else if (!strcmp (key, "mtu"))
else if (key == "mtu")
{
if (address->ssu)
{
@@ -295,36 +288,36 @@ namespace data
else
LogPrint (eLogWarning, "RouterInfo: Unexpected field 'mtu' for NTCP2");
}
else if (!strcmp (key, "caps"))
else if (key == "caps")
address->caps = ExtractAddressCaps (value);
else if (!strcmp (key, "s")) // ntcp2 or ssu2 static key
else if (key == "s") // ntcp2 or ssu2 static key
{
if (Base64ToByteStream (value, strlen (value), address->s, 32) == 32 &&
if (Base64ToByteStream (value.data (), value.length (), address->s, 32) == 32 &&
!(address->s[31] & 0x80)) // check if x25519 public key
isStaticKey = true;
else
address->transportStyle = eTransportUnknown; // invalid address
}
else if (!strcmp (key, "i")) // ntcp2 iv or ssu2 intro
else if (key == "i") // ntcp2 iv or ssu2 intro
{
if (address->IsNTCP2 ())
{
if (Base64ToByteStream (value, strlen (value), address->i, 16) == 16)
if (Base64ToByteStream (value.data (), value.length (), address->i, 16) == 16)
address->published = true; // presence of "i" means "published" NTCP2
else
address->transportStyle = eTransportUnknown; // invalid address
}
else if (address->IsSSU2 ())
{
if (Base64ToByteStream (value, strlen (value), address->i, 32) == 32)
if (Base64ToByteStream (value.data (), value.length (), address->i, 32) == 32)
isIntroKey = true;
else
address->transportStyle = eTransportUnknown; // invalid address
}
}
else if (!strcmp (key, "v"))
else if (key == "v")
{
if (!strcmp (value, "2"))
if (value == "2")
isV2 = true;
else
{
@@ -340,13 +333,11 @@ namespace data
LogPrint (eLogError, "RouterInfo: Introducer is presented for non-SSU address. Skipped");
continue;
}
size_t l = strlen(key);
unsigned char index = key[l-1] - '0'; // TODO:
key[l-1] = 0;
unsigned char index = key[key.length () - 1] - '0'; // TODO:
if (index > 9)
{
LogPrint (eLogError, "RouterInfo: Unexpected introducer's index ", index, " skipped");
if (s) continue; else return;
continue;
}
if (index >= address->ssu->introducers.size ())
{
@@ -355,7 +346,8 @@ namespace data
address->ssu->introducers.resize (index + 1);
}
Introducer& introducer = address->ssu->introducers.at (index);
if (!strcmp (key, "itag"))
auto key1 = key.substr(0, key.length () - 1);
if (key1 == "itag")
{
try
{
@@ -366,9 +358,9 @@ namespace data
LogPrint (eLogWarning, "RouterInfo: 'itag' exception ", ex.what ());
}
}
else if (!strcmp (key, "ih"))
Base64ToByteStream (value, strlen (value), introducer.iH, 32);
else if (!strcmp (key, "iexp"))
else if (key1 == "ih")
Base64ToByteStream (value.data (), value.length (), introducer.iH, 32);
else if (key1 == "iexp")
{
try
{
@@ -380,9 +372,7 @@ namespace data
}
}
}
if (!s) return;
}
}
if (address->transportStyle == eTransportNTCP2)
{
if (isStaticKey)
@@ -446,45 +436,41 @@ namespace data
boost::atomic_store (&m_Addresses, addresses);
#endif
// read peers
uint8_t numPeers;
s.read ((char *)&numPeers, sizeof (numPeers)); if (!s) return;
s.seekg (numPeers*32, std::ios_base::cur); // TODO: read peers
if (offset + 1 > len) return false;
uint8_t numPeers = buf[offset]; offset++; // num peers
offset += numPeers*32; // TODO: read peers
// read properties
if (offset + 2 > len) return false;
m_Version = 0;
bool isNetId = false;
std::string family;
uint16_t size, r = 0;
s.read ((char *)&size, sizeof (size)); if (!s) return;
size = be16toh (size);
uint16_t size = bufbe16toh (buf + offset); offset += 2; // size
if (offset + size > len) return false;
size_t r = 0;
while (r < size)
{
char key[255], value[255];
r += ReadString (key, 255, s);
s.seekg (1, std::ios_base::cur); r++; // =
r += ReadString (value, 255, s);
s.seekg (1, std::ios_base::cur); r++; // ;
if (!s) return;
auto [key, value, sz] = ExtractParam (buf + offset, len - offset);
r += sz; offset += sz;
if (key.empty ()) continue;
SetProperty (key, value);
// extract caps
if (!strcmp (key, "caps"))
if (key == "caps")
{
ExtractCaps (value);
m_IsFloodfill = IsDeclaredFloodfill ();
}
// extract version
else if (!strcmp (key, ROUTER_INFO_PROPERTY_VERSION))
else if (key == ROUTER_INFO_PROPERTY_VERSION)
{
m_Version = 0;
char * ch = value;
while (*ch)
for (auto ch: value)
{
if (*ch >= '0' && *ch <= '9')
if (ch >= '0' && ch <= '9')
{
m_Version *= 10;
m_Version += (*ch - '0');
m_Version += (ch - '0');
}
ch++;
}
if (m_Version < NETDB_MIN_PEER_TEST_VERSION && (m_SupportedTransports & (eSSU2V4 | eSSU2V6)))
{
@@ -497,24 +483,26 @@ namespace data
}
}
// check netId
else if (!strcmp (key, ROUTER_INFO_PROPERTY_NETID))
else if (key == ROUTER_INFO_PROPERTY_NETID)
{
isNetId = true;
if (atoi (value) != i2p::context.GetNetID ())
int netID;
auto res = std::from_chars(value.data(), value.data() + value.size(), netID);
if (res.ec != std::errc() || netID != i2p::context.GetNetID ())
{
LogPrint (eLogError, "RouterInfo: Unexpected ", ROUTER_INFO_PROPERTY_NETID, "=", value);
m_IsUnreachable = true;
}
}
// family
else if (!strcmp (key, ROUTER_INFO_PROPERTY_FAMILY))
else if (key == ROUTER_INFO_PROPERTY_FAMILY)
{
family = value;
boost::to_lower (family);
}
else if (!strcmp (key, ROUTER_INFO_PROPERTY_FAMILY_SIG))
else if (key == ROUTER_INFO_PROPERTY_FAMILY_SIG)
{
if (netdb.GetFamilies ().VerifyFamily (family, GetIdentHash (), value))
if (netdb.GetFamilies ().VerifyFamily (family, GetIdentHash (), value)) // TODO
m_FamilyID = netdb.GetFamilies ().GetFamilyID (family);
else
{
@@ -522,25 +510,24 @@ namespace data
SetUnreachable (true);
}
}
if (!s) return;
}
if (!m_SupportedTransports || !isNetId || !m_Version)
SetUnreachable (true);
}
return true;
}
bool RouterInfo::IsFamily (FamilyID famid) const
{
return m_FamilyID == famid;
}
void RouterInfo::ExtractCaps (const char * value)
void RouterInfo::ExtractCaps (std::string_view value)
{
const char * cap = value;
while (*cap)
for (auto cap: value)
{
switch (*cap)
switch (cap)
{
case CAPS_FLAG_FLOODFILL:
m_Caps |= Caps::eFloodfill;
@@ -549,16 +536,16 @@ namespace data
case CAPS_FLAG_LOW_BANDWIDTH2:
case CAPS_FLAG_LOW_BANDWIDTH3:
case CAPS_FLAG_LOW_BANDWIDTH4:
m_BandwidthCap = *cap;
m_BandwidthCap = cap;
break;
case CAPS_FLAG_HIGH_BANDWIDTH:
m_Caps |= Caps::eHighBandwidth;
m_BandwidthCap = *cap;
m_BandwidthCap = cap;
break;
case CAPS_FLAG_EXTRA_BANDWIDTH1:
case CAPS_FLAG_EXTRA_BANDWIDTH2:
m_Caps |= Caps::eExtraBandwidth | Caps::eHighBandwidth;
m_BandwidthCap = *cap;
m_BandwidthCap = cap;
break;
case CAPS_FLAG_HIDDEN:
m_Caps |= Caps::eHidden;
@@ -580,17 +567,15 @@ namespace data
break;
default: ;
}
cap++;
}
}
uint8_t RouterInfo::ExtractAddressCaps (const char * value) const
}
uint8_t RouterInfo::ExtractAddressCaps (std::string_view value) const
{
uint8_t caps = 0;
const char * cap = value;
while (*cap)
for (auto cap: value)
{
switch (*cap)
switch (cap)
{
case CAPS_FLAG_V4:
caps |= AddressCaps::eV4;
@@ -606,11 +591,10 @@ namespace data
break;
default: ;
}
cap++;
}
return caps;
}
}
void RouterInfo::UpdateIntroducers (std::shared_ptr<Address> address, uint64_t ts)
{
if (!address || !address->ssu) return;
@@ -670,25 +654,41 @@ namespace data
return SaveToFile (fullPath, m_Buffer);
}
size_t RouterInfo::ReadString (char * str, size_t len, std::istream& s) const
std::string_view RouterInfo::ExtractString (const uint8_t * buf, size_t len) const
{
uint8_t l;
s.read ((char *)&l, 1);
if (l < len)
{
s.read (str, l);
if (!s) l = 0; // failed, return empty string
str[l] = 0;
}
else
uint8_t l = buf[0];
if (l > len)
{
LogPrint (eLogWarning, "RouterInfo: String length ", (int)l, " exceeds buffer size ", len);
s.seekg (l, std::ios::cur); // skip
str[0] = 0;
}
return l+1;
l = len;
}
return { (const char *)(buf + 1), l };
}
std::tuple<std::string_view, std::string_view, size_t> RouterInfo::ExtractParam (const uint8_t * buf, size_t len) const
{
auto key = ExtractString (buf, len);
size_t offset = key.length () + 1;
if (offset >= len) return { std::string_view(), std::string_view(), len };
if (buf[offset] != '=')
{
LogPrint (eLogWarning, "RouterInfo: Unexpected character ", buf[offset], " instead '=' after ", key);
key = std::string_view();
}
offset++;
if (offset >= len) return { key, std::string_view(), len };
auto value = ExtractString (buf + offset, len - offset);
offset += value.length () + 1;
if (offset >= len) return { key, std::string_view(), len };
if (buf[offset] != ';')
{
LogPrint (eLogWarning, "RouterInfo: Unexpected character ", buf[offset], " instead ';' after ", value);
value = std::string_view();
}
offset++;
return { key, value, offset };
}
void RouterInfo::AddNTCP2Address (const uint8_t * staticKey, const uint8_t * iv,int port, uint8_t caps)
{
auto addr = std::make_shared<Address>();
@@ -1485,9 +1485,11 @@ namespace data
s.write (properties.str ().c_str (), properties.str ().size ());
}
void LocalRouterInfo::SetProperty (const std::string& key, const std::string& value)
void LocalRouterInfo::SetProperty (std::string_view key, std::string_view value)
{
m_Properties[key] = value;
auto [it, inserted] = m_Properties.emplace (key, value);
if (!inserted)
it->second = value;
}
void LocalRouterInfo::DeleteProperty (const std::string& key)

View File

@@ -11,6 +11,8 @@
#include <inttypes.h>
#include <string>
#include <string_view>
#include <tuple>
#include <map>
#include <vector>
#include <array>
@@ -219,7 +221,7 @@ namespace data
std::string GetIdentHashBase64 () const { return GetIdentHash ().ToBase64 (); };
uint64_t GetTimestamp () const { return m_Timestamp; };
int GetVersion () const { return m_Version; };
virtual void SetProperty (const std::string& key, const std::string& value) {};
virtual void SetProperty (std::string_view key, std::string_view value) {};
virtual void ClearProperties () {};
AddressesPtr GetAddresses () const; // should be called for local RI only, otherwise must return shared_ptr
std::shared_ptr<const Address> GetNTCP2V4Address () const;
@@ -333,11 +335,12 @@ namespace data
bool LoadFile (const std::string& fullPath);
void ReadFromFile (const std::string& fullPath);
void ReadFromStream (std::istream& s);
bool ReadFromBuffer (const uint8_t * buf, size_t len); // return false if malformed
void ReadFromBuffer (bool verifySignature);
size_t ReadString (char* str, size_t len, std::istream& s) const;
void ExtractCaps (const char * value);
uint8_t ExtractAddressCaps (const char * value) const;
std::string_view ExtractString (const uint8_t * buf, size_t len) const;
std::tuple<std::string_view, std::string_view, size_t> ExtractParam (const uint8_t * buf, size_t len) const;
void ExtractCaps (std::string_view value);
uint8_t ExtractAddressCaps (std::string_view value) const;
void UpdateIntroducers (std::shared_ptr<Address> address, uint64_t ts);
template<typename Filter>
std::shared_ptr<const Address> GetAddress (Filter filter) const;
@@ -379,7 +382,7 @@ namespace data
void UpdateCaps (uint8_t caps);
bool UpdateCongestion (Congestion c); // returns true if updated
void SetProperty (const std::string& key, const std::string& value) override;
void SetProperty (std::string_view key, std::string_view value) override;
void DeleteProperty (const std::string& key);
std::string GetProperty (const std::string& key) const;
void ClearProperties () override { m_Properties.clear (); };

View File

@@ -191,12 +191,7 @@ namespace transport
void SSU2PeerTestSession::SendPeerTest (uint8_t msg, const uint8_t * signedData, size_t signedDataLen, bool delayed)
{
#if __cplusplus >= 202002L // C++20
m_SignedData.assign (signedData, signedData + signedDataLen);
#else
m_SignedData.resize (signedDataLen);
memcpy (m_SignedData.data (), signedData, signedDataLen);
#endif
if (!delayed)
SendPeerTest (msg);
// schedule resend for msgs 5 or 6
@@ -257,7 +252,7 @@ namespace transport
{
// we are Charlie
uint64_t destConnID = htobe64 (((uint64_t)nonce << 32) | nonce); // dest id
uint32_t sourceConnID = ~destConnID;
uint64_t sourceConnID = ~destConnID;
SetSourceConnID (sourceConnID);
SetDestConnID (destConnID);
SetState (eSSU2SessionStateHolePunch);
@@ -313,12 +308,7 @@ namespace transport
void SSU2HolePunchSession::SendHolePunch (const uint8_t * relayResponseBlock, size_t relayResponseBlockLen)
{
#if __cplusplus >= 202002L // C++20
m_RelayResponseBlock.assign (relayResponseBlock, relayResponseBlock + relayResponseBlockLen);
#else
m_RelayResponseBlock.resize (relayResponseBlockLen);
memcpy (m_RelayResponseBlock.data (), relayResponseBlock, relayResponseBlockLen);
#endif
SendHolePunch ();
ScheduleResend ();
}

View File

@@ -189,7 +189,7 @@ namespace transport
if (!asz) return false;
payload[17] = asz;
packet->payloadSize = asz + 18;
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"RelayRequestData", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (session->GetRemoteIdentity ()->GetIdentHash (), 32); // chash
@@ -1965,6 +1965,7 @@ namespace transport
void SSU2Session::HandleRelayRequest (const uint8_t * buf, size_t len)
{
// we are Bob
if (len < 9) return;
auto mts = i2p::util::GetMillisecondsSinceEpoch ();
uint32_t nonce = bufbe32toh (buf + 1); // nonce
uint32_t relayTag = bufbe32toh (buf + 5); // relay tag
@@ -1998,7 +1999,7 @@ namespace transport
packet->payloadSize = r ? CreateRouterInfoBlock (packet->payload, m_MaxPayloadSize - len - 32, r) : 0;
if (!packet->payloadSize && r)
session->SendFragmentedMessage (CreateDatabaseStoreMsg (r));
packet->payloadSize += CreateRelayIntroBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize, buf + 1, len -1);
packet->payloadSize += CreateRelayIntroBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize, buf + 1, len - 1);
if (packet->payloadSize < m_MaxPayloadSize)
packet->payloadSize += CreatePaddingBlock (packet->payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
uint32_t packetNum = session->SendData (packet->payload, packet->payloadSize);
@@ -2013,18 +2014,24 @@ namespace transport
void SSU2Session::HandleRelayIntro (const uint8_t * buf, size_t len, int attempts)
{
// we are Charlie
if (len < 47) return;
SSU2RelayResponseCode code = eSSU2RelayResponseCodeAccept;
boost::asio::ip::udp::endpoint ep;
std::shared_ptr<const i2p::data::RouterInfo::Address> addr;
auto r = i2p::data::netdb.FindRouter (buf + 1); // Alice
if (r)
{
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"RelayRequestData", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (i2p::context.GetIdentHash (), 32); // chash
s.Insert (buf + 33, 14); // nonce, relay tag, timestamp, ver, asz
uint8_t asz = buf[46];
if (asz + 47 + r->GetIdentity ()->GetSignatureLen () > len)
{
LogPrint (eLogWarning, "SSU2: Malformed RelayIntro len=", len);
return;
}
s.Insert (buf + 47, asz); // Alice Port, Alice IP
if (s.Verify (r->GetIdentity (), buf + 47 + asz))
{
@@ -2113,6 +2120,7 @@ namespace transport
void SSU2Session::HandleRelayResponse (const uint8_t * buf, size_t len)
{
if (len < 6) return;
uint32_t nonce = bufbe32toh (buf + 2);
if (m_State == eSSU2SessionStateIntroduced)
{
@@ -2133,7 +2141,9 @@ namespace transport
auto it = m_RelaySessions.find (nonce);
if (it != m_RelaySessions.end ())
{
if (it->second.first && it->second.first->IsEstablished ())
auto relaySession = it->second.first;
m_RelaySessions.erase (it);
if (relaySession && relaySession->IsEstablished ())
{
// we are Bob, message from Charlie
auto packet = m_Server.GetSentPacketsPool ().AcquireShared ();
@@ -2143,12 +2153,12 @@ namespace transport
memcpy (payload + 3, buf, len); // forward to Alice as is
packet->payloadSize = len + 3;
packet->payloadSize += CreatePaddingBlock (payload + packet->payloadSize, m_MaxPayloadSize - packet->payloadSize);
uint32_t packetNum = it->second.first->SendData (packet->payload, packet->payloadSize);
uint32_t packetNum = relaySession->SendData (packet->payload, packet->payloadSize);
if (m_RemoteVersion >= SSU2_MIN_RELAY_RESPONSE_RESEND_VERSION)
{
// sometimes Alice doesn't ack this RelayResponse in older versions
packet->sendTime = i2p::util::GetMillisecondsSinceEpoch ();
it->second.first->m_SentPackets.emplace (packetNum, packet);
relaySession->m_SentPackets.emplace (packetNum, packet);
}
}
else
@@ -2157,25 +2167,31 @@ namespace transport
if (!buf[1]) // status code accepted?
{
// verify signature
uint8_t csz = buf[11];
SignedData s;
uint8_t csz = (len >= 12) ? buf[11] : 0;
if (csz + 12 + relaySession->GetRemoteIdentity ()->GetSignatureLen () > len)
{
LogPrint (eLogWarning, "SSU2: Malformed RelayResponse len=", len);
relaySession->Done ();
return;
}
SignedData<128> s;
s.Insert ((const uint8_t *)"RelayAgreementOK", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (buf + 2, 10 + csz); // nonce, timestamp, ver, csz and Charlie's endpoint
if (s.Verify (it->second.first->GetRemoteIdentity (), buf + 12 + csz))
if (s.Verify (relaySession->GetRemoteIdentity (), buf + 12 + csz))
{
if (it->second.first->m_State == eSSU2SessionStateIntroduced) // HolePunch not received yet
if (relaySession->m_State == eSSU2SessionStateIntroduced) // HolePunch not received yet
{
// update Charlie's endpoint
if (ExtractEndpoint (buf + 12, csz, it->second.first->m_RemoteEndpoint))
if (ExtractEndpoint (buf + 12, csz, relaySession->m_RemoteEndpoint))
{
// update token
uint64_t token;
memcpy (&token, buf + len - 8, 8);
m_Server.UpdateOutgoingToken (it->second.first->m_RemoteEndpoint,
m_Server.UpdateOutgoingToken (relaySession->m_RemoteEndpoint,
token, i2p::util::GetSecondsSinceEpoch () + SSU2_TOKEN_EXPIRATION_TIMEOUT);
// connect to Charlie, HolePunch will be ignored
it->second.first->ConnectAfterIntroduction ();
relaySession->ConnectAfterIntroduction ();
}
else
LogPrint (eLogWarning, "SSU2: RelayResponse can't extract endpoint");
@@ -2184,16 +2200,15 @@ namespace transport
else
{
LogPrint (eLogWarning, "SSU2: RelayResponse signature verification failed");
it->second.first->Done ();
relaySession->Done ();
}
}
else
{
LogPrint (eLogInfo, "SSU2: RelayResponse status code=", (int)buf[1], " nonce=", bufbe32toh (buf + 2));
it->second.first->Done ();
relaySession->Done ();
}
}
m_RelaySessions.erase (it);
}
else
LogPrint (eLogDebug, "SSU2: RelayResponse unknown nonce ", bufbe32toh (buf + 2));
@@ -2265,7 +2280,7 @@ namespace transport
uint8_t asz = buf[offset + 9];
std::vector<uint8_t> newSignedData (asz + 10 + i2p::context.GetIdentity ()->GetSignatureLen ());
memcpy (newSignedData.data (), buf + offset, asz + 10);
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"PeerTestValidate", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (buf + 3, 32); // ahash
@@ -2376,7 +2391,7 @@ namespace transport
if (r)
{
uint8_t asz = buf[offset + 9];
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"PeerTestValidate", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (i2p::context.GetIdentity ()->GetIdentHash (), 32); // ahash
@@ -2762,7 +2777,7 @@ namespace transport
size_t SSU2Session::CreatePaddingBlock (uint8_t * buf, size_t len, size_t minSize)
{
if (len < 3 || len < minSize) return 0;
size_t paddingSize = m_Server.GetRng ()() & 0x0F; // 0 - 15
size_t paddingSize = m_Server.GetRng ()() & 0x1F; // 0 - 31
if (paddingSize + 3 > len) paddingSize = len - 3;
else if (paddingSize + 3 < minSize) paddingSize = minSize - 3;
buf[0] = eSSU2BlkPadding;
@@ -2864,7 +2879,7 @@ namespace transport
LogPrint (eLogError, "SSU2: Buffer for RelayResponse signature is too small ", len);
return 0;
}
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"RelayAgreementOK", 16); // prologue
if (code == eSSU2RelayResponseCodeAccept || code >= 64) // Charlie
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
@@ -2926,7 +2941,7 @@ namespace transport
size_t asz = CreateEndpoint (signedData + 10, 86, boost::asio::ip::udp::endpoint (localAddress->host, localAddress->port));
signedData[9] = asz;
// signature
SignedData s;
SignedData<128> s;
s.Insert ((const uint8_t *)"PeerTestValidate", 16); // prologue
s.Insert (GetRemoteIdentity ()->GetIdentHash (), 32); // bhash
s.Insert (signedData, 10 + asz); // ver, nonce, ts, asz, Alice's endpoint

View File

@@ -1297,7 +1297,7 @@ namespace stream
m_NumPacketsToSend = 1; m_PacingTimeRem = 0;
}
m_IsSendTime = true;
if (m_WindowIncCounter && (m_WindowSize < MAX_WINDOW_SIZE || m_WindowDropTargetSize) && !m_SendBuffer.IsEmpty () && m_PacingTime > m_MinPacingTime)
if (m_WindowIncCounter && (m_WindowSize < MAX_WINDOW_SIZE || m_WindowDropTargetSize) && !m_SendBuffer.IsEmpty () && m_PacingTime > m_MinPacingTime && m_RTT <= m_SlowRTT)
{
for (int i = 0; i < m_NumPacketsToSend; i++)
{
@@ -1307,7 +1307,7 @@ namespace stream
{
if (m_LastWindowDropSize && (m_LastWindowDropSize >= m_WindowDropTargetSize))
m_WindowDropTargetSize += 1 - (1 / ((m_LastWindowDropSize + PREV_SPEED_KEEP_TIME_COEFF) / m_WindowDropTargetSize)); // some magic here
else if (m_LastWindowDropSize && (m_LastWindowDropSize < m_WindowSize))
else if (m_LastWindowDropSize && (m_LastWindowDropSize < m_WindowDropTargetSize))
m_WindowDropTargetSize += (m_WindowDropTargetSize - (m_LastWindowDropSize - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowDropTargetSize; // some magic here
else
m_WindowDropTargetSize += (m_WindowDropTargetSize - (1 - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowDropTargetSize;
@@ -1646,14 +1646,22 @@ namespace stream
void Stream::ProcessWindowDrop ()
{
if (m_WindowSize > m_LastWindowDropSize)
{
m_LastWindowDropSize = (m_LastWindowDropSize + m_WindowSize + m_WindowSizeTail) / 2;
if (m_LastWindowDropSize > MAX_WINDOW_SIZE) m_LastWindowDropSize = MAX_WINDOW_SIZE;
}
if (m_WindowDropTargetSize)
m_WindowDropTargetSize = (m_WindowDropTargetSize / 2) * 0.75; // congestion window size and -25% to drain queue
else
m_LastWindowDropSize = m_WindowSize;
m_WindowDropTargetSize = m_LastWindowDropSize - (m_LastWindowDropSize / 4); // -25%;
{
if (m_WindowSize < m_LastWindowDropSize)
{
m_LastWindowDropSize = m_WindowSize - (m_LastWindowDropSize - m_WindowSize);
if (m_LastWindowDropSize < MIN_WINDOW_SIZE) m_LastWindowDropSize = MIN_WINDOW_SIZE;
}
else
{
m_LastWindowDropSize = (m_LastWindowDropSize + m_WindowSize + m_WindowSizeTail) / 2;
if (m_LastWindowDropSize > MAX_WINDOW_SIZE) m_LastWindowDropSize = MAX_WINDOW_SIZE;
}
m_WindowDropTargetSize = m_LastWindowDropSize * 0.75; // -25% to drain queue
}
if (m_WindowDropTargetSize < MIN_WINDOW_SIZE)
m_WindowDropTargetSize = MIN_WINDOW_SIZE;
m_WindowIncCounter = 0; // disable window growth

View File

@@ -1,5 +1,5 @@
/*
* Copyright (c) 2013-2024, The PurpleI2P Project
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
@@ -10,7 +10,7 @@
#define TRANSPORT_SESSION_H__
#include <inttypes.h>
#include <iostream>
#include <string.h>
#include <memory>
#include <vector>
#include <mutex>
@@ -28,45 +28,51 @@ namespace transport
const size_t IPV6_HEADER_SIZE = 40;
const size_t UDP_HEADER_SIZE = 8;
template<size_t sz>
class SignedData
{
public:
SignedData () {}
SignedData (): m_Size(0) {}
SignedData (const SignedData& other)
{
m_Stream << other.m_Stream.rdbuf ();
m_Size = other.m_Size;
memcpy (m_Buf, other.m_Buf, m_Size);
}
void Reset ()
{
m_Stream.str("");
m_Size = 0;
}
void Insert (const uint8_t * buf, size_t len)
size_t Insert (const uint8_t * buf, size_t len)
{
m_Stream.write ((char *)buf, len);
if (m_Size + len > sz) len = sz - m_Size;
memcpy (m_Buf + m_Size, buf, len);
m_Size += len;
return len;
}
template<typename T>
void Insert (T t)
{
m_Stream.write ((char *)&t, sizeof (T));
Insert ((const uint8_t *)&t, sizeof (T));
}
bool Verify (std::shared_ptr<const i2p::data::IdentityEx> ident, const uint8_t * signature) const
{
return ident->Verify ((const uint8_t *)m_Stream.str ().c_str (), m_Stream.str ().size (), signature);
return ident->Verify (m_Buf, m_Size, signature);
}
void Sign (const i2p::data::PrivateKeys& keys, uint8_t * signature) const
{
keys.Sign ((const uint8_t *)m_Stream.str ().c_str (), m_Stream.str ().size (), signature);
keys.Sign (m_Buf, m_Size, signature);
}
private:
std::stringstream m_Stream;
uint8_t m_Buf[sz];
size_t m_Size;
};
const int64_t TRANSPORT_SESSION_SLOWNESS_THRESHOLD = 500; // in milliseconds

View File

@@ -571,7 +571,7 @@ namespace client
m_IsSending = false;
}
std::string_view I2CPSession::ExtractString (const uint8_t * buf, size_t len)
std::string_view I2CPSession::ExtractString (const uint8_t * buf, size_t len) const
{
uint8_t l = buf[0];
if (l > len) l = len;
@@ -588,7 +588,7 @@ namespace client
return l + 1;
}
void I2CPSession::ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping)
void I2CPSession::ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping) const
// TODO: move to Base.cpp
{
size_t offset = 0;

View File

@@ -194,9 +194,9 @@ namespace client
void HandleI2CPMessageSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
std::string_view ExtractString (const uint8_t * buf, size_t len);
std::string_view ExtractString (const uint8_t * buf, size_t len) const;
size_t PutString (uint8_t * buf, size_t len, std::string_view str);
void ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping);
void ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping) const;
void SendSessionStatusMessage (I2CPSessionStatus status);
void SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity);