mirror of
https://github.com/PurpleI2P/i2pd.git
synced 2025-03-07 06:09:42 +00:00
Compare commits
4 Commits
fde49b3dab
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d610e6c4c1 | ||
|
|
35352f1497 | ||
|
|
e695f1e060 | ||
|
|
ecc635e9bc |
6
.github/workflows/build-windows.yml
vendored
6
.github/workflows/build-windows.yml
vendored
@@ -133,8 +133,6 @@ jobs:
|
||||
git clone https://github.com/msys2/MINGW-packages
|
||||
cd MINGW-packages
|
||||
git checkout 4cbb366edf2f268ac3146174b40ce38604646fc5 mingw-w64-boost
|
||||
cd mingw-w64-boost
|
||||
sed -i 's/boostorg.jfrog.io\/artifactory\/main/archives.boost.io/' PKGBUILD
|
||||
|
||||
# headers
|
||||
- name: Get headers package version
|
||||
@@ -232,10 +230,8 @@ jobs:
|
||||
run: |
|
||||
cd MINGW-packages/mingw-w64-boost
|
||||
MINGW_ARCH=mingw32 makepkg-mingw -sCLf --noconfirm --nocheck
|
||||
- name: Remove boost packages
|
||||
run: pacman --noconfirm -R mingw-w64-i686-boost mingw-w64-i686-boost-libs
|
||||
- name: Install boost package
|
||||
run: pacman --noconfirm -U MINGW-packages/mingw-w64-boost/mingw-w64-i686-*-any.pkg.tar.zst
|
||||
run: pacman --noconfirm -U --overwrite MINGW-packages/mingw-w64-boost/mingw-w64-i686-*-any.pkg.tar.zst
|
||||
|
||||
# Building i2pd
|
||||
- name: Build application
|
||||
|
||||
41
ChangeLog
41
ChangeLog
@@ -1,47 +1,6 @@
|
||||
# for this file format description,
|
||||
# see https://github.com/olivierlacan/keep-a-changelog
|
||||
|
||||
## [2.55.0] - 2024-12-30
|
||||
### Added
|
||||
- Support boost 1.87
|
||||
- "i2p.streaming.maxConcurrentStreams" tunnel's param to limit number of simultaneous streams
|
||||
- Separate thread for tunnel build requests
|
||||
- Show next peer and connectivity on "Transit tunnels" page
|
||||
- Tunnel name for local destination thread
|
||||
- Throttle incoming ECIESx25519 sessions
|
||||
- Send tunnel data to transport session directly if possible
|
||||
- Publish 'R' cap for yggdrasil-only routers, and 'U' cap for routers through proxy
|
||||
- Random tunnel rejection when medium congestion
|
||||
- Save unreachable router's endpoint to use it next time without introducers
|
||||
- Recognize symmetric NAT from peer test message 7
|
||||
- Resend HolePunch and RelayResponse messages
|
||||
### Changed
|
||||
- Removed own implementation of AESNI and always use one from openssl
|
||||
- Renamed main thread to i2pd-daemon
|
||||
- Set i2p.streaming.profile=2 for shared local destination
|
||||
- Reduced LeaseSet and RouterInfo lookup timeouts
|
||||
- Cleanup ECIES sessions and tags more often
|
||||
- Check LeaseSet expiration time
|
||||
- Handle NTCP2 session handshakes in separate thread
|
||||
- Limit last decline time by 1.5 hours in router's profile
|
||||
- Don't handle RelayRequest and RelayIntro with same nonce twice
|
||||
- Increased hole punch expiration interval
|
||||
- Send peer test message 6 with delay if message 4 was received before message 5
|
||||
- Pre-calculate more x25519 keys for transports in runtime
|
||||
- Don't request LeaseSet for incoming stream
|
||||
- Terminate incoming stream right away if no remote LeaseSet
|
||||
- Handle choked, new RTO and window size calculation and resetting algorithm for streams
|
||||
### Fixed
|
||||
- Empty string in addressbook subscriptions
|
||||
- ECIESx25519 sessions without destination
|
||||
- Missing RouterInfo buffer in NetDb
|
||||
- Invalid I2PControl certificate
|
||||
- Routers disappear from NetDb when offline
|
||||
- Peer test message 6 sent to unknown endpoint
|
||||
- Race condition with LeaseSet update
|
||||
- Excessive CPU usage by streams
|
||||
- Crash on shutdown
|
||||
|
||||
## [2.54.0] - 2024-10-06
|
||||
### Added
|
||||
- Maintain recently connected routers list to avoid false-positive peer test
|
||||
|
||||
1
Makefile
1
Makefile
@@ -29,6 +29,7 @@ DAEMON_SRC_DIR := daemon
|
||||
# import source files lists
|
||||
include filelist.mk
|
||||
|
||||
USE_AESNI := $(or $(USE_AESNI),yes)
|
||||
USE_STATIC := $(or $(USE_STATIC),no)
|
||||
USE_UPNP := $(or $(USE_UPNP),no)
|
||||
DEBUG := $(or $(DEBUG),yes)
|
||||
|
||||
@@ -30,6 +30,13 @@ ifeq ($(USE_UPNP),yes)
|
||||
INCFLAGS += -I${UPNPROOT}/include
|
||||
endif
|
||||
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
ifneq (, $(findstring i386, $(SYS))$(findstring i686, $(SYS))$(findstring x86_64, $(SYS))) # only x86-based CPU supports that
|
||||
NEEDED_CXXFLAGS += -maes
|
||||
DEFINES += -D__AES__
|
||||
endif
|
||||
endif
|
||||
|
||||
install: all
|
||||
install -d ${PREFIX}/bin
|
||||
install -m 755 ${I2PD} ${PREFIX}/bin
|
||||
|
||||
@@ -51,6 +51,13 @@ ifeq ($(USE_UPNP),yes)
|
||||
DEFINES += -DUSE_UPNP
|
||||
endif
|
||||
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
ifneq (, $(findstring i386, $(SYS))$(findstring i686, $(SYS))$(findstring x86_64, $(SYS))) # only x86-based CPU supports that
|
||||
NEEDED_CXXFLAGS += -maes
|
||||
DEFINES += -D__AES__
|
||||
endif
|
||||
endif
|
||||
|
||||
install: all
|
||||
install -d ${PREFIX}/bin
|
||||
install -m 755 ${I2PD} ${PREFIX}/bin
|
||||
|
||||
@@ -42,6 +42,12 @@ ifeq ($(USE_WIN32_APP), yes)
|
||||
DAEMON_OBJS += $(patsubst %.rc,obj/%.o,$(DAEMON_RC))
|
||||
endif
|
||||
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
NEEDED_CXXFLAGS += -maes
|
||||
LDFLAGS += -maes
|
||||
DEFINES += -D__AES__
|
||||
endif
|
||||
|
||||
ifeq ($(USE_ASLR),yes)
|
||||
LDFLAGS += -Wl,--nxcompat -Wl,--high-entropy-va -Wl,--dynamicbase,--export-all-symbols
|
||||
endif
|
||||
|
||||
@@ -25,5 +25,9 @@ endif
|
||||
OSARCH = $(shell uname -p)
|
||||
|
||||
ifneq ($(OSARCH),powerpc)
|
||||
CXXFLAGS += -msse
|
||||
ifeq ($(USE_AESNI),yes)
|
||||
CXXFLAGS += -D__AES__ -maes
|
||||
else
|
||||
CXXFLAGS += -msse
|
||||
endif
|
||||
endif
|
||||
|
||||
@@ -29,6 +29,7 @@ project(
|
||||
)
|
||||
|
||||
# configurable options
|
||||
option(WITH_AESNI "Use AES-NI instructions set" ON)
|
||||
option(WITH_HARDENING "Use hardening compiler flags" OFF)
|
||||
option(WITH_LIBRARY "Build library" ON)
|
||||
option(WITH_BINARY "Build binary" ON)
|
||||
@@ -184,6 +185,16 @@ if(UNIX)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Note: AES-NI and AVX is available on x86-based CPU's.
|
||||
# Here also ARM64 implementation, but currently we don't support it.
|
||||
# MSVC is not supported due to different ASM processing, so we hope OpenSSL has its own checks to run optimized code.
|
||||
if(WITH_AESNI AND (ARCHITECTURE MATCHES "x86_64" OR ARCHITECTURE MATCHES "i386"))
|
||||
if(NOT MSVC)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -maes")
|
||||
endif()
|
||||
add_definitions(-D__AES__)
|
||||
endif()
|
||||
|
||||
if(WITH_ADDRSANITIZER)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
|
||||
@@ -324,6 +335,7 @@ message(STATUS "Architecture : ${ARCHITECTURE}")
|
||||
message(STATUS "Compiler flags : ${CMAKE_CXX_FLAGS}")
|
||||
message(STATUS "Install prefix: : ${CMAKE_INSTALL_PREFIX}")
|
||||
message(STATUS "Options:")
|
||||
message(STATUS " AESNI : ${WITH_AESNI}")
|
||||
message(STATUS " HARDENING : ${WITH_HARDENING}")
|
||||
message(STATUS " LIBRARY : ${WITH_LIBRARY}")
|
||||
message(STATUS " BINARY : ${WITH_BINARY}")
|
||||
|
||||
@@ -59,7 +59,7 @@ get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
|
||||
# function returns an empty string via _git_dir_var.
|
||||
#
|
||||
# Example: Given a path C:/bla/foo/bar and assuming C:/bla/.git exists and
|
||||
# neither foo nor bar contain a file/directory .git. This will return
|
||||
# neither foo nor bar contain a file/directory .git. This wil return
|
||||
# C:/bla/.git
|
||||
#
|
||||
function(_git_find_closest_git_dir _start_dir _git_dir_var)
|
||||
|
||||
@@ -2,13 +2,13 @@ Description: Enable UPnP usage in package
|
||||
Author: r4sas <r4sas@i2pmail.org>
|
||||
|
||||
Reviewed-By: r4sas <r4sas@i2pmail.org>
|
||||
Last-Update: 2024-12-30
|
||||
Last-Update: 2022-03-23
|
||||
|
||||
--- i2pd.orig/Makefile
|
||||
+++ i2pd/Makefile
|
||||
@@ -31,7 +31,7 @@ # import source files lists
|
||||
include filelist.mk
|
||||
@@ -31,7 +31,7 @@ include filelist.mk
|
||||
|
||||
USE_AESNI := $(or $(USE_AESNI),yes)
|
||||
USE_STATIC := $(or $(USE_STATIC),no)
|
||||
-USE_UPNP := $(or $(USE_UPNP),no)
|
||||
+USE_UPNP := $(or $(USE_UPNP),yes)
|
||||
|
||||
@@ -2,13 +2,13 @@ Description: Enable UPnP usage in package
|
||||
Author: r4sas <r4sas@i2pmail.org>
|
||||
|
||||
Reviewed-By: r4sas <r4sas@i2pmail.org>
|
||||
Last-Update: 2024-12-30
|
||||
Last-Update: 2022-03-23
|
||||
|
||||
--- i2pd.orig/Makefile
|
||||
+++ i2pd/Makefile
|
||||
@@ -31,7 +31,7 @@ # import source files lists
|
||||
include filelist.mk
|
||||
@@ -31,7 +31,7 @@ include filelist.mk
|
||||
|
||||
USE_AESNI := $(or $(USE_AESNI),yes)
|
||||
USE_STATIC := $(or $(USE_STATIC),no)
|
||||
-USE_UPNP := $(or $(USE_UPNP),no)
|
||||
+USE_UPNP := $(or $(USE_UPNP),yes)
|
||||
|
||||
@@ -243,7 +243,7 @@ verify = true
|
||||
## Default: reg.i2p at "mainline" I2P Network
|
||||
# defaulturl = http://shx5vqsw7usdaunyzr2qmes2fq37oumybpudrd4jjj4e4vk4uusa.b32.i2p/hosts.txt
|
||||
## Optional subscriptions URLs, separated by comma
|
||||
# subscriptions = http://reg.i2p/hosts.txt,http://identiguy.i2p/hosts.txt,http://stats.i2p/cgi-bin/newhosts.txt
|
||||
# subscriptions = http://reg.i2p/hosts.txt,http://identiguy.i2p/hosts.txt,http://stats.i2p/cgi-bin/newhosts.txt,http://rus.i2p/hosts.txt
|
||||
|
||||
[limits]
|
||||
## Maximum active transit sessions (default: 5000)
|
||||
@@ -277,3 +277,9 @@ verify = true
|
||||
## Save full addresses on disk (default: true)
|
||||
# addressbook = true
|
||||
|
||||
[cpuext]
|
||||
## Use CPU AES-NI instructions set when work with cryptography when available (default: true)
|
||||
# aesni = true
|
||||
## Force usage of CPU instructions set, even if they not found (default: false)
|
||||
## DO NOT TOUCH that option if you really don't know what are you doing!
|
||||
# force = false
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
%define git_hash %(git rev-parse HEAD | cut -c -7)
|
||||
|
||||
Name: i2pd-git
|
||||
Version: 2.55.0
|
||||
Version: 2.54.0
|
||||
Release: git%{git_hash}%{?dist}
|
||||
Summary: I2P router written in C++
|
||||
Conflicts: i2pd
|
||||
@@ -148,9 +148,6 @@ getent passwd i2pd >/dev/null || \
|
||||
|
||||
|
||||
%changelog
|
||||
* Mon Dec 30 2024 orignal <orignal@i2pmail.org> - 2.55.0
|
||||
- update to 2.55.0
|
||||
|
||||
* Sun Oct 6 2024 orignal <orignal@i2pmail.org> - 2.54.0
|
||||
- update to 2.54.0
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Name: i2pd
|
||||
Version: 2.55.0
|
||||
Version: 2.54.0
|
||||
Release: 1%{?dist}
|
||||
Summary: I2P router written in C++
|
||||
Conflicts: i2pd-git
|
||||
@@ -146,9 +146,6 @@ getent passwd i2pd >/dev/null || \
|
||||
|
||||
|
||||
%changelog
|
||||
* Mon Dec 30 2024 orignal <orignal@i2pmail.org> - 2.55.0
|
||||
- update to 2.55.0
|
||||
|
||||
* Sun Oct 6 2024 orignal <orignal@i2pmail.org> - 2.54.0
|
||||
- update to 2.54.0
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ port = 6668
|
||||
destination = irc.ilita.i2p
|
||||
destinationport = 6667
|
||||
keys = irc-keys.dat
|
||||
i2p.streaming.profile=2
|
||||
|
||||
#[IRC-IRC2P]
|
||||
#type = client
|
||||
|
||||
@@ -149,10 +149,12 @@ namespace util
|
||||
LogPrint(eLogDebug, "FS: Certificates directory: ", certsdir);
|
||||
|
||||
bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation);
|
||||
bool aesni; i2p::config::GetOption("cpuext.aesni", aesni);
|
||||
bool forceCpuExt; i2p::config::GetOption("cpuext.force", forceCpuExt);
|
||||
bool ssu; i2p::config::GetOption("ssu", ssu);
|
||||
if (!ssu && i2p::config::IsDefault ("precomputation.elgamal"))
|
||||
precomputation = false; // we don't elgamal table if no ssu, unless it's specified explicitly
|
||||
i2p::crypto::InitCrypto (precomputation);
|
||||
i2p::crypto::InitCrypto (precomputation, aesni, forceCpuExt);
|
||||
|
||||
i2p::transport::InitAddressFromIface (); // get address4/6 from interfaces
|
||||
|
||||
|
||||
@@ -826,7 +826,7 @@ namespace http {
|
||||
if (i2p::tunnel::tunnels.CountTransitTunnels())
|
||||
{
|
||||
s << "<b>" << tr("Transit Tunnels") << ":</b><br>\r\n";
|
||||
s << "<table><thead><th>⇒</th><th>ID</th><th>⇒</th><th>" << tr("Amount") << "</th><th>" << tr("Next") << "</th></thead><tbody class=\"tableitem\">";
|
||||
s << "<table><thead><th>⇒</th><th>ID</th><th>⇒</th><th>" << tr("Amount") << "</th></thead><tbody class=\"tableitem\">";
|
||||
for (const auto& it: i2p::tunnel::tunnels.GetTransitTunnels ())
|
||||
{
|
||||
if (std::dynamic_pointer_cast<i2p::tunnel::TransitTunnelGateway>(it))
|
||||
@@ -836,7 +836,7 @@ namespace http {
|
||||
else
|
||||
s << "<tr><td>⇒</td><td>" << it->GetTunnelID () << "</td><td>⇒</td><td>";
|
||||
ShowTraffic(s, it->GetNumTransmittedBytes ());
|
||||
s << "</td><td>" << it->GetNextPeerName () << "</td></tr>\r\n";
|
||||
s << "</td></tr>\r\n";
|
||||
}
|
||||
s << "</tbody></table>\r\n";
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ namespace transport
|
||||
{
|
||||
m_IsRunning = true;
|
||||
LogPrint(eLogInfo, "UPnP: Starting");
|
||||
boost::asio::post (m_Service, std::bind (&UPnP::Discover, this));
|
||||
m_Service.post (std::bind (&UPnP::Discover, this));
|
||||
std::unique_lock<std::mutex> l(m_StartedMutex);
|
||||
m_Thread.reset (new std::thread (std::bind (&UPnP::Run, this)));
|
||||
m_Started.wait_for (l, std::chrono::seconds (5)); // 5 seconds maximum
|
||||
@@ -150,7 +150,7 @@ namespace transport
|
||||
|
||||
// UPnP discovered
|
||||
LogPrint (eLogDebug, "UPnP: ExternalIPAddress is ", m_externalIPAddress);
|
||||
i2p::context.UpdateAddress (boost::asio::ip::make_address (m_externalIPAddress));
|
||||
i2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));
|
||||
// port mapping
|
||||
PortMapping ();
|
||||
}
|
||||
|
||||
6
debian/changelog
vendored
6
debian/changelog
vendored
@@ -1,9 +1,3 @@
|
||||
i2pd (2.55.0-1) unstable; urgency=medium
|
||||
|
||||
* updated to version 2.55.0
|
||||
|
||||
-- orignal <orignal@i2pmail.org> Mon, 30 Dec 2024 16:00:00 +0000
|
||||
|
||||
i2pd (2.54.0-1) unstable; urgency=medium
|
||||
|
||||
* updated to version 2.54.0/0.9.64
|
||||
|
||||
6
debian/patches/01-upnp.patch
vendored
6
debian/patches/01-upnp.patch
vendored
@@ -2,13 +2,13 @@ Description: Enable UPnP usage in package
|
||||
Author: r4sas <r4sas@i2pmail.org>
|
||||
|
||||
Reviewed-By: r4sas <r4sas@i2pmail.org>
|
||||
Last-Update: 2024-12-30
|
||||
Last-Update: 2022-03-23
|
||||
|
||||
--- i2pd.orig/Makefile
|
||||
+++ i2pd/Makefile
|
||||
@@ -31,7 +31,7 @@ # import source files lists
|
||||
include filelist.mk
|
||||
@@ -31,7 +31,7 @@ include filelist.mk
|
||||
|
||||
USE_AESNI := $(or $(USE_AESNI),yes)
|
||||
USE_STATIC := $(or $(USE_STATIC),no)
|
||||
-USE_UPNP := $(or $(USE_UPNP),no)
|
||||
+USE_UPNP := $(or $(USE_UPNP),yes)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2022, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -152,11 +152,11 @@ namespace data
|
||||
m_BlindedSigType = m_SigType;
|
||||
}
|
||||
|
||||
BlindedPublicKey::BlindedPublicKey (std::string_view b33):
|
||||
BlindedPublicKey::BlindedPublicKey (const std::string& b33):
|
||||
m_SigType (0) // 0 means invalid, we can't blind DSA, set it later
|
||||
{
|
||||
uint8_t addr[40]; // TODO: define length from b33
|
||||
size_t l = i2p::data::Base32ToByteStream (b33.data (), b33.length (), addr, 40);
|
||||
size_t l = i2p::data::Base32ToByteStream (b33.c_str (), b33.length (), addr, 40);
|
||||
if (l < 32)
|
||||
{
|
||||
LogPrint (eLogError, "Blinding: Malformed b33 ", b33);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2020, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
#include "Identity.h"
|
||||
|
||||
@@ -24,7 +23,7 @@ namespace data
|
||||
public:
|
||||
|
||||
BlindedPublicKey (std::shared_ptr<const IdentityEx> identity, bool clientAuth = false);
|
||||
BlindedPublicKey (std::string_view b33); // from b33 without .b32.i2p
|
||||
BlindedPublicKey (const std::string& b33); // from b33 without .b32.i2p
|
||||
std::string ToB33 () const;
|
||||
|
||||
const uint8_t * GetPublicKey () const { return m_PublicKey.data (); };
|
||||
|
||||
68
libi2pd/CPU.cpp
Normal file
68
libi2pd/CPU.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2023, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
* See full license text in LICENSE file at top of project tree
|
||||
*/
|
||||
|
||||
#include "CPU.h"
|
||||
#include "Log.h"
|
||||
|
||||
#ifndef bit_AES
|
||||
#define bit_AES (1 << 25)
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) && __GNUC__ < 6 && IS_X86
|
||||
#include <cpuid.h>
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <intrin.h>
|
||||
#endif
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace cpu
|
||||
{
|
||||
bool aesni = false;
|
||||
|
||||
inline bool cpu_support_aes()
|
||||
{
|
||||
#if IS_X86
|
||||
#if defined(__clang__)
|
||||
# if (__clang_major__ >= 6)
|
||||
__builtin_cpu_init();
|
||||
# endif
|
||||
return __builtin_cpu_supports("aes");
|
||||
#elif (defined(__GNUC__) && __GNUC__ >= 6)
|
||||
__builtin_cpu_init();
|
||||
return __builtin_cpu_supports("aes");
|
||||
#elif (defined(__GNUC__) && __GNUC__ < 6)
|
||||
int cpu_info[4];
|
||||
bool flag = false;
|
||||
__cpuid(0, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]);
|
||||
if (cpu_info[0] >= 0x00000001) {
|
||||
__cpuid(0x00000001, cpu_info[0], cpu_info[1], cpu_info[2], cpu_info[3]);
|
||||
flag = ((cpu_info[2] & bit_AES) != 0);
|
||||
}
|
||||
return flag;
|
||||
#elif defined(_MSC_VER)
|
||||
int cpu_info[4];
|
||||
__cpuid(cpu_info, 1);
|
||||
return ((cpu_info[2] & bit_AES) != 0);
|
||||
#endif
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
void Detect(bool AesSwitch, bool force)
|
||||
{
|
||||
if ((cpu_support_aes() && AesSwitch) || (AesSwitch && force)) {
|
||||
aesni = true;
|
||||
}
|
||||
|
||||
LogPrint(eLogInfo, "AESNI ", (aesni ? "enabled" : "disabled"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2023, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -21,4 +21,20 @@
|
||||
# define IS_X86_64 0
|
||||
#endif
|
||||
|
||||
#if defined(__AES__) && !defined(_MSC_VER) && IS_X86
|
||||
# define SUPPORTS_AES 1
|
||||
#else
|
||||
# define SUPPORTS_AES 0
|
||||
#endif
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace cpu
|
||||
{
|
||||
extern bool aesni;
|
||||
|
||||
void Detect(bool AesSwitch, bool force);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -117,7 +117,7 @@ namespace config {
|
||||
("httpproxy.latency.max", value<std::string>()->default_value("0"), "HTTP proxy max latency for tunnels")
|
||||
("httpproxy.outproxy", value<std::string>()->default_value(""), "HTTP proxy upstream out proxy url")
|
||||
("httpproxy.addresshelper", value<bool>()->default_value(true), "Enable or disable addresshelper")
|
||||
("httpproxy.senduseragent", value<bool>()->default_value(false), "Pass through user's User-Agent if enabled. Disabled by default")
|
||||
("httpproxy.senduseragent", value<bool>()->default_value(false), "Pass through user's User-Agent if enabled. Disabled by deafult")
|
||||
("httpproxy.i2cp.leaseSetType", value<std::string>()->default_value("3"), "Local destination's LeaseSet type")
|
||||
("httpproxy.i2cp.leaseSetEncType", value<std::string>()->default_value("0,4"), "Local destination's LeaseSet encryption type")
|
||||
("httpproxy.i2cp.leaseSetPrivKey", value<std::string>()->default_value(""), "LeaseSet private key")
|
||||
@@ -154,17 +154,6 @@ namespace config {
|
||||
("socksproxy.i2p.streaming.profile", value<std::string>()->default_value("1"), "SOCKS Proxy bandwidth usage profile. 1 - bulk(high), 2- interactive(low)")
|
||||
;
|
||||
|
||||
options_description shareddest("Shared local destination options");
|
||||
shareddest.add_options()
|
||||
("shareddest.inbound.length", value<std::string>()->default_value("3"), "Shared local destination inbound tunnel length")
|
||||
("shareddest.outbound.length", value<std::string>()->default_value("3"), "Shared local destination outbound tunnel length")
|
||||
("shareddest.inbound.quantity", value<std::string>()->default_value("3"), "Shared local destination inbound tunnels quantity")
|
||||
("shareddest.outbound.quantity", value<std::string>()->default_value("3"), "Shared local destination outbound tunnels quantity")
|
||||
("shareddest.i2cp.leaseSetType", value<std::string>()->default_value("3"), "Shared local destination's LeaseSet type")
|
||||
("shareddest.i2cp.leaseSetEncType", value<std::string>()->default_value("0,4"), "Shared local destination's LeaseSet encryption type")
|
||||
("shareddest.i2p.streaming.profile", value<std::string>()->default_value("2"), "Shared local destination bandwidth usage profile. 1 - bulk(high), 2- interactive(low)")
|
||||
;
|
||||
|
||||
options_description sam("SAM bridge options");
|
||||
sam.add_options()
|
||||
("sam.enabled", value<bool>()->default_value(true), "Enable or disable SAM Application bridge")
|
||||
@@ -238,7 +227,7 @@ namespace config {
|
||||
"https://reseed.onion.im/,"
|
||||
"https://i2pseed.creativecowpat.net:8443/,"
|
||||
"https://reseed.i2pgit.org/,"
|
||||
"https://coconut.incognet.io/,"
|
||||
"https://banana.incognet.io/,"
|
||||
"https://reseed-pl.i2pd.xyz/,"
|
||||
"https://www2.mk16.de/,"
|
||||
"https://i2p.ghativega.in/,"
|
||||
@@ -326,11 +315,11 @@ namespace config {
|
||||
("persist.addressbook", value<bool>()->default_value(true), "Persist full addresses (default: true)")
|
||||
;
|
||||
|
||||
options_description cpuext("CPU encryption extensions options. Deprecated");
|
||||
options_description cpuext("CPU encryption extensions options");
|
||||
cpuext.add_options()
|
||||
("cpuext.aesni", bool_switch()->default_value(true), "Deprecated option")
|
||||
("cpuext.aesni", bool_switch()->default_value(true), "Use auto detection for AESNI CPU extensions. If false, AESNI will be not used")
|
||||
("cpuext.avx", bool_switch()->default_value(false), "Deprecated option")
|
||||
("cpuext.force", bool_switch()->default_value(false), "Deprecated option")
|
||||
("cpuext.force", bool_switch()->default_value(false), "Force usage of CPU extensions. Useful when cpuinfo is not available on virtual machines")
|
||||
;
|
||||
|
||||
options_description meshnets("Meshnet transports options");
|
||||
@@ -352,7 +341,6 @@ namespace config {
|
||||
.add(httpserver)
|
||||
.add(httpproxy)
|
||||
.add(socksproxy)
|
||||
.add(shareddest)
|
||||
.add(sam)
|
||||
.add(bob)
|
||||
.add(i2cp)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -19,7 +19,6 @@
|
||||
#if OPENSSL_HKDF
|
||||
#include <openssl/kdf.h>
|
||||
#endif
|
||||
#include "CPU.h"
|
||||
#include "Crypto.h"
|
||||
#include "Ed25519.h"
|
||||
#include "I2PEndian.h"
|
||||
@@ -442,8 +441,9 @@ namespace crypto
|
||||
// encrypt
|
||||
CBCEncryption encryption;
|
||||
encryption.SetKey (shared);
|
||||
encryption.SetIV (iv);
|
||||
encrypted[257] = 0;
|
||||
encryption.Encrypt (m, 256, iv, encrypted + 258);
|
||||
encryption.Encrypt (m, 256, encrypted + 258);
|
||||
EC_POINT_free (p);
|
||||
BN_CTX_end (ctx);
|
||||
BN_CTX_free (ctx);
|
||||
@@ -476,7 +476,8 @@ namespace crypto
|
||||
uint8_t m[256];
|
||||
CBCDecryption decryption;
|
||||
decryption.SetKey (shared);
|
||||
decryption.Decrypt (encrypted + 258, 256, iv, m);
|
||||
decryption.SetIV (iv);
|
||||
decryption.Decrypt (encrypted + 258, 256, m);
|
||||
// verify and copy
|
||||
uint8_t hash[32];
|
||||
SHA256 (m + 33, 222, hash);
|
||||
@@ -514,114 +515,440 @@ namespace crypto
|
||||
}
|
||||
|
||||
// AES
|
||||
ECBEncryption::ECBEncryption ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
ECBEncryption::~ECBEncryption ()
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
void ECBEncryption::Encrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
EVP_EncryptInit_ex (m_Ctx, EVP_aes_256_ecb(), NULL, m_Key, NULL);
|
||||
EVP_CIPHER_CTX_set_padding (m_Ctx, 0);
|
||||
int len;
|
||||
EVP_EncryptUpdate (m_Ctx, out, &len, in, 16);
|
||||
EVP_EncryptFinal_ex (m_Ctx, out + len, &len);
|
||||
}
|
||||
#if SUPPORTS_AES
|
||||
#define KeyExpansion256(round0,round1) \
|
||||
"pshufd $0xff, %%xmm2, %%xmm2 \n" \
|
||||
"movaps %%xmm1, %%xmm4 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm1 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm1 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm1 \n" \
|
||||
"pxor %%xmm2, %%xmm1 \n" \
|
||||
"movaps %%xmm1, "#round0"(%[sched]) \n" \
|
||||
"aeskeygenassist $0, %%xmm1, %%xmm4 \n" \
|
||||
"pshufd $0xaa, %%xmm4, %%xmm2 \n" \
|
||||
"movaps %%xmm3, %%xmm4 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
"pslldq $4, %%xmm4 \n" \
|
||||
"pxor %%xmm4, %%xmm3 \n" \
|
||||
"pxor %%xmm2, %%xmm3 \n" \
|
||||
"movaps %%xmm3, "#round1"(%[sched]) \n"
|
||||
#endif
|
||||
|
||||
ECBDecryption::ECBDecryption ()
|
||||
#if SUPPORTS_AES
|
||||
void ECBCryptoAESNI::ExpandKey (const AESKey& key)
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
ECBDecryption::~ECBDecryption ()
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
void ECBDecryption::Decrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
EVP_DecryptInit_ex (m_Ctx, EVP_aes_256_ecb(), NULL, m_Key, NULL);
|
||||
EVP_CIPHER_CTX_set_padding (m_Ctx, 0);
|
||||
int len;
|
||||
EVP_DecryptUpdate (m_Ctx, out, &len, in, 16);
|
||||
EVP_DecryptFinal_ex (m_Ctx, out + len, &len);
|
||||
__asm__
|
||||
(
|
||||
"movups (%[key]), %%xmm1 \n"
|
||||
"movups 16(%[key]), %%xmm3 \n"
|
||||
"movaps %%xmm1, (%[sched]) \n"
|
||||
"movaps %%xmm3, 16(%[sched]) \n"
|
||||
"aeskeygenassist $1, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(32,48)
|
||||
"aeskeygenassist $2, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(64,80)
|
||||
"aeskeygenassist $4, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(96,112)
|
||||
"aeskeygenassist $8, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(128,144)
|
||||
"aeskeygenassist $16, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(160,176)
|
||||
"aeskeygenassist $32, %%xmm3, %%xmm2 \n"
|
||||
KeyExpansion256(192,208)
|
||||
"aeskeygenassist $64, %%xmm3, %%xmm2 \n"
|
||||
// key expansion final
|
||||
"pshufd $0xff, %%xmm2, %%xmm2 \n"
|
||||
"movaps %%xmm1, %%xmm4 \n"
|
||||
"pslldq $4, %%xmm4 \n"
|
||||
"pxor %%xmm4, %%xmm1 \n"
|
||||
"pslldq $4, %%xmm4 \n"
|
||||
"pxor %%xmm4, %%xmm1 \n"
|
||||
"pslldq $4, %%xmm4 \n"
|
||||
"pxor %%xmm4, %%xmm1 \n"
|
||||
"pxor %%xmm2, %%xmm1 \n"
|
||||
"movups %%xmm1, 224(%[sched]) \n"
|
||||
: // output
|
||||
: [key]"r"((const uint8_t *)key), [sched]"r"(GetKeySchedule ()) // input
|
||||
: "%xmm1", "%xmm2", "%xmm3", "%xmm4", "memory" // clogged
|
||||
);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
CBCEncryption::CBCEncryption ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
CBCEncryption::~CBCEncryption ()
|
||||
#if SUPPORTS_AES
|
||||
#define EncryptAES256(sched) \
|
||||
"pxor (%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 16(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 32(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 48(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 64(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 80(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 96(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 112(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 128(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 144(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 160(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 176(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 192(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenc 208(%["#sched"]), %%xmm0 \n" \
|
||||
"aesenclast 224(%["#sched"]), %%xmm0 \n"
|
||||
#endif
|
||||
|
||||
void ECBEncryption::Encrypt (const ChipherBlock * in, ChipherBlock * out)
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
void CBCEncryption::Encrypt (const uint8_t * in, size_t len, const uint8_t * iv, uint8_t * out)
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
EncryptAES256(sched)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
:
|
||||
: [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out)
|
||||
: "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
AES_encrypt (in->buf, out->buf, &m_Key);
|
||||
}
|
||||
}
|
||||
|
||||
#if SUPPORTS_AES
|
||||
#define DecryptAES256(sched) \
|
||||
"pxor 224(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 208(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 192(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 176(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 160(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 144(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 128(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 112(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 96(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 80(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 64(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 48(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 32(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdec 16(%["#sched"]), %%xmm0 \n" \
|
||||
"aesdeclast (%["#sched"]), %%xmm0 \n"
|
||||
#endif
|
||||
|
||||
void ECBDecryption::Decrypt (const ChipherBlock * in, ChipherBlock * out)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
DecryptAES256(sched)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
:
|
||||
: [sched]"r"(GetKeySchedule ()), [in]"r"(in), [out]"r"(out)
|
||||
: "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
AES_decrypt (in->buf, out->buf, &m_Key);
|
||||
}
|
||||
}
|
||||
|
||||
#if SUPPORTS_AES
|
||||
#define CallAESIMC(offset) \
|
||||
"movaps "#offset"(%[shed]), %%xmm0 \n" \
|
||||
"aesimc %%xmm0, %%xmm0 \n" \
|
||||
"movaps %%xmm0, "#offset"(%[shed]) \n"
|
||||
#endif
|
||||
|
||||
void ECBEncryption::SetKey (const AESKey& key)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
ExpandKey (key);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
AES_set_encrypt_key (key, 256, &m_Key);
|
||||
}
|
||||
}
|
||||
|
||||
void ECBDecryption::SetKey (const AESKey& key)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
ExpandKey (key); // expand encryption key first
|
||||
// then invert it using aesimc
|
||||
__asm__
|
||||
(
|
||||
CallAESIMC(16)
|
||||
CallAESIMC(32)
|
||||
CallAESIMC(48)
|
||||
CallAESIMC(64)
|
||||
CallAESIMC(80)
|
||||
CallAESIMC(96)
|
||||
CallAESIMC(112)
|
||||
CallAESIMC(128)
|
||||
CallAESIMC(144)
|
||||
CallAESIMC(160)
|
||||
CallAESIMC(176)
|
||||
CallAESIMC(192)
|
||||
CallAESIMC(208)
|
||||
:
|
||||
: [shed]"r"(GetKeySchedule ())
|
||||
: "%xmm0", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
AES_set_decrypt_key (key, 256, &m_Key);
|
||||
}
|
||||
}
|
||||
|
||||
void CBCEncryption::Encrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"1: \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
EncryptAES256(sched)
|
||||
"movaps %%xmm0, %%xmm1 \n"
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"dec %[num] \n"
|
||||
"jnz 1b \n"
|
||||
"movups %%xmm1, (%[iv]) \n"
|
||||
:
|
||||
: [iv]"r"((uint8_t *)m_LastBlock), [sched]"r"(m_ECBEncryption.GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out), [num]"r"(numBlocks)
|
||||
: "%xmm0", "%xmm1", "cc", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
for (int i = 0; i < numBlocks; i++)
|
||||
{
|
||||
*m_LastBlock.GetChipherBlock () ^= in[i];
|
||||
m_ECBEncryption.Encrypt (m_LastBlock.GetChipherBlock (), m_LastBlock.GetChipherBlock ());
|
||||
out[i] = *m_LastBlock.GetChipherBlock ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CBCEncryption::Encrypt (const uint8_t * in, std::size_t len, uint8_t * out)
|
||||
{
|
||||
// len/16
|
||||
EVP_EncryptInit_ex (m_Ctx, EVP_aes_256_cbc(), NULL, m_Key, iv);
|
||||
EVP_CIPHER_CTX_set_padding (m_Ctx, 0);
|
||||
int l;
|
||||
EVP_EncryptUpdate (m_Ctx, out, &l, in, len);
|
||||
EVP_EncryptFinal_ex (m_Ctx, out + l, &l);
|
||||
int numBlocks = len >> 4;
|
||||
if (numBlocks > 0)
|
||||
Encrypt (numBlocks, (const ChipherBlock *)in, (ChipherBlock *)out);
|
||||
}
|
||||
|
||||
CBCDecryption::CBCDecryption ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
void CBCEncryption::Encrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
EncryptAES256(sched)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
"movups %%xmm0, (%[iv]) \n"
|
||||
:
|
||||
: [iv]"r"((uint8_t *)m_LastBlock), [sched]"r"(m_ECBEncryption.GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out)
|
||||
: "%xmm0", "%xmm1", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
Encrypt (1, (const ChipherBlock *)in, (ChipherBlock *)out);
|
||||
}
|
||||
|
||||
CBCDecryption::~CBCDecryption ()
|
||||
|
||||
void CBCDecryption::Decrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out)
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
void CBCDecryption::Decrypt (const uint8_t * in, size_t len, const uint8_t * iv, uint8_t * out)
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"1: \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"movaps %%xmm0, %%xmm2 \n"
|
||||
DecryptAES256(sched)
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
"movaps %%xmm2, %%xmm1 \n"
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"dec %[num] \n"
|
||||
"jnz 1b \n"
|
||||
"movups %%xmm1, (%[iv]) \n"
|
||||
:
|
||||
: [iv]"r"((uint8_t *)m_IV), [sched]"r"(m_ECBDecryption.GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out), [num]"r"(numBlocks)
|
||||
: "%xmm0", "%xmm1", "%xmm2", "cc", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
for (int i = 0; i < numBlocks; i++)
|
||||
{
|
||||
ChipherBlock tmp = in[i];
|
||||
m_ECBDecryption.Decrypt (in + i, out + i);
|
||||
out[i] ^= *m_IV.GetChipherBlock ();
|
||||
*m_IV.GetChipherBlock () = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CBCDecryption::Decrypt (const uint8_t * in, std::size_t len, uint8_t * out)
|
||||
{
|
||||
// len/16
|
||||
EVP_DecryptInit_ex (m_Ctx, EVP_aes_256_cbc(), NULL, m_Key, iv);
|
||||
EVP_CIPHER_CTX_set_padding (m_Ctx, 0);
|
||||
int l;
|
||||
EVP_DecryptUpdate (m_Ctx, out, &l, in, len);
|
||||
EVP_DecryptFinal_ex (m_Ctx, out + l, &l);
|
||||
int numBlocks = len >> 4;
|
||||
if (numBlocks > 0)
|
||||
Decrypt (numBlocks, (const ChipherBlock *)in, (ChipherBlock *)out);
|
||||
}
|
||||
|
||||
void CBCDecryption::Decrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
"movups (%[iv]), %%xmm1 \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"movups %%xmm0, (%[iv]) \n"
|
||||
DecryptAES256(sched)
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
:
|
||||
: [iv]"r"((uint8_t *)m_IV), [sched]"r"(m_ECBDecryption.GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out)
|
||||
: "%xmm0", "%xmm1", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
Decrypt (1, (const ChipherBlock *)in, (ChipherBlock *)out);
|
||||
}
|
||||
|
||||
void TunnelEncryption::Encrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
uint8_t iv[16];
|
||||
m_IVEncryption.Encrypt (in, iv); // iv
|
||||
m_LayerEncryption.Encrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, iv, out + 16); // data
|
||||
m_IVEncryption.Encrypt (iv, out); // double iv
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
// encrypt IV
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
EncryptAES256(sched_iv)
|
||||
"movaps %%xmm0, %%xmm1 \n"
|
||||
// double IV encryption
|
||||
EncryptAES256(sched_iv)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
// encrypt data, IV is xmm1
|
||||
"1: \n"
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
EncryptAES256(sched_l)
|
||||
"movaps %%xmm0, %%xmm1 \n"
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
"dec %[num] \n"
|
||||
"jnz 1b \n"
|
||||
:
|
||||
: [sched_iv]"r"(m_IVEncryption.GetKeySchedule ()), [sched_l]"r"(m_LayerEncryption.ECB().GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out), [num]"r"(63) // 63 blocks = 1008 bytes
|
||||
: "%xmm0", "%xmm1", "cc", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
m_IVEncryption.Encrypt ((const ChipherBlock *)in, (ChipherBlock *)out); // iv
|
||||
m_LayerEncryption.SetIV (out);
|
||||
m_LayerEncryption.Encrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, out + 16); // data
|
||||
m_IVEncryption.Encrypt ((ChipherBlock *)out, (ChipherBlock *)out); // double iv
|
||||
}
|
||||
}
|
||||
|
||||
void TunnelDecryption::Decrypt (const uint8_t * in, uint8_t * out)
|
||||
{
|
||||
uint8_t iv[16];
|
||||
m_IVDecryption.Decrypt (in, iv); // iv
|
||||
m_LayerDecryption.Decrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, iv, out + 16); // data
|
||||
m_IVDecryption.Decrypt (iv, out); // double iv
|
||||
#if SUPPORTS_AES
|
||||
if(i2p::cpu::aesni)
|
||||
{
|
||||
__asm__
|
||||
(
|
||||
// decrypt IV
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
DecryptAES256(sched_iv)
|
||||
"movaps %%xmm0, %%xmm1 \n"
|
||||
// double IV encryption
|
||||
DecryptAES256(sched_iv)
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
// decrypt data, IV is xmm1
|
||||
"1: \n"
|
||||
"add $16, %[in] \n"
|
||||
"add $16, %[out] \n"
|
||||
"movups (%[in]), %%xmm0 \n"
|
||||
"movaps %%xmm0, %%xmm2 \n"
|
||||
DecryptAES256(sched_l)
|
||||
"pxor %%xmm1, %%xmm0 \n"
|
||||
"movups %%xmm0, (%[out]) \n"
|
||||
"movaps %%xmm2, %%xmm1 \n"
|
||||
"dec %[num] \n"
|
||||
"jnz 1b \n"
|
||||
:
|
||||
: [sched_iv]"r"(m_IVDecryption.GetKeySchedule ()), [sched_l]"r"(m_LayerDecryption.ECB().GetKeySchedule ()),
|
||||
[in]"r"(in), [out]"r"(out), [num]"r"(63) // 63 blocks = 1008 bytes
|
||||
: "%xmm0", "%xmm1", "%xmm2", "cc", "memory"
|
||||
);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
m_IVDecryption.Decrypt ((const ChipherBlock *)in, (ChipherBlock *)out); // iv
|
||||
m_LayerDecryption.SetIV (out);
|
||||
m_LayerDecryption.Decrypt (in + 16, i2p::tunnel::TUNNEL_DATA_ENCRYPTED_SIZE, out + 16); // data
|
||||
m_IVDecryption.Decrypt ((ChipherBlock *)out, (ChipherBlock *)out); // double iv
|
||||
}
|
||||
}
|
||||
|
||||
// AEAD/ChaCha20/Poly1305
|
||||
|
||||
static bool AEADChaCha20Poly1305 (EVP_CIPHER_CTX * ctx, const uint8_t * msg, size_t msgLen,
|
||||
const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt)
|
||||
bool AEADChaCha20Poly1305 (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt)
|
||||
{
|
||||
if (!ctx || len < msgLen) return false;
|
||||
if (len < msgLen) return false;
|
||||
if (encrypt && len < msgLen + 16) return false;
|
||||
bool ret = true;
|
||||
int outlen = 0;
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
|
||||
if (encrypt)
|
||||
{
|
||||
EVP_EncryptInit_ex(ctx, EVP_chacha20_poly1305(), 0, 0, 0);
|
||||
@@ -651,100 +978,38 @@ namespace crypto
|
||||
EVP_DecryptUpdate(ctx, buf, &outlen, msg, msgLen);
|
||||
ret = EVP_DecryptFinal_ex(ctx, buf + outlen, &outlen) > 0;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool AEADChaCha20Poly1305 (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt)
|
||||
{
|
||||
EVP_CIPHER_CTX * ctx = EVP_CIPHER_CTX_new ();
|
||||
auto ret = AEADChaCha20Poly1305 (ctx, msg, msgLen, ad, adLen, key, nonce, buf, len, encrypt);
|
||||
EVP_CIPHER_CTX_free (ctx);
|
||||
return ret;
|
||||
}
|
||||
|
||||
AEADChaCha20Poly1305Encryptor::AEADChaCha20Poly1305Encryptor ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
AEADChaCha20Poly1305Encryptor::~AEADChaCha20Poly1305Encryptor ()
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
bool AEADChaCha20Poly1305Encryptor::Encrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return AEADChaCha20Poly1305 (m_Ctx, msg, msgLen, ad, adLen, key, nonce, buf, len, true);
|
||||
}
|
||||
|
||||
void AEADChaCha20Poly1305Encryptor::Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * mac)
|
||||
void AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs, const uint8_t * key, const uint8_t * nonce, uint8_t * mac)
|
||||
{
|
||||
if (bufs.empty ()) return;
|
||||
int outlen = 0;
|
||||
EVP_EncryptInit_ex(m_Ctx, EVP_chacha20_poly1305(), 0, 0, 0);
|
||||
EVP_CIPHER_CTX_ctrl(m_Ctx, EVP_CTRL_AEAD_SET_IVLEN, 12, 0);
|
||||
EVP_EncryptInit_ex(m_Ctx, NULL, NULL, key, nonce);
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
|
||||
EVP_EncryptInit_ex(ctx, EVP_chacha20_poly1305(), 0, 0, 0);
|
||||
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, 12, 0);
|
||||
EVP_EncryptInit_ex(ctx, NULL, NULL, key, nonce);
|
||||
for (const auto& it: bufs)
|
||||
EVP_EncryptUpdate(m_Ctx, it.first, &outlen, it.first, it.second);
|
||||
EVP_EncryptFinal_ex(m_Ctx, NULL, &outlen);
|
||||
EVP_CIPHER_CTX_ctrl(m_Ctx, EVP_CTRL_AEAD_GET_TAG, 16, mac);
|
||||
}
|
||||
|
||||
AEADChaCha20Poly1305Decryptor::AEADChaCha20Poly1305Decryptor ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
AEADChaCha20Poly1305Decryptor::~AEADChaCha20Poly1305Decryptor ()
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
bool AEADChaCha20Poly1305Decryptor::Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return AEADChaCha20Poly1305 (m_Ctx, msg, msgLen, ad, adLen, key, nonce, buf, len, false);
|
||||
EVP_EncryptUpdate(ctx, it.first, &outlen, it.first, it.second);
|
||||
EVP_EncryptFinal_ex(ctx, NULL, &outlen);
|
||||
EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, mac);
|
||||
EVP_CIPHER_CTX_free (ctx);
|
||||
}
|
||||
|
||||
static void ChaCha20 (EVP_CIPHER_CTX *ctx, const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out)
|
||||
void ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out)
|
||||
{
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
|
||||
uint32_t iv[4];
|
||||
iv[0] = htole32 (1); memcpy (iv + 1, nonce, 12); // counter | nonce
|
||||
EVP_EncryptInit_ex(ctx, EVP_chacha20 (), NULL, key, (const uint8_t *)iv);
|
||||
int outlen = 0;
|
||||
EVP_EncryptUpdate(ctx, out, &outlen, msg, msgLen);
|
||||
EVP_EncryptFinal_ex(ctx, NULL, &outlen);
|
||||
}
|
||||
|
||||
void ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out)
|
||||
{
|
||||
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new ();
|
||||
ChaCha20 (ctx, msg, msgLen, key, nonce, out);
|
||||
EVP_CIPHER_CTX_free (ctx);
|
||||
}
|
||||
|
||||
|
||||
ChaCha20Context::ChaCha20Context ()
|
||||
{
|
||||
m_Ctx = EVP_CIPHER_CTX_new ();
|
||||
}
|
||||
|
||||
ChaCha20Context::~ChaCha20Context ()
|
||||
{
|
||||
if (m_Ctx)
|
||||
EVP_CIPHER_CTX_free (m_Ctx);
|
||||
}
|
||||
|
||||
void ChaCha20Context::operator ()(const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out)
|
||||
{
|
||||
ChaCha20 (m_Ctx, msg, msgLen, key, nonce, out);
|
||||
}
|
||||
|
||||
void HKDF (const uint8_t * salt, const uint8_t * key, size_t keyLen, const std::string& info,
|
||||
uint8_t * out, size_t outLen)
|
||||
{
|
||||
@@ -892,8 +1157,9 @@ namespace crypto
|
||||
}
|
||||
}*/
|
||||
|
||||
void InitCrypto (bool precomputation)
|
||||
void InitCrypto (bool precomputation, bool aesni, bool force)
|
||||
{
|
||||
i2p::cpu::Detect (aesni, force);
|
||||
/* auto numLocks = CRYPTO_num_locks();
|
||||
for (int i = 0; i < numLocks; i++)
|
||||
m_OpenSSLMutexes.emplace_back (new std::mutex);
|
||||
|
||||
202
libi2pd/Crypto.h
202
libi2pd/Crypto.h
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -25,6 +25,7 @@
|
||||
|
||||
#include "Base.h"
|
||||
#include "Tag.h"
|
||||
#include "CPU.h"
|
||||
|
||||
// recognize openssl version and features
|
||||
#if (OPENSSL_VERSION_NUMBER >= 0x010101000) // 1.1.1
|
||||
@@ -84,70 +85,142 @@ namespace crypto
|
||||
void GenerateECIESKeyPair (const EC_GROUP * curve, BIGNUM *& priv, EC_POINT *& pub);
|
||||
|
||||
// AES
|
||||
typedef i2p::data::Tag<32> AESKey;
|
||||
|
||||
class ECBEncryption
|
||||
struct ChipherBlock
|
||||
{
|
||||
public:
|
||||
uint8_t buf[16];
|
||||
|
||||
ECBEncryption ();
|
||||
~ECBEncryption ();
|
||||
|
||||
void SetKey (const uint8_t * key) { m_Key = key; };
|
||||
void Encrypt(const uint8_t * in, uint8_t * out);
|
||||
|
||||
private:
|
||||
|
||||
AESKey m_Key;
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
void operator^=(const ChipherBlock& other) // XOR
|
||||
{
|
||||
if (!(((size_t)buf | (size_t)other.buf) & 0x03)) // multiple of 4 ?
|
||||
{
|
||||
for (int i = 0; i < 4; i++)
|
||||
reinterpret_cast<uint32_t *>(buf)[i] ^= reinterpret_cast<const uint32_t *>(other.buf)[i];
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
buf[i] ^= other.buf[i];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class ECBDecryption
|
||||
typedef i2p::data::Tag<32> AESKey;
|
||||
|
||||
template<size_t sz>
|
||||
class AESAlignedBuffer // 16 bytes alignment
|
||||
{
|
||||
public:
|
||||
|
||||
ECBDecryption ();
|
||||
~ECBDecryption ();
|
||||
|
||||
void SetKey (const uint8_t * key) { m_Key = key; };
|
||||
void Decrypt (const uint8_t * in, uint8_t * out);
|
||||
|
||||
AESAlignedBuffer ()
|
||||
{
|
||||
m_Buf = m_UnalignedBuffer;
|
||||
uint8_t rem = ((size_t)m_Buf) & 0x0f;
|
||||
if (rem)
|
||||
m_Buf += (16 - rem);
|
||||
}
|
||||
|
||||
operator uint8_t * () { return m_Buf; };
|
||||
operator const uint8_t * () const { return m_Buf; };
|
||||
ChipherBlock * GetChipherBlock () { return (ChipherBlock *)m_Buf; };
|
||||
const ChipherBlock * GetChipherBlock () const { return (const ChipherBlock *)m_Buf; };
|
||||
|
||||
private:
|
||||
|
||||
AESKey m_Key;
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
|
||||
uint8_t m_UnalignedBuffer[sz + 15]; // up to 15 bytes alignment
|
||||
uint8_t * m_Buf;
|
||||
};
|
||||
|
||||
|
||||
#if SUPPORTS_AES
|
||||
class ECBCryptoAESNI
|
||||
{
|
||||
public:
|
||||
|
||||
uint8_t * GetKeySchedule () { return m_KeySchedule; };
|
||||
|
||||
protected:
|
||||
|
||||
void ExpandKey (const AESKey& key);
|
||||
|
||||
private:
|
||||
|
||||
AESAlignedBuffer<240> m_KeySchedule; // 14 rounds for AES-256, 240 bytes
|
||||
};
|
||||
#endif
|
||||
|
||||
#if SUPPORTS_AES
|
||||
class ECBEncryption: public ECBCryptoAESNI
|
||||
#else
|
||||
class ECBEncryption
|
||||
#endif
|
||||
{
|
||||
public:
|
||||
|
||||
void SetKey (const AESKey& key);
|
||||
|
||||
void Encrypt(const ChipherBlock * in, ChipherBlock * out);
|
||||
|
||||
private:
|
||||
AES_KEY m_Key;
|
||||
};
|
||||
|
||||
#if SUPPORTS_AES
|
||||
class ECBDecryption: public ECBCryptoAESNI
|
||||
#else
|
||||
class ECBDecryption
|
||||
#endif
|
||||
{
|
||||
public:
|
||||
|
||||
void SetKey (const AESKey& key);
|
||||
void Decrypt (const ChipherBlock * in, ChipherBlock * out);
|
||||
private:
|
||||
AES_KEY m_Key;
|
||||
};
|
||||
|
||||
class CBCEncryption
|
||||
{
|
||||
public:
|
||||
|
||||
CBCEncryption ();
|
||||
~CBCEncryption ();
|
||||
CBCEncryption () { memset ((uint8_t *)m_LastBlock, 0, 16); };
|
||||
|
||||
void SetKey (const AESKey& key) { m_ECBEncryption.SetKey (key); }; // 32 bytes
|
||||
void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_LastBlock, iv, 16); }; // 16 bytes
|
||||
void GetIV (uint8_t * iv) const { memcpy (iv, (const uint8_t *)m_LastBlock, 16); };
|
||||
|
||||
void Encrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
|
||||
void Encrypt (const uint8_t * in, std::size_t len, uint8_t * out);
|
||||
void Encrypt (const uint8_t * in, uint8_t * out); // one block
|
||||
|
||||
ECBEncryption & ECB() { return m_ECBEncryption; }
|
||||
|
||||
void SetKey (const uint8_t * key) { m_Key = key; }; // 32 bytes
|
||||
void Encrypt (const uint8_t * in, size_t len, const uint8_t * iv, uint8_t * out);
|
||||
|
||||
private:
|
||||
|
||||
AESKey m_Key;
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
AESAlignedBuffer<16> m_LastBlock;
|
||||
|
||||
ECBEncryption m_ECBEncryption;
|
||||
};
|
||||
|
||||
class CBCDecryption
|
||||
{
|
||||
public:
|
||||
|
||||
CBCDecryption ();
|
||||
~CBCDecryption ();
|
||||
|
||||
void SetKey (const uint8_t * key) { m_Key = key; }; // 32 bytes
|
||||
void Decrypt (const uint8_t * in, size_t len, const uint8_t * iv, uint8_t * out);
|
||||
CBCDecryption () { memset ((uint8_t *)m_IV, 0, 16); };
|
||||
|
||||
void SetKey (const AESKey& key) { m_ECBDecryption.SetKey (key); }; // 32 bytes
|
||||
void SetIV (const uint8_t * iv) { memcpy ((uint8_t *)m_IV, iv, 16); }; // 16 bytes
|
||||
void GetIV (uint8_t * iv) const { memcpy (iv, (const uint8_t *)m_IV, 16); };
|
||||
|
||||
void Decrypt (int numBlocks, const ChipherBlock * in, ChipherBlock * out);
|
||||
void Decrypt (const uint8_t * in, std::size_t len, uint8_t * out);
|
||||
void Decrypt (const uint8_t * in, uint8_t * out); // one block
|
||||
|
||||
ECBDecryption & ECB() { return m_ECBDecryption; }
|
||||
|
||||
private:
|
||||
|
||||
AESKey m_Key;
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
AESAlignedBuffer<16> m_IV;
|
||||
ECBDecryption m_ECBDecryption;
|
||||
};
|
||||
|
||||
class TunnelEncryption // with double IV encryption
|
||||
@@ -187,58 +260,13 @@ namespace crypto
|
||||
};
|
||||
|
||||
// AEAD/ChaCha20/Poly1305
|
||||
bool AEADChaCha20Poly1305 (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt); // msgLen is len without tag
|
||||
|
||||
class AEADChaCha20Poly1305Encryptor
|
||||
{
|
||||
public:
|
||||
void AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs, const uint8_t * key, const uint8_t * nonce, uint8_t * mac); // encrypt multiple buffers with zero ad
|
||||
|
||||
AEADChaCha20Poly1305Encryptor ();
|
||||
~AEADChaCha20Poly1305Encryptor ();
|
||||
|
||||
bool Encrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len); // msgLen is len without tag
|
||||
|
||||
void Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs, const uint8_t * key, const uint8_t * nonce, uint8_t * mac); // encrypt multiple buffers with zero ad
|
||||
|
||||
private:
|
||||
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
};
|
||||
|
||||
class AEADChaCha20Poly1305Decryptor
|
||||
{
|
||||
public:
|
||||
|
||||
AEADChaCha20Poly1305Decryptor ();
|
||||
~AEADChaCha20Poly1305Decryptor ();
|
||||
|
||||
bool Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len); // msgLen is len without tag
|
||||
|
||||
private:
|
||||
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
};
|
||||
|
||||
bool AEADChaCha20Poly1305 (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len, bool encrypt); // msgLen is len without tag
|
||||
|
||||
// ChaCha20
|
||||
void ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out);
|
||||
|
||||
class ChaCha20Context
|
||||
{
|
||||
public:
|
||||
|
||||
ChaCha20Context ();
|
||||
~ChaCha20Context ();
|
||||
void operator ()(const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out);
|
||||
|
||||
private:
|
||||
|
||||
EVP_CIPHER_CTX * m_Ctx;
|
||||
};
|
||||
|
||||
// HKDF
|
||||
|
||||
void HKDF (const uint8_t * salt, const uint8_t * key, size_t keyLen, const std::string& info, uint8_t * out, size_t outLen = 64); // salt - 32, out - 32 or 64, info <= 32
|
||||
@@ -260,7 +288,7 @@ namespace crypto
|
||||
void InitNoiseIKState (NoiseSymmetricState& state, const uint8_t * pub); // Noise_IK (ratchets)
|
||||
|
||||
// init and terminate
|
||||
void InitCrypto (bool precomputation);
|
||||
void InitCrypto (bool precomputation, bool aesni, bool force);
|
||||
void TerminateCrypto ();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -104,7 +104,8 @@ namespace datagram
|
||||
|
||||
if (verified)
|
||||
{
|
||||
auto session = ObtainSession (identity.GetIdentHash());
|
||||
auto h = identity.GetIdentHash();
|
||||
auto session = ObtainSession(h);
|
||||
session->Ack();
|
||||
auto r = FindReceiver(toPort);
|
||||
if(r)
|
||||
@@ -380,19 +381,15 @@ namespace datagram
|
||||
if (!found)
|
||||
{
|
||||
m_RoutingSession = m_LocalDestination->GetRoutingSession(m_RemoteLeaseSet, true);
|
||||
if (m_RoutingSession)
|
||||
{
|
||||
m_RoutingSession->SetAckRequestInterval (DATAGRAM_SESSION_ACK_REQUEST_INTERVAL);
|
||||
if (!m_RoutingSession->GetOwner () || !m_RoutingSession->IsReadyToSend ())
|
||||
m_PendingRoutingSessions.push_back (m_RoutingSession);
|
||||
}
|
||||
if (!m_RoutingSession->GetOwner () || !m_RoutingSession->IsReadyToSend ())
|
||||
m_PendingRoutingSessions.push_back (m_RoutingSession);
|
||||
}
|
||||
}
|
||||
|
||||
auto path = m_RoutingSession->GetSharedRoutingPath();
|
||||
if (path && m_RoutingSession->IsRatchets () && m_RoutingSession->CleanupUnconfirmedTags ())
|
||||
if (path && m_RoutingSession->IsRatchets () && (m_RoutingSession->CleanupUnconfirmedTags () ||
|
||||
m_LastUse > m_RoutingSession->GetLastActivityTimestamp ()*1000 + DATAGRAM_SESSION_PATH_TIMEOUT))
|
||||
{
|
||||
LogPrint (eLogDebug, "Datagram: path reset");
|
||||
m_RoutingSession->SetSharedRoutingPath (nullptr);
|
||||
path = nullptr;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -31,6 +31,8 @@ namespace datagram
|
||||
{
|
||||
// milliseconds for max session idle time
|
||||
const uint64_t DATAGRAM_SESSION_MAX_IDLE = 10 * 60 * 1000;
|
||||
// milliseconds for how long we try sticking to a dead routing path before trying to switch
|
||||
const uint64_t DATAGRAM_SESSION_PATH_TIMEOUT = 10 * 1000;
|
||||
// milliseconds interval a routing path is used before switching
|
||||
const uint64_t DATAGRAM_SESSION_PATH_SWITCH_INTERVAL = 20 * 60 * 1000;
|
||||
// milliseconds before lease expire should we try switching leases
|
||||
@@ -42,7 +44,6 @@ namespace datagram
|
||||
// max 64 messages buffered in send queue for each datagram session
|
||||
const size_t DATAGRAM_SEND_QUEUE_MAX_SIZE = 64;
|
||||
const uint64_t DATAGRAM_MAX_FLUSH_INTERVAL = 5; // in milliseconds
|
||||
const int DATAGRAM_SESSION_ACK_REQUEST_INTERVAL = 5500; // in milliseconds
|
||||
|
||||
class DatagramSession : public std::enable_shared_from_this<DatagramSession>
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -195,7 +195,7 @@ namespace client
|
||||
m_IsPublic = itr->second != "true";
|
||||
}
|
||||
|
||||
int inLen = 0, outLen = 0, inQuant = 0, outQuant = 0, numTags = 0, minLatency = 0, maxLatency = 0;
|
||||
int inLen, outLen, inQuant, outQuant, numTags, minLatency, maxLatency;
|
||||
std::map<std::string, int&> intOpts = {
|
||||
{I2CP_PARAM_INBOUND_TUNNEL_LENGTH, inLen},
|
||||
{I2CP_PARAM_OUTBOUND_TUNNEL_LENGTH, outLen},
|
||||
@@ -597,8 +597,7 @@ namespace client
|
||||
m_ExcludedFloodfills.clear ();
|
||||
m_PublishReplyToken = 0;
|
||||
// schedule verification
|
||||
m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT +
|
||||
(m_Pool ? m_Pool->GetRng ()() % PUBLISH_VERIFICATION_TIMEOUT_VARIANCE : 0)));
|
||||
m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT));
|
||||
m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
}
|
||||
@@ -677,8 +676,8 @@ namespace client
|
||||
m_ExcludedFloodfills.clear ();
|
||||
m_PublishReplyToken = 1; // dummy non-zero value
|
||||
// try again after a while
|
||||
LogPrint (eLogInfo, "Destination: Can't publish LeasetSet because destination is not ready. Try publishing again after ", PUBLISH_CONFIRMATION_TIMEOUT, " milliseconds");
|
||||
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::milliseconds(PUBLISH_CONFIRMATION_TIMEOUT));
|
||||
LogPrint (eLogInfo, "Destination: Can't publish LeasetSet because destination is not ready. Try publishing again after ", PUBLISH_CONFIRMATION_TIMEOUT, " seconds");
|
||||
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_CONFIRMATION_TIMEOUT));
|
||||
m_PublishConfirmationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishConfirmationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
return;
|
||||
@@ -697,7 +696,7 @@ namespace client
|
||||
s->HandlePublishConfirmationTimer (boost::system::error_code());
|
||||
});
|
||||
};
|
||||
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::milliseconds(PUBLISH_CONFIRMATION_TIMEOUT));
|
||||
m_PublishConfirmationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_CONFIRMATION_TIMEOUT));
|
||||
m_PublishConfirmationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishConfirmationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
outbound->SendTunnelDataMsgTo (floodfill->GetIdentHash (), 0, msg);
|
||||
@@ -713,15 +712,15 @@ namespace client
|
||||
m_PublishReplyToken = 0;
|
||||
if (GetIdentity ()->GetCryptoKeyType () == i2p::data::CRYPTO_KEY_TYPE_ELGAMAL)
|
||||
{
|
||||
LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " milliseconds or failed. will try again");
|
||||
LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " seconds or failed. will try again");
|
||||
Publish ();
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " milliseconds from Java floodfill for crypto type ", (int)GetIdentity ()->GetCryptoKeyType ());
|
||||
LogPrint (eLogWarning, "Destination: Publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, " seconds from Java floodfill for crypto type ", (int)GetIdentity ()->GetCryptoKeyType ());
|
||||
// Java floodfill never sends confirmation back for unknown crypto type
|
||||
// assume it successive and try to verify
|
||||
m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT + PUBLISH_VERIFICATION_TIMEOUT_VARIANCE)); // always max
|
||||
m_PublishVerificationTimer.expires_from_now (boost::posix_time::seconds(PUBLISH_VERIFICATION_TIMEOUT));
|
||||
m_PublishVerificationTimer.async_wait (std::bind (&LeaseSetDestination::HandlePublishVerificationTimer,
|
||||
shared_from_this (), std::placeholders::_1));
|
||||
|
||||
@@ -834,7 +833,7 @@ namespace client
|
||||
request->requestedBlindedKey = requestedBlindedKey; // for encrypted LeaseSet2
|
||||
if (requestComplete)
|
||||
request->requestComplete.push_back (requestComplete);
|
||||
auto ts = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
auto ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
auto ret = m_LeaseSetRequests.insert (std::pair<i2p::data::IdentHash, std::shared_ptr<LeaseSetRequest> >(dest,request));
|
||||
if (ret.second) // inserted
|
||||
{
|
||||
@@ -917,7 +916,7 @@ namespace client
|
||||
nextFloodfill->GetIdentHash (), 0, msg
|
||||
}
|
||||
});
|
||||
request->requestTimeoutTimer.expires_from_now (boost::posix_time::milliseconds(LEASESET_REQUEST_TIMEOUT));
|
||||
request->requestTimeoutTimer.expires_from_now (boost::posix_time::seconds(LEASESET_REQUEST_TIMEOUT));
|
||||
request->requestTimeoutTimer.async_wait (std::bind (&LeaseSetDestination::HandleRequestTimoutTimer,
|
||||
shared_from_this (), std::placeholders::_1, dest));
|
||||
}
|
||||
@@ -934,7 +933,7 @@ namespace client
|
||||
if (it != m_LeaseSetRequests.end ())
|
||||
{
|
||||
bool done = false;
|
||||
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
if (ts < it->second->requestTime + MAX_LEASESET_REQUEST_TIMEOUT)
|
||||
{
|
||||
auto floodfill = i2p::data::netdb.GetClosestFloodfill (dest, it->second->excluded);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -36,13 +36,12 @@ namespace client
|
||||
const uint8_t PROTOCOL_TYPE_STREAMING = 6;
|
||||
const uint8_t PROTOCOL_TYPE_DATAGRAM = 17;
|
||||
const uint8_t PROTOCOL_TYPE_RAW = 18;
|
||||
const int PUBLISH_CONFIRMATION_TIMEOUT = 1800; // in milliseconds
|
||||
const int PUBLISH_VERIFICATION_TIMEOUT = 5; // in seconds after successful publish
|
||||
const int PUBLISH_VERIFICATION_TIMEOUT_VARIANCE = 3; // in seconds
|
||||
const int PUBLISH_CONFIRMATION_TIMEOUT = 5; // in seconds
|
||||
const int PUBLISH_VERIFICATION_TIMEOUT = 10; // in seconds after successful publish
|
||||
const int PUBLISH_MIN_INTERVAL = 20; // in seconds
|
||||
const int PUBLISH_REGULAR_VERIFICATION_INTERNAL = 100; // in seconds periodically
|
||||
const int LEASESET_REQUEST_TIMEOUT = 1600; // in milliseconds
|
||||
const int MAX_LEASESET_REQUEST_TIMEOUT = 12000; // in milliseconds
|
||||
const int LEASESET_REQUEST_TIMEOUT = 5; // in seconds
|
||||
const int MAX_LEASESET_REQUEST_TIMEOUT = 40; // in seconds
|
||||
const int DESTINATION_CLEANUP_TIMEOUT = 44; // in seconds
|
||||
const int DESTINATION_CLEANUP_TIMEOUT_VARIANCE = 30; // in seconds
|
||||
const unsigned int MAX_NUM_FLOODFILLS_PER_REQUEST = 7;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -725,8 +725,6 @@ namespace garlic
|
||||
|
||||
bool ECIESX25519AEADRatchetSession::NewExistingSessionMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen)
|
||||
{
|
||||
auto owner = GetOwner ();
|
||||
if (!owner) return false;
|
||||
uint8_t nonce[12];
|
||||
auto index = m_SendTagset->GetNextIndex ();
|
||||
CreateNonce (index, nonce); // tag's index
|
||||
@@ -734,7 +732,8 @@ namespace garlic
|
||||
if (!tag)
|
||||
{
|
||||
LogPrint (eLogError, "Garlic: Can't create new ECIES-X25519-AEAD-Ratchet tag for send tagset");
|
||||
owner->RemoveECIESx25519Session (m_RemoteStaticKey);
|
||||
if (GetOwner ())
|
||||
GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey);
|
||||
return false;
|
||||
}
|
||||
memcpy (out, &tag, 8);
|
||||
@@ -742,7 +741,7 @@ namespace garlic
|
||||
// ciphertext = ENCRYPT(k, n, payload, ad)
|
||||
uint8_t key[32];
|
||||
m_SendTagset->GetSymmKey (index, key);
|
||||
if (!owner->AEADChaCha20Poly1305Encrypt (payload, len, out, 8, key, nonce, out + 8, outLen - 8))
|
||||
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, out, 8, key, nonce, out + 8, outLen - 8, true)) // encrypt
|
||||
{
|
||||
LogPrint (eLogWarning, "Garlic: Payload section AEAD encryption failed");
|
||||
return false;
|
||||
@@ -761,35 +760,34 @@ namespace garlic
|
||||
uint8_t * payload = buf + 8;
|
||||
uint8_t key[32];
|
||||
receiveTagset->GetSymmKey (index, key);
|
||||
auto owner = GetOwner ();
|
||||
if (!owner) return true; // drop message
|
||||
|
||||
if (!owner->AEADChaCha20Poly1305Decrypt (payload, len - 16, buf, 8, key, nonce, payload, len - 16))
|
||||
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len - 16, buf, 8, key, nonce, payload, len - 16, false)) // decrypt
|
||||
{
|
||||
LogPrint (eLogWarning, "Garlic: Payload section AEAD decryption failed");
|
||||
return false;
|
||||
}
|
||||
HandlePayload (payload, len - 16, receiveTagset, index);
|
||||
|
||||
int moreTags = 0;
|
||||
if (owner->GetNumRatchetInboundTags () > 0) // override in settings?
|
||||
if (GetOwner ())
|
||||
{
|
||||
if (receiveTagset->GetNextIndex () - index < owner->GetNumRatchetInboundTags ()/2)
|
||||
moreTags = owner->GetNumRatchetInboundTags ();
|
||||
index -= owner->GetNumRatchetInboundTags (); // trim behind
|
||||
int moreTags = 0;
|
||||
if (GetOwner ()->GetNumRatchetInboundTags () > 0) // override in settings?
|
||||
{
|
||||
if (receiveTagset->GetNextIndex () - index < GetOwner ()->GetNumRatchetInboundTags ()/2)
|
||||
moreTags = GetOwner ()->GetNumRatchetInboundTags ();
|
||||
index -= GetOwner ()->GetNumRatchetInboundTags (); // trim behind
|
||||
}
|
||||
else
|
||||
{
|
||||
moreTags = (receiveTagset->GetTagSetID () > 0) ? ECIESX25519_MAX_NUM_GENERATED_TAGS : // for non first tagset
|
||||
(ECIESX25519_MIN_NUM_GENERATED_TAGS + (index >> 1)); // N/2
|
||||
if (moreTags > ECIESX25519_MAX_NUM_GENERATED_TAGS) moreTags = ECIESX25519_MAX_NUM_GENERATED_TAGS;
|
||||
moreTags -= (receiveTagset->GetNextIndex () - index);
|
||||
index -= ECIESX25519_MAX_NUM_GENERATED_TAGS; // trim behind
|
||||
}
|
||||
if (moreTags > 0)
|
||||
GenerateMoreReceiveTags (receiveTagset, moreTags);
|
||||
if (index > 0)
|
||||
receiveTagset->SetTrimBehind (index);
|
||||
}
|
||||
else
|
||||
{
|
||||
moreTags = (receiveTagset->GetTagSetID () > 0) ? ECIESX25519_MAX_NUM_GENERATED_TAGS : // for non first tagset
|
||||
(ECIESX25519_MIN_NUM_GENERATED_TAGS + (index >> 1)); // N/2
|
||||
if (moreTags > ECIESX25519_MAX_NUM_GENERATED_TAGS) moreTags = ECIESX25519_MAX_NUM_GENERATED_TAGS;
|
||||
moreTags -= (receiveTagset->GetNextIndex () - index);
|
||||
index -= ECIESX25519_MAX_NUM_GENERATED_TAGS; // trim behind
|
||||
}
|
||||
if (moreTags > 0)
|
||||
GenerateMoreReceiveTags (receiveTagset, moreTags);
|
||||
if (index > 0)
|
||||
receiveTagset->SetTrimBehind (index);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -913,7 +911,7 @@ namespace garlic
|
||||
}
|
||||
}
|
||||
if (!sendAckRequest && !first &&
|
||||
((!m_AckRequestMsgID && ts > m_LastAckRequestSendTime + m_AckRequestInterval) || // regular request
|
||||
((!m_AckRequestMsgID && ts > m_LastAckRequestSendTime + ECIESX25519_ACK_REQUEST_INTERVAL) || // regular request
|
||||
(m_AckRequestMsgID && ts > m_LastAckRequestSendTime + LEASESET_CONFIRMATION_TIMEOUT))) // previous request failed. try again
|
||||
{
|
||||
// not LeaseSet
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -33,7 +33,7 @@ namespace garlic
|
||||
const int ECIESX25519_SESSION_CREATE_TIMEOUT = 3; // in seconds, NSR must be send after NS received
|
||||
const int ECIESX25519_SESSION_ESTABLISH_TIMEOUT = 15; // in seconds
|
||||
const int ECIESX25519_PREVIOUS_TAGSET_EXPIRATION_TIMEOUT = 180; // in seconds
|
||||
const int ECIESX25519_DEFAULT_ACK_REQUEST_INTERVAL = 33000; // in milliseconds
|
||||
const int ECIESX25519_ACK_REQUEST_INTERVAL = 33000; // in milliseconds
|
||||
const int ECIESX25519_ACK_REQUEST_MAX_NUM_ATTEMPTS = 3;
|
||||
const int ECIESX25519_TAGSET_MAX_NUM_TAGS = 8192; // number of tags we request new tagset after
|
||||
const int ECIESX25519_MIN_NUM_GENERATED_TAGS = 24;
|
||||
@@ -164,7 +164,7 @@ namespace garlic
|
||||
~ECIESX25519AEADRatchetSession ();
|
||||
|
||||
bool HandleNextMessage (uint8_t * buf, size_t len, std::shared_ptr<ReceiveRatchetTagSet> receiveTagset, int index = 0);
|
||||
std::shared_ptr<I2NPMessage> WrapSingleMessage (std::shared_ptr<const I2NPMessage> msg) override;
|
||||
std::shared_ptr<I2NPMessage> WrapSingleMessage (std::shared_ptr<const I2NPMessage> msg);
|
||||
std::shared_ptr<I2NPMessage> WrapOneTimeMessage (std::shared_ptr<const I2NPMessage> msg);
|
||||
|
||||
const uint8_t * GetRemoteStaticKey () const { return m_RemoteStaticKey; }
|
||||
@@ -180,12 +180,11 @@ namespace garlic
|
||||
bool CanBeRestarted (uint64_t ts) const { return ts > m_SessionCreatedTimestamp + ECIESX25519_RESTART_TIMEOUT; }
|
||||
bool IsInactive (uint64_t ts) const { return ts > m_LastActivityTimestamp + ECIESX25519_INACTIVITY_TIMEOUT && CanBeRestarted (ts); }
|
||||
|
||||
bool IsRatchets () const override { return true; };
|
||||
bool IsReadyToSend () const override { return m_State != eSessionStateNewSessionSent; };
|
||||
bool IsTerminated () const override { return m_IsTerminated; }
|
||||
uint64_t GetLastActivityTimestamp () const override { return m_LastActivityTimestamp; };
|
||||
void SetAckRequestInterval (int interval) override { m_AckRequestInterval = interval; };
|
||||
bool CleanupUnconfirmedTags () override; // return true if unaswered Ack requests, called from I2CP
|
||||
bool IsRatchets () const { return true; };
|
||||
bool IsReadyToSend () const { return m_State != eSessionStateNewSessionSent; };
|
||||
bool IsTerminated () const { return m_IsTerminated; }
|
||||
uint64_t GetLastActivityTimestamp () const { return m_LastActivityTimestamp; };
|
||||
bool CleanupUnconfirmedTags (); // return true if unaswered Ack requests, called from I2CP
|
||||
|
||||
protected:
|
||||
|
||||
@@ -193,7 +192,7 @@ namespace garlic
|
||||
void SetNoiseState (const i2p::crypto::NoiseSymmetricState& state) { GetNoiseState () = state; };
|
||||
void CreateNonce (uint64_t seqn, uint8_t * nonce);
|
||||
void HandlePayload (const uint8_t * buf, size_t len, const std::shared_ptr<ReceiveRatchetTagSet>& receiveTagset, int index);
|
||||
bool MessageConfirmed (uint32_t msgID) override;
|
||||
bool MessageConfirmed (uint32_t msgID);
|
||||
|
||||
private:
|
||||
|
||||
@@ -236,7 +235,6 @@ namespace garlic
|
||||
uint64_t m_LastAckRequestSendTime = 0; // milliseconds
|
||||
uint32_t m_AckRequestMsgID = 0;
|
||||
int m_AckRequestNumAttempts = 0;
|
||||
int m_AckRequestInterval = ECIESX25519_DEFAULT_ACK_REQUEST_INTERVAL; // milliseconds
|
||||
|
||||
public:
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ namespace garlic
|
||||
uint8_t iv[32]; // IV is first 16 bytes
|
||||
SHA256(elGamal.preIV, 32, iv);
|
||||
m_Destination->Encrypt ((uint8_t *)&elGamal, buf);
|
||||
m_IV = iv;
|
||||
m_Encryption.SetIV (iv);
|
||||
buf += 514;
|
||||
len += 514;
|
||||
}
|
||||
@@ -170,7 +170,7 @@ namespace garlic
|
||||
memcpy (buf, tag, 32);
|
||||
uint8_t iv[32]; // IV is first 16 bytes
|
||||
SHA256(tag, 32, iv);
|
||||
m_IV = iv;
|
||||
m_Encryption.SetIV (iv);
|
||||
buf += 32;
|
||||
len += 32;
|
||||
}
|
||||
@@ -210,7 +210,7 @@ namespace garlic
|
||||
size_t rem = blockSize % 16;
|
||||
if (rem)
|
||||
blockSize += (16-rem); //padding
|
||||
m_Encryption.Encrypt(buf, blockSize, m_IV, buf);
|
||||
m_Encryption.Encrypt(buf, blockSize, buf);
|
||||
return blockSize;
|
||||
}
|
||||
|
||||
@@ -514,7 +514,8 @@ namespace garlic
|
||||
{
|
||||
uint8_t iv[32]; // IV is first 16 bytes
|
||||
SHA256(buf, 32, iv);
|
||||
decryption->Decrypt (buf + 32, length - 32, iv, buf + 32);
|
||||
decryption->SetIV (iv);
|
||||
decryption->Decrypt (buf + 32, length - 32, buf + 32);
|
||||
HandleAESBlock (buf + 32, length - 32, decryption, msg->from);
|
||||
found = true;
|
||||
}
|
||||
@@ -532,7 +533,8 @@ namespace garlic
|
||||
auto decryption = std::make_shared<AESDecryption>(elGamal.sessionKey);
|
||||
uint8_t iv[32]; // IV is first 16 bytes
|
||||
SHA256(elGamal.preIV, 32, iv);
|
||||
decryption->Decrypt(buf + 514, length - 514, iv, buf + 514);
|
||||
decryption->SetIV (iv);
|
||||
decryption->Decrypt(buf + 514, length - 514, buf + 514);
|
||||
HandleAESBlock (buf + 514, length - 514, decryption, msg->from);
|
||||
}
|
||||
else if (SupportsEncryptionType (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD))
|
||||
@@ -548,7 +550,7 @@ namespace garlic
|
||||
LogPrint (eLogError, "Garlic: Can't handle ECIES-X25519-AEAD-Ratchet message");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogWarning, "Garlic: Incoming sessions come too often");
|
||||
LogPrint (eLogWarning, "Garlic: Incoming sessions come too ofter");
|
||||
}
|
||||
else
|
||||
LogPrint (eLogError, "Garlic: Failed to decrypt message");
|
||||
@@ -1103,17 +1105,5 @@ namespace garlic
|
||||
m_PayloadBuffer = new uint8_t[I2NP_MAX_MESSAGE_SIZE];
|
||||
return m_PayloadBuffer;
|
||||
}
|
||||
|
||||
bool GarlicDestination::AEADChaCha20Poly1305Encrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return m_Encryptor.Encrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
|
||||
}
|
||||
|
||||
bool GarlicDestination::AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return m_Decryptor.Decrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -116,8 +116,7 @@ namespace garlic
|
||||
virtual bool IsReadyToSend () const { return true; };
|
||||
virtual bool IsTerminated () const { return !GetOwner (); };
|
||||
virtual uint64_t GetLastActivityTimestamp () const { return 0; }; // non-zero for rathets only
|
||||
virtual void SetAckRequestInterval (int interval) {}; // in milliseconds, override in ECIESX25519AEADRatchetSession
|
||||
|
||||
|
||||
void SetLeaseSetUpdated ()
|
||||
{
|
||||
if (m_LeaseSetUpdateStatus != eLeaseSetDoNotSend) m_LeaseSetUpdateStatus = eLeaseSetUpdated;
|
||||
@@ -206,7 +205,6 @@ namespace garlic
|
||||
std::map<uint32_t, std::unique_ptr<UnconfirmedTags> > m_UnconfirmedTagsMsgs; // msgID->tags
|
||||
|
||||
i2p::crypto::CBCEncryption m_Encryption;
|
||||
i2p::data::Tag<16> m_IV;
|
||||
|
||||
public:
|
||||
|
||||
@@ -243,11 +241,6 @@ namespace garlic
|
||||
void RemoveDeliveryStatusSession (uint32_t msgID);
|
||||
std::shared_ptr<I2NPMessage> WrapMessageForRouter (std::shared_ptr<const i2p::data::RouterInfo> router,
|
||||
std::shared_ptr<I2NPMessage> msg);
|
||||
|
||||
bool AEADChaCha20Poly1305Encrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len);
|
||||
bool AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len);
|
||||
|
||||
void AddSessionKey (const uint8_t * key, const uint8_t * tag); // one tag
|
||||
void AddECIESx25519Key (const uint8_t * key, uint64_t tag); // one tag
|
||||
@@ -293,7 +286,7 @@ namespace garlic
|
||||
std::unordered_map<i2p::data::IdentHash, ElGamalAESSessionPtr> m_Sessions;
|
||||
std::unordered_map<i2p::data::Tag<32>, ECIESX25519AEADRatchetSessionPtr> m_ECIESx25519Sessions; // static key -> session
|
||||
uint8_t * m_PayloadBuffer; // for ECIESX25519AEADRatchet
|
||||
uint64_t m_LastIncomingSessionTimestamp; // in milliseconds
|
||||
uint64_t m_LastIncomingSessionTimestamp; // in millseconds
|
||||
// incoming
|
||||
int m_NumRatchetInboundTags;
|
||||
std::unordered_map<SessionTag, std::shared_ptr<AESDecryption>, std::hash<i2p::data::Tag<32> > > m_Tags;
|
||||
@@ -301,10 +294,7 @@ namespace garlic
|
||||
// DeliveryStatus
|
||||
std::mutex m_DeliveryStatusSessionsMutex;
|
||||
std::unordered_map<uint32_t, GarlicRoutingSessionPtr> m_DeliveryStatusSessions; // msgID -> session
|
||||
// encryption
|
||||
i2p::crypto::AEADChaCha20Poly1305Encryptor m_Encryptor;
|
||||
i2p::crypto::AEADChaCha20Poly1305Decryptor m_Decryptor;
|
||||
|
||||
|
||||
public:
|
||||
|
||||
// for HTTP only
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -27,15 +27,18 @@ namespace data
|
||||
|
||||
size_t Identity::FromBuffer (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (len < DEFAULT_IDENTITY_SIZE) return 0; // buffer too small, don't overflow
|
||||
memcpy (this, buf, DEFAULT_IDENTITY_SIZE);
|
||||
if ( len < DEFAULT_IDENTITY_SIZE ) {
|
||||
// buffer too small, don't overflow
|
||||
return 0;
|
||||
}
|
||||
memcpy (publicKey, buf, DEFAULT_IDENTITY_SIZE);
|
||||
return DEFAULT_IDENTITY_SIZE;
|
||||
}
|
||||
|
||||
IdentHash Identity::Hash () const
|
||||
{
|
||||
IdentHash hash;
|
||||
SHA256((const uint8_t *)this, DEFAULT_IDENTITY_SIZE, hash);
|
||||
SHA256(publicKey, DEFAULT_IDENTITY_SIZE, hash);
|
||||
return hash;
|
||||
}
|
||||
|
||||
@@ -259,11 +262,11 @@ namespace data
|
||||
return fullLen;
|
||||
}
|
||||
|
||||
size_t IdentityEx::FromBase64(std::string_view s)
|
||||
size_t IdentityEx::FromBase64(const std::string& s)
|
||||
{
|
||||
const size_t slen = s.length();
|
||||
std::vector<uint8_t> buf(slen); // binary data can't exceed base64
|
||||
const size_t len = Base64ToByteStream (s.data(), slen, buf.data(), slen);
|
||||
const size_t len = Base64ToByteStream (s.c_str(), slen, buf.data(), slen);
|
||||
return FromBuffer (buf.data(), len);
|
||||
}
|
||||
|
||||
@@ -725,7 +728,9 @@ namespace data
|
||||
case SIGNING_KEY_TYPE_RSA_SHA384_3072:
|
||||
case SIGNING_KEY_TYPE_RSA_SHA512_4096:
|
||||
LogPrint (eLogWarning, "Identity: RSA signature type is not supported. Creating EdDSA");
|
||||
#if (__cplusplus >= 201703L) // C++ 17 or higher
|
||||
[[fallthrough]];
|
||||
#endif
|
||||
// no break here
|
||||
case SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
|
||||
i2p::crypto::CreateEDDSA25519RandomKeys (priv, pub);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -12,7 +12,6 @@
|
||||
#include <inttypes.h>
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include "Base.h"
|
||||
@@ -100,7 +99,7 @@ namespace data
|
||||
|
||||
size_t FromBuffer (const uint8_t * buf, size_t len);
|
||||
size_t ToBuffer (uint8_t * buf, size_t len) const;
|
||||
size_t FromBase64(std::string_view s);
|
||||
size_t FromBase64(const std::string& s);
|
||||
std::string ToBase64 () const;
|
||||
const Identity& GetStandardIdentity () const { return m_StandardIdentity; };
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -120,8 +120,9 @@ namespace transport
|
||||
// encrypt X
|
||||
i2p::crypto::CBCEncryption encryption;
|
||||
encryption.SetKey (m_RemoteIdentHash);
|
||||
encryption.Encrypt (GetPub (), 32, m_IV, m_SessionRequestBuffer); // X
|
||||
memcpy (m_IV, m_SessionRequestBuffer + 16, 16); // save last block as IV for SessionCreated
|
||||
encryption.SetIV (m_IV);
|
||||
encryption.Encrypt (GetPub (), 32, m_SessionRequestBuffer); // X
|
||||
encryption.GetIV (m_IV); // save IV for SessionCreated
|
||||
// encryption key for next block
|
||||
if (!KDF1Alice ()) return false;
|
||||
// fill options
|
||||
@@ -160,7 +161,8 @@ namespace transport
|
||||
// encrypt Y
|
||||
i2p::crypto::CBCEncryption encryption;
|
||||
encryption.SetKey (i2p::context.GetIdentHash ());
|
||||
encryption.Encrypt (GetPub (), 32, m_IV, m_SessionCreatedBuffer); // Y
|
||||
encryption.SetIV (m_IV);
|
||||
encryption.Encrypt (GetPub (), 32, m_SessionCreatedBuffer); // Y
|
||||
// encryption key for next block (m_K)
|
||||
if (!KDF2Bob ()) return false;
|
||||
uint8_t options[16];
|
||||
@@ -206,8 +208,9 @@ namespace transport
|
||||
// decrypt X
|
||||
i2p::crypto::CBCDecryption decryption;
|
||||
decryption.SetKey (i2p::context.GetIdentHash ());
|
||||
decryption.Decrypt (m_SessionRequestBuffer, 32, i2p::context.GetNTCP2IV (), GetRemotePub ());
|
||||
memcpy (m_IV, m_SessionRequestBuffer + 16, 16); // save last block as IV for SessionCreated
|
||||
decryption.SetIV (i2p::context.GetNTCP2IV ());
|
||||
decryption.Decrypt (m_SessionRequestBuffer, 32, GetRemotePub ());
|
||||
decryption.GetIV (m_IV); // save IV for SessionCreated
|
||||
// decryption key for next block
|
||||
if (!KDF1Bob ())
|
||||
{
|
||||
@@ -265,7 +268,8 @@ namespace transport
|
||||
// decrypt Y
|
||||
i2p::crypto::CBCDecryption decryption;
|
||||
decryption.SetKey (m_RemoteIdentHash);
|
||||
decryption.Decrypt (m_SessionCreatedBuffer, 32, m_IV, GetRemotePub ());
|
||||
decryption.SetIV (m_IV);
|
||||
decryption.Decrypt (m_SessionCreatedBuffer, 32, GetRemotePub ());
|
||||
// decryption key for next block (m_K)
|
||||
if (!KDF2Alice ())
|
||||
{
|
||||
@@ -819,20 +823,15 @@ namespace transport
|
||||
Terminate ();
|
||||
return;
|
||||
}
|
||||
|
||||
bool isOlder = false;
|
||||
std::shared_ptr<i2p::data::RouterProfile> profile; // not null if older
|
||||
if (ri.GetTimestamp () + i2p::data::NETDB_EXPIRATION_TIMEOUT_THRESHOLD*1000LL < ri1->GetTimestamp ())
|
||||
{
|
||||
// received RouterInfo is older than one in netdb
|
||||
isOlder = true;
|
||||
if (ri1->HasProfile ())
|
||||
profile = i2p::data::GetRouterProfile (ri1->GetIdentHash ()); // retrieve profile
|
||||
if (profile && profile->IsDuplicated ())
|
||||
{
|
||||
auto profile = i2p::data::GetRouterProfile (ri1->GetIdentHash ()); // retrieve profile
|
||||
if (profile && profile->IsDuplicated ())
|
||||
{
|
||||
SendTerminationAndTerminate (eNTCP2Banned);
|
||||
return;
|
||||
}
|
||||
SendTerminationAndTerminate (eNTCP2Banned);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -849,12 +848,8 @@ namespace transport
|
||||
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data () + 1, addr->host.to_v6 ().to_bytes ().data () + 1, 7) : // from the same yggdrasil subnet
|
||||
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), addr->host.to_v6 ().to_bytes ().data (), 8)))) // temporary address
|
||||
{
|
||||
if (isOlder) // older router?
|
||||
i2p::data::UpdateRouterProfile (ri1->GetIdentHash (),
|
||||
[](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->Duplicated (); // mark router as duplicated in profile
|
||||
});
|
||||
if (profile) // older router?
|
||||
profile->Duplicated (); // mark router as duplicated in profile
|
||||
else
|
||||
LogPrint (eLogInfo, "NTCP2: Host mismatch between published address ", addr->host, " and actual endpoint ", m_RemoteEndpoint.address ());
|
||||
SendTerminationAndTerminate (eNTCP2Banned);
|
||||
@@ -1000,7 +995,7 @@ namespace transport
|
||||
i2p::transport::transports.UpdateReceivedBytes (bytes_transferred + 2);
|
||||
uint8_t nonce[12];
|
||||
CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++;
|
||||
if (m_Server.AEADChaCha20Poly1305Decrypt (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen))
|
||||
if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false))
|
||||
{
|
||||
LogPrint (eLogDebug, "NTCP2: Received message decrypted");
|
||||
ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16);
|
||||
@@ -1189,7 +1184,7 @@ namespace transport
|
||||
}
|
||||
uint8_t nonce[12];
|
||||
CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
|
||||
m_Server.AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers
|
||||
i2p::crypto::AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers
|
||||
SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block
|
||||
|
||||
// send buffers
|
||||
@@ -1220,7 +1215,7 @@ namespace transport
|
||||
// encrypt
|
||||
uint8_t nonce[12];
|
||||
CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
|
||||
m_Server.AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2);
|
||||
i2p::crypto::AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2);
|
||||
SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer);
|
||||
// send
|
||||
m_IsSending = true;
|
||||
@@ -1444,12 +1439,6 @@ namespace transport
|
||||
boost::asio::post (m_Server.GetService (), std::bind (&NTCP2Session::SendRouterInfo, shared_from_this ()));
|
||||
}
|
||||
|
||||
i2p::data::RouterInfo::SupportedTransports NTCP2Session::GetTransportType () const
|
||||
{
|
||||
if (m_RemoteEndpoint.address ().is_v4 ()) return i2p::data::RouterInfo::eNTCP2V4;
|
||||
return i2p::util::net::IsYggdrasilAddress (m_RemoteEndpoint.address ()) ? i2p::data::RouterInfo::eNTCP2V6Mesh : i2p::data::RouterInfo::eNTCP2V6;
|
||||
}
|
||||
|
||||
NTCP2Server::NTCP2Server ():
|
||||
RunnableServiceWithWork ("NTCP2"), m_TerminationTimer (GetService ()),
|
||||
m_ProxyType(eNoProxy), m_Resolver(GetService ()),
|
||||
@@ -1559,7 +1548,6 @@ namespace transport
|
||||
|
||||
void NTCP2Server::Stop ()
|
||||
{
|
||||
m_EstablisherService.Stop ();
|
||||
{
|
||||
// we have to copy it because Terminate changes m_NTCP2Sessions
|
||||
auto ntcpSessions = m_NTCP2Sessions;
|
||||
@@ -1575,6 +1563,7 @@ namespace transport
|
||||
m_TerminationTimer.cancel ();
|
||||
m_ProxyEndpoint = nullptr;
|
||||
}
|
||||
m_EstablisherService.Stop ();
|
||||
StopIOService ();
|
||||
}
|
||||
|
||||
@@ -1995,17 +1984,5 @@ namespace transport
|
||||
else
|
||||
m_Address4 = addr;
|
||||
}
|
||||
|
||||
void NTCP2Server::AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * mac)
|
||||
{
|
||||
return m_Encryptor.Encrypt (bufs, key, nonce, mac);
|
||||
}
|
||||
|
||||
bool NTCP2Server::AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen,
|
||||
const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return m_Decryptor.Decrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -147,7 +147,6 @@ namespace transport
|
||||
void SetRemoteEndpoint (const boost::asio::ip::tcp::endpoint& ep) { m_RemoteEndpoint = ep; };
|
||||
|
||||
bool IsEstablished () const override { return m_IsEstablished; };
|
||||
i2p::data::RouterInfo::SupportedTransports GetTransportType () const override;
|
||||
bool IsTerminated () const { return m_IsTerminated; };
|
||||
|
||||
void ClientLogin (); // Alice
|
||||
@@ -273,11 +272,6 @@ namespace transport
|
||||
auto& GetService () { return GetIOService (); };
|
||||
auto& GetEstablisherService () { return m_EstablisherService.GetService (); };
|
||||
std::mt19937& GetRng () { return m_Rng; };
|
||||
void AEADChaCha20Poly1305Encrypt (const std::vector<std::pair<uint8_t *, size_t> >& bufs,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * mac);
|
||||
bool AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len);
|
||||
|
||||
|
||||
bool AddNTCP2Session (std::shared_ptr<NTCP2Session> session, bool incoming = false);
|
||||
void RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session);
|
||||
@@ -315,12 +309,9 @@ namespace transport
|
||||
uint16_t m_ProxyPort;
|
||||
boost::asio::ip::tcp::resolver m_Resolver;
|
||||
std::unique_ptr<boost::asio::ip::tcp::endpoint> m_ProxyEndpoint;
|
||||
|
||||
std::shared_ptr<boost::asio::ip::tcp::endpoint> m_Address4, m_Address6, m_YggdrasilAddress;
|
||||
std::mt19937 m_Rng;
|
||||
EstablisherService m_EstablisherService;
|
||||
i2p::crypto::AEADChaCha20Poly1305Encryptor m_Encryptor;
|
||||
i2p::crypto::AEADChaCha20Poly1305Decryptor m_Decryptor;
|
||||
|
||||
public:
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <boost/asio.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
@@ -39,7 +40,7 @@ namespace data
|
||||
|
||||
NetDb::NetDb (): m_IsRunning (false), m_Thread (nullptr), m_Reseeder (nullptr),
|
||||
m_Storage("netDb", "r", "routerInfo-", "dat"), m_PersistProfiles (true),
|
||||
m_LastExploratorySelectionUpdateTime (0), m_Rng(i2p::util::GetMonotonicMicroseconds () % 1000000LL)
|
||||
m_LastExploratorySelectionUpdateTime (0)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -118,9 +119,8 @@ namespace data
|
||||
i2p::util::SetThreadName("NetDB");
|
||||
|
||||
uint64_t lastManage = 0;
|
||||
uint64_t lastProfilesCleanup = i2p::util::GetMonotonicMilliseconds (),
|
||||
lastObsoleteProfilesCleanup = lastProfilesCleanup, lastApplyingProfileUpdates = lastProfilesCleanup;
|
||||
int16_t profilesCleanupVariance = 0, obsoleteProfilesCleanVariance = 0, applyingProfileUpdatesVariance = 0;
|
||||
uint64_t lastProfilesCleanup = i2p::util::GetMonotonicMilliseconds (), lastObsoleteProfilesCleanup = lastProfilesCleanup;
|
||||
int16_t profilesCleanupVariance = 0, obsoleteProfilesCleanVariance = 0;
|
||||
|
||||
std::list<std::shared_ptr<const I2NPMessage> > msgs;
|
||||
while (m_IsRunning)
|
||||
@@ -181,7 +181,7 @@ namespace data
|
||||
LogPrint (eLogWarning, "NetDb: Can't persist profiles. Profiles are being saved to disk");
|
||||
}
|
||||
lastProfilesCleanup = mts;
|
||||
profilesCleanupVariance = m_Rng () % i2p::data::PEER_PROFILE_AUTOCLEAN_VARIANCE;
|
||||
profilesCleanupVariance = rand () % i2p::data::PEER_PROFILE_AUTOCLEAN_VARIANCE;
|
||||
}
|
||||
|
||||
if (mts >= lastObsoleteProfilesCleanup + (uint64_t)(i2p::data::PEER_PROFILE_OBSOLETE_PROFILES_CLEAN_TIMEOUT + obsoleteProfilesCleanVariance)*1000)
|
||||
@@ -197,20 +197,7 @@ namespace data
|
||||
else
|
||||
LogPrint (eLogWarning, "NetDb: Can't delete profiles. Profiles are being deleted from disk");
|
||||
lastObsoleteProfilesCleanup = mts;
|
||||
obsoleteProfilesCleanVariance = m_Rng () % i2p::data::PEER_PROFILE_OBSOLETE_PROFILES_CLEAN_VARIANCE;
|
||||
}
|
||||
if (mts >= lastApplyingProfileUpdates + i2p::data::PEER_PROFILE_APPLY_POSTPONED_TIMEOUT + applyingProfileUpdatesVariance)
|
||||
{
|
||||
bool isApplying = m_ApplyingProfileUpdates.valid ();
|
||||
if (isApplying && m_ApplyingProfileUpdates.wait_for(std::chrono::seconds(0)) == std::future_status::ready) // still active?
|
||||
{
|
||||
m_ApplyingProfileUpdates.get ();
|
||||
isApplying = false;
|
||||
}
|
||||
if (!isApplying)
|
||||
m_ApplyingProfileUpdates = i2p::data::FlushPostponedRouterProfileUpdates ();
|
||||
lastApplyingProfileUpdates = mts;
|
||||
applyingProfileUpdatesVariance = m_Rng () % i2p::data::PEER_PROFILE_APPLY_POSTPONED_TIMEOUT_VARIANCE;
|
||||
obsoleteProfilesCleanVariance = rand () % i2p::data::PEER_PROFILE_OBSOLETE_PROFILES_CLEAN_VARIANCE;
|
||||
}
|
||||
}
|
||||
catch (std::exception& ex)
|
||||
@@ -294,7 +281,6 @@ namespace data
|
||||
}
|
||||
else
|
||||
{
|
||||
r->CancelBufferToDelete (); // since an update received
|
||||
if (CheckLogLevel (eLogDebug))
|
||||
LogPrint (eLogDebug, "NetDb: RouterInfo is older: ", ident.ToBase64());
|
||||
updated = false;
|
||||
@@ -516,7 +502,7 @@ namespace data
|
||||
}
|
||||
|
||||
// send them off
|
||||
i2p::transport::transports.SendMessages(ih, std::move (requests));
|
||||
i2p::transport::transports.SendMessages(ih, requests);
|
||||
}
|
||||
|
||||
bool NetDb::LoadRouterInfo (const std::string& path, uint64_t ts)
|
||||
@@ -571,7 +557,7 @@ namespace data
|
||||
while(n > 0)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_RouterInfosMutex);
|
||||
uint32_t idx = m_Rng () % m_RouterInfos.size ();
|
||||
uint32_t idx = rand () % m_RouterInfos.size ();
|
||||
uint32_t i = 0;
|
||||
for (const auto & it : m_RouterInfos) {
|
||||
if(i >= idx) // are we at the random start point?
|
||||
@@ -651,7 +637,7 @@ namespace data
|
||||
if (checkForExpiration && uptime > i2p::transport::SSU2_TO_INTRODUCER_SESSION_DURATION) // 1 hour
|
||||
expirationTimeout = i2p::context.IsFloodfill () ? NETDB_FLOODFILL_EXPIRATION_TIMEOUT*1000LL :
|
||||
NETDB_MIN_EXPIRATION_TIMEOUT*1000LL + (NETDB_MAX_EXPIRATION_TIMEOUT - NETDB_MIN_EXPIRATION_TIMEOUT)*1000LL*NETDB_MIN_ROUTERS/total;
|
||||
bool isOffline = checkForExpiration && i2p::transport::transports.GetNumPeers () < NETDB_MIN_TRANSPORTS; // enough routers and uptime, but no transports
|
||||
bool isOffline = checkForExpiration && i2p::transport::transports.GetNumPeers () < NETDB_MIN_TRANSPORTS; // enough routers and uptime, but no tranports
|
||||
|
||||
std::list<std::pair<std::string, std::shared_ptr<RouterInfo::Buffer> > > saveToDisk;
|
||||
std::list<std::string> removeFromDisk;
|
||||
@@ -674,20 +660,15 @@ namespace data
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_RouterInfosMutex); // possible collision between DeleteBuffer and Update
|
||||
buffer = r->CopyBuffer ();
|
||||
}
|
||||
if (!i2p::transport::transports.IsConnected (ident))
|
||||
r->ScheduleBufferToDelete ();
|
||||
}
|
||||
if (buffer)
|
||||
saveToDisk.emplace_back(ident.ToBase64 (), buffer);
|
||||
saveToDisk.push_back(std::make_pair(ident.ToBase64 (), buffer));
|
||||
}
|
||||
r->SetUpdated (false);
|
||||
updatedCount++;
|
||||
continue;
|
||||
}
|
||||
else if (r->GetBuffer () && ts > r->GetTimestamp () + NETDB_MIN_EXPIRATION_TIMEOUT*1000LL)
|
||||
// since update was long time ago we assume that router is not connected anymore
|
||||
r->ScheduleBufferToDelete ();
|
||||
|
||||
if (r->GetProfile ()->IsUnreachable ())
|
||||
r->SetUnreachable (true);
|
||||
// make router reachable back if too few routers or floodfills
|
||||
@@ -723,7 +704,7 @@ namespace data
|
||||
{
|
||||
if (r->IsFloodfill ()) deletedFloodfillsCount++;
|
||||
// delete RI file
|
||||
removeFromDisk.emplace_back (ident.ToBase64());
|
||||
removeFromDisk.push_back (ident.ToBase64());
|
||||
deletedCount++;
|
||||
if (total - deletedCount < NETDB_MIN_ROUTERS) checkForExpiration = false;
|
||||
}
|
||||
@@ -1350,7 +1331,7 @@ namespace data
|
||||
if (eligible.size () > NETDB_MAX_EXPLORATORY_SELECTION_SIZE)
|
||||
{
|
||||
std::sample (eligible.begin(), eligible.end(), std::back_inserter(m_ExploratorySelection),
|
||||
NETDB_MAX_EXPLORATORY_SELECTION_SIZE, m_Rng);
|
||||
NETDB_MAX_EXPLORATORY_SELECTION_SIZE, std::mt19937(ts));
|
||||
}
|
||||
else
|
||||
std::swap (m_ExploratorySelection, eligible);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -16,7 +16,6 @@
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <future>
|
||||
#include <random>
|
||||
|
||||
#include "Base.h"
|
||||
#include "Gzip.h"
|
||||
@@ -53,7 +52,6 @@ namespace data
|
||||
const int NETDB_MIN_HIGHBANDWIDTH_VERSION = MAKE_VERSION_NUMBER(0, 9, 58); // 0.9.58
|
||||
const int NETDB_MIN_FLOODFILL_VERSION = MAKE_VERSION_NUMBER(0, 9, 59); // 0.9.59
|
||||
const int NETDB_MIN_SHORT_TUNNEL_BUILD_VERSION = MAKE_VERSION_NUMBER(0, 9, 51); // 0.9.51
|
||||
const int NETDB_MIN_PEER_TEST_VERSION = MAKE_VERSION_NUMBER(0, 9, 62); // 0.9.62
|
||||
const size_t NETDB_MAX_NUM_SEARCH_REPLY_PEER_HASHES = 16;
|
||||
const size_t NETDB_MAX_EXPLORATORY_SELECTION_SIZE = 500;
|
||||
const int NETDB_EXPLORATORY_SELECTION_UPDATE_INTERVAL = 82; // in seconds. for floodfill
|
||||
@@ -187,11 +185,10 @@ namespace data
|
||||
std::shared_ptr<NetDbRequests> m_Requests;
|
||||
|
||||
bool m_PersistProfiles;
|
||||
std::future<void> m_SavingProfiles, m_DeletingProfiles, m_ApplyingProfileUpdates, m_PersistingRouters;
|
||||
std::future<void> m_SavingProfiles, m_DeletingProfiles, m_PersistingRouters;
|
||||
|
||||
std::vector<std::shared_ptr<const RouterInfo> > m_ExploratorySelection;
|
||||
uint64_t m_LastExploratorySelectionUpdateTime; // in monotonic seconds
|
||||
std::mt19937 m_Rng;
|
||||
|
||||
i2p::util::MemoryPoolMt<RouterInfo::Buffer> m_RouterInfoBuffersPool;
|
||||
i2p::util::MemoryPoolMt<RouterInfo::Address> m_RouterInfoAddressesPool;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -20,10 +20,8 @@ namespace i2p
|
||||
namespace data
|
||||
{
|
||||
RequestedDestination::RequestedDestination (const IdentHash& destination, bool isExploratory, bool direct):
|
||||
m_Destination (destination), m_IsExploratory (isExploratory), m_IsDirect (direct),
|
||||
m_IsActive (true), m_IsSentDirectly (false),
|
||||
m_CreationTime (i2p::util::GetMillisecondsSinceEpoch ()),
|
||||
m_LastRequestTime (0), m_NumAttempts (0)
|
||||
m_Destination (destination), m_IsExploratory (isExploratory), m_IsDirect (direct), m_IsActive (true),
|
||||
m_CreationTime (i2p::util::GetSecondsSinceEpoch ()), m_LastRequestTime (0), m_NumAttempts (0)
|
||||
{
|
||||
if (i2p::context.IsFloodfill ())
|
||||
m_ExcludedPeers.insert (i2p::context.GetIdentHash ()); // exclude self if floodfill
|
||||
@@ -46,9 +44,8 @@ namespace data
|
||||
msg = i2p::CreateRouterInfoDatabaseLookupMsg(m_Destination, i2p::context.GetIdentHash(), 0, m_IsExploratory, &m_ExcludedPeers);
|
||||
if(router)
|
||||
m_ExcludedPeers.insert (router->GetIdentHash ());
|
||||
m_LastRequestTime = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
m_LastRequestTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
m_NumAttempts++;
|
||||
m_IsSentDirectly = false;
|
||||
return msg;
|
||||
}
|
||||
|
||||
@@ -58,8 +55,7 @@ namespace data
|
||||
i2p::context.GetRouterInfo ().GetIdentHash () , 0, false, &m_ExcludedPeers);
|
||||
m_ExcludedPeers.insert (floodfill);
|
||||
m_NumAttempts++;
|
||||
m_LastRequestTime = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
m_IsSentDirectly = true;
|
||||
m_LastRequestTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
return msg;
|
||||
}
|
||||
|
||||
@@ -214,7 +210,7 @@ namespace data
|
||||
|
||||
void NetDbRequests::ManageRequests ()
|
||||
{
|
||||
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
|
||||
uint64_t ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
for (auto it = m_RequestedDestinations.begin (); it != m_RequestedDestinations.end ();)
|
||||
{
|
||||
auto& dest = it->second;
|
||||
@@ -226,8 +222,7 @@ namespace data
|
||||
bool done = false;
|
||||
if (ts < dest->GetCreationTime () + MAX_REQUEST_TIME)
|
||||
{
|
||||
if (ts > dest->GetLastRequestTime () + (dest->IsSentDirectly () ? MIN_DIRECT_REQUEST_TIME : MIN_REQUEST_TIME))
|
||||
// try next floodfill if no response after min interval
|
||||
if (ts > dest->GetLastRequestTime () + MIN_REQUEST_TIME) // try next floodfill if no response after min interval
|
||||
done = !SendNextRequest (dest);
|
||||
}
|
||||
else // request is expired
|
||||
@@ -333,8 +328,7 @@ namespace data
|
||||
|
||||
void NetDbRequests::ScheduleManageRequests ()
|
||||
{
|
||||
m_ManageRequestsTimer.expires_from_now (boost::posix_time::milliseconds(MANAGE_REQUESTS_INTERVAL +
|
||||
m_Rng () % MANAGE_REQUESTS_INTERVAL_VARIANCE));
|
||||
m_ManageRequestsTimer.expires_from_now (boost::posix_time::seconds(MANAGE_REQUESTS_INTERVAL));
|
||||
m_ManageRequestsTimer.async_wait (std::bind (&NetDbRequests::HandleManageRequestsTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -24,17 +24,15 @@ namespace i2p
|
||||
namespace data
|
||||
{
|
||||
const int MAX_NUM_REQUEST_ATTEMPTS = 5;
|
||||
const uint64_t MANAGE_REQUESTS_INTERVAL = 400; // in milliseconds
|
||||
const uint64_t MANAGE_REQUESTS_INTERVAL_VARIANCE = 300; // in milliseconds
|
||||
const uint64_t MIN_REQUEST_TIME = 1200; // in milliseconds
|
||||
const uint64_t MAX_REQUEST_TIME = MAX_NUM_REQUEST_ATTEMPTS * (MIN_REQUEST_TIME + MANAGE_REQUESTS_INTERVAL + MANAGE_REQUESTS_INTERVAL_VARIANCE);
|
||||
const uint64_t MIN_DIRECT_REQUEST_TIME = 600; // in milliseconds
|
||||
const uint64_t MANAGE_REQUESTS_INTERVAL = 1; // in seconds
|
||||
const uint64_t MIN_REQUEST_TIME = 5; // in seconds
|
||||
const uint64_t MAX_REQUEST_TIME = MAX_NUM_REQUEST_ATTEMPTS * (MIN_REQUEST_TIME + MANAGE_REQUESTS_INTERVAL);
|
||||
const uint64_t EXPLORATORY_REQUEST_INTERVAL = 55; // in seconds
|
||||
const uint64_t EXPLORATORY_REQUEST_INTERVAL_VARIANCE = 170; // in seconds
|
||||
const uint64_t DISCOVERED_REQUEST_INTERVAL = 360; // in milliseconds
|
||||
const uint64_t DISCOVERED_REQUEST_INTERVAL_VARIANCE = 540; // in milliseconds
|
||||
const uint64_t MAX_EXPLORATORY_REQUEST_TIME = 30000; // in milliseconds
|
||||
const uint64_t REQUEST_CACHE_TIME = MAX_REQUEST_TIME + 40000; // in milliseconds
|
||||
const uint64_t MAX_EXPLORATORY_REQUEST_TIME = 30; // in seconds
|
||||
const uint64_t REQUEST_CACHE_TIME = MAX_REQUEST_TIME + 40; // in seconds
|
||||
const uint64_t REQUESTED_DESTINATIONS_POOL_CLEANUP_INTERVAL = 191; // in seconds
|
||||
|
||||
class RequestedDestination
|
||||
@@ -53,7 +51,6 @@ namespace data
|
||||
bool IsExploratory () const { return m_IsExploratory; };
|
||||
bool IsDirect () const { return m_IsDirect; };
|
||||
bool IsActive () const { return m_IsActive; };
|
||||
bool IsSentDirectly () const { return m_IsSentDirectly; };
|
||||
bool IsExcluded (const IdentHash& ident) const;
|
||||
uint64_t GetCreationTime () const { return m_CreationTime; };
|
||||
uint64_t GetLastRequestTime () const { return m_LastRequestTime; };
|
||||
@@ -72,9 +69,9 @@ namespace data
|
||||
private:
|
||||
|
||||
IdentHash m_Destination;
|
||||
bool m_IsExploratory, m_IsDirect, m_IsActive, m_IsSentDirectly;
|
||||
bool m_IsExploratory, m_IsDirect, m_IsActive;
|
||||
std::unordered_set<IdentHash> m_ExcludedPeers;
|
||||
uint64_t m_CreationTime, m_LastRequestTime; // in milliseconds
|
||||
uint64_t m_CreationTime, m_LastRequestTime; // in seconds
|
||||
std::list<RequestComplete> m_RequestComplete;
|
||||
int m_NumAttempts;
|
||||
};
|
||||
@@ -118,9 +115,9 @@ namespace data
|
||||
|
||||
private:
|
||||
|
||||
i2p::util::MemoryPoolMt<RequestedDestination> m_RequestedDestinationsPool;
|
||||
std::unordered_map<IdentHash, std::shared_ptr<RequestedDestination> > m_RequestedDestinations;
|
||||
std::list<IdentHash> m_DiscoveredRouterHashes;
|
||||
i2p::util::MemoryPoolMt<RequestedDestination> m_RequestedDestinationsPool;
|
||||
boost::asio::deadline_timer m_ManageRequestsTimer, m_ExploratoryTimer,
|
||||
m_CleanupTimer, m_DiscoveredRoutersTimer;
|
||||
std::mt19937 m_Rng;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -27,15 +27,13 @@ namespace data
|
||||
static i2p::fs::HashedStorage g_ProfilesStorage("peerProfiles", "p", "profile-", "txt");
|
||||
static std::unordered_map<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > g_Profiles;
|
||||
static std::mutex g_ProfilesMutex;
|
||||
static std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > > g_PostponedUpdates;
|
||||
static std::mutex g_PostponedUpdatesMutex;
|
||||
|
||||
|
||||
RouterProfile::RouterProfile ():
|
||||
m_IsUpdated (false), m_LastDeclineTime (0), m_LastUnreachableTime (0),
|
||||
m_LastUpdateTime (i2p::util::GetSecondsSinceEpoch ()), m_LastAccessTime (0),
|
||||
m_LastPersistTime (0), m_NumTunnelsAgreed (0), m_NumTunnelsDeclined (0),
|
||||
m_NumTunnelsNonReplied (0),m_NumTimesTaken (0), m_NumTimesRejected (0),
|
||||
m_HasConnected (false), m_IsDuplicated (false)
|
||||
m_LastUpdateTime (i2p::util::GetSecondsSinceEpoch ()),
|
||||
m_NumTunnelsAgreed (0), m_NumTunnelsDeclined (0), m_NumTunnelsNonReplied (0),
|
||||
m_NumTimesTaken (0), m_NumTimesRejected (0), m_HasConnected (false),
|
||||
m_IsDuplicated (false)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -80,7 +78,6 @@ namespace data
|
||||
|
||||
void RouterProfile::Load (const IdentHash& identHash)
|
||||
{
|
||||
m_IsUpdated = false;
|
||||
std::string ident = identHash.ToBase64 ();
|
||||
std::string path = g_ProfilesStorage.Path(ident);
|
||||
boost::property_tree::ptree pt;
|
||||
@@ -258,42 +255,30 @@ namespace data
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
auto it = g_Profiles.find (identHash);
|
||||
if (it != g_Profiles.end ())
|
||||
{
|
||||
it->second->SetLastAccessTime (i2p::util::GetSecondsSinceEpoch ());
|
||||
return it->second;
|
||||
}
|
||||
}
|
||||
auto profile = netdb.NewRouterProfile ();
|
||||
profile->Load (identHash); // if possible
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
g_Profiles.emplace (identHash, profile);
|
||||
return profile;
|
||||
}
|
||||
|
||||
bool IsRouterBanned (const IdentHash& identHash)
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
auto it = g_Profiles.find (identHash);
|
||||
if (it != g_Profiles.end ())
|
||||
return it->second->IsUnreachable ();
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsRouterDuplicated (const IdentHash& identHash)
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
auto it = g_Profiles.find (identHash);
|
||||
if (it != g_Profiles.end ())
|
||||
return it->second->IsDuplicated ();
|
||||
return false;
|
||||
}
|
||||
|
||||
void InitProfilesStorage ()
|
||||
{
|
||||
g_ProfilesStorage.SetPlace(i2p::fs::GetDataDir());
|
||||
g_ProfilesStorage.Init(i2p::data::GetBase64SubstitutionTable(), 64);
|
||||
}
|
||||
|
||||
|
||||
static void SaveProfilesToDisk (std::list<std::pair<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > >&& profiles)
|
||||
{
|
||||
for (auto& it: profiles)
|
||||
@@ -305,17 +290,15 @@ namespace data
|
||||
auto ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
std::list<std::pair<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > > tmp;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
for (auto it = g_Profiles.begin (); it != g_Profiles.end ();)
|
||||
{
|
||||
if (it->second->IsUpdated () && ts > it->second->GetLastPersistTime () + PEER_PROFILE_PERSIST_INTERVAL)
|
||||
if (ts - it->second->GetLastUpdateTime () > PEER_PROFILE_PERSIST_INTERVAL)
|
||||
{
|
||||
tmp.push_back (std::make_pair (it->first, it->second));
|
||||
it->second->SetLastPersistTime (ts);
|
||||
it->second->SetUpdated (false);
|
||||
}
|
||||
if (!it->second->IsUpdated () && ts > std::max (it->second->GetLastUpdateTime (), it->second->GetLastAccessTime ()) + PEER_PROFILE_PERSIST_INTERVAL)
|
||||
if (it->second->IsUpdated ())
|
||||
tmp.push_back (std::make_pair (it->first, it->second));
|
||||
it = g_Profiles.erase (it);
|
||||
}
|
||||
else
|
||||
it++;
|
||||
}
|
||||
@@ -329,7 +312,7 @@ namespace data
|
||||
{
|
||||
std::unordered_map<i2p::data::IdentHash, std::shared_ptr<RouterProfile> > tmp;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
std::swap (tmp, g_Profiles);
|
||||
}
|
||||
auto ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
@@ -364,7 +347,7 @@ namespace data
|
||||
{
|
||||
{
|
||||
auto ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
std::unique_lock<std::mutex> l(g_ProfilesMutex);
|
||||
for (auto it = g_Profiles.begin (); it != g_Profiles.end ();)
|
||||
{
|
||||
if (ts - it->second->GetLastUpdateTime () >= PEER_PROFILE_EXPIRATION_TIMEOUT)
|
||||
@@ -376,47 +359,5 @@ namespace data
|
||||
|
||||
return std::async (std::launch::async, DeleteFilesFromDisk);
|
||||
}
|
||||
|
||||
bool UpdateRouterProfile (const IdentHash& identHash, std::function<void (std::shared_ptr<RouterProfile>)> update)
|
||||
{
|
||||
if (!update) return true;
|
||||
std::shared_ptr<RouterProfile> profile;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_ProfilesMutex);
|
||||
auto it = g_Profiles.find (identHash);
|
||||
if (it != g_Profiles.end ())
|
||||
profile = it->second;
|
||||
}
|
||||
if (profile)
|
||||
{
|
||||
update (profile);
|
||||
return true;
|
||||
}
|
||||
// postpone
|
||||
std::lock_guard<std::mutex> l(g_PostponedUpdatesMutex);
|
||||
g_PostponedUpdates.emplace_back (identHash, update);
|
||||
return false;
|
||||
}
|
||||
|
||||
static void ApplyPostponedUpdates (std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > >&& updates)
|
||||
{
|
||||
for (const auto& [ident, update] : updates)
|
||||
{
|
||||
auto profile = GetRouterProfile (ident);
|
||||
update (profile);
|
||||
}
|
||||
}
|
||||
|
||||
std::future<void> FlushPostponedRouterProfileUpdates ()
|
||||
{
|
||||
if (g_PostponedUpdates.empty ()) return std::future<void>();
|
||||
|
||||
std::list<std::pair<i2p::data::IdentHash, std::function<void (std::shared_ptr<RouterProfile>)> > > updates;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_PostponedUpdatesMutex);
|
||||
g_PostponedUpdates.swap (updates);
|
||||
}
|
||||
return std::async (std::launch::async, ApplyPostponedUpdates, std::move (updates));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include <functional>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
|
||||
@@ -45,8 +44,6 @@ namespace data
|
||||
const int PEER_PROFILE_UNREACHABLE_INTERVAL = 480; // in seconds (8 minutes)
|
||||
const int PEER_PROFILE_USEFUL_THRESHOLD = 3;
|
||||
const int PEER_PROFILE_ALWAYS_DECLINING_NUM = 5; // num declines in row to consider always declined
|
||||
const int PEER_PROFILE_APPLY_POSTPONED_TIMEOUT = 2100; // in milliseconds
|
||||
const int PEER_PROFILE_APPLY_POSTPONED_TIMEOUT_VARIANCE = 500; // in milliseconds
|
||||
|
||||
class RouterProfile
|
||||
{
|
||||
@@ -70,11 +67,6 @@ namespace data
|
||||
|
||||
uint64_t GetLastUpdateTime () const { return m_LastUpdateTime; };
|
||||
bool IsUpdated () const { return m_IsUpdated; };
|
||||
void SetUpdated (bool updated) { m_IsUpdated = updated; }
|
||||
uint64_t GetLastAccessTime () const { return m_LastAccessTime; };
|
||||
void SetLastAccessTime (uint64_t ts) { m_LastAccessTime = ts; };
|
||||
uint64_t GetLastPersistTime () const { return m_LastPersistTime; };
|
||||
void SetLastPersistTime (uint64_t ts) { m_LastPersistTime = ts; };
|
||||
|
||||
bool IsUseful() const;
|
||||
bool IsDuplicated () const { return m_IsDuplicated; };
|
||||
@@ -96,8 +88,7 @@ namespace data
|
||||
private:
|
||||
|
||||
bool m_IsUpdated;
|
||||
uint64_t m_LastDeclineTime, m_LastUnreachableTime, m_LastUpdateTime,
|
||||
m_LastAccessTime, m_LastPersistTime; // in seconds
|
||||
uint64_t m_LastDeclineTime, m_LastUnreachableTime, m_LastUpdateTime; // in seconds
|
||||
// participation
|
||||
uint32_t m_NumTunnelsAgreed;
|
||||
uint32_t m_NumTunnelsDeclined;
|
||||
@@ -113,13 +104,10 @@ namespace data
|
||||
|
||||
std::shared_ptr<RouterProfile> GetRouterProfile (const IdentHash& identHash);
|
||||
bool IsRouterBanned (const IdentHash& identHash); // check only existing profiles
|
||||
bool IsRouterDuplicated (const IdentHash& identHash); // check only existing profiles
|
||||
void InitProfilesStorage ();
|
||||
std::future<void> DeleteObsoleteProfiles ();
|
||||
void SaveProfiles ();
|
||||
std::future<void> PersistProfiles ();
|
||||
bool UpdateRouterProfile (const IdentHash& identHash, std::function<void (std::shared_ptr<RouterProfile>)> update); // return true if updated immediately, and false if postponed
|
||||
std::future<void> FlushPostponedRouterProfileUpdates ();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -33,14 +33,13 @@ namespace i2p
|
||||
m_ShareRatio (100), m_Status (eRouterStatusUnknown), m_StatusV6 (eRouterStatusUnknown),
|
||||
m_Error (eRouterErrorNone), m_ErrorV6 (eRouterErrorNone),
|
||||
m_Testing (false), m_TestingV6 (false), m_NetID (I2PD_NET_ID),
|
||||
m_PublishReplyToken (0), m_IsHiddenMode (false),
|
||||
m_Rng(i2p::util::GetMonotonicMicroseconds () % 1000000LL), m_IsSaving (false)
|
||||
m_PublishReplyToken (0), m_IsHiddenMode (false)
|
||||
{
|
||||
}
|
||||
|
||||
void RouterContext::Init ()
|
||||
{
|
||||
srand (m_Rng () % 1000);
|
||||
srand (i2p::util::GetMillisecondsSinceEpoch () % 1000);
|
||||
m_StartupTime = i2p::util::GetMonotonicSeconds ();
|
||||
|
||||
if (!Load ())
|
||||
@@ -77,7 +76,7 @@ namespace i2p
|
||||
m_CongestionUpdateTimer->cancel ();
|
||||
m_Service->Stop ();
|
||||
CleanUp (); // GarlicDestination
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<i2p::data::RouterInfo::Buffer> RouterContext::CopyRouterInfoBuffer () const
|
||||
@@ -254,36 +253,11 @@ namespace i2p
|
||||
|
||||
void RouterContext::UpdateRouterInfo ()
|
||||
{
|
||||
std::shared_ptr<i2p::data::RouterInfo::Buffer> buffer;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_RouterInfoMutex);
|
||||
m_RouterInfo.CreateBuffer (m_Keys);
|
||||
buffer = m_RouterInfo.CopyBuffer ();
|
||||
}
|
||||
{
|
||||
// update save buffer to latest
|
||||
std::lock_guard<std::mutex> l(m_SaveBufferMutex);
|
||||
m_SaveBuffer = buffer;
|
||||
}
|
||||
bool isSaving = false;
|
||||
if (m_IsSaving.compare_exchange_strong (isSaving, true)) // try to save only if not being saved
|
||||
{
|
||||
auto savingRouterInfo = std::async (std::launch::async, [this]()
|
||||
{
|
||||
std::shared_ptr<i2p::data::RouterInfo::Buffer> buffer;
|
||||
while (m_SaveBuffer)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_SaveBufferMutex);
|
||||
buffer = m_SaveBuffer;
|
||||
m_SaveBuffer = nullptr;
|
||||
}
|
||||
if (buffer)
|
||||
i2p::data::RouterInfo::SaveToFile (i2p::fs::DataDirPath (ROUTER_INFO), buffer);
|
||||
}
|
||||
m_IsSaving = false;
|
||||
});
|
||||
}
|
||||
m_RouterInfo.SaveToFile (i2p::fs::DataDirPath (ROUTER_INFO));
|
||||
m_LastUpdateTime = i2p::util::GetSecondsSinceEpoch ();
|
||||
}
|
||||
|
||||
@@ -1385,7 +1359,7 @@ namespace i2p
|
||||
{
|
||||
m_PublishTimer->cancel ();
|
||||
m_PublishTimer->expires_from_now (boost::posix_time::seconds(ROUTER_INFO_PUBLISH_INTERVAL +
|
||||
m_Rng () % ROUTER_INFO_PUBLISH_INTERVAL_VARIANCE));
|
||||
rand () % ROUTER_INFO_PUBLISH_INTERVAL_VARIANCE));
|
||||
m_PublishTimer->async_wait (std::bind (&RouterContext::HandlePublishTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
@@ -1460,7 +1434,7 @@ namespace i2p
|
||||
i2p::garlic::WrapECIESX25519MessageForRouter (msg, floodfill->GetIdentity ()->GetEncryptionPublicKey ()));
|
||||
}
|
||||
else
|
||||
LogPrint (eLogInfo, "Router: Can't publish our RouterInfo. No tunnels. Try again in ", ROUTER_INFO_CONFIRMATION_TIMEOUT, " milliseconds");
|
||||
LogPrint (eLogInfo, "Router: Can't publish our RouterInfo. No tunnles. Try again in ", ROUTER_INFO_CONFIRMATION_TIMEOUT, " seconds");
|
||||
}
|
||||
m_PublishExcluded.insert (floodfill->GetIdentHash ());
|
||||
m_PublishReplyToken = replyToken;
|
||||
@@ -1474,7 +1448,7 @@ namespace i2p
|
||||
if (m_PublishTimer)
|
||||
{
|
||||
m_PublishTimer->cancel ();
|
||||
m_PublishTimer->expires_from_now (boost::posix_time::milliseconds(ROUTER_INFO_CONFIRMATION_TIMEOUT));
|
||||
m_PublishTimer->expires_from_now (boost::posix_time::seconds(ROUTER_INFO_CONFIRMATION_TIMEOUT));
|
||||
m_PublishTimer->async_wait (std::bind (&RouterContext::HandlePublishResendTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
@@ -1497,8 +1471,7 @@ namespace i2p
|
||||
if (m_CongestionUpdateTimer)
|
||||
{
|
||||
m_CongestionUpdateTimer->cancel ();
|
||||
m_CongestionUpdateTimer->expires_from_now (boost::posix_time::seconds(
|
||||
ROUTER_INFO_CONGESTION_UPDATE_INTERVAL + m_Rng () % ROUTER_INFO_CONGESTION_UPDATE_INTERVAL_VARIANCE));
|
||||
m_CongestionUpdateTimer->expires_from_now (boost::posix_time::seconds(ROUTER_INFO_CONGESTION_UPDATE_INTERVAL));
|
||||
m_CongestionUpdateTimer->async_wait (std::bind (&RouterContext::HandleCongestionUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -12,7 +12,6 @@
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <unordered_set>
|
||||
#include <boost/asio.hpp>
|
||||
#include "Identity.h"
|
||||
@@ -35,10 +34,9 @@ namespace garlic
|
||||
const int ROUTER_INFO_PUBLISH_INTERVAL = 39*60; // in seconds
|
||||
const int ROUTER_INFO_INITIAL_PUBLISH_INTERVAL = 10; // in seconds
|
||||
const int ROUTER_INFO_PUBLISH_INTERVAL_VARIANCE = 105;// in seconds
|
||||
const int ROUTER_INFO_CONFIRMATION_TIMEOUT = 1600; // in milliseconds
|
||||
const int ROUTER_INFO_CONFIRMATION_TIMEOUT = 5; // in seconds
|
||||
const int ROUTER_INFO_MAX_PUBLISH_EXCLUDED_FLOODFILLS = 15;
|
||||
const int ROUTER_INFO_CONGESTION_UPDATE_INTERVAL = 11*60; // in seconds
|
||||
const int ROUTER_INFO_CONGESTION_UPDATE_INTERVAL_VARIANCE = 130; // in seconds
|
||||
const int ROUTER_INFO_CONGESTION_UPDATE_INTERVAL = 12*60; // in seconds
|
||||
const int ROUTER_INFO_CLEANUP_INTERVAL = 102; // in seconds
|
||||
|
||||
enum RouterStatus
|
||||
@@ -265,10 +263,6 @@ namespace garlic
|
||||
uint32_t m_PublishReplyToken;
|
||||
bool m_IsHiddenMode; // not publish
|
||||
mutable std::mutex m_RouterInfoMutex;
|
||||
std::mt19937 m_Rng;
|
||||
std::shared_ptr<i2p::data::RouterInfo::Buffer> m_SaveBuffer;
|
||||
std::mutex m_SaveBufferMutex; // TODO: make m_SaveBuffer atomic
|
||||
std::atomic<bool> m_IsSaving;
|
||||
};
|
||||
|
||||
extern RouterContext context;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -486,15 +486,6 @@ namespace data
|
||||
}
|
||||
ch++;
|
||||
}
|
||||
if (m_Version < NETDB_MIN_PEER_TEST_VERSION && (m_SupportedTransports & (eSSU2V4 | eSSU2V6)))
|
||||
{
|
||||
auto addresses = GetAddresses ();
|
||||
if (addresses)
|
||||
{
|
||||
if ((*addresses)[eSSU2V4Idx]) (*addresses)[eSSU2V4Idx]->caps &= ~eSSUTesting;
|
||||
if ((*addresses)[eSSU2V6Idx]) (*addresses)[eSSU2V6Idx]->caps &= ~eSSUTesting;
|
||||
}
|
||||
}
|
||||
}
|
||||
// check netId
|
||||
else if (!strcmp (key, ROUTER_INFO_PROPERTY_NETID))
|
||||
@@ -1145,12 +1136,12 @@ namespace data
|
||||
|
||||
void RouterInfo::UpdateBuffer (const uint8_t * buf, size_t len)
|
||||
{
|
||||
m_IsBufferScheduledToDelete = false;
|
||||
if (!m_Buffer)
|
||||
m_Buffer = NewBuffer ();
|
||||
if (len > m_Buffer->size ()) len = m_Buffer->size ();
|
||||
memcpy (m_Buffer->data (), buf, len);
|
||||
m_Buffer->SetBufferLen (len);
|
||||
m_IsBufferScheduledToDelete = false;
|
||||
}
|
||||
|
||||
std::shared_ptr<RouterInfo::Buffer> RouterInfo::CopyBuffer () const
|
||||
@@ -1204,19 +1195,6 @@ namespace data
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string RouterInfo::GetTransportName (SupportedTransports tr)
|
||||
{
|
||||
switch (tr)
|
||||
{
|
||||
case eNTCP2V4: return "NTCP2V4";
|
||||
case eNTCP2V6: return "NTCP2V6";
|
||||
case eSSU2V4: return "SSU2V4";
|
||||
case eSSU2V6: return "SSU2V6";
|
||||
case eNTCP2V6Mesh: return "Mesh";
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
void LocalRouterInfo::CreateBuffer (const PrivateKeys& privateKeys)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -294,7 +294,6 @@ namespace data
|
||||
std::shared_ptr<Buffer> GetSharedBuffer () const { return m_Buffer; };
|
||||
std::shared_ptr<Buffer> CopyBuffer () const;
|
||||
void ScheduleBufferToDelete () { m_IsBufferScheduledToDelete = true; };
|
||||
void CancelBufferToDelete () { m_IsBufferScheduledToDelete = false; };
|
||||
bool IsBufferScheduledToDelete () const { return m_IsBufferScheduledToDelete; };
|
||||
|
||||
bool IsUpdated () const { return m_IsUpdated; };
|
||||
@@ -364,10 +363,6 @@ namespace data
|
||||
int m_Version;
|
||||
Congestion m_Congestion;
|
||||
mutable std::shared_ptr<RouterProfile> m_Profile;
|
||||
|
||||
public:
|
||||
|
||||
static std::string GetTransportName (SupportedTransports tr);
|
||||
};
|
||||
|
||||
class LocalRouterInfo: public RouterInfo
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2022-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2022-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -890,7 +890,7 @@ namespace transport
|
||||
}
|
||||
|
||||
auto session = std::make_shared<SSU2Session> (*this, router, address);
|
||||
if (!isValidEndpoint && router->HasProfile () && router->GetProfile ()->HasLastEndpoint (address->IsV4 ()))
|
||||
if (!isValidEndpoint && router->GetProfile ()->HasLastEndpoint (address->IsV4 ()))
|
||||
{
|
||||
// router doesn't publish endpoint, but we connected before and hole punch might be alive
|
||||
auto ep = router->GetProfile ()->GetLastEndpoint ();
|
||||
@@ -1389,7 +1389,7 @@ namespace transport
|
||||
excluded.insert (ident);
|
||||
}
|
||||
|
||||
// session about to expire are not counted
|
||||
// sesssion about to expire are not counted
|
||||
for (auto i = introducers.size (); i < SSU2_MAX_NUM_INTRODUCERS + numOldSessions; i++)
|
||||
{
|
||||
auto introducer = i2p::data::netdb.GetRandomSSU2Introducer (v4, excluded);
|
||||
@@ -1516,23 +1516,6 @@ namespace transport
|
||||
}
|
||||
}
|
||||
|
||||
bool SSU2Server::AEADChaCha20Poly1305Encrypt (const uint8_t * msg, size_t msgLen,
|
||||
const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return m_Encryptor.Encrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
|
||||
}
|
||||
|
||||
bool SSU2Server::AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen,
|
||||
const uint8_t * ad, size_t adLen, const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len)
|
||||
{
|
||||
return m_Decryptor.Decrypt (msg, msgLen, ad, adLen, key, nonce, buf, len);
|
||||
}
|
||||
|
||||
void SSU2Server::ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out)
|
||||
{
|
||||
m_ChaCha20 (msg, msgLen, key, nonce, out);
|
||||
}
|
||||
|
||||
void SSU2Server::SendThroughProxy (const uint8_t * header, size_t headerLen, const uint8_t * headerX, size_t headerXLen,
|
||||
const uint8_t * payload, size_t payloadLen, const boost::asio::ip::udp::endpoint& to)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2022-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2022-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -82,11 +82,6 @@ namespace transport
|
||||
bool IsConnectedRecently (const boost::asio::ip::udp::endpoint& ep, bool max = true);
|
||||
void AddConnectedRecently (const boost::asio::ip::udp::endpoint& ep, uint64_t ts);
|
||||
std::mt19937& GetRng () { return m_Rng; }
|
||||
bool AEADChaCha20Poly1305Encrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len);
|
||||
bool AEADChaCha20Poly1305Decrypt (const uint8_t * msg, size_t msgLen, const uint8_t * ad, size_t adLen,
|
||||
const uint8_t * key, const uint8_t * nonce, uint8_t * buf, size_t len);
|
||||
void ChaCha20 (const uint8_t * msg, size_t msgLen, const uint8_t * key, const uint8_t * nonce, uint8_t * out);
|
||||
bool IsMaxNumIntroducers (bool v4) const { return (v4 ? m_Introducers.size () : m_IntroducersV6.size ()) >= SSU2_MAX_NUM_INTRODUCERS; }
|
||||
bool IsSyncClockFromPeers () const { return m_IsSyncClockFromPeers; };
|
||||
void AdjustTimeOffset (int64_t offset, std::shared_ptr<const i2p::data::IdentityEx> from);
|
||||
@@ -205,9 +200,6 @@ namespace transport
|
||||
std::unordered_map<uint32_t, std::pair <std::weak_ptr<SSU2PeerTestSession>, uint64_t > > m_RequestedPeerTests; // nonce->(Alice, timestamp)
|
||||
std::list<Packet *> m_ReceivedPacketsQueue;
|
||||
mutable std::mutex m_ReceivedPacketsQueueMutex;
|
||||
i2p::crypto::AEADChaCha20Poly1305Encryptor m_Encryptor;
|
||||
i2p::crypto::AEADChaCha20Poly1305Decryptor m_Decryptor;
|
||||
i2p::crypto::ChaCha20Context m_ChaCha20;
|
||||
|
||||
// proxy
|
||||
bool m_IsThroughProxy;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -46,7 +46,7 @@ namespace transport
|
||||
}
|
||||
uint8_t nonce[12] = {0};
|
||||
uint64_t headerX[2]; // sourceConnID, token
|
||||
GetServer ().ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
SetDestConnID (headerX[0]);
|
||||
// decrypt and handle payload
|
||||
uint8_t * payload = buf + 32;
|
||||
@@ -68,7 +68,7 @@ namespace transport
|
||||
void SSU2PeerTestSession::HandleAddress (const uint8_t * buf, size_t len)
|
||||
{
|
||||
if (!ExtractEndpoint (buf, len, m_OurEndpoint))
|
||||
LogPrint (eLogWarning, "SSU2: Can't handle address block from peer test message");
|
||||
LogPrint (eLogWarning, "SSU2: Can't hanlde address block from peer test message");
|
||||
}
|
||||
|
||||
void SSU2PeerTestSession::HandlePeerTest (const uint8_t * buf, size_t len)
|
||||
@@ -89,7 +89,7 @@ namespace transport
|
||||
{
|
||||
if (htobe64 (((uint64_t)nonce << 32) | nonce) == GetSourceConnID ())
|
||||
{
|
||||
m_PeerTestResendTimer.cancel (); // cancel delayed msg 6 if any
|
||||
m_PeerTestResendTimer.cancel (); // calcel delayed msg 6 if any
|
||||
m_IsConnectedRecently = GetServer ().IsConnectedRecently (GetRemoteEndpoint ());
|
||||
if (GetAddress ())
|
||||
{
|
||||
@@ -183,7 +183,7 @@ namespace transport
|
||||
header.ll[0] ^= CreateHeaderMask (addr->i, payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (addr->i, payload + (payloadSize - 12));
|
||||
memset (n, 0, 12);
|
||||
GetServer ().ChaCha20 (h + 16, 16, addr->i, n, h + 16);
|
||||
i2p::crypto::ChaCha20 (h + 16, 16, addr->i, n, h + 16);
|
||||
// send
|
||||
GetServer ().Send (header.buf, 16, h + 16, 16, payload, payloadSize, GetRemoteEndpoint ());
|
||||
UpdateNumSentBytes (payloadSize + 32);
|
||||
@@ -305,7 +305,7 @@ namespace transport
|
||||
header.ll[0] ^= CreateHeaderMask (addr->i, payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (addr->i, payload + (payloadSize - 12));
|
||||
memset (n, 0, 12);
|
||||
GetServer ().ChaCha20 (h + 16, 16, addr->i, n, h + 16);
|
||||
i2p::crypto::ChaCha20 (h + 16, 16, addr->i, n, h + 16);
|
||||
// send
|
||||
GetServer ().Send (header.buf, 16, h + 16, 16, payload, payloadSize, ep);
|
||||
UpdateNumSentBytes (payloadSize + 32);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2022-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2022-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -92,7 +92,7 @@ namespace transport
|
||||
m_RTO (SSU2_INITIAL_RTO), m_RelayTag (0),m_ConnectTimer (server.GetService ()),
|
||||
m_TerminationReason (eSSU2TerminationReasonNormalClose),
|
||||
m_MaxPayloadSize (SSU2_MIN_PACKET_SIZE - IPV6_HEADER_SIZE - UDP_HEADER_SIZE - 32), // min size
|
||||
m_LastResendTime (0), m_LastResendAttemptTime (0), m_NumRanges (0)
|
||||
m_LastResendTime (0), m_LastResendAttemptTime (0)
|
||||
{
|
||||
if (noise)
|
||||
m_NoiseState.reset (new i2p::crypto::NoiseSymmetricState);
|
||||
@@ -349,7 +349,7 @@ namespace transport
|
||||
|
||||
void SSU2Session::Done ()
|
||||
{
|
||||
boost::asio::post (m_Server.GetService (), std::bind (&SSU2Session::Terminate, shared_from_this ()));
|
||||
m_Server.GetService ().post (std::bind (&SSU2Session::Terminate, shared_from_this ()));
|
||||
}
|
||||
|
||||
void SSU2Session::SendLocalRouterInfo (bool update)
|
||||
@@ -357,7 +357,7 @@ namespace transport
|
||||
if (update || !IsOutgoing ())
|
||||
{
|
||||
auto s = shared_from_this ();
|
||||
boost::asio::post (m_Server.GetService (), [s]()
|
||||
m_Server.GetService ().post ([s]()
|
||||
{
|
||||
if (!s->IsEstablished ()) return;
|
||||
uint8_t payload[SSU2_MAX_PACKET_SIZE];
|
||||
@@ -389,7 +389,7 @@ namespace transport
|
||||
m_IntermediateQueue.splice (m_IntermediateQueue.end (), msgs);
|
||||
}
|
||||
if (empty)
|
||||
boost::asio::post (m_Server.GetService (), std::bind (&SSU2Session::PostI2NPMessages, shared_from_this ()));
|
||||
m_Server.GetService ().post (std::bind (&SSU2Session::PostI2NPMessages, shared_from_this ()));
|
||||
}
|
||||
|
||||
void SSU2Session::PostI2NPMessages ()
|
||||
@@ -623,8 +623,7 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
uint32_t packetNum = SendData (it->second->payload, it->second->payloadSize,
|
||||
it->second->numResends > 1 ? SSU2_FLAG_IMMEDIATE_ACK_REQUESTED : 0);
|
||||
uint32_t packetNum = SendData (it->second->payload, it->second->payloadSize);
|
||||
it->second->numResends++;
|
||||
it->second->sendTime = ts;
|
||||
resentPackets.emplace (packetNum, it->second);
|
||||
@@ -683,7 +682,7 @@ namespace transport
|
||||
}
|
||||
const uint8_t nonce[12] = {0};
|
||||
uint64_t headerX[2];
|
||||
m_Server.ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
LogPrint (eLogWarning, "SSU2: Unexpected PeerTest message SourceConnID=", connID, " DestConnID=", headerX[0]);
|
||||
break;
|
||||
}
|
||||
@@ -749,7 +748,7 @@ namespace transport
|
||||
payloadSize += 16;
|
||||
header.ll[0] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 12));
|
||||
m_Server.ChaCha20 (headerX, 48, m_Address->i, nonce, headerX);
|
||||
i2p::crypto::ChaCha20 (headerX, 48, m_Address->i, nonce, headerX);
|
||||
m_NoiseState->MixHash (payload, payloadSize); // h = SHA256(h || encrypted payload from Session Request) for SessionCreated
|
||||
m_SentHandshakePacket->payloadSize = payloadSize;
|
||||
// send
|
||||
@@ -776,7 +775,7 @@ namespace transport
|
||||
}
|
||||
const uint8_t nonce[12] = {0};
|
||||
uint8_t headerX[48];
|
||||
m_Server.ChaCha20 (buf + 16, 48, i2p::context.GetSSU2IntroKey (), nonce, headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 48, i2p::context.GetSSU2IntroKey (), nonce, headerX);
|
||||
memcpy (&m_DestConnID, headerX, 8);
|
||||
uint64_t token;
|
||||
memcpy (&token, headerX + 8, 8);
|
||||
@@ -875,7 +874,7 @@ namespace transport
|
||||
m_NoiseState->MixHash (payload, payloadSize); // h = SHA256(h || encrypted Noise payload from Session Created)
|
||||
header.ll[0] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (kh2, payload + (payloadSize - 12));
|
||||
m_Server.ChaCha20 (headerX, 48, kh2, nonce, headerX);
|
||||
i2p::crypto::ChaCha20 (headerX, 48, kh2, nonce, headerX);
|
||||
m_State = eSSU2SessionStateSessionCreatedSent;
|
||||
m_SentHandshakePacket->payloadSize = payloadSize;
|
||||
// send
|
||||
@@ -903,7 +902,7 @@ namespace transport
|
||||
m_HandshakeInterval = i2p::util::GetMillisecondsSinceEpoch () - m_HandshakeInterval;
|
||||
const uint8_t nonce[12] = {0};
|
||||
uint8_t headerX[48];
|
||||
m_Server.ChaCha20 (buf + 16, 48, kh2, nonce, headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 48, kh2, nonce, headerX);
|
||||
// KDF for SessionCreated
|
||||
m_NoiseState->MixHash ( { {header.buf, 16}, {headerX, 16} } ); // h = SHA256(h || header)
|
||||
m_NoiseState->MixHash (headerX + 16, 32); // h = SHA256(h || bepk);
|
||||
@@ -1179,18 +1178,13 @@ namespace transport
|
||||
LogPrint (eLogError, "SSU2: Couldn't update RouterInfo from SessionConfirmed in netdb");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isOlder = false;
|
||||
std::shared_ptr<i2p::data::RouterProfile> profile; // not null if older
|
||||
if (ri->GetTimestamp () + i2p::data::NETDB_EXPIRATION_TIMEOUT_THRESHOLD*1000LL < ri1->GetTimestamp ())
|
||||
{
|
||||
// received RouterInfo is older than one in netdb
|
||||
isOlder = true;
|
||||
if (ri->HasProfile ())
|
||||
{
|
||||
auto profile = i2p::data::GetRouterProfile (ri->GetIdentHash ()); // retrieve profile
|
||||
if (profile && profile->IsDuplicated ())
|
||||
return false;
|
||||
}
|
||||
profile = i2p::data::GetRouterProfile (ri->GetIdentHash ()); // retrieve profile
|
||||
if (profile && profile->IsDuplicated ())
|
||||
return false;
|
||||
}
|
||||
ri = ri1;
|
||||
|
||||
@@ -1204,28 +1198,15 @@ namespace transport
|
||||
(!m_RemoteEndpoint.address ().is_v6 () ||
|
||||
memcmp (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), m_Address->host.to_v6 ().to_bytes ().data (), 8))) // temporary address
|
||||
{
|
||||
if (isOlder) // older router?
|
||||
i2p::data::UpdateRouterProfile (ri->GetIdentHash (),
|
||||
[](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->Duplicated (); // mark router as duplicated in profile
|
||||
});
|
||||
if (profile) // older router?
|
||||
profile->Duplicated (); // mark router as duplicated in profile
|
||||
else
|
||||
LogPrint (eLogInfo, "SSU2: Host mismatch between published address ", m_Address->host,
|
||||
" and actual endpoint ", m_RemoteEndpoint.address (), " from ", i2p::data::GetIdentHashAbbreviation (ri->GetIdentHash ()));
|
||||
return false;
|
||||
}
|
||||
if (!m_Address->published)
|
||||
{
|
||||
if (ri->HasProfile ())
|
||||
ri->GetProfile ()->SetLastEndpoint (m_RemoteEndpoint);
|
||||
else
|
||||
i2p::data::UpdateRouterProfile (ri->GetIdentHash (),
|
||||
[ep = m_RemoteEndpoint](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->SetLastEndpoint (ep);
|
||||
});
|
||||
}
|
||||
ri->GetProfile ()->SetLastEndpoint (m_RemoteEndpoint);
|
||||
SetRemoteIdentity (ri->GetRouterIdentity ());
|
||||
AdjustMaxPayloadSize ();
|
||||
m_Server.AddSessionByRouterHash (shared_from_this ()); // we know remote router now
|
||||
@@ -1283,7 +1264,7 @@ namespace transport
|
||||
header.ll[0] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (m_Address->i, payload + (payloadSize - 12));
|
||||
memset (nonce, 0, 12);
|
||||
m_Server.ChaCha20 (h + 16, 16, m_Address->i, nonce, h + 16);
|
||||
i2p::crypto::ChaCha20 (h + 16, 16, m_Address->i, nonce, h + 16);
|
||||
// send
|
||||
if (m_Server.AddPendingOutgoingSession (shared_from_this ()))
|
||||
m_Server.Send (header.buf, 16, h + 16, 16, payload, payloadSize, m_RemoteEndpoint);
|
||||
@@ -1305,7 +1286,7 @@ namespace transport
|
||||
uint8_t nonce[12] = {0};
|
||||
uint8_t h[32];
|
||||
memcpy (h, header.buf, 16);
|
||||
m_Server.ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, h + 16);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, h + 16);
|
||||
memcpy (&m_DestConnID, h + 16, 8);
|
||||
// decrypt
|
||||
CreateNonce (be32toh (header.h.packetNum), nonce);
|
||||
@@ -1357,7 +1338,7 @@ namespace transport
|
||||
header.ll[0] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), payload + (payloadSize - 24));
|
||||
header.ll[1] ^= CreateHeaderMask (i2p::context.GetSSU2IntroKey (), payload + (payloadSize - 12));
|
||||
memset (nonce, 0, 12);
|
||||
m_Server.ChaCha20 (h + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, h + 16);
|
||||
i2p::crypto::ChaCha20 (h + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, h + 16);
|
||||
// send
|
||||
m_Server.Send (header.buf, 16, h + 16, 16, payload, payloadSize, m_RemoteEndpoint);
|
||||
}
|
||||
@@ -1381,7 +1362,7 @@ namespace transport
|
||||
}
|
||||
uint8_t nonce[12] = {0};
|
||||
uint64_t headerX[2]; // sourceConnID, token
|
||||
m_Server.ChaCha20 (buf + 16, 16, m_Address->i, nonce, (uint8_t *)headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 16, m_Address->i, nonce, (uint8_t *)headerX);
|
||||
uint64_t token = headerX[1];
|
||||
if (token)
|
||||
m_Server.UpdateOutgoingToken (m_RemoteEndpoint, token, i2p::util::GetSecondsSinceEpoch () + SSU2_TOKEN_EXPIRATION_TIMEOUT);
|
||||
@@ -1430,7 +1411,7 @@ namespace transport
|
||||
}
|
||||
uint8_t nonce[12] = {0};
|
||||
uint64_t headerX[2]; // sourceConnID, token
|
||||
m_Server.ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
i2p::crypto::ChaCha20 (buf + 16, 16, i2p::context.GetSSU2IntroKey (), nonce, (uint8_t *)headerX);
|
||||
m_DestConnID = headerX[0];
|
||||
// decrypt and handle payload
|
||||
uint8_t * payload = buf + 32;
|
||||
@@ -1474,7 +1455,7 @@ namespace transport
|
||||
uint8_t nonce[12];
|
||||
CreateNonce (m_SendPacketNum, nonce);
|
||||
uint8_t payload[SSU2_MAX_PACKET_SIZE];
|
||||
m_Server.AEADChaCha20Poly1305Encrypt (buf, len, header.buf, 16, m_KeyDataSend, nonce, payload, SSU2_MAX_PACKET_SIZE);
|
||||
i2p::crypto::AEADChaCha20Poly1305 (buf, len, header.buf, 16, m_KeyDataSend, nonce, payload, SSU2_MAX_PACKET_SIZE, true);
|
||||
header.ll[0] ^= CreateHeaderMask (m_Address->i, payload + (len - 8));
|
||||
header.ll[1] ^= CreateHeaderMask (m_KeyDataSend + 32, payload + (len + 4));
|
||||
m_Server.Send (header.buf, 16, payload, len + 16, m_RemoteEndpoint);
|
||||
@@ -1514,8 +1495,8 @@ namespace transport
|
||||
uint32_t packetNum = be32toh (header.h.packetNum);
|
||||
uint8_t nonce[12];
|
||||
CreateNonce (packetNum, nonce);
|
||||
if (!m_Server.AEADChaCha20Poly1305Decrypt (buf + 16, payloadSize, header.buf, 16,
|
||||
m_KeyDataReceive, nonce, payload, payloadSize))
|
||||
if (!i2p::crypto::AEADChaCha20Poly1305 (buf + 16, payloadSize, header.buf, 16,
|
||||
m_KeyDataReceive, nonce, payload, payloadSize, false))
|
||||
{
|
||||
LogPrint (eLogWarning, "SSU2: Data AEAD verification failed ");
|
||||
return;
|
||||
@@ -1763,7 +1744,6 @@ namespace transport
|
||||
HandleAckRange (firstPacketNum, ackThrough, i2p::util::GetMillisecondsSinceEpoch ()); // acnt
|
||||
// ranges
|
||||
len -= 5;
|
||||
if (!len || m_SentPackets.empty ()) return; // don't handle ranges if nothing to acknowledge
|
||||
const uint8_t * ranges = buf + 5;
|
||||
while (len > 0 && firstPacketNum && ackThrough - firstPacketNum < SSU2_MAX_NUM_ACK_PACKETS)
|
||||
{
|
||||
@@ -2072,7 +2052,7 @@ namespace transport
|
||||
auto vec = std::make_shared<std::vector<uint8_t> >(len);
|
||||
memcpy (vec->data (), buf, len);
|
||||
auto s = shared_from_this ();
|
||||
boost::asio::post (m_Server.GetService (), [s, vec, attempts]()
|
||||
m_Server.GetService ().post ([s, vec, attempts]()
|
||||
{
|
||||
LogPrint (eLogDebug, "SSU2: RelayIntro attempt ", attempts + 1);
|
||||
s->HandleRelayIntro (vec->data (), vec->size (), attempts + 1);
|
||||
@@ -2644,17 +2624,17 @@ namespace transport
|
||||
size_t SSU2Session::CreateAckBlock (uint8_t * buf, size_t len)
|
||||
{
|
||||
if (len < 8) return 0;
|
||||
int maxNumRanges = (len - 8) >> 1;
|
||||
if (maxNumRanges > SSU2_MAX_NUM_ACK_RANGES) maxNumRanges = SSU2_MAX_NUM_ACK_RANGES;
|
||||
buf[0] = eSSU2BlkAck;
|
||||
uint32_t ackThrough = m_OutOfSequencePackets.empty () ? m_ReceivePacketNum : *m_OutOfSequencePackets.rbegin ();
|
||||
htobe32buf (buf + 3, ackThrough); // Ack Through
|
||||
uint16_t acnt = 0;
|
||||
int numRanges = 0;
|
||||
if (ackThrough)
|
||||
{
|
||||
if (m_OutOfSequencePackets.empty ())
|
||||
{
|
||||
acnt = std::min ((int)ackThrough, SSU2_MAX_NUM_ACNT); // no gaps
|
||||
m_NumRanges = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
auto it = m_OutOfSequencePackets.rbegin (); it++; // prev packet num
|
||||
@@ -2667,96 +2647,87 @@ namespace transport
|
||||
it++;
|
||||
}
|
||||
// ranges
|
||||
if (!m_NumRanges)
|
||||
{
|
||||
int maxNumRanges = (len - 8) >> 1;
|
||||
if (maxNumRanges > SSU2_MAX_NUM_ACK_RANGES) maxNumRanges = SSU2_MAX_NUM_ACK_RANGES;
|
||||
int numRanges = 0;
|
||||
uint32_t lastNum = ackThrough - acnt;
|
||||
if (acnt > SSU2_MAX_NUM_ACNT)
|
||||
uint32_t lastNum = ackThrough - acnt;
|
||||
if (acnt > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
auto d = std::div (acnt - SSU2_MAX_NUM_ACNT, SSU2_MAX_NUM_ACNT);
|
||||
acnt = SSU2_MAX_NUM_ACNT;
|
||||
if (d.quot > maxNumRanges)
|
||||
{
|
||||
auto d = std::div (acnt - SSU2_MAX_NUM_ACNT, SSU2_MAX_NUM_ACNT);
|
||||
acnt = SSU2_MAX_NUM_ACNT;
|
||||
if (d.quot > maxNumRanges)
|
||||
{
|
||||
d.quot = maxNumRanges;
|
||||
d.rem = 0;
|
||||
}
|
||||
// Acks only ranges for acnt
|
||||
for (int i = 0; i < d.quot; i++)
|
||||
{
|
||||
m_Ranges[numRanges*2] = 0; m_Ranges[numRanges*2 + 1] = SSU2_MAX_NUM_ACNT; // NACKs 0, Acks 255
|
||||
numRanges++;
|
||||
}
|
||||
if (d.rem > 0)
|
||||
{
|
||||
m_Ranges[numRanges*2] = 0; m_Ranges[numRanges*2 + 1] = d.rem;
|
||||
numRanges++;
|
||||
}
|
||||
d.quot = maxNumRanges;
|
||||
d.rem = 0;
|
||||
}
|
||||
int numPackets = acnt + numRanges*SSU2_MAX_NUM_ACNT;
|
||||
while (it != m_OutOfSequencePackets.rend () &&
|
||||
numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS)
|
||||
// Acks only ranges for acnt
|
||||
for (int i = 0; i < d.quot; i++)
|
||||
{
|
||||
if (lastNum - (*it) > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
// NACKs only ranges
|
||||
if (lastNum > (*it) + SSU2_MAX_NUM_ACNT*(maxNumRanges - numRanges)) break; // too many NACKs
|
||||
while (lastNum - (*it) > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
m_Ranges[numRanges*2] = SSU2_MAX_NUM_ACNT; m_Ranges[numRanges*2 + 1] = 0; // NACKs 255, Acks 0
|
||||
lastNum -= SSU2_MAX_NUM_ACNT;
|
||||
numRanges++;
|
||||
numPackets += SSU2_MAX_NUM_ACNT;
|
||||
}
|
||||
}
|
||||
// NACKs and Acks ranges
|
||||
m_Ranges[numRanges*2] = lastNum - (*it) - 1; // NACKs
|
||||
numPackets += m_Ranges[numRanges*2];
|
||||
lastNum = *it; it++;
|
||||
int numAcks = 1;
|
||||
while (it != m_OutOfSequencePackets.rend () && lastNum > 0 && *it == lastNum - 1)
|
||||
{
|
||||
numAcks++; lastNum--;
|
||||
it++;
|
||||
}
|
||||
while (numAcks > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
// Acks only ranges
|
||||
m_Ranges[numRanges*2 + 1] = SSU2_MAX_NUM_ACNT; // Acks 255
|
||||
numAcks -= SSU2_MAX_NUM_ACNT;
|
||||
numRanges++;
|
||||
numPackets += SSU2_MAX_NUM_ACNT;
|
||||
m_Ranges[numRanges*2] = 0; // NACKs 0
|
||||
if (numRanges >= maxNumRanges || numPackets >= SSU2_MAX_NUM_ACK_PACKETS) break;
|
||||
}
|
||||
if (numAcks > SSU2_MAX_NUM_ACNT) numAcks = SSU2_MAX_NUM_ACNT;
|
||||
m_Ranges[numRanges*2 + 1] = (uint8_t)numAcks; // Acks
|
||||
numPackets += numAcks;
|
||||
buf[8 + numRanges*2] = 0; buf[8 + numRanges*2 + 1] = SSU2_MAX_NUM_ACNT; // NACKs 0, Acks 255
|
||||
numRanges++;
|
||||
}
|
||||
if (it == m_OutOfSequencePackets.rend () &&
|
||||
numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS)
|
||||
if (d.rem > 0)
|
||||
{
|
||||
// add range between out-of-sequence and received
|
||||
int nacks = *m_OutOfSequencePackets.begin () - m_ReceivePacketNum - 1;
|
||||
if (nacks > 0)
|
||||
buf[8 + numRanges*2] = 0; buf[8 + numRanges*2 + 1] = d.rem;
|
||||
numRanges++;
|
||||
}
|
||||
}
|
||||
int numPackets = acnt + numRanges*SSU2_MAX_NUM_ACNT;
|
||||
while (it != m_OutOfSequencePackets.rend () &&
|
||||
numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS)
|
||||
{
|
||||
if (lastNum - (*it) > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
// NACKs only ranges
|
||||
if (lastNum > (*it) + SSU2_MAX_NUM_ACNT*(maxNumRanges - numRanges)) break; // too many NACKs
|
||||
while (lastNum - (*it) > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
if (nacks > SSU2_MAX_NUM_ACNT) nacks = SSU2_MAX_NUM_ACNT;
|
||||
m_Ranges[numRanges*2] = nacks;
|
||||
m_Ranges[numRanges*2 + 1] = std::min ((int)m_ReceivePacketNum + 1, SSU2_MAX_NUM_ACNT);
|
||||
buf[8 + numRanges*2] = SSU2_MAX_NUM_ACNT; buf[8 + numRanges*2 + 1] = 0; // NACKs 255, Acks 0
|
||||
lastNum -= SSU2_MAX_NUM_ACNT;
|
||||
numRanges++;
|
||||
numPackets += SSU2_MAX_NUM_ACNT;
|
||||
}
|
||||
}
|
||||
m_NumRanges = numRanges;
|
||||
}
|
||||
if (m_NumRanges)
|
||||
memcpy (buf + 8, m_Ranges, m_NumRanges*2);
|
||||
// NACKs and Acks ranges
|
||||
buf[8 + numRanges*2] = lastNum - (*it) - 1; // NACKs
|
||||
numPackets += buf[8 + numRanges*2];
|
||||
lastNum = *it; it++;
|
||||
int numAcks = 1;
|
||||
while (it != m_OutOfSequencePackets.rend () && lastNum > 0 && *it == lastNum - 1)
|
||||
{
|
||||
numAcks++; lastNum--;
|
||||
it++;
|
||||
}
|
||||
while (numAcks > SSU2_MAX_NUM_ACNT)
|
||||
{
|
||||
// Acks only ranges
|
||||
buf[8 + numRanges*2 + 1] = SSU2_MAX_NUM_ACNT; // Acks 255
|
||||
numAcks -= SSU2_MAX_NUM_ACNT;
|
||||
numRanges++;
|
||||
numPackets += SSU2_MAX_NUM_ACNT;
|
||||
buf[8 + numRanges*2] = 0; // NACKs 0
|
||||
if (numRanges >= maxNumRanges || numPackets >= SSU2_MAX_NUM_ACK_PACKETS) break;
|
||||
}
|
||||
if (numAcks > SSU2_MAX_NUM_ACNT) numAcks = SSU2_MAX_NUM_ACNT;
|
||||
buf[8 + numRanges*2 + 1] = (uint8_t)numAcks; // Acks
|
||||
numPackets += numAcks;
|
||||
numRanges++;
|
||||
}
|
||||
if (it == m_OutOfSequencePackets.rend () &&
|
||||
numRanges < maxNumRanges && numPackets < SSU2_MAX_NUM_ACK_PACKETS)
|
||||
{
|
||||
// add range between out-of-sequence and received
|
||||
int nacks = *m_OutOfSequencePackets.begin () - m_ReceivePacketNum - 1;
|
||||
if (nacks > 0)
|
||||
{
|
||||
if (nacks > SSU2_MAX_NUM_ACNT) nacks = SSU2_MAX_NUM_ACNT;
|
||||
buf[8 + numRanges*2] = nacks;
|
||||
buf[8 + numRanges*2 + 1] = std::min ((int)m_ReceivePacketNum + 1, SSU2_MAX_NUM_ACNT);
|
||||
numRanges++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf[7] = (uint8_t)acnt; // acnt
|
||||
htobe16buf (buf + 1, 5 + m_NumRanges*2);
|
||||
return 8 + m_NumRanges*2;
|
||||
htobe16buf (buf + 1, 5 + numRanges*2);
|
||||
return 8 + numRanges*2;
|
||||
}
|
||||
|
||||
size_t SSU2Session::CreatePaddingBlock (uint8_t * buf, size_t len, size_t minSize)
|
||||
@@ -2990,17 +2961,11 @@ namespace transport
|
||||
}
|
||||
m_OutOfSequencePackets.erase (m_OutOfSequencePackets.begin (), it);
|
||||
}
|
||||
m_NumRanges = 0; // recalculate ranges when create next Ack
|
||||
}
|
||||
m_ReceivePacketNum = packetNum;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_NumRanges && (m_OutOfSequencePackets.empty () ||
|
||||
packetNum != (*m_OutOfSequencePackets.rbegin ()) + 1))
|
||||
m_NumRanges = 0; // reset ranges if received packet is not next
|
||||
m_OutOfSequencePackets.insert (packetNum);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3149,10 +3114,5 @@ namespace transport
|
||||
else if (!sent && !m_SentPackets.empty ()) // if only acks received, nothing sent and we still have something to resend
|
||||
Resend (i2p::util::GetMillisecondsSinceEpoch ()); // than right time to resend
|
||||
}
|
||||
|
||||
i2p::data::RouterInfo::SupportedTransports SSU2Session::GetTransportType () const
|
||||
{
|
||||
return m_RemoteEndpoint.address ().is_v4 () ? i2p::data::RouterInfo::eSSU2V4 : i2p::data::RouterInfo::eSSU2V6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2022-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2022-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -267,7 +267,6 @@ namespace transport
|
||||
size_t Resend (uint64_t ts); // return number of resent packets
|
||||
uint64_t GetLastResendTime () const { return m_LastResendTime; };
|
||||
bool IsEstablished () const override { return m_State == eSSU2SessionStateEstablished; };
|
||||
i2p::data::RouterInfo::SupportedTransports GetTransportType () const override;
|
||||
uint64_t GetConnID () const { return m_SourceConnID; };
|
||||
SSU2SessionState GetState () const { return m_State; };
|
||||
void SetState (SSU2SessionState state) { m_State = state; };
|
||||
@@ -397,8 +396,6 @@ namespace transport
|
||||
std::unique_ptr<i2p::data::IdentHash> m_PathChallenge;
|
||||
std::unordered_map<uint32_t, uint32_t> m_ReceivedI2NPMsgIDs; // msgID -> timestamp in seconds
|
||||
uint64_t m_LastResendTime, m_LastResendAttemptTime; // in milliseconds
|
||||
int m_NumRanges;
|
||||
uint8_t m_Ranges[SSU2_MAX_NUM_ACK_RANGES*2]; // ranges sent with previous Ack if any
|
||||
};
|
||||
|
||||
inline uint64_t CreateHeaderMask (const uint8_t * kh, const uint8_t * nonce)
|
||||
|
||||
@@ -72,15 +72,15 @@ namespace stream
|
||||
m_TunnelsChangeSequenceNumber (0), m_LastReceivedSequenceNumber (-1), m_PreviousReceivedSequenceNumber (-1),
|
||||
m_LastConfirmedReceivedSequenceNumber (0), // for limit inbound speed
|
||||
m_Status (eStreamStatusNew), m_IsIncoming (false), m_IsAckSendScheduled (false), m_IsNAcked (false), m_IsFirstACK (false),
|
||||
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsWinDropped (false), m_IsClientChoked (false),
|
||||
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsWinDropped (false),
|
||||
m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false), m_DoubleWinIncCounter (false), m_LocalDestination (local),
|
||||
m_RemoteLeaseSet (remote), m_ReceiveTimer (m_Service), m_SendTimer (m_Service), m_ResendTimer (m_Service),
|
||||
m_AckSendTimer (m_Service), m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (port),
|
||||
m_RTT (INITIAL_RTT), m_SlowRTT (INITIAL_RTT), m_SlowRTT2 (INITIAL_RTT), m_WindowSize (INITIAL_WINDOW_SIZE), m_LastWindowDropSize (0),
|
||||
m_WindowDropTargetSize (0), m_WindowIncCounter (0), m_RTO (INITIAL_RTO),
|
||||
m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()), m_PrevRTTSample (INITIAL_RTT), m_WindowSizeTail (0),
|
||||
m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()), m_PrevRTTSample (INITIAL_RTT),
|
||||
m_Jitter (0), m_MinPacingTime (0),
|
||||
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()), m_RemoteLeaseChangeTime (0),
|
||||
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_RemoteLeaseChangeTime (0),
|
||||
m_LastACKSendTime (0), m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed
|
||||
m_NumResendAttempts (0), m_NumPacketsToSend (0), m_MTU (STREAMING_MTU)
|
||||
{
|
||||
@@ -99,15 +99,15 @@ namespace stream
|
||||
m_Service (service), m_SendStreamID (0), m_SequenceNumber (0), m_DropWindowDelaySequenceNumber (0),
|
||||
m_TunnelsChangeSequenceNumber (0), m_LastReceivedSequenceNumber (-1), m_PreviousReceivedSequenceNumber (-1),
|
||||
m_LastConfirmedReceivedSequenceNumber (0), // for limit inbound speed
|
||||
m_Status (eStreamStatusNew), m_IsIncoming (true), m_IsAckSendScheduled (false), m_IsNAcked (false), m_IsFirstACK (false),
|
||||
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsWinDropped (false), m_IsClientChoked (false),
|
||||
m_Status (eStreamStatusNew), m_IsIncoming (true), m_IsAckSendScheduled (false), m_IsNAcked (false), m_IsFirstACK (false),
|
||||
m_IsResendNeeded (false), m_IsFirstRttSample (false), m_IsSendTime (true), m_IsWinDropped (false),
|
||||
m_IsTimeOutResend (false), m_IsImmediateAckRequested (false), m_IsRemoteLeaseChangeInProgress (false), m_DoubleWinIncCounter (false), m_LocalDestination (local),
|
||||
m_ReceiveTimer (m_Service), m_SendTimer (m_Service), m_ResendTimer (m_Service), m_AckSendTimer (m_Service),
|
||||
m_NumSentBytes (0), m_NumReceivedBytes (0), m_Port (0), m_RTT (INITIAL_RTT), m_SlowRTT (INITIAL_RTT), m_SlowRTT2 (INITIAL_RTT),
|
||||
m_WindowSize (INITIAL_WINDOW_SIZE), m_LastWindowDropSize (0), m_WindowDropTargetSize (0), m_WindowIncCounter (0),
|
||||
m_RTO (INITIAL_RTO), m_AckDelay (local.GetOwner ()->GetStreamingAckDelay ()),
|
||||
m_PrevRTTSample (INITIAL_RTT), m_WindowSizeTail (0), m_Jitter (0), m_MinPacingTime (0),
|
||||
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_LastACKRecieveTime (0), m_ACKRecieveInterval (local.GetOwner ()->GetStreamingAckDelay ()), m_RemoteLeaseChangeTime (0),
|
||||
m_PrevRTTSample (INITIAL_RTT), m_Jitter (0), m_MinPacingTime (0),
|
||||
m_PacingTime (INITIAL_PACING_TIME), m_PacingTimeRem (0), m_LastSendTime (0), m_RemoteLeaseChangeTime (0),
|
||||
m_LastACKSendTime (0), m_PacketACKInterval (1), m_PacketACKIntervalRem (0), // for limit inbound speed
|
||||
m_NumResendAttempts (0), m_NumPacketsToSend (0), m_MTU (STREAMING_MTU)
|
||||
{
|
||||
@@ -364,14 +364,12 @@ namespace stream
|
||||
}
|
||||
if (delayRequested >= DELAY_CHOKING)
|
||||
{
|
||||
if (!m_IsClientChoked)
|
||||
if (!m_IsWinDropped)
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: Client choked, set min. window size");
|
||||
m_WindowDropTargetSize = MIN_WINDOW_SIZE;
|
||||
m_LastWindowDropSize = 0;
|
||||
m_WindowIncCounter = 0;
|
||||
m_IsClientChoked = true;
|
||||
m_IsWinDropped = false;
|
||||
m_IsWinDropped = true; // don't drop window twice
|
||||
m_DropWindowDelaySequenceNumber = m_SequenceNumber;
|
||||
UpdatePacingTime ();
|
||||
}
|
||||
@@ -539,21 +537,12 @@ namespace stream
|
||||
m_SentPackets.erase (it++);
|
||||
m_LocalDestination.DeletePacket (sentPacket);
|
||||
acknowledged = true;
|
||||
if (m_WindowIncCounter < MAX_WINDOW_SIZE && !m_IsFirstACK && !m_IsWinDropped)
|
||||
if (m_WindowSize < MAX_WINDOW_SIZE && !m_IsFirstACK)
|
||||
incCounter++;
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
if (m_LastACKRecieveTime)
|
||||
{
|
||||
uint64_t interval = ts - m_LastACKRecieveTime;
|
||||
if (m_ACKRecieveInterval)
|
||||
m_ACKRecieveInterval = (m_ACKRecieveInterval + interval) / 2;
|
||||
else
|
||||
m_ACKRecieveInterval = interval;
|
||||
}
|
||||
m_LastACKRecieveTime = ts;
|
||||
if (rttSample != INT_MAX)
|
||||
{
|
||||
if (m_IsFirstRttSample && !m_IsFirstACK)
|
||||
@@ -599,33 +588,36 @@ namespace stream
|
||||
m_WindowIncCounter = m_WindowIncCounter + incCounter;
|
||||
//
|
||||
// delay-based CC
|
||||
if ((m_SlowRTT2 > m_SlowRTT + m_Jitter && rttSample > m_SlowRTT2 && rttSample > m_PrevRTTSample) && !m_IsWinDropped && !m_IsClientChoked) // Drop window if RTT grows too fast, late detection
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: Congestion detected, reduce window size");
|
||||
if ((m_SlowRTT2 > m_SlowRTT + m_Jitter && rttSample > m_SlowRTT2 && rttSample > m_PrevRTTSample) && !m_IsWinDropped) // Drop window if RTT grows too fast, late detection
|
||||
ProcessWindowDrop ();
|
||||
}
|
||||
UpdatePacingTime ();
|
||||
m_PrevRTTSample = rttSample;
|
||||
|
||||
bool wasInitial = m_RTO == INITIAL_RTO;
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.3 + m_Jitter + m_ACKRecieveInterval)); // TODO: implement it better
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.3 + m_Jitter)); // TODO: implement it better
|
||||
|
||||
if (wasInitial)
|
||||
ScheduleResend ();
|
||||
}
|
||||
if (m_IsClientChoked && ackThrough > m_DropWindowDelaySequenceNumber)
|
||||
{
|
||||
m_IsClientChoked = false;
|
||||
}
|
||||
if (m_IsWinDropped && ackThrough > m_DropWindowDelaySequenceNumber)
|
||||
{
|
||||
m_IsFirstRttSample = true;
|
||||
m_IsWinDropped = false;
|
||||
}
|
||||
if (m_WindowDropTargetSize && int(m_SentPackets.size ()) <= m_WindowDropTargetSize)
|
||||
if (m_WindowDropTargetSize && m_WindowSize <= m_WindowDropTargetSize)
|
||||
{
|
||||
m_WindowSize = m_WindowDropTargetSize;
|
||||
m_WindowDropTargetSize = 0;
|
||||
m_DropWindowDelaySequenceNumber = m_SequenceNumber;
|
||||
}
|
||||
if (acknowledged && m_WindowDropTargetSize && m_WindowSize > m_WindowDropTargetSize)
|
||||
{
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.5 + m_Jitter)); // we assume that the next rtt sample may be much larger than the current
|
||||
m_IsResendNeeded = true;
|
||||
m_WindowSize = m_SentPackets.size () + 1; // if there are no packets to resend, just send one regular packet
|
||||
if (m_WindowSize < MIN_WINDOW_SIZE) m_WindowSize = MIN_WINDOW_SIZE;
|
||||
if (m_WindowSize > MAX_WINDOW_SIZE) m_WindowSize = MAX_WINDOW_SIZE;
|
||||
m_WindowIncCounter = 0;
|
||||
UpdatePacingTime ();
|
||||
}
|
||||
if (acknowledged || m_IsNAcked)
|
||||
{
|
||||
@@ -634,14 +626,12 @@ namespace stream
|
||||
if (m_SendBuffer.IsEmpty () && m_SentPackets.size () > 0) // tail loss
|
||||
{
|
||||
m_IsResendNeeded = true;
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.5 + m_Jitter + m_ACKRecieveInterval)); // to prevent spurious retransmit
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.5 + m_Jitter)); // to prevent spurious retransmit
|
||||
}
|
||||
if (m_SentPackets.empty () && m_SendBuffer.IsEmpty ())
|
||||
{
|
||||
m_ResendTimer.cancel ();
|
||||
m_SendTimer.cancel ();
|
||||
m_LastACKRecieveTime = 0;
|
||||
m_ACKRecieveInterval = m_AckDelay;
|
||||
}
|
||||
if (acknowledged && m_IsFirstACK)
|
||||
{
|
||||
@@ -968,7 +958,7 @@ namespace stream
|
||||
if (choking || requestImmediateAck)
|
||||
{
|
||||
htobe16buf (packet + size, 2); // 2 bytes delay interval
|
||||
htobe16buf (packet + size + 2, choking ? DELAY_CHOKING : 0); // set choking or immediate ack interval
|
||||
htobe16buf (packet + size + 2, choking ? DELAY_CHOKING : 0); // set choking or immediated ack interval
|
||||
size += 2;
|
||||
if (requestImmediateAck) // ack request sent
|
||||
{
|
||||
@@ -1157,6 +1147,7 @@ namespace stream
|
||||
m_CurrentOutboundTunnel = routingPath->outboundTunnel;
|
||||
m_CurrentRemoteLease = routingPath->remoteLease;
|
||||
m_RTT = routingPath->rtt;
|
||||
m_RTO = std::max (MIN_RTO, (int)(m_RTT * 1.3 + m_Jitter)); // TODO: implement it better
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1168,10 +1159,9 @@ namespace stream
|
||||
}
|
||||
if (m_RemoteLeaseChangeTime && m_IsRemoteLeaseChangeInProgress && ts > m_RemoteLeaseChangeTime + INITIAL_RTO)
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: RemoteLease changed, set initial window size");
|
||||
CancelRemoteLeaseChange ();
|
||||
m_CurrentRemoteLease = m_NextRemoteLease;
|
||||
ResetWindowSize ();
|
||||
HalveWindowSize ();
|
||||
}
|
||||
auto currentRemoteLease = m_CurrentRemoteLease;
|
||||
if (!m_IsRemoteLeaseChangeInProgress && m_RemoteLeaseSet && m_CurrentRemoteLease && ts >= m_CurrentRemoteLease->endDate - i2p::data::LEASE_ENDDATE_THRESHOLD)
|
||||
@@ -1206,8 +1196,7 @@ namespace stream
|
||||
}
|
||||
if (freshTunnel)
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: OutboundTunnel changed, set initial window size");
|
||||
ResetWindowSize ();
|
||||
m_RTO = INITIAL_RTO;
|
||||
// m_TunnelsChangeSequenceNumber = m_SequenceNumber; // should be determined more precisely
|
||||
}
|
||||
|
||||
@@ -1297,47 +1286,31 @@ 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_SendBuffer.IsEmpty () && m_PacingTime > m_MinPacingTime)
|
||||
{
|
||||
for (int i = 0; i < m_NumPacketsToSend; i++)
|
||||
{
|
||||
if (m_WindowIncCounter)
|
||||
{
|
||||
if (m_WindowDropTargetSize)
|
||||
{
|
||||
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))
|
||||
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;
|
||||
if (m_WindowDropTargetSize > MAX_WINDOW_SIZE) m_WindowDropTargetSize = MAX_WINDOW_SIZE;
|
||||
m_WindowIncCounter--;
|
||||
}
|
||||
if (m_LastWindowDropSize && (m_LastWindowDropSize >= m_WindowSize))
|
||||
m_WindowSize += 1 - (1 / ((m_LastWindowDropSize + PREV_SPEED_KEEP_TIME_COEFF) / m_WindowSize)); // some magic here
|
||||
else if (m_LastWindowDropSize && (m_LastWindowDropSize < m_WindowSize))
|
||||
m_WindowSize += (m_WindowSize - (m_LastWindowDropSize - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowSize; // some magic here
|
||||
else
|
||||
{
|
||||
if (m_LastWindowDropSize && (m_LastWindowDropSize >= m_WindowSize))
|
||||
m_WindowSize += 1 - (1 / ((m_LastWindowDropSize + PREV_SPEED_KEEP_TIME_COEFF) / m_WindowSize)); // some magic here
|
||||
else if (m_LastWindowDropSize && (m_LastWindowDropSize < m_WindowSize))
|
||||
m_WindowSize += (m_WindowSize - (m_LastWindowDropSize - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowSize; // some magic here
|
||||
else
|
||||
m_WindowSize += (m_WindowSize - (1 - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowSize;
|
||||
if (m_WindowSize > MAX_WINDOW_SIZE) m_WindowSize = MAX_WINDOW_SIZE;
|
||||
m_WindowIncCounter--;
|
||||
}
|
||||
m_WindowSize += (m_WindowSize - (1 - PREV_SPEED_KEEP_TIME_COEFF)) / m_WindowSize;
|
||||
if (m_WindowSize > MAX_WINDOW_SIZE) m_WindowSize = MAX_WINDOW_SIZE;
|
||||
m_WindowIncCounter--;
|
||||
}
|
||||
else
|
||||
break;
|
||||
}
|
||||
UpdatePacingTime ();
|
||||
}
|
||||
else if (m_WindowIncCounter && m_WindowSize == MAX_WINDOW_SIZE && !m_SendBuffer.IsEmpty () && m_PacingTime > m_MinPacingTime)
|
||||
{
|
||||
m_WindowSizeTail = m_WindowSizeTail + m_WindowIncCounter;
|
||||
if (m_WindowSizeTail > MAX_WINDOW_SIZE) m_WindowSizeTail = MAX_WINDOW_SIZE;
|
||||
}
|
||||
if (m_IsNAcked || m_IsResendNeeded || m_IsClientChoked) // resend packets
|
||||
if (m_IsNAcked)
|
||||
ResendPacket ();
|
||||
else if (m_IsResendNeeded) // resend packets
|
||||
ResendPacket ();
|
||||
// delay-based CC
|
||||
else if (m_WindowSize > int(m_SentPackets.size ())) // send packets
|
||||
SendBuffer ();
|
||||
}
|
||||
@@ -1436,11 +1409,8 @@ namespace stream
|
||||
if (m_NumResendAttempts == 1 && m_RTO != INITIAL_RTO)
|
||||
{
|
||||
// loss-based CC
|
||||
if (!m_IsWinDropped && LOSS_BASED_CONTROL_ENABLED && !m_IsClientChoked)
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: Packet loss, reduce window size");
|
||||
if (!m_IsWinDropped && LOSS_BASED_CONTROL_ENABLED)
|
||||
ProcessWindowDrop ();
|
||||
}
|
||||
}
|
||||
else if (m_IsTimeOutResend)
|
||||
{
|
||||
@@ -1453,8 +1423,6 @@ namespace stream
|
||||
m_IsFirstRttSample = true;
|
||||
m_DropWindowDelaySequenceNumber = 0;
|
||||
m_IsFirstACK = true;
|
||||
m_LastACKRecieveTime = 0;
|
||||
m_ACKRecieveInterval = m_AckDelay;
|
||||
UpdatePacingTime ();
|
||||
if (m_RoutingSession) m_RoutingSession->SetSharedRoutingPath (nullptr);
|
||||
if (m_NumResendAttempts & 1)
|
||||
@@ -1475,12 +1443,11 @@ namespace stream
|
||||
SendPackets (packets);
|
||||
m_LastSendTime = ts;
|
||||
m_IsSendTime = false;
|
||||
if (m_IsNAcked || m_IsResendNeeded || m_IsClientChoked) ScheduleSend ();
|
||||
if (m_IsNAcked || m_IsResendNeeded) ScheduleSend ();
|
||||
}
|
||||
else if (!m_IsClientChoked)
|
||||
else
|
||||
SendBuffer ();
|
||||
if (!m_IsNAcked && !m_IsResendNeeded) ScheduleResend ();
|
||||
if (m_IsClientChoked) ScheduleSend ();
|
||||
}
|
||||
|
||||
void Stream::ScheduleAck (int timeout)
|
||||
@@ -1619,8 +1586,7 @@ namespace stream
|
||||
}
|
||||
if (isLeaseChanged && !m_IsRemoteLeaseChangeInProgress)
|
||||
{
|
||||
LogPrint (eLogDebug, "Streaming: RemoteLease changed, set initial window size");
|
||||
ResetWindowSize ();
|
||||
HalveWindowSize ();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1636,10 +1602,7 @@ namespace stream
|
||||
|
||||
void Stream::UpdatePacingTime ()
|
||||
{
|
||||
if (m_WindowDropTargetSize)
|
||||
m_PacingTime = std::round (m_RTT*1000/m_WindowDropTargetSize);
|
||||
else
|
||||
m_PacingTime = std::round (m_RTT*1000/m_WindowSize);
|
||||
m_PacingTime = std::round (m_RTT*1000/m_WindowSize);
|
||||
if (m_MinPacingTime && m_PacingTime < m_MinPacingTime)
|
||||
m_PacingTime = m_MinPacingTime;
|
||||
}
|
||||
@@ -1647,41 +1610,35 @@ 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;
|
||||
}
|
||||
m_LastWindowDropSize = (m_LastWindowDropSize + m_WindowSize) / 2;
|
||||
else
|
||||
m_LastWindowDropSize = m_WindowSize;
|
||||
m_WindowDropTargetSize = m_LastWindowDropSize - (m_LastWindowDropSize / 4); // -25%;
|
||||
if (m_WindowDropTargetSize < MIN_WINDOW_SIZE)
|
||||
m_WindowDropTargetSize = MIN_WINDOW_SIZE;
|
||||
if (m_WindowDropTargetSize < MIN_WINDOW_SIZE + 1)
|
||||
m_WindowDropTargetSize = MIN_WINDOW_SIZE + 1;
|
||||
m_WindowSize = m_SentPackets.size (); // stop sending now
|
||||
if (m_WindowSize < MIN_WINDOW_SIZE) m_WindowSize = MIN_WINDOW_SIZE;
|
||||
m_WindowIncCounter = 0; // disable window growth
|
||||
m_DropWindowDelaySequenceNumber = m_SequenceNumber + int(m_WindowDropTargetSize);
|
||||
m_DropWindowDelaySequenceNumber = m_SequenceNumber;
|
||||
m_IsFirstACK = true; // ignore first RTT sample
|
||||
m_IsWinDropped = true; // don't drop window twice
|
||||
m_WindowSizeTail = 0;
|
||||
UpdatePacingTime ();
|
||||
}
|
||||
|
||||
void Stream::ResetWindowSize ()
|
||||
void Stream::HalveWindowSize ()
|
||||
{
|
||||
m_RTO = INITIAL_RTO;
|
||||
if (!m_IsClientChoked)
|
||||
if (m_WindowSize > INITIAL_WINDOW_SIZE)
|
||||
{
|
||||
if (m_WindowSize > INITIAL_WINDOW_SIZE)
|
||||
{
|
||||
m_WindowDropTargetSize = (float)INITIAL_WINDOW_SIZE;
|
||||
m_IsWinDropped = true;
|
||||
}
|
||||
else
|
||||
m_WindowSize = INITIAL_WINDOW_SIZE;
|
||||
m_WindowDropTargetSize = std::max (m_WindowSize/2, (float)INITIAL_WINDOW_SIZE);
|
||||
m_IsWinDropped = true;
|
||||
}
|
||||
else
|
||||
m_WindowSize = INITIAL_WINDOW_SIZE;
|
||||
m_LastWindowDropSize = 0;
|
||||
m_WindowIncCounter = 0;
|
||||
m_IsFirstRttSample = true;
|
||||
m_IsFirstACK = true;
|
||||
m_WindowSizeTail = 0;
|
||||
UpdatePacingTime ();
|
||||
}
|
||||
|
||||
|
||||
@@ -251,7 +251,7 @@ namespace stream
|
||||
|
||||
void UpdatePacingTime ();
|
||||
void ProcessWindowDrop ();
|
||||
void ResetWindowSize ();
|
||||
void HalveWindowSize ();
|
||||
void CancelRemoteLeaseChange ();
|
||||
|
||||
private:
|
||||
@@ -272,7 +272,6 @@ namespace stream
|
||||
bool m_IsFirstRttSample;
|
||||
bool m_IsSendTime;
|
||||
bool m_IsWinDropped;
|
||||
bool m_IsClientChoked;
|
||||
bool m_IsTimeOutResend;
|
||||
bool m_IsImmediateAckRequested;
|
||||
bool m_IsRemoteLeaseChangeInProgress;
|
||||
@@ -296,10 +295,10 @@ namespace stream
|
||||
SendBufferQueue m_SendBuffer;
|
||||
double m_RTT, m_SlowRTT, m_SlowRTT2;
|
||||
float m_WindowSize, m_LastWindowDropSize, m_WindowDropTargetSize;
|
||||
int m_WindowIncCounter, m_RTO, m_AckDelay, m_PrevRTTSample, m_WindowSizeTail;
|
||||
int m_WindowIncCounter, m_RTO, m_AckDelay, m_PrevRTTSample;
|
||||
double m_Jitter;
|
||||
uint64_t m_MinPacingTime, m_PacingTime, m_PacingTimeRem, // microseconds
|
||||
m_LastSendTime, m_LastACKRecieveTime, m_ACKRecieveInterval, m_RemoteLeaseChangeTime; // milliseconds
|
||||
m_LastSendTime, m_RemoteLeaseChangeTime; // miliseconds
|
||||
uint64_t m_LastACKSendTime, m_PacketACKInterval, m_PacketACKIntervalRem; // for limit inbound speed
|
||||
int m_NumResendAttempts, m_NumPacketsToSend;
|
||||
size_t m_MTU;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2023, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -12,14 +12,10 @@
|
||||
#include <boost/static_assert.hpp>
|
||||
#include <string.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include "Base.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace data
|
||||
{
|
||||
namespace i2p {
|
||||
namespace data {
|
||||
template<size_t sz>
|
||||
class Tag
|
||||
{
|
||||
@@ -74,14 +70,14 @@ namespace data
|
||||
return std::string (str, str + l);
|
||||
}
|
||||
|
||||
size_t FromBase32 (std::string_view s)
|
||||
size_t FromBase32 (const std::string& s)
|
||||
{
|
||||
return i2p::data::Base32ToByteStream (s.data (), s.length (), m_Buf, sz);
|
||||
return i2p::data::Base32ToByteStream (s.c_str (), s.length (), m_Buf, sz);
|
||||
}
|
||||
|
||||
size_t FromBase64 (std::string_view s)
|
||||
size_t FromBase64 (const std::string& s)
|
||||
{
|
||||
return i2p::data::Base64ToByteStream (s.data (), s.length (), m_Buf, sz);
|
||||
return i2p::data::Base64ToByteStream (s.c_str (), s.length (), m_Buf, sz);
|
||||
}
|
||||
|
||||
uint8_t GetBit (int i) const
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -10,8 +10,6 @@
|
||||
#include "I2PEndian.h"
|
||||
#include "Crypto.h"
|
||||
#include "Log.h"
|
||||
#include "Identity.h"
|
||||
#include "RouterInfo.h"
|
||||
#include "RouterContext.h"
|
||||
#include "I2NPProtocol.h"
|
||||
#include "Garlic.h"
|
||||
@@ -43,21 +41,6 @@ namespace tunnel
|
||||
i2p::transport::transports.UpdateTotalTransitTransmittedBytes (TUNNEL_DATA_MSG_SIZE);
|
||||
}
|
||||
|
||||
std::string TransitTunnel::GetNextPeerName () const
|
||||
{
|
||||
return i2p::data::GetIdentHashAbbreviation (GetNextIdentHash ());
|
||||
}
|
||||
|
||||
void TransitTunnel::SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg)
|
||||
{
|
||||
LogPrint (eLogError, "TransitTunnel: We are not a gateway for ", GetTunnelID ());
|
||||
}
|
||||
|
||||
void TransitTunnel::HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg)
|
||||
{
|
||||
LogPrint (eLogError, "TransitTunnel: Incoming tunnel message is not supported ", GetTunnelID ());
|
||||
}
|
||||
|
||||
TransitTunnelParticipant::~TransitTunnelParticipant ()
|
||||
{
|
||||
}
|
||||
@@ -79,92 +62,44 @@ namespace tunnel
|
||||
auto num = m_TunnelDataMsgs.size ();
|
||||
if (num > 1)
|
||||
LogPrint (eLogDebug, "TransitTunnel: ", GetTunnelID (), "->", GetNextTunnelID (), " ", num);
|
||||
if (!m_Sender) m_Sender = std::make_unique<TunnelTransportSender>();
|
||||
m_Sender->SendMessagesTo (GetNextIdentHash (), m_TunnelDataMsgs); // send and clear
|
||||
i2p::transport::transports.SendMessages (GetNextIdentHash (), m_TunnelDataMsgs); // send and clear
|
||||
}
|
||||
}
|
||||
|
||||
std::string TransitTunnelParticipant::GetNextPeerName () const
|
||||
void TransitTunnel::SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg)
|
||||
{
|
||||
if (m_Sender)
|
||||
{
|
||||
auto transport = m_Sender->GetCurrentTransport ();
|
||||
if (transport)
|
||||
return TransitTunnel::GetNextPeerName () + "-" +
|
||||
i2p::data::RouterInfo::GetTransportName (transport->GetTransportType ());
|
||||
}
|
||||
return TransitTunnel::GetNextPeerName ();
|
||||
}
|
||||
|
||||
LogPrint (eLogError, "TransitTunnel: We are not a gateway for ", GetTunnelID ());
|
||||
}
|
||||
|
||||
void TransitTunnel::HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg)
|
||||
{
|
||||
LogPrint (eLogError, "TransitTunnel: Incoming tunnel message is not supported ", GetTunnelID ());
|
||||
}
|
||||
|
||||
void TransitTunnelGateway::SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg)
|
||||
{
|
||||
TunnelMessageBlock block;
|
||||
block.deliveryType = eDeliveryTypeLocal;
|
||||
block.data = msg;
|
||||
std::lock_guard<std::mutex> l(m_SendMutex);
|
||||
std::unique_lock<std::mutex> l(m_SendMutex);
|
||||
m_Gateway.PutTunnelDataMsg (block);
|
||||
}
|
||||
|
||||
void TransitTunnelGateway::FlushTunnelDataMsgs ()
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_SendMutex);
|
||||
std::unique_lock<std::mutex> l(m_SendMutex);
|
||||
m_Gateway.SendBuffer ();
|
||||
}
|
||||
|
||||
std::string TransitTunnelGateway::GetNextPeerName () const
|
||||
{
|
||||
const auto& sender = m_Gateway.GetSender ();
|
||||
if (sender)
|
||||
{
|
||||
auto transport = sender->GetCurrentTransport ();
|
||||
if (transport)
|
||||
return TransitTunnel::GetNextPeerName () + "-" +
|
||||
i2p::data::RouterInfo::GetTransportName (transport->GetTransportType ());
|
||||
}
|
||||
return TransitTunnel::GetNextPeerName ();
|
||||
}
|
||||
|
||||
void TransitTunnelEndpoint::HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg)
|
||||
{
|
||||
auto newMsg = CreateEmptyTunnelDataMsg (true);
|
||||
EncryptTunnelMsg (tunnelMsg, newMsg);
|
||||
|
||||
LogPrint (eLogDebug, "TransitTunnel: handle msg for endpoint ", GetTunnelID ());
|
||||
std::lock_guard<std::mutex> l(m_HandleMutex);
|
||||
m_Endpoint.HandleDecryptedTunnelDataMsg (newMsg);
|
||||
}
|
||||
|
||||
void TransitTunnelEndpoint::FlushTunnelDataMsgs ()
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_HandleMutex);
|
||||
m_Endpoint.FlushI2NPMsgs ();
|
||||
}
|
||||
|
||||
void TransitTunnelEndpoint::Cleanup ()
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_HandleMutex);
|
||||
m_Endpoint.Cleanup ();
|
||||
}
|
||||
|
||||
std::string TransitTunnelEndpoint::GetNextPeerName () const
|
||||
{
|
||||
auto hash = m_Endpoint.GetCurrentHash ();
|
||||
if (hash)
|
||||
{
|
||||
const auto& sender = m_Endpoint.GetSender ();
|
||||
if (sender)
|
||||
{
|
||||
auto transport = sender->GetCurrentTransport ();
|
||||
if (transport)
|
||||
return i2p::data::GetIdentHashAbbreviation (*hash) + "-" +
|
||||
i2p::data::RouterInfo::GetTransportName (transport->GetTransportType ());
|
||||
else
|
||||
return i2p::data::GetIdentHashAbbreviation (*hash);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
std::shared_ptr<TransitTunnel> CreateTransitTunnel (uint32_t receiveTunnelID,
|
||||
const i2p::data::IdentHash& nextIdent, uint32_t nextTunnelID,
|
||||
const i2p::crypto::AESKey& layerKey, const i2p::crypto::AESKey& ivKey,
|
||||
@@ -188,7 +123,7 @@ namespace tunnel
|
||||
}
|
||||
|
||||
TransitTunnels::TransitTunnels ():
|
||||
m_IsRunning (false), m_Rng(i2p::util::GetMonotonicMicroseconds ()%1000000LL)
|
||||
m_IsRunning (false)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -328,44 +263,19 @@ namespace tunnel
|
||||
// check if we accept this tunnel
|
||||
std::shared_ptr<i2p::tunnel::TransitTunnel> transitTunnel;
|
||||
uint8_t retCode = 0;
|
||||
if (i2p::context.AcceptsTunnels ())
|
||||
{
|
||||
auto congestionLevel = i2p::context.GetCongestionLevel (false);
|
||||
if (congestionLevel < CONGESTION_LEVEL_FULL)
|
||||
{
|
||||
if (congestionLevel >= CONGESTION_LEVEL_MEDIUM)
|
||||
{
|
||||
// random reject depending on congestion level
|
||||
int level = m_Rng () % (CONGESTION_LEVEL_FULL - CONGESTION_LEVEL_MEDIUM) + CONGESTION_LEVEL_MEDIUM;
|
||||
if (congestionLevel > level)
|
||||
retCode = 30;
|
||||
}
|
||||
}
|
||||
else
|
||||
retCode = 30;
|
||||
}
|
||||
else
|
||||
if (!i2p::context.AcceptsTunnels () || i2p::context.GetCongestionLevel (false) >= CONGESTION_LEVEL_FULL)
|
||||
retCode = 30;
|
||||
|
||||
if (!retCode)
|
||||
{
|
||||
i2p::data::IdentHash nextIdent(clearText + SHORT_REQUEST_RECORD_NEXT_IDENT_OFFSET);
|
||||
bool isEndpoint = clearText[SHORT_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_ENDPOINT_FLAG;
|
||||
if (isEndpoint || !i2p::data::IsRouterDuplicated (nextIdent))
|
||||
{
|
||||
// create new transit tunnel
|
||||
transitTunnel = CreateTransitTunnel (
|
||||
bufbe32toh (clearText + SHORT_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
|
||||
nextIdent,
|
||||
bufbe32toh (clearText + SHORT_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
layerKey, ivKey,
|
||||
clearText[SHORT_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_GATEWAY_FLAG,
|
||||
isEndpoint);
|
||||
if (!AddTransitTunnel (transitTunnel))
|
||||
retCode = 30;
|
||||
}
|
||||
else
|
||||
// decline tunnel going to duplicated router
|
||||
// create new transit tunnel
|
||||
transitTunnel = i2p::tunnel::CreateTransitTunnel (
|
||||
bufbe32toh (clearText + SHORT_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
|
||||
clearText + SHORT_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
bufbe32toh (clearText + SHORT_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
layerKey, ivKey,
|
||||
clearText[SHORT_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_GATEWAY_FLAG,
|
||||
clearText[SHORT_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_ENDPOINT_FLAG);
|
||||
if (!AddTransitTunnel (transitTunnel))
|
||||
retCode = 30;
|
||||
}
|
||||
|
||||
@@ -477,7 +387,7 @@ namespace tunnel
|
||||
if (congestionLevel < CONGESTION_LEVEL_FULL)
|
||||
{
|
||||
// random reject depending on congestion level
|
||||
int level = m_Rng () % (CONGESTION_LEVEL_FULL - CONGESTION_LEVEL_MEDIUM) + CONGESTION_LEVEL_MEDIUM;
|
||||
int level = i2p::tunnel::tunnels.GetRng ()() % (CONGESTION_LEVEL_FULL - CONGESTION_LEVEL_MEDIUM) + CONGESTION_LEVEL_MEDIUM;
|
||||
if (congestionLevel > level)
|
||||
accept = false;
|
||||
}
|
||||
@@ -485,32 +395,23 @@ namespace tunnel
|
||||
accept = false;
|
||||
}
|
||||
}
|
||||
|
||||
// replace record to reply
|
||||
if (accept)
|
||||
{
|
||||
i2p::data::IdentHash nextIdent(clearText + ECIES_BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET);
|
||||
bool isEndpoint = clearText[ECIES_BUILD_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_ENDPOINT_FLAG;
|
||||
if (isEndpoint || !i2p::data::IsRouterDuplicated (nextIdent))
|
||||
{
|
||||
auto transitTunnel = CreateTransitTunnel (
|
||||
bufbe32toh (clearText + ECIES_BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
|
||||
nextIdent,
|
||||
bufbe32toh (clearText + ECIES_BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
clearText + ECIES_BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET,
|
||||
clearText + ECIES_BUILD_REQUEST_RECORD_IV_KEY_OFFSET,
|
||||
clearText[ECIES_BUILD_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_GATEWAY_FLAG,
|
||||
isEndpoint);
|
||||
if (!AddTransitTunnel (transitTunnel))
|
||||
retCode = 30;
|
||||
}
|
||||
else
|
||||
// decline tunnel going to duplicated router
|
||||
auto transitTunnel = i2p::tunnel::CreateTransitTunnel (
|
||||
bufbe32toh (clearText + ECIES_BUILD_REQUEST_RECORD_RECEIVE_TUNNEL_OFFSET),
|
||||
clearText + ECIES_BUILD_REQUEST_RECORD_NEXT_IDENT_OFFSET,
|
||||
bufbe32toh (clearText + ECIES_BUILD_REQUEST_RECORD_NEXT_TUNNEL_OFFSET),
|
||||
clearText + ECIES_BUILD_REQUEST_RECORD_LAYER_KEY_OFFSET,
|
||||
clearText + ECIES_BUILD_REQUEST_RECORD_IV_KEY_OFFSET,
|
||||
clearText[ECIES_BUILD_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_GATEWAY_FLAG,
|
||||
clearText[ECIES_BUILD_REQUEST_RECORD_FLAG_OFFSET] & TUNNEL_BUILD_RECORD_ENDPOINT_FLAG);
|
||||
if (!AddTransitTunnel (transitTunnel))
|
||||
retCode = 30;
|
||||
}
|
||||
else
|
||||
retCode = 30; // always reject with bandwidth reason (30)
|
||||
|
||||
// replace record to reply
|
||||
memset (record + ECIES_BUILD_RESPONSE_RECORD_OPTIONS_OFFSET, 0, 2); // no options
|
||||
record[ECIES_BUILD_RESPONSE_RECORD_RET_OFFSET] = retCode;
|
||||
// encrypt reply
|
||||
@@ -533,7 +434,8 @@ namespace tunnel
|
||||
else
|
||||
{
|
||||
encryption.SetKey (clearText + ECIES_BUILD_REQUEST_RECORD_REPLY_KEY_OFFSET);
|
||||
encryption.Encrypt(reply, TUNNEL_BUILD_RECORD_SIZE, clearText + ECIES_BUILD_REQUEST_RECORD_REPLY_IV_OFFSET, reply);
|
||||
encryption.SetIV (clearText + ECIES_BUILD_REQUEST_RECORD_REPLY_IV_OFFSET);
|
||||
encryption.Encrypt(reply, TUNNEL_BUILD_RECORD_SIZE, reply);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -33,13 +33,11 @@ namespace tunnel
|
||||
const i2p::crypto::AESKey& layerKey, const i2p::crypto::AESKey& ivKey);
|
||||
|
||||
virtual size_t GetNumTransmittedBytes () const { return 0; };
|
||||
virtual std::string GetNextPeerName () const;
|
||||
|
||||
// implements TunnelBase
|
||||
void SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg) override;
|
||||
void HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg) override;
|
||||
void EncryptTunnelMsg (std::shared_ptr<const I2NPMessage> in, std::shared_ptr<I2NPMessage> out) override;
|
||||
|
||||
private:
|
||||
|
||||
i2p::crypto::AESKey m_LayerKey, m_IVKey;
|
||||
@@ -58,7 +56,6 @@ namespace tunnel
|
||||
~TransitTunnelParticipant ();
|
||||
|
||||
size_t GetNumTransmittedBytes () const override { return m_NumTransmittedBytes; };
|
||||
std::string GetNextPeerName () const override;
|
||||
void HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg) override;
|
||||
void FlushTunnelDataMsgs () override;
|
||||
|
||||
@@ -66,7 +63,6 @@ namespace tunnel
|
||||
|
||||
size_t m_NumTransmittedBytes;
|
||||
std::list<std::shared_ptr<i2p::I2NPMessage> > m_TunnelDataMsgs;
|
||||
std::unique_ptr<TunnelTransportSender> m_Sender;
|
||||
};
|
||||
|
||||
class TransitTunnelGateway: public TransitTunnel
|
||||
@@ -82,8 +78,7 @@ namespace tunnel
|
||||
void SendTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage> msg) override;
|
||||
void FlushTunnelDataMsgs () override;
|
||||
size_t GetNumTransmittedBytes () const override { return m_Gateway.GetNumSentBytes (); };
|
||||
std::string GetNextPeerName () const override;
|
||||
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_SendMutex;
|
||||
@@ -100,16 +95,13 @@ namespace tunnel
|
||||
TransitTunnel (receiveTunnelID, nextIdent, nextTunnelID, layerKey, ivKey),
|
||||
m_Endpoint (false) {}; // transit endpoint is always outbound
|
||||
|
||||
void Cleanup () override;
|
||||
|
||||
void Cleanup () override { m_Endpoint.Cleanup (); }
|
||||
|
||||
void HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg) override;
|
||||
void FlushTunnelDataMsgs () override;
|
||||
size_t GetNumTransmittedBytes () const override { return m_Endpoint.GetNumReceivedBytes (); }
|
||||
std::string GetNextPeerName () const override;
|
||||
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_HandleMutex;
|
||||
TunnelEndpoint m_Endpoint;
|
||||
};
|
||||
|
||||
@@ -152,7 +144,6 @@ namespace tunnel
|
||||
std::unique_ptr<std::thread> m_Thread;
|
||||
std::list<std::shared_ptr<TransitTunnel> > m_TransitTunnels;
|
||||
i2p::util::Queue<std::shared_ptr<I2NPMessage> > m_TunnelBuildMsgQueue;
|
||||
std::mt19937 m_Rng;
|
||||
|
||||
public:
|
||||
|
||||
|
||||
@@ -151,7 +151,6 @@ namespace transport
|
||||
};
|
||||
virtual void SendI2NPMessages (std::list<std::shared_ptr<I2NPMessage> >& msgs) = 0;
|
||||
virtual bool IsEstablished () const = 0;
|
||||
virtual i2p::data::RouterInfo::SupportedTransports GetTransportType () const = 0;
|
||||
|
||||
private:
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -55,13 +55,6 @@ namespace transport
|
||||
m_Thread->join ();
|
||||
m_Thread = nullptr;
|
||||
}
|
||||
if (!m_Queue.empty ())
|
||||
{
|
||||
// clean up queue
|
||||
std::queue<std::shared_ptr<Keys> > tmp;
|
||||
std::swap (m_Queue, tmp);
|
||||
}
|
||||
m_KeysPool.CleanUpMt ();
|
||||
}
|
||||
|
||||
template<typename Keys>
|
||||
@@ -160,8 +153,7 @@ namespace transport
|
||||
m_TotalSentBytes (0), m_TotalReceivedBytes (0), m_TotalTransitTransmittedBytes (0),
|
||||
m_InBandwidth (0), m_OutBandwidth (0), m_TransitBandwidth (0),
|
||||
m_InBandwidth15s (0), m_OutBandwidth15s (0), m_TransitBandwidth15s (0),
|
||||
m_InBandwidth5m (0), m_OutBandwidth5m (0), m_TransitBandwidth5m (0),
|
||||
m_Rng(i2p::util::GetMonotonicMicroseconds () % 1000000LL)
|
||||
m_InBandwidth5m (0), m_OutBandwidth5m (0), m_TransitBandwidth5m (0)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -339,7 +331,7 @@ namespace transport
|
||||
|
||||
if (m_IsNAT)
|
||||
{
|
||||
m_PeerTestTimer->expires_from_now (boost::posix_time::seconds(PEER_TEST_INTERVAL + m_Rng() % PEER_TEST_INTERVAL_VARIANCE));
|
||||
m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
|
||||
m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
@@ -462,6 +454,13 @@ namespace transport
|
||||
return {}; // invalid future
|
||||
}
|
||||
|
||||
std::future<std::shared_ptr<TransportSession> > Transports::SendMessages (const i2p::data::IdentHash& ident, std::list<std::shared_ptr<i2p::I2NPMessage> >& msgs)
|
||||
{
|
||||
std::list<std::shared_ptr<i2p::I2NPMessage> > msgs1;
|
||||
msgs.swap (msgs1);
|
||||
return SendMessages (ident, std::move (msgs1));
|
||||
}
|
||||
|
||||
std::future<std::shared_ptr<TransportSession> > Transports::SendMessages (const i2p::data::IdentHash& ident, std::list<std::shared_ptr<i2p::I2NPMessage> >&& msgs)
|
||||
{
|
||||
return boost::asio::post (*m_Service, boost::asio::use_future ([this, ident, msgs = std::move(msgs)] () mutable
|
||||
@@ -561,14 +560,7 @@ namespace transport
|
||||
bool Transports::ConnectToPeer (const i2p::data::IdentHash& ident, std::shared_ptr<Peer> peer)
|
||||
{
|
||||
if (!peer->router) // reconnect
|
||||
{
|
||||
auto r = netdb.FindRouter (ident); // try to get new one from netdb
|
||||
if (r)
|
||||
{
|
||||
peer->SetRouter (r);
|
||||
r->CancelBufferToDelete ();
|
||||
}
|
||||
}
|
||||
peer->SetRouter (netdb.FindRouter (ident)); // try to get new one from netdb
|
||||
if (peer->router) // we have RI already
|
||||
{
|
||||
if (peer->priority.empty ())
|
||||
@@ -655,7 +647,7 @@ namespace transport
|
||||
return true;
|
||||
}
|
||||
|
||||
void Transports::SetPriority (std::shared_ptr<Peer> peer)
|
||||
void Transports::SetPriority (std::shared_ptr<Peer> peer) const
|
||||
{
|
||||
static const std::vector<i2p::data::RouterInfo::SupportedTransports>
|
||||
ntcp2Priority =
|
||||
@@ -681,7 +673,7 @@ namespace transport
|
||||
peer->numAttempts = 0;
|
||||
peer->priority.clear ();
|
||||
bool isReal = peer->router->GetProfile ()->IsReal ();
|
||||
bool ssu2 = isReal ? (m_Rng () & 1) : false; // try NTCP2 if router is not confirmed real
|
||||
bool ssu2 = isReal ? (rand () & 1) : false; // try NTCP2 if router is not confirmed real
|
||||
const auto& priority = ssu2 ? ssu2Priority : ntcp2Priority;
|
||||
if (directTransports)
|
||||
{
|
||||
@@ -709,8 +701,7 @@ namespace transport
|
||||
// try recently connected SSU2 if any
|
||||
auto supportedTransports = context.GetRouterInfo ().GetCompatibleTransports (false) &
|
||||
peer->router->GetCompatibleTransports (false);
|
||||
if ((supportedTransports & (i2p::data::RouterInfo::eSSU2V4 | i2p::data::RouterInfo::eSSU2V6)) &&
|
||||
peer->router->HasProfile ())
|
||||
if (supportedTransports & (i2p::data::RouterInfo::eSSU2V4 | i2p::data::RouterInfo::eSSU2V6))
|
||||
{
|
||||
auto ep = peer->router->GetProfile ()->GetLastEndpoint ();
|
||||
if (!ep.address ().is_unspecified () && ep.port ())
|
||||
@@ -800,7 +791,7 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
testDelay += PEER_TEST_DELAY_INTERVAL + m_Rng() % PEER_TEST_DELAY_INTERVAL_VARIANCE;
|
||||
testDelay += PEER_TEST_DELAY_INTERVAL + rand() % PEER_TEST_DELAY_INTERVAL_VARIANCE;
|
||||
if (m_Service)
|
||||
{
|
||||
auto delayTimer = std::make_shared<boost::asio::deadline_timer>(*m_Service);
|
||||
@@ -838,7 +829,7 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
testDelay += PEER_TEST_DELAY_INTERVAL + m_Rng() % PEER_TEST_DELAY_INTERVAL_VARIANCE;
|
||||
testDelay += PEER_TEST_DELAY_INTERVAL + rand() % PEER_TEST_DELAY_INTERVAL_VARIANCE;
|
||||
if (m_Service)
|
||||
{
|
||||
auto delayTimer = std::make_shared<boost::asio::deadline_timer>(*m_Service);
|
||||
@@ -895,11 +886,7 @@ namespace transport
|
||||
auto transport = peer->priority[peer->numAttempts-1];
|
||||
if (transport == i2p::data::RouterInfo::eNTCP2V4 ||
|
||||
transport == i2p::data::RouterInfo::eNTCP2V6 || transport == i2p::data::RouterInfo::eNTCP2V6Mesh)
|
||||
i2p::data::UpdateRouterProfile (ident,
|
||||
[](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->Connected (); // outgoing NTCP2 connection if always real
|
||||
});
|
||||
peer->router->GetProfile ()->Connected (); // outgoing NTCP2 connection if always real
|
||||
i2p::data::netdb.SetUnreachable (ident, false); // clear unreachable
|
||||
}
|
||||
peer->numAttempts = 0;
|
||||
@@ -934,11 +921,7 @@ namespace transport
|
||||
session->SendI2NPMessages (msgs); // send DatabaseStore
|
||||
}
|
||||
auto r = i2p::data::netdb.FindRouter (ident); // router should be in netdb after SessionConfirmed
|
||||
i2p::data::UpdateRouterProfile (ident,
|
||||
[](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->Connected ();
|
||||
});
|
||||
if (r) r->GetProfile ()->Connected ();
|
||||
auto ts = i2p::util::GetSecondsSinceEpoch ();
|
||||
auto peer = std::make_shared<Peer>(r, ts);
|
||||
peer->sessions.push_back (session);
|
||||
@@ -972,13 +955,8 @@ namespace transport
|
||||
}
|
||||
else
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_PeersMutex);
|
||||
m_Peers.erase (it);
|
||||
}
|
||||
// delete buffer of just disconnected router
|
||||
auto r = i2p::data::netdb.FindRouter (ident);
|
||||
if (r && !r->IsUpdated ()) r->ScheduleBufferToDelete ();
|
||||
std::lock_guard<std::mutex> l(m_PeersMutex);
|
||||
m_Peers.erase (it);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1028,7 +1006,7 @@ namespace transport
|
||||
if (session)
|
||||
session->SendLocalRouterInfo (true);
|
||||
it->second->nextRouterInfoUpdateTime = ts + PEER_ROUTER_INFO_UPDATE_INTERVAL +
|
||||
m_Rng() % PEER_ROUTER_INFO_UPDATE_INTERVAL_VARIANCE;
|
||||
rand () % PEER_ROUTER_INFO_UPDATE_INTERVAL_VARIANCE;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
@@ -1042,7 +1020,7 @@ namespace transport
|
||||
// if still testing or unknown, repeat peer test
|
||||
if (ipv4Testing || ipv6Testing)
|
||||
PeerTest (ipv4Testing, ipv6Testing);
|
||||
m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(2 * SESSION_CREATION_TIMEOUT + m_Rng() % SESSION_CREATION_TIMEOUT));
|
||||
m_PeerCleanupTimer->expires_from_now (boost::posix_time::seconds(3 * SESSION_CREATION_TIMEOUT));
|
||||
m_PeerCleanupTimer->async_wait (std::bind (&Transports::HandlePeerCleanupTimer, this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
@@ -1052,7 +1030,7 @@ namespace transport
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
PeerTest ();
|
||||
m_PeerTestTimer->expires_from_now (boost::posix_time::seconds(PEER_TEST_INTERVAL + m_Rng() % PEER_TEST_INTERVAL_VARIANCE));
|
||||
m_PeerTestTimer->expires_from_now (boost::posix_time::minutes(PEER_TEST_INTERVAL));
|
||||
m_PeerTestTimer->async_wait (std::bind (&Transports::HandlePeerTestTimer, this, std::placeholders::_1));
|
||||
}
|
||||
}
|
||||
@@ -1199,7 +1177,7 @@ namespace transport
|
||||
}
|
||||
|
||||
/** XXX: if routes are not restricted this dies */
|
||||
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRestrictedPeer()
|
||||
std::shared_ptr<const i2p::data::RouterInfo> Transports::GetRestrictedPeer() const
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_FamilyMutex);
|
||||
@@ -1208,7 +1186,7 @@ namespace transport
|
||||
if(sz > 1)
|
||||
{
|
||||
auto it = m_TrustedFamilies.begin ();
|
||||
std::advance(it, m_Rng() % sz);
|
||||
std::advance(it, rand() % sz);
|
||||
fam = *it;
|
||||
}
|
||||
else if (sz == 1)
|
||||
@@ -1226,7 +1204,7 @@ namespace transport
|
||||
if(sz == 1)
|
||||
return i2p::data::netdb.FindRouter(m_TrustedRouters[0]);
|
||||
auto it = m_TrustedRouters.begin();
|
||||
std::advance(it, m_Rng() % sz);
|
||||
std::advance(it, rand() % sz);
|
||||
return i2p::data::netdb.FindRouter(*it);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -20,7 +20,6 @@
|
||||
#include <string>
|
||||
#include <memory>
|
||||
#include <atomic>
|
||||
#include <random>
|
||||
#include <boost/asio.hpp>
|
||||
#include "TransportSession.h"
|
||||
#include "SSU2.h"
|
||||
@@ -55,8 +54,8 @@ namespace transport
|
||||
private:
|
||||
|
||||
const int m_QueueSize;
|
||||
i2p::util::MemoryPoolMt<Keys> m_KeysPool;
|
||||
std::queue<std::shared_ptr<Keys> > m_Queue;
|
||||
i2p::util::MemoryPoolMt<Keys> m_KeysPool;
|
||||
|
||||
bool m_IsRunning;
|
||||
std::unique_ptr<std::thread> m_Thread;
|
||||
@@ -107,8 +106,7 @@ namespace transport
|
||||
};
|
||||
|
||||
const uint64_t SESSION_CREATION_TIMEOUT = 15; // in seconds
|
||||
const int PEER_TEST_INTERVAL = 68*60; // in seconds
|
||||
const int PEER_TEST_INTERVAL_VARIANCE = 3*60; // in seconds
|
||||
const int PEER_TEST_INTERVAL = 71; // in minutes
|
||||
const int PEER_TEST_DELAY_INTERVAL = 20; // in milliseconds
|
||||
const int PEER_TEST_DELAY_INTERVAL_VARIANCE = 30; // in milliseconds
|
||||
const int MAX_NUM_DELAYED_MESSAGES = 150;
|
||||
@@ -147,6 +145,7 @@ namespace transport
|
||||
void ReuseX25519KeysPair (std::shared_ptr<i2p::crypto::X25519Keys> pair);
|
||||
|
||||
std::future<std::shared_ptr<TransportSession> > SendMessage (const i2p::data::IdentHash& ident, std::shared_ptr<i2p::I2NPMessage> msg);
|
||||
std::future<std::shared_ptr<TransportSession> > SendMessages (const i2p::data::IdentHash& ident, std::list<std::shared_ptr<i2p::I2NPMessage> >& msgs);
|
||||
std::future<std::shared_ptr<TransportSession> > SendMessages (const i2p::data::IdentHash& ident, std::list<std::shared_ptr<i2p::I2NPMessage> >&& msgs);
|
||||
|
||||
void PeerConnected (std::shared_ptr<TransportSession> session);
|
||||
@@ -170,7 +169,7 @@ namespace transport
|
||||
std::shared_ptr<const i2p::data::RouterInfo> GetRandomPeer (bool isHighBandwidth) const;
|
||||
|
||||
/** get a trusted first hop for restricted routes */
|
||||
std::shared_ptr<const i2p::data::RouterInfo> GetRestrictedPeer();
|
||||
std::shared_ptr<const i2p::data::RouterInfo> GetRestrictedPeer() const;
|
||||
/** do we want to use restricted routes? */
|
||||
bool RoutesRestricted() const;
|
||||
/** restrict routes to use only these router families for first hops */
|
||||
@@ -193,7 +192,7 @@ namespace transport
|
||||
void HandleRequestComplete (std::shared_ptr<const i2p::data::RouterInfo> r, i2p::data::IdentHash ident);
|
||||
std::shared_ptr<TransportSession> PostMessages (const i2p::data::IdentHash& ident, std::list<std::shared_ptr<i2p::I2NPMessage> >& msgs);
|
||||
bool ConnectToPeer (const i2p::data::IdentHash& ident, std::shared_ptr<Peer> peer);
|
||||
void SetPriority (std::shared_ptr<Peer> peer);
|
||||
void SetPriority (std::shared_ptr<Peer> peer) const;
|
||||
void HandlePeerCleanupTimer (const boost::system::error_code& ecode);
|
||||
void HandlePeerTestTimer (const boost::system::error_code& ecode);
|
||||
void HandleUpdateBandwidthTimer (const boost::system::error_code& ecode);
|
||||
@@ -241,7 +240,6 @@ namespace transport
|
||||
mutable std::mutex m_TrustedRoutersMutex;
|
||||
|
||||
i2p::I2NPMessagesHandler m_LoopbackHandler;
|
||||
std::mt19937 m_Rng;
|
||||
|
||||
public:
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -103,7 +103,7 @@ namespace tunnel
|
||||
if (m_Config->IsShort ())
|
||||
{
|
||||
auto ident = m_Config->GetFirstHop () ? m_Config->GetFirstHop ()->ident : nullptr;
|
||||
if (ident && ident->GetIdentHash () != outboundTunnel->GetEndpointIdentHash ()) // don't encrypt if IBGW = OBEP
|
||||
if (ident && ident->GetIdentHash () != outboundTunnel->GetNextIdentHash ()) // don't encrypt if IBGW = OBEP
|
||||
{
|
||||
auto msg1 = i2p::garlic::WrapECIESX25519MessageForRouter (msg, ident->GetEncryptionPublicKey ());
|
||||
if (msg1) msg = msg1;
|
||||
@@ -179,12 +179,9 @@ namespace tunnel
|
||||
{
|
||||
uint8_t ret = hop->GetRetCode (msg + 1);
|
||||
LogPrint (eLogDebug, "Tunnel: Build response ret code=", (int)ret);
|
||||
if (hop->ident)
|
||||
i2p::data::UpdateRouterProfile (hop->ident->GetIdentHash (),
|
||||
[ret](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->TunnelBuildResponse (ret);
|
||||
});
|
||||
auto profile = i2p::data::netdb.FindRouterProfile (hop->ident->GetIdentHash ());
|
||||
if (profile)
|
||||
profile->TunnelBuildResponse (ret);
|
||||
if (ret)
|
||||
// if any of participants declined the tunnel is not established
|
||||
established = false;
|
||||
@@ -281,21 +278,6 @@ namespace tunnel
|
||||
m_Endpoint.HandleDecryptedTunnelDataMsg (msg);
|
||||
}
|
||||
|
||||
bool InboundTunnel::Recreate ()
|
||||
{
|
||||
if (!IsRecreated ())
|
||||
{
|
||||
auto pool = GetTunnelPool ();
|
||||
if (pool)
|
||||
{
|
||||
SetRecreated (true);
|
||||
pool->RecreateInboundTunnel (std::static_pointer_cast<InboundTunnel>(shared_from_this ()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ZeroHopsInboundTunnel::ZeroHopsInboundTunnel ():
|
||||
InboundTunnel (std::make_shared<ZeroHopsTunnelConfig> ()),
|
||||
m_NumReceivedBytes (0)
|
||||
@@ -315,28 +297,22 @@ namespace tunnel
|
||||
void OutboundTunnel::SendTunnelDataMsgTo (const uint8_t * gwHash, uint32_t gwTunnel, std::shared_ptr<i2p::I2NPMessage> msg)
|
||||
{
|
||||
TunnelMessageBlock block;
|
||||
block.tunnelID = 0; // Initialize tunnelID to a default value
|
||||
|
||||
if (gwHash)
|
||||
{
|
||||
block.hash = gwHash;
|
||||
if (gwTunnel)
|
||||
{
|
||||
block.deliveryType = eDeliveryTypeTunnel;
|
||||
block.tunnelID = gwTunnel; // Set tunnelID only if gwTunnel is non-zero
|
||||
block.tunnelID = gwTunnel;
|
||||
}
|
||||
else
|
||||
{
|
||||
block.deliveryType = eDeliveryTypeRouter;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
block.deliveryType = eDeliveryTypeLocal;
|
||||
}
|
||||
|
||||
block.data = msg;
|
||||
SendTunnelDataMsgs({block});
|
||||
|
||||
SendTunnelDataMsgs ({block});
|
||||
}
|
||||
|
||||
void OutboundTunnel::SendTunnelDataMsgs (const std::vector<TunnelMessageBlock>& msgs)
|
||||
@@ -352,21 +328,6 @@ namespace tunnel
|
||||
LogPrint (eLogError, "Tunnel: Incoming message for outbound tunnel ", GetTunnelID ());
|
||||
}
|
||||
|
||||
bool OutboundTunnel::Recreate ()
|
||||
{
|
||||
if (!IsRecreated ())
|
||||
{
|
||||
auto pool = GetTunnelPool ();
|
||||
if (pool)
|
||||
{
|
||||
SetRecreated (true);
|
||||
pool->RecreateOutboundTunnel (std::static_pointer_cast<OutboundTunnel>(shared_from_this ()));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ZeroHopsOutboundTunnel::ZeroHopsOutboundTunnel ():
|
||||
OutboundTunnel (std::make_shared<ZeroHopsTunnelConfig> ()),
|
||||
m_NumSentBytes (0)
|
||||
@@ -473,7 +434,7 @@ namespace tunnel
|
||||
std::shared_ptr<OutboundTunnel> Tunnels::GetNextOutboundTunnel ()
|
||||
{
|
||||
if (m_OutboundTunnels.empty ()) return nullptr;
|
||||
uint32_t ind = m_Rng () % m_OutboundTunnels.size (), i = 0;
|
||||
uint32_t ind = rand () % m_OutboundTunnels.size (), i = 0;
|
||||
std::shared_ptr<OutboundTunnel> tunnel;
|
||||
for (const auto& it: m_OutboundTunnels)
|
||||
{
|
||||
@@ -750,17 +711,8 @@ namespace tunnel
|
||||
void Tunnels::ManageTunnels (uint64_t ts)
|
||||
{
|
||||
ManagePendingTunnels (ts);
|
||||
std::vector<std::shared_ptr<Tunnel> > tunnelsToRecreate;
|
||||
ManageInboundTunnels (ts, tunnelsToRecreate);
|
||||
ManageOutboundTunnels (ts, tunnelsToRecreate);
|
||||
// rec-create in random order
|
||||
if (!tunnelsToRecreate.empty ())
|
||||
{
|
||||
if (tunnelsToRecreate.size () > 1)
|
||||
std::shuffle (tunnelsToRecreate.begin(), tunnelsToRecreate.end(), m_Rng);
|
||||
for (auto& it: tunnelsToRecreate)
|
||||
it->Recreate ();
|
||||
}
|
||||
ManageInboundTunnels (ts);
|
||||
ManageOutboundTunnels (ts);
|
||||
}
|
||||
|
||||
void Tunnels::ManagePendingTunnels (uint64_t ts)
|
||||
@@ -791,11 +743,11 @@ namespace tunnel
|
||||
while (hop)
|
||||
{
|
||||
if (hop->ident)
|
||||
i2p::data::UpdateRouterProfile (hop->ident->GetIdentHash (),
|
||||
[](std::shared_ptr<i2p::data::RouterProfile> profile)
|
||||
{
|
||||
if (profile) profile->TunnelNonReplied ();
|
||||
});
|
||||
{
|
||||
auto profile = i2p::data::netdb.FindRouterProfile (hop->ident->GetIdentHash ());
|
||||
if (profile)
|
||||
profile->TunnelNonReplied ();
|
||||
}
|
||||
hop = hop->next;
|
||||
}
|
||||
}
|
||||
@@ -823,7 +775,7 @@ namespace tunnel
|
||||
}
|
||||
}
|
||||
|
||||
void Tunnels::ManageOutboundTunnels (uint64_t ts, std::vector<std::shared_ptr<Tunnel> >& toRecreate)
|
||||
void Tunnels::ManageOutboundTunnels (uint64_t ts)
|
||||
{
|
||||
for (auto it = m_OutboundTunnels.begin (); it != m_OutboundTunnels.end ();)
|
||||
{
|
||||
@@ -847,7 +799,10 @@ namespace tunnel
|
||||
auto pool = tunnel->GetTunnelPool ();
|
||||
// let it die if the tunnel pool has been reconfigured and this is old
|
||||
if (pool && tunnel->GetNumHops() == pool->GetNumOutboundHops())
|
||||
toRecreate.push_back (tunnel);
|
||||
{
|
||||
tunnel->SetRecreated (true);
|
||||
pool->RecreateOutboundTunnel (tunnel);
|
||||
}
|
||||
}
|
||||
if (ts + TUNNEL_EXPIRATION_THRESHOLD > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT)
|
||||
tunnel->SetState (eTunnelStateExpiring);
|
||||
@@ -872,7 +827,7 @@ namespace tunnel
|
||||
}
|
||||
}
|
||||
|
||||
void Tunnels::ManageInboundTunnels (uint64_t ts, std::vector<std::shared_ptr<Tunnel> >& toRecreate)
|
||||
void Tunnels::ManageInboundTunnels (uint64_t ts)
|
||||
{
|
||||
for (auto it = m_InboundTunnels.begin (); it != m_InboundTunnels.end ();)
|
||||
{
|
||||
@@ -896,7 +851,10 @@ namespace tunnel
|
||||
auto pool = tunnel->GetTunnelPool ();
|
||||
// let it die if the tunnel pool was reconfigured and has different number of hops
|
||||
if (pool && tunnel->GetNumHops() == pool->GetNumInboundHops())
|
||||
toRecreate.push_back (tunnel);
|
||||
{
|
||||
tunnel->SetRecreated (true);
|
||||
pool->RecreateInboundTunnel (tunnel);
|
||||
}
|
||||
}
|
||||
|
||||
if (ts + TUNNEL_EXPIRATION_THRESHOLD > tunnel->GetCreationTime () + TUNNEL_EXPIRATION_TIMEOUT)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -99,7 +99,6 @@ namespace tunnel
|
||||
void SetRecreated (bool recreated) { m_IsRecreated = recreated; };
|
||||
int GetNumHops () const { return m_Hops.size (); };
|
||||
virtual bool IsInbound() const = 0;
|
||||
virtual bool Recreate () = 0;
|
||||
|
||||
std::shared_ptr<TunnelPool> GetTunnelPool () const { return m_Pool; };
|
||||
void SetTunnelPool (std::shared_ptr<TunnelPool> pool) { m_Pool = pool; };
|
||||
@@ -151,7 +150,6 @@ namespace tunnel
|
||||
void HandleTunnelDataMsg (std::shared_ptr<i2p::I2NPMessage>&& tunnelMsg) override;
|
||||
|
||||
bool IsInbound() const override { return false; }
|
||||
bool Recreate () override;
|
||||
|
||||
private:
|
||||
|
||||
@@ -168,7 +166,6 @@ namespace tunnel
|
||||
void HandleTunnelDataMsg (std::shared_ptr<I2NPMessage>&& msg) override;
|
||||
virtual size_t GetNumReceivedBytes () const { return m_Endpoint.GetNumReceivedBytes (); };
|
||||
bool IsInbound() const override { return true; }
|
||||
bool Recreate () override;
|
||||
|
||||
// override TunnelBase
|
||||
void Cleanup () override { m_Endpoint.Cleanup (); };
|
||||
@@ -248,6 +245,8 @@ namespace tunnel
|
||||
void SetMaxNumTransitTunnels (uint32_t maxNumTransitTunnels);
|
||||
uint32_t GetMaxNumTransitTunnels () const { return m_MaxNumTransitTunnels; };
|
||||
int GetCongestionLevel() const { return m_MaxNumTransitTunnels ? CONGESTION_LEVEL_FULL * m_TransitTunnels.GetNumTransitTunnels () / m_MaxNumTransitTunnels : CONGESTION_LEVEL_FULL; }
|
||||
|
||||
std::mt19937& GetRng () { return m_Rng; };
|
||||
|
||||
private:
|
||||
|
||||
@@ -265,8 +264,8 @@ namespace tunnel
|
||||
|
||||
void Run ();
|
||||
void ManageTunnels (uint64_t ts);
|
||||
void ManageOutboundTunnels (uint64_t ts, std::vector<std::shared_ptr<Tunnel> >& toRecreate);
|
||||
void ManageInboundTunnels (uint64_t ts, std::vector<std::shared_ptr<Tunnel> >& toRecreate);
|
||||
void ManageOutboundTunnels (uint64_t ts);
|
||||
void ManageInboundTunnels (uint64_t ts);
|
||||
void ManagePendingTunnels (uint64_t ts);
|
||||
template<class PendingTunnels>
|
||||
void ManagePendingTunnels (PendingTunnels& pendingTunnels, uint64_t ts);
|
||||
@@ -297,8 +296,6 @@ namespace tunnel
|
||||
|
||||
bool m_IsRunning;
|
||||
std::thread * m_Thread;
|
||||
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE> > m_I2NPTunnelEndpointMessagesMemoryPool;
|
||||
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_MESSAGE_SIZE> > m_I2NPTunnelMessagesMemoryPool;
|
||||
std::map<uint32_t, std::shared_ptr<InboundTunnel> > m_PendingInboundTunnels; // by replyMsgID
|
||||
std::map<uint32_t, std::shared_ptr<OutboundTunnel> > m_PendingOutboundTunnels; // by replyMsgID
|
||||
std::list<std::shared_ptr<InboundTunnel> > m_InboundTunnels;
|
||||
@@ -309,6 +306,8 @@ namespace tunnel
|
||||
std::list<std::shared_ptr<TunnelPool>> m_Pools;
|
||||
std::shared_ptr<TunnelPool> m_ExploratoryPool;
|
||||
i2p::util::Queue<std::shared_ptr<I2NPMessage> > m_Queue;
|
||||
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_ENPOINT_MESSAGE_SIZE> > m_I2NPTunnelEndpointMessagesMemoryPool;
|
||||
i2p::util::MemoryPoolMt<I2NPMessageBuffer<I2NP_TUNNEL_MESSAGE_SIZE> > m_I2NPTunnelMessagesMemoryPool;
|
||||
uint32_t m_MaxNumTransitTunnels;
|
||||
// count of tunnels for total TCSR algorithm
|
||||
int m_TotalNumSuccesiveTunnelCreations, m_TotalNumFailedTunnelCreations;
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
* See full license text in LICENSE file at top of project tree
|
||||
*
|
||||
*/
|
||||
|
||||
#include "Transports.h"
|
||||
#include "TunnelBase.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace tunnel
|
||||
{
|
||||
void TunnelTransportSender::SendMessagesTo (const i2p::data::IdentHash& to,
|
||||
std::list<std::shared_ptr<I2NPMessage> >&& msgs)
|
||||
{
|
||||
if (msgs.empty ()) return;
|
||||
auto currentTransport = m_CurrentTransport.lock ();
|
||||
if (!currentTransport)
|
||||
{
|
||||
// try to obtain transport from pending request or send thought transport is not complete
|
||||
if (m_PendingTransport.valid ()) // pending request?
|
||||
{
|
||||
if (m_PendingTransport.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
|
||||
{
|
||||
// pending request complete
|
||||
currentTransport = m_PendingTransport.get (); // take transports used in pending request
|
||||
if (currentTransport)
|
||||
{
|
||||
if (currentTransport->IsEstablished ())
|
||||
m_CurrentTransport = currentTransport;
|
||||
else
|
||||
currentTransport = nullptr;
|
||||
}
|
||||
}
|
||||
else // still pending
|
||||
{
|
||||
// send through transports, but don't update pending transport
|
||||
i2p::transport::transports.SendMessages (to, std::move (msgs));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentTransport) // session is good
|
||||
// send to session directly
|
||||
currentTransport->SendI2NPMessages (msgs);
|
||||
else // no session yet
|
||||
// send through transports
|
||||
m_PendingTransport = i2p::transport::transports.SendMessages (to, std::move (msgs));
|
||||
|
||||
}
|
||||
|
||||
void TunnelTransportSender::SendMessagesTo (const i2p::data::IdentHash& to,
|
||||
std::list<std::shared_ptr<I2NPMessage> >& msgs)
|
||||
{
|
||||
std::list<std::shared_ptr<i2p::I2NPMessage> > msgs1;
|
||||
msgs.swap (msgs1);
|
||||
SendMessagesTo (to, std::move (msgs1));
|
||||
}
|
||||
|
||||
void TunnelTransportSender::Reset ()
|
||||
{
|
||||
m_CurrentTransport.reset ();
|
||||
if (m_PendingTransport.valid ())
|
||||
m_PendingTransport = std::future<std::shared_ptr<i2p::transport::TransportSession> >();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2022, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -11,19 +11,12 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include <list>
|
||||
#include "Timestamp.h"
|
||||
#include "I2NPProtocol.h"
|
||||
#include "Identity.h"
|
||||
|
||||
namespace i2p
|
||||
{
|
||||
namespace transport
|
||||
{
|
||||
class TransportSession;
|
||||
}
|
||||
|
||||
namespace tunnel
|
||||
{
|
||||
const size_t TUNNEL_DATA_MSG_SIZE = 1028;
|
||||
@@ -83,25 +76,6 @@ namespace tunnel
|
||||
return t1 < t2;
|
||||
}
|
||||
};
|
||||
|
||||
class TunnelTransportSender final
|
||||
{
|
||||
public:
|
||||
|
||||
TunnelTransportSender () = default;
|
||||
~TunnelTransportSender () = default;
|
||||
|
||||
void SendMessagesTo (const i2p::data::IdentHash& to, std::list<std::shared_ptr<I2NPMessage> >&& msgs);
|
||||
void SendMessagesTo (const i2p::data::IdentHash& to, std::list<std::shared_ptr<I2NPMessage> >& msgs); // send and clear
|
||||
|
||||
std::shared_ptr<const i2p::transport::TransportSession> GetCurrentTransport () const { return m_CurrentTransport.lock (); }
|
||||
void Reset ();
|
||||
|
||||
private:
|
||||
|
||||
std::weak_ptr<i2p::transport::TransportSession> m_CurrentTransport;
|
||||
std::future<std::shared_ptr<i2p::transport::TransportSession> > m_PendingTransport;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,8 @@ namespace tunnel
|
||||
uint8_t * record = records + index*TUNNEL_BUILD_RECORD_SIZE;
|
||||
i2p::crypto::CBCDecryption decryption;
|
||||
decryption.SetKey (replyKey);
|
||||
decryption.Decrypt(record, TUNNEL_BUILD_RECORD_SIZE, replyIV, record);
|
||||
decryption.SetIV (replyIV);
|
||||
decryption.Decrypt(record, TUNNEL_BUILD_RECORD_SIZE, record);
|
||||
}
|
||||
|
||||
void ECIESTunnelHopConfig::EncryptECIES (const uint8_t * plainText, size_t len, uint8_t * encrypted)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2023, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -21,7 +21,10 @@ namespace i2p
|
||||
{
|
||||
namespace tunnel
|
||||
{
|
||||
|
||||
TunnelEndpoint::~TunnelEndpoint ()
|
||||
{
|
||||
}
|
||||
|
||||
void TunnelEndpoint::HandleDecryptedTunnelDataMsg (std::shared_ptr<I2NPMessage> msg)
|
||||
{
|
||||
m_NumReceivedBytes += TUNNEL_DATA_MSG_SIZE;
|
||||
@@ -258,8 +261,9 @@ namespace tunnel
|
||||
void TunnelEndpoint::AddOutOfSequenceFragment (uint32_t msgID, uint8_t fragmentNum,
|
||||
bool isLastFragment, const uint8_t * fragment, size_t size)
|
||||
{
|
||||
if (!m_OutOfSequenceFragments.try_emplace ((uint64_t)msgID << 32 | fragmentNum,
|
||||
isLastFragment, i2p::util::GetMillisecondsSinceEpoch (), fragment, size).second)
|
||||
std::unique_ptr<Fragment> f(new Fragment (isLastFragment, i2p::util::GetMillisecondsSinceEpoch (), size));
|
||||
memcpy (f->data.data (), fragment, size);
|
||||
if (!m_OutOfSequenceFragments.emplace ((uint64_t)msgID << 32 | fragmentNum, std::move (f)).second)
|
||||
LogPrint (eLogInfo, "TunnelMessage: Duplicate out-of-sequence fragment ", fragmentNum, " of message ", msgID);
|
||||
}
|
||||
|
||||
@@ -289,7 +293,7 @@ namespace tunnel
|
||||
if (it != m_OutOfSequenceFragments.end ())
|
||||
{
|
||||
LogPrint (eLogDebug, "TunnelMessage: Out-of-sequence fragment ", (int)msg.nextFragmentNum, " of message ", msgID, " found");
|
||||
size_t size = it->second.data.size ();
|
||||
size_t size = it->second->data.size ();
|
||||
if (msg.data->len + size > msg.data->maxLen)
|
||||
{
|
||||
LogPrint (eLogWarning, "TunnelMessage: Tunnel endpoint I2NP message size ", msg.data->maxLen, " is not enough");
|
||||
@@ -297,9 +301,9 @@ namespace tunnel
|
||||
*newMsg = *(msg.data);
|
||||
msg.data = newMsg;
|
||||
}
|
||||
if (msg.data->Concat (it->second.data.data (), size) < size) // concatenate out-of-sync fragment
|
||||
if (msg.data->Concat (it->second->data.data (), size) < size) // concatenate out-of-sync fragment
|
||||
LogPrint (eLogError, "TunnelMessage: Tunnel endpoint I2NP buffer overflow ", msg.data->maxLen);
|
||||
if (it->second.isLastFragment)
|
||||
if (it->second->isLastFragment)
|
||||
// message complete
|
||||
msg.nextFragmentNum = 0;
|
||||
else
|
||||
@@ -327,13 +331,13 @@ namespace tunnel
|
||||
break;
|
||||
case eDeliveryTypeTunnel:
|
||||
if (!m_IsInbound) // outbound transit tunnel
|
||||
SendMessageTo (msg.hash, i2p::CreateTunnelGatewayMsg (msg.tunnelID, msg.data));
|
||||
i2p::transport::transports.SendMessage (msg.hash, i2p::CreateTunnelGatewayMsg (msg.tunnelID, msg.data));
|
||||
else
|
||||
LogPrint (eLogError, "TunnelMessage: Delivery type 'tunnel' arrived from an inbound tunnel, dropped");
|
||||
break;
|
||||
case eDeliveryTypeRouter:
|
||||
if (!m_IsInbound) // outbound transit tunnel
|
||||
i2p::transport::transports.SendMessage (msg.hash, msg.data); // send right away, because most likely it's single message
|
||||
i2p::transport::transports.SendMessage (msg.hash, msg.data);
|
||||
else // we shouldn't send this message. possible leakage
|
||||
LogPrint (eLogError, "TunnelMessage: Delivery type 'router' arrived from an inbound tunnel, dropped");
|
||||
break;
|
||||
@@ -348,7 +352,7 @@ namespace tunnel
|
||||
// out-of-sequence fragments
|
||||
for (auto it = m_OutOfSequenceFragments.begin (); it != m_OutOfSequenceFragments.end ();)
|
||||
{
|
||||
if (ts > it->second.receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
|
||||
if (ts > it->second->receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
|
||||
it = m_OutOfSequenceFragments.erase (it);
|
||||
else
|
||||
++it;
|
||||
@@ -362,35 +366,5 @@ namespace tunnel
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
void TunnelEndpoint::SendMessageTo (const i2p::data::IdentHash& to, std::shared_ptr<i2p::I2NPMessage> msg)
|
||||
{
|
||||
if (msg)
|
||||
{
|
||||
if (!m_Sender && m_I2NPMsgs.empty ()) // first message
|
||||
m_CurrentHash = to;
|
||||
else if (m_CurrentHash != to) // new target router
|
||||
{
|
||||
FlushI2NPMsgs (); // flush message to previous
|
||||
if (m_Sender) m_Sender->Reset (); // reset sender
|
||||
m_CurrentHash = to; // set new target router
|
||||
} // otherwise add msg to the list for current target router
|
||||
m_I2NPMsgs.push_back (msg);
|
||||
}
|
||||
}
|
||||
|
||||
void TunnelEndpoint::FlushI2NPMsgs ()
|
||||
{
|
||||
if (!m_I2NPMsgs.empty ())
|
||||
{
|
||||
if (!m_Sender) m_Sender = std::make_unique<TunnelTransportSender>();
|
||||
m_Sender->SendMessagesTo (m_CurrentHash, m_I2NPMsgs); // send and clear
|
||||
}
|
||||
}
|
||||
|
||||
const i2p::data::IdentHash * TunnelEndpoint::GetCurrentHash () const
|
||||
{
|
||||
return (m_Sender || !m_I2NPMsgs.empty ()) ? &m_CurrentHash : nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2021, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -11,10 +11,8 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <vector>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <memory>
|
||||
#include "I2NPProtocol.h"
|
||||
#include "TunnelBase.h"
|
||||
|
||||
@@ -22,7 +20,7 @@ namespace i2p
|
||||
{
|
||||
namespace tunnel
|
||||
{
|
||||
class TunnelEndpoint final
|
||||
class TunnelEndpoint
|
||||
{
|
||||
struct TunnelMessageBlockEx: public TunnelMessageBlock
|
||||
{
|
||||
@@ -32,8 +30,7 @@ namespace tunnel
|
||||
|
||||
struct Fragment
|
||||
{
|
||||
Fragment (bool last, uint64_t t, const uint8_t * buf, size_t size):
|
||||
isLastFragment (last), receiveTime (t), data (size) { memcpy (data.data(), buf, size); };
|
||||
Fragment (bool last, uint64_t t, size_t size): isLastFragment (last), receiveTime (t), data (size) {};
|
||||
bool isLastFragment;
|
||||
uint64_t receiveTime; // milliseconds since epoch
|
||||
std::vector<uint8_t> data;
|
||||
@@ -42,23 +39,18 @@ namespace tunnel
|
||||
public:
|
||||
|
||||
TunnelEndpoint (bool isInbound): m_IsInbound (isInbound), m_NumReceivedBytes (0), m_CurrentMsgID (0) {};
|
||||
~TunnelEndpoint () = default;
|
||||
~TunnelEndpoint ();
|
||||
size_t GetNumReceivedBytes () const { return m_NumReceivedBytes; };
|
||||
void Cleanup ();
|
||||
|
||||
void HandleDecryptedTunnelDataMsg (std::shared_ptr<I2NPMessage> msg);
|
||||
void FlushI2NPMsgs ();
|
||||
|
||||
const i2p::data::IdentHash * GetCurrentHash () const; // return null if not avaiable
|
||||
const std::unique_ptr<TunnelTransportSender>& GetSender () const { return m_Sender; };
|
||||
|
||||
private:
|
||||
|
||||
void HandleFollowOnFragment (uint32_t msgID, bool isLastFragment, uint8_t fragmentNum, const uint8_t * fragment, size_t size);
|
||||
bool ConcatFollowOnFragment (TunnelMessageBlockEx& msg, const uint8_t * fragment, size_t size) const; // true if success
|
||||
void HandleCurrenMessageFollowOnFragment (const uint8_t * fragment, size_t size, bool isLastFragment);
|
||||
void HandleNextMessage (const TunnelMessageBlock& msg);
|
||||
void SendMessageTo (const i2p::data::IdentHash& to, std::shared_ptr<i2p::I2NPMessage> msg);
|
||||
|
||||
void AddOutOfSequenceFragment (uint32_t msgID, uint8_t fragmentNum, bool isLastFragment, const uint8_t * fragment, size_t size);
|
||||
bool ConcatNextOutOfSequenceFragment (uint32_t msgID, TunnelMessageBlockEx& msg); // true if something added
|
||||
@@ -68,15 +60,11 @@ namespace tunnel
|
||||
private:
|
||||
|
||||
std::unordered_map<uint32_t, TunnelMessageBlockEx> m_IncompleteMessages;
|
||||
std::unordered_map<uint64_t, Fragment> m_OutOfSequenceFragments; // ((msgID << 8) + fragment#)->fragment
|
||||
std::unordered_map<uint64_t, std::unique_ptr<Fragment> > m_OutOfSequenceFragments; // ((msgID << 8) + fragment#)->fragment
|
||||
bool m_IsInbound;
|
||||
size_t m_NumReceivedBytes;
|
||||
TunnelMessageBlockEx m_CurrentMessage;
|
||||
uint32_t m_CurrentMsgID;
|
||||
// I2NP messages to send
|
||||
std::list<std::shared_ptr<i2p::I2NPMessage> > m_I2NPMsgs; // to send
|
||||
i2p::data::IdentHash m_CurrentHash; // send msgs to
|
||||
std::unique_ptr<TunnelTransportSender> m_Sender;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,9 +235,40 @@ namespace tunnel
|
||||
m_NumSentBytes += TUNNEL_DATA_MSG_SIZE;
|
||||
}
|
||||
m_Buffer.ClearTunnelDataMsgs ();
|
||||
|
||||
// send
|
||||
if (!m_Sender) m_Sender = std::make_unique<TunnelTransportSender>();
|
||||
m_Sender->SendMessagesTo (m_Tunnel.GetNextIdentHash (), std::move (newTunnelMsgs));
|
||||
auto currentTransport = m_CurrentTransport.lock ();
|
||||
if (!currentTransport)
|
||||
{
|
||||
// try to obtain transport from peding reequest or send thought transport is not complete
|
||||
if (m_PendingTransport.valid ()) // pending request?
|
||||
{
|
||||
if (m_PendingTransport.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
|
||||
{
|
||||
// pending request complete
|
||||
currentTransport = m_PendingTransport.get (); // take tarnsports used in pending request
|
||||
if (currentTransport)
|
||||
{
|
||||
if (currentTransport->IsEstablished ())
|
||||
m_CurrentTransport = currentTransport;
|
||||
else
|
||||
currentTransport = nullptr;
|
||||
}
|
||||
}
|
||||
else // still pending
|
||||
{
|
||||
// send through transports, but don't update pedning transport
|
||||
i2p::transport::transports.SendMessages (m_Tunnel.GetNextIdentHash (), std::move (newTunnelMsgs));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (currentTransport) // session is good
|
||||
// send to session directly
|
||||
currentTransport->SendI2NPMessages (newTunnelMsgs);
|
||||
else // no session yet
|
||||
// send through transports
|
||||
m_PendingTransport = i2p::transport::transports.SendMessages (m_Tunnel.GetNextIdentHash (), std::move (newTunnelMsgs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
#include <inttypes.h>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <future>
|
||||
#include "I2NPProtocol.h"
|
||||
#include "TransportSession.h"
|
||||
#include "TunnelBase.h"
|
||||
|
||||
namespace i2p
|
||||
@@ -51,14 +53,14 @@ namespace tunnel
|
||||
void PutTunnelDataMsg (const TunnelMessageBlock& block);
|
||||
void SendBuffer ();
|
||||
size_t GetNumSentBytes () const { return m_NumSentBytes; };
|
||||
const std::unique_ptr<TunnelTransportSender>& GetSender () const { return m_Sender; };
|
||||
|
||||
private:
|
||||
|
||||
TunnelBase& m_Tunnel;
|
||||
TunnelGatewayBuffer m_Buffer;
|
||||
size_t m_NumSentBytes;
|
||||
std::unique_ptr<TunnelTransportSender> m_Sender;
|
||||
std::weak_ptr<i2p::transport::TransportSession> m_CurrentTransport;
|
||||
std::future<std::shared_ptr<i2p::transport::TransportSession> > m_PendingTransport;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -560,7 +560,7 @@ namespace tunnel
|
||||
i2p::data::netdb.GetRandomRouter (prevHop, reverse, endpoint, false);
|
||||
if (hop)
|
||||
{
|
||||
if (!hop->HasProfile () || !hop->GetProfile ()->IsBad ())
|
||||
if (!hop->GetProfile ()->IsBad ())
|
||||
break;
|
||||
}
|
||||
else if (tryClient)
|
||||
@@ -588,7 +588,7 @@ namespace tunnel
|
||||
(inbound && i2p::transport::transports.GetNumPeers () > 25))
|
||||
{
|
||||
auto r = i2p::transport::transports.GetRandomPeer (m_IsHighBandwidth && !i2p::context.IsLimitedConnectivity ());
|
||||
if (r && r->IsECIES () && (!r->HasProfile () || !r->GetProfile ()->IsBad ()) &&
|
||||
if (r && r->IsECIES () && !r->GetProfile ()->IsBad () &&
|
||||
(numHops > 1 || (r->IsV4 () && (!inbound || r->IsPublished (true))))) // first inbound must be published ipv4
|
||||
{
|
||||
prevHop = r;
|
||||
|
||||
@@ -37,7 +37,9 @@ namespace api
|
||||
i2p::fs::Init();
|
||||
|
||||
bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation);
|
||||
i2p::crypto::InitCrypto (precomputation);
|
||||
bool aesni; i2p::config::GetOption("cpuext.aesni", aesni);
|
||||
bool forceCpuExt; i2p::config::GetOption("cpuext.force", forceCpuExt);
|
||||
i2p::crypto::InitCrypto (precomputation, aesni, forceCpuExt);
|
||||
|
||||
int netID; i2p::config::GetOption("netid", netID);
|
||||
i2p::context.SetNetID (netID);
|
||||
|
||||
@@ -454,9 +454,9 @@ namespace net
|
||||
#ifdef _WIN32
|
||||
LogPrint(eLogError, "NetIface: Cannot get address by interface name, not implemented on WIN32");
|
||||
if (ipv6)
|
||||
return boost::asio::ip::make_address("::1");
|
||||
return boost::asio::ip::address::from_string("::1");
|
||||
else
|
||||
return boost::asio::ip::make_address("127.0.0.1");
|
||||
return boost::asio::ip::address::from_string("127.0.0.1");
|
||||
#else
|
||||
int af = (ipv6 ? AF_INET6 : AF_INET);
|
||||
ifaddrs *addrs;
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
#define MAKE_VERSION_NUMBER(a,b,c) ((a*100+b)*100+c)
|
||||
|
||||
#define I2PD_VERSION_MAJOR 2
|
||||
#define I2PD_VERSION_MINOR 55
|
||||
#define I2PD_VERSION_MINOR 54
|
||||
#define I2PD_VERSION_MICRO 0
|
||||
#define I2PD_VERSION_PATCH 0
|
||||
#ifdef GITVER
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -9,7 +9,7 @@
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <map>
|
||||
#include <fstream>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
@@ -17,7 +17,6 @@
|
||||
#include <boost/algorithm/string.hpp>
|
||||
#include "Base.h"
|
||||
#include "util.h"
|
||||
#include "Timestamp.h"
|
||||
#include "Identity.h"
|
||||
#include "FS.h"
|
||||
#include "Log.h"
|
||||
@@ -50,23 +49,22 @@ namespace client
|
||||
if (m_IsPersist)
|
||||
i2p::config::GetOption("addressbook.hostsfile", m_HostsFile);
|
||||
}
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) override;
|
||||
void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address) override;
|
||||
void RemoveAddress (const i2p::data::IdentHash& ident) override;
|
||||
void CleanUpCache () override;
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) const;
|
||||
void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address);
|
||||
void RemoveAddress (const i2p::data::IdentHash& ident);
|
||||
|
||||
bool Init () override;
|
||||
int Load (Addresses& addresses) override;
|
||||
int LoadLocal (Addresses& addresses) override;
|
||||
int Save (const Addresses& addresses) override;
|
||||
bool Init ();
|
||||
int Load (std::map<std::string, std::shared_ptr<Address> > & addresses);
|
||||
int LoadLocal (std::map<std::string, std::shared_ptr<Address> >& addresses);
|
||||
int Save (const std::map<std::string, std::shared_ptr<Address> >& addresses);
|
||||
|
||||
void SaveEtag (const i2p::data::IdentHash& subsciption, const std::string& etag, const std::string& lastModified);
|
||||
bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified);
|
||||
void ResetEtags ();
|
||||
|
||||
void SaveEtag (const i2p::data::IdentHash& subsciption, const std::string& etag, const std::string& lastModified) override;
|
||||
bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified) override;
|
||||
void ResetEtags () override;
|
||||
|
||||
private:
|
||||
|
||||
int LoadFromFile (const std::string& filename, Addresses& addresses); // returns -1 if can't open file, otherwise number of records
|
||||
int LoadFromFile (const std::string& filename, std::map<std::string, std::shared_ptr<Address> >& addresses); // returns -1 if can't open file, otherwise number of records
|
||||
|
||||
private:
|
||||
|
||||
@@ -74,8 +72,6 @@ namespace client
|
||||
std::string etagsPath, indexPath, localPath;
|
||||
bool m_IsPersist;
|
||||
std::string m_HostsFile; // file to dump hosts.txt, empty if not used
|
||||
std::unordered_map<i2p::data::IdentHash, std::pair<std::vector<uint8_t>, uint64_t> > m_FullAddressCache; // ident hash -> (full ident buffer, last access timestamp)
|
||||
std::mutex m_FullAddressCacheMutex;
|
||||
};
|
||||
|
||||
bool AddressBookFilesystemStorage::Init()
|
||||
@@ -96,19 +92,8 @@ namespace client
|
||||
return false;
|
||||
}
|
||||
|
||||
std::shared_ptr<const i2p::data::IdentityEx> AddressBookFilesystemStorage::GetAddress (const i2p::data::IdentHash& ident)
|
||||
std::shared_ptr<const i2p::data::IdentityEx> AddressBookFilesystemStorage::GetAddress (const i2p::data::IdentHash& ident) const
|
||||
{
|
||||
auto ts = i2p::util::GetMonotonicSeconds ();
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_FullAddressCacheMutex);
|
||||
auto it = m_FullAddressCache.find (ident);
|
||||
if (it != m_FullAddressCache.end ())
|
||||
{
|
||||
it->second.second = ts;
|
||||
return std::make_shared<i2p::data::IdentityEx>(it->second.first.data (), it->second.first.size ());
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_IsPersist)
|
||||
{
|
||||
LogPrint(eLogDebug, "Addressbook: Persistence is disabled");
|
||||
@@ -116,72 +101,48 @@ namespace client
|
||||
}
|
||||
std::string filename = storage.Path(ident.ToBase32());
|
||||
std::ifstream f(filename, std::ifstream::binary);
|
||||
if (!f.is_open ())
|
||||
{
|
||||
if (!f.is_open ()) {
|
||||
LogPrint(eLogDebug, "Addressbook: Requested, but not found: ", filename);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
f.seekg (0,std::ios::end);
|
||||
size_t len = f.tellg ();
|
||||
if (len < i2p::data::DEFAULT_IDENTITY_SIZE)
|
||||
{
|
||||
if (len < i2p::data::DEFAULT_IDENTITY_SIZE) {
|
||||
LogPrint (eLogError, "Addressbook: File ", filename, " is too short: ", len);
|
||||
return nullptr;
|
||||
}
|
||||
f.seekg(0, std::ios::beg);
|
||||
std::vector<uint8_t> buf(len);
|
||||
f.read((char *)buf.data (), len);
|
||||
if (!f)
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Couldn't read ", filename);
|
||||
return nullptr;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_FullAddressCacheMutex);
|
||||
m_FullAddressCache.try_emplace (ident, buf, ts);
|
||||
}
|
||||
return std::make_shared<i2p::data::IdentityEx>(buf.data (), len);
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
f.read((char *)buf, len);
|
||||
auto address = std::make_shared<i2p::data::IdentityEx>(buf, len);
|
||||
delete[] buf;
|
||||
return address;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address)
|
||||
{
|
||||
if (!address) return;
|
||||
size_t len = address->GetFullLen ();
|
||||
std::vector<uint8_t> buf;
|
||||
if (!len) return; // invalid address
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_FullAddressCacheMutex);
|
||||
auto [it, inserted] = m_FullAddressCache.try_emplace (address->GetIdentHash(), len, i2p::util::GetMonotonicSeconds ());
|
||||
if (inserted)
|
||||
address->ToBuffer (it->second.first.data (), len);
|
||||
if (m_IsPersist)
|
||||
buf = it->second.first;
|
||||
if (!m_IsPersist) return;
|
||||
std::string path = storage.Path( address->GetIdentHash().ToBase32() );
|
||||
std::ofstream f (path, std::ofstream::binary | std::ofstream::out);
|
||||
if (!f.is_open ()) {
|
||||
LogPrint (eLogError, "Addressbook: Can't open file ", path);
|
||||
return;
|
||||
}
|
||||
if (m_IsPersist && !buf.empty ())
|
||||
{
|
||||
std::string path = storage.Path(address->GetIdentHash().ToBase32());
|
||||
std::ofstream f (path, std::ofstream::binary | std::ofstream::out);
|
||||
if (!f.is_open ())
|
||||
{
|
||||
LogPrint (eLogError, "Addressbook: Can't open file ", path);
|
||||
return;
|
||||
}
|
||||
f.write ((const char *)buf.data (), len);
|
||||
}
|
||||
size_t len = address->GetFullLen ();
|
||||
uint8_t * buf = new uint8_t[len];
|
||||
address->ToBuffer (buf, len);
|
||||
f.write ((char *)buf, len);
|
||||
delete[] buf;
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::RemoveAddress (const i2p::data::IdentHash& ident)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> l(m_FullAddressCacheMutex);
|
||||
m_FullAddressCache.erase (ident);
|
||||
}
|
||||
if (!m_IsPersist) return;
|
||||
storage.Remove( ident.ToBase32() );
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::LoadFromFile (const std::string& filename, Addresses& addresses)
|
||||
int AddressBookFilesystemStorage::LoadFromFile (const std::string& filename, std::map<std::string, std::shared_ptr<Address> >& addresses)
|
||||
{
|
||||
int num = 0;
|
||||
std::ifstream f (filename, std::ifstream::in); // in text mode
|
||||
@@ -207,7 +168,7 @@ namespace client
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Load (Addresses& addresses)
|
||||
int AddressBookFilesystemStorage::Load (std::map<std::string, std::shared_ptr<Address> >& addresses)
|
||||
{
|
||||
int num = LoadFromFile (indexPath, addresses);
|
||||
if (num < 0)
|
||||
@@ -221,7 +182,7 @@ namespace client
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::LoadLocal (Addresses& addresses)
|
||||
int AddressBookFilesystemStorage::LoadLocal (std::map<std::string, std::shared_ptr<Address> >& addresses)
|
||||
{
|
||||
int num = LoadFromFile (localPath, addresses);
|
||||
if (num < 0) return 0;
|
||||
@@ -229,7 +190,7 @@ namespace client
|
||||
return num;
|
||||
}
|
||||
|
||||
int AddressBookFilesystemStorage::Save (const Addresses& addresses)
|
||||
int AddressBookFilesystemStorage::Save (const std::map<std::string, std::shared_ptr<Address> >& addresses)
|
||||
{
|
||||
if (addresses.empty())
|
||||
{
|
||||
@@ -320,22 +281,9 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBookFilesystemStorage::CleanUpCache ()
|
||||
{
|
||||
auto ts = i2p::util::GetMonotonicSeconds ();
|
||||
std::lock_guard<std::mutex> l(m_FullAddressCacheMutex);
|
||||
for (auto it = m_FullAddressCache.begin (); it != m_FullAddressCache.end ();)
|
||||
{
|
||||
if (ts > it->second.second + ADDRESS_CACHE_EXPIRATION_TIMEOUT)
|
||||
it = m_FullAddressCache.erase (it);
|
||||
else
|
||||
it++;
|
||||
}
|
||||
}
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
Address::Address (std::string_view b32):
|
||||
Address::Address (const std::string& b32):
|
||||
addressType (eAddressInvalid)
|
||||
{
|
||||
if (b32.length () <= B33_ADDRESS_THRESHOLD)
|
||||
@@ -379,7 +327,6 @@ namespace client
|
||||
LoadHosts (); /* try storage, then hosts.txt, then download */
|
||||
StartSubscriptions ();
|
||||
StartLookups ();
|
||||
ScheduleCacheUpdate ();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,14 +341,9 @@ namespace client
|
||||
StopSubscriptions ();
|
||||
if (m_SubscriptionsUpdateTimer)
|
||||
{
|
||||
m_SubscriptionsUpdateTimer->cancel ();
|
||||
delete m_SubscriptionsUpdateTimer;
|
||||
m_SubscriptionsUpdateTimer = nullptr;
|
||||
}
|
||||
if (m_AddressCacheUpdateTimer)
|
||||
{
|
||||
m_AddressCacheUpdateTimer->cancel ();
|
||||
m_AddressCacheUpdateTimer = nullptr;
|
||||
}
|
||||
bool isDownloading = m_Downloading.valid ();
|
||||
if (isDownloading)
|
||||
{
|
||||
@@ -435,7 +377,7 @@ namespace client
|
||||
m_Subscriptions.clear ();
|
||||
}
|
||||
|
||||
std::shared_ptr<const Address> AddressBook::GetAddress (std::string_view address)
|
||||
std::shared_ptr<const Address> AddressBook::GetAddress (const std::string& address)
|
||||
{
|
||||
auto pos = address.find(".b32.i2p");
|
||||
if (pos != std::string::npos)
|
||||
@@ -462,7 +404,7 @@ namespace client
|
||||
return std::make_shared<const Address>(dest.GetIdentHash ());
|
||||
}
|
||||
|
||||
std::shared_ptr<const Address> AddressBook::FindAddress (std::string_view address)
|
||||
std::shared_ptr<const Address> AddressBook::FindAddress (const std::string& address)
|
||||
{
|
||||
auto it = m_Addresses.find (address);
|
||||
if (it != m_Addresses.end ())
|
||||
@@ -667,7 +609,7 @@ namespace client
|
||||
void AddressBook::LoadLocal ()
|
||||
{
|
||||
if (!m_Storage) return;
|
||||
AddressBookStorage::Addresses localAddresses;
|
||||
std::map<std::string, std::shared_ptr<Address>> localAddresses;
|
||||
m_Storage->LoadLocal (localAddresses);
|
||||
for (const auto& it: localAddresses)
|
||||
{
|
||||
@@ -740,7 +682,7 @@ namespace client
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if (dest)
|
||||
{
|
||||
m_SubscriptionsUpdateTimer = std::make_unique<boost::asio::deadline_timer>(dest->GetService ());
|
||||
m_SubscriptionsUpdateTimer = new boost::asio::deadline_timer (dest->GetService ());
|
||||
m_SubscriptionsUpdateTimer->expires_from_now (boost::posix_time::minutes(INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT));
|
||||
m_SubscriptionsUpdateTimer->async_wait (std::bind (&AddressBook::HandleSubscriptionsUpdateTimer,
|
||||
this, std::placeholders::_1));
|
||||
@@ -824,7 +766,7 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::LookupAddress (std::string_view address)
|
||||
void AddressBook::LookupAddress (const std::string& address)
|
||||
{
|
||||
std::shared_ptr<const Address> addr;
|
||||
auto dot = address.find ('.');
|
||||
@@ -854,7 +796,7 @@ namespace client
|
||||
memset (buf, 0, 4);
|
||||
htobe32buf (buf + 4, nonce);
|
||||
buf[8] = address.length ();
|
||||
memcpy (buf + 9, address.data (), address.length ());
|
||||
memcpy (buf + 9, address.c_str (), address.length ());
|
||||
datagram->SendDatagramTo (buf, len, addr->identHash, ADDRESS_RESPONSE_DATAGRAM_PORT, ADDRESS_RESOLVER_DATAGRAM_PORT);
|
||||
delete[] buf;
|
||||
}
|
||||
@@ -891,29 +833,6 @@ namespace client
|
||||
}
|
||||
}
|
||||
|
||||
void AddressBook::ScheduleCacheUpdate ()
|
||||
{
|
||||
if (!m_AddressCacheUpdateTimer)
|
||||
{
|
||||
auto dest = i2p::client::context.GetSharedLocalDestination ();
|
||||
if(dest)
|
||||
m_AddressCacheUpdateTimer = std::make_unique<boost::asio::deadline_timer>(dest->GetService ());
|
||||
}
|
||||
if (m_AddressCacheUpdateTimer)
|
||||
{
|
||||
m_AddressCacheUpdateTimer->expires_from_now (boost::posix_time::seconds(ADDRESS_CACHE_UPDATE_INTERVAL ));
|
||||
m_AddressCacheUpdateTimer->async_wait (
|
||||
[this](const boost::system::error_code& ecode)
|
||||
{
|
||||
if (ecode != boost::asio::error::operation_aborted)
|
||||
{
|
||||
if (m_Storage) m_Storage->CleanUpCache ();
|
||||
ScheduleCacheUpdate ();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
AddressBookSubscription::AddressBookSubscription (AddressBook& book, std::string_view link):
|
||||
m_Book (book), m_Link (link)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -34,9 +34,7 @@ namespace client
|
||||
const int CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT = 720; // in minutes (12 hours)
|
||||
const int CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT = 5; // in minutes
|
||||
const int CONTINIOUS_SUBSCRIPTION_MAX_NUM_RETRIES = 10; // then update timeout
|
||||
const int SUBSCRIPTION_REQUEST_TIMEOUT = 120; //in seconds
|
||||
const int ADDRESS_CACHE_EXPIRATION_TIMEOUT = 710; // in seconds
|
||||
const int ADDRESS_CACHE_UPDATE_INTERVAL = 76; // in seconds
|
||||
const int SUBSCRIPTION_REQUEST_TIMEOUT = 120; //in second
|
||||
|
||||
const uint16_t ADDRESS_RESOLVER_DATAGRAM_PORT = 53;
|
||||
const uint16_t ADDRESS_RESPONSE_DATAGRAM_PORT = 54;
|
||||
@@ -49,7 +47,7 @@ namespace client
|
||||
i2p::data::IdentHash identHash;
|
||||
std::shared_ptr<i2p::data::BlindedPublicKey> blindedPublicKey;
|
||||
|
||||
Address (std::string_view b32);
|
||||
Address (const std::string& b32);
|
||||
Address (const i2p::data::IdentHash& hash);
|
||||
bool IsIdentHash () const { return addressType == eAddressIndentHash; };
|
||||
bool IsValid () const { return addressType != eAddressInvalid; };
|
||||
@@ -61,18 +59,15 @@ namespace client
|
||||
{
|
||||
public:
|
||||
|
||||
typedef std::map<std::string, std::shared_ptr<Address>, std::less<> > Addresses;
|
||||
|
||||
virtual ~AddressBookStorage () {};
|
||||
virtual std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) = 0;
|
||||
virtual std::shared_ptr<const i2p::data::IdentityEx> GetAddress (const i2p::data::IdentHash& ident) const = 0;
|
||||
virtual void AddAddress (std::shared_ptr<const i2p::data::IdentityEx> address) = 0;
|
||||
virtual void RemoveAddress (const i2p::data::IdentHash& ident) = 0;
|
||||
virtual void CleanUpCache () = 0;
|
||||
|
||||
virtual bool Init () = 0;
|
||||
virtual int Load (Addresses& addresses) = 0;
|
||||
virtual int LoadLocal (Addresses& addresses) = 0;
|
||||
virtual int Save (const Addresses& addresses) = 0;
|
||||
virtual int Load (std::map<std::string, std::shared_ptr<Address> >& addresses) = 0;
|
||||
virtual int LoadLocal (std::map<std::string, std::shared_ptr<Address> >& addresses) = 0;
|
||||
virtual int Save (const std::map<std::string, std::shared_ptr<Address> >& addresses) = 0;
|
||||
|
||||
virtual void SaveEtag (const i2p::data::IdentHash& subscription, const std::string& etag, const std::string& lastModified) = 0;
|
||||
virtual bool GetEtag (const i2p::data::IdentHash& subscription, std::string& etag, std::string& lastModified) = 0;
|
||||
@@ -84,16 +79,16 @@ namespace client
|
||||
class AddressBook
|
||||
{
|
||||
public:
|
||||
|
||||
|
||||
AddressBook ();
|
||||
~AddressBook ();
|
||||
void Start ();
|
||||
void StartResolvers ();
|
||||
void Stop ();
|
||||
std::shared_ptr<const Address> GetAddress (std::string_view address);
|
||||
std::shared_ptr<const Address> GetAddress (const std::string& address);
|
||||
std::shared_ptr<const i2p::data::IdentityEx> GetFullAddress (const std::string& address);
|
||||
std::shared_ptr<const Address> FindAddress (std::string_view address);
|
||||
void LookupAddress (std::string_view address);
|
||||
std::shared_ptr<const Address> FindAddress (const std::string& address);
|
||||
void LookupAddress (const std::string& address);
|
||||
void InsertAddress (const std::string& address, const std::string& jump); // for jump links
|
||||
void InsertFullAddress (std::shared_ptr<const i2p::data::IdentityEx> address);
|
||||
|
||||
@@ -123,12 +118,10 @@ namespace client
|
||||
void StopLookups ();
|
||||
void HandleLookupResponse (const i2p::data::IdentityEx& from, uint16_t fromPort, uint16_t toPort, const uint8_t * buf, size_t len);
|
||||
|
||||
void ScheduleCacheUpdate ();
|
||||
|
||||
private:
|
||||
|
||||
std::mutex m_AddressBookMutex;
|
||||
AddressBookStorage::Addresses m_Addresses;
|
||||
std::map<std::string, std::shared_ptr<Address> > m_Addresses;
|
||||
std::map<i2p::data::IdentHash, std::shared_ptr<AddressResolver> > m_Resolvers; // local destination->resolver
|
||||
std::mutex m_LookupsMutex;
|
||||
std::map<uint32_t, std::string> m_Lookups; // nonce -> address
|
||||
@@ -138,7 +131,7 @@ namespace client
|
||||
int m_NumRetries;
|
||||
std::vector<std::shared_ptr<AddressBookSubscription> > m_Subscriptions;
|
||||
std::shared_ptr<AddressBookSubscription> m_DefaultSubscription; // in case if we don't know any addresses yet
|
||||
std::unique_ptr<boost::asio::deadline_timer> m_SubscriptionsUpdateTimer, m_AddressCacheUpdateTimer;
|
||||
boost::asio::deadline_timer * m_SubscriptionsUpdateTimer;
|
||||
bool m_IsEnabled;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -416,10 +416,15 @@ namespace client
|
||||
|
||||
void ClientContext::CreateNewSharedLocalDestination ()
|
||||
{
|
||||
std::map<std::string, std::string> params;
|
||||
ReadI2CPOptionsFromConfig ("shareddest.", params);
|
||||
params[I2CP_PARAM_OUTBOUND_NICKNAME] = "SharedDest";
|
||||
|
||||
std::map<std::string, std::string> params
|
||||
{
|
||||
{ I2CP_PARAM_INBOUND_TUNNELS_QUANTITY, "3" },
|
||||
{ I2CP_PARAM_OUTBOUND_TUNNELS_QUANTITY, "3" },
|
||||
{ I2CP_PARAM_LEASESET_TYPE, "3" },
|
||||
{ I2CP_PARAM_LEASESET_ENCRYPTION_TYPE, "0,4" },
|
||||
{ I2CP_PARAM_OUTBOUND_NICKNAME, "SharedDest" },
|
||||
{ I2CP_PARAM_STREAMING_PROFILE, "2" }
|
||||
};
|
||||
m_SharedLocalDestination = CreateNewLocalDestination (false, i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519,
|
||||
i2p::data::CRYPTO_KEY_TYPE_ELGAMAL, ¶ms); // non-public, EDDSA
|
||||
m_SharedLocalDestination->Acquire ();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -60,7 +60,7 @@ namespace proxy {
|
||||
"</head>\r\n"
|
||||
;
|
||||
|
||||
static bool str_rmatch(std::string_view str, const char *suffix)
|
||||
static bool str_rmatch(std::string & str, const char *suffix)
|
||||
{
|
||||
auto pos = str.rfind (suffix);
|
||||
if (pos == std::string::npos)
|
||||
@@ -84,16 +84,16 @@ namespace proxy {
|
||||
void SentHTTPFailed(const boost::system::error_code & ecode);
|
||||
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
|
||||
/* error helpers */
|
||||
void GenericProxyError(std::string_view title, std::string_view description);
|
||||
void GenericProxyInfo(std::string_view title, std::string_view description);
|
||||
void HostNotFound(std::string_view host);
|
||||
void SendProxyError(std::string_view content);
|
||||
void GenericProxyError(const std::string& title, const std::string& description);
|
||||
void GenericProxyInfo(const std::string& title, const std::string& description);
|
||||
void HostNotFound(const std::string& host);
|
||||
void SendProxyError(const std::string& content);
|
||||
void SendRedirect(const std::string& address);
|
||||
|
||||
void ForwardToUpstreamProxy();
|
||||
void HandleUpstreamHTTPProxyConnect(const boost::system::error_code & ec);
|
||||
void HandleUpstreamSocksProxyConnect(const boost::system::error_code & ec);
|
||||
void HTTPConnect(std::string_view host, uint16_t port);
|
||||
void HTTPConnect(const std::string & host, uint16_t port);
|
||||
void HandleHTTPConnectStreamRequestComplete(std::shared_ptr<i2p::stream::Stream> stream);
|
||||
|
||||
typedef std::function<void(boost::asio::ip::tcp::endpoint)> ProxyResolvedHandler;
|
||||
@@ -162,23 +162,23 @@ namespace proxy {
|
||||
Done(shared_from_this());
|
||||
}
|
||||
|
||||
void HTTPReqHandler::GenericProxyError(std::string_view title, std::string_view description)
|
||||
{
|
||||
void HTTPReqHandler::GenericProxyError(const std::string& title, const std::string& description) {
|
||||
std::stringstream ss;
|
||||
ss << "<h1>" << tr("Proxy error") << ": " << title << "</h1>\r\n";
|
||||
ss << "<p>" << description << "</p>\r\n";
|
||||
SendProxyError(ss.str ());
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::GenericProxyInfo(std::string_view title, std::string_view description)
|
||||
{
|
||||
void HTTPReqHandler::GenericProxyInfo(const std::string& title, const std::string& description) {
|
||||
std::stringstream ss;
|
||||
ss << "<h1>" << tr("Proxy info") << ": " << title << "</h1>\r\n";
|
||||
ss << "<p>" << description << "</p>\r\n";
|
||||
SendProxyError(ss.str ());
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HostNotFound(std::string_view host)
|
||||
void HTTPReqHandler::HostNotFound(const std::string& host)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << "<h1>" << tr("Proxy error: Host not found") << "</h1>\r\n"
|
||||
@@ -192,10 +192,11 @@ namespace proxy {
|
||||
ss << " <li><a href=\"" << js->second << host << "\">" << js->first << "</a></li>\r\n";
|
||||
}
|
||||
ss << "</ul>\r\n";
|
||||
SendProxyError(ss.str ());
|
||||
std::string content = ss.str();
|
||||
SendProxyError(content);
|
||||
}
|
||||
|
||||
void HTTPReqHandler::SendProxyError(std::string_view content)
|
||||
void HTTPReqHandler::SendProxyError(const std::string& content)
|
||||
{
|
||||
i2p::http::HTTPRes res;
|
||||
res.code = 500;
|
||||
@@ -472,7 +473,7 @@ namespace proxy {
|
||||
if (dest_host != "")
|
||||
{
|
||||
/* absolute url, replace 'Host' header */
|
||||
std::string h (dest_host);
|
||||
std::string h = dest_host;
|
||||
if (dest_port != 0 && dest_port != 80)
|
||||
h += ":" + std::to_string(dest_port);
|
||||
m_ClientRequest.UpdateHeader("Host", h);
|
||||
@@ -512,7 +513,7 @@ namespace proxy {
|
||||
GenericProxyError(tr("Outproxy failure"), tr("Bad outproxy settings"));
|
||||
} else {
|
||||
LogPrint (eLogWarning, "HTTPProxy: Outproxy failure for ", dest_host, ": no outproxy enabled");
|
||||
std::stringstream ss; ss << tr("Host %s is not inside I2P network, but outproxy is not enabled", dest_host.c_str ());
|
||||
std::stringstream ss; ss << tr("Host %s is not inside I2P network, but outproxy is not enabled", dest_host.c_str());
|
||||
GenericProxyError(tr("Outproxy failure"), ss.str());
|
||||
}
|
||||
return true;
|
||||
@@ -652,10 +653,11 @@ namespace proxy {
|
||||
Terminate();
|
||||
}
|
||||
|
||||
void HTTPReqHandler::HTTPConnect(std::string_view host, uint16_t port)
|
||||
void HTTPReqHandler::HTTPConnect(const std::string & host, uint16_t port)
|
||||
{
|
||||
LogPrint(eLogDebug, "HTTPProxy: CONNECT ",host, ":", port);
|
||||
if(str_rmatch(host, ".i2p"))
|
||||
std::string hostname(host);
|
||||
if(str_rmatch(hostname, ".i2p"))
|
||||
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleHTTPConnectStreamRequestComplete,
|
||||
shared_from_this(), std::placeholders::_1), host, port);
|
||||
else
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -555,20 +555,20 @@ namespace client
|
||||
m_IsSending = false;
|
||||
}
|
||||
|
||||
std::string_view I2CPSession::ExtractString (const uint8_t * buf, size_t len)
|
||||
std::string I2CPSession::ExtractString (const uint8_t * buf, size_t len)
|
||||
{
|
||||
uint8_t l = buf[0];
|
||||
if (l > len) l = len;
|
||||
return { (const char *)(buf + 1), l };
|
||||
return std::string ((const char *)(buf + 1), l);
|
||||
}
|
||||
|
||||
size_t I2CPSession::PutString (uint8_t * buf, size_t len, std::string_view str)
|
||||
size_t I2CPSession::PutString (uint8_t * buf, size_t len, const std::string& str)
|
||||
{
|
||||
auto l = str.length ();
|
||||
if (l + 1 >= len) l = len - 1;
|
||||
if (l > 255) l = 255; // 1 byte max
|
||||
buf[0] = l;
|
||||
memcpy (buf + 1, str.data (), l);
|
||||
memcpy (buf + 1, str.c_str (), l);
|
||||
return l + 1;
|
||||
}
|
||||
|
||||
@@ -578,7 +578,7 @@ namespace client
|
||||
size_t offset = 0;
|
||||
while (offset < len)
|
||||
{
|
||||
auto param = ExtractString (buf + offset, len - offset);
|
||||
std::string param = ExtractString (buf + offset, len - offset);
|
||||
offset += param.length () + 1;
|
||||
if (buf[offset] != '=')
|
||||
{
|
||||
@@ -587,7 +587,7 @@ namespace client
|
||||
}
|
||||
offset++;
|
||||
|
||||
auto value = ExtractString (buf + offset, len - offset);
|
||||
std::string value = ExtractString (buf + offset, len - offset);
|
||||
offset += value.length () + 1;
|
||||
if (buf[offset] != ';')
|
||||
{
|
||||
@@ -595,7 +595,7 @@ namespace client
|
||||
break;
|
||||
}
|
||||
offset++;
|
||||
mapping.emplace (param, value);
|
||||
mapping.insert (std::make_pair (param, value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -764,7 +764,6 @@ namespace client
|
||||
void I2CPSession::AddRoutingSession (const i2p::data::IdentHash& signingKey, std::shared_ptr<i2p::garlic::GarlicRoutingSession> remoteSession)
|
||||
{
|
||||
if (!remoteSession) return;
|
||||
remoteSession->SetAckRequestInterval (I2CP_SESSION_ACK_REQUEST_INTERVAL);
|
||||
std::lock_guard<std::mutex> l(m_RoutingSessionsMutex);
|
||||
m_RoutingSessions[signingKey] = remoteSession;
|
||||
}
|
||||
@@ -880,7 +879,7 @@ namespace client
|
||||
if (!remoteSession || !m_Destination->SendMsg (buf + offset, payloadLen, remoteSession, nonce))
|
||||
{
|
||||
i2p::data::IdentHash identHash;
|
||||
SHA256(ident, identSize, identHash); // calculate ident hash, because we don't need full identity
|
||||
SHA256(ident, identSize, identHash); // caclulate ident hash, because we don't need full identity
|
||||
m_Destination->SendMsgTo (buf + offset, payloadLen, identHash, nonce);
|
||||
}
|
||||
}
|
||||
@@ -1111,12 +1110,12 @@ namespace client
|
||||
void I2CPServer::Stop ()
|
||||
{
|
||||
m_Acceptor.cancel ();
|
||||
|
||||
decltype(m_Sessions) sessions;
|
||||
m_Sessions.swap (sessions);
|
||||
for (auto& it: sessions)
|
||||
it.second->Stop ();
|
||||
|
||||
{
|
||||
auto sessions = m_Sessions;
|
||||
for (auto& it: sessions)
|
||||
it.second->Stop ();
|
||||
}
|
||||
m_Sessions.clear ();
|
||||
StopIOService ();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
#include <inttypes.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
@@ -31,7 +30,6 @@ namespace client
|
||||
const size_t I2CP_MAX_MESSAGE_LENGTH = 65535;
|
||||
const size_t I2CP_MAX_SEND_QUEUE_SIZE = 1024*1024; // in bytes, 1M
|
||||
const int I2CP_LEASESET_CREATION_TIMEOUT = 10; // in seconds
|
||||
const int I2CP_SESSION_ACK_REQUEST_INTERVAL = 12100; // in milliseconds
|
||||
|
||||
const size_t I2CP_HEADER_LENGTH_OFFSET = 0;
|
||||
const size_t I2CP_HEADER_TYPE_OFFSET = I2CP_HEADER_LENGTH_OFFSET + 4;
|
||||
@@ -193,8 +191,8 @@ 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);
|
||||
size_t PutString (uint8_t * buf, size_t len, std::string_view str);
|
||||
std::string ExtractString (const uint8_t * buf, size_t len);
|
||||
size_t PutString (uint8_t * buf, size_t len, const std::string& str);
|
||||
void ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping);
|
||||
void SendSessionStatusMessage (I2CPSessionStatus status);
|
||||
void SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -107,7 +107,7 @@ namespace client
|
||||
m_ReadyTimerTriggered = false;
|
||||
}
|
||||
|
||||
void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, std::string_view dest, uint16_t port) {
|
||||
void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, uint16_t port) {
|
||||
assert(streamRequestComplete);
|
||||
auto address = i2p::client::context.GetAddressBook ().GetAddress (dest);
|
||||
if (address)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -59,7 +59,7 @@ namespace client
|
||||
if (dest) dest->Acquire ();
|
||||
m_LocalDestination = dest;
|
||||
}
|
||||
void CreateStream (StreamRequestComplete streamRequestComplete, std::string_view dest, uint16_t port = 0);
|
||||
void CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, uint16_t port = 0);
|
||||
void CreateStream(StreamRequestComplete complete, std::shared_ptr<const Address> address, uint16_t port);
|
||||
auto& GetService () { return m_LocalDestination->GetService (); }
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2013-2025, The PurpleI2P Project
|
||||
* Copyright (c) 2013-2024, The PurpleI2P Project
|
||||
*
|
||||
* This file is part of Purple i2pd project and licensed under BSD3
|
||||
*
|
||||
@@ -1350,14 +1350,12 @@ namespace client
|
||||
LogPrint (eLogError, "SAM: Runtime exception: ", ex.what ());
|
||||
}
|
||||
|
||||
decltype(m_Sessions) sessions;
|
||||
{
|
||||
std::unique_lock<std::mutex> l(m_SessionsMutex);
|
||||
m_Sessions.swap (sessions);
|
||||
}
|
||||
for (auto& it: sessions)
|
||||
it.second->Close ();
|
||||
|
||||
for (auto& it: m_Sessions)
|
||||
it.second->Close ();
|
||||
m_Sessions.clear ();
|
||||
}
|
||||
StopIOService ();
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ namespace client
|
||||
}
|
||||
else
|
||||
{
|
||||
LogPrint(eLogWarning, "UDPServer: Session with from ", remotePort, " and to ", localPort, " ports already exists. But from different address. Removed");
|
||||
LogPrint(eLogWarning, "UDPServer: Session with from ", remotePort, " and to ", localPort, " ports already exists. But from differend address. Removed");
|
||||
m_Sessions.erase (it);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,10 +65,6 @@ set(test-eddsa_SRCS
|
||||
test-eddsa.cpp
|
||||
)
|
||||
|
||||
set(test-aes_SRCS
|
||||
test-aes.cpp
|
||||
)
|
||||
|
||||
add_executable(test-http-merge_chunked ${test-http-merge_chunked_SRCS})
|
||||
add_executable(test-http-req ${test-http-req_SRCS})
|
||||
add_executable(test-http-res ${test-http-res_SRCS})
|
||||
@@ -81,7 +77,6 @@ add_executable(test-aeadchacha20poly1305 ${test-aeadchacha20poly1305_SRCS})
|
||||
add_executable(test-blinding ${test-blinding_SRCS})
|
||||
add_executable(test-elligator ${test-elligator_SRCS})
|
||||
add_executable(test-eddsa ${test-eddsa_SRCS})
|
||||
add_executable(test-aes ${test-aes_SRCS})
|
||||
|
||||
set(LIBS
|
||||
libi2pd
|
||||
@@ -106,7 +101,6 @@ target_link_libraries(test-aeadchacha20poly1305 ${LIBS})
|
||||
target_link_libraries(test-blinding ${LIBS})
|
||||
target_link_libraries(test-elligator ${LIBS})
|
||||
target_link_libraries(test-eddsa ${LIBS})
|
||||
target_link_libraries(test-aes ${LIBS})
|
||||
|
||||
add_test(test-http-merge_chunked ${TEST_PATH}/test-http-merge_chunked)
|
||||
add_test(test-http-req ${TEST_PATH}/test-http-req)
|
||||
@@ -120,4 +114,3 @@ add_test(test-aeadchacha20poly1305 ${TEST_PATH}/test-aeadchacha20poly1305)
|
||||
add_test(test-blinding ${TEST_PATH}/test-blinding)
|
||||
add_test(test-elligator ${TEST_PATH}/test-elligator)
|
||||
add_test(test-eddsa ${TEST_PATH}/test-eddsa)
|
||||
add_test(test-aes ${TEST_PATH}/test-aes)
|
||||
|
||||
@@ -8,7 +8,7 @@ LIBI2PD = ../libi2pd.a
|
||||
TESTS = \
|
||||
test-http-merge_chunked test-http-req test-http-res test-http-url test-http-url_decode \
|
||||
test-gost test-gost-sig test-base-64 test-aeadchacha20poly1305 test-blinding \
|
||||
test-elligator test-eddsa test-aes
|
||||
test-elligator test-eddsa
|
||||
|
||||
ifneq (, $(findstring mingw, $(SYS))$(findstring windows-gnu, $(SYS))$(findstring cygwin, $(SYS)))
|
||||
CXXFLAGS += -DWIN32_LEAN_AND_MEAN
|
||||
@@ -56,9 +56,6 @@ test-elligator: test-elligator.cpp $(LIBI2PD)
|
||||
test-eddsa: test-eddsa.cpp $(LIBI2PD)
|
||||
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
|
||||
|
||||
test-aes: test-aes.cpp $(LIBI2PD)
|
||||
$(CXX) $(CXXFLAGS) $(NEEDED_CXXFLAGS) $(INCFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
|
||||
|
||||
run: $(TESTS)
|
||||
@for TEST in $(TESTS); do echo Running $$TEST; ./$$TEST ; done
|
||||
|
||||
|
||||
@@ -43,20 +43,18 @@ uint8_t encrypted[114] =
|
||||
int main ()
|
||||
{
|
||||
uint8_t buf[114+16];
|
||||
i2p::crypto::AEADChaCha20Poly1305Encryptor encryptor;
|
||||
// test encryption
|
||||
encryptor.Encrypt ((uint8_t *)text, 114, ad, 12, key, nonce, buf, 114 + 16);
|
||||
i2p::crypto::AEADChaCha20Poly1305 ((uint8_t *)text, 114, ad, 12, key, nonce, buf, 114 + 16, true);
|
||||
assert (memcmp (buf, encrypted, 114) == 0);
|
||||
assert (memcmp (buf + 114, tag, 16) == 0);
|
||||
// test decryption
|
||||
uint8_t buf1[114];
|
||||
i2p::crypto::AEADChaCha20Poly1305Decryptor decryptor;
|
||||
assert (decryptor.Decrypt (buf, 114, ad, 12, key, nonce, buf1, 114));
|
||||
assert (i2p::crypto::AEADChaCha20Poly1305 (buf, 114, ad, 12, key, nonce, buf1, 114, false));
|
||||
assert (memcmp (buf1, text, 114) == 0);
|
||||
// test encryption of multiple buffers
|
||||
memcpy (buf, text, 114);
|
||||
std::vector<std::pair<uint8_t*, std::size_t> > bufs{ std::make_pair (buf, 20), std::make_pair (buf + 20, 10), std::make_pair (buf + 30, 70), std::make_pair (buf + 100, 14) };
|
||||
encryptor.Encrypt (bufs, key, nonce, buf + 114);
|
||||
decryptor.Decrypt (buf, 114, nullptr, 0, key, nonce, buf1, 114);
|
||||
i2p::crypto::AEADChaCha20Poly1305Encrypt (bufs, key, nonce, buf + 114);
|
||||
i2p::crypto::AEADChaCha20Poly1305 (buf, 114, nullptr, 0, key, nonce, buf1, 114, false);
|
||||
assert (memcmp (buf1, text, 114) == 0);
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
#include <cassert>
|
||||
#include <inttypes.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "Crypto.h"
|
||||
|
||||
uint8_t ecb_key1[32] =
|
||||
{
|
||||
0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
|
||||
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4
|
||||
};
|
||||
|
||||
uint8_t ecb_plain1[16] =
|
||||
{
|
||||
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a
|
||||
};
|
||||
|
||||
uint8_t ecb_cipher1[16] =
|
||||
{
|
||||
0xf3, 0xee, 0xd1, 0xbd, 0xb5, 0xd2, 0xa0, 0x3c, 0x06, 0x4b, 0x5a, 0x7e, 0x3d, 0xb1, 0x81, 0xf8
|
||||
};
|
||||
|
||||
uint8_t cbc_key1[32] =
|
||||
{
|
||||
0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
|
||||
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4
|
||||
};
|
||||
|
||||
uint8_t cbc_iv1[16] =
|
||||
{
|
||||
0xF5, 0x8C, 0x4C, 0x04, 0xD6, 0xE5, 0xF1, 0xBA, 0x77, 0x9E, 0xAB, 0xFB, 0x5F, 0x7B, 0xFB, 0xD6
|
||||
};
|
||||
|
||||
uint8_t cbc_plain1[16] =
|
||||
{
|
||||
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51
|
||||
};
|
||||
|
||||
uint8_t cbc_cipher1[16] =
|
||||
{
|
||||
0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d
|
||||
};
|
||||
|
||||
int main ()
|
||||
{
|
||||
// ECB encrypt test1
|
||||
i2p::crypto::ECBEncryption ecbencryption;
|
||||
ecbencryption.SetKey (ecb_key1);
|
||||
uint8_t out[16];
|
||||
ecbencryption.Encrypt (ecb_plain1, out);
|
||||
assert (memcmp (ecb_cipher1, out, 16) == 0);
|
||||
|
||||
// ECB decrypt test1
|
||||
i2p::crypto::ECBDecryption ecbdecryption;
|
||||
ecbdecryption.SetKey (ecb_key1);
|
||||
ecbdecryption.Decrypt (ecb_cipher1, out);
|
||||
assert (memcmp (ecb_plain1, out, 16) == 0);
|
||||
// CBC encrypt test
|
||||
i2p::crypto::CBCEncryption cbcencryption;
|
||||
cbcencryption.SetKey (cbc_key1);
|
||||
cbcencryption.Encrypt (cbc_plain1, 16, cbc_iv1, out);
|
||||
assert (memcmp (cbc_cipher1, out, 16) == 0);
|
||||
// CBC decrypt test
|
||||
i2p::crypto::CBCDecryption cbcdecryption;
|
||||
cbcdecryption.SetKey (cbc_key1);
|
||||
cbcdecryption.Decrypt (cbc_cipher1, 16, cbc_iv1, out);
|
||||
assert (memcmp (cbc_plain1, out, 16) == 0);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user