BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
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 <utilstrencodings.h>
8 #include <netbase.h>
9 #include <net.h>
10 #include <util.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/bind.hpp>
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 
439  void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
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, boost::bind(&TorController::connected_cb, this, _1),
463  boost::bind(&TorController::disconnected_cb, this, _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(), GetListenPort());
505  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
506  if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
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  SetLimited(NET_ONION, false);
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 doesn't have to be the same as our internal port, but this is just a convenient
539  // choice. TODO; refactor the shutdown sequence some day.
540  _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
541  boost::bind(&TorController::add_onion_cb, this, _1, _2));
542  } else {
543  LogPrintf("tor: Authentication failed\n");
544  }
545 }
546 
563 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)
564 {
565  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
566  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
567  computeHash.Write(cookie.data(), cookie.size());
568  computeHash.Write(clientNonce.data(), clientNonce.size());
569  computeHash.Write(serverNonce.data(), serverNonce.size());
570  computeHash.Finalize(computedHash.data());
571  return computedHash;
572 }
573 
575 {
576  if (reply.code == 250) {
577  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
578  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
579  if (l.first == "AUTHCHALLENGE") {
580  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
581  if (m.empty()) {
582  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
583  return;
584  }
585  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
586  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
587  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
588  if (serverNonce.size() != 32) {
589  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
590  return;
591  }
592 
593  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
594  if (computedServerHash != serverHash) {
595  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
596  return;
597  }
598 
599  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
600  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
601  } else {
602  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
603  }
604  } else {
605  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
606  }
607 }
608 
610 {
611  if (reply.code == 250) {
612  std::set<std::string> methods;
613  std::string cookiefile;
614  /*
615  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
616  * 250-AUTH METHODS=NULL
617  * 250-AUTH METHODS=HASHEDPASSWORD
618  */
619  for (const std::string &s : reply.lines) {
620  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
621  if (l.first == "AUTH") {
622  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
623  std::map<std::string,std::string>::iterator i;
624  if ((i = m.find("METHODS")) != m.end())
625  boost::split(methods, i->second, boost::is_any_of(","));
626  if ((i = m.find("COOKIEFILE")) != m.end())
627  cookiefile = i->second;
628  } else if (l.first == "VERSION") {
629  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
630  std::map<std::string,std::string>::iterator i;
631  if ((i = m.find("Tor")) != m.end()) {
632  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
633  }
634  }
635  }
636  for (const std::string &s : methods) {
637  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
638  }
639  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
640  /* Authentication:
641  * cookie: hex-encoded ~/.tor/control_auth_cookie
642  * password: "password"
643  */
644  std::string torpassword = gArgs.GetArg("-torpassword", "");
645  if (!torpassword.empty()) {
646  if (methods.count("HASHEDPASSWORD")) {
647  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
648  boost::replace_all(torpassword, "\"", "\\\"");
649  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
650  } else {
651  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
652  }
653  } else if (methods.count("NULL")) {
654  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
655  _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
656  } else if (methods.count("SAFECOOKIE")) {
657  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
658  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
659  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
660  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
661  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
662  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
663  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
664  GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
665  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
666  } else {
667  if (status_cookie.first) {
668  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
669  } else {
670  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
671  }
672  }
673  } else if (methods.count("HASHEDPASSWORD")) {
674  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
675  } else {
676  LogPrintf("tor: No supported authentication method\n");
677  }
678  } else {
679  LogPrintf("tor: Requesting protocol info failed\n");
680  }
681 }
682 
684 {
685  reconnect_timeout = RECONNECT_TIMEOUT_START;
686  // First send a PROTOCOLINFO command to figure out what authentication is expected
687  if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
688  LogPrintf("tor: Error sending initial protocolinfo command\n");
689 }
690 
692 {
693  // Stop advertising service when disconnected
694  if (service.IsValid())
696  service = CService();
697  if (!reconnect)
698  return;
699 
700  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
701 
702  // Single-shot timer for reconnect. Use exponential backoff.
703  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
704  if (reconnect_ev)
705  event_add(reconnect_ev, &time);
706  reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
707 }
708 
710 {
711  /* Try to reconnect and reestablish if we get booted - for example, Tor
712  * may be restarting.
713  */
714  if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
715  boost::bind(&TorController::disconnected_cb, this, _1) )) {
716  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
717  }
718 }
719 
721 {
722  return GetDataDir() / "onion_private_key";
723 }
724 
725 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
726 {
727  TorController *self = static_cast<TorController*>(arg);
728  self->Reconnect();
729 }
730 
731 /****** Thread ********/
732 static struct event_base *gBase;
733 static std::thread torControlThread;
734 
735 static void TorControlThread()
736 {
737  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
738 
739  event_base_dispatch(gBase);
740 }
741 
743 {
744  assert(!gBase);
745 #ifdef WIN32
746  evthread_use_windows_threads();
747 #else
748  evthread_use_pthreads();
749 #endif
750  gBase = event_base_new();
751  if (!gBase) {
752  LogPrintf("tor: Unable to create event_base\n");
753  return;
754  }
755 
756  torControlThread = std::thread(std::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
757 }
758 
760 {
761  if (gBase) {
762  LogPrintf("tor: Thread interrupt\n");
763  event_base_loopbreak(gBase);
764  }
765 }
766 
768 {
769  if (gBase) {
770  torControlThread.join();
771  event_base_free(gBase);
772  gBase = nullptr;
773  }
774 }
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:574
void StartTorControl()
Definition: torcontrol.cpp:742
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:209
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:13
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
Definition: tinyformat.h:1066
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:434
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:168
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
void StopTorControl()
Definition: torcontrol.cpp:767
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
void SetLimited(enum Network net, bool fLimited)
Make a particular network entirely off-limits (no automatic connects to it)
Definition: net.cpp:248
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:609
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:709
std::vector< std::string > lines
Definition: torcontrol.cpp:59
unsigned short GetListenPort()
Definition: net.cpp:99
float reconnect_timeout
Definition: torcontrol.cpp:429
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:116
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:691
std::string target
Definition: torcontrol.cpp:423
bool IsValid() const
Definition: netaddress.cpp:188
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 fo file to store private key in.
Definition: torcontrol.cpp:720
struct event * reconnect_ev
Definition: torcontrol.cpp:428
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:123
if(!params[0].isNull()) nMinDepth
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
TorControlConnection conn
Definition: torcontrol.cpp:424
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:142
TorController(struct event_base *base, const std::string &target)
Definition: torcontrol.cpp:453
void TraceThread(const char *name, Callable func)
Definition: util.h:317
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:725
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:485
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:253
std::string service_id
Definition: torcontrol.cpp:426
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:542
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:178
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:520
ArgsManager gArgs
Definition: util.cpp:88
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
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: util.cpp:526
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:233
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:275
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:683
std::string ToString() const
Definition: netaddress.cpp:574
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:766
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral h...
Definition: torcontrol.cpp:410
void InterruptTorControl()
Definition: torcontrol.cpp:759
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:71
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:103
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
TorControlReply message
Message being received.
Definition: torcontrol.cpp:114
int atoi(const std::string &str)
void RemoveLocal(const CService &addr)
Definition: net.cpp:240
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
std::vector< unsigned char > ParseHex(const char *psz)