Bitcoin ABC  0.26.3
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2016 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 <boost/algorithm/string/classification.hpp>
22 #include <boost/algorithm/string/replace.hpp>
23 #include <boost/algorithm/string/split.hpp>
24 #include <boost/signals2/signal.hpp>
25 
26 #include <event2/buffer.h>
27 #include <event2/bufferevent.h>
28 #include <event2/event.h>
29 #include <event2/thread.h>
30 #include <event2/util.h>
31 
32 #include <cstdlib>
33 #include <deque>
34 #include <functional>
35 #include <set>
36 #include <vector>
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 =
46  "Tor safe cookie authentication server-to-controller hash";
48 static const std::string TOR_SAFE_CLIENTKEY =
49  "Tor safe cookie authentication controller-to-server hash";
51 static const float RECONNECT_TIMEOUT_START = 1.0;
53 static const float RECONNECT_TIMEOUT_EXP = 1.5;
60 static const int MAX_LINE_LENGTH = 100000;
61 
62 /****** Low-level TorControlConnection ********/
63 
66 public:
68 
69  int code;
70  std::vector<std::string> lines;
71 
72  void Clear() {
73  code = 0;
74  lines.clear();
75  }
76 };
77 
83 public:
84  typedef std::function<void(TorControlConnection &)> ConnectionCB;
85  typedef std::function<void(TorControlConnection &, const TorControlReply &)>
87 
90  explicit TorControlConnection(struct event_base *base);
92 
101  bool Connect(const std::string &tor_control_center,
102  const ConnectionCB &connected,
103  const ConnectionCB &disconnected);
104 
108  void Disconnect();
109 
115  bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler);
116 
118  boost::signals2::signal<void(TorControlConnection &,
119  const TorControlReply &)>
121 
122 private:
124  std::function<void(TorControlConnection &)> connected;
126  std::function<void(TorControlConnection &)> disconnected;
128  struct event_base *base;
130  struct bufferevent *b_conn;
134  std::deque<ReplyHandlerCB> reply_handlers;
135 
137  static void readcb(struct bufferevent *bev, void *ctx);
138  static void eventcb(struct bufferevent *bev, short what, void *ctx);
139 };
140 
142  : base(_base), b_conn(nullptr) {}
143 
145  if (b_conn) {
146  bufferevent_free(b_conn);
147  }
148 }
149 
150 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx) {
151  TorControlConnection *self = static_cast<TorControlConnection *>(ctx);
152  struct evbuffer *input = bufferevent_get_input(bev);
153  size_t n_read_out = 0;
154  char *line;
155  assert(input);
156  // If there is not a whole line to read, evbuffer_readln returns nullptr
157  while ((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
158  nullptr) {
159  std::string s(line, n_read_out);
160  free(line);
161  // Short line
162  if (s.size() < 4) {
163  continue;
164  }
165  // <status>(-|+| )<data><CRLF>
166  self->message.code = atoi(s.substr(0, 3));
167  self->message.lines.push_back(s.substr(4));
168  // '-','+' or ' '
169  char ch = s[3];
170  if (ch == ' ') {
171  // Final line, dispatch reply and clean up
172  if (self->message.code >= 600) {
173  // Dispatch async notifications to async handler.
174  // Synchronous and asynchronous messages are never interleaved
175  self->async_handler(*self, self->message);
176  } else {
177  if (!self->reply_handlers.empty()) {
178  // Invoke reply handler with message
179  self->reply_handlers.front()(*self, self->message);
180  self->reply_handlers.pop_front();
181  } else {
183  "tor: Received unexpected sync reply %i\n",
184  self->message.code);
185  }
186  }
187  self->message.Clear();
188  }
189  }
190 
191  // Check for size of buffer - protect against memory exhaustion with very
192  // long lines. Do this after evbuffer_readln to make sure all full lines
193  // have been removed from the buffer. Everything left is an incomplete line.
194  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
195  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
196  self->Disconnect();
197  }
198 }
199 
200 void TorControlConnection::eventcb(struct bufferevent *bev, short what,
201  void *ctx) {
202  TorControlConnection *self = static_cast<TorControlConnection *>(ctx);
203  if (what & BEV_EVENT_CONNECTED) {
204  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
205  self->connected(*self);
206  } else if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
207  if (what & BEV_EVENT_ERROR) {
209  "tor: Error connecting to Tor control socket\n");
210  } else {
211  LogPrint(BCLog::TOR, "tor: End of stream\n");
212  }
213  self->Disconnect();
214  self->disconnected(*self);
215  }
216 }
217 
218 bool TorControlConnection::Connect(const std::string &tor_control_center,
219  const ConnectionCB &_connected,
220  const ConnectionCB &_disconnected) {
221  if (b_conn) {
222  Disconnect();
223  }
224  // Parse tor_control_center address:port
225  struct sockaddr_storage connect_to_addr;
226  int connect_to_addrlen = sizeof(connect_to_addr);
227  if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
228  (struct sockaddr *)&connect_to_addr,
229  &connect_to_addrlen) < 0) {
230  LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
231  return false;
232  }
233 
234  // Create a new socket, set up callbacks and enable notification bits
235  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
236  if (!b_conn) {
237  return false;
238  }
239  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr,
241  bufferevent_enable(b_conn, EV_READ | EV_WRITE);
242  this->connected = _connected;
243  this->disconnected = _disconnected;
244 
245  // Finally, connect to tor_control_center
246  if (bufferevent_socket_connect(b_conn, (struct sockaddr *)&connect_to_addr,
247  connect_to_addrlen) < 0) {
248  LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
249  return false;
250  }
251  return true;
252 }
253 
255  if (b_conn) {
256  bufferevent_free(b_conn);
257  }
258  b_conn = nullptr;
259 }
260 
261 bool TorControlConnection::Command(const std::string &cmd,
262  const ReplyHandlerCB &reply_handler) {
263  if (!b_conn) {
264  return false;
265  }
266  struct evbuffer *buf = bufferevent_get_output(b_conn);
267  if (!buf) {
268  return false;
269  }
270  evbuffer_add(buf, cmd.data(), cmd.size());
271  evbuffer_add(buf, "\r\n", 2);
272  reply_handlers.push_back(reply_handler);
273  return true;
274 }
275 
276 /****** General parsing utilities ********/
277 
278 /* Split reply line in the form 'AUTH METHODS=...' into a type
279  * 'AUTH' and arguments 'METHODS=...'.
280  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
281  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
282  */
283 std::pair<std::string, std::string> SplitTorReplyLine(const std::string &s) {
284  size_t ptr = 0;
285  std::string type;
286  while (ptr < s.size() && s[ptr] != ' ') {
287  type.push_back(s[ptr]);
288  ++ptr;
289  }
290  if (ptr < s.size()) {
291  // skip ' '
292  ++ptr;
293  }
294  return make_pair(type, s.substr(ptr));
295 }
296 
305 std::map<std::string, std::string> ParseTorReplyMapping(const std::string &s) {
306  std::map<std::string, std::string> mapping;
307  size_t ptr = 0;
308  while (ptr < s.size()) {
309  std::string key, value;
310  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
311  key.push_back(s[ptr]);
312  ++ptr;
313  }
314  // unexpected end of line
315  if (ptr == s.size()) {
316  return std::map<std::string, std::string>();
317  }
318  // The remaining string is an OptArguments
319  if (s[ptr] == ' ') {
320  break;
321  }
322  // skip '='
323  ++ptr;
324  // Quoted string
325  if (ptr < s.size() && s[ptr] == '"') {
326  // skip opening '"'
327  ++ptr;
328  bool escape_next = false;
329  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
330  // Repeated backslashes must be interpreted as pairs
331  escape_next = (s[ptr] == '\\' && !escape_next);
332  value.push_back(s[ptr]);
333  ++ptr;
334  }
335  // unexpected end of line
336  if (ptr == s.size()) {
337  return std::map<std::string, std::string>();
338  }
339  // skip closing '"'
340  ++ptr;
353  std::string escaped_value;
354  for (size_t i = 0; i < value.size(); ++i) {
355  if (value[i] == '\\') {
356  // This will always be valid, because if the QuotedString
357  // ended in an odd number of backslashes, then the parser
358  // would already have returned above, due to a missing
359  // terminating double-quote.
360  ++i;
361  if (value[i] == 'n') {
362  escaped_value.push_back('\n');
363  } else if (value[i] == 't') {
364  escaped_value.push_back('\t');
365  } else if (value[i] == 'r') {
366  escaped_value.push_back('\r');
367  } else if ('0' <= value[i] && value[i] <= '7') {
368  size_t j;
369  // Octal escape sequences have a limit of three octal
370  // digits, but terminate at the first character that is
371  // not a valid octal digit if encountered sooner.
372  for (j = 1; j < 3 && (i + j) < value.size() &&
373  '0' <= value[i + j] && value[i + j] <= '7';
374  ++j) {
375  }
376  // Tor restricts first digit to 0-3 for three-digit
377  // octals. A leading digit of 4-7 would therefore be
378  // interpreted as a two-digit octal.
379  if (j == 3 && value[i] > '3') {
380  j--;
381  }
382  escaped_value.push_back(
383  strtol(value.substr(i, j).c_str(), NULL, 8));
384  // Account for automatic incrementing at loop end
385  i += j - 1;
386  } else {
387  escaped_value.push_back(value[i]);
388  }
389  } else {
390  escaped_value.push_back(value[i]);
391  }
392  }
393  value = escaped_value;
394  } else {
395  // Unquoted value. Note that values can contain '=' at will, just no
396  // spaces
397  while (ptr < s.size() && s[ptr] != ' ') {
398  value.push_back(s[ptr]);
399  ++ptr;
400  }
401  }
402  if (ptr < s.size() && s[ptr] == ' ') {
403  // skip ' ' after key=value
404  ++ptr;
405  }
406  mapping[key] = value;
407  }
408  return mapping;
409 }
410 
411 /****** Bitcoin specific TorController implementation ********/
412 
418 public:
419  TorController(struct event_base *base,
420  const std::string &tor_control_center,
421  const CService &target);
422  ~TorController();
423 
426 
428  void Reconnect();
429 
430 private:
431  struct event_base *base;
432  const std::string m_tor_control_center;
434  std::string private_key;
435  std::string service_id;
436  bool reconnect;
437  struct event *reconnect_ev;
442  std::vector<uint8_t> cookie;
444  std::vector<uint8_t> clientNonce;
445 
449  void auth_cb(TorControlConnection &conn, const TorControlReply &reply);
452  const TorControlReply &reply);
455  const TorControlReply &reply);
460 
462  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
463 };
464 
465 TorController::TorController(struct event_base *_base,
466  const std::string &tor_control_center,
467  const CService &target)
468  : base(_base), m_tor_control_center(tor_control_center), conn(base),
469  reconnect(true), reconnect_ev(0),
470  reconnect_timeout(RECONNECT_TIMEOUT_START), m_target(target) {
471  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
472  if (!reconnect_ev) {
473  LogPrintf(
474  "tor: Failed to create event for reconnection: out of memory?\n");
475  }
476  // Start connection attempts immediately
478  std::bind(&TorController::connected_cb, this,
479  std::placeholders::_1),
480  std::bind(&TorController::disconnected_cb, this,
481  std::placeholders::_1))) {
482  LogPrintf("tor: Initiating connection to Tor control port %s failed\n",
484  }
485  // Read service private key if cached
486  std::pair<bool, std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
487  if (pkf.first) {
488  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n",
490  private_key = pkf.second;
491  }
492 }
493 
495  if (reconnect_ev) {
496  event_free(reconnect_ev);
497  reconnect_ev = nullptr;
498  }
499  if (service.IsValid()) {
501  }
502 }
503 
505  const TorControlReply &reply) {
506  if (reply.code == 250) {
507  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
508  for (const std::string &s : reply.lines) {
509  std::map<std::string, std::string> m = ParseTorReplyMapping(s);
510  std::map<std::string, std::string>::iterator i;
511  if ((i = m.find("ServiceID")) != m.end()) {
512  service_id = i->second;
513  }
514  if ((i = m.find("PrivateKey")) != m.end()) {
515  private_key = i->second;
516  }
517  }
518  if (service_id.empty()) {
519  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
520  for (const std::string &s : reply.lines) {
521  LogPrintf(" %s\n", SanitizeString(s));
522  }
523  return;
524  }
525  service = LookupNumeric(std::string(service_id + ".onion"),
526  Params().GetDefaultPort());
527  LogPrintf("tor: Got service ID %s, advertising service %s\n",
530  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n",
532  } else {
533  LogPrintf("tor: Error writing service private key to %s\n",
535  }
537  // ... onion requested - keep connection open
538  } else if (reply.code == 510) { // 510 Unrecognized command
539  LogPrintf("tor: Add onion failed with unrecognized command (You "
540  "probably need to upgrade Tor)\n");
541  } else {
542  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
543  }
544 }
545 
547  const TorControlReply &reply) {
548  if (reply.code == 250) {
549  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
550 
551  // Now that we know Tor is running setup the proxy for onion addresses
552  // if -onion isn't set to something else.
553  if (gArgs.GetArg("-onion", "") == "") {
554  CService resolved(LookupNumeric("127.0.0.1", 9050));
555  proxyType addrOnion = proxyType(resolved, true);
556  SetProxy(NET_ONION, addrOnion);
557  SetReachable(NET_ONION, true);
558  }
559 
560  // Finally - now create the service
561  // No private key, generate one
562  if (private_key.empty()) {
563  // Explicitly request key type - see issue #9214
564  private_key = "NEW:ED25519-V3";
565  }
566  // Request onion service, redirect port.
567  // Note that the 'virtual' port doesn't have to be the same as our
568  // internal port, but this is just a convenient choice. TODO; refactor
569  // the shutdown sequence some day.
570  _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key,
573  std::bind(&TorController::add_onion_cb, this,
574  std::placeholders::_1, std::placeholders::_2));
575  } else {
576  LogPrintf("tor: Authentication failed\n");
577  }
578 }
579 
596 static std::vector<uint8_t>
597 ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie,
598  const std::vector<uint8_t> &clientNonce,
599  const std::vector<uint8_t> &serverNonce) {
600  CHMAC_SHA256 computeHash((const uint8_t *)key.data(), key.size());
601  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
602  computeHash.Write(cookie.data(), cookie.size());
603  computeHash.Write(clientNonce.data(), clientNonce.size());
604  computeHash.Write(serverNonce.data(), serverNonce.size());
605  computeHash.Finalize(computedHash.data());
606  return computedHash;
607 }
608 
610  const TorControlReply &reply) {
611  if (reply.code == 250) {
613  "tor: SAFECOOKIE authentication challenge successful\n");
614  std::pair<std::string, std::string> l =
615  SplitTorReplyLine(reply.lines[0]);
616  if (l.first == "AUTHCHALLENGE") {
617  std::map<std::string, std::string> m =
618  ParseTorReplyMapping(l.second);
619  if (m.empty()) {
620  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n",
621  SanitizeString(l.second));
622  return;
623  }
624  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
625  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
627  "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
628  HexStr(serverHash), HexStr(serverNonce));
629  if (serverNonce.size() != 32) {
630  LogPrintf(
631  "tor: ServerNonce is not 32 bytes, as required by spec\n");
632  return;
633  }
634 
635  std::vector<uint8_t> computedServerHash = ComputeResponse(
636  TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
637  if (computedServerHash != serverHash) {
638  LogPrintf("tor: ServerHash %s does not match expected "
639  "ServerHash %s\n",
640  HexStr(serverHash), HexStr(computedServerHash));
641  return;
642  }
643 
644  std::vector<uint8_t> computedClientHash = ComputeResponse(
645  TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
646  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash),
647  std::bind(&TorController::auth_cb, this,
648  std::placeholders::_1,
649  std::placeholders::_2));
650  } else {
651  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
652  }
653  } else {
654  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
655  }
656 }
657 
659  const TorControlReply &reply) {
660  if (reply.code == 250) {
661  std::set<std::string> methods;
662  std::string cookiefile;
663  /*
664  * 250-AUTH METHODS=COOKIE,SAFECOOKIE
665  * COOKIEFILE="/home/x/.tor/control_auth_cookie"
666  * 250-AUTH METHODS=NULL
667  * 250-AUTH METHODS=HASHEDPASSWORD
668  */
669  for (const std::string &s : reply.lines) {
670  std::pair<std::string, std::string> l = SplitTorReplyLine(s);
671  if (l.first == "AUTH") {
672  std::map<std::string, std::string> m =
673  ParseTorReplyMapping(l.second);
674  std::map<std::string, std::string>::iterator i;
675  if ((i = m.find("METHODS")) != m.end()) {
676  boost::split(methods, i->second, boost::is_any_of(","));
677  }
678  if ((i = m.find("COOKIEFILE")) != m.end()) {
679  cookiefile = i->second;
680  }
681  } else if (l.first == "VERSION") {
682  std::map<std::string, std::string> m =
683  ParseTorReplyMapping(l.second);
684  std::map<std::string, std::string>::iterator i;
685  if ((i = m.find("Tor")) != m.end()) {
686  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n",
687  i->second);
688  }
689  }
690  }
691  for (const std::string &s : methods) {
692  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n",
693  s);
694  }
695  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use
696  // HASHEDPASSWORD
697  /* Authentication:
698  * cookie: hex-encoded ~/.tor/control_auth_cookie
699  * password: "password"
700  */
701  std::string torpassword = gArgs.GetArg("-torpassword", "");
702  if (!torpassword.empty()) {
703  if (methods.count("HASHEDPASSWORD")) {
705  "tor: Using HASHEDPASSWORD authentication\n");
706  boost::replace_all(torpassword, "\"", "\\\"");
707  _conn.Command("AUTHENTICATE \"" + torpassword + "\"",
708  std::bind(&TorController::auth_cb, this,
709  std::placeholders::_1,
710  std::placeholders::_2));
711  } else {
712  LogPrintf("tor: Password provided with -torpassword, but "
713  "HASHEDPASSWORD authentication is not available\n");
714  }
715  } else if (methods.count("NULL")) {
716  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
717  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb,
718  this, std::placeholders::_1,
719  std::placeholders::_2));
720  } else if (methods.count("SAFECOOKIE")) {
721  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
723  "tor: Using SAFECOOKIE authentication, "
724  "reading cookie authentication from %s\n",
725  cookiefile);
726  std::pair<bool, std::string> status_cookie =
728  if (status_cookie.first &&
729  status_cookie.second.size() == TOR_COOKIE_SIZE) {
730  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second),
731  // std::bind(&TorController::auth_cb, this,
732  // std::placeholders::_1, std::placeholders::_2));
733  cookie = std::vector<uint8_t>(status_cookie.second.begin(),
734  status_cookie.second.end());
735  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
737  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce),
738  std::bind(&TorController::authchallenge_cb, this,
739  std::placeholders::_1,
740  std::placeholders::_2));
741  } else {
742  if (status_cookie.first) {
743  LogPrintf("tor: Authentication cookie %s is not exactly %i "
744  "bytes, as is required by the spec\n",
745  cookiefile, TOR_COOKIE_SIZE);
746  } else {
747  LogPrintf("tor: Authentication cookie %s could not be "
748  "opened (check permissions)\n",
749  cookiefile);
750  }
751  }
752  } else if (methods.count("HASHEDPASSWORD")) {
753  LogPrintf("tor: The only supported authentication mechanism left "
754  "is password, but no password provided with "
755  "-torpassword\n");
756  } else {
757  LogPrintf("tor: No supported authentication method\n");
758  }
759  } else {
760  LogPrintf("tor: Requesting protocol info failed\n");
761  }
762 }
763 
766  // First send a PROTOCOLINFO command to figure out what authentication is
767  // expected
768  if (!_conn.Command("PROTOCOLINFO 1",
769  std::bind(&TorController::protocolinfo_cb, this,
770  std::placeholders::_1,
771  std::placeholders::_2))) {
772  LogPrintf("tor: Error sending initial protocolinfo command\n");
773  }
774 }
775 
777  // Stop advertising service when disconnected
778  if (service.IsValid()) {
780  }
781  service = CService();
782  if (!reconnect) {
783  return;
784  }
785 
787  "tor: Not connected to Tor control port %s, trying to reconnect\n",
789 
790  // Single-shot timer for reconnect. Use exponential backoff.
791  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
792  if (reconnect_ev) {
793  event_add(reconnect_ev, &time);
794  }
796 }
797 
799  /* Try to reconnect and reestablish if we get booted - for example, Tor may
800  * be restarting.
801  */
803  std::bind(&TorController::connected_cb, this,
804  std::placeholders::_1),
805  std::bind(&TorController::disconnected_cb, this,
806  std::placeholders::_1))) {
807  LogPrintf(
808  "tor: Re-initiating connection to Tor control port %s failed\n",
810  }
811 }
812 
814  return gArgs.GetDataDirNet() / "onion_v3_private_key";
815 }
816 
817 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg) {
818  TorController *self = static_cast<TorController *>(arg);
819  self->Reconnect();
820 }
821 
822 /****** Thread ********/
823 static struct event_base *gBase;
824 static std::thread torControlThread;
825 
826 static void TorControlThread(CService onion_service_target) {
827  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL),
828  onion_service_target);
829 
830  event_base_dispatch(gBase);
831 }
832 
833 void StartTorControl(CService onion_service_target) {
834  assert(!gBase);
835 #ifdef WIN32
836  evthread_use_windows_threads();
837 #else
838  evthread_use_pthreads();
839 #endif
840  gBase = event_base_new();
841  if (!gBase) {
842  LogPrintf("tor: Unable to create event_base\n");
843  return;
844  }
845 
847  std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
848  TorControlThread(onion_service_target);
849  });
850 }
851 
853  if (gBase) {
854  LogPrintf("tor: Thread interrupt\n");
855  event_base_once(
856  gBase, -1, EV_TIMEOUT,
857  [](evutil_socket_t, short, void *) { event_base_loopbreak(gBase); },
858  nullptr, nullptr);
859  }
860 }
861 
863  if (gBase) {
864  torControlThread.join();
865  event_base_free(gBase);
866  gBase = nullptr;
867  }
868 }
869 
871  struct in_addr onion_service_target;
872  onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
873  return {onion_service_target, BaseParams().OnionServiceTargetPort()};
874 }
secp256k1_context * ctx
const CChainParams & Params()
Return the currently selected parameters.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:257
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:584
uint16_t OnionServiceTargetPort() const
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
CHMAC_SHA256 & Write(const uint8_t *data, size_t len)
Definition: hmac_sha256.h:23
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:20
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:30
bool IsValid() const
Definition: netaddress.cpp:479
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
std::string ToStringIPPort() const
std::string ToString() const
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:82
TorControlReply message
Message being received.
Definition: torcontrol.cpp:132
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:134
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:218
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:141
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:261
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.cpp:124
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:120
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:150
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.cpp:126
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:200
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.cpp:86
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:254
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.cpp:130
struct event_base * base
Libevent event base.
Definition: torcontrol.cpp:128
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.cpp:84
Reply from Tor, can be single or multi-line.
Definition: torcontrol.cpp:65
std::vector< std::string > lines
Definition: torcontrol.cpp:70
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.cpp:417
TorControlConnection conn
Definition: torcontrol.cpp:433
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:817
std::string service_id
Definition: torcontrol.cpp:435
struct event_base * base
Definition: torcontrol.cpp:431
fs::path GetPrivateKeyFile()
Get name fo file to store private key in.
Definition: torcontrol.cpp:813
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:444
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:764
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:504
const std::string m_tor_control_center
Definition: torcontrol.cpp:432
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:776
const CService m_target
Definition: torcontrol.cpp:440
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:609
CService service
Definition: torcontrol.cpp:439
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.cpp:442
struct event * reconnect_ev
Definition: torcontrol.cpp:437
TorController(struct event_base *base, const std::string &tor_control_center, const CService &target)
Definition: torcontrol.cpp:465
float reconnect_timeout
Definition: torcontrol.cpp:438
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:546
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:798
std::string private_key
Definition: torcontrol.cpp:434
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:658
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
#define LogPrint(category,...)
Definition: logging.h:208
#define LogPrintf(...)
Definition: logging.h:204
@ TOR
Definition: logging.h:40
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:134
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:147
void TraceThread(const char *thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:13
void RemoveLocal(const CService &addr)
Definition: net.cpp:273
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:279
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:241
@ LOCAL_MANUAL
Definition: net.h:235
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:57
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:260
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:710
void GetRandBytes(uint8_t *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:634
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.
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
static uint16_t GetDefaultPort()
Definition: bitcoin.h:16
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
int atoi(const std::string &str)
std::vector< uint8_t > ParseHex(const char *psz)
ArgsManager gArgs
Definition: system.cpp:77
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:167
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:48
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:870
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:60
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:597
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:53
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:39
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:826
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:45
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:41
static struct event_base * gBase
Definition: torcontrol.cpp:823
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:43
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:305
void InterruptTorControl()
Definition: torcontrol.cpp:852
static std::thread torControlThread
Definition: torcontrol.cpp:824
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:283
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:51
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:833
void StopTorControl()
Definition: torcontrol.cpp:862
assert(!tx.IsCoinBase())