Skip to content

Commit 77f0ceb

Browse files
committed
Merge bitcoin#28077: I2P: also sleep after errors in Accept() & destroy the session if we get an unexpected error
5c8e15c i2p: destroy the session if we get an unexpected error from the I2P router (Vasil Dimov) 762404a i2p: also sleep after errors in Accept() (Vasil Dimov) Pull request description: ### Background In the `i2p::sam::Session` class: `Listen()` does: * if the session is not created yet * create the control socket and on it: * `HELLO` * `SESSION CREATE ID=sessid` * leave the control socked opened * create a new socket and on it: * `HELLO` * `STREAM ACCEPT ID=sessid` * read reply (`STREAM STATUS`), `Listen()` only succeeds if it contains `RESULT=OK` Then a wait starts, for a peer to connect. When connected, `Accept()` does: * on the socket from `STREAM ACCEPT` from `Listen()`: read the Base64 identification of the connecting peer ### Problem The I2P router may be in such a state that this happens in a quick succession (many times per second, see bitcoin#22759 (comment)): `Listen()`-succeeds, `Accept()`-fails. `Accept()` fails because the I2P router sends something that is not Base64 on the socket: `STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"` We only sleep after failed `Listen()` because the assumption was that if `Accept()` fails then the next `Listen()` will also fail. ### Solution Avoid filling the log with "Error accepting:" messages and sleep also after a failed `Accept()`. ### Extra changes * Reset the error waiting time after one successful connection. Otherwise the timer will remain high due to problems that have been solved long time in the past. * Increment the wait time less aggressively. * Handle the unexpected "Session was closed" message more gracefully (don't log stupid messages like `Cannot decode Base64: "STREAM STATUS...`) and destroy the session right way. ACKs for top commit: achow101: ACK 5c8e15c jonatack: re-ACK 5c8e15c Tree-SHA512: 1d47958c50eeae9eefcb668b8539fd092adead93328e4bf3355267819304b99ab41cbe1b5dbedbc3452c2bc389dc8330c0e27eb5ccb880e33dc46930a1592885
2 parents 0655e9d + 5c8e15c commit 77f0ceb

File tree

4 files changed

+148
-30
lines changed

4 files changed

+148
-30
lines changed

src/i2p.cpp

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <netaddress.h>
1313
#include <netbase.h>
1414
#include <random.h>
15+
#include <sync.h>
1516
#include <tinyformat.h>
1617
#include <util/fs.h>
1718
#include <util/readwritefile.h>
@@ -153,27 +154,59 @@ bool Session::Listen(Connection& conn)
153154

154155
bool Session::Accept(Connection& conn)
155156
{
156-
try {
157-
while (!*m_interrupt) {
158-
Sock::Event occurred;
159-
if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
160-
throw std::runtime_error("wait on socket failed");
161-
}
157+
AssertLockNotHeld(m_mutex);
162158

163-
if (occurred == 0) {
164-
// Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
165-
continue;
166-
}
159+
std::string errmsg;
160+
bool disconnect{false};
167161

168-
const std::string& peer_dest =
169-
conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
162+
while (!*m_interrupt) {
163+
Sock::Event occurred;
164+
if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
165+
errmsg = "wait on socket failed";
166+
break;
167+
}
170168

171-
conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);
169+
if (occurred == 0) {
170+
// Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
171+
continue;
172+
}
172173

173-
return true;
174+
std::string peer_dest;
175+
try {
176+
peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
177+
} catch (const std::runtime_error& e) {
178+
errmsg = e.what();
179+
break;
174180
}
175-
} catch (const std::runtime_error& e) {
176-
Log("Error accepting: %s", e.what());
181+
182+
CNetAddr peer_addr;
183+
try {
184+
peer_addr = DestB64ToAddr(peer_dest);
185+
} catch (const std::runtime_error& e) {
186+
// The I2P router is expected to send the Base64 of the connecting peer,
187+
// but it may happen that something like this is sent instead:
188+
// STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"
189+
// In that case consider the session damaged and close it right away,
190+
// even if the control socket is alive.
191+
if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) {
192+
errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest);
193+
disconnect = true;
194+
} else {
195+
errmsg = e.what();
196+
}
197+
break;
198+
}
199+
200+
conn.peer = CService(peer_addr, I2P_SAM31_PORT);
201+
202+
return true;
203+
}
204+
205+
Log("Error accepting%s: %s", disconnect ? " (will close the session)" : "", errmsg);
206+
if (disconnect) {
207+
LOCK(m_mutex);
208+
Disconnect();
209+
} else {
177210
CheckControlSock();
178211
}
179212
return false;

