Merge #8006: Qt: Add option to disable the system tray icon
[bitcoinplatinum.git] / src / torcontrol.cpp
blob47d834c7b4eff0203b577a64eb2de84f4b371d99
1 // Copyright (c) 2015 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 "net.h"
8 #include "util.h"
9 #include "crypto/hmac_sha256.h"
11 #include <vector>
12 #include <deque>
13 #include <set>
14 #include <stdlib.h>
16 #include <boost/function.hpp>
17 #include <boost/bind.hpp>
18 #include <boost/signals2/signal.hpp>
19 #include <boost/foreach.hpp>
20 #include <boost/algorithm/string/predicate.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 boost::function<void(TorControlConnection&)> ConnectionCB;
76 typedef boost::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 boost::function<void(TorControlConnection&)> connected;
108 /** Callback when connection lost */
109 boost::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("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("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("tor", "tor: Error connecting to Tor control socket\n");
189 else
190 LogPrint("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, NULL, 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 = 0;
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=...'.
252 static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
254 size_t ptr=0;
255 std::string type;
256 while (ptr < s.size() && s[ptr] != ' ') {
257 type.push_back(s[ptr]);
258 ++ptr;
260 if (ptr < s.size())
261 ++ptr; // skip ' '
262 return make_pair(type, s.substr(ptr));
265 /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
267 static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
269 std::map<std::string,std::string> mapping;
270 size_t ptr=0;
271 while (ptr < s.size()) {
272 std::string key, value;
273 while (ptr < s.size() && s[ptr] != '=') {
274 key.push_back(s[ptr]);
275 ++ptr;
277 if (ptr == s.size()) // unexpected end of line
278 return std::map<std::string,std::string>();
279 ++ptr; // skip '='
280 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
281 ++ptr; // skip '='
282 bool escape_next = false;
283 while (ptr < s.size() && (!escape_next && s[ptr] != '"')) {
284 escape_next = (s[ptr] == '\\');
285 value.push_back(s[ptr]);
286 ++ptr;
288 if (ptr == s.size()) // unexpected end of line
289 return std::map<std::string,std::string>();
290 ++ptr; // skip closing '"'
291 /* TODO: unescape value - according to the spec this depends on the
292 * context, some strings use C-LogPrintf style escape codes, some
293 * don't. So may be better handled at the call site.
295 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
296 while (ptr < s.size() && s[ptr] != ' ') {
297 value.push_back(s[ptr]);
298 ++ptr;
301 if (ptr < s.size() && s[ptr] == ' ')
302 ++ptr; // skip ' ' after key=value
303 mapping[key] = value;
305 return mapping;
308 /** Read full contents of a file and return them in a std::string.
309 * Returns a pair <status, string>.
310 * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
312 * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
313 * (with len > maxsize) will be returned.
315 static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max())
317 FILE *f = fopen(filename.c_str(), "rb");
318 if (f == NULL)
319 return std::make_pair(false,"");
320 std::string retval;
321 char buffer[128];
322 size_t n;
323 while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
324 retval.append(buffer, buffer+n);
325 if (retval.size() > maxsize)
326 break;
328 fclose(f);
329 return std::make_pair(true,retval);
332 /** Write contents of std::string to a file.
333 * @return true on success.
335 static bool WriteBinaryFile(const std::string &filename, const std::string &data)
337 FILE *f = fopen(filename.c_str(), "wb");
338 if (f == NULL)
339 return false;
340 if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
341 fclose(f);
342 return false;
344 fclose(f);
345 return true;
348 /****** Bitcoin specific TorController implementation ********/
350 /** Controller that connects to Tor control socket, authenticate, then create
351 * and maintain a ephemeral hidden service.
353 class TorController
355 public:
356 TorController(struct event_base* base, const std::string& target);
357 ~TorController();
359 /** Get name fo file to store private key in */
360 std::string GetPrivateKeyFile();
362 /** Reconnect, after getting disconnected */
363 void Reconnect();
364 private:
365 struct event_base* base;
366 std::string target;
367 TorControlConnection conn;
368 std::string private_key;
369 std::string service_id;
370 bool reconnect;
371 struct event *reconnect_ev;
372 float reconnect_timeout;
373 CService service;
374 /** Cooie for SAFECOOKIE auth */
375 std::vector<uint8_t> cookie;
376 /** ClientNonce for SAFECOOKIE auth */
377 std::vector<uint8_t> clientNonce;
379 /** Callback for ADD_ONION result */
380 void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
381 /** Callback for AUTHENTICATE result */
382 void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
383 /** Callback for AUTHCHALLENGE result */
384 void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
385 /** Callback for PROTOCOLINFO result */
386 void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
387 /** Callback after successful connection */
388 void connected_cb(TorControlConnection& conn);
389 /** Callback after connection lost or failed connection attempt */
390 void disconnected_cb(TorControlConnection& conn);
392 /** Callback for reconnect timer */
393 static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
396 TorController::TorController(struct event_base* baseIn, const std::string& target):
397 base(baseIn),
398 target(target), conn(base), reconnect(true), reconnect_ev(0),
399 reconnect_timeout(RECONNECT_TIMEOUT_START)
401 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
402 if (!reconnect_ev)
403 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
404 // Start connection attempts immediately
405 if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
406 boost::bind(&TorController::disconnected_cb, this, _1) )) {
407 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", target);
409 // Read service private key if cached
410 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
411 if (pkf.first) {
412 LogPrint("tor", "tor: Reading cached private key from %s\n", GetPrivateKeyFile());
413 private_key = pkf.second;
417 TorController::~TorController()
419 if (reconnect_ev) {
420 event_free(reconnect_ev);
421 reconnect_ev = 0;
423 if (service.IsValid()) {
424 RemoveLocal(service);
428 void TorController::add_onion_cb(TorControlConnection& conn, const TorControlReply& reply)
430 if (reply.code == 250) {
431 LogPrint("tor", "tor: ADD_ONION successful\n");
432 BOOST_FOREACH(const std::string &s, reply.lines) {
433 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
434 std::map<std::string,std::string>::iterator i;
435 if ((i = m.find("ServiceID")) != m.end())
436 service_id = i->second;
437 if ((i = m.find("PrivateKey")) != m.end())
438 private_key = i->second;
441 service = CService(service_id+".onion", 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 proxyType addrOnion = proxyType(CService("127.0.0.1", 9050), true);
466 SetProxy(NET_TOR, addrOnion);
467 SetLimited(NET_TOR, false);
470 // Finally - now create the service
471 if (private_key.empty()) // No private key, generate one
472 private_key = "NEW:BEST";
473 // Request hidden service, redirect port.
474 // Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
475 // choice. TODO; refactor the shutdown sequence some day.
476 conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
477 boost::bind(&TorController::add_onion_cb, this, _1, _2));
478 } else {
479 LogPrintf("tor: Authentication failed\n");
483 /** Compute Tor SAFECOOKIE response.
485 * ServerHash is computed as:
486 * HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
487 * CookieString | ClientNonce | ServerNonce)
488 * (with the HMAC key as its first argument)
490 * After a controller sends a successful AUTHCHALLENGE command, the
491 * next command sent on the connection must be an AUTHENTICATE command,
492 * and the only authentication string which that AUTHENTICATE command
493 * will accept is:
495 * HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
496 * CookieString | ClientNonce | ServerNonce)
499 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)
501 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
502 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
503 computeHash.Write(begin_ptr(cookie), cookie.size());
504 computeHash.Write(begin_ptr(clientNonce), clientNonce.size());
505 computeHash.Write(begin_ptr(serverNonce), serverNonce.size());
506 computeHash.Finalize(begin_ptr(computedHash));
507 return computedHash;
510 void TorController::authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply)
512 if (reply.code == 250) {
513 LogPrint("tor", "tor: SAFECOOKIE authentication challenge successful\n");
514 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
515 if (l.first == "AUTHCHALLENGE") {
516 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
517 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
518 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
519 LogPrint("tor", "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
520 if (serverNonce.size() != 32) {
521 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
522 return;
525 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
526 if (computedServerHash != serverHash) {
527 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
528 return;
531 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
532 conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
533 } else {
534 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
536 } else {
537 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
541 void TorController::protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply)
543 if (reply.code == 250) {
544 std::set<std::string> methods;
545 std::string cookiefile;
547 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
548 * 250-AUTH METHODS=NULL
549 * 250-AUTH METHODS=HASHEDPASSWORD
551 BOOST_FOREACH(const std::string &s, reply.lines) {
552 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
553 if (l.first == "AUTH") {
554 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
555 std::map<std::string,std::string>::iterator i;
556 if ((i = m.find("METHODS")) != m.end())
557 boost::split(methods, i->second, boost::is_any_of(","));
558 if ((i = m.find("COOKIEFILE")) != m.end())
559 cookiefile = i->second;
560 } else if (l.first == "VERSION") {
561 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
562 std::map<std::string,std::string>::iterator i;
563 if ((i = m.find("Tor")) != m.end()) {
564 LogPrint("tor", "tor: Connected to Tor version %s\n", i->second);
568 BOOST_FOREACH(const std::string &s, methods) {
569 LogPrint("tor", "tor: Supported authentication method: %s\n", s);
571 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
572 /* Authentication:
573 * cookie: hex-encoded ~/.tor/control_auth_cookie
574 * password: "password"
576 std::string torpassword = GetArg("-torpassword", "");
577 if (methods.count("NULL")) {
578 LogPrint("tor", "tor: Using NULL authentication\n");
579 conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
580 } else if (methods.count("SAFECOOKIE")) {
581 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
582 LogPrint("tor", "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
583 std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
584 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
585 // conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
586 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
587 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
588 GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
589 conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
590 } else {
591 if (status_cookie.first) {
592 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
593 } else {
594 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
597 } else if (methods.count("HASHEDPASSWORD")) {
598 if (!torpassword.empty()) {
599 LogPrint("tor", "tor: Using HASHEDPASSWORD authentication\n");
600 boost::replace_all(torpassword, "\"", "\\\"");
601 conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
602 } else {
603 LogPrintf("tor: Password authentication required, but no password provided with -torpassword\n");
605 } else {
606 LogPrintf("tor: No supported authentication method\n");
608 } else {
609 LogPrintf("tor: Requesting protocol info failed\n");
613 void TorController::connected_cb(TorControlConnection& conn)
615 reconnect_timeout = RECONNECT_TIMEOUT_START;
616 // First send a PROTOCOLINFO command to figure out what authentication is expected
617 if (!conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
618 LogPrintf("tor: Error sending initial protocolinfo command\n");
621 void TorController::disconnected_cb(TorControlConnection& conn)
623 // Stop advertising service when disconnected
624 if (service.IsValid())
625 RemoveLocal(service);
626 service = CService();
627 if (!reconnect)
628 return;
630 LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
632 // Single-shot timer for reconnect. Use exponential backoff.
633 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
634 if (reconnect_ev)
635 event_add(reconnect_ev, &time);
636 reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
639 void TorController::Reconnect()
641 /* Try to reconnect and reestablish if we get booted - for example, Tor
642 * may be restarting.
644 if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
645 boost::bind(&TorController::disconnected_cb, this, _1) )) {
646 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
650 std::string TorController::GetPrivateKeyFile()
652 return (GetDataDir() / "onion_private_key").string();
655 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
657 TorController *self = (TorController*)arg;
658 self->Reconnect();
661 /****** Thread ********/
662 struct event_base *base;
663 boost::thread torControlThread;
665 static void TorControlThread()
667 TorController ctrl(base, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
669 event_base_dispatch(base);
672 void StartTorControl(boost::thread_group& threadGroup, CScheduler& scheduler)
674 assert(!base);
675 #ifdef WIN32
676 evthread_use_windows_threads();
677 #else
678 evthread_use_pthreads();
679 #endif
680 base = event_base_new();
681 if (!base) {
682 LogPrintf("tor: Unable to create event_base\n");
683 return;
686 torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
689 void InterruptTorControl()
691 if (base) {
692 LogPrintf("tor: Thread interrupt\n");
693 event_base_loopbreak(base);
697 void StopTorControl()
699 if (base) {
700 torControlThread.join();
701 event_base_free(base);
702 base = 0;