Merge branch 'openssl' into BandwithParameter

This commit is contained in:
🜃 Ezor Kael 2025-08-18 19:50:54 +07:00 committed by GitHub
commit b3d566c6f2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 357 additions and 213 deletions

View file

@ -3,7 +3,7 @@ CXXFLAGS ?= ${CXX_DEBUG} -Wall -Wextra -Wno-unused-parameter -pedantic -Wno-misl
DEFINES = -D_GLIBCXX_USE_NANOSLEEP=1 DEFINES = -D_GLIBCXX_USE_NANOSLEEP=1
INCFLAGS = -I/usr/include/ -I/usr/local/include/ INCFLAGS = -I/usr/include/ -I/usr/local/include/
LDFLAGS = ${LD_DEBUG} -Wl,-rpath,/usr/local/lib -L/usr/local/lib LDFLAGS = ${LD_DEBUG} -Wl,-rpath,/usr/local/lib -L/usr/local/lib
LDLIBS = -lssl -lcrypto -lz -lpthread -lboost_system -lboost_program_options LDLIBS = -lssl -lcrypto -lz -lpthread -lboost_program_options
## NOTE: NEEDED_CXXFLAGS is here so that custom CXXFLAGS can be specified at build time ## NOTE: NEEDED_CXXFLAGS is here so that custom CXXFLAGS can be specified at build time
## **without** overwriting the CXXFLAGS which we need in order to build. ## **without** overwriting the CXXFLAGS which we need in order to build.

View file

@ -18,7 +18,7 @@ endif
LDLIBS += -lpthread -ldl LDLIBS += -lpthread -ldl
else else
LDFLAGS += -L${SSLROOT}/lib -L${BOOSTROOT}/lib LDFLAGS += -L${SSLROOT}/lib -L${BOOSTROOT}/lib
LDLIBS = -lz -lssl -lcrypto -lboost_system -lboost_filesystem -lboost_program_options -lpthread LDLIBS = -lz -lssl -lcrypto -lboost_program_options -lpthread
ifeq ($(USE_UPNP),yes) ifeq ($(USE_UPNP),yes)
LDFLAGS += -L${UPNPROOT}/lib LDFLAGS += -L${UPNPROOT}/lib
LDLIBS += -lminiupnpc LDLIBS += -lminiupnpc

View file

@ -9,7 +9,7 @@ LDFLAGS += -Wl,-dead_strip_dylibs
ifeq ($(USE_STATIC),yes) ifeq ($(USE_STATIC),yes)
LDLIBS = -lz /usr/local/lib/libssl.a /usr/local/lib/libcrypto.a /usr/local/lib/libboost_system.a /usr/local/lib/libboost_filesystem.a /usr/local/lib/libboost_program_options.a -lpthread LDLIBS = -lz /usr/local/lib/libssl.a /usr/local/lib/libcrypto.a /usr/local/lib/libboost_system.a /usr/local/lib/libboost_filesystem.a /usr/local/lib/libboost_program_options.a -lpthread
else else
LDLIBS = -lz -lssl -lcrypto -lboost_system -lboost_filesystem -lboost_program_options -lpthread LDLIBS = -lz -lssl -lcrypto -lboost_program_options -lpthread
endif endif
ifeq ($(USE_UPNP),yes) ifeq ($(USE_UPNP),yes)

View file

