Bitcoin Core  21.99.0
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 <chainparams.h>
6 #include <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 <util/strencodings.h>
16 #include <tinyformat.h>
17 #include <util/readwritefile.h>
18 #include <util/sock.h>
19 #include <util/spanparsing.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  bool invalid;
73  Binary decoded = DecodeBase64(std_b64.c_str(), &invalid);
74  if (invalid) {
75  throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
76  }
77  return 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), m_control_host(control_host), m_interrupt(interrupt),
120  m_control_sock(std::make_unique<Sock>(INVALID_SOCKET))
121 {
122 }
123 
125 {
126  LOCK(m_mutex);
127  Disconnect();
128 }
129 
131 {
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) {
139  Log("Error listening: %s", e.what());
141  }
142  return false;
143 }
144 
146 {
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 & Sock::RECV) == 0) {
153  // Timeout, no incoming connections within MAX_WAIT_FOR_IO.
154  continue;
155  }
156 
157  const std::string& peer_dest =
158  conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
159 
160  conn.peer = CService(DestB64ToAddr(peer_dest), Params().GetDefaultPort());
161 
162  return true;
163  }
164  } catch (const std::runtime_error& e) {
165  Log("Error accepting: %s", e.what());
167  }
168  return false;
169 }
170 
171 bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)
172 {
173  proxy_error = true;
174 
175  std::string session_id;
176  std::unique_ptr<Sock> sock;
177  conn.peer = to;
178 
179  try {
180  {
181  LOCK(m_mutex);
183  session_id = m_session_id;
184  conn.me = m_my_addr;
185  sock = Hello();
186  }
187 
188  const Reply& lookup_reply =
189  SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringIP()));
190 
191  const std::string& dest = lookup_reply.Get("VALUE");
192 
193  const Reply& connect_reply = SendRequestAndGetReply(
194  *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest),
195  false);
196 
197  const std::string& result = connect_reply.Get("RESULT");
198 
199  if (result == "OK") {
200  conn.sock = std::move(sock);
201  return true;
202  }
203 
204  if (result == "INVALID_ID") {
205  LOCK(m_mutex);
206  Disconnect();
207  throw std::runtime_error("Invalid session id");
208  }
209 
210  if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
211  proxy_error = false;
212  }
213 
214  throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
215  } catch (const std::runtime_error& e) {
216  Log("Error connecting to %s: %s", to.ToString(), e.what());
218  return false;
219  }
220 }
221 
222 // Private methods
223 
224 std::string Session::Reply::Get(const std::string& key) const
225 {
226  const auto& pos = keys.find(key);
227  if (pos == keys.end() || !pos->second.has_value()) {
228  throw std::runtime_error(
229  strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full));
230  }
231  return pos->second.value();
232 }
233 
234 template <typename... Args>
235 void Session::Log(const std::string& fmt, const Args&... args) const
236 {
237  LogPrint(BCLog::I2P, "I2P: %s\n", tfm::format(fmt, args...));
238 }
239 
241  const std::string& request,
242  bool check_result_ok) const
243 {
244  sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
245 
246  Reply reply;
247 
248  // Don't log the full "SESSION CREATE ..." because it contains our private key.
249  reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request;
250 
251  // It could take a few minutes for the I2P router to reply as it is querying the I2P network
252  // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking
253  // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is
254  // signaled.
255  static constexpr auto recv_timeout = 3min;
256 
257  reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);
258 
259  for (const auto& kv : spanparsing::Split(reply.full, ' ')) {
260  const auto& pos = std::find(kv.begin(), kv.end(), '=');
261  if (pos != kv.end()) {
262  reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});
263  } else {
264  reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);
265  }
266  }
267 
268  if (check_result_ok && reply.Get("RESULT") != "OK") {
269  throw std::runtime_error(
270  strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full));
271  }
272 
273  return reply;
274 }
275 
276 std::unique_ptr<Sock> Session::Hello() const
277 {
278  auto sock = CreateSock(m_control_host);
279 
280  if (!sock) {
281  throw std::runtime_error("Cannot create socket");
282  }
283 
285  throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToString()));
286  }
287 
288  SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
289 
290  return sock;
291 }
292 
294 {
295  LOCK(m_mutex);
296 
297  std::string errmsg;
298  if (!m_control_sock->IsConnected(errmsg)) {
299  Log("Control socket error: %s", errmsg);
300  Disconnect();
301  }
302 }
303 
304 void Session::DestGenerate(const Sock& sock)
305 {
306  // https://geti2p.net/spec/common-structures#key-certificates
307  // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations".
308  // Use "7" because i2pd <2.24.0 does not recognize the textual form.
309  const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
310 
311  m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
312 }
313 
315 {
316  DestGenerate(sock);
317 
318  // umask is set to 077 in init.cpp, which is ok (unless -sysperms is given)
320  std::string(m_private_key.begin(), m_private_key.end()))) {
321  throw std::runtime_error(
322  strprintf("Cannot save I2P private key to %s", m_private_key_file));
323  }
324 }
325 
327 {
328  // From https://geti2p.net/spec/common-structures#destination:
329  // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be
330  // non-zero"
331  static constexpr size_t DEST_LEN_BASE = 387;
332  static constexpr size_t CERT_LEN_POS = 385;
333 
334  uint16_t cert_len;
335  memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
336  cert_len = be16toh(cert_len);
337 
338  const size_t dest_len = DEST_LEN_BASE + cert_len;
339 
340  return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
341 }
342 
344 {
345  std::string errmsg;
346  if (m_control_sock->IsConnected(errmsg)) {
347  return;
348  }
349 
350  Log("Creating SAM session with %s", m_control_host.ToString());
351 
352  auto sock = Hello();
353 
354  const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);
355  if (read_ok) {
356  m_private_key.assign(data.begin(), data.end());
357  } else {
359  }
360 
361  const std::string& session_id = GetRandHash().GetHex().substr(0, 10); // full is an overkill, too verbose in the logs
362  const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));
363 
364  SendRequestAndGetReply(*sock, strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s",
365  session_id, private_key_b64));
366 
367  m_my_addr = CService(DestBinToAddr(MyDestination()), Params().GetDefaultPort());
368  m_session_id = session_id;
369  m_control_sock = std::move(sock);
370 
371  LogPrintf("I2P: SAM session created: session id=%s, my address=%s\n", m_session_id,
372  m_my_addr.ToString());
373 }
374 
375 std::unique_ptr<Sock> Session::StreamAccept()
376 {
377  auto sock = Hello();
378 
379  const Reply& reply = SendRequestAndGetReply(
380  *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false);
381 
382  const std::string& result = reply.Get("RESULT");
383 
384  if (result == "OK") {
385  return sock;
386  }
387 
388  if (result == "INVALID_ID") {
389  // If our session id is invalid, then force session re-creation on next usage.
390  Disconnect();
391  }
392 
393  throw std::runtime_error(strprintf("\"%s\"", reply.full));
394 }
395 
397 {
398  if (m_control_sock->Get() != INVALID_SOCKET) {
399  if (m_session_id.empty()) {
400  Log("Destroying incomplete session");
401  } else {
402  Log("Destroying session %s", m_session_id);
403  }
404  }
405  m_control_sock->Reset();
406  m_session_id.clear();
407 }
408 } // namespace sam
409 } // namespace i2p
i2p::SwapBase64
static std::string SwapBase64(const std::string &from)
Swap Standard Base64 <-> I2P Base64.
Definition: i2p.cpp:37
i2p::sam::Session::Reply::keys
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
Definition: i2p.h:130
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:551
readwritefile.h
i2p::sam::Session::m_private_key_file
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:222
CSHA256::Write
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:637
tinyformat::format
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
BCLog::I2P
@ I2P
Definition: logging.h:60
i2p::sam::Session::Disconnect
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:396
fs.h
i2p::sam::Session::Session
Session(const fs::path &private_key_file, const CService &control_host, CThreadInterrupt *interrupt)
Construct a session.
Definition: i2p.cpp:116
i2p::sam::Session::Reply
A reply from the SAM proxy.
Definition: i2p.h:112
i2p::Connection::peer
CService peer
The peer's I2P address.
Definition: i2p.h:39
CNetAddr
Network address.
Definition: netaddress.h:119
i2p::sam::Session::Hello
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
Definition: i2p.cpp:276
spanparsing::Split
std::vector< Span< const char > > Split(const Span< const char > &sp, char sep)
Split a string on every instance of sep, returning a vector.
Definition: spanparsing.cpp:51
i2p::sam::Session::GenerateAndSavePrivateKey
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:314
nConnectTimeout
int nConnectTimeout
Definition: netbase.cpp:38
ConnectSocketDirectly
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:540
Sock::SendComplete
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:145
i2p
Definition: i2p.cpp:27
CreateSock
std::function< std::unique_ptr< Sock >const CService &)> CreateSock
Socket factory.
Definition: netbase.cpp:528
i2p::sam::Session::Reply::full
std::string full
Full, unparsed reply.
Definition: i2p.h:116
EncodeBase64
std::string EncodeBase64(Span< const unsigned char > input)
Definition: strencodings.cpp:131
chainparams.h
WriteBinaryFile
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: readwritefile.cpp:34
i2p::sam::Session::m_control_host
const CService m_control_host
The host and port of the SAM control service.
Definition: i2p.h:227
i2p::sam::Session::Listen
bool Listen(Connection &conn)
Start listening for an incoming connection.
Definition: i2p.cpp:130
CNetAddr::ToStringIP
std::string ToStringIP() const
Definition: netaddress.cpp:570
tinyformat.h
Sock
RAII helper class that manages a socket.
Definition: sock.h:25
ReadBinaryFile
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.
Definition: readwritefile.cpp:13
Sock::RecvUntilTerminator
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:186
strencodings.h
i2p::sam::Session::SendRequestAndGetReply
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:240
i2p::DecodeI2PBase64
static Binary DecodeI2PBase64(const std::string &i2p_b64)
Decode an I2P-style Base64 string.
Definition: i2p.cpp:69
i2p::Binary
std::vector< uint8_t > Binary
Binary data.
Definition: i2p.h:26
random.h
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1028
i2p::sam::Session::CreateIfNotCreatedAlready
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
Definition: i2p.cpp:343
INVALID_SOCKET
#define INVALID_SOCKET
Definition: compat.h:53
CNetAddr::SetSpecial
bool SetSpecial(const std::string &addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:224
i2p::sam::Session::m_mutex
Mutex m_mutex
Mutex protecting the members that can be concurrently accessed.
Definition: i2p.h:237
i2p::sam::Session::m_interrupt
CThreadInterrupt *const m_interrupt
Cease network activity when this is signaled.
Definition: i2p.h:232
compat.h
i2p::sam::Session::MyDestination
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
Definition: i2p.cpp:326
DecodeBase64
std::vector< unsigned char > DecodeBase64(const char *p, bool *pf_invalid)
Definition: strencodings.cpp:147
netaddress.h
i2p::DestBinToAddr
static CNetAddr DestBinToAddr(const Binary &dest)
Derive the .b32.i2p address of an I2P destination (binary).
Definition: i2p.cpp:86
be16toh
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:170
GetRandHash
uint256 GetRandHash() noexcept
Definition: random.cpp:601
i2p::sam::Session::Reply::request
std::string request
Request, used for detailed error reporting.
Definition: i2p.h:121
i2p::sam::Session::Reply::Get
std::string Get(const std::string &key) const
Get the value of a given key.
Definition: i2p.cpp:224
LogPrintf
#define LogPrintf(...)
Definition: logging.h:183
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:20
i2p::sam::Session::Connect
bool Connect(const CService &to, Connection &conn, bool &proxy_error)
Connect to an I2P peer.
Definition: i2p.cpp:171
spanparsing.h
CSHA256::Finalize
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:663
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
i2p::sam::Session::StreamAccept
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:375
EncodeBase32
std::string EncodeBase32(Span< const unsigned char > input, bool pad)
Base32 encode.
Definition: strencodings.cpp:206
CSHA256::OUTPUT_SIZE
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
sha256.h
system.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
i2p::sam::Session::Log
void Log(const std::string &fmt, const Args &... args) const
Log a message in the BCLog::I2P category.
Definition: i2p.cpp:235
i2p::sam::Session::DestGenerate
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:304
LOCK
#define LOCK(cs)
Definition: sync.h:232
i2p.h
Sock::Event
uint8_t Event
Definition: sock.h:106
i2p::sam::MAX_MSG_SIZE
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
logging.h
i2p::Connection
An established connection with another peer.
Definition: i2p.h:31
CSHA256
A hasher class for SHA-256.
Definition: sha256.h:13
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:523
MAX_WAIT_FOR_IO
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:19
i2p::Connection::me
CService me
Our I2P address.
Definition: i2p.h:36
i2p::DestB64ToAddr
static CNetAddr DestB64ToAddr(const std::string &dest)
Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
Definition: i2p.cpp:108
i2p::sam::Session::CheckControlSock
void CheckControlSock()
Check the control socket for errors and possibly disconnect.
Definition: i2p.cpp:293
netbase.h
Sock::RECV
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:111
CThreadInterrupt
Definition: threadinterrupt.h:19
sock.h
i2p::sam::Session::Accept
bool Accept(Connection &conn)
Wait for and accept a new incoming connection.
Definition: i2p.cpp:145
i2p::Connection::sock
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:33
i2p::sam::Session::~Session
~Session()
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:124
endian.h