Bitcoin Core  24.99.0
P2P Digital Currency
i2p.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-2022 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 <chainparams.h>
6 #include <compat/compat.h>
7 #include <compat/endian.h>
8 #include <crypto/sha256.h>
9 #include <fs.h>
10 #include <i2p.h>
11 #include <logging.h>
12 #include <netaddress.h>
13 #include <netbase.h>
14 #include <random.h>
15 #include <tinyformat.h>
16 #include <util/readwritefile.h>
17 #include <util/sock.h>
18 #include <util/spanparsing.h>
19 #include <util/strencodings.h>
20 #include <util/system.h>
21 #include <util/threadinterrupt.h>
22 
23 #include <chrono>
24 #include <memory>
25 #include <stdexcept>
26 #include <string>
27 
28 namespace i2p {
29 
38 static std::string SwapBase64(const std::string& from)
39 {
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 
70 static Binary DecodeI2PBase64(const std::string& i2p_b64)
71 {
72  const std::string& std_b64 = SwapBase64(i2p_b64);
73  auto decoded = DecodeBase64(std_b64);
74  if (!decoded) {
75  throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
76  }
77  return std::move(*decoded);
78 }
79 
86 static CNetAddr DestBinToAddr(const Binary& dest)
87 {
88  CSHA256 hasher;
89  hasher.Write(dest.data(), dest.size());
90  unsigned char hash[CSHA256::OUTPUT_SIZE];
91  hasher.Finalize(hash);
92 
93  CNetAddr addr;
94  const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
95  if (!addr.SetSpecial(addr_str)) {
96  throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str));
97  }
98 
99  return addr;
100 }
101 
108 static CNetAddr DestB64ToAddr(const std::string& dest)
109 {
110  const Binary& decoded = DecodeI2PBase64(dest);
111  return DestBinToAddr(decoded);
112 }
113 
114 namespace sam {
115 
116 Session::Session(const fs::path& private_key_file,
117  const CService& control_host,
118  CThreadInterrupt* interrupt)
119  : m_private_key_file{private_key_file},
120  m_control_host{control_host},
121  m_interrupt{interrupt},
122  m_control_sock{std::make_unique<Sock>(INVALID_SOCKET)},
123  m_transient{false}
124 {
125 }
126 
127 Session::Session(const CService& control_host, CThreadInterrupt* interrupt)
128  : m_control_host{control_host},
129  m_interrupt{interrupt},
130  m_control_sock{std::make_unique<Sock>(INVALID_SOCKET)},
131  m_transient{true}
132 {
133 }
134 
136 {
137  LOCK(m_mutex);
138  Disconnect();
139 }
140 
142 {
143  try {
144  LOCK(m_mutex);
146  conn.me = m_my_addr;
147  conn.sock = StreamAccept();
148  return true;
149  } catch (const std::runtime_error& e) {
150  Log("Error listening: %s", e.what());
152  }
153  return false;
154 }
155 
157 {
158  try {
159  while (!*m_interrupt) {
160  Sock::Event occurred;
161  if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
162  throw std::runtime_error("wait on socket failed");
163  }
164 
165  if (occurred == 0) {
166  // Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
167  continue;
168  }
169 
170  const std::string& peer_dest =
171  conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
172 
173  conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);
174 
175  return true;
176  }
177  } catch (const std::runtime_error& e) {
178  Log("Error accepting: %s", e.what());
180  }
181  return false;
182 }
183 
184 bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)
185 {
186  // Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy
187  // when connecting (SAM 3.1 does not use ports) and it forces/defaults it to I2P_SAM31_PORT.
188  if (to.GetPort() != I2P_SAM31_PORT) {
189  proxy_error = false;
190  return false;
191  }
192 
193  proxy_error = true;
194 
195  std::string session_id;
196  std::unique_ptr<Sock> sock;
197  conn.peer = to;
198 
199  try {
200  {
201  LOCK(m_mutex);
203  session_id = m_session_id;
204  conn.me = m_my_addr;
205  sock = Hello();
206  }
207 
208  const Reply& lookup_reply =
209  SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringAddr()));
210 
211  const std::string& dest = lookup_reply.Get("VALUE");
212 
213  const Reply& connect_reply = SendRequestAndGetReply(
214  *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest),
215  false);
216 
217  const std::string& result = connect_reply.Get("RESULT");
218 
219  if (result == "OK") {
220  conn.sock = std::move(sock);
221  return true;
222  }
223 
224  if (result == "INVALID_ID") {
225  LOCK(m_mutex);
226  Disconnect();
227  throw std::runtime_error("Invalid session id");
228  }
229 
230  if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
231  proxy_error = false;
232  }
233 
234  throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
235  } catch (const std::runtime_error& e) {
236  Log("Error connecting to %s: %s", to.ToStringAddrPort(), e.what());
238  return false;
239  }
240 }
241 
242 // Private methods
243 
244 std::string Session::Reply::Get(const std::string& key) const
245 {
246  const auto& pos = keys.find(key);
247  if (pos == keys.end() || !pos->second.has_value()) {
248  throw std::runtime_error(
249  strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full));
250  }
251  return pos->second.value();
252 }
253 
254 template <typename... Args>
255 void Session::Log(const std::string& fmt, const Args&... args) const
256 {
257  LogPrint(BCLog::I2P, "%s\n", tfm::format(fmt, args...));
258 }
259 
261  const std::string& request,
262  bool check_result_ok) const
263 {
264  sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
265 
266  Reply reply;
267 
268  // Don't log the full "SESSION CREATE ..." because it contains our private key.
269  reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request;
270 
271  // It could take a few minutes for the I2P router to reply as it is querying the I2P network
272  // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking
273  // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is
274  // signaled.
275  static constexpr auto recv_timeout = 3min;
276 
277  reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);
278 
279  for (const auto& kv : spanparsing::Split(reply.full, ' ')) {
280  const auto& pos = std::find(kv.begin(), kv.end(), '=');
281  if (pos != kv.end()) {
282  reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});
283  } else {
284  reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);
285  }
286  }
287 
288  if (check_result_ok && reply.Get("RESULT") != "OK") {
289  throw std::runtime_error(
290  strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full));
291  }
292 
293  return reply;
294 }
295 
296 std::unique_ptr<Sock> Session::Hello() const
297 {
298  auto sock = CreateSock(m_control_host);
299 
300  if (!sock) {
301  throw std::runtime_error("Cannot create socket");
302  }
303 
305  throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToStringAddrPort()));
306  }
307 
308  SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
309 
310  return sock;
311 }
312 
314 {
315  LOCK(m_mutex);
316 
317  std::string errmsg;
318  if (!m_control_sock->IsConnected(errmsg)) {
319  Log("Control socket error: %s", errmsg);
320  Disconnect();
321  }
322 }
323 
324 void Session::DestGenerate(const Sock& sock)
325 {
326  // https://geti2p.net/spec/common-structures#key-certificates
327  // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations".
328  // Use "7" because i2pd <2.24.0 does not recognize the textual form.
329  // If SIGNATURE_TYPE is not specified, then the default one is DSA_SHA1.
330  const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
331 
332  m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
333 }
334 
336 {
337  DestGenerate(sock);
338 
339  // umask is set to 0077 in util/system.cpp, which is ok.
341  std::string(m_private_key.begin(), m_private_key.end()))) {
342  throw std::runtime_error(
343  strprintf("Cannot save I2P private key to %s", fs::quoted(fs::PathToString(m_private_key_file))));
344  }
345 }
346 
348 {
349  // From https://geti2p.net/spec/common-structures#destination:
350  // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be
351  // non-zero"
352  static constexpr size_t DEST_LEN_BASE = 387;
353  static constexpr size_t CERT_LEN_POS = 385;
354 
355  uint16_t cert_len;
356  memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
357  cert_len = be16toh(cert_len);
358 
359  const size_t dest_len = DEST_LEN_BASE + cert_len;
360 
361  return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
362 }
363 
365 {
366  std::string errmsg;
367  if (m_control_sock->IsConnected(errmsg)) {
368  return;
369  }
370 
371  const auto session_type = m_transient ? "transient" : "persistent";
372  const auto session_id = GetRandHash().GetHex().substr(0, 10); // full is overkill, too verbose in the logs
373 
374  Log("Creating %s SAM session %s with %s", session_type, session_id, m_control_host.ToStringAddrPort());
375 
376  auto sock = Hello();
377 
378  if (m_transient) {
379  // The destination (private key) is generated upon session creation and returned
380  // in the reply in DESTINATION=.
381  const Reply& reply = SendRequestAndGetReply(
382  *sock,
383  strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT SIGNATURE_TYPE=7 "
384  "inbound.quantity=1 outbound.quantity=1",
385  session_id));
386 
387  m_private_key = DecodeI2PBase64(reply.Get("DESTINATION"));
388  } else {
389  // Read our persistent destination (private key) from disk or generate
390  // one and save it to disk. Then use it when creating the session.
391  const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);
392  if (read_ok) {
393  m_private_key.assign(data.begin(), data.end());
394  } else {
396  }
397 
398  const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));
399 
401  strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s "
402  "inbound.quantity=3 outbound.quantity=3",
403  session_id,
404  private_key_b64));
405  }
406 
408  m_session_id = session_id;
409  m_control_sock = std::move(sock);
410 
411  Log("%s SAM session %s created, my address=%s",
412  Capitalize(session_type),
413  m_session_id,
414  m_my_addr.ToStringAddrPort());
415 }
416 
417 std::unique_ptr<Sock> Session::StreamAccept()
418 {
419  auto sock = Hello();
420 
421  const Reply& reply = SendRequestAndGetReply(
422  *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false);
423 
424  const std::string& result = reply.Get("RESULT");
425 
426  if (result == "OK") {
427  return sock;
428  }
429 
430  if (result == "INVALID_ID") {
431  // If our session id is invalid, then force session re-creation on next usage.
432  Disconnect();
433  }
434 
435  throw std::runtime_error(strprintf("\"%s\"", reply.full));
436 }
437 
439 {
440  if (m_control_sock->Get() != INVALID_SOCKET) {
441  if (m_session_id.empty()) {
442  Log("Destroying incomplete SAM session");
443  } else {
444  Log("Destroying SAM session %s", m_session_id);
445  }
446  }
447  m_control_sock = std::make_unique<Sock>(INVALID_SOCKET);
448  m_session_id.clear();
449 }
450 } // namespace sam
451 } // namespace i2p
Network address.
Definition: netaddress.h:120
std::string ToStringAddr() const
Definition: netaddress.cpp:602
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:208
A hasher class for SHA-256.
Definition: sha256.h:14
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:707
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:681
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:520
uint16_t GetPort() const
Definition: netaddress.cpp:846
std::string ToStringAddrPort() const
Definition: netaddress.cpp:914
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:254
uint8_t Event
Definition: sock.h:148
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:153
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:295
std::string GetHex() const
Definition: uint256.cpp:11
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
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:235
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:260
bool Listen(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start listening for an incoming connection.
Definition: i2p.cpp:141
bool Accept(Connection &conn)
Wait for and accept a new incoming connection.
Definition: i2p.cpp:156
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
Definition: i2p.cpp:364
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:438
const CService m_control_host
The host and port of the SAM control service.
Definition: i2p.h:240
Session(const fs::path &private_key_file, const CService &control_host, CThreadInterrupt *interrupt)
Construct a session.
Definition: i2p.cpp:116
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
Definition: i2p.cpp:296
void CheckControlSock() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check the control socket for errors and possibly disconnect.
Definition: i2p.cpp:313
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:417
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
Definition: i2p.cpp:347
~Session()
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:135
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:283
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:335
bool Connect(const CService &to, Connection &conn, bool &proxy_error) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Connect to an I2P peer.
Definition: i2p.cpp:184
void Log(const std::string &fmt, const Args &... args) const
Log a message in the BCLog::I2P category.
Definition: i2p.cpp:255
CThreadInterrupt *const m_interrupt
Cease network activity when this is signaled.
Definition: i2p.h:245
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:324
Mutex m_mutex
Mutex protecting the members that can be concurrently accessed.
Definition: i2p.h:250
#define INVALID_SOCKET
Definition: compat.h:54
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:170
#define LogPrint(category,...)
Definition: logging.h:245
@ I2P
Definition: logging.h:62
static auto quoted(const std::string &s)
Definition: fs.h:94
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
static constexpr size_t MAX_MSG_SIZE
The maximum size of an incoming message from the I2P SAM proxy (in bytes).
Definition: i2p.h:50
Definition: i2p.cpp:28
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:38
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:26
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, std::string_view separators)
Split a string on any char found in separators, returning a vector.
Definition: spanparsing.h:48
void format(std::ostream &out, const char *fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1060
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:112
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:534
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:546
int nConnectTimeout
Definition: netbase.cpp:36
ArgsManager args
uint256 GetRandHash() noexcept
Definition: random.cpp:591
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)
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:31
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:33
CService me
Our I2P address.
Definition: i2p.h:36
CService peer
The peer's I2P address.
Definition: i2p.h:39
A reply from the SAM proxy.
Definition: i2p.h:125
std::string Get(const std::string &key) const
Get the value of a given key.
Definition: i2p.cpp:244
std::string full
Full, unparsed reply.
Definition: i2p.h:129
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
Definition: i2p.h:143
std::string request
Request, used for detailed error reporting.
Definition: i2p.h:134
#define LOCK(cs)
Definition: sync.h:258
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
std::string EncodeBase64(Span< const unsigned char > input)
std::string EncodeBase32(Span< const unsigned char > input, bool pad)
Base32 encode.
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)