Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015 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  bool 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 {
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 {
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  return true;
232 }
233 
234 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
235 {
236  if (!b_conn)
237  return false;
238  struct evbuffer *buf = bufferevent_get_output(b_conn);
239  if (!buf)
240  return false;
241  evbuffer_add(buf, cmd.data(), cmd.size());
242  evbuffer_add(buf, "\r\n", 2);
243  reply_handlers.push_back(reply_handler);
244  return true;
245 }
246 
247 /****** General parsing utilities ********/
248 
249 /* Split reply line in the form 'AUTH METHODS=...' into a type
250  * 'AUTH' and arguments 'METHODS=...'.
251  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
252  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
253  */
254 static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
255 {
256  size_t ptr=0;
257  std::string type;
258  while (ptr < s.size() && s[ptr] != ' ') {
259  type.push_back(s[ptr]);
260  ++ptr;
261  }
262  if (ptr < s.size())
263  ++ptr; // skip ' '
264  return make_pair(type, s.substr(ptr));
265 }
266 
273 static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
274 {
275  std::map<std::string,std::string> mapping;
276  size_t ptr=0;
277  while (ptr < s.size()) {
278  std::string key, value;
279  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
280  key.push_back(s[ptr]);
281  ++ptr;
282  }
283  if (ptr == s.size()) // unexpected end of line
284  return std::map<std::string,std::string>();
285  if (s[ptr] == ' ') // The remaining string is an OptArguments
286  break;
287  ++ptr; // skip '='
288  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
289  ++ptr; // skip opening '"'
290  bool escape_next = false;
291  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
292  // Repeated backslashes must be interpreted as pairs
293  escape_next = (s[ptr] == '\\' && !escape_next);
294  value.push_back(s[ptr]);
295  ++ptr;
296  }
297  if (ptr == s.size()) // unexpected end of line
298  return std::map<std::string,std::string>();
299  ++ptr; // skip closing '"'
310  std::string escaped_value;
311  for (size_t i = 0; i < value.size(); ++i) {
312  if (value[i] == '\\') {
313  // This will always be valid, because if the QuotedString
314  // ended in an odd number of backslashes, then the parser
315  // would already have returned above, due to a missing
316  // terminating double-quote.
317  ++i;
318  if (value[i] == 'n') {
319  escaped_value.push_back('\n');
320  } else if (value[i] == 't') {
321  escaped_value.push_back('\t');
322  } else if (value[i] == 'r') {
323  escaped_value.push_back('\r');
324  } else if ('0' <= value[i] && value[i] <= '7') {
325  size_t j;
326  // Octal escape sequences have a limit of three octal digits,
327  // but terminate at the first character that is not a valid
328  // octal digit if encountered sooner.
329  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
330  // Tor restricts first digit to 0-3 for three-digit octals.
331  // A leading digit of 4-7 would therefore be interpreted as
332  // a two-digit octal.
333  if (j == 3 && value[i] > '3') {
334  j--;
335  }
336  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
337  // Account for automatic incrementing at loop end
338  i += j - 1;
339  } else {
340  escaped_value.push_back(value[i]);
341  }
342  } else {
343  escaped_value.push_back(value[i]);
344  }
345  }
346  value = escaped_value;
347  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
348  while (ptr < s.size() && s[ptr] != ' ') {
349  value.push_back(s[ptr]);
350  ++ptr;
351  }
352  }
353  if (ptr < s.size() && s[ptr] == ' ')
354  ++ptr; // skip ' ' after key=value
355  mapping[key] = value;
356  }
357  return mapping;
358 }
359 
367 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
368 {
369  FILE *f = fsbridge::fopen(filename, "rb");
370  if (f == nullptr)
371  return std::make_pair(false,"");
372  std::string retval;
373  char buffer[128];
374  size_t n;
375  while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
376  // Check for reading errors so we don't return any data if we couldn't
377  // read the entire file (or up to maxsize)
378  if (ferror(f)) {
379  fclose(f);
380  return std::make_pair(false,"");
381  }
382  retval.append(buffer, buffer+n);
383  if (retval.size() > maxsize)
384  break;
385  }
386  fclose(f);
387  return std::make_pair(true,retval);
388 }
389 
393 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
394 {
395  FILE *f = fsbridge::fopen(filename, "wb");
396  if (f == nullptr)
397  return false;
398  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
399  fclose(f);
400  return false;
401  }
402  fclose(f);
403  return true;
404 }
405 
406 /****** Bitcoin specific TorController implementation ********/
407 
412 {
413 public:
414  TorController(struct event_base* base, const std::string& target);
415  ~TorController();
416 
418  fs::path GetPrivateKeyFile();
419 
421  void Reconnect();
422 private:
423  struct event_base* base;
424  std::string target;
426  std::string private_key;
427  std::string service_id;
428  bool reconnect;
429  struct event *reconnect_ev;
433  std::vector<uint8_t> cookie;
435  std::vector<uint8_t> clientNonce;
436 
440  void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
449 
451  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
452 };
453 
454 TorController::TorController(struct event_base* _base, const std::string& _target):
455  base(_base),
456  target(_target), conn(base), reconnect(true), reconnect_ev(0),
457  reconnect_timeout(RECONNECT_TIMEOUT_START)
458 {
459  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
460  if (!reconnect_ev)
461  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
462  // Start connection attempts immediately
463  if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
464  boost::bind(&TorController::disconnected_cb, this, _1) )) {
465  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
466  }
467  // Read service private key if cached
468  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
469  if (pkf.first) {
470  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
471  private_key = pkf.second;
472  }
473 }
474 
476 {
477  if (reconnect_ev) {
478  event_free(reconnect_ev);
479  reconnect_ev = nullptr;
480  }
481  if (service.IsValid()) {
483  }
484 }
485 
487 {
488  if (reply.code == 250) {
489  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
490  for (const std::string &s : reply.lines) {
491  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
492  std::map<std::string,std::string>::iterator i;
493  if ((i = m.find("ServiceID")) != m.end())
494  service_id = i->second;
495  if ((i = m.find("PrivateKey")) != m.end())
496  private_key = i->second;
497  }
498  if (service_id.empty()) {
499  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
500  for (const std::string &s : reply.lines) {
501  LogPrintf(" %s\n", SanitizeString(s));
502  }
503  return;
504  }
505  service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
506  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
508  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
509  } else {
510  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
511  }
513  // ... onion requested - keep connection open
514  } else if (reply.code == 510) { // 510 Unrecognized command
515  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
516  } else {
517  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
518  }
519 }
520 
522 {
523  if (reply.code == 250) {
524  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
525 
526  // Now that we know Tor is running setup the proxy for onion addresses
527  // if -onion isn't set to something else.
528  if (gArgs.GetArg("-onion", "") == "") {
529  CService resolved(LookupNumeric("127.0.0.1", 9050));
530  proxyType addrOnion = proxyType(resolved, true);
531  SetProxy(NET_TOR, addrOnion);
532  SetLimited(NET_TOR, false);
533  }
534 
535  // Finally - now create the service
536  if (private_key.empty()) // No private key, generate one
537  private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
538  // Request hidden service, redirect port.
539  // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
540  // choice. TODO; refactor the shutdown sequence some day.
541  _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
542  boost::bind(&TorController::add_onion_cb, this, _1, _2));
543  } else {
544  LogPrintf("tor: Authentication failed\n");
545  }
546 }
547 
564 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)
565 {
566  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
567  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
568  computeHash.Write(cookie.data(), cookie.size());
569  computeHash.Write(clientNonce.data(), clientNonce.size());
570  computeHash.Write(serverNonce.data(), serverNonce.size());
571  computeHash.Finalize(computedHash.data());
572  return computedHash;
573 }
574 
576 {
577  if (reply.code == 250) {
578  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
579  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
580  if (l.first == "AUTHCHALLENGE") {
581  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
582  if (m.empty()) {
583  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
584  return;
585  }
586  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
587  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
588  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
589  if (serverNonce.size() != 32) {
590  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
591  return;
592  }
593 
594  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
595  if (computedServerHash != serverHash) {
596  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
597  return;
598  }
599 
600  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
601  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
602  } else {
603  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
604  }
605  } else {
606  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
607  }
608 }
609 
611 {
612  if (reply.code == 250) {
613  std::set<std::string> methods;
614  std::string cookiefile;
615  /*
616  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
617  * 250-AUTH METHODS=NULL
618  * 250-AUTH METHODS=HASHEDPASSWORD
619  */
620  for (const std::string &s : reply.lines) {
621  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
622  if (l.first == "AUTH") {
623  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
624  std::map<std::string,std::string>::iterator i;
625  if ((i = m.find("METHODS")) != m.end())
626  boost::split(methods, i->second, boost::is_any_of(","));
627  if ((i = m.find("COOKIEFILE")) != m.end())
628  cookiefile = i->second;
629  } else if (l.first == "VERSION") {
630  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
631  std::map<std::string,std::string>::iterator i;
632  if ((i = m.find("Tor")) != m.end()) {
633  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
634  }
635  }
636  }
637  for (const std::string &s : methods) {
638  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
639  }
640  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
641  /* Authentication:
642  * cookie: hex-encoded ~/.tor/control_auth_cookie
643  * password: "password"
644  */
645  std::string torpassword = gArgs.GetArg("-torpassword", "");
646  if (!torpassword.empty()) {
647  if (methods.count("HASHEDPASSWORD")) {
648  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
649  boost::replace_all(torpassword, "\"", "\\\"");
650  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
651  } else {
652  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
653  }
654  } else if (methods.count("NULL")) {
655  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
656  _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
657  } else if (methods.count("SAFECOOKIE")) {
658  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
659  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
660  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
661  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
662  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
663  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
664  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
666  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
667  } else {
668  if (status_cookie.first) {
669  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
670  } else {
671  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
672  }
673  }
674  } else if (methods.count("HASHEDPASSWORD")) {
675  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
676  } else {
677  LogPrintf("tor: No supported authentication method\n");
678  }
679  } else {
680  LogPrintf("tor: Requesting protocol info failed\n");
681  }
682 }
683 
685 {
687  // First send a PROTOCOLINFO command to figure out what authentication is expected
688  if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
689  LogPrintf("tor: Error sending initial protocolinfo command\n");
690 }
691 
693 {
694  // Stop advertising service when disconnected
695  if (service.IsValid())
697  service = CService();
698  if (!reconnect)
699  return;
700 
701  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
702 
703  // Single-shot timer for reconnect. Use exponential backoff.
704  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
705  if (reconnect_ev)
706  event_add(reconnect_ev, &time);
708 }
709 
711 {
712  /* Try to reconnect and reestablish if we get booted - for example, Tor
713  * may be restarting.
714  */
715  if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
716  boost::bind(&TorController::disconnected_cb, this, _1) )) {
717  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
718  }
719 }
720 
722 {
723  return GetDataDir() / "onion_private_key";
724 }
725 
726 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
727 {
728  TorController *self = (TorController*)arg;
729  self->Reconnect();
730 }
731 
732 /****** Thread ********/
733 static struct event_base *gBase;
734 static boost::thread torControlThread;
735 
736 static void TorControlThread()
737 {
738  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
739 
740  event_base_dispatch(gBase);
741 }
742 
743 void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
744 {
745  assert(!gBase);
746 #ifdef WIN32
747  evthread_use_windows_threads();
748 #else
749  evthread_use_pthreads();
750 #endif
751  gBase = event_base_new();
752  if (!gBase) {
753  LogPrintf("tor: Unable to create event_base\n");
754  return;
755  }
756 
757  torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
758 }
759 
761 {
762  if (gBase) {
763  LogPrintf("tor: Thread interrupt\n");
764  event_base_loopbreak(gBase);
765  }
766 }
767 
769 {
770  // timed_join() avoids the wallet not closing during a repair-restart. For a 'normal' wallet exit
771  // it behaves for our cases exactly like the normal join()
772  if (gBase) {
773 #if BOOST_VERSION >= 105000
774  torControlThread.try_join_for(boost::chrono::seconds(1));
775 #else
776  torControlThread.timed_join(boost::posix_time::seconds(1));
777 #endif
778  event_base_free(gBase);
779  gBase = nullptr;
780  }
781 }
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:575
static void TorControlThread()
Definition: torcontrol.cpp:736
static boost::thread torControlThread
Definition: torcontrol.cpp:734
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:39
static 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:273
std::string ToString(bool fUseGetnameinfo=true) const
Definition: netaddress.cpp:581
void TraceThread(const std::string name, Callable func)
Definition: util.h:436
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:236
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: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
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:435
static struct event_base * gBase
Definition: torcontrol.cpp:733
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:768
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:276
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:610
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:710
static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: torcontrol.cpp:393
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
false true true true
Definition: bls_dkg.cpp:176
unsigned short GetListenPort()
Definition: net.cpp:126
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:367
float reconnect_timeout
Definition: torcontrol.cpp:430
static boost::thread_group threadGroup
Definition: init.cpp:212
static CScheduler scheduler
Definition: init.cpp:213
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:116
static std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:254
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:692
std::string target
Definition: torcontrol.cpp:424
bool IsValid() const
Definition: netaddress.cpp:191
std::string private_key
Definition: torcontrol.cpp:426
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:721
struct event * reconnect_ev
Definition: torcontrol.cpp:429
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:123
#define LogPrintf(...)
Definition: util.h:203
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:433
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:41
TorControlConnection conn
Definition: torcontrol.cpp:425
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:43
static secp256k1_context * ctx
Definition: tests.c:46
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:143
TorController(struct event_base *base, const std::string &target)
Definition: torcontrol.cpp:454
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:726
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:486
std::string service_id
Definition: torcontrol.cpp:427
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:547
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:178
#define LogPrint(category,...)
Definition: util.h:214
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:521
ArgsManager gArgs
Definition: util.cpp:108
CService service
Definition: torcontrol.cpp:431
bool RemoveLocal(const CService &addr)
Definition: net.cpp:267
struct event_base * base
Definition: torcontrol.cpp:423
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:808
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:234
void StartTorControl(boost::thread_group &threadGroup, CScheduler &scheduler)
Definition: torcontrol.cpp:743
void GetRandBytes(unsigned char *buf, int num)
Functions to gather random data via the OpenSSL PRNG.
Definition: random.cpp:273
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:684
const fs::path & GetDataDir(bool fNetSpecific)
Definition: util.cpp:928
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral h...
Definition: torcontrol.cpp:411
void InterruptTorControl()
Definition: torcontrol.cpp:760
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
bool Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:226
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.
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:564
TorControlReply message
Message being received.
Definition: torcontrol.cpp:114
int atoi(const std::string &str)
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)
Released under the MIT license