@ -44,7 +44,7 @@
namespace i2p { namespace i2p {
namespace http { namespace http {
static void LoadExtCSS (std::string fileName = "style.css") static void LoadExtCSS (std::string fileName = "style")
{ {
std::stringstream s; std::stringstream s;
std::string styleFile = i2p::fs::DataDirPath ("webconsole/"+fileName+".css"); std::string styleFile = i2p::fs::DataDirPath ("webconsole/"+fileName+".css");
@ -971,7 +971,8 @@ namespace http {
for (auto& it: sam->GetSessions ()) for (auto& it: sam->GetSessions ())
{ {
auto& name = it.second->GetLocalDestination ()->GetNickname (); auto& name = it.second->GetLocalDestination ()->GetNickname ();
s << "<div class=\"listitem\"><a href=\"" << webroot << "?page=" << HTTP_PAGE_SAM_SESSION << "&sam_id=" << it.first << "\">"; auto sam_id = i2p::data::ByteStreamToBase64 ((const uint8_t *)it.first.data (), it.first.length ()); // base64, becuase session name might be UTF-8
s << "<div class=\"listitem\"><a href=\"" << webroot << "?page=" << HTTP_PAGE_SAM_SESSION << "&sam_id=" << sam_id << "\">";
s << name << " (" << it.first << ")</a></div>\r\n" << std::endl; s << name << " (" << it.first << ")</a></div>\r\n" << std::endl;
} }
s << "</div>\r\n"; s << "</div>\r\n";
@ -983,13 +984,26 @@ namespace http {
void ShowSAMSession (std::stringstream& s, const std::string& id) void ShowSAMSession (std::stringstream& s, const std::string& id)
{ {
auto sam = i2p::client::context.GetSAMBridge (); auto sam = i2p::client::context.GetSAMBridge ();
if (!sam) { if (!sam)
{
ShowError(s, tr("SAM disabled")); ShowError(s, tr("SAM disabled"));
return; return;
} }
if (id.empty ())
auto session = sam->FindSession (id); {
if (!session) { ShowError(s, tr("No sam_id"));
return;
}
std::vector<uint8_t> sam_id(id.length ()); // id is in base64
size_t l = i2p::data::Base64ToByteStream (id, sam_id.data (), sam_id.size ());
if (!l)
{
ShowError(s, tr("Invalid sam_id"));
return;
}
auto session = sam->FindSession ( { (const char *)sam_id.data (), l });
if (!session)
{
ShowError(s, tr("SAM session not found")); ShowError(s, tr("SAM session not found"));
return; return;
} }
@ -1001,7 +1015,7 @@ namespace http {
s << i2p::client::context.GetAddressBook ().ToAddress(ident) << "</a></div>\r\n"; s << i2p::client::context.GetAddressBook ().ToAddress(ident) << "</a></div>\r\n";
s << "<br>\r\n"; s << "<br>\r\n";
s << "<b>" << tr("Streams") << ":</b><br>\r\n<div class=\"list\">\r\n"; s << "<b>" << tr("Streams") << ":</b><br>\r\n<div class=\"list\">\r\n";
for (const auto& it: sam->ListSockets(id)) for (const auto& it: sam->ListSockets({ (const char *)sam_id.data (), l }))
{ {
s << "<div class=\"listitem\">"; s << "<div class=\"listitem\">";
switch (it->GetSocketType ()) switch (it->GetSocketType ())

View file

@ -60,28 +60,49 @@ namespace datagram
{ {
if (session) if (session)
{ {
if (session->GetVersion () == eDatagramV3) std::shared_ptr<I2NPMessage> msg;
switch (session->GetVersion ())
{ {
constexpr uint8_t flags[] = { 0x00, 0x03 }; // datagram3, no options case eDatagramV3:
auto msg = CreateDataMessage ({{m_Owner->GetIdentity ()->GetIdentHash (), 32},
{flags, 2}, {payload, len}}, fromPort, toPort, i2p::client::PROTOCOL_TYPE_DATAGRAM3, false); // datagram3
session->SendMsg(msg);
}
else
{
if (m_Owner->GetIdentity ()->GetSigningKeyType () == i2p::data::SIGNING_KEY_TYPE_DSA_SHA1)
{ {
uint8_t hash[32]; constexpr uint8_t flags[] = { 0x00, 0x03 }; // datagram3, no options
SHA256(payload, len, hash); msg = CreateDataMessage ({{m_Owner->GetIdentity ()->GetIdentHash (), 32},
m_Owner->Sign (hash, 32, m_Signature.data ()); {flags, 2}, {payload, len}}, fromPort, toPort, i2p::client::PROTOCOL_TYPE_DATAGRAM3, false); // datagram3
break;
} }
else case eDatagramV1:
m_Owner->Sign (payload, len, m_Signature.data ()); {
if (m_Owner->GetIdentity ()->GetSigningKeyType () == i2p::data::SIGNING_KEY_TYPE_DSA_SHA1)
{
uint8_t hash[32];
SHA256(payload, len, hash);
m_Owner->Sign (hash, 32, m_Signature.data ());
}
else
m_Owner->Sign (payload, len, m_Signature.data ());
msg = CreateDataMessage ({{m_From.data (), m_From.size ()}, {m_Signature.data (), m_Signature.size ()}, {payload, len}},
fromPort, toPort, i2p::client::PROTOCOL_TYPE_DATAGRAM, !session->IsRatchets ()); // datagram1
break;
}
case eDatagramV2:
{
constexpr uint8_t flags[] = { 0x00, 0x02 }; // datagram2, no options
// signature
std::vector<uint8_t> signedData (len + 32 + 2);
memcpy (signedData.data (), m_Owner->GetIdentity ()->GetIdentHash (), 32);
memcpy (signedData.data () + 32, flags, 2);
memcpy (signedData.data () + 34, payload, len);
m_Owner->Sign (signedData.data (), signedData.size (), m_Signature.data ());
// TODO: offline signatures and options
msg = CreateDataMessage ({{m_From.data (), m_From.size ()}, {flags, 2}, {payload, len},
{m_Signature.data (), m_Signature.size ()}}, fromPort, toPort, i2p::client::PROTOCOL_TYPE_DATAGRAM2, false); // datagram2
auto msg = CreateDataMessage ({{m_From.data (), m_From.size ()}, {m_Signature.data (), m_Signature.size ()}, {payload, len}}, break;
fromPort, toPort, i2p::client::PROTOCOL_TYPE_DATAGRAM, !session->IsRatchets ()); // datagram1 }
session->SendMsg(msg); default:
LogPrint (eLogError, "Datagram: datagram type ", (int)session->GetVersion (), " is not supported");
} }
if (msg) session->SendMsg(msg);
} }
} }

View file

@ -11,6 +11,7 @@
#include <string> #include <string>
#include <set> #include <set>
#include <vector> #include <vector>
#include <charconv>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include "Crypto.h" #include "Crypto.h"
#include "ECIESX25519AEADRatchetSession.h" #include "ECIESX25519AEADRatchetSession.h"
@ -93,10 +94,8 @@ namespace client
} }
it = params->find (I2CP_PARAM_DONT_PUBLISH_LEASESET); it = params->find (I2CP_PARAM_DONT_PUBLISH_LEASESET);
if (it != params->end ()) if (it != params->end ())
{
// override isPublic // override isPublic
m_IsPublic = (it->second != "true"); m_IsPublic = GetBoolParamValue (it->second);
}
it = params->find (I2CP_PARAM_LEASESET_TYPE); it = params->find (I2CP_PARAM_LEASESET_TYPE);
if (it != params->end ()) if (it != params->end ())
m_LeaseSetType = std::stoi(it->second); m_LeaseSetType = std::stoi(it->second);
@ -188,6 +187,24 @@ namespace client
CleanUp (); // GarlicDestination CleanUp (); // GarlicDestination
} }
bool LeaseSetDestination::GetBoolParamValue (std::string_view value)
{
bool ret = false;
if (value == "true")
ret = true;
else if (value == "false")
ret = false;
else
{
int v = 0;
auto res = std::from_chars(value.data(), value.data() + value.size(), v);
if (res.ec != std::errc())
LogPrint (eLogError, "Destination: Unable to parse bool param value ", value, ": ", std::make_error_code (res.ec).message ());
ret = v;
}
return ret;
}
bool LeaseSetDestination::Reconfigure(std::map<std::string, std::string> params) bool LeaseSetDestination::Reconfigure(std::map<std::string, std::string> params)
{ {
auto itr = params.find("i2cp.dontPublishLeaseSet"); auto itr = params.find("i2cp.dontPublishLeaseSet");
@ -1010,9 +1027,9 @@ namespace client
m_StreamingInboundSpeed (DEFAULT_MAX_INBOUND_SPEED), m_StreamingInboundSpeed (DEFAULT_MAX_INBOUND_SPEED),
m_StreamingMaxConcurrentStreams (DEFAULT_MAX_CONCURRENT_STREAMS), m_StreamingMaxConcurrentStreams (DEFAULT_MAX_CONCURRENT_STREAMS),
m_StreamingMaxWindowSize (i2p::stream::MAX_WINDOW_SIZE), m_StreamingMaxWindowSize (i2p::stream::MAX_WINDOW_SIZE),
m_IsStreamingAnswerPings (DEFAULT_ANSWER_PINGS), m_LastPort (0), m_IsStreamingAnswerPings (DEFAULT_ANSWER_PINGS), m_IsStreamingDontSign (DEFAULT_DONT_SIGN),
m_DatagramDestination (nullptr), m_RefCounter (0), m_LastPublishedTimestamp (0), m_LastPort (0), m_DatagramDestination (nullptr), m_RefCounter (0),
m_ReadyChecker(service) m_LastPublishedTimestamp (0), m_ReadyChecker(service)
{ {
if (keys.IsOfflineSignature () && GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_LEASESET) if (keys.IsOfflineSignature () && GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_LEASESET)
SetLeaseSetType (i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2); // offline keys can be published with LS2 only SetLeaseSetType (i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2); // offline keys can be published with LS2 only
@ -1096,15 +1113,10 @@ namespace client
} }
it = params->find (I2CP_PARAM_STREAMING_ANSWER_PINGS); it = params->find (I2CP_PARAM_STREAMING_ANSWER_PINGS);
if (it != params->end ()) if (it != params->end ())
{ m_IsStreamingAnswerPings = GetBoolParamValue (it->second);
LogPrint (eLogDebug, "Destination: Reading parameter ", I2CP_PARAM_STREAMING_ANSWER_PINGS, " value ", it->second); it = params->find (I2CP_PARAM_STREAMING_DONT_SIGN);
if (it->second == "true") if (it != params->end ())
m_IsStreamingAnswerPings = true; m_IsStreamingDontSign = GetBoolParamValue (it->second);
else if (it->second == "false")
m_IsStreamingAnswerPings = false;
else
m_IsStreamingAnswerPings = std::stoi (it->second); // 1 for true
}
if (GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2) if (GetLeaseSetType () == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2)
{ {

View file

@ -102,6 +102,8 @@ namespace client
const char I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS[] = "i2p.streaming.maxConcurrentStreams"; const char I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS[] = "i2p.streaming.maxConcurrentStreams";
const int DEFAULT_MAX_CONCURRENT_STREAMS = 2048; const int DEFAULT_MAX_CONCURRENT_STREAMS = 2048;
const char I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE[] = "i2p.streaming.maxWindowSize"; const char I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE[] = "i2p.streaming.maxWindowSize";
const char I2CP_PARAM_STREAMING_DONT_SIGN[] = "i2p.streaming.dontSign";
const int DEFAULT_DONT_SIGN = false;
typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete; typedef std::function<void (std::shared_ptr<i2p::stream::Stream> stream)> StreamRequestComplete;
@ -174,6 +176,7 @@ namespace client
int GetLeaseSetType () const { return m_LeaseSetType; }; int GetLeaseSetType () const { return m_LeaseSetType; };
void SetLeaseSetType (int leaseSetType) { m_LeaseSetType = leaseSetType; }; void SetLeaseSetType (int leaseSetType) { m_LeaseSetType = leaseSetType; };
int GetAuthType () const { return m_AuthType; }; int GetAuthType () const { return m_AuthType; };
static bool GetBoolParamValue (std::string_view value);
virtual void CleanupDestination () {}; // additional clean up in derived classes virtual void CleanupDestination () {}; // additional clean up in derived classes
virtual i2p::data::CryptoKeyType GetPreferredCryptoType () const = 0; virtual i2p::data::CryptoKeyType GetPreferredCryptoType () const = 0;
// I2CP // I2CP
@ -272,6 +275,7 @@ namespace client
int GetStreamingInboundSpeed () const { return m_StreamingInboundSpeed; } int GetStreamingInboundSpeed () const { return m_StreamingInboundSpeed; }
int GetStreamingMaxConcurrentStreams () const { return m_StreamingMaxConcurrentStreams; } int GetStreamingMaxConcurrentStreams () const { return m_StreamingMaxConcurrentStreams; }
bool IsStreamingAnswerPings () const { return m_IsStreamingAnswerPings; } bool IsStreamingAnswerPings () const { return m_IsStreamingAnswerPings; }
bool IsStreamingDontSign () const { return m_IsStreamingDontSign; }
int GetStreamingMaxWindowSize () const { return m_StreamingMaxWindowSize; } int GetStreamingMaxWindowSize () const { return m_StreamingMaxWindowSize; }
// datagram // datagram
@ -314,7 +318,7 @@ namespace client
i2p::data::CryptoKeyType m_PreferredCryptoType; i2p::data::CryptoKeyType m_PreferredCryptoType;
int m_StreamingAckDelay,m_StreamingOutboundSpeed, m_StreamingInboundSpeed, m_StreamingMaxConcurrentStreams, m_StreamingMaxWindowSize; int m_StreamingAckDelay,m_StreamingOutboundSpeed, m_StreamingInboundSpeed, m_StreamingMaxConcurrentStreams, m_StreamingMaxWindowSize;
bool m_IsStreamingAnswerPings; bool m_IsStreamingAnswerPings, m_IsStreamingDontSign;
std::shared_ptr<i2p::stream::StreamingDestination> m_StreamingDestination; // default std::shared_ptr<i2p::stream::StreamingDestination> m_StreamingDestination; // default
std::map<uint16_t, std::shared_ptr<i2p::stream::StreamingDestination> > m_StreamingDestinationsByPorts; std::map<uint16_t, std::shared_ptr<i2p::stream::StreamingDestination> > m_StreamingDestinationsByPorts;
std::shared_ptr<i2p::stream::StreamingDestination> m_LastStreamingDestination; uint16_t m_LastPort; // for server tunnels std::shared_ptr<i2p::stream::StreamingDestination> m_LastStreamingDestination; uint16_t m_LastPort; // for server tunnels

View file

@ -41,7 +41,7 @@ namespace data
const int NETDB_MIN_ROUTERS = 90; const int NETDB_MIN_ROUTERS = 90;
const int NETDB_MIN_FLOODFILLS = 5; const int NETDB_MIN_FLOODFILLS = 5;
const int NETDB_MIN_TRANSPORTS = 10 ; // otherwise assume offline const int NETDB_MIN_TRANSPORTS = 10 ; // otherwise assume offline
const int NETDB_NUM_FLOODFILLS_THRESHOLD = 1500; const int NETDB_NUM_FLOODFILLS_THRESHOLD = 1800;
const int NETDB_NUM_ROUTERS_THRESHOLD = 4*NETDB_NUM_FLOODFILLS_THRESHOLD; const int NETDB_NUM_ROUTERS_THRESHOLD = 4*NETDB_NUM_FLOODFILLS_THRESHOLD;
const int NETDB_TUNNEL_CREATION_RATE_THRESHOLD = 10; // in % const int NETDB_TUNNEL_CREATION_RATE_THRESHOLD = 10; // in %
const int NETDB_CHECK_FOR_EXPIRATION_UPTIME = 600; // 10 minutes, in seconds const int NETDB_CHECK_FOR_EXPIRATION_UPTIME = 600; // 10 minutes, in seconds

View file

@ -34,7 +34,11 @@ namespace transport
const int SSU2_RESEND_CHECK_MORE_TIMEOUT_VARIANCE = 9; // in milliseconds const int SSU2_RESEND_CHECK_MORE_TIMEOUT_VARIANCE = 9; // in milliseconds
const size_t SSU2_MAX_RESEND_PACKETS = 128; // packets to resend at the time const size_t SSU2_MAX_RESEND_PACKETS = 128; // packets to resend at the time
const uint64_t SSU2_SOCKET_MIN_BUFFER_SIZE = 128 * 1024; const uint64_t SSU2_SOCKET_MIN_BUFFER_SIZE = 128 * 1024;
#if defined(__OpenBSD__)
const uint64_t SSU2_SOCKET_MAX_BUFFER_SIZE = 2 * 1024 * 1024;
#else
const uint64_t SSU2_SOCKET_MAX_BUFFER_SIZE = 4 * 1024 * 1024; const uint64_t SSU2_SOCKET_MAX_BUFFER_SIZE = 4 * 1024 * 1024;
#endif
const size_t SSU2_MAX_NUM_INTRODUCERS = 3; const size_t SSU2_MAX_NUM_INTRODUCERS = 3;
const size_t SSU2_MIN_RECEIVED_PACKET_SIZE = 40; // 16 byte short header + 8 byte minimum payload + 16 byte MAC const size_t SSU2_MIN_RECEIVED_PACKET_SIZE = 40; // 16 byte short header + 8 byte minimum payload + 16 byte MAC
const size_t SSU2_MAX_RECEIVED_QUEUE_SIZE = 2500; // in packets const size_t SSU2_MAX_RECEIVED_QUEUE_SIZE = 2500; // in packets

View file

@ -91,16 +91,18 @@ namespace stream
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true),
m_IsWinDropped (true), m_IsChoking2 (false), m_IsClientChoked (false), m_IsClientChoked2 (false), m_IsWinDropped (true), m_IsChoking2 (false), m_IsClientChoked (false), m_IsClientChoked2 (false),
m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false), m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false),
m_IsBufferEmpty (false), m_IsJavaClient (false), m_LocalDestination (local), m_IsBufferEmpty (false), m_IsJavaClient (false), m_DontSign (local.GetOwner ()->IsStreamingDontSign ()),
m_RemoteLeaseSet (remote), m_ReceiveTimer (m_Service), m_SendTimer (m_Service), m_ResendTimer (m_Service), m_LocalDestination (local), m_RemoteLeaseSet (remote), m_ReceiveTimer (m_Service),
m_AckSendTimer (m_Service), m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (port), m_SendTimer (m_Service), m_ResendTimer (m_Service), m_AckSendTimer (m_Service), m_NumSentBytes (0),
m_RTT (INITIAL_RTT), m_MinRTT (INITIAL_RTT), m_SlowRTT (INITIAL_RTT), m_FastRTT (INITIAL_RTT), m_NumReceivedBytes (0), m_Port (port), m_RTT (INITIAL_RTT), m_MinRTT (INITIAL_RTT),
m_WindowSize (INITIAL_WINDOW_SIZE), m_MaxWindowSize (local.GetOwner ()->GetStreamingMaxWindowSize ()), m_SlowRTT (INITIAL_RTT), m_FastRTT (INITIAL_RTT), m_WindowSize (INITIAL_WINDOW_SIZE),
m_LastWindowDropSize (0), m_WindowDropTargetSize (0), m_WindowIncCounter (0), m_RTO (INITIAL_RTO), m_MaxWindowSize (local.GetOwner ()->GetStreamingMaxWindowSize ()), m_LastWindowDropSize (0),
m_WindowDropTargetSize (0), m_WindowIncCounter (0), m_RTO (INITIAL_RTO),
m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()), m_PrevRTTSample (INITIAL_RTT), m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()), m_PrevRTTSample (INITIAL_RTT),
m_Jitter (0), m_MinPacingTime (0), m_Jitter (0), m_MinPacingTime (0), m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0),
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()), m_RemoteLeaseChangeTime (0), m_LastWindowIncTime (0), m_LastACKRequestTime (0), m_LastSendTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()),
m_LastACKSendTime (0), m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed m_RemoteLeaseChangeTime (0), m_LastWindowIncTime (0), m_LastACKRequestTime (0), m_LastACKSendTime (0),
m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed
m_NumResendAttempts (0), m_NumPacketsToSend (0), m_JitterAccum (0), m_JitterDiv (1), m_MTU (STREAMING_MTU) m_NumResendAttempts (0), m_NumPacketsToSend (0), m_JitterAccum (0), m_JitterDiv (1), m_MTU (STREAMING_MTU)
{ {
RAND_bytes ((uint8_t *)&m_RecvStreamID, 4); RAND_bytes ((uint8_t *)&m_RecvStreamID, 4);
@ -122,14 +124,16 @@ namespace stream
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true),
m_IsWinDropped (true), m_IsChoking2 (false), m_IsClientChoked (false), m_IsClientChoked2 (false), m_IsWinDropped (true), m_IsChoking2 (false), m_IsClientChoked (false), m_IsClientChoked2 (false),
m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false), m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false),
m_IsBufferEmpty (false), m_IsJavaClient (false), m_LocalDestination (local), m_IsBufferEmpty (false), m_IsJavaClient (false), m_DontSign (local.GetOwner ()->IsStreamingDontSign ()),
m_ReceiveTimer (m_Service), m_SendTimer (m_Service), m_ResendTimer (m_Service), m_AckSendTimer (m_Service), m_LocalDestination (local),m_ReceiveTimer (m_Service), m_SendTimer (m_Service),
m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (0), m_RTT (INITIAL_RTT), m_MinRTT (INITIAL_RTT), m_SlowRTT (INITIAL_RTT), m_FastRTT (INITIAL_RTT), m_ResendTimer (m_Service), m_AckSendTimer (m_Service),m_NumSentBytes (0), m_NumReceivedBytes (0),
m_Port (0), m_RTT (INITIAL_RTT), m_MinRTT (INITIAL_RTT), m_SlowRTT (INITIAL_RTT), m_FastRTT (INITIAL_RTT),
m_WindowSize (INITIAL_WINDOW_SIZE), m_MaxWindowSize (local.GetOwner ()->GetStreamingMaxWindowSize ()), m_WindowSize (INITIAL_WINDOW_SIZE), m_MaxWindowSize (local.GetOwner ()->GetStreamingMaxWindowSize ()),
m_LastWindowDropSize (0), m_WindowDropTargetSize (0), m_WindowIncCounter (0), m_LastWindowDropSize (0), m_WindowDropTargetSize (0), m_WindowIncCounter (0), m_RTO (INITIAL_RTO),
m_RTO (INITIAL_RTO), m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()), m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()),m_PrevRTTSample (INITIAL_RTT), m_Jitter (0),
m_PrevRTTSample (INITIAL_RTT), m_Jitter (0), m_MinPacingTime (0), m_MinPacingTime (0), m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0),
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()), m_RemoteLeaseChangeTime (0), m_LastWindowIncTime (0), m_LastACKRequestTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()),
m_RemoteLeaseChangeTime (0), m_LastWindowIncTime (0), m_LastACKRequestTime (0),
m_LastACKSendTime (0), m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed m_LastACKSendTime (0), m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed
m_NumResendAttempts (0), m_NumPacketsToSend (0), m_JitterAccum (0), m_JitterDiv (1), m_MTU (STREAMING_MTU) m_NumResendAttempts (0), m_NumPacketsToSend (0), m_JitterAccum (0), m_JitterDiv (1), m_MTU (STREAMING_MTU)
{ {
@ -457,9 +461,10 @@ namespace stream
optionData += 2; optionData += 2;
} }
bool sessionVerified = false; bool verified = true;
if (flags & PACKET_FLAG_FROM_INCLUDED) if (flags & PACKET_FLAG_FROM_INCLUDED)
{ {
verified = false;
if (m_RemoteLeaseSet) m_RemoteIdentity = m_RemoteLeaseSet->GetIdentity (); if (m_RemoteLeaseSet) m_RemoteIdentity = m_RemoteLeaseSet->GetIdentity ();
if (!m_RemoteIdentity) if (!m_RemoteIdentity)
m_RemoteIdentity = std::make_shared<i2p::data::IdentityEx>(optionData, optionSize); m_RemoteIdentity = std::make_shared<i2p::data::IdentityEx>(optionData, optionSize);
@ -486,7 +491,9 @@ namespace stream
m_RemoteIdentity->GetIdentHash ().ToBase32 ()); m_RemoteIdentity->GetIdentHash ().ToBase32 ());
return false; return false;
} }
sessionVerified = true; verified = true;
if (!(flags & PACKET_FLAG_SIGNATURE_INCLUDED))
m_DontSign = true; // don't sign if the remote didn't sign
} }
} }
@ -497,6 +504,30 @@ namespace stream
optionData += 2; optionData += 2;
} }
if (flags & (PACKET_FLAG_CLOSE | PACKET_FLAG_RESET))
{
verified = false;
if (packet->from)
{
if (!m_RemoteLeaseSet && m_RemoteIdentity)
m_RemoteLeaseSet = m_LocalDestination.GetOwner ()->FindLeaseSet (m_RemoteIdentity->GetIdentHash ());
if (m_RemoteLeaseSet)
{
uint8_t staticKey[32];
m_RemoteLeaseSet->Encrypt (nullptr, staticKey);
if (memcmp (packet->from->GetRemoteStaticKey (), staticKey, 32))
{
LogPrint (eLogError, "Streaming: Remote LeaseSet static key mismatch for stream from ",
m_RemoteIdentity->GetIdentHash ().ToBase32 ());
return false;
}
verified = true;
}
else // invalid stream, safe to close
verified = true;
}
}
if (flags & PACKET_FLAG_OFFLINE_SIGNATURE) if (flags & PACKET_FLAG_OFFLINE_SIGNATURE)
{ {
if (!m_RemoteIdentity) if (!m_RemoteIdentity)
@ -504,7 +535,7 @@ namespace stream
LogPrint (eLogInfo, "Streaming: offline signature without identity"); LogPrint (eLogInfo, "Streaming: offline signature without identity");
return false; return false;
} }
if (sessionVerified) if (verified)
{ {
// skip offline signature // skip offline signature
optionData += 4; // timestamp optionData += 4; // timestamp
@ -552,7 +583,6 @@ namespace stream
LogPrint (eLogError, "Streaming: Signature too big, ", signatureLen, " bytes"); LogPrint (eLogError, "Streaming: Signature too big, ", signatureLen, " bytes");
return false; return false;
} }
bool verified = sessionVerified;
if (!verified) // packet was not verified through session if (!verified) // packet was not verified through session
{ {
// verify actual signature // verify actual signature
@ -587,6 +617,11 @@ namespace stream
return false; return false;
} }
} }
if (!verified)
{
LogPrint (eLogError, "Streaming: Missing signature, sSID=", m_SendStreamID, ", rSID=", m_RecvStreamID);
return false;
}
if (immediateAckRequested) if (immediateAckRequested)
SendQuickAck (); SendQuickAck ();
return true; return true;
@ -942,8 +977,8 @@ namespace stream
m_RoutingSession = m_LocalDestination.GetOwner ()->GetRoutingSession (m_RemoteLeaseSet, true, !m_IsIncoming); m_RoutingSession = m_LocalDestination.GetOwner ()->GetRoutingSession (m_RemoteLeaseSet, true, !m_IsIncoming);
m_MTU = (m_RoutingSession && m_RoutingSession->IsRatchets ()) ? STREAMING_MTU_RATCHETS : STREAMING_MTU; m_MTU = (m_RoutingSession && m_RoutingSession->IsRatchets ()) ? STREAMING_MTU_RATCHETS : STREAMING_MTU;
} }
uint16_t flags = PACKET_FLAG_SYNCHRONIZE | PACKET_FLAG_FROM_INCLUDED | uint16_t flags = PACKET_FLAG_SYNCHRONIZE | PACKET_FLAG_FROM_INCLUDED | PACKET_FLAG_MAX_PACKET_SIZE_INCLUDED;
PACKET_FLAG_SIGNATURE_INCLUDED | PACKET_FLAG_MAX_PACKET_SIZE_INCLUDED; if (!m_DontSign) flags |= PACKET_FLAG_SIGNATURE_INCLUDED;
if (isNoAck) flags |= PACKET_FLAG_NO_ACK; if (isNoAck) flags |= PACKET_FLAG_NO_ACK;
bool isOfflineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().IsOfflineSignature (); bool isOfflineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().IsOfflineSignature ();
if (isOfflineSignature) flags |= PACKET_FLAG_OFFLINE_SIGNATURE; if (isOfflineSignature) flags |= PACKET_FLAG_OFFLINE_SIGNATURE;
@ -957,18 +992,26 @@ namespace stream
size += identityLen; // from size += identityLen; // from
htobe16buf (packet + size, m_MTU); htobe16buf (packet + size, m_MTU);
size += 2; // max packet size size += 2; // max packet size
if (isOfflineSignature) if (m_DontSign)
{ {
const auto& offlineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetOfflineSignature (); htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
memcpy (packet + size, offlineSignature.data (), offlineSignature.size ()); size += m_SendBuffer.Get (packet + size, m_MTU); // payload
size += offlineSignature.size (); // offline signature }
else
{
if (isOfflineSignature)
{
const auto& offlineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetOfflineSignature ();
memcpy (packet + size, offlineSignature.data (), offlineSignature.size ());
size += offlineSignature.size (); // offline signature
}
uint8_t * signature = packet + size; // set it later
memset (signature, 0, signatureLen); // zeroes for now
size += signatureLen; // signature
htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
size += m_SendBuffer.Get (packet + size, m_MTU); // payload
m_LocalDestination.GetOwner ()->Sign (packet, size, signature);
} }
uint8_t * signature = packet + size; // set it later
memset (signature, 0, signatureLen); // zeroes for now
size += signatureLen; // signature
htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
size += m_SendBuffer.Get (packet + size, m_MTU); // payload
m_LocalDestination.GetOwner ()->Sign (packet, size, signature);
} }
else else
{ {
@ -1178,28 +1221,34 @@ namespace stream
size += 4; // sendStreamID size += 4; // sendStreamID
memset (packet + size, 0, 14); memset (packet + size, 0, 14);
size += 14; // all zeroes size += 14; // all zeroes
uint16_t flags = PACKET_FLAG_ECHO | PACKET_FLAG_SIGNATURE_INCLUDED | PACKET_FLAG_FROM_INCLUDED; uint16_t flags = PACKET_FLAG_ECHO | PACKET_FLAG_FROM_INCLUDED;
if (!m_DontSign) flags |= PACKET_FLAG_SIGNATURE_INCLUDED;
bool isOfflineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().IsOfflineSignature (); bool isOfflineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().IsOfflineSignature ();
if (isOfflineSignature) flags |= PACKET_FLAG_OFFLINE_SIGNATURE; if (isOfflineSignature) flags |= PACKET_FLAG_OFFLINE_SIGNATURE;
htobe16buf (packet + size, flags); htobe16buf (packet + size, flags);
size += 2; // flags size += 2; // flags
size_t identityLen = m_LocalDestination.GetOwner ()->GetIdentity ()->GetFullLen (); size_t identityLen = m_LocalDestination.GetOwner ()->GetIdentity ()->GetFullLen ();
size_t signatureLen = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetSignatureLen ();
uint8_t * optionsSize = packet + size; // set options size later uint8_t * optionsSize = packet + size; // set options size later
size += 2; // options size size += 2; // options size
m_LocalDestination.GetOwner ()->GetIdentity ()->ToBuffer (packet + size, identityLen); m_LocalDestination.GetOwner ()->GetIdentity ()->ToBuffer (packet + size, identityLen);
size += identityLen; // from size += identityLen; // from
if (isOfflineSignature) if (m_DontSign)
htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
else
{ {
const auto& offlineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetOfflineSignature (); if (isOfflineSignature)
memcpy (packet + size, offlineSignature.data (), offlineSignature.size ()); {
size += offlineSignature.size (); // offline signature const auto& offlineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetOfflineSignature ();
memcpy (packet + size, offlineSignature.data (), offlineSignature.size ());
size += offlineSignature.size (); // offline signature
}
size_t signatureLen = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetSignatureLen ();
uint8_t * signature = packet + size; // set it later
memset (signature, 0, signatureLen); // zeroes for now
size += signatureLen; // signature
htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
m_LocalDestination.GetOwner ()->Sign (packet, size, signature);
} }
uint8_t * signature = packet + size; // set it later
memset (signature, 0, signatureLen); // zeroes for now
size += signatureLen; // signature
htobe16buf (optionsSize, packet + size - 2 - optionsSize); // actual options size
m_LocalDestination.GetOwner ()->Sign (packet, size, signature);
p.len = size; p.len = size;
SendPackets (std::vector<Packet *> { &p }); SendPackets (std::vector<Packet *> { &p });
LogPrint (eLogDebug, "Streaming: Ping of ", p.len, " bytes sent"); LogPrint (eLogDebug, "Streaming: Ping of ", p.len, " bytes sent");
@ -1253,15 +1302,33 @@ namespace stream
size++; // NACK count size++; // NACK count
packet[size] = 0; packet[size] = 0;
size++; // resend delay size++; // resend delay
htobe16buf (packet + size, PACKET_FLAG_CLOSE | PACKET_FLAG_SIGNATURE_INCLUDED); uint16_t flags = PACKET_FLAG_CLOSE;
if (!m_DontSign) flags |= PACKET_FLAG_SIGNATURE_INCLUDED;
bool isOfflineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().IsOfflineSignature ();
if (isOfflineSignature) flags |= PACKET_FLAG_OFFLINE_SIGNATURE;
htobe16buf (packet + size, flags);
size += 2; // flags size += 2; // flags
size_t signatureLen = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetSignatureLen (); if (m_DontSign)
htobe16buf (packet + size, signatureLen); // signature only {
size += 2; // options size memset (packet + size, 0, 2); // no options
uint8_t * signature = packet + size; size += 2; // options size
memset (packet + size, 0, signatureLen); }
size += signatureLen; // signature else
m_LocalDestination.GetOwner ()->Sign (packet, size, signature); {
if (isOfflineSignature)
{
const auto& offlineSignature = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetOfflineSignature ();
memcpy (packet + size, offlineSignature.data (), offlineSignature.size ());
size += offlineSignature.size (); // offline signature
}
size_t signatureLen = m_LocalDestination.GetOwner ()->GetPrivateKeys ().GetSignatureLen ();
htobe16buf (packet + size, signatureLen); // signature only
size += 2; // options size
uint8_t * signature = packet + size;
memset (packet + size, 0, signatureLen);
size += signatureLen; // signature
m_LocalDestination.GetOwner ()->Sign (packet, size, signature);
}
p->len = size; p->len = size;
boost::asio::post (m_Service, std::bind (&Stream::SendPacket, shared_from_this (), p)); boost::asio::post (m_Service, std::bind (&Stream::SendPacket, shared_from_this (), p));

View file

@ -273,22 +273,10 @@ namespace stream
int32_t m_PreviousReceivedSequenceNumber; int32_t m_PreviousReceivedSequenceNumber;
int32_t m_LastConfirmedReceivedSequenceNumber; // for limit inbound speed int32_t m_LastConfirmedReceivedSequenceNumber; // for limit inbound speed
StreamStatus m_Status; StreamStatus m_Status;
bool m_IsIncoming; bool m_IsIncoming, m_IsAckSendScheduled, m_IsNAcked, m_IsFirstACK, m_IsResendNeeded,
bool m_IsAckSendScheduled; m_IsFirstRttSample, m_IsSendTime, m_IsWinDropped, m_IsChoking2, m_IsClientChoked,
bool m_IsNAcked; m_IsClientChoked2, m_IsTimeOutResend, m_IsImmediateAckRequested,
bool m_IsFirstACK; m_IsRemoteLeaseChangeInProgress, m_IsBufferEmpty, m_IsJavaClient, m_DontSign;
bool m_IsResendNeeded;
bool m_IsFirstRttSample;
bool m_IsSendTime;
bool m_IsWinDropped;
bool m_IsChoking2;
bool m_IsClientChoked;
bool m_IsClientChoked2;
bool m_IsTimeOutResend;
bool m_IsImmediateAckRequested;
bool m_IsRemoteLeaseChangeInProgress;
bool m_IsBufferEmpty;
bool m_IsJavaClient;
StreamingDestination& m_LocalDestination; StreamingDestination& m_LocalDestination;
std::shared_ptr<const i2p::data::IdentityEx> m_RemoteIdentity; std::shared_ptr<const i2p::data::IdentityEx> m_RemoteIdentity;
std::shared_ptr<const i2p::crypto::Verifier> m_TransientVerifier; // in case of offline key std::shared_ptr<const i2p::crypto::Verifier> m_TransientVerifier; // in case of offline key

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 * This file is part of Purple i2pd project and licensed under BSD3
* *
@ -14,6 +14,7 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include <boost/asio.hpp> #include <boost/asio.hpp>
#include <boost/asio/deadline_timer.hpp> // for boost 1.89
namespace i2p namespace i2p
{ {

View file

@ -476,6 +476,7 @@ namespace client
options[I2CP_PARAM_STREAMING_MAX_INBOUND_SPEED] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_INBOUND_SPEED, DEFAULT_MAX_INBOUND_SPEED); options[I2CP_PARAM_STREAMING_MAX_INBOUND_SPEED] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_INBOUND_SPEED, DEFAULT_MAX_INBOUND_SPEED);
options[I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS, DEFAULT_MAX_CONCURRENT_STREAMS); options[I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_CONCURRENT_STREAMS, DEFAULT_MAX_CONCURRENT_STREAMS);
options[I2CP_PARAM_STREAMING_ANSWER_PINGS] = GetI2CPOption(section, I2CP_PARAM_STREAMING_ANSWER_PINGS, isServer ? DEFAULT_ANSWER_PINGS : false); options[I2CP_PARAM_STREAMING_ANSWER_PINGS] = GetI2CPOption(section, I2CP_PARAM_STREAMING_ANSWER_PINGS, isServer ? DEFAULT_ANSWER_PINGS : false);
options[I2CP_PARAM_STREAMING_DONT_SIGN] = GetI2CPOption(section, I2CP_PARAM_STREAMING_DONT_SIGN, DEFAULT_DONT_SIGN);
options[I2CP_PARAM_STREAMING_PROFILE] = GetI2CPOption(section, I2CP_PARAM_STREAMING_PROFILE, DEFAULT_STREAMING_PROFILE); options[I2CP_PARAM_STREAMING_PROFILE] = GetI2CPOption(section, I2CP_PARAM_STREAMING_PROFILE, DEFAULT_STREAMING_PROFILE);
options[I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE, i2p::stream::MAX_WINDOW_SIZE); options[I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE] = GetI2CPOption(section, I2CP_PARAM_STREAMING_MAX_WINDOW_SIZE, i2p::stream::MAX_WINDOW_SIZE);
options[I2CP_PARAM_LEASESET_TYPE] = GetI2CPOption(section, I2CP_PARAM_LEASESET_TYPE, DEFAULT_LEASESET_TYPE); options[I2CP_PARAM_LEASESET_TYPE] = GetI2CPOption(section, I2CP_PARAM_LEASESET_TYPE, DEFAULT_LEASESET_TYPE);

View file

@ -26,9 +26,9 @@ namespace client
{ {
SAMSocket::SAMSocket (SAMBridge& owner): SAMSocket::SAMSocket (SAMBridge& owner):
m_Owner (owner), m_Socket(owner.GetService()), m_Timer (m_Owner.GetService ()), m_Owner (owner), m_Socket(owner.GetService()), m_Timer (m_Owner.GetService ()),
m_BufferOffset (0), m_BufferOffset (0), m_SocketType (SAMSocketType::eSAMSocketTypeUnknown),
m_SocketType (SAMSocketType::eSAMSocketTypeUnknown), m_IsSilent (false), m_IsSilent (false), m_IsAccepting (false), m_IsReceiving (false),
m_IsAccepting (false), m_IsReceiving (false) m_Version (MIN_SAM_VERSION)
{ {
} }
@ -81,19 +81,24 @@ namespace client
std::placeholders::_1, std::placeholders::_2)); std::placeholders::_1, std::placeholders::_2));
} }
static bool SAMVersionAcceptable(const std::string & ver) static int ExtractVersion (std::string_view ver)
{ {
return ver == "3.0" || ver == "3.1"; int version = 0;
for (auto ch: ver)
{
if (ch >= '0' && ch <= '9')
{
version *= 10;
version += (ch - '0');
}
}
return version;
} }
static bool SAMVersionTooLow(const std::string & ver) static std::string CreateVersion (int ver)
{ {
return ver.size() && ver[0] < '3'; auto d = div (ver, 10);
} return std::to_string (d.quot) + "." + std::to_string (d.rem);
static bool SAMVersionTooHigh(const std::string & ver)
{
return ver.size() && ver > "3.1";
} }
void SAMSocket::HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) void SAMSocket::HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
@ -121,8 +126,7 @@ namespace client
if (!strcmp (m_Buffer, SAM_HANDSHAKE)) if (!strcmp (m_Buffer, SAM_HANDSHAKE))
{ {
std::string maxver("3.1"); int minVer = 0, maxVer = 0;
std::string minver("3.0");
// try to find MIN and MAX, 3.0 if not found // try to find MIN and MAX, 3.0 if not found
if (separator) if (separator)
{ {
@ -130,39 +134,33 @@ namespace client
auto params = ExtractParams (separator); auto params = ExtractParams (separator);
auto it = params.find (SAM_PARAM_MAX); auto it = params.find (SAM_PARAM_MAX);
if (it != params.end ()) if (it != params.end ())
maxver = it->second; maxVer = ExtractVersion (it->second);
it = params.find(SAM_PARAM_MIN); it = params.find(SAM_PARAM_MIN);
if (it != params.end ()) if (it != params.end ())
minver = it->second; minVer = ExtractVersion (it->second);
} }
// version negotiation // version negotiation
std::string version; if (maxVer && maxVer <= MAX_SAM_VERSION)
if (SAMVersionAcceptable(maxver)) m_Version = maxVer;
{ else if (minVer && minVer >= MIN_SAM_VERSION && minVer <= MAX_SAM_VERSION)
version = maxver; m_Version = minVer;
} else if (!maxVer && !minVer)
else if (SAMVersionAcceptable(minver)) m_Version = MIN_SAM_VERSION;
{
version = minver;
}
else if (SAMVersionTooLow(minver) && SAMVersionTooHigh(maxver))
{
version = "3.0";
}
if (SAMVersionAcceptable(version))
{
#ifdef _MSC_VER
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
#else
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, version.c_str ());
#endif
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Buffer, l), boost::asio::transfer_all (),
std::bind(&SAMSocket::HandleHandshakeReplySent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
}
else else
SendMessageReply (SAM_HANDSHAKE_NOVERSION, strlen (SAM_HANDSHAKE_NOVERSION), true); {
LogPrint (eLogError, "SAM: Handshake version mismatch ", minVer, " ", maxVer);
SendMessageReply (SAM_HANDSHAKE_NOVERSION, true);
return;
}
// send reply
#ifdef _MSC_VER
size_t l = sprintf_s (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, CreateVersion (m_Version).c_str ());
#else
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_HANDSHAKE_REPLY, CreateVersion (m_Version).c_str ());
#endif
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Buffer, l), boost::asio::transfer_all (),
std::bind(&SAMSocket::HandleHandshakeReplySent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2));
} }
else else
{ {
@ -193,12 +191,12 @@ namespace client
} }
} }
void SAMSocket::SendMessageReply (const char * msg, size_t len, bool close) void SAMSocket::SendMessageReply (std::string_view msg, bool close)
{ {
LogPrint (eLogDebug, "SAMSocket::SendMessageReply, close=",close?"true":"false", " reason: ", msg); LogPrint (eLogDebug, "SAMSocket::SendMessageReply, close=",close?"true":"false", " reason: ", msg);
if (!m_IsSilent || m_SocketType == SAMSocketType::eSAMSocketTypeForward) if (!m_IsSilent || m_SocketType == SAMSocketType::eSAMSocketTypeForward)
boost::asio::async_write (m_Socket, boost::asio::buffer (msg, len), boost::asio::transfer_all (), boost::asio::async_write (m_Socket, boost::asio::buffer (msg.data (), msg.size ()), boost::asio::transfer_all (),
std::bind(&SAMSocket::HandleMessageReplySent, shared_from_this (), std::bind(&SAMSocket::HandleMessageReplySent, shared_from_this (),
std::placeholders::_1, std::placeholders::_2, close)); std::placeholders::_1, std::placeholders::_2, close));
else else
@ -341,14 +339,14 @@ namespace client
if(!IsAcceptableSessionName(id)) if(!IsAcceptableSessionName(id))
{ {
// invalid session id // invalid session id
SendMessageReply (SAM_SESSION_CREATE_INVALID_ID, strlen(SAM_SESSION_CREATE_INVALID_ID), true); SendMessageReply (SAM_SESSION_CREATE_INVALID_ID, true);
return; return;
} }
m_ID = id; m_ID = id;
if (m_Owner.FindSession (id)) if (m_Owner.FindSession (id))
{ {
// session exists // session exists
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, strlen(SAM_SESSION_CREATE_DUPLICATED_ID), true); SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, true);
return; return;
} }
@ -375,7 +373,15 @@ namespace client
} }
} }
else if (style == SAM_VALUE_RAW) type = SAMSessionType::eSAMSessionTypeRaw; else if (style == SAM_VALUE_RAW) type = SAMSessionType::eSAMSessionTypeRaw;
else if (style == SAM_VALUE_MASTER) type = SAMSessionType::eSAMSessionTypeMaster; else if (style == SAM_VALUE_MASTER)
{
if (m_Version < SAM_VERSION_33) // < SAM 3.3
{
SendSessionI2PError("MASTER session is not supported");
return;
}
type = SAMSessionType::eSAMSessionTypeMaster;
}
if (type == SAMSessionType::eSAMSessionTypeUnknown) if (type == SAMSessionType::eSAMSessionTypeUnknown)
{ {
// unknown style // unknown style
@ -412,7 +418,7 @@ namespace client
//ensure we actually received a destination //ensure we actually received a destination
if (destination.empty()) if (destination.empty())
{ {
SendMessageReply (SAM_SESSION_STATUS_INVALID_KEY, strlen(SAM_SESSION_STATUS_INVALID_KEY), true); SendMessageReply (SAM_SESSION_STATUS_INVALID_KEY, true);
return; return;
} }
@ -422,7 +428,7 @@ namespace client
i2p::data::PrivateKeys keys; i2p::data::PrivateKeys keys;
if (!keys.FromBase64(destination)) if (!keys.FromBase64(destination))
{ {
SendMessageReply(SAM_SESSION_STATUS_INVALID_KEY, strlen(SAM_SESSION_STATUS_INVALID_KEY), true); SendMessageReply(SAM_SESSION_STATUS_INVALID_KEY, true);
return; return;
} }
} }
@ -465,7 +471,7 @@ namespace client
} }
} }
else else
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_DEST, strlen(SAM_SESSION_CREATE_DUPLICATED_DEST), true); SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_DEST, true);
} }
void SAMSocket::HandleSessionReadinessCheckTimer (const boost::system::error_code& ecode) void SAMSocket::HandleSessionReadinessCheckTimer (const boost::system::error_code& ecode)
@ -503,7 +509,7 @@ namespace client
#else #else
size_t l2 = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_CREATE_REPLY_OK, priv.c_str ()); size_t l2 = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_SESSION_CREATE_REPLY_OK, priv.c_str ());
#endif #endif
SendMessageReply (m_Buffer, l2, false); SendMessageReply ({m_Buffer, l2}, false);
} }
} }
@ -571,10 +577,10 @@ namespace client
shared_from_this(), std::placeholders::_1)); shared_from_this(), std::placeholders::_1));
} }
else else
SendMessageReply (SAM_STREAM_STATUS_INVALID_KEY, strlen(SAM_STREAM_STATUS_INVALID_KEY), true); SendMessageReply (SAM_STREAM_STATUS_INVALID_KEY, true);
} }
else else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true); SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, true);
} }
void SAMSocket::Connect (std::shared_ptr<const i2p::data::LeaseSet> remote, std::shared_ptr<SAMSession> session) void SAMSocket::Connect (std::shared_ptr<const i2p::data::LeaseSet> remote, std::shared_ptr<SAMSession> session)
@ -591,16 +597,16 @@ namespace client
m_Stream->Send ((uint8_t *)m_Buffer, m_BufferOffset); // connect and send m_Stream->Send ((uint8_t *)m_Buffer, m_BufferOffset); // connect and send
m_BufferOffset = 0; m_BufferOffset = 0;
I2PReceive (); I2PReceive ();
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false); SendMessageReply (SAM_STREAM_STATUS_OK, false);
} }
else else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true); SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, true);
} }
else else
SendStreamCantReachPeer ("Incompatible crypto"); SendStreamCantReachPeer ("Incompatible crypto");
} }
else else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true); SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, true);
} }
void SAMSocket::HandleConnectLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet) void SAMSocket::HandleConnectLeaseSetRequestComplete (std::shared_ptr<i2p::data::LeaseSet> leaseSet)
@ -634,7 +640,7 @@ namespace client
if (!session->GetLocalDestination ()->IsAcceptingStreams ()) if (!session->GetLocalDestination ()->IsAcceptingStreams ())
{ {
m_IsAccepting = true; m_IsAccepting = true;
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false); SendMessageReply (SAM_STREAM_STATUS_OK, false);
session->GetLocalDestination ()->AcceptOnce (std::bind (&SAMSocket::HandleI2PAccept, shared_from_this (), std::placeholders::_1)); session->GetLocalDestination ()->AcceptOnce (std::bind (&SAMSocket::HandleI2PAccept, shared_from_this (), std::placeholders::_1));
} }
else else
@ -650,7 +656,7 @@ namespace client
if (session->acceptQueue.size () < SAM_SESSION_MAX_ACCEPT_QUEUE_SIZE) if (session->acceptQueue.size () < SAM_SESSION_MAX_ACCEPT_QUEUE_SIZE)
{ {
// already accepting, queue up // already accepting, queue up
SendMessageReply (SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false); SendMessageReply (SAM_STREAM_STATUS_OK, false);
session->acceptQueue.push_back (std::make_pair(shared_from_this(), ts)); session->acceptQueue.push_back (std::make_pair(shared_from_this(), ts));
} }
else else
@ -661,7 +667,7 @@ namespace client
} }
} }
else else
SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true); SendMessageReply (SAM_STREAM_STATUS_INVALID_ID, true);
} }
void SAMSocket::ProcessStreamForward (std::string_view buf) void SAMSocket::ProcessStreamForward (std::string_view buf)
@ -680,7 +686,7 @@ namespace client
auto session = m_Owner.FindSession(id); auto session = m_Owner.FindSession(id);
if (!session) if (!session)
{ {
SendMessageReply(SAM_STREAM_STATUS_INVALID_ID, strlen(SAM_STREAM_STATUS_INVALID_ID), true); SendMessageReply(SAM_STREAM_STATUS_INVALID_ID, true);
return; return;
} }
if (session->GetLocalDestination()->IsAcceptingStreams()) if (session->GetLocalDestination()->IsAcceptingStreams())
@ -748,7 +754,7 @@ namespace client
session->GetLocalDestination()->AcceptStreams( session->GetLocalDestination()->AcceptStreams(
std::bind(&SAMSocket::HandleI2PForward, shared_from_this(), std::placeholders::_1, ep)); std::bind(&SAMSocket::HandleI2PForward, shared_from_this(), std::placeholders::_1, ep));
SendMessageReply(SAM_STREAM_STATUS_OK, strlen(SAM_STREAM_STATUS_OK), false); SendMessageReply(SAM_STREAM_STATUS_OK, false);
} }
@ -823,7 +829,7 @@ namespace client
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY, size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_DEST_REPLY,
keys.GetPublic ()->ToBase64 ().c_str (), keys.ToBase64 ().c_str ()); keys.GetPublic ()->ToBase64 ().c_str (), keys.ToBase64 ().c_str ());
#endif #endif
SendMessageReply (m_Buffer, l, false); SendMessageReply ({m_Buffer, l}, false);
} }
void SAMSocket::ProcessNamingLookup (std::string_view buf) void SAMSocket::ProcessNamingLookup (std::string_view buf)
@ -864,12 +870,17 @@ namespace client
#else #else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str()); size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#endif #endif
SendMessageReply (m_Buffer, len, false); SendMessageReply ({m_Buffer, len}, false);
} }
} }
void SAMSocket::ProcessSessionAdd (std::string_view buf) void SAMSocket::ProcessSessionAdd (std::string_view buf)
{ {
if (m_Version < SAM_VERSION_33) // < SAM 3.3
{
SendSessionI2PError("SESSION ADD is not supported");
return;
}
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if (session && session->Type == SAMSessionType::eSAMSessionTypeMaster) if (session && session->Type == SAMSessionType::eSAMSessionTypeMaster)
{ {
@ -880,7 +891,7 @@ namespace client
if (masterSession->subsessions.count (id) > 1) if (masterSession->subsessions.count (id) > 1)
{ {
// session exists // session exists
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, strlen(SAM_SESSION_CREATE_DUPLICATED_ID), false); SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, false);
return; return;
} }
std::string_view style = params[SAM_PARAM_STYLE]; std::string_view style = params[SAM_PARAM_STYLE];
@ -893,11 +904,17 @@ namespace client
SendSessionI2PError("Unsupported STYLE"); SendSessionI2PError("Unsupported STYLE");
return; return;
} }
auto fromPort = std::stoi(std::string (params[SAM_PARAM_FROM_PORT])); uint16_t fromPort = 0;
if (fromPort == -1) auto it = params.find (SAM_PARAM_FROM_PORT);
if (it != params.end ())
{ {
SendSessionI2PError("Invalid from port"); auto p = it->second;
return; auto res = std::from_chars(p.data(), p.data() + p.size(), fromPort);
if (res.ec != std::errc())
{
SendSessionI2PError("Invalid from port");
return;
}
} }
auto subsession = std::make_shared<SAMSubSession>(masterSession, id, type, fromPort); auto subsession = std::make_shared<SAMSubSession>(masterSession, id, type, fromPort);
if (m_Owner.AddSession (subsession)) if (m_Owner.AddSession (subsession))
@ -906,7 +923,7 @@ namespace client
SendSessionCreateReplyOk (); SendSessionCreateReplyOk ();
} }
else else
SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, strlen(SAM_SESSION_CREATE_DUPLICATED_ID), false); SendMessageReply (SAM_SESSION_CREATE_DUPLICATED_ID, false);
} }
else else
SendSessionI2PError ("Wrong session type"); SendSessionI2PError ("Wrong session type");
@ -914,6 +931,11 @@ namespace client
void SAMSocket::ProcessSessionRemove (std::string_view buf) void SAMSocket::ProcessSessionRemove (std::string_view buf)
{ {
if (m_Version < SAM_VERSION_33) // < SAM 3.3
{
SendSessionI2PError("SESSION REMOVE is not supported");
return;
}
auto session = m_Owner.FindSession(m_ID); auto session = m_Owner.FindSession(m_ID);
if (session && session->Type == SAMSessionType::eSAMSessionTypeMaster) if (session && session->Type == SAMSessionType::eSAMSessionTypeMaster)
{ {
@ -923,7 +945,7 @@ namespace client
std::string id(params[SAM_PARAM_ID]); std::string id(params[SAM_PARAM_ID]);
if (!masterSession->subsessions.erase (id)) if (!masterSession->subsessions.erase (id))
{ {
SendMessageReply (SAM_SESSION_STATUS_INVALID_KEY, strlen(SAM_SESSION_STATUS_INVALID_KEY), false); SendMessageReply (SAM_SESSION_STATUS_INVALID_KEY, false);
return; return;
} }
m_Owner.CloseSession (id); m_Owner.CloseSession (id);
@ -940,7 +962,7 @@ namespace client
#else #else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, reply, msg.c_str()); size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, reply, msg.c_str());
#endif #endif
SendMessageReply (m_Buffer, len, true); SendMessageReply ({m_Buffer, len}, true);
} }
void SAMSocket::SendSessionI2PError(const std::string & msg) void SAMSocket::SendSessionI2PError(const std::string & msg)
@ -975,7 +997,7 @@ namespace client
#else #else
size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str()); size_t len = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY_INVALID_KEY, name.c_str());
#endif #endif
SendMessageReply (m_Buffer, len, false); SendMessageReply ({m_Buffer, len}, false);
} }
} }
@ -987,7 +1009,7 @@ namespace client
#else #else
size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, name.c_str (), base64.c_str ()); size_t l = snprintf (m_Buffer, SAM_SOCKET_BUFFER_SIZE, SAM_NAMING_REPLY, name.c_str (), base64.c_str ());
#endif #endif
SendMessageReply (m_Buffer, l, false); SendMessageReply ({m_Buffer, l}, false);
} }
const std::map<std::string_view, std::string_view> SAMSocket::ExtractParams (std::string_view buf) const std::map<std::string_view, std::string_view> SAMSocket::ExtractParams (std::string_view buf)
@ -1365,8 +1387,9 @@ namespace client
SAMSubSession::SAMSubSession (std::shared_ptr<SAMMasterSession> master, std::string_view name, SAMSessionType type, uint16_t port): SAMSubSession::SAMSubSession (std::shared_ptr<SAMMasterSession> master, std::string_view name, SAMSessionType type, uint16_t port):
SAMSession (master->m_Bridge, name, type), masterSession (master), inPort (port) SAMSession (master->m_Bridge, name, type), masterSession (master), inPort (port)
{ {
if (Type == SAMSessionType::eSAMSessionTypeStream) if (Type == SAMSessionType::eSAMSessionTypeStream && port)
{ {
// additional streaming destination, use default if port is 0
auto d = masterSession->GetLocalDestination ()->CreateStreamingDestination (inPort); auto d = masterSession->GetLocalDestination ()->CreateStreamingDestination (inPort);
if (d) d->Start (); if (d) d->Start ();
} }
@ -1590,14 +1613,17 @@ namespace client
if (dest) if (dest)
{ {
auto streamingDest = dest->GetStreamingDestination (); auto streamingDest = dest->GetStreamingDestination ();
auto numStreams = streamingDest->GetNumStreams (); if (streamingDest)
if (numStreams > 0)
{ {
LogPrint (eLogInfo, "SAM: Session ", session->Name, " still has ", numStreams, " streams"); auto numStreams = streamingDest->GetNumStreams ();
ScheduleSessionCleanupTimer (session); if (numStreams > 0)
{
LogPrint (eLogInfo, "SAM: Session ", session->Name, " still has ", numStreams, " streams");
ScheduleSessionCleanupTimer (session);
}
else
LogPrint (eLogDebug, "SAM: Session ", session->Name, " terminated");
} }
else
LogPrint (eLogDebug, "SAM: Session ", session->Name, " terminated");
} }
} }
// session's destructor is called here unless rescheduled // session's destructor is called here unless rescheduled

