LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 91 471 19.3 %
Date: 2022-04-21 14:51:19 Functions: 5 30 16.7 %
Legend: Modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed

Not modified by patch:
Lines: hit not hit | Branches: + taken - not taken # not executed
Branches: 69 270 25.6 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2015-2021 The Bitcoin Core developers
#       2                 :            : // Copyright (c) 2017 The Zcash developers
#       3                 :            : // Distributed under the MIT software license, see the accompanying
#       4                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
#       5                 :            : 
#       6                 :            : #include <torcontrol.h>
#       7                 :            : 
#       8                 :            : #include <chainparams.h>
#       9                 :            : #include <chainparamsbase.h>
#      10                 :            : #include <compat.h>
#      11                 :            : #include <crypto/hmac_sha256.h>
#      12                 :            : #include <net.h>
#      13                 :            : #include <netaddress.h>
#      14                 :            : #include <netbase.h>
#      15                 :            : #include <util/readwritefile.h>
#      16                 :            : #include <util/strencodings.h>
#      17                 :            : #include <util/syscall_sandbox.h>
#      18                 :            : #include <util/system.h>
#      19                 :            : #include <util/thread.h>
#      20                 :            : #include <util/time.h>
#      21                 :            : 
#      22                 :            : #include <deque>
#      23                 :            : #include <functional>
#      24                 :            : #include <set>
#      25                 :            : #include <vector>
#      26                 :            : 
#      27                 :            : #include <boost/algorithm/string/classification.hpp>
#      28                 :            : #include <boost/algorithm/string/replace.hpp>
#      29                 :            : #include <boost/algorithm/string/split.hpp>
#      30                 :            : 
#      31                 :            : #include <event2/buffer.h>
#      32                 :            : #include <event2/bufferevent.h>
#      33                 :            : #include <event2/event.h>
#      34                 :            : #include <event2/thread.h>
#      35                 :            : #include <event2/util.h>
#      36                 :            : 
#      37                 :            : /** Default control port */
#      38                 :            : const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
#      39                 :            : /** Tor cookie size (from control-spec.txt) */
#      40                 :            : static const int TOR_COOKIE_SIZE = 32;
#      41                 :            : /** Size of client/server nonce for SAFECOOKIE */
#      42                 :            : static const int TOR_NONCE_SIZE = 32;
#      43                 :            : /** For computing serverHash in SAFECOOKIE */
#      44                 :            : static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
#      45                 :            : /** For computing clientHash in SAFECOOKIE */
#      46                 :            : static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
#      47                 :            : /** Exponential backoff configuration - initial timeout in seconds */
#      48                 :            : static const float RECONNECT_TIMEOUT_START = 1.0;
#      49                 :            : /** Exponential backoff configuration - growth factor */
#      50                 :            : static const float RECONNECT_TIMEOUT_EXP = 1.5;
#      51                 :            : /** Maximum length for lines received on TorControlConnection.
#      52                 :            :  * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
#      53                 :            :  * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
#      54                 :            :  */
#      55                 :            : static const int MAX_LINE_LENGTH = 100000;
#      56                 :            : static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050;
#      57                 :            : 
#      58                 :            : /****** Low-level TorControlConnection ********/
#      59                 :            : 
#      60                 :            : TorControlConnection::TorControlConnection(struct event_base *_base):
#      61                 :            :     base(_base), b_conn(nullptr)
#      62                 :          0 : {
#      63                 :          0 : }
#      64                 :            : 
#      65                 :            : TorControlConnection::~TorControlConnection()
#      66                 :          0 : {
#      67         [ #  # ]:          0 :     if (b_conn)
#      68                 :          0 :         bufferevent_free(b_conn);
#      69                 :          0 : }
#      70                 :            : 
#      71                 :            : void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
#      72                 :          0 : {
#      73                 :          0 :     TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
#      74                 :          0 :     struct evbuffer *input = bufferevent_get_input(bev);
#      75                 :          0 :     size_t n_read_out = 0;
#      76                 :          0 :     char *line;
#      77                 :          0 :     assert(input);
#      78                 :            :     //  If there is not a whole line to read, evbuffer_readln returns nullptr
#      79         [ #  # ]:          0 :     while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
#      80                 :          0 :     {
#      81                 :          0 :         std::string s(line, n_read_out);
#      82                 :          0 :         free(line);
#      83         [ #  # ]:          0 :         if (s.size() < 4) // Short line
#      84                 :          0 :             continue;
#      85                 :            :         // <status>(-|+| )<data><CRLF>
#      86                 :          0 :         self->message.code = LocaleIndependentAtoi<int>(s.substr(0,3));
#      87                 :          0 :         self->message.lines.push_back(s.substr(4));
#      88                 :          0 :         char ch = s[3]; // '-','+' or ' '
#      89         [ #  # ]:          0 :         if (ch == ' ') {
#      90                 :            :             // Final line, dispatch reply and clean up
#      91         [ #  # ]:          0 :             if (self->message.code >= 600) {
#      92                 :            :                 // Dispatch async notifications to async handler
#      93                 :            :                 // Synchronous and asynchronous messages are never interleaved
#      94                 :          0 :                 self->async_handler(*self, self->message);
#      95                 :          0 :             } else {
#      96         [ #  # ]:          0 :                 if (!self->reply_handlers.empty()) {
#      97                 :            :                     // Invoke reply handler with message
#      98                 :          0 :                     self->reply_handlers.front()(*self, self->message);
#      99                 :          0 :                     self->reply_handlers.pop_front();
#     100                 :          0 :                 } else {
#     101         [ #  # ]:          0 :                     LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
#     102                 :          0 :                 }
#     103                 :          0 :             }
#     104                 :          0 :             self->message.Clear();
#     105                 :          0 :         }
#     106                 :          0 :     }
#     107                 :            :     //  Check for size of buffer - protect against memory exhaustion with very long lines
#     108                 :            :     //  Do this after evbuffer_readln to make sure all full lines have been
#     109                 :            :     //  removed from the buffer. Everything left is an incomplete line.
#     110         [ #  # ]:          0 :     if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
#     111                 :          0 :         LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
#     112                 :          0 :         self->Disconnect();
#     113                 :          0 :     }
#     114                 :          0 : }
#     115                 :            : 
#     116                 :            : void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
#     117                 :          0 : {
#     118                 :          0 :     TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
#     119         [ #  # ]:          0 :     if (what & BEV_EVENT_CONNECTED) {
#     120         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
#     121                 :          0 :         self->connected(*self);
#     122         [ #  # ]:          0 :     } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
#     123         [ #  # ]:          0 :         if (what & BEV_EVENT_ERROR) {
#     124         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
#     125                 :          0 :         } else {
#     126         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: End of stream\n");
#     127                 :          0 :         }
#     128                 :          0 :         self->Disconnect();
#     129                 :          0 :         self->disconnected(*self);
#     130                 :          0 :     }
#     131                 :          0 : }
#     132                 :            : 
#     133                 :            : bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
#     134                 :          0 : {
#     135         [ #  # ]:          0 :     if (b_conn) {
#     136                 :          0 :         Disconnect();
#     137                 :          0 :     }
#     138                 :            : 
#     139                 :          0 :     CService control_service;
#     140         [ #  # ]:          0 :     if (!Lookup(tor_control_center, control_service, 9051, fNameLookup)) {
#     141                 :          0 :         LogPrintf("tor: Failed to look up control center %s\n", tor_control_center);
#     142                 :          0 :         return false;
#     143                 :          0 :     }
#     144                 :            : 
#     145                 :          0 :     struct sockaddr_storage control_address;
#     146                 :          0 :     socklen_t control_address_len = sizeof(control_address);
#     147         [ #  # ]:          0 :     if (!control_service.GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) {
#     148                 :          0 :         LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
#     149                 :          0 :         return false;
#     150                 :          0 :     }
#     151                 :            : 
#     152                 :            :     // Create a new socket, set up callbacks and enable notification bits
#     153                 :          0 :     b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
#     154         [ #  # ]:          0 :     if (!b_conn) {
#     155                 :          0 :         return false;
#     156                 :          0 :     }
#     157                 :          0 :     bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
#     158                 :          0 :     bufferevent_enable(b_conn, EV_READ|EV_WRITE);
#     159                 :          0 :     this->connected = _connected;
#     160                 :          0 :     this->disconnected = _disconnected;
#     161                 :            : 
#     162                 :            :     // Finally, connect to tor_control_center
#     163         [ #  # ]:          0 :     if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) {
#     164                 :          0 :         LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
#     165                 :          0 :         return false;
#     166                 :          0 :     }
#     167                 :          0 :     return true;
#     168                 :          0 : }
#     169                 :            : 
#     170                 :            : void TorControlConnection::Disconnect()
#     171                 :          0 : {
#     172         [ #  # ]:          0 :     if (b_conn)
#     173                 :          0 :         bufferevent_free(b_conn);
#     174                 :          0 :     b_conn = nullptr;
#     175                 :          0 : }
#     176                 :            : 
#     177                 :            : bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
#     178                 :          0 : {
#     179         [ #  # ]:          0 :     if (!b_conn)
#     180                 :          0 :         return false;
#     181                 :          0 :     struct evbuffer *buf = bufferevent_get_output(b_conn);
#     182         [ #  # ]:          0 :     if (!buf)
#     183                 :          0 :         return false;
#     184                 :          0 :     evbuffer_add(buf, cmd.data(), cmd.size());
#     185                 :          0 :     evbuffer_add(buf, "\r\n", 2);
#     186                 :          0 :     reply_handlers.push_back(reply_handler);
#     187                 :          0 :     return true;
#     188                 :          0 : }
#     189                 :            : 
#     190                 :            : /****** General parsing utilities ********/
#     191                 :            : 
#     192                 :            : /* Split reply line in the form 'AUTH METHODS=...' into a type
#     193                 :            :  * 'AUTH' and arguments 'METHODS=...'.
#     194                 :            :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
#     195                 :            :  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
#     196                 :            :  */
#     197                 :            : std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
#     198                 :         20 : {
#     199                 :         20 :     size_t ptr=0;
#     200                 :         20 :     std::string type;
#     201 [ +  + ][ +  + ]:        164 :     while (ptr < s.size() && s[ptr] != ' ') {
#     202                 :        144 :         type.push_back(s[ptr]);
#     203                 :        144 :         ++ptr;
#     204                 :        144 :     }
#     205         [ +  + ]:         20 :     if (ptr < s.size())
#     206                 :         18 :         ++ptr; // skip ' '
#     207                 :         20 :     return make_pair(type, s.substr(ptr));
#     208                 :         20 : }
#     209                 :            : 
#     210                 :            : /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
#     211                 :            :  * Returns a map of keys to values, or an empty map if there was an error.
#     212                 :            :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
#     213                 :            :  * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
#     214                 :            :  * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
#     215                 :            :  */
#     216                 :            : std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
#     217                 :         54 : {
#     218                 :         54 :     std::map<std::string,std::string> mapping;
#     219                 :         54 :     size_t ptr=0;
#     220         [ +  + ]:        116 :     while (ptr < s.size()) {
#     221                 :         76 :         std::string key, value;
#     222 [ +  + ][ +  + ]:        492 :         while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
#                 [ +  + ]
#     223                 :        416 :             key.push_back(s[ptr]);
#     224                 :        416 :             ++ptr;
#     225                 :        416 :         }
#     226         [ +  + ]:         76 :         if (ptr == s.size()) // unexpected end of line
#     227                 :          2 :             return std::map<std::string,std::string>();
#     228         [ +  + ]:         74 :         if (s[ptr] == ' ') // The remaining string is an OptArguments
#     229                 :         10 :             break;
#     230                 :         64 :         ++ptr; // skip '='
#     231 [ +  - ][ +  + ]:         64 :         if (ptr < s.size() && s[ptr] == '"') { // Quoted string
#     232                 :         36 :             ++ptr; // skip opening '"'
#     233                 :         36 :             bool escape_next = false;
#     234 [ +  + ][ +  + ]:        448 :             while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
#                 [ +  + ]
#     235                 :            :                 // Repeated backslashes must be interpreted as pairs
#     236 [ +  + ][ +  + ]:        412 :                 escape_next = (s[ptr] == '\\' && !escape_next);
#     237                 :        412 :                 value.push_back(s[ptr]);
#     238                 :        412 :                 ++ptr;
#     239                 :        412 :             }
#     240         [ +  + ]:         36 :             if (ptr == s.size()) // unexpected end of line
#     241                 :          2 :                 return std::map<std::string,std::string>();
#     242                 :         34 :             ++ptr; // skip closing '"'
#     243                 :            :             /**
#     244                 :            :              * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
#     245                 :            :              *
#     246                 :            :              *   For future-proofing, controller implementors MAY use the following
#     247                 :            :              *   rules to be compatible with buggy Tor implementations and with
#     248                 :            :              *   future ones that implement the spec as intended:
#     249                 :            :              *
#     250                 :            :              *     Read \n \t \r and \0 ... \377 as C escapes.
#     251                 :            :              *     Treat a backslash followed by any other character as that character.
#     252                 :            :              */
#     253                 :         34 :             std::string escaped_value;
#     254         [ +  + ]:        366 :             for (size_t i = 0; i < value.size(); ++i) {
#     255         [ +  + ]:        332 :                 if (value[i] == '\\') {
#     256                 :            :                     // This will always be valid, because if the QuotedString
#     257                 :            :                     // ended in an odd number of backslashes, then the parser
#     258                 :            :                     // would already have returned above, due to a missing
#     259                 :            :                     // terminating double-quote.
#     260                 :         46 :                     ++i;
#     261         [ +  + ]:         46 :                     if (value[i] == 'n') {
#     262                 :          2 :                         escaped_value.push_back('\n');
#     263         [ +  + ]:         44 :                     } else if (value[i] == 't') {
#     264                 :          2 :                         escaped_value.push_back('\t');
#     265         [ +  + ]:         42 :                     } else if (value[i] == 'r') {
#     266                 :          2 :                         escaped_value.push_back('\r');
#     267 [ +  + ][ +  + ]:         40 :                     } else if ('0' <= value[i] && value[i] <= '7') {
#     268                 :         22 :                         size_t j;
#     269                 :            :                         // Octal escape sequences have a limit of three octal digits,
#     270                 :            :                         // but terminate at the first character that is not a valid
#     271                 :            :                         // octal digit if encountered sooner.
#     272 [ +  + ][ +  + ]:         42 :                         for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
#         [ +  - ][ +  + ]
#     273                 :            :                         // Tor restricts first digit to 0-3 for three-digit octals.
#     274                 :            :                         // A leading digit of 4-7 would therefore be interpreted as
#     275                 :            :                         // a two-digit octal.
#     276 [ +  + ][ +  + ]:         22 :                         if (j == 3 && value[i] > '3') {
#     277                 :          2 :                             j--;
#     278                 :          2 :                         }
#     279                 :         22 :                         const auto end{i + j};
#     280                 :         22 :                         uint8_t val{0};
#     281         [ +  + ]:         62 :                         while (i < end) {
#     282                 :         40 :                             val *= 8;
#     283                 :         40 :                             val += value[i++] - '0';
#     284                 :         40 :                         }
#     285                 :         22 :                         escaped_value.push_back(char(val));
#     286                 :            :                         // Account for automatic incrementing at loop end
#     287                 :         22 :                         --i;
#     288                 :         22 :                     } else {
#     289                 :         18 :                         escaped_value.push_back(value[i]);
#     290                 :         18 :                     }
#     291                 :        286 :                 } else {
#     292                 :        286 :                     escaped_value.push_back(value[i]);
#     293                 :        286 :                 }
#     294                 :        332 :             }
#     295                 :         34 :             value = escaped_value;
#     296                 :         34 :         } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
#     297 [ +  + ][ +  + ]:        264 :             while (ptr < s.size() && s[ptr] != ' ') {
#     298                 :        236 :                 value.push_back(s[ptr]);
#     299                 :        236 :                 ++ptr;
#     300                 :        236 :             }
#     301                 :         28 :         }
#     302 [ +  + ][ +  - ]:         62 :         if (ptr < s.size() && s[ptr] == ' ')
#     303                 :         22 :             ++ptr; // skip ' ' after key=value
#     304                 :         62 :         mapping[key] = value;
#     305                 :         62 :     }
#     306                 :         50 :     return mapping;
#     307                 :         54 : }
#     308                 :            : 
#     309                 :            : TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
#     310                 :            :     base(_base),
#     311                 :            :     m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
#     312                 :            :     reconnect_timeout(RECONNECT_TIMEOUT_START),
#     313                 :            :     m_target(target)
#     314                 :          0 : {
#     315                 :          0 :     reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
#     316         [ #  # ]:          0 :     if (!reconnect_ev)
#     317                 :          0 :         LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
#     318                 :            :     // Start connection attempts immediately
#     319         [ #  # ]:          0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
#     320                 :          0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
#     321                 :          0 :         LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
#     322                 :          0 :     }
#     323                 :            :     // Read service private key if cached
#     324                 :          0 :     std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
#     325         [ #  # ]:          0 :     if (pkf.first) {
#     326         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", fs::PathToString(GetPrivateKeyFile()));
#     327                 :          0 :         private_key = pkf.second;
#     328                 :          0 :     }
#     329                 :          0 : }
#     330                 :            : 
#     331                 :            : TorController::~TorController()
#     332                 :          0 : {
#     333         [ #  # ]:          0 :     if (reconnect_ev) {
#     334                 :          0 :         event_free(reconnect_ev);
#     335                 :          0 :         reconnect_ev = nullptr;
#     336                 :          0 :     }
#     337         [ #  # ]:          0 :     if (service.IsValid()) {
#     338                 :          0 :         RemoveLocal(service);
#     339                 :          0 :     }
#     340                 :          0 : }
#     341                 :            : 
#     342                 :            : void TorController::get_socks_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     343                 :          0 : {
#     344                 :            :     // NOTE: We can only get here if -onion is unset
#     345                 :          0 :     std::string socks_location;
#     346         [ #  # ]:          0 :     if (reply.code == 250) {
#     347         [ #  # ]:          0 :         for (const auto& line : reply.lines) {
#     348         [ #  # ]:          0 :             if (0 == line.compare(0, 20, "net/listeners/socks=")) {
#     349                 :          0 :                 const std::string port_list_str = line.substr(20);
#     350                 :          0 :                 std::vector<std::string> port_list;
#     351                 :          0 :                 boost::split(port_list, port_list_str, boost::is_any_of(" "));
#     352         [ #  # ]:          0 :                 for (auto& portstr : port_list) {
#     353         [ #  # ]:          0 :                     if (portstr.empty()) continue;
#     354 [ #  # ][ #  # ]:          0 :                     if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
#         [ #  # ][ #  # ]
#                 [ #  # ]
#     355                 :          0 :                         portstr = portstr.substr(1, portstr.size() - 2);
#     356         [ #  # ]:          0 :                         if (portstr.empty()) continue;
#     357                 :          0 :                     }
#     358                 :          0 :                     socks_location = portstr;
#     359         [ #  # ]:          0 :                     if (0 == portstr.compare(0, 10, "127.0.0.1:")) {
#     360                 :            :                         // Prefer localhost - ignore other ports
#     361                 :          0 :                         break;
#     362                 :          0 :                     }
#     363                 :          0 :                 }
#     364                 :          0 :             }
#     365                 :          0 :         }
#     366         [ #  # ]:          0 :         if (!socks_location.empty()) {
#     367         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Get SOCKS port command yielded %s\n", socks_location);
#     368                 :          0 :         } else {
#     369                 :          0 :             LogPrintf("tor: Get SOCKS port command returned nothing\n");
#     370                 :          0 :         }
#     371         [ #  # ]:          0 :     } else if (reply.code == 510) {  // 510 Unrecognized command
#     372                 :          0 :         LogPrintf("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n");
#     373                 :          0 :     } else {
#     374                 :          0 :         LogPrintf("tor: Get SOCKS port command failed; error code %d\n", reply.code);
#     375                 :          0 :     }
#     376                 :            : 
#     377                 :          0 :     CService resolved;
#     378                 :          0 :     Assume(!resolved.IsValid());
#     379         [ #  # ]:          0 :     if (!socks_location.empty()) {
#     380                 :          0 :         resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT);
#     381                 :          0 :     }
#     382         [ #  # ]:          0 :     if (!resolved.IsValid()) {
#     383                 :            :         // Fallback to old behaviour
#     384                 :          0 :         resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
#     385                 :          0 :     }
#     386                 :            : 
#     387                 :          0 :     Assume(resolved.IsValid());
#     388         [ #  # ]:          0 :     LogPrint(BCLog::TOR, "tor: Configuring onion proxy for %s\n", resolved.ToStringIPPort());
#     389                 :          0 :     Proxy addrOnion = Proxy(resolved, true);
#     390                 :          0 :     SetProxy(NET_ONION, addrOnion);
#     391                 :            : 
#     392                 :          0 :     const auto onlynets = gArgs.GetArgs("-onlynet");
#     393                 :            : 
#     394                 :          0 :     const bool onion_allowed_by_onlynet{
#     395         [ #  # ]:          0 :         !gArgs.IsArgSet("-onlynet") ||
#     396         [ #  # ]:          0 :         std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
#     397                 :          0 :             return ParseNetwork(n) == NET_ONION;
#     398                 :          0 :         })};
#     399                 :            : 
#     400         [ #  # ]:          0 :     if (onion_allowed_by_onlynet) {
#     401                 :            :         // If NET_ONION is reachable, then the below is a noop.
#     402                 :            :         //
#     403                 :            :         // If NET_ONION is not reachable, then none of -proxy or -onion was given.
#     404                 :            :         // Since we are here, then -torcontrol and -torpassword were given.
#     405                 :          0 :         SetReachable(NET_ONION, true);
#     406                 :          0 :     }
#     407                 :          0 : }
#     408                 :            : 
#     409                 :            : void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     410                 :          0 : {
#     411         [ #  # ]:          0 :     if (reply.code == 250) {
#     412         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
#     413         [ #  # ]:          0 :         for (const std::string &s : reply.lines) {
#     414                 :          0 :             std::map<std::string,std::string> m = ParseTorReplyMapping(s);
#     415                 :          0 :             std::map<std::string,std::string>::iterator i;
#     416         [ #  # ]:          0 :             if ((i = m.find("ServiceID")) != m.end())
#     417                 :          0 :                 service_id = i->second;
#     418         [ #  # ]:          0 :             if ((i = m.find("PrivateKey")) != m.end())
#     419                 :          0 :                 private_key = i->second;
#     420                 :          0 :         }
#     421         [ #  # ]:          0 :         if (service_id.empty()) {
#     422                 :          0 :             LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
#     423         [ #  # ]:          0 :             for (const std::string &s : reply.lines) {
#     424                 :          0 :                 LogPrintf("    %s\n", SanitizeString(s));
#     425                 :          0 :             }
#     426                 :          0 :             return;
#     427                 :          0 :         }
#     428                 :          0 :         service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
#     429                 :          0 :         LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
#     430         [ #  # ]:          0 :         if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
#     431         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
#     432                 :          0 :         } else {
#     433                 :          0 :             LogPrintf("tor: Error writing service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
#     434                 :          0 :         }
#     435                 :          0 :         AddLocal(service, LOCAL_MANUAL);
#     436                 :            :         // ... onion requested - keep connection open
#     437         [ #  # ]:          0 :     } else if (reply.code == 510) { // 510 Unrecognized command
#     438                 :          0 :         LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
#     439                 :          0 :     } else {
#     440                 :          0 :         LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
#     441                 :          0 :     }
#     442                 :          0 : }
#     443                 :            : 
#     444                 :            : void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     445                 :          0 : {
#     446         [ #  # ]:          0 :     if (reply.code == 250) {
#     447         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: Authentication successful\n");
#     448                 :            : 
#     449                 :            :         // Now that we know Tor is running setup the proxy for onion addresses
#     450                 :            :         // if -onion isn't set to something else.
#     451         [ #  # ]:          0 :         if (gArgs.GetArg("-onion", "") == "") {
#     452                 :          0 :             _conn.Command("GETINFO net/listeners/socks", std::bind(&TorController::get_socks_cb, this, std::placeholders::_1, std::placeholders::_2));
#     453                 :          0 :         }
#     454                 :            : 
#     455                 :            :         // Finally - now create the service
#     456         [ #  # ]:          0 :         if (private_key.empty()) { // No private key, generate one
#     457                 :          0 :             private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
#     458                 :          0 :         }
#     459                 :            :         // Request onion service, redirect port.
#     460                 :            :         // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
#     461                 :          0 :         _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringIPPort()),
#     462                 :          0 :             std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
#     463                 :          0 :     } else {
#     464                 :          0 :         LogPrintf("tor: Authentication failed\n");
#     465                 :          0 :     }
#     466                 :          0 : }
#     467                 :            : 
#     468                 :            : /** Compute Tor SAFECOOKIE response.
#     469                 :            :  *
#     470                 :            :  *    ServerHash is computed as:
#     471                 :            :  *      HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
#     472                 :            :  *                  CookieString | ClientNonce | ServerNonce)
#     473                 :            :  *    (with the HMAC key as its first argument)
#     474                 :            :  *
#     475                 :            :  *    After a controller sends a successful AUTHCHALLENGE command, the
#     476                 :            :  *    next command sent on the connection must be an AUTHENTICATE command,
#     477                 :            :  *    and the only authentication string which that AUTHENTICATE command
#     478                 :            :  *    will accept is:
#     479                 :            :  *
#     480                 :            :  *      HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
#     481                 :            :  *                  CookieString | ClientNonce | ServerNonce)
#     482                 :            :  *
#     483                 :            :  */
#     484                 :            : 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)
#     485                 :          0 : {
#     486                 :          0 :     CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
#     487                 :          0 :     std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
#     488                 :          0 :     computeHash.Write(cookie.data(), cookie.size());
#     489                 :          0 :     computeHash.Write(clientNonce.data(), clientNonce.size());
#     490                 :          0 :     computeHash.Write(serverNonce.data(), serverNonce.size());
#     491                 :          0 :     computeHash.Finalize(computedHash.data());
#     492                 :          0 :     return computedHash;
#     493                 :          0 : }
#     494                 :            : 
#     495                 :            : void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     496                 :          0 : {
#     497         [ #  # ]:          0 :     if (reply.code == 250) {
#     498         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
#     499                 :          0 :         std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
#     500         [ #  # ]:          0 :         if (l.first == "AUTHCHALLENGE") {
#     501                 :          0 :             std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     502         [ #  # ]:          0 :             if (m.empty()) {
#     503                 :          0 :                 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
#     504                 :          0 :                 return;
#     505                 :          0 :             }
#     506                 :          0 :             std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
#     507                 :          0 :             std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
#     508         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
#     509         [ #  # ]:          0 :             if (serverNonce.size() != 32) {
#     510                 :          0 :                 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
#     511                 :          0 :                 return;
#     512                 :          0 :             }
#     513                 :            : 
#     514                 :          0 :             std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
#     515         [ #  # ]:          0 :             if (computedServerHash != serverHash) {
#     516                 :          0 :                 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
#     517                 :          0 :                 return;
#     518                 :          0 :             }
#     519                 :            : 
#     520                 :          0 :             std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
#     521                 :          0 :             _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     522                 :          0 :         } else {
#     523                 :          0 :             LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
#     524                 :          0 :         }
#     525                 :          0 :     } else {
#     526                 :          0 :         LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
#     527                 :          0 :     }
#     528                 :          0 : }
#     529                 :            : 
#     530                 :            : void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     531                 :          0 : {
#     532         [ #  # ]:          0 :     if (reply.code == 250) {
#     533                 :          0 :         std::set<std::string> methods;
#     534                 :          0 :         std::string cookiefile;
#     535                 :            :         /*
#     536                 :            :          * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
#     537                 :            :          * 250-AUTH METHODS=NULL
#     538                 :            :          * 250-AUTH METHODS=HASHEDPASSWORD
#     539                 :            :          */
#     540         [ #  # ]:          0 :         for (const std::string &s : reply.lines) {
#     541                 :          0 :             std::pair<std::string,std::string> l = SplitTorReplyLine(s);
#     542         [ #  # ]:          0 :             if (l.first == "AUTH") {
#     543                 :          0 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     544                 :          0 :                 std::map<std::string,std::string>::iterator i;
#     545         [ #  # ]:          0 :                 if ((i = m.find("METHODS")) != m.end())
#     546                 :          0 :                     boost::split(methods, i->second, boost::is_any_of(","));
#     547         [ #  # ]:          0 :                 if ((i = m.find("COOKIEFILE")) != m.end())
#     548                 :          0 :                     cookiefile = i->second;
#     549         [ #  # ]:          0 :             } else if (l.first == "VERSION") {
#     550                 :          0 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     551                 :          0 :                 std::map<std::string,std::string>::iterator i;
#     552         [ #  # ]:          0 :                 if ((i = m.find("Tor")) != m.end()) {
#     553         [ #  # ]:          0 :                     LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
#     554                 :          0 :                 }
#     555                 :          0 :             }
#     556                 :          0 :         }
#     557         [ #  # ]:          0 :         for (const std::string &s : methods) {
#     558         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
#     559                 :          0 :         }
#     560                 :            :         // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
#     561                 :            :         /* Authentication:
#     562                 :            :          *   cookie:   hex-encoded ~/.tor/control_auth_cookie
#     563                 :            :          *   password: "password"
#     564                 :            :          */
#     565                 :          0 :         std::string torpassword = gArgs.GetArg("-torpassword", "");
#     566         [ #  # ]:          0 :         if (!torpassword.empty()) {
#     567         [ #  # ]:          0 :             if (methods.count("HASHEDPASSWORD")) {
#     568         [ #  # ]:          0 :                 LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
#     569                 :          0 :                 boost::replace_all(torpassword, "\"", "\\\"");
#     570                 :          0 :                 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     571                 :          0 :             } else {
#     572                 :          0 :                 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
#     573                 :          0 :             }
#     574         [ #  # ]:          0 :         } else if (methods.count("NULL")) {
#     575         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
#     576                 :          0 :             _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     577         [ #  # ]:          0 :         } else if (methods.count("SAFECOOKIE")) {
#     578                 :            :             // Cookie: hexdump -e '32/1 "%02x""\n"'  ~/.tor/control_auth_cookie
#     579         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
#     580                 :          0 :             std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE);
#     581 [ #  # ][ #  # ]:          0 :             if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
#     582                 :            :                 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     583                 :          0 :                 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
#     584                 :          0 :                 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
#     585                 :          0 :                 GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
#     586                 :          0 :                 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
#     587                 :          0 :             } else {
#     588         [ #  # ]:          0 :                 if (status_cookie.first) {
#     589                 :          0 :                     LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
#     590                 :          0 :                 } else {
#     591                 :          0 :                     LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
#     592                 :          0 :                 }
#     593                 :          0 :             }
#     594         [ #  # ]:          0 :         } else if (methods.count("HASHEDPASSWORD")) {
#     595                 :          0 :             LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
#     596                 :          0 :         } else {
#     597                 :          0 :             LogPrintf("tor: No supported authentication method\n");
#     598                 :          0 :         }
#     599                 :          0 :     } else {
#     600                 :          0 :         LogPrintf("tor: Requesting protocol info failed\n");
#     601                 :          0 :     }
#     602                 :          0 : }
#     603                 :            : 
#     604                 :            : void TorController::connected_cb(TorControlConnection& _conn)
#     605                 :          0 : {
#     606                 :          0 :     reconnect_timeout = RECONNECT_TIMEOUT_START;
#     607                 :            :     // First send a PROTOCOLINFO command to figure out what authentication is expected
#     608         [ #  # ]:          0 :     if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
#     609                 :          0 :         LogPrintf("tor: Error sending initial protocolinfo command\n");
#     610                 :          0 : }
#     611                 :            : 
#     612                 :            : void TorController::disconnected_cb(TorControlConnection& _conn)
#     613                 :          0 : {
#     614                 :            :     // Stop advertising service when disconnected
#     615         [ #  # ]:          0 :     if (service.IsValid())
#     616                 :          0 :         RemoveLocal(service);
#     617                 :          0 :     service = CService();
#     618         [ #  # ]:          0 :     if (!reconnect)
#     619                 :          0 :         return;
#     620                 :            : 
#     621         [ #  # ]:          0 :     LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
#     622                 :            : 
#     623                 :            :     // Single-shot timer for reconnect. Use exponential backoff.
#     624                 :          0 :     struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
#     625         [ #  # ]:          0 :     if (reconnect_ev)
#     626                 :          0 :         event_add(reconnect_ev, &time);
#     627                 :          0 :     reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
#     628                 :          0 : }
#     629                 :            : 
#     630                 :            : void TorController::Reconnect()
#     631                 :          0 : {
#     632                 :            :     /* Try to reconnect and reestablish if we get booted - for example, Tor
#     633                 :            :      * may be restarting.
#     634                 :            :      */
#     635         [ #  # ]:          0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
#     636                 :          0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
#     637                 :          0 :         LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
#     638                 :          0 :     }
#     639                 :          0 : }
#     640                 :            : 
#     641                 :            : fs::path TorController::GetPrivateKeyFile()
#     642                 :          0 : {
#     643                 :          0 :     return gArgs.GetDataDirNet() / "onion_v3_private_key";
#     644                 :          0 : }
#     645                 :            : 
#     646                 :            : void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
#     647                 :          0 : {
#     648                 :          0 :     TorController *self = static_cast<TorController*>(arg);
#     649                 :          0 :     self->Reconnect();
#     650                 :          0 : }
#     651                 :            : 
#     652                 :            : /****** Thread ********/
#     653                 :            : static struct event_base *gBase;
#     654                 :            : static std::thread torControlThread;
#     655                 :            : 
#     656                 :            : static void TorControlThread(CService onion_service_target)
#     657                 :          0 : {
#     658                 :          0 :     SetSyscallSandboxPolicy(SyscallSandboxPolicy::TOR_CONTROL);
#     659                 :          0 :     TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
#     660                 :            : 
#     661                 :          0 :     event_base_dispatch(gBase);
#     662                 :          0 : }
#     663                 :            : 
#     664                 :            : void StartTorControl(CService onion_service_target)
#     665                 :          0 : {
#     666                 :          0 :     assert(!gBase);
#     667                 :            : #ifdef WIN32
#     668                 :            :     evthread_use_windows_threads();
#     669                 :            : #else
#     670                 :          0 :     evthread_use_pthreads();
#     671                 :          0 : #endif
#     672                 :          0 :     gBase = event_base_new();
#     673         [ #  # ]:          0 :     if (!gBase) {
#     674                 :          0 :         LogPrintf("tor: Unable to create event_base\n");
#     675                 :          0 :         return;
#     676                 :          0 :     }
#     677                 :            : 
#     678                 :          0 :     torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
#     679                 :          0 :         TorControlThread(onion_service_target);
#     680                 :          0 :     });
#     681                 :          0 : }
#     682                 :            : 
#     683                 :            : void InterruptTorControl()
#     684                 :        794 : {
#     685         [ -  + ]:        794 :     if (gBase) {
#     686                 :          0 :         LogPrintf("tor: Thread interrupt\n");
#     687                 :          0 :         event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
#     688                 :          0 :             event_base_loopbreak(gBase);
#     689                 :          0 :         }, nullptr, nullptr);
#     690                 :          0 :     }
#     691                 :        794 : }
#     692                 :            : 
#     693                 :            : void StopTorControl()
#     694                 :        794 : {
#     695         [ -  + ]:        794 :     if (gBase) {
#     696                 :          0 :         torControlThread.join();
#     697                 :          0 :         event_base_free(gBase);
#     698                 :          0 :         gBase = nullptr;
#     699                 :          0 :     }
#     700                 :        794 : }
#     701                 :            : 
#     702                 :            : CService DefaultOnionServiceTarget()
#     703                 :        722 : {
#     704                 :        722 :     struct in_addr onion_service_target;
#     705                 :        722 :     onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
#     706                 :        722 :     return {onion_service_target, BaseParams().OnionServiceTargetPort()};
#     707                 :        722 : }

Generated by: LCOV version 0-eol-96201-ge66f56f4af6a