Bitcoin ABC 0.32.4
P2P Digital Currency
i2p.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-2020 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <i2p.h>
6
7#include <chainparams.h>
8#include <common/args.h>
9#include <compat.h>
10#include <compat/endian.h>
11#include <crypto/sha256.h>
12#include <logging.h>
13#include <netaddress.h>
14#include <netbase.h>
15#include <random.h>
16#include <tinyformat.h>
17#include <util/fs.h>
18#include <util/readwritefile.h>
19#include <util/sock.h>
20#include <util/spanparsing.h>
21#include <util/strencodings.h>
23
24#include <chrono>
25#include <memory>
26#include <stdexcept>
27#include <string>
28
29namespace i2p {
30
39static std::string SwapBase64(const std::string &from) {
40 std::string to;
41 to.resize(from.size());
42 for (size_t i = 0; i < from.size(); ++i) {
43 switch (from[i]) {
44 case '-':
45 to[i] = '+';
46 break;
47 case '~':
48 to[i] = '/';
49 break;
50 case '+':
51 to[i] = '-';
52 break;
53 case '/':
54 to[i] = '~';
55 break;
56 default:
57 to[i] = from[i];
58 break;
59 }
60 }
61 return to;
62}
63
70static Binary DecodeI2PBase64(const std::string &i2p_b64) {
71 const std::string &std_b64 = SwapBase64(i2p_b64);
72 auto decoded = DecodeBase64(std_b64);
73 if (!decoded) {
74 throw std::runtime_error(
75 strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
76 }
77 return std::move(*decoded);
78}
79
86static CNetAddr DestBinToAddr(const Binary &dest) {
87 CSHA256 hasher;
88 hasher.Write(dest.data(), dest.size());
89 uint8_t hash[CSHA256::OUTPUT_SIZE];
90 hasher.Finalize(hash);
91
92 CNetAddr addr;
93 const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
94 if (!addr.SetSpecial(addr_str)) {
95 throw std::runtime_error(
96 strprintf("Cannot parse I2P address: \"%s\"", addr_str));
97 }
98
99 return addr;
100}
101
108static CNetAddr DestB64ToAddr(const std::string &dest) {
109 const Binary &decoded = DecodeI2PBase64(dest);
110 return DestBinToAddr(decoded);
111}
112
113namespace sam {
114
115 Session::Session(const fs::path &private_key_file,
116 const CService &control_host, CThreadInterrupt *interrupt)
117 : m_private_key_file(private_key_file), m_control_host(control_host),
118 m_interrupt(interrupt),
119 m_control_sock(std::make_unique<Sock>(INVALID_SOCKET)) {}
120
122 LOCK(m_mutex);
123 Disconnect();
124 }
125
127 try {
128 LOCK(m_mutex);
130 conn.me = m_my_addr;
131 conn.sock = StreamAccept();
132 return true;
133 } catch (const std::runtime_error &e) {
135 "Couldn't listen: %s\n", e.what());
137 }
138 return false;
139 }
140
142 try {
143 while (!*m_interrupt) {
144 Sock::Event occurred;
145 conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred);
146
147 if (occurred == 0) {
148 // Timeout, no incoming connections or errors within
149 // MAX_WAIT_FOR_IO.
150 continue;
151 }
152
153 const std::string &peer_dest = conn.sock->RecvUntilTerminator(
155
156 conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);
157
158 return true;
159 }
160 } catch (const std::runtime_error &e) {
161 // TODO: Improve log message as per core#29833 (commit 7d3662fbe)
162 // when backporting core#28077
164 "Error accepting: %s\n", e.what());
166 }
167 return false;
168 }
169
170 bool Session::Connect(const CService &to, Connection &conn,
171 bool &proxy_error) {
172 // Refuse connecting to arbitrary ports. We don't specify any
173 // destination port to the SAM proxy when connecting (SAM 3.1 does not
174 // use ports) and it forces/defaults it to I2P_SAM31_PORT.
175 if (to.GetPort() != I2P_SAM31_PORT) {
176 proxy_error = false;
177 return false;
178 }
179
180 proxy_error = true;
181
182 std::string session_id;
183 std::unique_ptr<Sock> sock;
184 conn.peer = to;
185
186 try {
187 {
188 LOCK(m_mutex);
190 session_id = m_session_id;
191 conn.me = m_my_addr;
192 sock = Hello();
193 }
194
195 const Reply &lookup_reply = SendRequestAndGetReply(
196 *sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringIP()));
197
198 const std::string &dest = lookup_reply.Get("VALUE");
199
200 const Reply &connect_reply = SendRequestAndGetReply(
201 *sock,
202 strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false",
203 session_id, dest),
204 false);
205
206 const std::string &result = connect_reply.Get("RESULT");
207
208 if (result == "OK") {
209 conn.sock = std::move(sock);
210 return true;
211 }
212
213 if (result == "INVALID_ID") {
214 LOCK(m_mutex);
215 Disconnect();
216 throw std::runtime_error("Invalid session id");
217 }
218
219 if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
220 proxy_error = false;
221 }
222
223 throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
224 } catch (const std::runtime_error &e) {
226 "Error connecting to %s: %s\n", to.ToString(),
227 e.what());
229 return false;
230 }
231 }
232
233 // Private methods
234
235 std::string Session::Reply::Get(const std::string &key) const {
236 const auto &pos = keys.find(key);
237 if (pos == keys.end() || !pos->second.has_value()) {
238 throw std::runtime_error(
239 strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key,
240 request, full));
241 }
242 return pos->second.value();
243 }
244
246 const std::string &request,
247 bool check_result_ok) const {
248 sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
249
250 Reply reply;
251
252 // Don't log the full "SESSION CREATE ..." because it contains our
253 // private key.
254 reply.request = request.substr(0, 14) == "SESSION CREATE"
255 ? "SESSION CREATE ..."
256 : request;
257
258 // It could take a few minutes for the I2P router to reply as it is
259 // querying the I2P network (when doing name lookup, for example).
260 // Notice: `RecvUntilTerminator()` is checking `m_interrupt` more often,
261 // so we would not be stuck here for long if `m_interrupt` is signaled.
262 static constexpr auto recv_timeout = 3min;
263
264 reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt,
266
267 for (const auto &kv : spanparsing::Split(reply.full, ' ')) {
268 const auto &pos = std::find(kv.begin(), kv.end(), '=');
269 if (pos != kv.end()) {
270 reply.keys.emplace(std::string{kv.begin(), pos},
271 std::string{pos + 1, kv.end()});
272 } else {
273 reply.keys.emplace(std::string{kv.begin(), kv.end()},
274 std::nullopt);
275 }
276 }
277
278 if (check_result_ok && reply.Get("RESULT") != "OK") {
279 throw std::runtime_error(strprintf(
280 "Unexpected reply to \"%s\": \"%s\"", request, reply.full));
281 }
282
283 return reply;
284 }
285
286 std::unique_ptr<Sock> Session::Hello() const {
287 auto sock = CreateSock(m_control_host);
288
289 if (!sock) {
290 throw std::runtime_error("Cannot create socket");
291 }
292
294 true)) {
295 throw std::runtime_error(
296 strprintf("Cannot connect to %s", m_control_host.ToString()));
297 }
298
299 SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
300
301 return sock;
302 }
303
305 LOCK(m_mutex);
306
307 std::string errmsg;
308 if (!m_control_sock->IsConnected(errmsg)) {
310 "Control socket error: %s\n", errmsg);
311 Disconnect();
312 }
313 }
314
315 void Session::DestGenerate(const Sock &sock) {
316 // https://geti2p.net/spec/common-structures#key-certificates
317 // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and
318 // Destinations". Use "7" because i2pd <2.24.0 does not recognize the
319 // textual form.
320 const Reply &reply = SendRequestAndGetReply(
321 sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
322
323 m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
324 }
325
327 DestGenerate(sock);
328
329 // umask is set to 077 in init.cpp, which is ok (unless -sysperms is
330 // given)
331 if (!WriteBinaryFile(
333 std::string(m_private_key.begin(), m_private_key.end()))) {
334 throw std::runtime_error(
335 strprintf("Cannot save I2P private key to %s",
337 }
338 }
339
341 // From https://geti2p.net/spec/common-structures#destination:
342 // "They are 387 bytes plus the certificate length specified at bytes
343 // 385-386, which may be non-zero"
344 static constexpr size_t DEST_LEN_BASE = 387;
345 static constexpr size_t CERT_LEN_POS = 385;
346
347 uint16_t cert_len;
348 memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
349 cert_len = be16toh(cert_len);
350
351 const size_t dest_len = DEST_LEN_BASE + cert_len;
352
353 return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
354 }
355
357 std::string errmsg;
358 if (m_control_sock->IsConnected(errmsg)) {
359 return;
360 }
361
363 "Creating SAM session with %s\n",
365
366 auto sock = Hello();
367
368 const auto &[read_ok, data] = ReadBinaryFile(m_private_key_file);
369 if (read_ok) {
370 m_private_key.assign(data.begin(), data.end());
371 } else {
373 }
374
375 const std::string &session_id = GetRandHash().GetHex().substr(
376 0, 10); // full is an overkill, too verbose in the logs
377 const std::string &private_key_b64 =
378 SwapBase64(EncodeBase64(m_private_key));
379
381 *sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s",
382 session_id, private_key_b64));
383
385 m_session_id = session_id;
386 m_control_sock = std::move(sock);
387
389 "SAM session created: session id=%s, my address=%s\n",
390 m_session_id, m_my_addr.ToString());
391 }
392
393 std::unique_ptr<Sock> Session::StreamAccept() {
394 auto sock = Hello();
395
396 const Reply &reply = SendRequestAndGetReply(
397 *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id),
398 false);
399
400 const std::string &result = reply.Get("RESULT");
401
402 if (result == "OK") {
403 return sock;
404 }
405
406 if (result == "INVALID_ID") {
407 // If our session id is invalid, then force session re-creation on
408 // next usage.
409 Disconnect();
410 }
411
412 throw std::runtime_error(strprintf("\"%s\"", reply.full));
413 }
414
416 if (m_control_sock->Get() != INVALID_SOCKET) {
417 if (m_session_id.empty()) {
419 "Destroying incomplete SAM session\n");
420 } else {
422 "Destroying SAM session %s\n", m_session_id);
423 }
424 }
425 m_control_sock->Reset();
426 m_session_id.clear();
427 }
428} // namespace sam
429} // namespace i2p
Network address.
Definition: netaddress.h:121
std::string ToStringIP() const
Definition: netaddress.cpp:623
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:224
A hasher class for SHA-256.
Definition: sha256.h:13
CSHA256 & Write(const uint8_t *data, size_t len)
Definition: sha256.cpp:819
static const size_t OUTPUT_SIZE
Definition: sha256.h:20
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: sha256.cpp:844
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
std::string ToString() const
uint16_t GetPort() const
A helper class for interruptible sleeps.
RAII helper class that manages a socket.
Definition: sock.h:28
virtual void SendComplete(const std::string &data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
Definition: sock.cpp:215
uint8_t Event
Definition: sock.h:129
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:135
virtual std::string RecvUntilTerminator(uint8_t terminator, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt, size_t max_data) const
Read from socket until a terminator character is encountered.
Definition: sock.cpp:260
std::string GetHex() const
Definition: uint256.cpp:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
const fs::path m_private_key_file
The name of the file where this peer's private key is stored (in binary).
Definition: i2p.h:228
Reply SendRequestAndGetReply(const Sock &sock, const std::string &request, bool check_result_ok=true) const
Send request and get a reply from the SAM proxy.
Definition: i2p.cpp:245
bool Listen(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start listening for an incoming connection.
Definition: i2p.cpp:126
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
Definition: i2p.cpp:356
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:415
const CService m_control_host
The host and port of the SAM control service.
Definition: i2p.h:233
Session(const fs::path &private_key_file, const CService &control_host, CThreadInterrupt *interrupt)
Construct a session.
Definition: i2p.cpp:115
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
Definition: i2p.cpp:286
void CheckControlSock() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check the control socket for errors and possibly disconnect.
Definition: i2p.cpp:304
std::unique_ptr< Sock > StreamAccept() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy and issue "STREAM ACCEPT" request using the existing session i...
Definition: i2p.cpp:393
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
Definition: i2p.cpp:340
~Session()
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:121
void GenerateAndSavePrivateKey(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy, set m_private_key to it and save it on disk to m_priva...
Definition: i2p.cpp:326
bool Connect(const CService &to, Connection &conn, bool &proxy_error) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Connect to an I2P peer.
Definition: i2p.cpp:170
CThreadInterrupt *const m_interrupt
Cease network activity when this is signaled.
Definition: i2p.h:238
void DestGenerate(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy and set m_private_key to it.
Definition: i2p.cpp:315
Mutex m_mutex
Mutex protecting the members that can be concurrently accessed.
Definition: i2p.h:243
bool Accept(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait for and accept a new incoming connection.
Definition: i2p.cpp:141
#define INVALID_SOCKET
Definition: compat.h:52
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:156
#define LogPrintLevel(category, level,...)
Definition: logging.h:437
@ I2P
Definition: logging.h:92
static auto quoted(const std::string &s)
Definition: fs.h:112
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
static constexpr size_t MAX_MSG_SIZE
The maximum size of an incoming message from the I2P SAM proxy (in bytes).
Definition: i2p.h:53
Definition: i2p.cpp:29
static CNetAddr DestB64ToAddr(const std::string &dest)
Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
Definition: i2p.cpp:108
static std::string SwapBase64(const std::string &from)
Swap Standard Base64 <-> I2P Base64.
Definition: i2p.cpp:39
static CNetAddr DestBinToAddr(const Binary &dest)
Derive the .b32.i2p address of an I2P destination (binary).
Definition: i2p.cpp:86
std::vector< uint8_t > Binary
Binary data.
Definition: i2p.h:27
static Binary DecodeI2PBase64(const std::string &i2p_b64)
Decode an I2P-style Base64 string.
Definition: i2p.cpp:70
std::vector< T > Split(const Span< const char > &sp, char sep)
Split a string on every instance of sep, returning a vector.
Definition: spanparsing.h:52
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
static constexpr uint16_t I2P_SAM31_PORT
SAM 3.1 and earlier do not support specifying ports and force the port to 0.
Definition: netaddress.h:116
std::function< std::unique_ptr< Sock >(const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:630
bool ConnectSocketDirectly(const CService &addrConnect, const Sock &sock, int nTimeout, bool manual_connection)
Try to connect to the specified service on the specified socket.
Definition: netbase.cpp:644
int nConnectTimeout
Definition: netbase.cpp:37
uint256 GetRandHash() noexcept
Definition: random.cpp:662
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits< size_t >::max())
Read full contents of a file and return them in a std::string.
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:21
An established connection with another peer.
Definition: i2p.h:32
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:34
CService me
Our I2P address.
Definition: i2p.h:37
CService peer
The peer's I2P address.
Definition: i2p.h:40
A reply from the SAM proxy.
Definition: i2p.h:120
std::string Get(const std::string &key) const
Get the value of a given key.
Definition: i2p.cpp:235
std::string full
Full, unparsed reply.
Definition: i2p.h:124
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
Definition: i2p.h:138
std::string request
Request, used for detailed error reporting.
Definition: i2p.h:129
#define LOCK(cs)
Definition: sync.h:306
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
std::string EncodeBase64(Span< const uint8_t > input)
std::string EncodeBase32(Span< const uint8_t > input, bool pad)
Base32 encode.
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)