Merge #12062: Increment MIT Licence copyright header year on files modified in 2017
[bitcoinplatinum.git] / src / torcontrol.cpp
blobc45b5dac0d56a9d184530b6af02fdea23ba7f056
1 // Copyright (c) 2015-2017 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.
6 #include <torcontrol.h>
7 #include <utilstrencodings.h>
8 #include <netbase.h>
9 #include <net.h>
10 #include <util.h>
11 #include <crypto/hmac_sha256.h>
13 #include <vector>
14 #include <deque>
15 #include <set>
16 #include <stdlib.h>
18 #include <boost/bind.hpp>
19 #include <boost/signals2/signal.hpp>
20 #include <boost/algorithm/string/split.hpp>
21 #include <boost/algorithm/string/classification.hpp>
22 #include <boost/algorithm/string/replace.hpp>
24 #include <event2/bufferevent.h>
25 #include <event2/buffer.h>
26 #include <event2/util.h>
27 #include <event2/event.h>
28 #include <event2/thread.h>
30 /** Default control port */
31 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
32 /** Tor cookie size (from control-spec.txt) */
33 static const int TOR_COOKIE_SIZE = 32;
34 /** Size of client/server nonce for SAFECOOKIE */
35 static const int TOR_NONCE_SIZE = 32;
36 /** For computing serverHash in SAFECOOKIE */
37 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
38 /** For computing clientHash in SAFECOOKIE */
39 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
40 /** Exponential backoff configuration - initial timeout in seconds */
41 static const float RECONNECT_TIMEOUT_START = 1.0;
42 /** Exponential backoff configuration - growth factor */
43 static const float RECONNECT_TIMEOUT_EXP = 1.5;
44 /** Maximum length for lines received on TorControlConnection.
45 * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
46 * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
48 static const int MAX_LINE_LENGTH = 100000;
50 /****** Low-level TorControlConnection ********/
52 /** Reply from Tor, can be single or multi-line */
53 class TorControlReply
55 public:
56 TorControlReply() { Clear(); }
58 int code;
59 std::vector<std::string> lines;
61 void Clear()
63 code = 0;
64 lines.clear();
68 /** Low-level handling for Tor control connection.
69 * Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
71 class TorControlConnection
73 public:
74 typedef std::function<void(TorControlConnection&)> ConnectionCB;
75 typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
77 /** Create a new TorControlConnection.
79 explicit TorControlConnection(struct event_base *base);
80 ~TorControlConnection();
82 /**
83 * Connect to a Tor control port.
84 * target is address of the form host:port.
85 * connected is the handler that is called when connection is successfully established.
86 * disconnected is a handler that is called when the connection is broken.
87 * Return true on success.
89 bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
91 /**
92 * Disconnect from Tor control port.
94 bool Disconnect();
96 /** Send a command, register a handler for the reply.
97 * A trailing CRLF is automatically added.
98 * Return true on success.
100 bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
102 /** Response handlers for async replies */
103 boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
104 private:
105 /** Callback when ready for use */
106 std::function<void(TorControlConnection&)> connected;
107 /** Callback when connection lost */
108 std::function<void(TorControlConnection&)> disconnected;
109 /** Libevent event base */
110 struct event_base *base;
111 /** Connection to control socket */
112 struct bufferevent *b_conn;
113 /** Message being received */
114 TorControlReply message;
115 /** Response handlers */
116 std::deque<ReplyHandlerCB> reply_handlers;
118 /** Libevent handlers: internal */
119 static void readcb(struct bufferevent *bev, void *ctx);
120 static void eventcb(struct bufferevent *bev, short what, void *ctx);
123 TorControlConnection::TorControlConnection(struct event_base *_base):
124 base(_base), b_conn(nullptr)
128 TorControlConnection::~TorControlConnection()
130 if (b_conn)
131 bufferevent_free(b_conn);
134 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
136 TorControlConnection *self = (TorControlConnection*)ctx;
137 struct evbuffer *input = bufferevent_get_input(bev);
138 size_t n_read_out = 0;
139 char *line;
140 assert(input);
141 // If there is not a whole line to read, evbuffer_readln returns nullptr
142 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
144 std::string s(line, n_read_out);
145 free(line);
146 if (s.size() < 4) // Short line
147 continue;
148 // <status>(-|+| )<data><CRLF>
149 self->message.code = atoi(s.substr(0,3));
150 self->message.lines.push_back(s.substr(4));
151 char ch = s[3]; // '-','+' or ' '
152 if (ch == ' ') {
153 // Final line, dispatch reply and clean up
154 if (self->message.code >= 600) {
155 // Dispatch async notifications to async handler
156 // Synchronous and asynchronous messages are never interleaved
157 self->async_handler(*self, self->message);
158 } else {
159 if (!self->reply_handlers.empty()) {
160 // Invoke reply handler with message
161 self->reply_handlers.front()(*self, self->message);
162 self->reply_handlers.pop_front();
163 } else {
164 LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
167 self->message.Clear();
170 // Check for size of buffer - protect against memory exhaustion with very long lines
171 // Do this after evbuffer_readln to make sure all full lines have been
172 // removed from the buffer. Everything left is an incomplete line.
173 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
174 LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
175 self->Disconnect();
179 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
181 TorControlConnection *self = (TorControlConnection*)ctx;
182 if (what & BEV_EVENT_CONNECTED) {
183 LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
184 self->connected(*self);
185 } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
186 if (what & BEV_EVENT_ERROR) {
187 LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
188 } else {
189 LogPrint(BCLog::TOR, "tor: End of stream\n");
191 self->Disconnect();
192 self->disconnected(*self);
196 bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
198 if (b_conn)
199 Disconnect();
200 // Parse target address:port
201 struct sockaddr_storage connect_to_addr;
202 int connect_to_addrlen = sizeof(connect_to_addr);
203 if (evutil_parse_sockaddr_port(target.c_str(),
204 (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
205 LogPrintf("tor: Error parsing socket address %s\n", target);
206 return false;
209 // Create a new socket, set up callbacks and enable notification bits
210 b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
211 if (!b_conn)
212 return false;
213 bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
214 bufferevent_enable(b_conn, EV_READ|EV_WRITE);
215 this->connected = _connected;
216 this->disconnected = _disconnected;
218 // Finally, connect to target
219 if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
220 LogPrintf("tor: Error connecting to address %s\n", target);
221 return false;
223 return true;
226 bool TorControlConnection::Disconnect()
228 if (b_conn)
229 bufferevent_free(b_conn);
230 b_conn = nullptr;
231 return true;
234 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
236 if (!b_conn)
237 return false;
238 struct evbuffer *buf = bufferevent_get_output(b_conn);
239 if (!buf)
240 return false;
241 evbuffer_add(buf, cmd.data(), cmd.size());
242 evbuffer_add(buf, "\r\n", 2);
243 reply_handlers.push_back(reply_handler);
244 return true;
247 /****** General parsing utilities ********/
249 /* Split reply line in the form 'AUTH METHODS=...' into a type
250 * 'AUTH' and arguments 'METHODS=...'.
251 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
252 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
254 static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
256 size_t ptr=0;
257 std::string type;
258 while (ptr < s.size() && s[ptr] != ' ') {
259 type.push_back(s[ptr]);
260 ++ptr;
262 if (ptr < s.size())
263 ++ptr; // skip ' '
264 return make_pair(type, s.substr(ptr));
267 /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
268 * Returns a map of keys to values, or an empty map if there was an error.
269 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
270 * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
271 * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
273 static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
275 std::map<std::string,std::string> mapping;
276 size_t ptr=0;
277 while (ptr < s.size()) {
278 std::string key, value;
279 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
280 key.push_back(s[ptr]);
281 ++ptr;
283 if (ptr == s.size()) // unexpected end of line
284 return std::map<std::string,std::string>();
285 if (s[ptr] == ' ') // The remaining string is an OptArguments
286 break;
287 ++ptr; // skip '='
288 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
289 ++ptr; // skip opening '"'
290 bool escape_next = false;
291 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
292 // Repeated backslashes must be interpreted as pairs
293 escape_next = (s[ptr] == '\\' && !escape_next);
294 value.push_back(s[ptr]);
295 ++ptr;
297 if (ptr == s.size()) // unexpected end of line
298 return std::map<std::string,std::string>();
299 ++ptr; // skip closing '"'
301 * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
303 * For future-proofing, controller implementors MAY use the following
304 * rules to be compatible with buggy Tor implementations and with
305 * future ones that implement the spec as intended:
307 * Read \n \t \r and \0 ... \377 as C escapes.
308 * Treat a backslash followed by any other character as that character.
310 std::string escaped_value;
311 for (size_t i = 0; i < value.size(); ++i) {
312 if (value[i] == '\\') {
313 // This will always be valid, because if the QuotedString
314 // ended in an odd number of backslashes, then the parser
315 // would already have returned above, due to a missing
316 // terminating double-quote.
317 ++i;
318 if (value[i] == 'n') {
319 escaped_value.push_back('\n');
320 } else if (value[i] == 't') {
321 escaped_value.push_back('\t');
322 } else if (value[i] == 'r') {
323 escaped_value.push_back('\r');
324 } else if ('0' <= value[i] && value[i] <= '7') {
325 size_t j;
326 // Octal escape sequences have a limit of three octal digits,
327 // but terminate at the first character that is not a valid
328 // octal digit if encountered sooner.
329 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
330 // Tor restricts first digit to 0-3 for three-digit octals.
331 // A leading digit of 4-7 would therefore be interpreted as
332 // a two-digit octal.
333 if (j == 3 && value[i] > '3') {
334 j--;
336 escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
337 // Account for automatic incrementing at loop end
338 i += j - 1;
339 } else {
340 escaped_value.push_back(value[i]);
342 } else {
343 escaped_value.push_back(value[i]);
346 value = escaped_value;
347 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
348 while (ptr < s.size() && s[ptr] != ' ') {
349 value.push_back(s[ptr]);
350 ++ptr;
353 if (ptr < s.size() && s[ptr] == ' ')
354 ++ptr; // skip ' ' after key=value
355 mapping[key] = value;
357 return mapping;
360 /** Read full contents of a file and return them in a std::string.
361 * Returns a pair <status, string>.
362 * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
364 * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
365 * (with len > maxsize) will be returned.
367 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
369 FILE *f = fsbridge::fopen(filename, "rb");
370 if (f == nullptr)
371 return std::make_pair(false,"");
372 std::string retval;
373 char buffer[128];
374 size_t n;
375 while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
376 // Check for reading errors so we don't return any data if we couldn't
377 // read the entire file (or up to maxsize)
378 if (ferror(f)) {
379 fclose(f);
380 return std::make_pair(false,"");
382 retval.append(buffer, buffer+n);
383 if (retval.size() > maxsize)
384 break;
386 fclose(f);
387 return std::make_pair(true,retval);
390 /** Write contents of std::string to a file.
391 * @return true on success.
393 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
395 FILE *f = fsbridge::fopen(filename, "wb");
396 if (f == nullptr)
397 return false;
398 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
399 fclose(f);
400 return false;
402 fclose(f);
403 return true;
406 /****** Bitcoin specific TorController implementation ********/
408 /** Controller that connects to Tor control socket, authenticate, then create
409 * and maintain an ephemeral hidden service.
411 class TorController
413 public:
414 TorController(struct event_base* base, const std::string& target);
415 ~TorController();
417 /** Get name fo file to store private key in */
418 fs::path GetPrivateKeyFile();
420 /** Reconnect, after getting disconnected */
421 void Reconnect();
422 private:
423 struct event_base* base;
424 std::string target;
425 TorControlConnection conn;
426 std::string private_key;
427 std::string service_id;
428 bool reconnect;
429 struct event *reconnect_ev;
430 float reconnect_timeout;
431 CService service;
432 /** Cookie for SAFECOOKIE auth */
433 std::vector<uint8_t> cookie;
434 /** ClientNonce for SAFECOOKIE auth */
435 std::vector<uint8_t> clientNonce;
437 /** Callback for ADD_ONION result */
438 void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
439 /** Callback for AUTHENTICATE result */
440 void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
441 /** Callback for AUTHCHALLENGE result */
442 void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
443 /** Callback for PROTOCOLINFO result */
444 void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
445 /** Callback after successful connection */
446 void connected_cb(TorControlConnection& conn);
447 /** Callback after connection lost or failed connection attempt */
448 void disconnected_cb(TorControlConnection& conn);
450 /** Callback for reconnect timer */
451 static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
454 TorController::TorController(struct event_base* _base, const std::string& _target):
455 base(_base),
456 target(_target), conn(base), reconnect(true), reconnect_ev(0),
457 reconnect_timeout(RECONNECT_TIMEOUT_START)
459 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
460 if (!reconnect_ev)
461 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
462 // Start connection attempts immediately
463 if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
464 boost::bind(&TorController::disconnected_cb, this, _1) )) {
465 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
467 // Read service private key if cached
468 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
469 if (pkf.first) {
470 LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
471 private_key = pkf.second;
475 TorController::~TorController()
477 if (reconnect_ev) {
478 event_free(reconnect_ev);
479 reconnect_ev = nullptr;
481 if (service.IsValid()) {
482 RemoveLocal(service);
486 void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
488 if (reply.code == 250) {
489 LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
490 for (const std::string &s : reply.lines) {
491 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
492 std::map<std::string,std::string>::iterator i;
493 if ((i = m.find("ServiceID")) != m.end())
494 service_id = i->second;
495 if ((i = m.find("PrivateKey")) != m.end())
496 private_key = i->second;
498 if (service_id.empty()) {
499 LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
500 for (const std::string &s : reply.lines) {
501 LogPrintf(" %s\n", SanitizeString(s));
503 return;
505 service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
506 LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
507 if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
508 LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
509 } else {
510 LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
512 AddLocal(service, LOCAL_MANUAL);
513 // ... onion requested - keep connection open
514 } else if (reply.code == 510) { // 510 Unrecognized command
515 LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
516 } else {
517 LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
521 void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
523 if (reply.code == 250) {
524 LogPrint(BCLog::TOR, "tor: Authentication successful\n");
526 // Now that we know Tor is running setup the proxy for onion addresses
527 // if -onion isn't set to something else.
528 if (gArgs.GetArg("-onion", "") == "") {
529 CService resolved(LookupNumeric("127.0.0.1", 9050));
530 proxyType addrOnion = proxyType(resolved, true);
531 SetProxy(NET_TOR, addrOnion);
532 SetLimited(NET_TOR, false);
535 // Finally - now create the service
536 if (private_key.empty()) // No private key, generate one
537 private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
538 // Request hidden service, redirect port.
539 // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
540 // choice. TODO; refactor the shutdown sequence some day.
541 _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
542 boost::bind(&TorController::add_onion_cb, this, _1, _2));
543 } else {
544 LogPrintf("tor: Authentication failed\n");
548 /** Compute Tor SAFECOOKIE response.
550 * ServerHash is computed as:
551 * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
552 * CookieString | ClientNonce | ServerNonce)
553 * (with the HMAC key as its first argument)
555 * After a controller sends a successful AUTHCHALLENGE command, the
556 * next command sent on the connection must be an AUTHENTICATE command,
557 * and the only authentication string which that AUTHENTICATE command
558 * will accept is:
560 * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
561 * CookieString | ClientNonce | ServerNonce)
564 static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
566 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
567 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
568 computeHash.Write(cookie.data(), cookie.size());
569 computeHash.Write(clientNonce.data(), clientNonce.size());
570 computeHash.Write(serverNonce.data(), serverNonce.size());
571 computeHash.Finalize(computedHash.data());
572 return computedHash;
575 void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
577 if (reply.code == 250) {
578 LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
579 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
580 if (l.first == "AUTHCHALLENGE") {
581 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
582 if (m.empty()) {
583 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
584 return;
586 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
587 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
588 LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
589 if (serverNonce.size() != 32) {
590 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
591 return;
594 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
595 if (computedServerHash != serverHash) {
596 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
597 return;
600 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
601 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
602 } else {
603 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
605 } else {
606 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
610 void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
612 if (reply.code == 250) {
613 std::set<std::string> methods;
614 std::string cookiefile;
616 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
617 * 250-AUTH METHODS=NULL
618 * 250-AUTH METHODS=HASHEDPASSWORD
620 for (const std::string &s : reply.lines) {
621 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
622 if (l.first == "AUTH") {
623 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
624 std::map<std::string,std::string>::iterator i;
625 if ((i = m.find("METHODS")) != m.end())
626 boost::split(methods, i->second, boost::is_any_of(","));
627 if ((i = m.find("COOKIEFILE")) != m.end())
628 cookiefile = i->second;
629 } else if (l.first == "VERSION") {
630 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
631 std::map<std::string,std::string>::iterator i;
632 if ((i = m.find("Tor")) != m.end()) {
633 LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
637 for (const std::string &s : methods) {
638 LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
640 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
641 /* Authentication:
642 * cookie: hex-encoded ~/.tor/control_auth_cookie
643 * password: "password"
645 std::string torpassword = gArgs.GetArg("-torpassword", "");
646 if (!torpassword.empty()) {
647 if (methods.count("HASHEDPASSWORD")) {
648 LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
649 boost::replace_all(torpassword, "\"", "\\\"");
650 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
651 } else {
652 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
654 } else if (methods.count("NULL")) {
655 LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
656 _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
657 } else if (methods.count("SAFECOOKIE")) {
658 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
659 LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
660 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
661 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
662 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
663 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
664 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
665 GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
666 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
667 } else {
668 if (status_cookie.first) {
669 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
670 } else {
671 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
674 } else if (methods.count("HASHEDPASSWORD")) {
675 LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
676 } else {
677 LogPrintf("tor: No supported authentication method\n");
679 } else {
680 LogPrintf("tor: Requesting protocol info failed\n");
684 void TorController::connected_cb(TorControlConnection& _conn)
686 reconnect_timeout = RECONNECT_TIMEOUT_START;
687 // First send a PROTOCOLINFO command to figure out what authentication is expected
688 if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
689 LogPrintf("tor: Error sending initial protocolinfo command\n");
692 void TorController::disconnected_cb(TorControlConnection& _conn)
694 // Stop advertising service when disconnected
695 if (service.IsValid())
696 RemoveLocal(service);
697 service = CService();
698 if (!reconnect)
699 return;
701 LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
703 // Single-shot timer for reconnect. Use exponential backoff.
704 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
705 if (reconnect_ev)
706 event_add(reconnect_ev, &time);
707 reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
710 void TorController::Reconnect()
712 /* Try to reconnect and reestablish if we get booted - for example, Tor
713 * may be restarting.
715 if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
716 boost::bind(&TorController::disconnected_cb, this, _1) )) {
717 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
721 fs::path TorController::GetPrivateKeyFile()
723 return GetDataDir() / "onion_private_key";
726 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
728 TorController *self = (TorController*)arg;
729 self->Reconnect();
732 /****** Thread ********/
733 static struct event_base *gBase;
734 static boost::thread torControlThread;
736 static void TorControlThread()
738 TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
740 event_base_dispatch(gBase);
743 void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
745 assert(!gBase);
746 #ifdef WIN32
747 evthread_use_windows_threads();
748 #else
749 evthread_use_pthreads();
750 #endif
751 gBase = event_base_new();
752 if (!gBase) {
753 LogPrintf("tor: Unable to create event_base\n");
754 return;
757 torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
760 void InterruptTorControl()
762 if (gBase) {
763 LogPrintf("tor: Thread interrupt\n");
764 event_base_loopbreak(gBase);
768 void StopTorControl()
770 if (gBase) {
771 torControlThread.join();
772 event_base_free(gBase);
773 gBase = nullptr;