Bitcoin Core 29.99.0
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1// Copyright (c) 2015-2022 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 <common/args.h>
11#include <compat/compat.h>
12#include <crypto/hmac_sha256.h>
13#include <logging.h>
14#include <net.h>
15#include <netaddress.h>
16#include <netbase.h>
17#include <random.h>
18#include <tinyformat.h>
19#include <util/check.h>
20#include <util/fs.h>
21#include <util/readwritefile.h>
22#include <util/strencodings.h>
23#include <util/string.h>
24#include <util/thread.h>
25#include <util/time.h>
26
27#include <algorithm>
28#include <cassert>
29#include <cstdint>
30#include <cstdlib>
31#include <deque>
32#include <functional>
33#include <map>
34#include <optional>
35#include <set>
36#include <thread>
37#include <utility>
38#include <vector>
39
40#include <event2/buffer.h>
41#include <event2/bufferevent.h>
42#include <event2/event.h>
43#include <event2/thread.h>
44#include <event2/util.h>
45
48using util::ToString;
49
51const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT);
53static const int TOR_COOKIE_SIZE = 32;
55static const int TOR_NONCE_SIZE = 32;
57static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
59static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
61static const float RECONNECT_TIMEOUT_START = 1.0;
63static const float RECONNECT_TIMEOUT_EXP = 1.5;
65static const float RECONNECT_TIMEOUT_MAX = 600.0;
70static const int MAX_LINE_LENGTH = 100000;
71static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050;
72
73/****** Low-level TorControlConnection ********/
74
76 : base(_base)
77{
78}
79
81{
82 if (b_conn)
83 bufferevent_free(b_conn);
84}
85
86void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
87{
88 TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
89 struct evbuffer *input = bufferevent_get_input(bev);
90 size_t n_read_out = 0;
91 char *line;
92 assert(input);
93 // If there is not a whole line to read, evbuffer_readln returns nullptr
94 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
95 {
96 std::string s(line, n_read_out);
97 free(line);
98 if (s.size() < 4) // Short line
99 continue;
100 // <status>(-|+| )<data><CRLF>
101 self->message.code = ToIntegral<int>(s.substr(0, 3)).value_or(0);
102 self->message.lines.push_back(s.substr(4));
103 char ch = s[3]; // '-','+' or ' '
104 if (ch == ' ') {
105 // Final line, dispatch reply and clean up
106 if (self->message.code >= 600) {
107 // (currently unused)
108 // Dispatch async notifications to async handler
109 // Synchronous and asynchronous messages are never interleaved
110 } else {
111 if (!self->reply_handlers.empty()) {
112 // Invoke reply handler with message
113 self->reply_handlers.front()(*self, self->message);
114 self->reply_handlers.pop_front();
115 } else {
116 LogDebug(BCLog::TOR, "Received unexpected sync reply %i\n", self->message.code);
117 }
118 }
119 self->message.Clear();
120 }
121 }
122 // Check for size of buffer - protect against memory exhaustion with very long lines
123 // Do this after evbuffer_readln to make sure all full lines have been
124 // removed from the buffer. Everything left is an incomplete line.
125 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
126 LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
127 self->Disconnect();
128 }
129}
130
131void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
132{
133 TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
134 if (what & BEV_EVENT_CONNECTED) {
135 LogDebug(BCLog::TOR, "Successfully connected!\n");
136 self->connected(*self);
137 } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
138 if (what & BEV_EVENT_ERROR) {
139 LogDebug(BCLog::TOR, "Error connecting to Tor control socket\n");
140 } else {
141 LogDebug(BCLog::TOR, "End of stream\n");
142 }
143 self->Disconnect();
144 self->disconnected(*self);
145 }
146}
147
148bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
149{
150 if (b_conn) {
151 Disconnect();
152 }
153
154 const std::optional<CService> control_service{Lookup(tor_control_center, DEFAULT_TOR_CONTROL_PORT, fNameLookup)};
155 if (!control_service.has_value()) {
156 LogPrintf("tor: Failed to look up control center %s\n", tor_control_center);
157 return false;
158 }
159
160 struct sockaddr_storage control_address;
161 socklen_t control_address_len = sizeof(control_address);
162 if (!control_service.value().GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) {
163 LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
164 return false;
165 }
166
167 // Create a new socket, set up callbacks and enable notification bits
168 b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
169 if (!b_conn) {
170 return false;
171 }
172 bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
173 bufferevent_enable(b_conn, EV_READ|EV_WRITE);
174 this->connected = _connected;
175 this->disconnected = _disconnected;
176
177 // Finally, connect to tor_control_center
178 if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) {
179 LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
180 return false;
181 }
182 return true;
183}
184
186{
187 if (b_conn)
188 bufferevent_free(b_conn);
189 b_conn = nullptr;
190}
191
192bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
193{
194 if (!b_conn)
195 return false;
196 struct evbuffer *buf = bufferevent_get_output(b_conn);
197 if (!buf)
198 return false;
199 evbuffer_add(buf, cmd.data(), cmd.size());
200 evbuffer_add(buf, "\r\n", 2);
201 reply_handlers.push_back(reply_handler);
202 return true;
203}
204
205/****** General parsing utilities ********/
206
207/* Split reply line in the form 'AUTH METHODS=...' into a type
208 * 'AUTH' and arguments 'METHODS=...'.
209 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
210 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
211 */
212std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
213{
214 size_t ptr=0;
215 std::string type;
216 while (ptr < s.size() && s[ptr] != ' ') {
217 type.push_back(s[ptr]);
218 ++ptr;
219 }
220 if (ptr < s.size())
221 ++ptr; // skip ' '
222 return make_pair(type, s.substr(ptr));
223}
224
231std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
232{
233 std::map<std::string,std::string> mapping;
234 size_t ptr=0;
235 while (ptr < s.size()) {
236 std::string key, value;
237 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
238 key.push_back(s[ptr]);
239 ++ptr;
240 }
241 if (ptr == s.size()) // unexpected end of line
242 return std::map<std::string,std::string>();
243 if (s[ptr] == ' ') // The remaining string is an OptArguments
244 break;
245 ++ptr; // skip '='
246 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
247 ++ptr; // skip opening '"'
248 bool escape_next = false;
249 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
250 // Repeated backslashes must be interpreted as pairs
251 escape_next = (s[ptr] == '\\' && !escape_next);
252 value.push_back(s[ptr]);
253 ++ptr;
254 }
255 if (ptr == s.size()) // unexpected end of line
256 return std::map<std::string,std::string>();
257 ++ptr; // skip closing '"'
268 std::string escaped_value;
269 for (size_t i = 0; i < value.size(); ++i) {
270 if (value[i] == '\\') {
271 // This will always be valid, because if the QuotedString
272 // ended in an odd number of backslashes, then the parser
273 // would already have returned above, due to a missing
274 // terminating double-quote.
275 ++i;
276 if (value[i] == 'n') {
277 escaped_value.push_back('\n');
278 } else if (value[i] == 't') {
279 escaped_value.push_back('\t');
280 } else if (value[i] == 'r') {
281 escaped_value.push_back('\r');
282 } else if ('0' <= value[i] && value[i] <= '7') {
283 size_t j;
284 // Octal escape sequences have a limit of three octal digits,
285 // but terminate at the first character that is not a valid
286 // octal digit if encountered sooner.
287 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
288 // Tor restricts first digit to 0-3 for three-digit octals.
289 // A leading digit of 4-7 would therefore be interpreted as
290 // a two-digit octal.
291 if (j == 3 && value[i] > '3') {
292 j--;
293 }
294 const auto end{i + j};
295 uint8_t val{0};
296 while (i < end) {
297 val *= 8;
298 val += value[i++] - '0';
299 }
300 escaped_value.push_back(char(val));
301 // Account for automatic incrementing at loop end
302 --i;
303 } else {
304 escaped_value.push_back(value[i]);
305 }
306 } else {
307 escaped_value.push_back(value[i]);
308 }
309 }
310 value = escaped_value;
311 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
312 while (ptr < s.size() && s[ptr] != ' ') {
313 value.push_back(s[ptr]);
314 ++ptr;
315 }
316 }
317 if (ptr < s.size() && s[ptr] == ' ')
318 ++ptr; // skip ' ' after key=value
319 mapping[key] = value;
320 }
321 return mapping;
322}
323
324TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
325 base(_base),
326 m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(RECONNECT_TIMEOUT_START),
327 m_target(target)
328{
329 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
330 if (!reconnect_ev)
331 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
332 // Start connection attempts immediately
333 if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
334 std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
335 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
336 }
337 // Read service private key if cached
338 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
339 if (pkf.first) {
340 LogDebug(BCLog::TOR, "Reading cached private key from %s\n", fs::PathToString(GetPrivateKeyFile()));
341 private_key = pkf.second;
342 }
343}
344
346{
347 if (reconnect_ev) {
348 event_free(reconnect_ev);
349 reconnect_ev = nullptr;
350 }
351 if (service.IsValid()) {
353 }
354}
355
357{
358 // NOTE: We can only get here if -onion is unset
359 std::string socks_location;
360 if (reply.code == 250) {
361 for (const auto& line : reply.lines) {
362 if (line.starts_with("net/listeners/socks=")) {
363 const std::string port_list_str = line.substr(20);
364 std::vector<std::string> port_list = SplitString(port_list_str, ' ');
365
366 for (auto& portstr : port_list) {
367 if (portstr.empty()) continue;
368 if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
369 portstr = portstr.substr(1, portstr.size() - 2);
370 if (portstr.empty()) continue;
371 }
372 socks_location = portstr;
373 if (portstr.starts_with("127.0.0.1:")) {
374 // Prefer localhost - ignore other ports
375 break;
376 }
377 }
378 }
379 }
380 if (!socks_location.empty()) {
381 LogDebug(BCLog::TOR, "Get SOCKS port command yielded %s\n", socks_location);
382 } else {
383 LogPrintf("tor: Get SOCKS port command returned nothing\n");
384 }
385 } else if (reply.code == 510) { // 510 Unrecognized command
386 LogPrintf("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n");
387 } else {
388 LogPrintf("tor: Get SOCKS port command failed; error code %d\n", reply.code);
389 }
390
391 CService resolved;
392 Assume(!resolved.IsValid());
393 if (!socks_location.empty()) {
394 resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT);
395 }
396 if (!resolved.IsValid()) {
397 // Fallback to old behaviour
398 resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
399 }
400
401 Assume(resolved.IsValid());
402 LogDebug(BCLog::TOR, "Configuring onion proxy for %s\n", resolved.ToStringAddrPort());
403 Proxy addrOnion = Proxy(resolved, true);
404 SetProxy(NET_ONION, addrOnion);
405
406 const auto onlynets = gArgs.GetArgs("-onlynet");
407
408 const bool onion_allowed_by_onlynet{
409 onlynets.empty() ||
410 std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
411 return ParseNetwork(n) == NET_ONION;
412 })};
413
414 if (onion_allowed_by_onlynet) {
415 // If NET_ONION is reachable, then the below is a noop.
416 //
417 // If NET_ONION is not reachable, then none of -proxy or -onion was given.
418 // Since we are here, then -torcontrol and -torpassword were given.
420 }
421}
422
424{
425 if (reply.code == 250) {
426 LogDebug(BCLog::TOR, "ADD_ONION successful\n");
427 for (const std::string &s : reply.lines) {
428 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
429 std::map<std::string,std::string>::iterator i;
430 if ((i = m.find("ServiceID")) != m.end())
431 service_id = i->second;
432 if ((i = m.find("PrivateKey")) != m.end())
433 private_key = i->second;
434 }
435 if (service_id.empty()) {
436 LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
437 for (const std::string &s : reply.lines) {
438 LogPrintf(" %s\n", SanitizeString(s));
439 }
440 return;
441 }
442 service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
443 LogInfo("Got tor service ID %s, advertising service %s\n", service_id, service.ToStringAddrPort());
445 LogDebug(BCLog::TOR, "Cached service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
446 } else {
447 LogPrintf("tor: Error writing service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
448 }
450 // ... onion requested - keep connection open
451 } else if (reply.code == 510) { // 510 Unrecognized command
452 LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
453 } else {
454 LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
455 }
456}
457
459{
460 if (reply.code == 250) {
461 LogDebug(BCLog::TOR, "Authentication successful\n");
462
463 // Now that we know Tor is running setup the proxy for onion addresses
464 // if -onion isn't set to something else.
465 if (gArgs.GetArg("-onion", "") == "") {
466 _conn.Command("GETINFO net/listeners/socks", std::bind(&TorController::get_socks_cb, this, std::placeholders::_1, std::placeholders::_2));
467 }
468
469 // Finally - now create the service
470 if (private_key.empty()) { // No private key, generate one
471 private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
472 }
473 // Request onion service, redirect port.
474 // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
475 _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringAddrPort()),
476 std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
477 } else {
478 LogPrintf("tor: Authentication failed\n");
479 }
480}
481
498static 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)
499{
500 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
501 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
502 computeHash.Write(cookie.data(), cookie.size());
503 computeHash.Write(clientNonce.data(), clientNonce.size());
504 computeHash.Write(serverNonce.data(), serverNonce.size());
505 computeHash.Finalize(computedHash.data());
506 return computedHash;
507}
508
510{
511 if (reply.code == 250) {
512 LogDebug(BCLog::TOR, "SAFECOOKIE authentication challenge successful\n");
513 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
514 if (l.first == "AUTHCHALLENGE") {
515 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
516 if (m.empty()) {
517 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
518 return;
519 }
520 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
521 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
522 LogDebug(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
523 if (serverNonce.size() != 32) {
524 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
525 return;
526 }
527
528 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
529 if (computedServerHash != serverHash) {
530 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
531 return;
532 }
533
534 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
535 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
536 } else {
537 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
538 }
539 } else {
540 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
541 }
542}
543
545{
546 if (reply.code == 250) {
547 std::set<std::string> methods;
548 std::string cookiefile;
549 /*
550 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
551 * 250-AUTH METHODS=NULL
552 * 250-AUTH METHODS=HASHEDPASSWORD
553 */
554 for (const std::string &s : reply.lines) {
555 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
556 if (l.first == "AUTH") {
557 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
558 std::map<std::string,std::string>::iterator i;
559 if ((i = m.find("METHODS")) != m.end()) {
560 std::vector<std::string> m_vec = SplitString(i->second, ',');
561 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
562 }
563 if ((i = m.find("COOKIEFILE")) != m.end())
564 cookiefile = i->second;
565 } else if (l.first == "VERSION") {
566 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
567 std::map<std::string,std::string>::iterator i;
568 if ((i = m.find("Tor")) != m.end()) {
569 LogDebug(BCLog::TOR, "Connected to Tor version %s\n", i->second);
570 }
571 }
572 }
573 for (const std::string &s : methods) {
574 LogDebug(BCLog::TOR, "Supported authentication method: %s\n", s);
575 }
576 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
577 /* Authentication:
578 * cookie: hex-encoded ~/.tor/control_auth_cookie
579 * password: "password"
580 */
581 std::string torpassword = gArgs.GetArg("-torpassword", "");
582 if (!torpassword.empty()) {
583 if (methods.count("HASHEDPASSWORD")) {
584 LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication\n");
585 ReplaceAll(torpassword, "\"", "\\\"");
586 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
587 } else {
588 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
589 }
590 } else if (methods.count("NULL")) {
591 LogDebug(BCLog::TOR, "Using NULL authentication\n");
592 _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
593 } else if (methods.count("SAFECOOKIE")) {
594 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
595 LogDebug(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
596 std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE);
597 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
598 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
599 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
600 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
602 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
603 } else {
604 if (status_cookie.first) {
605 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
606 } else {
607 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
608 }
609 }
610 } else if (methods.count("HASHEDPASSWORD")) {
611 LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
612 } else {
613 LogPrintf("tor: No supported authentication method\n");
614 }
615 } else {
616 LogPrintf("tor: Requesting protocol info failed\n");
617 }
618}
619
621{
623 // First send a PROTOCOLINFO command to figure out what authentication is expected
624 if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
625 LogPrintf("tor: Error sending initial protocolinfo command\n");
626}
627
629{
630 // Stop advertising service when disconnected
631 if (service.IsValid())
633 service = CService();
634 if (!reconnect)
635 return;
636
637 LogDebug(BCLog::TOR, "Not connected to Tor control port %s, retrying in %.2f s\n",
639
640 // Single-shot timer for reconnect. Use exponential backoff with a maximum.
641 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
642 if (reconnect_ev)
643 event_add(reconnect_ev, &time);
644
646}
647
649{
650 /* Try to reconnect and reestablish if we get booted - for example, Tor
651 * may be restarting.
652 */
653 if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
654 std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
655 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
656 }
657}
658
660{
661 return gArgs.GetDataDirNet() / "onion_v3_private_key";
662}
663
664void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
665{
666 TorController *self = static_cast<TorController*>(arg);
667 self->Reconnect();
668}
669
670/****** Thread ********/
671static struct event_base *gBase;
672static std::thread torControlThread;
673
674static void TorControlThread(CService onion_service_target)
675{
676 TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
677
678 event_base_dispatch(gBase);
679}
680
681void StartTorControl(CService onion_service_target)
682{
683 assert(!gBase);
684#ifdef WIN32
685 evthread_use_windows_threads();
686#else
687 evthread_use_pthreads();
688#endif
689 gBase = event_base_new();
690 if (!gBase) {
691 LogPrintf("tor: Unable to create event_base\n");
692 return;
693 }
694
695 torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
696 TorControlThread(onion_service_target);
697 });
698}
699
701{
702 if (gBase) {
703 LogPrintf("tor: Thread interrupt\n");
704 event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
705 event_base_loopbreak(gBase);
706 }, nullptr, nullptr);
707 }
708}
709
711{
712 if (gBase) {
713 torControlThread.join();
714 event_base_free(gBase);
715 gBase = nullptr;
716 }
717}
718
720{
721 struct in_addr onion_service_target;
722 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
723 return {onion_service_target, port};
724}
ArgsManager gArgs
Definition: args.cpp:42
const auto cmd
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:362
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:234
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:457
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:15
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
bool IsValid() const
Definition: netaddress.cpp:428
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
std::string ToStringAddrPort() const
Definition: netaddress.cpp:907
Definition: netbase.h:59
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:103
Low-level handling for Tor control connection.
Definition: torcontrol.h:52
TorControlReply message
Message being received.
Definition: torcontrol.h:92
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.h:94
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:148
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:75
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:192
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.h:84
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:86
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.h:55
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:131
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.h:86
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.h:54
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:185
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.h:90
struct event_base * base
Libevent event base.
Definition: torcontrol.h:88
Reply from Tor, can be single or multi-line.
Definition: torcontrol.h:34
std::vector< std::string > lines
Definition: torcontrol.h:39
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.h:107
TorControlConnection conn
Definition: torcontrol.h:123
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:664
std::string service_id
Definition: torcontrol.h:125
struct event_base * base
Definition: torcontrol.h:121
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:659
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.h:134
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:620
void get_socks_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for GETINFO net/listeners/socks result.
Definition: torcontrol.cpp:356
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:423
const std::string m_tor_control_center
Definition: torcontrol.h:122
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:628
const CService m_target
Definition: torcontrol.h:130
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:509
CService service
Definition: torcontrol.h:129
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.h:132
struct event * reconnect_ev
Definition: torcontrol.h:127
float reconnect_timeout
Definition: torcontrol.h:128
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:458
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:648
std::string private_key
Definition: torcontrol.h:124
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:544
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
#define LogInfo(...)
Definition: logging.h:261
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
@ TOR
Definition: logging.h:44
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:174
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:136
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:16
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:11
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:277
@ LOCAL_MANUAL
Definition: net.h:152
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:43
bool SetProxy(enum Network net, const Proxy &addrProxy)
Definition: netbase.cpp:680
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:195
ReachableNets g_reachable_nets
Definition: netbase.cpp:43
bool fNameLookup
Definition: netbase.cpp:37
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:220
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:676
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize)
Read full contents of a file and return them in a std::string.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:68
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:119
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:59
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:498
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:70
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:63
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
Definition: torcontrol.cpp:51
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:674
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:212
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:57
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:53
static struct event_base * gBase
Definition: torcontrol.cpp:671
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:55
static const float RECONNECT_TIMEOUT_MAX
Maximum reconnect timeout in seconds to prevent excessive delays.
Definition: torcontrol.cpp:65
void InterruptTorControl()
Definition: torcontrol.cpp:700
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:231
static std::thread torControlThread
Definition: torcontrol.cpp:672
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:61
static const uint16_t DEFAULT_TOR_SOCKS_PORT
Definition: torcontrol.cpp:71
CService DefaultOnionServiceTarget(uint16_t port)
Definition: torcontrol.cpp:719
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:681
void StopTorControl()
Definition: torcontrol.cpp:710
constexpr int DEFAULT_TOR_CONTROL_PORT
Functionality for communicating with Tor.
Definition: torcontrol.h:22
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
assert(!tx.IsCoinBase())