View file

@ -39,21 +39,21 @@ namespace client
const char SAM_HANDSHAKE[] = "HELLO VERSION"; const char SAM_HANDSHAKE[] = "HELLO VERSION";
const char SAM_HANDSHAKE_REPLY[] = "HELLO REPLY RESULT=OK VERSION=%s\n"; const char SAM_HANDSHAKE_REPLY[] = "HELLO REPLY RESULT=OK VERSION=%s\n";
const char SAM_HANDSHAKE_NOVERSION[] = "HELLO REPLY RESULT=NOVERSION\n"; constexpr std::string_view SAM_HANDSHAKE_NOVERSION { "HELLO REPLY RESULT=NOVERSION\n" };
const char SAM_HANDSHAKE_I2P_ERROR[] = "HELLO REPLY RESULT=I2P_ERROR\n"; const char SAM_HANDSHAKE_I2P_ERROR[] = "HELLO REPLY RESULT=I2P_ERROR\n";
const char SAM_SESSION_CREATE[] = "SESSION CREATE"; const char SAM_SESSION_CREATE[] = "SESSION CREATE";
const char SAM_SESSION_CREATE_REPLY_OK[] = "SESSION STATUS RESULT=OK DESTINATION=%s\n"; const char SAM_SESSION_CREATE_REPLY_OK[] = "SESSION STATUS RESULT=OK DESTINATION=%s\n";
const char SAM_SESSION_CREATE_DUPLICATED_ID[] = "SESSION STATUS RESULT=DUPLICATED_ID\n"; constexpr std::string_view SAM_SESSION_CREATE_DUPLICATED_ID { "SESSION STATUS RESULT=DUPLICATED_ID\n" };
const char SAM_SESSION_CREATE_DUPLICATED_DEST[] = "SESSION STATUS RESULT=DUPLICATED_DEST\n"; constexpr std::string_view SAM_SESSION_CREATE_DUPLICATED_DEST { "SESSION STATUS RESULT=DUPLICATED_DEST\n" };
const char SAM_SESSION_CREATE_INVALID_ID[] = "SESSION STATUS RESULT=INVALID_ID\n"; constexpr std::string_view SAM_SESSION_CREATE_INVALID_ID { "SESSION STATUS RESULT=INVALID_ID\n" };
const char SAM_SESSION_STATUS_INVALID_KEY[] = "SESSION STATUS RESULT=INVALID_KEY\n"; constexpr std::string_view SAM_SESSION_STATUS_INVALID_KEY { "SESSION STATUS RESULT=INVALID_KEY\n" };
const char SAM_SESSION_STATUS_I2P_ERROR[] = "SESSION STATUS RESULT=I2P_ERROR MESSAGE=\"%s\"\n"; const char SAM_SESSION_STATUS_I2P_ERROR[] = "SESSION STATUS RESULT=I2P_ERROR MESSAGE=\"%s\"\n";
const char SAM_SESSION_ADD[] = "SESSION ADD"; const char SAM_SESSION_ADD[] = "SESSION ADD";
const char SAM_SESSION_REMOVE[] = "SESSION REMOVE"; const char SAM_SESSION_REMOVE[] = "SESSION REMOVE";
const char SAM_STREAM_CONNECT[] = "STREAM CONNECT"; const char SAM_STREAM_CONNECT[] = "STREAM CONNECT";
const char SAM_STREAM_STATUS_OK[] = "STREAM STATUS RESULT=OK\n"; constexpr std::string_view SAM_STREAM_STATUS_OK { "STREAM STATUS RESULT=OK\n" };
const char SAM_STREAM_STATUS_INVALID_ID[] = "STREAM STATUS RESULT=INVALID_ID\n"; constexpr std::string_view SAM_STREAM_STATUS_INVALID_ID { "STREAM STATUS RESULT=INVALID_ID\n" };
const char SAM_STREAM_STATUS_INVALID_KEY[] = "STREAM STATUS RESULT=INVALID_KEY\n"; constexpr std::string_view SAM_STREAM_STATUS_INVALID_KEY { "STREAM STATUS RESULT=INVALID_KEY\n" };
const char SAM_STREAM_STATUS_CANT_REACH_PEER[] = "STREAM STATUS RESULT=CANT_REACH_PEER MESSAGE=\"%s\"\n"; const char SAM_STREAM_STATUS_CANT_REACH_PEER[] = "STREAM STATUS RESULT=CANT_REACH_PEER MESSAGE=\"%s\"\n";
const char SAM_STREAM_STATUS_I2P_ERROR[] = "STREAM STATUS RESULT=I2P_ERROR MESSAGE=\"%s\"\n"; const char SAM_STREAM_STATUS_I2P_ERROR[] = "STREAM STATUS RESULT=I2P_ERROR MESSAGE=\"%s\"\n";
const char SAM_STREAM_ACCEPT[] = "STREAM ACCEPT"; const char SAM_STREAM_ACCEPT[] = "STREAM ACCEPT";
@ -91,6 +91,11 @@ namespace client
constexpr std::string_view SAM_VALUE_RAW { "RAW" }; constexpr std::string_view SAM_VALUE_RAW { "RAW" };
constexpr std::string_view SAM_VALUE_MASTER { "MASTER" }; constexpr std::string_view SAM_VALUE_MASTER { "MASTER" };
constexpr int MAKE_SAM_VERSION_NUMBER (int major, int minor) { return major*10 + minor; }
constexpr int MIN_SAM_VERSION = MAKE_SAM_VERSION_NUMBER (3, 0);
constexpr int MAX_SAM_VERSION = MAKE_SAM_VERSION_NUMBER (3, 3);
constexpr int SAM_VERSION_33 = MAKE_SAM_VERSION_NUMBER (3, 3); // SAM 3.3
enum class SAMSocketType enum class SAMSocketType
{ {
eSAMSocketTypeUnknown, eSAMSocketTypeUnknown,
@ -127,7 +132,7 @@ namespace client
void HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandleHandshakeReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void HandleHandshakeReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandleHandshakeReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void HandleMessage (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandleMessage (const boost::system::error_code& ecode, std::size_t bytes_transferred);
void SendMessageReply (const char * msg, size_t len, bool close); void SendMessageReply (std::string_view msg, bool close);
void HandleMessageReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred, bool close); void HandleMessageReplySent (const boost::system::error_code& ecode, std::size_t bytes_transferred, bool close);
void Receive (); void Receive ();
void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred); void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
@ -182,6 +187,7 @@ namespace client
bool m_IsAccepting; // for eSAMSocketTypeAcceptor only bool m_IsAccepting; // for eSAMSocketTypeAcceptor only
bool m_IsReceiving; // for eSAMSocketTypeStream only bool m_IsReceiving; // for eSAMSocketTypeStream only
std::shared_ptr<i2p::stream::Stream> m_Stream; std::shared_ptr<i2p::stream::Stream> m_Stream;
int m_Version;
}; };
enum class SAMSessionType enum class SAMSessionType