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 <torcontrol.h>
7 #include <util/strencodings.h>
8 #include <netbase.h>
9 #include <net.h>
10 #include <util/system.h>
11 #include <crypto/hmac_sha256.h>
12 
13 #include <vector>
14 #include <deque>
15 #include <set>
16 #include <stdlib.h>
17 
18 #include <boost/signals2/signal.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 #include <boost/algorithm/string/classification.hpp>
21 #include <boost/algorithm/string/replace.hpp>
22 
23 #include <event2/bufferevent.h>
24 #include <event2/buffer.h>
25 #include <event2/util.h>
26 #include <event2/event.h>
27 #include <event2/thread.h>
28 
30 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
32 static const int TOR_COOKIE_SIZE = 32;
34 static const int TOR_NONCE_SIZE = 32;
36 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
38 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
40 static const float RECONNECT_TIMEOUT_START = 1.0;
42 static const float RECONNECT_TIMEOUT_EXP = 1.5;
47 static const int MAX_LINE_LENGTH = 100000;
48 
49 /****** Low-level TorControlConnection ********/
50 
53 {
54 public:
56 
57  int code;
58  std::vector<std::string> lines;
59 
60  void Clear()
61  {
62  code = 0;
63  lines.clear();
64  }
65 };
66 
71 {
72 public:
73  typedef std::function<void(TorControlConnection&)> ConnectionCB;
74  typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
75 
78  explicit TorControlConnection(struct event_base *base);
80 
88  bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
89 
93  void Disconnect();
94 
99  bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
100 
102  boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
103 private:
105  std::function<void(TorControlConnection&)> connected;
107  std::function<void(TorControlConnection&)> disconnected;
109  struct event_base *base;
111  struct bufferevent *b_conn;
115  std::deque<ReplyHandlerCB> reply_handlers;
116 
118  static void readcb(struct bufferevent *bev, void *ctx);
119  static void eventcb(struct bufferevent *bev, short what, void *ctx);
120 };
121 
123  base(_base), b_conn(nullptr)
124 {
125 }
126 
128 {
129  if (b_conn)
130  bufferevent_free(b_conn);
131 }
132 
133 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
134 {
135  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
136  struct evbuffer *input = bufferevent_get_input(bev);
137  size_t n_read_out = 0;
138  char *line;
139  assert(input);
140  // If there is not a whole line to read, evbuffer_readln returns nullptr
141  while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
142  {
143  std::string s(line, n_read_out);
144  free(line);
145  if (s.size() < 4) // Short line
146  continue;
147  // <status>(-|+| )<data><CRLF>
148  self->message.code = atoi(s.substr(0,3));
149  self->message.lines.push_back(s.substr(4));
150  char ch = s[3]; // '-','+' or ' '
151  if (ch == ' ') {
152  // Final line, dispatch reply and clean up
153  if (self->message.code >= 600) {
154  // Dispatch async notifications to async handler
155  // Synchronous and asynchronous messages are never interleaved
156  self->async_handler(*self, self->message);
157  } else {
158  if (!self->reply_handlers.empty()) {
159  // Invoke reply handler with message
160  self->reply_handlers.front()(*self, self->message);
161  self->reply_handlers.pop_front();
162  } else {
163  LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
164  }
165  }
166  self->message.Clear();
167  }
168  }
169  // Check for size of buffer - protect against memory exhaustion with very long lines
170  // Do this after evbuffer_readln to make sure all full lines have been
171  // removed from the buffer. Everything left is an incomplete line.
172  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
173  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
174  self->Disconnect();
175  }
176 }
177 
178 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
179 {
180  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
181  if (what & BEV_EVENT_CONNECTED) {
182  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
183  self->connected(*self);
184  } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
185  if (what & BEV_EVENT_ERROR) {
186  LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
187  } else {
188  LogPrint(BCLog::TOR, "tor: End of stream\n");
189  }
190  self->Disconnect();
191  self->disconnected(*self);
192  }
193 }
194 
195 bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
196 {
197  if (b_conn)
198  Disconnect();
199  // Parse target address:port
200  struct sockaddr_storage connect_to_addr;
201  int connect_to_addrlen = sizeof(connect_to_addr);
202  if (evutil_parse_sockaddr_port(target.c_str(),
203  (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
204  LogPrintf("tor: Error parsing socket address %s\n", target);
205  return false;
206  }
207 
208  // Create a new socket, set up callbacks and enable notification bits
209  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
210  if (!b_conn)
211  return false;
212  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
213  bufferevent_enable(b_conn, EV_READ|EV_WRITE);
214  this->connected = _connected;
215  this->disconnected = _disconnected;
216 
217  // Finally, connect to target
218  if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
219  LogPrintf("tor: Error connecting to address %s\n", target);
220  return false;
221  }
222  return true;
223 }
224 
226 {
227  if (b_conn)
228  bufferevent_free(b_conn);
229  b_conn = nullptr;
230 }
231 
232 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
233 {
234  if (!b_conn)
235  return false;
236  struct evbuffer *buf = bufferevent_get_output(b_conn);
237  if (!buf)
238  return false;
239  evbuffer_add(buf, cmd.data(), cmd.size());
240  evbuffer_add(buf, "\r\n", 2);
241  reply_handlers.push_back(reply_handler);
242  return true;
243 }
244 
245 /****** General parsing utilities ********/
246 
247 /* Split reply line in the form 'AUTH METHODS=...' into a type
248  * 'AUTH' and arguments 'METHODS=...'.
249  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
250  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
251  */
252 std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
253 {
254  size_t ptr=0;
255  std::string type;
256  while (ptr < s.size() && s[ptr] != ' ') {
257  type.push_back(s[ptr]);
258  ++ptr;
259  }
260  if (ptr < s.size())
261  ++ptr; // skip ' '
262  return make_pair(type, s.substr(ptr));
263 }
264 
271 std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
272 {
273  std::map<std::string,std::string> mapping;
274  size_t ptr=0;
275  while (ptr < s.size()) {
276  std::string key, value;
277  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
278  key.push_back(s[ptr]);
279  ++ptr;
280  }
281  if (ptr == s.size()) // unexpected end of line
282  return std::map<std::string,std::string>();
283  if (s[ptr] == ' ') // The remaining string is an OptArguments
284  break;
285  ++ptr; // skip '='
286  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
287  ++ptr; // skip opening '"'
288  bool escape_next = false;
289  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
290  // Repeated backslashes must be interpreted as pairs
291  escape_next = (s[ptr] == '\\' && !escape_next);
292  value.push_back(s[ptr]);
293  ++ptr;
294  }
295  if (ptr == s.size()) // unexpected end of line
296  return std::map<std::string,std::string>();
297  ++ptr; // skip closing '"'
308  std::string escaped_value;
309  for (size_t i = 0; i < value.size(); ++i) {
310  if (value[i] == '\\') {
311  // This will always be valid, because if the QuotedString
312  // ended in an odd number of backslashes, then the parser
313  // would already have returned above, due to a missing
314  // terminating double-quote.
315  ++i;
316  if (value[i] == 'n') {
317  escaped_value.push_back('\n');
318  } else if (value[i] == 't') {
319  escaped_value.push_back('\t');
320  } else if (value[i] == 'r') {
321  escaped_value.push_back('\r');
322  } else if ('0' <= value[i] && value[i] <= '7') {
323  size_t j;
324  // Octal escape sequences have a limit of three octal digits,
325  // but terminate at the first character that is not a valid
326  // octal digit if encountered sooner.
327  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
328  // Tor restricts first digit to 0-3 for three-digit octals.
329  // A leading digit of 4-7 would therefore be interpreted as
330  // a two-digit octal.
331  if (j == 3 && value[i] > '3') {
332  j--;
333  }
334  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
335  // Account for automatic incrementing at loop end
336  i += j - 1;
337  } else {
338  escaped_value.push_back(value[i]);
339  }
340  } else {
341  escaped_value.push_back(value[i]);
342  }
343  }
344  value = escaped_value;
345  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
346  while (ptr < s.size() && s[ptr] != ' ') {
347  value.push_back(s[ptr]);
348  ++ptr;
349  }
350  }
351  if (ptr < s.size() && s[ptr] == ' ')
352  ++ptr; // skip ' ' after key=value
353  mapping[key] = value;
354  }
355  return mapping;
356 }
357 
365 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
366 {
367  FILE *f = fsbridge::fopen(filename, "rb");
368  if (f == nullptr)
369  return std::make_pair(false,"");
370  std::string retval;
371  char buffer[128];
372  size_t n;
373  while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
374  // Check for reading errors so we don't return any data if we couldn't
375  // read the entire file (or up to maxsize)
376  if (ferror(f)) {
377  fclose(f);
378  return std::make_pair(false,"");
379  }
380  retval.append(buffer, buffer+n);
381  if (retval.size() > maxsize)
382  break;
383  }
384  fclose(f);
385  return std::make_pair(true,retval);
386 }
387 
391 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
392 {
393  FILE *f = fsbridge::fopen(filename, "wb");
394  if (f == nullptr)
395  return false;
396  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
397  fclose(f);
398  return false;
399  }
400  fclose(f);
401  return true;
402 }
403 
404 /****** Bitcoin specific TorController implementation ********/
405 
410 {
411 public:
412  TorController(struct event_base* base, const std::string& target);
413  ~TorController();
414 
416  fs::path GetPrivateKeyFile();
417 
419  void Reconnect();
420 private:
421  struct event_base* base;
422  std::string target;
424  std::string private_key;
425  std::string service_id;
426  bool reconnect;
427  struct event *reconnect_ev;
431  std::vector<uint8_t> cookie;
433  std::vector<uint8_t> clientNonce;
434 
436  void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
438  void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
440  void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
442  void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
444  void connected_cb(TorControlConnection& conn);
446  void disconnected_cb(TorControlConnection& conn);
447 
449  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
450 };
451 
452 TorController::TorController(struct event_base* _base, const std::string& _target):
453  base(_base),
454  target(_target), conn(base), reconnect(true), reconnect_ev(0),
455  reconnect_timeout(RECONNECT_TIMEOUT_START)
456 {
457  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
458  if (!reconnect_ev)
459  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
460  // Start connection attempts immediately
461  if (!conn.Connect(_target, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
462  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
463  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
464  }
465  // Read service private key if cached
466  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
467  if (pkf.first) {
468  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
469  private_key = pkf.second;
470  }
471 }
472 
474 {
475  if (reconnect_ev) {
476  event_free(reconnect_ev);
477  reconnect_ev = nullptr;
478  }
479  if (service.IsValid()) {
481  }
482 }
483 
485 {
486  if (reply.code == 250) {
487  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
488  for (const std::string &s : reply.lines) {
489  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
490  std::map<std::string,std::string>::iterator i;
491  if ((i = m.find("ServiceID")) != m.end())
492  service_id = i->second;
493  if ((i = m.find("PrivateKey")) != m.end())
494  private_key = i->second;
495  }
496  if (service_id.empty()) {
497  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
498  for (const std::string &s : reply.lines) {
499  LogPrintf(" %s\n", SanitizeString(s));
500  }
501  return;
502  }
503  service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
504  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
505  if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
506  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
507  } else {
508  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
509  }
511  // ... onion requested - keep connection open
512  } else if (reply.code == 510) { // 510 Unrecognized command
513  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
514  } else {
515  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
516  }
517 }
518 
520 {
521  if (reply.code == 250) {
522  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
523 
524  // Now that we know Tor is running setup the proxy for onion addresses
525  // if -onion isn't set to something else.
526  if (gArgs.GetArg("-onion", "") == "") {
527  CService resolved(LookupNumeric("127.0.0.1", 9050));
528  proxyType addrOnion = proxyType(resolved, true);
529  SetProxy(NET_ONION, addrOnion);
530  SetReachable(NET_ONION, true);
531  }
532 
533  // Finally - now create the service
534  if (private_key.empty()) // No private key, generate one
535  private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
536  // Request hidden service, redirect port.
537  // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
538  // choice. TODO; refactor the shutdown sequence some day.
539  _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), 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 {
684  reconnect_timeout = RECONNECT_TIMEOUT_START;
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);
705  reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
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_loopbreak(gBase);
763  }
764 }
765 
767 {
768  if (gBase) {
769  torControlThread.join();
770  event_base_free(gBase);
771  gBase = nullptr;
772  }
773 }
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
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:204
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:107
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.cpp:73
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.cpp:111
#define strprintf
Definition: tinyformat.h:1066
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:433
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:165
Reply from Tor, can be single or multi-line.
Definition: torcontrol.cpp:52
bool Connect(const std::string &target, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:195
std::vector< unsigned char > ParseHex(const char *psz)
void StopTorControl()
Definition: torcontrol.cpp:766
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
std::vector< std::string > lines
Definition: torcontrol.cpp:58
unsigned short GetListenPort()
Definition: net.cpp:94
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:428
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:115
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:242
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.cpp:74
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:690
std::string target
Definition: torcontrol.cpp:422
bool IsValid() const
Definition: netaddress.cpp:247
std::string private_key
Definition: torcontrol.cpp:424
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:133
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:719
struct event * reconnect_ev
Definition: torcontrol.cpp:427
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:122
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:271
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:30
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.cpp:431
TorControlConnection conn
Definition: torcontrol.cpp:423
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:452
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:738
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:484
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:252
void TraceThread(const char *name, Callable func)
Definition: system.h:332
std::string service_id
Definition: torcontrol.cpp:425
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:554
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:175
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:519
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:225
CService service
Definition: torcontrol.cpp:429
struct event_base * base
Definition: torcontrol.cpp:421
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:178
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:494
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:232
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:125
ArgsManager gArgs
Definition: system.cpp:72
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:409
void InterruptTorControl()
Definition: torcontrol.cpp:758
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:70
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:102
TorControlReply message
Message being received.
Definition: torcontrol.cpp:113
void RemoveLocal(const CService &addr)
Definition: net.cpp:235
struct event_base * base
Libevent event base.
Definition: torcontrol.cpp:109
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.cpp:105