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