src/i2p.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ class Session
105105
* completion the `peer` member will be set to the address of the incoming peer.
106106
* @return true on success
107107
*/
108-
bool Accept(Connection& conn);
108+
bool Accept(Connection& conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
109109

110110
/**
111111
* Connect to an I2P peer.

src/net.cpp

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2928,19 +2928,21 @@ void CConnman::ThreadI2PAcceptIncoming()
29282928
bool advertising_listen_addr = false;
29292929
i2p::Connection conn;
29302930

2931+
auto SleepOnFailure = [&]() {
2932+
interruptNet.sleep_for(err_wait);
2933+
if (err_wait < err_wait_cap) {
2934+
err_wait += 1s;
2935+
}
2936+
};
2937+
29312938
while (!interruptNet) {
29322939

29332940
if (!m_i2p_sam_session->Listen(conn)) {
29342941
if (advertising_listen_addr && conn.me.IsValid()) {
29352942
RemoveLocal(conn.me);
29362943
advertising_listen_addr = false;
29372944
}
2938-
2939-
interruptNet.sleep_for(err_wait);
2940-
if (err_wait < err_wait_cap) {
2941-
err_wait *= 2;
2942-
}
2943-
2945+
SleepOnFailure();
29442946
continue;
29452947
}
29462948

@@ -2950,11 +2952,14 @@ void CConnman::ThreadI2PAcceptIncoming()
29502952
}
29512953

29522954
if (!m_i2p_sam_session->Accept(conn)) {
2955+
SleepOnFailure();
29532956
continue;
29542957
}
29552958

29562959
CreateNodeFromAcceptedSocket(std::move(conn.sock), NetPermissionFlags::None,
29572960
CAddress{conn.me, NODE_NONE}, CAddress{conn.peer, NODE_NONE});
2961+
2962+
err_wait = err_wait_begin;
29582963
}
29592964
}
29602965

src/test/i2p_tests.cpp

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,34 @@
1616
#include <memory>
1717
#include <string>
1818

19-
BOOST_FIXTURE_TEST_SUITE(i2p_tests, BasicTestingSetup)
19+
/// Save the log level and the value of CreateSock and restore them when the test ends.
20+
class EnvTestingSetup : public BasicTestingSetup
21+
{
22+
public:
23+
explicit EnvTestingSetup(const ChainType chainType = ChainType::MAIN,
24+
const std::vector<const char*>& extra_args = {})
25+
: BasicTestingSetup{chainType, extra_args},
26+
m_prev_log_level{LogInstance().LogLevel()},
27+
m_create_sock_orig{CreateSock}
28+
{
29+
LogInstance().SetLogLevel(BCLog::Level::Trace);
30+
}
31+
32+
~EnvTestingSetup()
33+
{
34+
CreateSock = m_create_sock_orig;
35+
LogInstance().SetLogLevel(m_prev_log_level);
36+
}
37+
38+
private:
39+
const BCLog::Level m_prev_log_level;
40+
const std::function<std::unique_ptr<Sock>(const CService&)> m_create_sock_orig;
41+
};
42+
43+
BOOST_FIXTURE_TEST_SUITE(i2p_tests, EnvTestingSetup)
2044

2145
BOOST_AUTO_TEST_CASE(unlimited_recv)
2246
{
23-
const auto prev_log_level{LogInstance().LogLevel()};
24-
LogInstance().SetLogLevel(BCLog::Level::Trace);
25-
auto CreateSockOrig = CreateSock;
26-
2747
// Mock CreateSock() to create MockSock.
2848
CreateSock = [](const CService&) {
2949
return std::make_unique<StaticContentsSock>(std::string(i2p::sam::MAX_MSG_SIZE + 1, 'a'));
@@ -40,9 +60,69 @@ BOOST_AUTO_TEST_CASE(unlimited_recv)
4060
bool proxy_error;
4161
BOOST_REQUIRE(!session.Connect(CService{}, conn, proxy_error));
4262
}
63+
}
64+
65+
BOOST_AUTO_TEST_CASE(listen_ok_accept_fail)
66+
{
67+
size_t num_sockets{0};
68+
CreateSock = [&num_sockets](const CService&) {
69+
// clang-format off
70+
++num_sockets;
71+
// First socket is the control socket for creating the session.
72+
if (num_sockets == 1) {
73+
return std::make_unique<StaticContentsSock>(
74+
// reply to HELLO
75+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
76+
// reply to DEST GENERATE
77+
"DEST REPLY PUB=WnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqLE4SD-yjT48UNI7qiTUfIPiDitCoiTTz2cr4QGfw89rBQAEAAcAAA== PRIV=WnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8BnNlaZbWtSoWnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqLE4SD-yjT48UNI7qiTUfIPiDitCoiTTz2cr4QGfw89rBQAEAAcAAOvuCIKTyv5f~1QgGq7XQl-IqBULTB5WzB3gw5yGPtd1p0AeoADrq1ccZggLPQ4ZLUsGK-HVw373rcTfvxrcuwenqVjiN4tbbYLWtP7xXGWj6fM6HyORhU63GphrjEePpMUHDHXd3o7pWGM-ieVVQSK~1MzF9P93pQWI3Do52EeNAayz4HbpPjNhVBzG1hUEFwznfPmUZBPuaOR4-uBm1NEWEuONlNOCctE4-U0Ukh94z-Qb55U5vXjR5G4apmBblr68t6Wm1TKlzpgFHzSqLryh3stWqrOKY1H0z9eZ2z1EkHFOpD5LyF6nf51e-lV7HLMl44TYzoEHK8RRVodtLcW9lacVdBpv~tOzlZERIiDziZODPETENZMz5oy9DQ7UUw==\n"
78+
// reply to SESSION CREATE
79+
"SESSION STATUS RESULT=OK\n"
80+
// dummy to avoid reporting EOF on the socket
81+
"a"
82+
);
83+
}
84+
// Subsequent sockets are for recreating the session or for listening and accepting incoming connections.
85+
if (num_sockets % 2 == 0) {
86+
// Replies to Listen() and Accept()
87+
return std::make_unique<StaticContentsSock>(
88+
// reply to HELLO
89+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
90+
// reply to STREAM ACCEPT
91+
"STREAM STATUS RESULT=OK\n"
92+
// continued reply to STREAM ACCEPT, violating the protocol described at
93+
// https://geti2p.net/en/docs/api/samv3#Accept%20Response
94+
// should be base64, something like
95+
// "IchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLlSreVaCuCS5sdb-8ToWULWP7kt~lRPDeUNxQMq3cRSBBQAEAAcAAA==\n"
96+
"STREAM STATUS RESULT=I2P_ERROR MESSAGE=\"Session was closed\"\n"
97+
);
98+
} else {
99+
// Another control socket, but without creating a destination (it is cached in the session).
100+
return std::make_unique<StaticContentsSock>(
101+
// reply to HELLO
102+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
103+
// reply to SESSION CREATE
104+
"SESSION STATUS RESULT=OK\n"
105+
// dummy to avoid reporting EOF on the socket
106+
"a"
107+
);
108+
}
109+
// clang-format on
110+
};
43111

44-
CreateSock = CreateSockOrig;
45-
LogInstance().SetLogLevel(prev_log_level);
112+
CThreadInterrupt interrupt;
113+
i2p::sam::Session session(gArgs.GetDataDirNet() / "test_i2p_private_key",
114+
CService{in6_addr(IN6ADDR_LOOPBACK_INIT), /*port=*/7656},
115+
&interrupt);
116+
117+
i2p::Connection conn;
118+
for (size_t i = 0; i < 5; ++i) {
119+
ASSERT_DEBUG_LOG("Creating persistent SAM session");
120+
ASSERT_DEBUG_LOG("Persistent SAM session" /* ... created */);
121+
ASSERT_DEBUG_LOG("Error accepting");
122+
ASSERT_DEBUG_LOG("Destroying SAM session");
123+
BOOST_REQUIRE(session.Listen(conn));
124+
BOOST_REQUIRE(!session.Accept(conn));
125+
}
46126
}
47127

48128
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)