Bitcoin ABC 0.33.3
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/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 <script/parsing.h>
17#include <tinyformat.h>
18#include <util/fs.h>
19#include <util/readwritefile.h>
20#include <util/sock.h>
21#include <util/strencodings.h>
23
24#include <chrono>
25#include <memory>
26#include <stdexcept>
27#include <string>
28
29using util::Split;
30
31namespace i2p {
32
41static std::string SwapBase64(const std::string &from) {
42 std::string to;
43 to.resize(from.size());
44 for (size_t i = 0; i < from.size(); ++i) {
45 switch (from[i]) {
46 case '-':
47 to[i] = '+';
48 break;
49 case '~':
50 to[i] = '/';
51 break;
52 case '+':
53 to[i] = '-';
54 break;
55 case '/':
56 to[i] = '~';
57 break;
58 default:
59 to[i] = from[i];
60 break;
61 }
62 }
63 return to;
64}
65
72static Binary DecodeI2PBase64(const std::string &i2p_b64) {
73 const std::string &std_b64 = SwapBase64(i2p_b64);
74 auto decoded = DecodeBase64(std_b64);
75 if (!decoded) {
76 throw std::runtime_error(
77 strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
78 }
79 return std::move(*decoded);
80}
81
88static CNetAddr DestBinToAddr(const Binary &dest) {
89 CSHA256 hasher;
90 hasher.Write(dest.data(), dest.size());
91 uint8_t hash[CSHA256::OUTPUT_SIZE];
92 hasher.Finalize(hash);
93
94 CNetAddr addr;
95 const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
96 if (!addr.SetSpecial(addr_str)) {
97 throw std::runtime_error(
98 strprintf("Cannot parse I2P address: \"%s\"", addr_str));
99 }
100
101 return addr;
102}
103
110static CNetAddr DestB64ToAddr(const std::string &dest) {
111 const Binary &decoded = DecodeI2PBase64(dest);
112 return DestBinToAddr(decoded);
113}
114
115namespace sam {
116
117 Session::Session(const fs::path &private_key_file,
118 const Proxy &control_host, CThreadInterrupt *interrupt)
119 : m_private_key_file{private_key_file}, m_control_host{control_host},
120 m_interrupt{interrupt}, m_transient{false} {}
121
122 Session::Session(const Proxy &control_host, CThreadInterrupt *interrupt)
123 : m_control_host{control_host}, m_interrupt{interrupt},
124 m_transient{true} {}
125
127 LOCK(m_mutex);
128 Disconnect();
129 }
130
132 try {
133 LOCK(m_mutex);
135 conn.me = m_my_addr;
136 conn.sock = StreamAccept();
137 return true;
138 } catch (const std::runtime_error &e) {
140 "Couldn't listen: %s\n", e.what());
142 }
143 return false;
144 }
145
147 try {
148 while (!*m_interrupt) {
149 Sock::Event occurred;
150 conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred);
151
152 if (occurred == 0) {
153 // Timeout, no incoming connections or errors within
154 // MAX_WAIT_FOR_IO.
155 continue;
156 }
157
158 const std::string &peer_dest = conn.sock->RecvUntilTerminator(
160
161 conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);
162
163 return true;
164 }
165 } catch (const std::runtime_error &e) {
166 // TODO: Improve log message as per core#29833 (commit 7d3662fbe)
167 // when backporting core#28077
169 "Error accepting: %s\n", e.what());
171 }
172 return false;
173 }
174
175 bool Session::Connect(const CService &to, Connection &conn,
176 bool &proxy_error) {
177 // Refuse connecting to arbitrary ports. We don't specify any
178 // destination port to the SAM proxy when connecting (SAM 3.1 does not
179 // use ports) and it forces/defaults it to I2P_SAM31_PORT.
180 if (to.GetPort() != I2P_SAM31_PORT) {
181 proxy_error = false;
182 return false;
183 }
184
185 proxy_error = true;
186
187 std::string session_id;
188 std::unique_ptr<Sock> sock;
189 conn.peer = to;
190
191 try {
192 {
193 LOCK(m_mutex);
195 session_id = m_session_id;
196 conn.me = m_my_addr;
197 sock = Hello();
198 }
199
200 const Reply &lookup_reply = SendRequestAndGetReply(
201 *sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringAddr()));
202
203 const std::string &dest = lookup_reply.Get("VALUE");
204
205 const Reply &connect_reply = SendRequestAndGetReply(
206 *sock,
207 strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false",
208 session_id, dest),
209 false);
210
211 const std::string &result = connect_reply.Get("RESULT");
212
213 if (result == "OK") {
214 conn.sock = std::move(sock);
215 return true;
216 }
217
218 if (result == "INVALID_ID") {
219 LOCK(m_mutex);
220 Disconnect();
221 throw std::runtime_error("Invalid session id");
222 }
223
224 if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
225 proxy_error = false;
226 }
227
228 throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
229 } catch (const std::runtime_error &e) {
231 "Error connecting to %s: %s\n", to.ToStringAddrPort(),
232 e.what());
234 return false;
235 }
236 }
237
238 // Private methods
239
240 std::string Session::Reply::Get(const std::string &key) const {
241 const auto &pos = keys.find(key);
242 if (pos == keys.end() || !pos->second.has_value()) {
243 throw std::runtime_error(
244 strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key,
245 request, full));
246 }
247 return pos->second.value();
248 }
249
251 const std::string &request,
252 bool check_result_ok) const {
253 sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
254
255 Reply reply;
256
257 // Don't log the full "SESSION CREATE ..." because it contains our
258 // private key.
259 reply.request = request.substr(0, 14) == "SESSION CREATE"
260 ? "SESSION CREATE ..."
261 : request;
262
263 // It could take a few minutes for the I2P router to reply as it is
264 // querying the I2P network (when doing name lookup, for example).
265 // Notice: `RecvUntilTerminator()` is checking `m_interrupt` more often,
266 // so we would not be stuck here for long if `m_interrupt` is signaled.
267 static constexpr auto recv_timeout = 3min;
268
269 reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt,
271
272 for (const auto &kv : Split(reply.full, ' ')) {
273 const auto &pos = std::find(kv.begin(), kv.end(), '=');
274 if (pos != kv.end()) {
275 reply.keys.emplace(std::string{kv.begin(), pos},
276 std::string{pos + 1, kv.end()});
277 } else {
278 reply.keys.emplace(std::string{kv.begin(), kv.end()},
279 std::nullopt);
280 }
281 }
282
283 if (check_result_ok && reply.Get("RESULT") != "OK") {
284 throw std::runtime_error(strprintf(
285 "Unexpected reply to \"%s\": \"%s\"", request, reply.full));
286 }
287
288 return reply;
289 }
290
291 std::unique_ptr<Sock> Session::Hello() const {
292 auto sock = m_control_host.Connect();
293
294 if (!sock) {
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 && !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. If SIGNATURE_TYPE is not specified, then the default
320 // one is DSA_SHA1.
321 const Reply &reply = SendRequestAndGetReply(
322 sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
323
324 m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
325 }
326
328 DestGenerate(sock);
329
330 // umask is set to 077 in init.cpp, which is ok (unless -sysperms is
331 // given)
332 if (!WriteBinaryFile(
334 std::string(m_private_key.begin(), m_private_key.end()))) {
335 throw std::runtime_error(
336 strprintf("Cannot save I2P private key to %s",
338 }
339 }
340
342 // From https://geti2p.net/spec/common-structures#destination:
343 // "They are 387 bytes plus the certificate length specified at bytes
344 // 385-386, which may be non-zero"
345 static constexpr size_t DEST_LEN_BASE = 387;
346 static constexpr size_t CERT_LEN_POS = 385;
347
348 uint16_t cert_len;
349 memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
350 cert_len = be16toh_internal(cert_len);
351
352 const size_t dest_len = DEST_LEN_BASE + cert_len;
353
354 return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
355 }
356
358 std::string errmsg;
359 if (m_control_sock && m_control_sock->IsConnected(errmsg)) {
360 return;
361 }
362
363 const auto session_type = m_transient ? "transient" : "persistent";
364 // full is overkill, too verbose in the logs
365 const auto session_id = GetRandHash().GetHex().substr(0, 10);
366
368 "Creating %s SAM session %s with %s\n", session_type,
369 session_id, m_control_host.ToString());
370
371 auto sock = Hello();
372
373 if (m_transient) {
374 // The destination (private key) is generated upon session creation
375 // and returned in the reply in DESTINATION=.
376 const Reply &reply = SendRequestAndGetReply(
377 *sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s "
378 "DESTINATION=TRANSIENT SIGNATURE_TYPE=7 "
379 "inbound.quantity=1 outbound.quantity=1",
380 session_id));
381
382 m_private_key = DecodeI2PBase64(reply.Get("DESTINATION"));
383 } else {
384 // Read our persistent destination (private key) from disk or
385 // generate one and save it to disk. Then use it when creating the
386 // session.
387 const auto &[read_ok, data] = ReadBinaryFile(m_private_key_file);
388 if (read_ok) {
389 m_private_key.assign(data.begin(), data.end());
390 } else {
392 }
393
394 const std::string &private_key_b64 =
395 SwapBase64(EncodeBase64(m_private_key));
396
398 *sock,
399 strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s "
400 "inbound.quantity=3 outbound.quantity=3",
401 session_id, private_key_b64));
402 }
403
405 m_session_id = session_id;
406 m_control_sock = std::move(sock);
407
409 "%s SAM session %s created, my address=%s\n",
410 Capitalize(session_type), m_session_id,
411 m_my_addr.ToStringAddrPort());
412 }
413
414 std::unique_ptr<Sock> Session::StreamAccept() {
415 auto sock = Hello();
416
417 const Reply &reply = SendRequestAndGetReply(
418 *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id),
419 false);
420
421 const std::string &result = reply.Get("RESULT");
422
423 if (result == "OK") {
424 return sock;
425 }
426
427 if (result == "INVALID_ID") {
428 // If our session id is invalid, then force session re-creation on
429 // next usage.
430 Disconnect();
431 }
432
433 throw std::runtime_error(strprintf("\"%s\"", reply.full));
434 }
435
437 if (m_control_sock) {
438 if (m_session_id.empty()) {
440 "Destroying incomplete SAM session\n");
441 } else {
443 "Destroying SAM session %s\n", m_session_id);
444 }
445 m_control_sock.reset();
446 }
447 m_session_id.clear();
448 }
449} // namespace sam
450} // namespace i2p
Network address.
Definition: netaddress.h:114
std::string ToStringAddr() const
Definition: netaddress.cpp:630
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:227
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:573
uint16_t GetPort() const
std::string ToStringAddrPort() const
A helper class for interruptible sleeps.
Definition: netbase.h:67
std::string ToString() const
Definition: netbase.h:96
std::unique_ptr< Sock > Connect() const
Definition: netbase.cpp:759
RAII helper class that manages a socket and closes it automatically when it goes out of scope.
Definition: sock.h:27
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:254
uint8_t Event
Definition: sock.h:153
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:159
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:299
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:244
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:250
Session(const fs::path &private_key_file, const Proxy &control_host, CThreadInterrupt *interrupt)
Construct a session.
Definition: i2p.cpp:117
bool Listen(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start listening for an incoming connection.
Definition: i2p.cpp:131
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
Definition: i2p.cpp:357
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:436
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
Definition: i2p.cpp:291
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:414
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
Definition: i2p.cpp:341
~Session()
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:126
const bool m_transient
Whether this is a transient session (the I2P private key will not be read or written to disk).
Definition: i2p.h:294
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:327
bool Connect(const CService &to, Connection &conn, bool &proxy_error) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Connect to an I2P peer.
Definition: i2p.cpp:175
CThreadInterrupt *const m_interrupt
Cease network activity when this is signaled.
Definition: i2p.h:254
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:259
bool Accept(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait for and accept a new incoming connection.
Definition: i2p.cpp:146
const Proxy m_control_host
The SAM control service proxy.
Definition: i2p.h:249
BSWAP_CONSTEXPR uint16_t be16toh_internal(uint16_t big_endian_16bits)
Definition: endian.h:27
#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:54
Definition: i2p.cpp:31
static CNetAddr DestB64ToAddr(const std::string &dest)
Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
Definition: i2p.cpp:110
static std::string SwapBase64(const std::string &from)
Swap Standard Base64 <-> I2P Base64.
Definition: i2p.cpp:41
static CNetAddr DestBinToAddr(const Binary &dest)
Derive the .b32.i2p address of an I2P destination (binary).
Definition: i2p.cpp:88
std::vector< uint8_t > Binary
Binary data.
Definition: i2p.h:28
static Binary DecodeI2PBase64(const std::string &i2p_b64)
Decode an I2P-style Base64 string.
Definition: i2p.cpp:72
std::vector< T > Split(const Span< const char > &sp, std::string_view separators)
Split a string on any char found in separators, returning a vector.
Definition: string.h:32
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:109
uint256 GetRandHash() noexcept
========== CONVENIENCE FUNCTIONS FOR COMMONLY USED RANDOMNESS ==========
Definition: random.h:494
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:33
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:35
CService me
Our I2P address.
Definition: i2p.h:38
CService peer
The peer's I2P address.
Definition: i2p.h:41
A reply from the SAM proxy.
Definition: i2p.h:136
std::string Get(const std::string &key) const
Get the value of a given key.
Definition: i2p.cpp:240
std::string full
Full, unparsed reply.
Definition: i2p.h:140
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
Definition: i2p.h:154
std::string request
Request, used for detailed error reporting.
Definition: i2p.h:145
#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 Capitalize(std::string str)
Capitalizes the first character of the given string.
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)