Bitcoin Core  21.99.0
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2020 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 
8 #include <chainparams.h>
9 #include <chainparamsbase.h>
10 #include <compat.h>
11 #include <crypto/hmac_sha256.h>
12 #include <net.h>
13 #include <netaddress.h>
14 #include <netbase.h>
15 #include <util/readwritefile.h>
16 #include <util/strencodings.h>
17 #include <util/system.h>
18 #include <util/time.h>
19 
20 #include <deque>
21 #include <functional>
22 #include <set>
23 #include <stdlib.h>
24 #include <vector>
25 
26 #include <boost/signals2/signal.hpp>
27 #include <boost/algorithm/string/split.hpp>
28 #include <boost/algorithm/string/classification.hpp>
29 #include <boost/algorithm/string/replace.hpp>
30 
31 #include <event2/bufferevent.h>
32 #include <event2/buffer.h>
33 #include <event2/util.h>
34 #include <event2/event.h>
35 #include <event2/thread.h>
36 
38 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
40 static const int TOR_COOKIE_SIZE = 32;
42 static const int TOR_NONCE_SIZE = 32;
44 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
46 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
48 static const float RECONNECT_TIMEOUT_START = 1.0;
50 static const float RECONNECT_TIMEOUT_EXP = 1.5;
55 static const int MAX_LINE_LENGTH = 100000;
56 
57 /****** Low-level TorControlConnection ********/
58 
60  base(_base), b_conn(nullptr)
61 {
62 }
63 
65 {
66  if (b_conn)
67  bufferevent_free(b_conn);
68 }
69 
70 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
71 {
72  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
73  struct evbuffer *input = bufferevent_get_input(bev);
74  size_t n_read_out = 0;
75  char *line;
76  assert(input);
77  // If there is not a whole line to read, evbuffer_readln returns nullptr
78  while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
79  {
80  std::string s(line, n_read_out);
81  free(line);
82  if (s.size() < 4) // Short line
83  continue;
84  // <status>(-|+| )<data><CRLF>
85  self->message.code = atoi(s.substr(0,3));
86  self->message.lines.push_back(s.substr(4));
87  char ch = s[3]; // '-','+' or ' '
88  if (ch == ' ') {
89  // Final line, dispatch reply and clean up
90  if (self->message.code >= 600) {
91  // Dispatch async notifications to async handler
92  // Synchronous and asynchronous messages are never interleaved
93  self->async_handler(*self, self->message);
94  } else {
95  if (!self->reply_handlers.empty()) {
96  // Invoke reply handler with message
97  self->reply_handlers.front()(*self, self->message);
98  self->reply_handlers.pop_front();
99  } else {
100  LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
101  }
102  }
103  self->message.Clear();
104  }
105  }
106  // Check for size of buffer - protect against memory exhaustion with very long lines
107  // Do this after evbuffer_readln to make sure all full lines have been
108  // removed from the buffer. Everything left is an incomplete line.
109  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
110  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
111  self->Disconnect();
112  }
113 }
114 
115 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
116 {
117  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
118  if (what & BEV_EVENT_CONNECTED) {
119  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
120  self->connected(*self);
121  } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
122  if (what & BEV_EVENT_ERROR) {
123  LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
124  } else {
125  LogPrint(BCLog::TOR, "tor: End of stream\n");
126  }
127  self->Disconnect();
128  self->disconnected(*self);
129  }
130 }
131 
132 bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
133 {
134  if (b_conn)
135  Disconnect();
136  // Parse tor_control_center address:port
137  struct sockaddr_storage connect_to_addr;
138  int connect_to_addrlen = sizeof(connect_to_addr);
139  if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
140  (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
141  LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
142  return false;
143  }
144 
145  // Create a new socket, set up callbacks and enable notification bits
146  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
147  if (!b_conn)
148  return false;
149  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
150  bufferevent_enable(b_conn, EV_READ|EV_WRITE);
151  this->connected = _connected;
152  this->disconnected = _disconnected;
153 
154  // Finally, connect to tor_control_center
155  if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
156  LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
157  return false;
158  }
159  return true;
160 }
161 
163 {
164  if (b_conn)
165  bufferevent_free(b_conn);
166  b_conn = nullptr;
167 }
168 
169 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
170 {
171  if (!b_conn)
172  return false;
173  struct evbuffer *buf = bufferevent_get_output(b_conn);
174  if (!buf)
175  return false;
176  evbuffer_add(buf, cmd.data(), cmd.size());
177  evbuffer_add(buf, "\r\n", 2);
178  reply_handlers.push_back(reply_handler);
179  return true;
180 }
181 
182 /****** General parsing utilities ********/
183 
184 /* Split reply line in the form 'AUTH METHODS=...' into a type
185  * 'AUTH' and arguments 'METHODS=...'.
186  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
187  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
188  */
189 std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
190 {
191  size_t ptr=0;
192  std::string type;
193  while (ptr < s.size() && s[ptr] != ' ') {
194  type.push_back(s[ptr]);
195  ++ptr;
196  }
197  if (ptr < s.size())
198  ++ptr; // skip ' '
199  return make_pair(type, s.substr(ptr));
200 }
201 
208 std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
209 {
210  std::map<std::string,std::string> mapping;
211  size_t ptr=0;
212  while (ptr < s.size()) {
213  std::string key, value;
214  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
215  key.push_back(s[ptr]);
216  ++ptr;
217  }
218  if (ptr == s.size()) // unexpected end of line
219  return std::map<std::string,std::string>();
220  if (s[ptr] == ' ') // The remaining string is an OptArguments
221  break;
222  ++ptr; // skip '='
223  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
224  ++ptr; // skip opening '"'
225  bool escape_next = false;
226  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
227  // Repeated backslashes must be interpreted as pairs
228  escape_next = (s[ptr] == '\\' && !escape_next);
229  value.push_back(s[ptr]);
230  ++ptr;
231  }
232  if (ptr == s.size()) // unexpected end of line
233  return std::map<std::string,std::string>();
234  ++ptr; // skip closing '"'
245  std::string escaped_value;
246  for (size_t i = 0; i < value.size(); ++i) {
247  if (value[i] == '\\') {
248  // This will always be valid, because if the QuotedString
249  // ended in an odd number of backslashes, then the parser
250  // would already have returned above, due to a missing
251  // terminating double-quote.
252  ++i;
253  if (value[i] == 'n') {
254  escaped_value.push_back('\n');
255  } else if (value[i] == 't') {
256  escaped_value.push_back('\t');
257  } else if (value[i] == 'r') {
258  escaped_value.push_back('\r');
259  } else if ('0' <= value[i] && value[i] <= '7') {
260  size_t j;
261  // Octal escape sequences have a limit of three octal digits,
262  // but terminate at the first character that is not a valid
263  // octal digit if encountered sooner.
264  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
265  // Tor restricts first digit to 0-3 for three-digit octals.
266  // A leading digit of 4-7 would therefore be interpreted as
267  // a two-digit octal.
268  if (j == 3 && value[i] > '3') {
269  j--;
270  }
271  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
272  // Account for automatic incrementing at loop end
273  i += j - 1;
274  } else {
275  escaped_value.push_back(value[i]);
276  }
277  } else {
278  escaped_value.push_back(value[i]);
279  }
280  }
281  value = escaped_value;
282  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
283  while (ptr < s.size() && s[ptr] != ' ') {
284  value.push_back(s[ptr]);
285  ++ptr;
286  }
287  }
288  if (ptr < s.size() && s[ptr] == ' ')
289  ++ptr; // skip ' ' after key=value
290  mapping[key] = value;
291  }
292  return mapping;
293 }
294 
295 TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
296  base(_base),
297  m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
298  reconnect_timeout(RECONNECT_TIMEOUT_START),
299  m_target(target)
300 {
301  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
302  if (!reconnect_ev)
303  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
304  // Start connection attempts immediately
305  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
306  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
307  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
308  }
309  // Read service private key if cached
310  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
311  if (pkf.first) {
312  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
313  private_key = pkf.second;
314  }
315 }
316 
318 {
319  if (reconnect_ev) {
320  event_free(reconnect_ev);
321  reconnect_ev = nullptr;
322  }
323  if (service.IsValid()) {
325  }
326 }
327 
329 {
330  if (reply.code == 250) {
331  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
332  for (const std::string &s : reply.lines) {
333  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
334  std::map<std::string,std::string>::iterator i;
335  if ((i = m.find("ServiceID")) != m.end())
336  service_id = i->second;
337  if ((i = m.find("PrivateKey")) != m.end())
338  private_key = i->second;
339  }
340  if (service_id.empty()) {
341  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
342  for (const std::string &s : reply.lines) {
343  LogPrintf(" %s\n", SanitizeString(s));
344  }
345  return;
346  }
347  service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
348  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
350  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
351  } else {
352  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
353  }
355  // ... onion requested - keep connection open
356  } else if (reply.code == 510) { // 510 Unrecognized command
357  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
358  } else {
359  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
360  }
361 }
362 
364 {
365  if (reply.code == 250) {
366  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
367 
368  // Now that we know Tor is running setup the proxy for onion addresses
369  // if -onion isn't set to something else.
370  if (gArgs.GetArg("-onion", "") == "") {
371  CService resolved(LookupNumeric("127.0.0.1", 9050));
372  proxyType addrOnion = proxyType(resolved, true);
373  SetProxy(NET_ONION, addrOnion);
374  SetReachable(NET_ONION, true);
375  }
376 
377  // Finally - now create the service
378  if (private_key.empty()) { // No private key, generate one
379  private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
380  }
381  // Request onion service, redirect port.
382  // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
383  _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringIPPort()),
384  std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
385  } else {
386  LogPrintf("tor: Authentication failed\n");
387  }
388 }
389 
406 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)
407 {
408  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
409  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
410  computeHash.Write(cookie.data(), cookie.size());
411  computeHash.Write(clientNonce.data(), clientNonce.size());
412  computeHash.Write(serverNonce.data(), serverNonce.size());
413  computeHash.Finalize(computedHash.data());
414  return computedHash;
415 }
416 
418 {
419  if (reply.code == 250) {
420  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
421  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
422  if (l.first == "AUTHCHALLENGE") {
423  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
424  if (m.empty()) {
425  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
426  return;
427  }
428  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
429  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
430  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
431  if (serverNonce.size() != 32) {
432  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
433  return;
434  }
435 
436  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
437  if (computedServerHash != serverHash) {
438  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
439  return;
440  }
441 
442  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
443  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
444  } else {
445  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
446  }
447  } else {
448  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
449  }
450 }
451 
453 {
454  if (reply.code == 250) {
455  std::set<std::string> methods;
456  std::string cookiefile;
457  /*
458  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
459  * 250-AUTH METHODS=NULL
460  * 250-AUTH METHODS=HASHEDPASSWORD
461  */
462  for (const std::string &s : reply.lines) {
463  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
464  if (l.first == "AUTH") {
465  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
466  std::map<std::string,std::string>::iterator i;
467  if ((i = m.find("METHODS")) != m.end())
468  boost::split(methods, i->second, boost::is_any_of(","));
469  if ((i = m.find("COOKIEFILE")) != m.end())
470  cookiefile = i->second;
471  } else if (l.first == "VERSION") {
472  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
473  std::map<std::string,std::string>::iterator i;
474  if ((i = m.find("Tor")) != m.end()) {
475  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
476  }
477  }
478  }
479  for (const std::string &s : methods) {
480  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
481  }
482  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
483  /* Authentication:
484  * cookie: hex-encoded ~/.tor/control_auth_cookie
485  * password: "password"
486  */
487  std::string torpassword = gArgs.GetArg("-torpassword", "");
488  if (!torpassword.empty()) {
489  if (methods.count("HASHEDPASSWORD")) {
490  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
491  boost::replace_all(torpassword, "\"", "\\\"");
492  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
493  } else {
494  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
495  }
496  } else if (methods.count("NULL")) {
497  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
498  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
499  } else if (methods.count("SAFECOOKIE")) {
500  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
501  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
502  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
503  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
504  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
505  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
506  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
508  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
509  } else {
510  if (status_cookie.first) {
511  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
512  } else {
513  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
514  }
515  }
516  } else if (methods.count("HASHEDPASSWORD")) {
517  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
518  } else {
519  LogPrintf("tor: No supported authentication method\n");
520  }
521  } else {
522  LogPrintf("tor: Requesting protocol info failed\n");
523  }
524 }
525 
527 {
529  // First send a PROTOCOLINFO command to figure out what authentication is expected
530  if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
531  LogPrintf("tor: Error sending initial protocolinfo command\n");
532 }
533 
535 {
536  // Stop advertising service when disconnected
537  if (service.IsValid())
539  service = CService();
540  if (!reconnect)
541  return;
542 
543  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
544 
545  // Single-shot timer for reconnect. Use exponential backoff.
546  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
547  if (reconnect_ev)
548  event_add(reconnect_ev, &time);
550 }
551 
553 {
554  /* Try to reconnect and reestablish if we get booted - for example, Tor
555  * may be restarting.
556  */
557  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
558  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
559  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
560  }
561 }
562 
564 {
565  return GetDataDir() / "onion_v3_private_key";
566 }
567 
568 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
569 {
570  TorController *self = static_cast<TorController*>(arg);
571  self->Reconnect();
572 }
573 
574 /****** Thread ********/
575 static struct event_base *gBase;
576 static std::thread torControlThread;
577 
578 static void TorControlThread(CService onion_service_target)
579 {
580  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
581 
582  event_base_dispatch(gBase);
583 }
584 
585 void StartTorControl(CService onion_service_target)
586 {
587  assert(!gBase);
588 #ifdef WIN32
589  evthread_use_windows_threads();
590 #else
591  evthread_use_pthreads();
592 #endif
593  gBase = event_base_new();
594  if (!gBase) {
595  LogPrintf("tor: Unable to create event_base\n");
596  return;
597  }
598 
599  torControlThread = std::thread(&TraceThread<std::function<void()>>, "torcontrol", [onion_service_target] {
600  TorControlThread(onion_service_target);
601  });
602 }
603 
605 {
606  if (gBase) {
607  LogPrintf("tor: Thread interrupt\n");
608  event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
609  event_base_loopbreak(gBase);
610  }, nullptr, nullptr);
611  }
612 }
613 
615 {
616  if (gBase) {
617  torControlThread.join();
618  event_base_free(gBase);
619  gBase = nullptr;
620  }
621 }
622 
624 {
625  struct in_addr onion_service_target;
626  onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
627  return {onion_service_target, BaseParams().OnionServiceTargetPort()};
628 }
TorControlReply
Reply from Tor, can be single or multi-line.
Definition: torcontrol.h:37
TorController::conn
TorControlConnection conn
Definition: torcontrol.h:129
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:551
CHMAC_SHA256::Finalize
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
readwritefile.h
TOR_SAFE_CLIENTKEY
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:46
hmac_sha256.h
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:805
RemoveLocal
void RemoveLocal(const CService &addr)
Definition: net.cpp:258
TorControlConnection::b_conn
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.h:96
TorControlReply::code
int code
Definition: torcontrol.h:42
TorController::m_tor_control_center
const std::string m_tor_control_center
Definition: torcontrol.h:128
RECONNECT_TIMEOUT_START
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:48
TorController::connected_cb
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:526
TorController::protocolinfo_cb
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:452
TorControlConnection::disconnected
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.h:92
TorControlConnection::ConnectionCB
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.h:58
TorControlConnection
Low-level handling for Tor control connection.
Definition: torcontrol.h:55
atoi
int atoi(const std::string &str)
Definition: strencodings.cpp:449
CHMAC_SHA256
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
TorController::cookie
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.h:138
TorControlConnection::reply_handlers
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.h:100
chainparamsbase.h
StartTorControl
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:585
TorController::~TorController
~TorController()
Definition: torcontrol.cpp:317
InterruptTorControl
void InterruptTorControl()
Definition: torcontrol.cpp:604
TorControlConnection::readcb
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:70
SplitTorReplyLine
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:189
TorControlConnection::Connect
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:132
TorController::disconnected_cb
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:534
chainparams.h
WriteBinaryFile
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: readwritefile.cpp:34
proxyType
Definition: netbase.h:48
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1019
TorController::reconnect_ev
struct event * reconnect_ev
Definition: torcontrol.h:133
ParseTorReplyMapping
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
Definition: torcontrol.cpp:208
ReadBinaryFile
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: readwritefile.cpp:13
TOR_NONCE_SIZE
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:42
strencodings.h
TraceThread
void TraceThread(const char *name, Callable func)
Definition: system.h:484
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1028
TOR_COOKIE_SIZE
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:40
CHMAC_SHA256::Write
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:196
torControlThread
static std::thread torControlThread
Definition: torcontrol.cpp:576
DEFAULT_TOR_CONTROL
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:38
TorController::add_onion_cb
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:328
DefaultOnionServiceTarget
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:623
compat.h
TorController::service_id
std::string service_id
Definition: torcontrol.h:131
TorControlConnection::TorControlConnection
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:59
netaddress.h
CBaseChainParams::OnionServiceTargetPort
uint16_t OnionServiceTargetPort() const
Definition: chainparamsbase.h:30
GetRandBytes
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:584
TorControlConnection::ReplyHandlerCB
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.h:59
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:265
time.h
TorControlReply::lines
std::vector< std::string > lines
Definition: torcontrol.h:43
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
LogPrintf
#define LogPrintf(...)
Definition: logging.h:183
gBase
static struct event_base * gBase
Definition: torcontrol.cpp:575
TOR_SAFE_SERVERKEY
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:44
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:469
BCLog::TOR
@ TOR
Definition: logging.h:39
TorControlConnection::Disconnect
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:162
TorController::service
CService service
Definition: torcontrol.h:135
TorController::base
struct event_base * base
Definition: torcontrol.h:127
LogPrint
#define LogPrint(category,...)
Definition: logging.h:187
TorController::auth_cb
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:363
MAX_LINE_LENGTH
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:55
TorController::reconnect
bool reconnect
Definition: torcontrol.h:132
CHMAC_SHA256::OUTPUT_SIZE
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
system.h
TorController::Reconnect
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:552
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:607
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
TorController::clientNonce
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.h:140
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:27
ComputeResponse
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:406
torcontrol.h
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:33
TorControlConnection::Command
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:169
TorController::m_target
const CService m_target
Definition: torcontrol.h:136
gArgs
ArgsManager gArgs
Definition: system.cpp:79
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
TorController::reconnect_timeout
float reconnect_timeout
Definition: torcontrol.h:134
MillisToTimeval
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:172
TorController::authchallenge_cb
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:417
RECONNECT_TIMEOUT_EXP
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:50
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:538
TorController
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.h:112
StopTorControl
void StopTorControl()
Definition: torcontrol.cpp:614
netbase.h
TorController::TorController
TorController()
Definition: torcontrol.h:116
TorController::private_key
std::string private_key
Definition: torcontrol.h:130
LookupNumeric
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:229
TorController::GetPrivateKeyFile
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:563
TorControlConnection::~TorControlConnection
~TorControlConnection()
Definition: torcontrol.cpp:64
net.h
TorControlConnection::eventcb
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:115
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
TorControlConnection::base
struct event_base * base
Libevent event base.
Definition: torcontrol.h:94
TorControlThread
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:578
TorControlConnection::connected
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.h:90
TorController::reconnect_cb
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:568
ctx
static secp256k1_context * ctx
Definition: tests.c:36
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:227