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