Fix parameter naming inconsistencies between .h and .cpp files
[bitcoinplatinum.git] / src / torcontrol.cpp
blobd24020e51f5dd515be7ddccb6d5fcda6f91015bc
1 // Copyright (c) 2015-2016 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include "torcontrol.h"
6 #include "utilstrencodings.h"
7 #include "netbase.h"
8 #include "net.h"
9 #include "util.h"
10 #include "crypto/hmac_sha256.h"
12 #include <vector>
13 #include <deque>
14 #include <set>
15 #include <stdlib.h>
17 #include <boost/function.hpp>
18 #include <boost/bind.hpp>
19 #include <boost/signals2/signal.hpp>
20 #include <boost/foreach.hpp>
21 #include <boost/algorithm/string/predicate.hpp>
22 #include <boost/algorithm/string/split.hpp>
23 #include <boost/algorithm/string/classification.hpp>
24 #include <boost/algorithm/string/replace.hpp>
26 #include <event2/bufferevent.h>
27 #include <event2/buffer.h>
28 #include <event2/util.h>
29 #include <event2/event.h>
30 #include <event2/thread.h>
32 /** Default control port */
33 const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
34 /** Tor cookie size (from control-spec.txt) */
35 static const int TOR_COOKIE_SIZE = 32;
36 /** Size of client/server nonce for SAFECOOKIE */
37 static const int TOR_NONCE_SIZE = 32;
38 /** For computing serverHash in SAFECOOKIE */
39 static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
40 /** For computing clientHash in SAFECOOKIE */
41 static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
42 /** Exponential backoff configuration - initial timeout in seconds */
43 static const float RECONNECT_TIMEOUT_START = 1.0;
44 /** Exponential backoff configuration - growth factor */
45 static const float RECONNECT_TIMEOUT_EXP = 1.5;
46 /** Maximum length for lines received on TorControlConnection.
47 * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
48 * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
50 static const int MAX_LINE_LENGTH = 100000;
52 /****** Low-level TorControlConnection ********/
54 /** Reply from Tor, can be single or multi-line */
55 class TorControlReply
57 public:
58 TorControlReply() { Clear(); }
60 int code;
61 std::vector<std::string> lines;
63 void Clear()
65 code = 0;
66 lines.clear();
70 /** Low-level handling for Tor control connection.
71 * Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
73 class TorControlConnection
75 public:
76 typedef boost::function<void(TorControlConnection&)> ConnectionCB;
77 typedef boost::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
79 /** Create a new TorControlConnection.
81 TorControlConnection(struct event_base *base);
82 ~TorControlConnection();
84 /**
85 * Connect to a Tor control port.
86 * target is address of the form host:port.
87 * connected is the handler that is called when connection is successfully established.
88 * disconnected is a handler that is called when the connection is broken.
89 * Return true on success.
91 bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
93 /**
94 * Disconnect from Tor control port.
96 bool Disconnect();
98 /** Send a command, register a handler for the reply.
99 * A trailing CRLF is automatically added.
100 * Return true on success.
102 bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
104 /** Response handlers for async replies */
105 boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
106 private:
107 /** Callback when ready for use */
108 boost::function<void(TorControlConnection&)> connected;
109 /** Callback when connection lost */
110 boost::function<void(TorControlConnection&)> disconnected;
111 /** Libevent event base */
112 struct event_base *base;
113 /** Connection to control socket */
114 struct bufferevent *b_conn;
115 /** Message being received */
116 TorControlReply message;
117 /** Response handlers */
118 std::deque<ReplyHandlerCB> reply_handlers;
120 /** Libevent handlers: internal */
121 static void readcb(struct bufferevent *bev, void *ctx);
122 static void eventcb(struct bufferevent *bev, short what, void *ctx);
125 TorControlConnection::TorControlConnection(struct event_base *_base):
126 base(_base), b_conn(0)
130 TorControlConnection::~TorControlConnection()
132 if (b_conn)
133 bufferevent_free(b_conn);
136 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
138 TorControlConnection *self = (TorControlConnection*)ctx;
139 struct evbuffer *input = bufferevent_get_input(bev);
140 size_t n_read_out = 0;
141 char *line;
142 assert(input);
143 // If there is not a whole line to read, evbuffer_readln returns NULL
144 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL)
146 std::string s(line, n_read_out);
147 free(line);
148 if (s.size() < 4) // Short line
149 continue;
150 // <status>(-|+| )<data><CRLF>
151 self->message.code = atoi(s.substr(0,3));
152 self->message.lines.push_back(s.substr(4));
153 char ch = s[3]; // '-','+' or ' '
154 if (ch == ' ') {
155 // Final line, dispatch reply and clean up
156 if (self->message.code >= 600) {
157 // Dispatch async notifications to async handler
158 // Synchronous and asynchronous messages are never interleaved
159 self->async_handler(*self, self->message);
160 } else {
161 if (!self->reply_handlers.empty()) {
162 // Invoke reply handler with message
163 self->reply_handlers.front()(*self, self->message);
164 self->reply_handlers.pop_front();
165 } else {
166 LogPrint("tor", "tor: Received unexpected sync reply %i\n", self->message.code);
169 self->message.Clear();
172 // Check for size of buffer - protect against memory exhaustion with very long lines
173 // Do this after evbuffer_readln to make sure all full lines have been
174 // removed from the buffer. Everything left is an incomplete line.
175 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
176 LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
177 self->Disconnect();
181 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
183 TorControlConnection *self = (TorControlConnection*)ctx;
184 if (what & BEV_EVENT_CONNECTED) {
185 LogPrint("tor", "tor: Successfully connected!\n");
186 self->connected(*self);
187 } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
188 if (what & BEV_EVENT_ERROR)
189 LogPrint("tor", "tor: Error connecting to Tor control socket\n");
190 else
191 LogPrint("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=...'.
253 static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
255 size_t ptr=0;
256 std::string type;
257 while (ptr < s.size() && s[ptr] != ' ') {
258 type.push_back(s[ptr]);
259 ++ptr;
261 if (ptr < s.size())
262 ++ptr; // skip ' '
263 return make_pair(type, s.substr(ptr));
266 /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
268 static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
270 std::map<std::string,std::string> mapping;
271 size_t ptr=0;
272 while (ptr < s.size()) {
273 std::string key, value;
274 while (ptr < s.size() && s[ptr] != '=') {
275 key.push_back(s[ptr]);
276 ++ptr;
278 if (ptr == s.size()) // unexpected end of line
279 return std::map<std::string,std::string>();
280 ++ptr; // skip '='
281 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
282 ++ptr; // skip '='
283 bool escape_next = false;
284 while (ptr < s.size() && (!escape_next && s[ptr] != '"')) {
285 escape_next = (s[ptr] == '\\');
286 value.push_back(s[ptr]);
287 ++ptr;
289 if (ptr == s.size()) // unexpected end of line
290 return std::map<std::string,std::string>();
291 ++ptr; // skip closing '"'
292 /* TODO: unescape value - according to the spec this depends on the
293 * context, some strings use C-LogPrintf style escape codes, some
294 * don't. So may be better handled at the call site.
296 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
297 while (ptr < s.size() && s[ptr] != ' ') {
298 value.push_back(s[ptr]);
299 ++ptr;
302 if (ptr < s.size() && s[ptr] == ' ')
303 ++ptr; // skip ' ' after key=value
304 mapping[key] = value;
306 return mapping;
309 /** Read full contents of a file and return them in a std::string.
310 * Returns a pair <status, string>.
311 * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
313 * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
314 * (with len > maxsize) will be returned.
316 static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max())
318 FILE *f = fopen(filename.c_str(), "rb");
319 if (f == NULL)
320 return std::make_pair(false,"");
321 std::string retval;
322 char buffer[128];
323 size_t n;
324 while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
325 retval.append(buffer, buffer+n);
326 if (retval.size() > maxsize)
327 break;
329 fclose(f);
330 return std::make_pair(true,retval);
333 /** Write contents of std::string to a file.
334 * @return true on success.
336 static bool WriteBinaryFile(const std::string &filename, const std::string &data)
338 FILE *f = fopen(filename.c_str(), "wb");
339 if (f == NULL)
340 return false;
341 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
342 fclose(f);
343 return false;
345 fclose(f);
346 return true;
349 /****** Bitcoin specific TorController implementation ********/
351 /** Controller that connects to Tor control socket, authenticate, then create
352 * and maintain a ephemeral hidden service.
354 class TorController
356 public:
357 TorController(struct event_base* base, const std::string& target);
358 ~TorController();
360 /** Get name fo file to store private key in */
361 std::string GetPrivateKeyFile();
363 /** Reconnect, after getting disconnected */
364 void Reconnect();
365 private:
366 struct event_base* base;
367 std::string target;
368 TorControlConnection conn;
369 std::string private_key;
370 std::string service_id;
371 bool reconnect;
372 struct event *reconnect_ev;
373 float reconnect_timeout;
374 CService service;
375 /** Cookie for SAFECOOKIE auth */
376 std::vector<uint8_t> cookie;
377 /** ClientNonce for SAFECOOKIE auth */
378 std::vector<uint8_t> clientNonce;
380 /** Callback for ADD_ONION result */
381 void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
382 /** Callback for AUTHENTICATE result */
383 void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
384 /** Callback for AUTHCHALLENGE result */
385 void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
386 /** Callback for PROTOCOLINFO result */
387 void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
388 /** Callback after successful connection */
389 void connected_cb(TorControlConnection& conn);
390 /** Callback after connection lost or failed connection attempt */
391 void disconnected_cb(TorControlConnection& conn);
393 /** Callback for reconnect timer */
394 static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
397 TorController::TorController(struct event_base* _base, const std::string& _target):
398 base(_base),
399 target(_target), conn(base), reconnect(true), reconnect_ev(0),
400 reconnect_timeout(RECONNECT_TIMEOUT_START)
402 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
403 if (!reconnect_ev)
404 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
405 // Start connection attempts immediately
406 if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
407 boost::bind(&TorController::disconnected_cb, this, _1) )) {
408 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
410 // Read service private key if cached
411 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
412 if (pkf.first) {
413 LogPrint("tor", "tor: Reading cached private key from %s\n", GetPrivateKeyFile());
414 private_key = pkf.second;
418 TorController::~TorController()
420 if (reconnect_ev) {
421 event_free(reconnect_ev);
422 reconnect_ev = 0;
424 if (service.IsValid()) {
425 RemoveLocal(service);
429 void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
431 if (reply.code == 250) {
432 LogPrint("tor", "tor: ADD_ONION successful\n");
433 BOOST_FOREACH(const std::string &s, reply.lines) {
434 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
435 std::map<std::string,std::string>::iterator i;
436 if ((i = m.find("ServiceID")) != m.end())
437 service_id = i->second;
438 if ((i = m.find("PrivateKey")) != m.end())
439 private_key = i->second;
441 service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
442 LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
443 if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
444 LogPrint("tor", "tor: Cached service private key to %s\n", GetPrivateKeyFile());
445 } else {
446 LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile());
448 AddLocal(service, LOCAL_MANUAL);
449 // ... onion requested - keep connection open
450 } else if (reply.code == 510) { // 510 Unrecognized command
451 LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
452 } else {
453 LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
457 void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
459 if (reply.code == 250) {
460 LogPrint("tor", "tor: Authentication successful\n");
462 // Now that we know Tor is running setup the proxy for onion addresses
463 // if -onion isn't set to something else.
464 if (GetArg("-onion", "") == "") {
465 CService resolved(LookupNumeric("127.0.0.1", 9050));
466 proxyType addrOnion = proxyType(resolved, true);
467 SetProxy(NET_TOR, addrOnion);
468 SetLimited(NET_TOR, false);
471 // Finally - now create the service
472 if (private_key.empty()) // No private key, generate one
473 private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
474 // Request hidden service, redirect port.
475 // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
476 // choice. TODO; refactor the shutdown sequence some day.
477 _conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
478 boost::bind(&TorController::add_onion_cb, this, _1, _2));
479 } else {
480 LogPrintf("tor: Authentication failed\n");
484 /** Compute Tor SAFECOOKIE response.
486 * ServerHash is computed as:
487 * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
488 * CookieString | ClientNonce | ServerNonce)
489 * (with the HMAC key as its first argument)
491 * After a controller sends a successful AUTHCHALLENGE command, the
492 * next command sent on the connection must be an AUTHENTICATE command,
493 * and the only authentication string which that AUTHENTICATE command
494 * will accept is:
496 * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
497 * CookieString | ClientNonce | ServerNonce)
500 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)
502 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
503 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
504 computeHash.Write(cookie.data(), cookie.size());
505 computeHash.Write(clientNonce.data(), clientNonce.size());
506 computeHash.Write(serverNonce.data(), serverNonce.size());
507 computeHash.Finalize(computedHash.data());
508 return computedHash;
511 void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
513 if (reply.code == 250) {
514 LogPrint("tor", "tor: SAFECOOKIE authentication challenge successful\n");
515 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
516 if (l.first == "AUTHCHALLENGE") {
517 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
518 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
519 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
520 LogPrint("tor", "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
521 if (serverNonce.size() != 32) {
522 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
523 return;
526 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
527 if (computedServerHash != serverHash) {
528 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
529 return;
532 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
533 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
534 } else {
535 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
537 } else {
538 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
542 void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
544 if (reply.code == 250) {
545 std::set<std::string> methods;
546 std::string cookiefile;
548 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
549 * 250-AUTH METHODS=NULL
550 * 250-AUTH METHODS=HASHEDPASSWORD
552 BOOST_FOREACH(const std::string &s, reply.lines) {
553 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
554 if (l.first == "AUTH") {
555 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
556 std::map<std::string,std::string>::iterator i;
557 if ((i = m.find("METHODS")) != m.end())
558 boost::split(methods, i->second, boost::is_any_of(","));
559 if ((i = m.find("COOKIEFILE")) != m.end())
560 cookiefile = i->second;
561 } else if (l.first == "VERSION") {
562 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
563 std::map<std::string,std::string>::iterator i;
564 if ((i = m.find("Tor")) != m.end()) {
565 LogPrint("tor", "tor: Connected to Tor version %s\n", i->second);
569 BOOST_FOREACH(const std::string &s, methods) {
570 LogPrint("tor", "tor: Supported authentication method: %s\n", s);
572 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
573 /* Authentication:
574 * cookie: hex-encoded ~/.tor/control_auth_cookie
575 * password: "password"
577 std::string torpassword = GetArg("-torpassword", "");
578 if (!torpassword.empty()) {
579 if (methods.count("HASHEDPASSWORD")) {
580 LogPrint("tor", "tor: Using HASHEDPASSWORD authentication\n");
581 boost::replace_all(torpassword, "\"", "\\\"");
582 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
583 } else {
584 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
586 } else if (methods.count("NULL")) {
587 LogPrint("tor", "tor: Using NULL authentication\n");
588 _conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
589 } else if (methods.count("SAFECOOKIE")) {
590 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
591 LogPrint("tor", "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
592 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
593 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
594 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
595 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
596 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
597 GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
598 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
599 } else {
600 if (status_cookie.first) {
601 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
602 } else {
603 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
606 } else if (methods.count("HASHEDPASSWORD")) {
607 LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
608 } else {
609 LogPrintf("tor: No supported authentication method\n");
611 } else {
612 LogPrintf("tor: Requesting protocol info failed\n");
616 void TorController::connected_cb(TorControlConnection& _conn)
618 reconnect_timeout = RECONNECT_TIMEOUT_START;
619 // First send a PROTOCOLINFO command to figure out what authentication is expected
620 if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
621 LogPrintf("tor: Error sending initial protocolinfo command\n");
624 void TorController::disconnected_cb(TorControlConnection& _conn)
626 // Stop advertising service when disconnected
627 if (service.IsValid())
628 RemoveLocal(service);
629 service = CService();
630 if (!reconnect)
631 return;
633 LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
635 // Single-shot timer for reconnect. Use exponential backoff.
636 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
637 if (reconnect_ev)
638 event_add(reconnect_ev, &time);
639 reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
642 void TorController::Reconnect()
644 /* Try to reconnect and reestablish if we get booted - for example, Tor
645 * may be restarting.
647 if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
648 boost::bind(&TorController::disconnected_cb, this, _1) )) {
649 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
653 std::string TorController::GetPrivateKeyFile()
655 return (GetDataDir() / "onion_private_key").string();
658 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
660 TorController *self = (TorController*)arg;
661 self->Reconnect();
664 /****** Thread ********/
665 static struct event_base *gBase;
666 static boost::thread torControlThread;
668 static void TorControlThread()
670 TorController ctrl(gBase, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
672 event_base_dispatch(gBase);
675 void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
677 assert(!gBase);
678 #ifdef WIN32
679 evthread_use_windows_threads();
680 #else
681 evthread_use_pthreads();
682 #endif
683 gBase = event_base_new();
684 if (!gBase) {
685 LogPrintf("tor: Unable to create event_base\n");
686 return;
689 torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
692 void InterruptTorControl()
694 if (gBase) {
695 LogPrintf("tor: Thread interrupt\n");
696 event_base_loopbreak(gBase);
700 void StopTorControl()
702 if (gBase) {
703 torControlThread.join();
704 event_base_free(gBase);
705 gBase = 0;