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