Bitcoin Core  0.18.99
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2018 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 <chainparams.h>
7 #include <torcontrol.h>
8 #include <util/strencodings.h>
9 #include <netbase.h>
10 #include <net.h>
11 #include <util/system.h>
12 #include <crypto/hmac_sha256.h>
13 
14 #include <vector>
15 #include <deque>
16 #include <set>
17 #include <stdlib.h>
18 
19 #include <boost/signals2/signal.hpp>
20 #include <boost/algorithm/string/split.hpp>
21 #include <boost/algorithm/string/classification.hpp>
22 #include <boost/algorithm/string/replace.hpp>
23 
24 #include <event2/bufferevent.h>
25 #include <event2/buffer.h>
26 #include <event2/util.h>
27 #include <event2/event.h>
28 #include <event2/thread.h>
29 
31 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
33 static const int TOR_COOKIE_SIZE = 32;
35 static const int TOR_NONCE_SIZE = 32;
37 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
39 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
41 static const float RECONNECT_TIMEOUT_START = 1.0;
43 static const float RECONNECT_TIMEOUT_EXP = 1.5;
48 static const int MAX_LINE_LENGTH = 100000;
49 
50 /****** Low-level TorControlConnection ********/
51 
54 {
55 public:
57 
58  int code;
59  std::vector<std::string> lines;
60 
61  void Clear()
62  {
63  code = 0;
64  lines.clear();
65  }
66 };
67 
72 {
73 public:
74  typedef std::function<void(TorControlConnection&)> ConnectionCB;
75  typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
76 
79  explicit TorControlConnection(struct event_base *base);
81 
89  bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
90 
94  void Disconnect();
95 
100  bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
101 
103  boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
104 private:
106  std::function<void(TorControlConnection&)> connected;
108  std::function<void(TorControlConnection&)> disconnected;
110  struct event_base *base;
112  struct bufferevent *b_conn;
116  std::deque<ReplyHandlerCB> reply_handlers;
117 
119  static void readcb(struct bufferevent *bev, void *ctx);
120  static void eventcb(struct bufferevent *bev, short what, void *ctx);
121 };
122 
124  base(_base), b_conn(nullptr)
125 {
126 }
127 
129 {
130  if (b_conn)
131  bufferevent_free(b_conn);
132 }
133 
134 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
135 {
136  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
137  struct evbuffer *input = bufferevent_get_input(bev);
138  size_t n_read_out = 0;
139  char *line;
140  assert(input);
141  // If there is not a whole line to read, evbuffer_readln returns nullptr
142  while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
143  {
144  std::string s(line, n_read_out);
145  free(line);
146  if (s.size() < 4) // Short line
147  continue;
148  // <status>(-|+| )<data><CRLF>
149  self->message.code = atoi(s.substr(0,3));
150  self->message.lines.push_back(s.substr(4));
151  char ch = s[3]; // '-','+' or ' '
152  if (ch == ' ') {
153  // Final line, dispatch reply and clean up
154  if (self->message.code >= 600) {
155  // Dispatch async notifications to async handler
156  // Synchronous and asynchronous messages are never interleaved
157  self->async_handler(*self, self->message);
158  } else {
159  if (!self->reply_handlers.empty()) {
160  // Invoke reply handler with message
161  self->reply_handlers.front()(*self, self->message);
162  self->reply_handlers.pop_front();
163  } else {
164  LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
165  }
166  }
167  self->message.Clear();
168  }
169  }
170  // Check for size of buffer - protect against memory exhaustion with very long lines
171  // Do this after evbuffer_readln to make sure all full lines have been
172  // removed from the buffer. Everything left is an incomplete line.
173  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
174  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
175  self->Disconnect();
176  }
177 }
178 
179 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
180 {
181  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
182  if (what & BEV_EVENT_CONNECTED) {
183  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
184  self->connected(*self);
185  } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
186  if (what & BEV_EVENT_ERROR) {
187  LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
188  } else {
189  LogPrint(BCLog::TOR, "tor: End of stream\n");
190  }
191  self->Disconnect();
192  self->disconnected(*self);
193  }
194 }
195 
196 bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
197 {
198  if (b_conn)
199  Disconnect();
200  // Parse target address:port
201  struct sockaddr_storage connect_to_addr;
202  int connect_to_addrlen = sizeof(connect_to_addr);
203  if (evutil_parse_sockaddr_port(target.c_str(),
204  (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
205  LogPrintf("tor: Error parsing socket address %s\n", target);
206  return false;
207  }
208 
209  // Create a new socket, set up callbacks and enable notification bits
210  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
211  if (!b_conn)
212  return false;
213  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
214  bufferevent_enable(b_conn, EV_READ|EV_WRITE);
215  this->connected = _connected;
216  this->disconnected = _disconnected;
217 
218  // Finally, connect to target
219  if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
220  LogPrintf("tor: Error connecting to address %s\n", target);
221  return false;
222  }
223  return true;
224 }
225 
227 {
228  if (b_conn)
229  bufferevent_free(b_conn);
230  b_conn = nullptr;
231 }
232 
233 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
234 {
235  if (!b_conn)
236  return false;
237  struct evbuffer *buf = bufferevent_get_output(b_conn);
238  if (!buf)
239  return false;
240  evbuffer_add(buf, cmd.data(), cmd.size());
241  evbuffer_add(buf, "\r\n", 2);
242  reply_handlers.push_back(reply_handler);
243  return true;
244 }
245 
246 /****** General parsing utilities ********/
247 
248 /* Split reply line in the form 'AUTH METHODS=...' into a type
249  * 'AUTH' and arguments 'METHODS=...'.
250  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
251  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
252  */
253 std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
254 {
255  size_t ptr=0;
256  std::string type;
257  while (ptr < s.size() && s[ptr] != ' ') {
258  type.push_back(s[ptr]);
259  ++ptr;
260  }
261  if (ptr < s.size())
262  ++ptr; // skip ' '
263  return make_pair(type, s.substr(ptr));
264 }
265 
272 std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
273 {
274  std::map<std::string,std::string> mapping;
275  size_t ptr=0;
276  while (ptr < s.size()) {
277  std::string key, value;
278  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
279  key.push_back(s[ptr]);
280  ++ptr;
281  }
282  if (ptr == s.size()) // unexpected end of line
283  return std::map<std::string,std::string>();
284  if (s[ptr] == ' ') // The remaining string is an OptArguments
285  break;
286  ++ptr; // skip '='
287  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
288  ++ptr; // skip opening '"'
289  bool escape_next = false;
290  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
291  // Repeated backslashes must be interpreted as pairs
292  escape_next = (s[ptr] == '\\' && !escape_next);
293  value.push_back(s[ptr]);
294  ++ptr;
295  }
296  if (ptr == s.size()) // unexpected end of line
297  return std::map<std::string,std::string>();
298  ++ptr; // skip closing '"'
309  std::string escaped_value;
310  for (size_t i = 0; i < value.size(); ++i) {
311  if (value[i] == '\\') {
312  // This will always be valid, because if the QuotedString
313  // ended in an odd number of backslashes, then the parser
314  // would already have returned above, due to a missing
315  // terminating double-quote.
316  ++i;
317  if (value[i] == 'n') {
318  escaped_value.push_back('\n');
319  } else if (value[i] == 't') {
320  escaped_value.push_back('\t');
321  } else if (value[i] == 'r') {
322  escaped_value.push_back('\r');
323  } else if ('0' <= value[i] && value[i] <= '7') {
324  size_t j;
325  // Octal escape sequences have a limit of three octal digits,
326  // but terminate at the first character that is not a valid
327  // octal digit if encountered sooner.
328  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
329  // Tor restricts first digit to 0-3 for three-digit octals.
330  // A leading digit of 4-7 would therefore be interpreted as
331  // a two-digit octal.
332  if (j == 3 && value[i] > '3') {
333  j--;
334  }
335  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
336  // Account for automatic incrementing at loop end
337  i += j - 1;
338  } else {
339  escaped_value.push_back(value[i]);
340  }
341  } else {
342  escaped_value.push_back(value[i]);
343  }
344  }
345  value = escaped_value;
346  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
347  while (ptr < s.size() && s[ptr] != ' ') {
348  value.push_back(s[ptr]);
349  ++ptr;
350  }
351  }
352  if (ptr < s.size() && s[ptr] == ' ')
353  ++ptr; // skip ' ' after key=value
354  mapping[key] = value;
355  }
356  return mapping;
357 }
358 
366 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
367 {
368  FILE *f = fsbridge::fopen(filename, "rb");
369  if (f == nullptr)
370  return std::make_pair(false,"");
371  std::string retval;
372  char buffer[128];
373  size_t n;
374  while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
375  // Check for reading errors so we don't return any data if we couldn't
376  // read the entire file (or up to maxsize)
377  if (ferror(f)) {
378  fclose(f);
379  return std::make_pair(false,"");
380  }
381  retval.append(buffer, buffer+n);
382  if (retval.size() > maxsize)
383  break;
384  }
385  fclose(f);
386  return std::make_pair(true,retval);
387 }
388 
392 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
393 {
394  FILE *f = fsbridge::fopen(filename, "wb");
395  if (f == nullptr)
396  return false;
397  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
398  fclose(f);
399  return false;
400  }
401  fclose(f);
402  return true;
403 }
404 
405 /****** Bitcoin specific TorController implementation ********/
406 
411 {
412 public:
413  TorController(struct event_base* base, const std::string& target);
414  ~TorController();
415 
417  fs::path GetPrivateKeyFile();
418 
420  void Reconnect();
421 private:
422  struct event_base* base;
423  std::string target;
425  std::string private_key;
426  std::string service_id;
427  bool reconnect;
428  struct event *reconnect_ev;
432  std::vector<uint8_t> cookie;
434  std::vector<uint8_t> clientNonce;
435 
437  void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
439  void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
441  void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
443  void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
445  void connected_cb(TorControlConnection& conn);
447  void disconnected_cb(TorControlConnection& conn);
448 
450  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
451 };
452 
453 TorController::TorController(struct event_base* _base, const std::string& _target):
454  base(_base),
455  target(_target), conn(base), reconnect(true), reconnect_ev(0),
456  reconnect_timeout(RECONNECT_TIMEOUT_START)
457 {
458  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
459  if (!reconnect_ev)
460  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
461  // Start connection attempts immediately
462  if (!conn.Connect(_target, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
463  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
464  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
465  }
466  // Read service private key if cached
467  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
468  if (pkf.first) {
469  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
470  private_key = pkf.second;
471  }
472 }
473 
475 {
476  if (reconnect_ev) {
477  event_free(reconnect_ev);
478  reconnect_ev = nullptr;
479  }
480  if (service.IsValid()) {
482  }
483 }
484 
486 {
487  if (reply.code == 250) {
488  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
489  for (const std::string &s : reply.lines) {
490  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
491  std::map<std::string,std::string>::iterator i;
492  if ((i = m.find("ServiceID")) != m.end())
493  service_id = i->second;
494  if ((i = m.find("PrivateKey")) != m.end())
495  private_key = i->second;
496  }
497  if (service_id.empty()) {
498  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
499  for (const std::string &s : reply.lines) {
500  LogPrintf(" %s\n", SanitizeString(s));
501  }
502  return;
503  }
504  service = LookupNumeric(std::string(service_id+".onion").c_str(), Params().GetDefaultPort());
505  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
507  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
508  } else {
509  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
510  }
512  // ... onion requested - keep connection open
513  } else if (reply.code == 510) { // 510 Unrecognized command
514  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
515  } else {
516  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
517  }
518 }
519 
521 {
522  if (reply.code == 250) {
523  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
524 
525  // Now that we know Tor is running setup the proxy for onion addresses
526  // if -onion isn't set to something else.
527  if (gArgs.GetArg("-onion", "") == "") {
528  CService resolved(LookupNumeric("127.0.0.1", 9050));
529  proxyType addrOnion = proxyType(resolved, true);
530  SetProxy(NET_ONION, addrOnion);
531  SetReachable(NET_ONION, true);
532  }
533 
534  // Finally - now create the service
535  if (private_key.empty()) // No private key, generate one
536  private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
537  // Request hidden service, redirect port.
538  // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
539  _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, Params().GetDefaultPort(), GetListenPort()),
540  std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
541  } else {
542  LogPrintf("tor: Authentication failed\n");
543  }
544 }
545 
562 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)
563 {
564  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
565  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
566  computeHash.Write(cookie.data(), cookie.size());
567  computeHash.Write(clientNonce.data(), clientNonce.size());
568  computeHash.Write(serverNonce.data(), serverNonce.size());
569  computeHash.Finalize(computedHash.data());
570  return computedHash;
571 }
572 
574 {
575  if (reply.code == 250) {
576  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
577  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
578  if (l.first == "AUTHCHALLENGE") {
579  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
580  if (m.empty()) {
581  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
582  return;
583  }
584  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
585  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
586  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
587  if (serverNonce.size() != 32) {
588  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
589  return;
590  }
591 
592  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
593  if (computedServerHash != serverHash) {
594  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
595  return;
596  }
597 
598  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
599  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
600  } else {
601  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
602  }
603  } else {
604  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
605  }
606 }
607 
609 {
610  if (reply.code == 250) {
611  std::set<std::string> methods;
612  std::string cookiefile;
613  /*
614  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
615  * 250-AUTH METHODS=NULL
616  * 250-AUTH METHODS=HASHEDPASSWORD
617  */
618  for (const std::string &s : reply.lines) {
619  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
620  if (l.first == "AUTH") {
621  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
622  std::map<std::string,std::string>::iterator i;
623  if ((i = m.find("METHODS")) != m.end())
624  boost::split(methods, i->second, boost::is_any_of(","));
625  if ((i = m.find("COOKIEFILE")) != m.end())
626  cookiefile = i->second;
627  } else if (l.first == "VERSION") {
628  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
629  std::map<std::string,std::string>::iterator i;
630  if ((i = m.find("Tor")) != m.end()) {
631  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
632  }
633  }
634  }
635  for (const std::string &s : methods) {
636  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
637  }
638  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
639  /* Authentication:
640  * cookie: hex-encoded ~/.tor/control_auth_cookie
641  * password: "password"
642  */
643  std::string torpassword = gArgs.GetArg("-torpassword", "");
644  if (!torpassword.empty()) {
645  if (methods.count("HASHEDPASSWORD")) {
646  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
647  boost::replace_all(torpassword, "\"", "\\\"");
648  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
649  } else {
650  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
651  }
652  } else if (methods.count("NULL")) {
653  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
654  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
655  } else if (methods.count("SAFECOOKIE")) {
656  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
657  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
658  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
659  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
660  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
661  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
662  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
663  GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
664  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
665  } else {
666  if (status_cookie.first) {
667  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
668  } else {
669  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
670  }
671  }
672  } else if (methods.count("HASHEDPASSWORD")) {
673  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
674  } else {
675  LogPrintf("tor: No supported authentication method\n");
676  }
677  } else {
678  LogPrintf("tor: Requesting protocol info failed\n");
679  }
680 }
681 
683 {
685  // First send a PROTOCOLINFO command to figure out what authentication is expected
686  if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
687  LogPrintf("tor: Error sending initial protocolinfo command\n");
688 }
689 
691 {
692  // Stop advertising service when disconnected
693  if (service.IsValid())
695  service = CService();
696  if (!reconnect)
697  return;
698 
699  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
700 
701  // Single-shot timer for reconnect. Use exponential backoff.
702  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
703  if (reconnect_ev)
704  event_add(reconnect_ev, &time);
706 }
707 
709 {
710  /* Try to reconnect and reestablish if we get booted - for example, Tor
711  * may be restarting.
712  */
713  if (!conn.Connect(target, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
714  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
715  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
716  }
717 }
718 
720 {
721  return GetDataDir() / "onion_private_key";
722 }
723 
724 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
725 {
726  TorController *self = static_cast<TorController*>(arg);
727  self->Reconnect();
728 }
729 
730 /****** Thread ********/
731 static struct event_base *gBase;
732 static std::thread torControlThread;
733 
734 static void TorControlThread()
735 {
736  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
737 
738  event_base_dispatch(gBase);
739 }
740 
742 {
743  assert(!gBase);
744 #ifdef WIN32
745  evthread_use_windows_threads();
746 #else
747  evthread_use_pthreads();
748 #endif
749  gBase = event_base_new();
750  if (!gBase) {
751  LogPrintf("tor: Unable to create event_base\n");
752  return;
753  }
754 
755  torControlThread = std::thread(std::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
756 }
757 
759 {
760  if (gBase) {
761  LogPrintf("tor: Thread interrupt\n");
762  event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
763  event_base_loopbreak(gBase);
764  }, nullptr, nullptr);
765  }
766 }
767 
769 {
770  if (gBase) {
771  torControlThread.join();
772  event_base_free(gBase);
773  gBase = nullptr;
774  }
775 }
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:573
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
void StartTorControl()
Definition: torcontrol.cpp:741
static void TorControlThread()
Definition: torcontrol.cpp:734
if(expired !=0)
Definition: validation.cpp:321
static std::thread torControlThread
Definition: torcontrol.cpp:732
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:39
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:208
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:15
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.cpp:108
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.cpp:74
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.cpp:112
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1067
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:33
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:434
static struct event_base * gBase
Definition: torcontrol.cpp:731
CService LookupNumeric(const char *pszName, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:238
Reply from Tor, can be single or multi-line.
Definition: torcontrol.cpp:53
bool Connect(const std::string &target, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:196
std::vector< unsigned char > ParseHex(const char *psz)
void StopTorControl()
Definition: torcontrol.cpp:768
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:608
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:708
static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: torcontrol.cpp:392
std::vector< std::string > lines
Definition: torcontrol.cpp:59
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:35
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:144
unsigned short GetListenPort()
Definition: net.cpp:98
static 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: torcontrol.cpp:366
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:659
float reconnect_timeout
Definition: torcontrol.cpp:429
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:116
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:246
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.cpp:75
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:690
std::string target
Definition: torcontrol.cpp:423
bool IsValid() const
Definition: netaddress.cpp:247
std::string private_key
Definition: torcontrol.cpp:425
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:134
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:719
struct event * reconnect_ev
Definition: torcontrol.cpp:428
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:123
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form &#39;METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"&#39;.
Definition: torcontrol.cpp:272
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:31
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.cpp:432
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:41
TorControlConnection conn
Definition: torcontrol.cpp:424
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:43
static secp256k1_context * ctx
Definition: tests.c:46
int atoi(const std::string &str)
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:140
TorController(struct event_base *base, const std::string &target)
Definition: torcontrol.cpp:453
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:724
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:742
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:485
static void LogPrint(const BCLog::LogFlags &category, const Args &... args)
Definition: logging.h:159
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:253
void TraceThread(const char *name, Callable func)
Definition: system.h:340
std::string service_id
Definition: torcontrol.cpp:426
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:692
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:248
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:520
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:226
CService service
Definition: torcontrol.cpp:430
struct event_base * base
Definition: torcontrol.cpp:422
const CChainParams & Params()
Return the currently selected parameters.
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:179
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:496
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:233
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:125
ArgsManager gArgs
Definition: system.cpp:73
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:682
std::string ToString() const
Definition: netaddress.cpp:693
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral h...
Definition: torcontrol.cpp:410
void InterruptTorControl()
Definition: torcontrol.cpp:758
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:71
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:48
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:37
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:103
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:562
TorControlReply message
Message being received.
Definition: torcontrol.cpp:114
void RemoveLocal(const CService &addr)
Definition: net.cpp:239
struct event_base * base
Libevent event base.
Definition: torcontrol.cpp:110
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.cpp:106