Header include guideline
[bitcoinplatinum.git] / src / torcontrol.cpp
blobe3baa0556a0bcb0a1cb4187da5dc483bacc1a023
1 // Copyright (c) 2015-2016 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/foreach.hpp>
21 #include <boost/algorithm/string/split.hpp>
22 #include <boost/algorithm/string/classification.hpp>
23 #include <boost/algorithm/string/replace.hpp>
25 #include <event2/bufferevent.h>
26 #include <event2/buffer.h>
27 #include <event2/util.h>
28 #include <event2/event.h>
29 #include <event2/thread.h>
31 /** Default control port */
32 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
33 /** Tor cookie size (from control-spec.txt) */
34 static const int TOR_COOKIE_SIZE = 32;
35 /** Size of client/server nonce for SAFECOOKIE */
36 static const int TOR_NONCE_SIZE = 32;
37 /** For computing serverHash in SAFECOOKIE */
38 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
39 /** For computing clientHash in SAFECOOKIE */
40 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
41 /** Exponential backoff configuration - initial timeout in seconds */
42 static const float RECONNECT_TIMEOUT_START = 1.0;
43 /** Exponential backoff configuration - growth factor */
44 static const float RECONNECT_TIMEOUT_EXP = 1.5;
45 /** Maximum length for lines received on TorControlConnection.
46 * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
47 * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
49 static const int MAX_LINE_LENGTH = 100000;
51 /****** Low-level TorControlConnection ********/
53 /** Reply from Tor, can be single or multi-line */
54 class TorControlReply
56 public:
57 TorControlReply() { Clear(); }
59 int code;
60 std::vector<std::string> lines;
62 void Clear()
64 code = 0;
65 lines.clear();
69 /** Low-level handling for Tor control connection.
70 * Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
72 class TorControlConnection
74 public:
75 typedef std::function<void(TorControlConnection&)> ConnectionCB;
76 typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
78 /** Create a new TorControlConnection.
80 TorControlConnection(struct event_base *base);
81 ~TorControlConnection();
83 /**
84 * Connect to a Tor control port.
85 * target is address of the form host:port.
86 * connected is the handler that is called when connection is successfully established.
87 * disconnected is a handler that is called when the connection is broken.
88 * Return true on success.
90 bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
92 /**
93 * Disconnect from Tor control port.
95 bool Disconnect();
97 /** Send a command, register a handler for the reply.
98 * A trailing CRLF is automatically added.
99 * Return true on success.
101 bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
103 /** Response handlers for async replies */
104 boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
105 private:
106 /** Callback when ready for use */
107 std::function<void(TorControlConnection&)> connected;
108 /** Callback when connection lost */
109 std::function<void(TorControlConnection&)> disconnected;
110 /** Libevent event base */
111 struct event_base *base;
112 /** Connection to control socket */
113 struct bufferevent *b_conn;
114 /** Message being received */
115 TorControlReply message;
116 /** Response handlers */
117 std::deque<ReplyHandlerCB> reply_handlers;
119 /** Libevent handlers: internal */
120 static void readcb(struct bufferevent *bev, void *ctx);
121 static void eventcb(struct bufferevent *bev, short what, void *ctx);
124 TorControlConnection::TorControlConnection(struct event_base *_base):
125 base(_base), b_conn(0)
129 TorControlConnection::~TorControlConnection()
131 if (b_conn)
132 bufferevent_free(b_conn);
135 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
137 TorControlConnection *self = (TorControlConnection*)ctx;
138 struct evbuffer *input = bufferevent_get_input(bev);
139 size_t n_read_out = 0;
140 char *line;
141 assert(input);
142 // If there is not a whole line to read, evbuffer_readln returns NULL
143 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL)
145 std::string s(line, n_read_out);
146 free(line);
147 if (s.size() < 4) // Short line
148 continue;
149 // <status>(-|+| )<data><CRLF>
150 self->message.code = atoi(s.substr(0,3));
151 self->message.lines.push_back(s.substr(4));
152 char ch = s[3]; // '-','+' or ' '
153 if (ch == ' ') {
154 // Final line, dispatch reply and clean up
155 if (self->message.code >= 600) {
156 // Dispatch async notifications to async handler
157 // Synchronous and asynchronous messages are never interleaved
158 self->async_handler(*self, self->message);
159 } else {
160 if (!self->reply_handlers.empty()) {
161 // Invoke reply handler with message
162 self->reply_handlers.front()(*self, self->message);
163 self->reply_handlers.pop_front();
164 } else {
165 LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
168 self->message.Clear();
171 // Check for size of buffer - protect against memory exhaustion with very long lines
172 // Do this after evbuffer_readln to make sure all full lines have been
173 // removed from the buffer. Everything left is an incomplete line.
174 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
175 LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
176 self->Disconnect();
180 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
182 TorControlConnection *self = (TorControlConnection*)ctx;
183 if (what & BEV_EVENT_CONNECTED) {
184 LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
185 self->connected(*self);
186 } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
187 if (what & BEV_EVENT_ERROR) {
188 LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
189 } else {
190 LogPrint(BCLog::TOR, "tor: End of stream\n");
192 self->Disconnect();
193 self->disconnected(*self);
197 bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
199 if (b_conn)
200 Disconnect();
201 // Parse target address:port
202 struct sockaddr_storage connect_to_addr;
203 int connect_to_addrlen = sizeof(connect_to_addr);
204 if (evutil_parse_sockaddr_port(target.c_str(),
205 (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
206 LogPrintf("tor: Error parsing socket address %s\n", target);
207 return false;
210 // Create a new socket, set up callbacks and enable notification bits
211 b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
212 if (!b_conn)
213 return false;
214 bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this);
215 bufferevent_enable(b_conn, EV_READ|EV_WRITE);
216 this->connected = _connected;
217 this->disconnected = _disconnected;
219 // Finally, connect to target
220 if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
221 LogPrintf("tor: Error connecting to address %s\n", target);
222 return false;
224 return true;
227 bool TorControlConnection::Disconnect()
229 if (b_conn)
230 bufferevent_free(b_conn);
231 b_conn = 0;
232 return true;
235 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
237 if (!b_conn)
238 return false;
239 struct evbuffer *buf = bufferevent_get_output(b_conn);
240 if (!buf)
241 return false;
242 evbuffer_add(buf, cmd.data(), cmd.size());
243 evbuffer_add(buf, "\r\n", 2);
244 reply_handlers.push_back(reply_handler);
245 return true;
248 /****** General parsing utilities ********/
250 /* Split reply line in the form 'AUTH METHODS=...' into a type
251 * 'AUTH' and arguments 'METHODS=...'.
252 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
253 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
255 static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
257 size_t ptr=0;
258 std::string type;
259 while (ptr < s.size() && s[ptr] != ' ') {
260 type.push_back(s[ptr]);
261 ++ptr;
263 if (ptr < s.size())
264 ++ptr; // skip ' '
265 return make_pair(type, s.substr(ptr));
268 /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
269 * Returns a map of keys to values, or an empty map if there was an error.
270 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
271 * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
272 * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
274 static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
276 std::map<std::string,std::string> mapping;
277 size_t ptr=0;
278 while (ptr < s.size()) {
279 std::string key, value;
280 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
281 key.push_back(s[ptr]);
282 ++ptr;
284 if (ptr == s.size()) // unexpected end of line
285 return std::map<std::string,std::string>();
286 if (s[ptr] == ' ') // The remaining string is an OptArguments
287 break;
288 ++ptr; // skip '='
289 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
290 ++ptr; // skip opening '"'
291 bool escape_next = false;
292 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
293 // Repeated backslashes must be interpreted as pairs
294 escape_next = (s[ptr] == '\\' && !escape_next);
295 value.push_back(s[ptr]);
296 ++ptr;
298 if (ptr == s.size()) // unexpected end of line
299 return std::map<std::string,std::string>();
300 ++ptr; // skip closing '"'
302 * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
304 * For future-proofing, controller implementors MAY use the following
305 * rules to be compatible with buggy Tor implementations and with
306 * future ones that implement the spec as intended:
308 * Read \n \t \r and \0 ... \377 as C escapes.
309 * Treat a backslash followed by any other character as that character.
311 std::string escaped_value;
312 for (size_t i = 0; i < value.size(); ++i) {
313 if (value[i] == '\\') {
314 // This will always be valid, because if the QuotedString
315 // ended in an odd number of backslashes, then the parser
316 // would already have returned above, due to a missing
317 // terminating double-quote.
318 ++i;
319 if (value[i] == 'n') {
320 escaped_value.push_back('\n');
321 } else if (value[i] == 't') {
322 escaped_value.push_back('\t');
323 } else if (value[i] == 'r') {
324 escaped_value.push_back('\r');
325 } else if ('0' <= value[i] && value[i] <= '7') {
326 size_t j;
327 // Octal escape sequences have a limit of three octal digits,
328 // but terminate at the first character that is not a valid
329 // octal digit if encountered sooner.
330 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
331 // Tor restricts first digit to 0-3 for three-digit octals.
332 // A leading digit of 4-7 would therefore be interpreted as
333 // a two-digit octal.
334 if (j == 3 && value[i] > '3') {
335 j--;
337 escaped_value.push_back(strtol(value.substr(i, j).c_str(), NULL, 8));
338 // Account for automatic incrementing at loop end
339 i += j - 1;
340 } else {
341 escaped_value.push_back(value[i]);
343 } else {
344 escaped_value.push_back(value[i]);
347 value = escaped_value;
348 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
349 while (ptr < s.size() && s[ptr] != ' ') {
350 value.push_back(s[ptr]);
351 ++ptr;
354 if (ptr < s.size() && s[ptr] == ' ')
355 ++ptr; // skip ' ' after key=value
356 mapping[key] = value;
358 return mapping;
361 /** Read full contents of a file and return them in a std::string.
362 * Returns a pair <status, string>.
363 * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
365 * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
366 * (with len > maxsize) will be returned.
368 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
370 FILE *f = fsbridge::fopen(filename, "rb");
371 if (f == NULL)
372 return std::make_pair(false,"");
373 std::string retval;
374 char buffer[128];
375 size_t n;
376 while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
377 // Check for reading errors so we don't return any data if we couldn't
378 // read the entire file (or up to maxsize)
379 if (ferror(f))
380 return std::make_pair(false,"");
381 retval.append(buffer, buffer+n);
382 if (retval.size() > maxsize)
383 break;
385 fclose(f);
386 return std::make_pair(true,retval);
389 /** Write contents of std::string to a file.
390 * @return true on success.
392 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
394 FILE *f = fsbridge::fopen(filename, "wb");
395 if (f == NULL)
396 return false;
397 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
398 fclose(f);
399 return false;
401 fclose(f);
402 return true;
405 /****** Bitcoin specific TorController implementation ********/
407 /** Controller that connects to Tor control socket, authenticate, then create
408 * and maintain a ephemeral hidden service.
410 class TorController
412 public:
413 TorController(struct event_base* base, const std::string& target);
414 ~TorController();
416 /** Get name fo file to store private key in */
417 fs::path GetPrivateKeyFile();
419 /** Reconnect, after getting disconnected */
420 void Reconnect();
421 private:
422 struct event_base* base;
423 std::string target;
424 TorControlConnection conn;
425 std::string private_key;
426 std::string service_id;
427 bool reconnect;
428 struct event *reconnect_ev;
429 float reconnect_timeout;
430 CService service;
431 /** Cookie for SAFECOOKIE auth */
432 std::vector<uint8_t> cookie;
433 /** ClientNonce for SAFECOOKIE auth */
434 std::vector<uint8_t> clientNonce;
436 /** Callback for ADD_ONION result */
437 void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
438 /** Callback for AUTHENTICATE result */
439 void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
440 /** Callback for AUTHCHALLENGE result */
441 void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
442 /** Callback for PROTOCOLINFO result */
443 void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
444 /** Callback after successful connection */
445 void connected_cb(TorControlConnection& conn);
446 /** Callback after connection lost or failed connection attempt */
447 void disconnected_cb(TorControlConnection& conn);
449 /** Callback for reconnect timer */
450 static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
453 TorController::TorController(struct event_base* _base, const std::string& _target):
454 base(_base),
455 target(_target), conn(base), reconnect(true), reconnect_ev(0),
456 reconnect_timeout(RECONNECT_TIMEOUT_START)
458 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
459 if (!reconnect_ev)
460 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
461 // Start connection attempts immediately
462 if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
463 boost::bind(&TorController::disconnected_cb, this, _1) )) {
464 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
466 // Read service private key if cached
467 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
468 if (pkf.first) {
469 LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
470 private_key = pkf.second;
474 TorController::~TorController()
476 if (reconnect_ev) {
477 event_free(reconnect_ev);
478 reconnect_ev = 0;
480 if (service.IsValid()) {
481 RemoveLocal(service);
485 void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
487 if (reply.code == 250) {
488 LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
489 BOOST_FOREACH(const std::string &s, reply.lines) {
490 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
491 std::map<std::string,std::string>::iterator i;
492 if ((i = m.find("ServiceID")) != m.end())
493 service_id = i->second;
494 if ((i = m.find("PrivateKey")) != m.end())
495 private_key = i->second;
497 if (service_id.empty()) {
498 LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
499 for (const std::string &s : reply.lines) {
500 LogPrintf(" %s\n", SanitizeString(s));
502 return;
504 service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
505 LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
506 if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
507 LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
508 } else {
509 LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
511 AddLocal(service, LOCAL_MANUAL);
512 // ... onion requested - keep connection open
513 } else if (reply.code == 510) { // 510 Unrecognized command
514 LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
515 } else {
516 LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
520 void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
522 if (reply.code == 250) {
523 LogPrint(BCLog::TOR, "tor: Authentication successful\n");
525 // Now that we know Tor is running setup the proxy for onion addresses
526 // if -onion isn't set to something else.
527 if (GetArg("-onion", "") == "") {
528 CService resolved(LookupNumeric("127.0.0.1", 9050));
529 proxyType addrOnion = proxyType(resolved, true);
530 SetProxy(NET_TOR, addrOnion);
531 SetLimited(NET_TOR, false);
534 // Finally - now create the service
535 if (private_key.empty()) // No private key, generate one
536 private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
537 // Request hidden service, redirect port.
538 // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
539 // choice. TODO; refactor the shutdown sequence some day.
540 _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
541 boost::bind(&TorController::add_onion_cb, this, _1, _2));
542 } else {
543 LogPrintf("tor: Authentication failed\n");
547 /** Compute Tor SAFECOOKIE response.
549 * ServerHash is computed as:
550 * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
551 * CookieString | ClientNonce | ServerNonce)
552 * (with the HMAC key as its first argument)
554 * After a controller sends a successful AUTHCHALLENGE command, the
555 * next command sent on the connection must be an AUTHENTICATE command,
556 * and the only authentication string which that AUTHENTICATE command
557 * will accept is:
559 * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
560 * CookieString | ClientNonce | ServerNonce)
563 static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
565 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
566 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
567 computeHash.Write(cookie.data(), cookie.size());
568 computeHash.Write(clientNonce.data(), clientNonce.size());
569 computeHash.Write(serverNonce.data(), serverNonce.size());
570 computeHash.Finalize(computedHash.data());
571 return computedHash;
574 void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
576 if (reply.code == 250) {
577 LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
578 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
579 if (l.first == "AUTHCHALLENGE") {
580 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
581 if (m.empty()) {
582 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
583 return;
585 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
586 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
587 LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
588 if (serverNonce.size() != 32) {
589 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
590 return;
593 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
594 if (computedServerHash != serverHash) {
595 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
596 return;
599 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
600 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
601 } else {
602 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
604 } else {
605 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
609 void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
611 if (reply.code == 250) {
612 std::set<std::string> methods;
613 std::string cookiefile;
615 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
616 * 250-AUTH METHODS=NULL
617 * 250-AUTH METHODS=HASHEDPASSWORD
619 BOOST_FOREACH(const std::string &s, reply.lines) {
620 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
621 if (l.first == "AUTH") {
622 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
623 std::map<std::string,std::string>::iterator i;
624 if ((i = m.find("METHODS")) != m.end())
625 boost::split(methods, i->second, boost::is_any_of(","));
626 if ((i = m.find("COOKIEFILE")) != m.end())
627 cookiefile = i->second;
628 } else if (l.first == "VERSION") {
629 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
630 std::map<std::string,std::string>::iterator i;
631 if ((i = m.find("Tor")) != m.end()) {
632 LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
636 BOOST_FOREACH(const std::string &s, methods) {
637 LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
639 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
640 /* Authentication:
641 * cookie: hex-encoded ~/.tor/control_auth_cookie
642 * password: "password"
644 std::string torpassword = GetArg("-torpassword", "");
645 if (!torpassword.empty()) {
646 if (methods.count("HASHEDPASSWORD")) {
647 LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
648 boost::replace_all(torpassword, "\"", "\\\"");
649 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
650 } else {
651 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
653 } else if (methods.count("NULL")) {
654 LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
655 _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
656 } else if (methods.count("SAFECOOKIE")) {
657 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
658 LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
659 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
660 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
661 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
662 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
663 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
664 GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
665 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
666 } else {
667 if (status_cookie.first) {
668 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
669 } else {
670 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
673 } else if (methods.count("HASHEDPASSWORD")) {
674 LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
675 } else {
676 LogPrintf("tor: No supported authentication method\n");
678 } else {
679 LogPrintf("tor: Requesting protocol info failed\n");
683 void TorController::connected_cb(TorControlConnection& _conn)
685 reconnect_timeout = RECONNECT_TIMEOUT_START;
686 // First send a PROTOCOLINFO command to figure out what authentication is expected
687 if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
688 LogPrintf("tor: Error sending initial protocolinfo command\n");
691 void TorController::disconnected_cb(TorControlConnection& _conn)
693 // Stop advertising service when disconnected
694 if (service.IsValid())
695 RemoveLocal(service);
696 service = CService();
697 if (!reconnect)
698 return;
700 LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
702 // Single-shot timer for reconnect. Use exponential backoff.
703 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
704 if (reconnect_ev)
705 event_add(reconnect_ev, &time);
706 reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
709 void TorController::Reconnect()
711 /* Try to reconnect and reestablish if we get booted - for example, Tor
712 * may be restarting.
714 if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
715 boost::bind(&TorController::disconnected_cb, this, _1) )) {
716 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
720 fs::path TorController::GetPrivateKeyFile()
722 return GetDataDir() / "onion_private_key";
725 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
727 TorController *self = (TorController*)arg;
728 self->Reconnect();
731 /****** Thread ********/
732 static struct event_base *gBase;
733 static boost::thread torControlThread;
735 static void TorControlThread()
737 TorController ctrl(gBase, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
739 event_base_dispatch(gBase);
742 void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
744 assert(!gBase);
745 #ifdef WIN32
746 evthread_use_windows_threads();
747 #else
748 evthread_use_pthreads();
749 #endif
750 gBase = event_base_new();
751 if (!gBase) {
752 LogPrintf("tor: Unable to create event_base\n");
753 return;
756 torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
759 void InterruptTorControl()
761 if (gBase) {
762 LogPrintf("tor: Thread interrupt\n");
763 event_base_loopbreak(gBase);
767 void StopTorControl()
769 if (gBase) {
770 torControlThread.join();
771 event_base_free(gBase);
772 gBase = 0;