Bitcoin Core  22.99.0
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2020 The Bitcoin Core developers
2 // Copyright (c) 2017 The Zcash developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <torcontrol.h>
7 
8 #include <chainparams.h>
9 #include <chainparamsbase.h>
10 #include <compat.h>
11 #include <crypto/hmac_sha256.h>
12 #include <net.h>
13 #include <netaddress.h>
14 #include <netbase.h>
15 #include <util/readwritefile.h>
16 #include <util/strencodings.h>
17 #include <util/system.h>
18 #include <util/thread.h>
19 #include <util/time.h>
20 
21 #include <deque>
22 #include <functional>
23 #include <set>
24 #include <stdlib.h>
25 #include <vector>
26 
27 #include <boost/signals2/signal.hpp>
28 #include <boost/algorithm/string/split.hpp>
29 #include <boost/algorithm/string/classification.hpp>
30 #include <boost/algorithm/string/replace.hpp>
31 
32 #include <event2/bufferevent.h>
33 #include <event2/buffer.h>
34 #include <event2/util.h>
35 #include <event2/event.h>
36 #include <event2/thread.h>
37 
39 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
41 static const int TOR_COOKIE_SIZE = 32;
43 static const int TOR_NONCE_SIZE = 32;
45 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
47 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
49 static const float RECONNECT_TIMEOUT_START = 1.0;
51 static const float RECONNECT_TIMEOUT_EXP = 1.5;
56 static const int MAX_LINE_LENGTH = 100000;
57 
58 /****** Low-level TorControlConnection ********/
59 
61  base(_base), b_conn(nullptr)
62 {
63 }
64 
66 {
67  if (b_conn)
68  bufferevent_free(b_conn);
69 }
70 
71 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
72 {
73  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
74  struct evbuffer *input = bufferevent_get_input(bev);
75  size_t n_read_out = 0;
76  char *line;
77  assert(input);
78  // If there is not a whole line to read, evbuffer_readln returns nullptr
79  while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
80  {
81  std::string s(line, n_read_out);
82  free(line);
83  if (s.size() < 4) // Short line
84  continue;
85  // <status>(-|+| )<data><CRLF>
86  self->message.code = atoi(s.substr(0,3));
87  self->message.lines.push_back(s.substr(4));
88  char ch = s[3]; // '-','+' or ' '
89  if (ch == ' ') {
90  // Final line, dispatch reply and clean up
91  if (self->message.code >= 600) {
92  // Dispatch async notifications to async handler
93  // Synchronous and asynchronous messages are never interleaved
94  self->async_handler(*self, self->message);
95  } else {
96  if (!self->reply_handlers.empty()) {
97  // Invoke reply handler with message
98  self->reply_handlers.front()(*self, self->message);
99  self->reply_handlers.pop_front();
100  } else {
101  LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
102  }
103  }
104  self->message.Clear();
105  }
106  }
107  // Check for size of buffer - protect against memory exhaustion with very long lines
108  // Do this after evbuffer_readln to make sure all full lines have been
109  // removed from the buffer. Everything left is an incomplete line.
110  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
111  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
112  self->Disconnect();
113  }
114 }
115 
116 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
117 {
118  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
119  if (what & BEV_EVENT_CONNECTED) {
120  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
121  self->connected(*self);
122  } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
123  if (what & BEV_EVENT_ERROR) {
124  LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
125  } else {
126  LogPrint(BCLog::TOR, "tor: End of stream\n");
127  }
128  self->Disconnect();
129  self->disconnected(*self);
130  }
131 }
132 
133 bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
134 {
135  if (b_conn) {
136  Disconnect();
137  }
138 
139  CService control_service;
140  if (!Lookup(tor_control_center, control_service, 9051, fNameLookup)) {
141  LogPrintf("tor: Failed to look up control center %s\n", tor_control_center);
142  return false;
143  }
144 
145  struct sockaddr_storage control_address;
146  socklen_t control_address_len = sizeof(control_address);
147  if (!control_service.GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) {
148  LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
149  return false;
150  }
151 
152  // Create a new socket, set up callbacks and enable notification bits
153  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
154  if (!b_conn) {
155  return false;
156  }
157  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
158  bufferevent_enable(b_conn, EV_READ|EV_WRITE);
159  this->connected = _connected;
160  this->disconnected = _disconnected;
161 
162  // Finally, connect to tor_control_center
163  if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) {
164  LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
165  return false;
166  }
167  return true;
168 }
169 
171 {
172  if (b_conn)
173  bufferevent_free(b_conn);
174  b_conn = nullptr;
175 }
176 
177 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
178 {
179  if (!b_conn)
180  return false;
181  struct evbuffer *buf = bufferevent_get_output(b_conn);
182  if (!buf)
183  return false;
184  evbuffer_add(buf, cmd.data(), cmd.size());
185  evbuffer_add(buf, "\r\n", 2);
186  reply_handlers.push_back(reply_handler);
187  return true;
188 }
189 
190 /****** General parsing utilities ********/
191 
192 /* Split reply line in the form 'AUTH METHODS=...' into a type
193  * 'AUTH' and arguments 'METHODS=...'.
194  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
195  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
196  */
197 std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
198 {
199  size_t ptr=0;
200  std::string type;
201  while (ptr < s.size() && s[ptr] != ' ') {
202  type.push_back(s[ptr]);
203  ++ptr;
204  }
205  if (ptr < s.size())
206  ++ptr; // skip ' '
207  return make_pair(type, s.substr(ptr));
208 }
209 
216 std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
217 {
218  std::map<std::string,std::string> mapping;
219  size_t ptr=0;
220  while (ptr < s.size()) {
221  std::string key, value;
222  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
223  key.push_back(s[ptr]);
224  ++ptr;
225  }
226  if (ptr == s.size()) // unexpected end of line
227  return std::map<std::string,std::string>();
228  if (s[ptr] == ' ') // The remaining string is an OptArguments
229  break;
230  ++ptr; // skip '='
231  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
232  ++ptr; // skip opening '"'
233  bool escape_next = false;
234  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
235  // Repeated backslashes must be interpreted as pairs
236  escape_next = (s[ptr] == '\\' && !escape_next);
237  value.push_back(s[ptr]);
238  ++ptr;
239  }
240  if (ptr == s.size()) // unexpected end of line
241  return std::map<std::string,std::string>();
242  ++ptr; // skip closing '"'
253  std::string escaped_value;
254  for (size_t i = 0; i < value.size(); ++i) {
255  if (value[i] == '\\') {
256  // This will always be valid, because if the QuotedString
257  // ended in an odd number of backslashes, then the parser
258  // would already have returned above, due to a missing
259  // terminating double-quote.
260  ++i;
261  if (value[i] == 'n') {
262  escaped_value.push_back('\n');
263  } else if (value[i] == 't') {
264  escaped_value.push_back('\t');
265  } else if (value[i] == 'r') {
266  escaped_value.push_back('\r');
267  } else if ('0' <= value[i] && value[i] <= '7') {
268  size_t j;
269  // Octal escape sequences have a limit of three octal digits,
270  // but terminate at the first character that is not a valid
271  // octal digit if encountered sooner.
272  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
273  // Tor restricts first digit to 0-3 for three-digit octals.
274  // A leading digit of 4-7 would therefore be interpreted as
275  // a two-digit octal.
276  if (j == 3 && value[i] > '3') {
277  j--;
278  }
279  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
280  // Account for automatic incrementing at loop end
281  i += j - 1;
282  } else {
283  escaped_value.push_back(value[i]);
284  }
285  } else {
286  escaped_value.push_back(value[i]);
287  }
288  }
289  value = escaped_value;
290  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
291  while (ptr < s.size() && s[ptr] != ' ') {
292  value.push_back(s[ptr]);
293  ++ptr;
294  }
295  }
296  if (ptr < s.size() && s[ptr] == ' ')
297  ++ptr; // skip ' ' after key=value
298  mapping[key] = value;
299  }
300  return mapping;
301 }
302 
303 TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
304  base(_base),
305  m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
306  reconnect_timeout(RECONNECT_TIMEOUT_START),
307  m_target(target)
308 {
309  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
310  if (!reconnect_ev)
311  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
312  // Start connection attempts immediately
313  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
314  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
315  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
316  }
317  // Read service private key if cached
318  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
319  if (pkf.first) {
320  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
321  private_key = pkf.second;
322  }
323 }
324 
326 {
327  if (reconnect_ev) {
328  event_free(reconnect_ev);
329  reconnect_ev = nullptr;
330  }
331  if (service.IsValid()) {
333  }
334 }
335 
337 {
338  if (reply.code == 250) {
339  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
340  for (const std::string &s : reply.lines) {
341  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
342  std::map<std::string,std::string>::iterator i;
343  if ((i = m.find("ServiceID")) != m.end())
344  service_id = i->second;
345  if ((i = m.find("PrivateKey")) != m.end())
346  private_key = i->second;
347  }
348  if (service_id.empty()) {
349  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
350  for (const std::string &s : reply.lines) {
351  LogPrintf(" %s\n", SanitizeString(s));
352  }
353  return;
354  }
355  service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
356  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
358  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
359  } else {
360  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
361  }
363  // ... onion requested - keep connection open
364  } else if (reply.code == 510) { // 510 Unrecognized command
365  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
366  } else {
367  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
368  }
369 }
370 
372 {
373  if (reply.code == 250) {
374  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
375 
376  // Now that we know Tor is running setup the proxy for onion addresses
377  // if -onion isn't set to something else.
378  if (gArgs.GetArg("-onion", "") == "") {
379  CService resolved(LookupNumeric("127.0.0.1", 9050));
380  proxyType addrOnion = proxyType(resolved, true);
381  SetProxy(NET_ONION, addrOnion);
382  SetReachable(NET_ONION, true);
383  }
384 
385  // Finally - now create the service
386  if (private_key.empty()) { // No private key, generate one
387  private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
388  }
389  // Request onion service, redirect port.
390  // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
391  _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringIPPort()),
392  std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
393  } else {
394  LogPrintf("tor: Authentication failed\n");
395  }
396 }
397 
414 static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
415 {
416  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
417  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
418  computeHash.Write(cookie.data(), cookie.size());
419  computeHash.Write(clientNonce.data(), clientNonce.size());
420  computeHash.Write(serverNonce.data(), serverNonce.size());
421  computeHash.Finalize(computedHash.data());
422  return computedHash;
423 }
424 
426 {
427  if (reply.code == 250) {
428  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
429  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
430  if (l.first == "AUTHCHALLENGE") {
431  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
432  if (m.empty()) {
433  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
434  return;
435  }
436  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
437  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
438  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
439  if (serverNonce.size() != 32) {
440  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
441  return;
442  }
443 
444  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
445  if (computedServerHash != serverHash) {
446  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
447  return;
448  }
449 
450  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
451  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
452  } else {
453  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
454  }
455  } else {
456  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
457  }
458 }
459 
461 {
462  if (reply.code == 250) {
463  std::set<std::string> methods;
464  std::string cookiefile;
465  /*
466  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
467  * 250-AUTH METHODS=NULL
468  * 250-AUTH METHODS=HASHEDPASSWORD
469  */
470  for (const std::string &s : reply.lines) {
471  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
472  if (l.first == "AUTH") {
473  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
474  std::map<std::string,std::string>::iterator i;
475  if ((i = m.find("METHODS")) != m.end())
476  boost::split(methods, i->second, boost::is_any_of(","));
477  if ((i = m.find("COOKIEFILE")) != m.end())
478  cookiefile = i->second;
479  } else if (l.first == "VERSION") {
480  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
481  std::map<std::string,std::string>::iterator i;
482  if ((i = m.find("Tor")) != m.end()) {
483  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
484  }
485  }
486  }
487  for (const std::string &s : methods) {
488  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
489  }
490  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
491  /* Authentication:
492  * cookie: hex-encoded ~/.tor/control_auth_cookie
493  * password: "password"
494  */
495  std::string torpassword = gArgs.GetArg("-torpassword", "");
496  if (!torpassword.empty()) {
497  if (methods.count("HASHEDPASSWORD")) {
498  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
499  boost::replace_all(torpassword, "\"", "\\\"");
500  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
501  } else {
502  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
503  }
504  } else if (methods.count("NULL")) {
505  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
506  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
507  } else if (methods.count("SAFECOOKIE")) {
508  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
509  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
510  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
511  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
512  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
513  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
514  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
516  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
517  } else {
518  if (status_cookie.first) {
519  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
520  } else {
521  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
522  }
523  }
524  } else if (methods.count("HASHEDPASSWORD")) {
525  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
526  } else {
527  LogPrintf("tor: No supported authentication method\n");
528  }
529  } else {
530  LogPrintf("tor: Requesting protocol info failed\n");
531  }
532 }
533 
535 {
537  // First send a PROTOCOLINFO command to figure out what authentication is expected
538  if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
539  LogPrintf("tor: Error sending initial protocolinfo command\n");
540 }
541 
543 {
544  // Stop advertising service when disconnected
545  if (service.IsValid())
547  service = CService();
548  if (!reconnect)
549  return;
550 
551  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
552 
553  // Single-shot timer for reconnect. Use exponential backoff.
554  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
555  if (reconnect_ev)
556  event_add(reconnect_ev, &time);
558 }
559 
561 {
562  /* Try to reconnect and reestablish if we get booted - for example, Tor
563  * may be restarting.
564  */
565  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
566  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
567  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
568  }
569 }
570 
572 {
573  return gArgs.GetDataDirNet() / "onion_v3_private_key";
574 }
575 
576 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
577 {
578  TorController *self = static_cast<TorController*>(arg);
579  self->Reconnect();
580 }
581 
582 /****** Thread ********/
583 static struct event_base *gBase;
584 static std::thread torControlThread;
585 
586 static void TorControlThread(CService onion_service_target)
587 {
588  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
589 
590  event_base_dispatch(gBase);
591 }
592 
593 void StartTorControl(CService onion_service_target)
594 {
595  assert(!gBase);
596 #ifdef WIN32
597  evthread_use_windows_threads();
598 #else
599  evthread_use_pthreads();
600 #endif
601  gBase = event_base_new();
602  if (!gBase) {
603  LogPrintf("tor: Unable to create event_base\n");
604  return;
605  }
606 
607  torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
608  TorControlThread(onion_service_target);
609  });
610 }
611 
613 {
614  if (gBase) {
615  LogPrintf("tor: Thread interrupt\n");
616  event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
617  event_base_loopbreak(gBase);
618  }, nullptr, nullptr);
619  }
620 }
621 
623 {
624  if (gBase) {
625  torControlThread.join();
626  event_base_free(gBase);
627  gBase = nullptr;
628  }
629 }
630 
632 {
633  struct in_addr onion_service_target;
634  onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
635  return {onion_service_target, BaseParams().OnionServiceTargetPort()};
636 }
TorControlReply
Reply from Tor, can be single or multi-line.
Definition: torcontrol.h:37
TorController::conn
TorControlConnection conn
Definition: torcontrol.h:129
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:539
CService::GetSockAddr
bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const
Obtain the IPv4/6 socket address this represents.
Definition: netaddress.cpp:982
CHMAC_SHA256::Finalize
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
readwritefile.h
TOR_SAFE_CLIENTKEY
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:47
hmac_sha256.h
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
RemoveLocal
void RemoveLocal(const CService &addr)
Definition: net.cpp:262
TorControlConnection::b_conn
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.h:96
TorControlReply::code
int code
Definition: torcontrol.h:42
TorController::m_tor_control_center
const std::string m_tor_control_center
Definition: torcontrol.h:128
RECONNECT_TIMEOUT_START
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:49
TorController::connected_cb
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:534
util::TraceThread
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
TorController::protocolinfo_cb
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:460
ArgsManager::GetDataDirNet
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:282
TorControlConnection::disconnected
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.h:92
TorControlConnection::ConnectionCB
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.h:58
TorControlConnection
Low-level handling for Tor control connection.
Definition: torcontrol.h:55
atoi
int atoi(const std::string &str)
Definition: strencodings.cpp:449
CHMAC_SHA256
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
TorController::cookie
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.h:138
TorControlConnection::reply_handlers
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.h:100
chainparamsbase.h
StartTorControl
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:593
TorController::~TorController
~TorController()
Definition: torcontrol.cpp:325
InterruptTorControl
void InterruptTorControl()
Definition: torcontrol.cpp:612
TorControlConnection::readcb
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:71
SplitTorReplyLine
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:197
TorControlConnection::Connect
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:133
TorController::disconnected_cb
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:542
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
proxyType
Definition: netbase.h:48
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1028
TorController::reconnect_ev
struct event * reconnect_ev
Definition: torcontrol.h:133
ParseTorReplyMapping
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
Definition: torcontrol.cpp:216
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
TOR_NONCE_SIZE
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:43
strencodings.h
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1037
TOR_COOKIE_SIZE
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:41
CHMAC_SHA256::Write
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:194
torControlThread
static std::thread torControlThread
Definition: torcontrol.cpp:584
DEFAULT_TOR_CONTROL
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:39
TorController::add_onion_cb
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:336
DefaultOnionServiceTarget
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:631
compat.h
TorController::service_id
std::string service_id
Definition: torcontrol.h:131
TorControlConnection::TorControlConnection
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:60
netaddress.h
CBaseChainParams::OnionServiceTargetPort
uint16_t OnionServiceTargetPort() const
Definition: chainparamsbase.h:30
GetRandBytes
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:584
TorControlConnection::ReplyHandlerCB
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.h:59
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:269
time.h
TorControlReply::lines
std::vector< std::string > lines
Definition: torcontrol.h:43
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:588
LogPrintf
#define LogPrintf(...)
Definition: logging.h:184
gBase
static struct event_base * gBase
Definition: torcontrol.cpp:583
TOR_SAFE_SERVERKEY
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:45
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:451
fNameLookup
bool fNameLookup
Definition: netbase.cpp:39
BCLog::TOR
@ TOR
Definition: logging.h:39
TorControlConnection::Disconnect
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:170
TorController::service
CService service
Definition: torcontrol.h:135
TorController::base
struct event_base * base
Definition: torcontrol.h:127
LogPrint
#define LogPrint(category,...)
Definition: logging.h:188
TorController::auth_cb
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:371
MAX_LINE_LENGTH
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:56
gArgs
ArgsManager gArgs
Definition: system.cpp:84
TorController::reconnect
bool reconnect
Definition: torcontrol.h:132
CHMAC_SHA256::OUTPUT_SIZE
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
system.h
TorController::Reconnect
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:560
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:607
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
TorController::clientNonce
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.h:140
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:27
ComputeResponse
static std::vector< uint8_t > ComputeResponse(const std::string &key, const std::vector< uint8_t > &cookie, const std::vector< uint8_t > &clientNonce, const std::vector< uint8_t > &serverNonce)
Compute Tor SAFECOOKIE response.
Definition: torcontrol.cpp:414
torcontrol.h
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:33
TorControlConnection::Command
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:177
TorController::m_target
const CService m_target
Definition: torcontrol.h:136
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:56
TorController::reconnect_timeout
float reconnect_timeout
Definition: torcontrol.h:134
MillisToTimeval
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:172
TorController::authchallenge_cb
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:425
RECONNECT_TIMEOUT_EXP
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:51
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:536
TorController
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.h:112
assert
assert(s1.IsAddrV1Compatible())
StopTorControl
void StopTorControl()
Definition: torcontrol.cpp:622
netbase.h
TorController::TorController
TorController()
Definition: torcontrol.h:116
TorController::private_key
std::string private_key
Definition: torcontrol.h:130
LookupNumeric
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:229
TorController::GetPrivateKeyFile
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:571
TorControlConnection::~TorControlConnection
~TorControlConnection()
Definition: torcontrol.cpp:65
Lookup
bool Lookup(const std::string &name, std::vector< CService > &vAddr, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:197
net.h
TorControlConnection::eventcb
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:116
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
thread.h
TorControlConnection::base
struct event_base * base
Libevent event base.
Definition: torcontrol.h:94
TorControlThread
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:586
TorControlConnection::connected
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.h:90
TorController::reconnect_cb
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:576
ctx
static secp256k1_context * ctx
Definition: tests.c:42
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:231