LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Hit Total Coverage
Test: coverage.lcov Lines: 85 408 20.8 %
Date: 2021-06-29 14:35:33 Functions: 5 28 17.9 %
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: 67 224 29.9 %

           Branch data     Line data    Source code
#       1                 :            : // Copyright (c) 2015-2020 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/system.h>
#      18                 :            : #include <util/thread.h>
#      19                 :            : #include <util/time.h>
#      20                 :            : 
#      21                 :            : #include <deque>
#      22                 :            : #include <functional>
#      23                 :            : #include <set>
#      24                 :            : #include <stdlib.h>
#      25                 :            : #include <vector>
#      26                 :            : 
#      27                 :            : #include <boost/signals2/signal.hpp>
#      28                 :            : #include <boost/algorithm/string/split.hpp>
#      29                 :            : #include <boost/algorithm/string/classification.hpp>
#      30                 :            : #include <boost/algorithm/string/replace.hpp>
#      31                 :            : 
#      32                 :            : #include <event2/bufferevent.h>
#      33                 :            : #include <event2/buffer.h>
#      34                 :            : #include <event2/util.h>
#      35                 :            : #include <event2/event.h>
#      36                 :            : #include <event2/thread.h>
#      37                 :            : 
#      38                 :            : /** Default control port */
#      39                 :            : const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
#      40                 :            : /** Tor cookie size (from control-spec.txt) */
#      41                 :            : static const int TOR_COOKIE_SIZE = 32;
#      42                 :            : /** Size of client/server nonce for SAFECOOKIE */
#      43                 :            : static const int TOR_NONCE_SIZE = 32;
#      44                 :            : /** For computing serverHash in SAFECOOKIE */
#      45                 :            : static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
#      46                 :            : /** For computing clientHash in SAFECOOKIE */
#      47                 :            : static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
#      48                 :            : /** Exponential backoff configuration - initial timeout in seconds */
#      49                 :            : static const float RECONNECT_TIMEOUT_START = 1.0;
#      50                 :            : /** Exponential backoff configuration - growth factor */
#      51                 :            : static const float RECONNECT_TIMEOUT_EXP = 1.5;
#      52                 :            : /** Maximum length for lines received on TorControlConnection.
#      53                 :            :  * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
#      54                 :            :  * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
#      55                 :            :  */
#      56                 :            : static const int MAX_LINE_LENGTH = 100000;
#      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 = atoi(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                 :            :     // Parse tor_control_center address:port
#     138                 :          0 :     struct sockaddr_storage connect_to_addr;
#     139                 :          0 :     int connect_to_addrlen = sizeof(connect_to_addr);
#     140         [ #  # ]:          0 :     if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
#     141                 :          0 :         (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
#     142                 :          0 :         LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
#     143                 :          0 :         return false;
#     144                 :          0 :     }
#     145                 :            : 
#     146                 :            :     // Create a new socket, set up callbacks and enable notification bits
#     147                 :          0 :     b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
#     148         [ #  # ]:          0 :     if (!b_conn)
#     149                 :          0 :         return false;
#     150                 :          0 :     bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
#     151                 :          0 :     bufferevent_enable(b_conn, EV_READ|EV_WRITE);
#     152                 :          0 :     this->connected = _connected;
#     153                 :          0 :     this->disconnected = _disconnected;
#     154                 :            : 
#     155                 :            :     // Finally, connect to tor_control_center
#     156         [ #  # ]:          0 :     if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
#     157                 :          0 :         LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
#     158                 :          0 :         return false;
#     159                 :          0 :     }
#     160                 :          0 :     return true;
#     161                 :          0 : }
#     162                 :            : 
#     163                 :            : void TorControlConnection::Disconnect()
#     164                 :          0 : {
#     165         [ #  # ]:          0 :     if (b_conn)
#     166                 :          0 :         bufferevent_free(b_conn);
#     167                 :          0 :     b_conn = nullptr;
#     168                 :          0 : }
#     169                 :            : 
#     170                 :            : bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
#     171                 :          0 : {
#     172         [ #  # ]:          0 :     if (!b_conn)
#     173                 :          0 :         return false;
#     174                 :          0 :     struct evbuffer *buf = bufferevent_get_output(b_conn);
#     175         [ #  # ]:          0 :     if (!buf)
#     176                 :          0 :         return false;
#     177                 :          0 :     evbuffer_add(buf, cmd.data(), cmd.size());
#     178                 :          0 :     evbuffer_add(buf, "\r\n", 2);
#     179                 :          0 :     reply_handlers.push_back(reply_handler);
#     180                 :          0 :     return true;
#     181                 :          0 : }
#     182                 :            : 
#     183                 :            : /****** General parsing utilities ********/
#     184                 :            : 
#     185                 :            : /* Split reply line in the form 'AUTH METHODS=...' into a type
#     186                 :            :  * 'AUTH' and arguments 'METHODS=...'.
#     187                 :            :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
#     188                 :            :  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
#     189                 :            :  */
#     190                 :            : std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
#     191                 :         20 : {
#     192                 :         20 :     size_t ptr=0;
#     193                 :         20 :     std::string type;
#     194 [ +  + ][ +  + ]:        164 :     while (ptr < s.size() && s[ptr] != ' ') {
#     195                 :        144 :         type.push_back(s[ptr]);
#     196                 :        144 :         ++ptr;
#     197                 :        144 :     }
#     198         [ +  + ]:         20 :     if (ptr < s.size())
#     199                 :         18 :         ++ptr; // skip ' '
#     200                 :         20 :     return make_pair(type, s.substr(ptr));
#     201                 :         20 : }
#     202                 :            : 
#     203                 :            : /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
#     204                 :            :  * Returns a map of keys to values, or an empty map if there was an error.
#     205                 :            :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
#     206                 :            :  * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
#     207                 :            :  * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
#     208                 :            :  */
#     209                 :            : std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
#     210                 :         54 : {
#     211                 :         54 :     std::map<std::string,std::string> mapping;
#     212                 :         54 :     size_t ptr=0;
#     213         [ +  + ]:        116 :     while (ptr < s.size()) {
#     214                 :         76 :         std::string key, value;
#     215 [ +  + ][ +  + ]:        492 :         while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
#                 [ +  + ]
#     216                 :        416 :             key.push_back(s[ptr]);
#     217                 :        416 :             ++ptr;
#     218                 :        416 :         }
#     219         [ +  + ]:         76 :         if (ptr == s.size()) // unexpected end of line
#     220                 :          2 :             return std::map<std::string,std::string>();
#     221         [ +  + ]:         74 :         if (s[ptr] == ' ') // The remaining string is an OptArguments
#     222                 :         10 :             break;
#     223                 :         64 :         ++ptr; // skip '='
#     224 [ +  - ][ +  + ]:         64 :         if (ptr < s.size() && s[ptr] == '"') { // Quoted string
#     225                 :         36 :             ++ptr; // skip opening '"'
#     226                 :         36 :             bool escape_next = false;
#     227 [ +  + ][ +  + ]:        448 :             while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
#                 [ +  + ]
#     228                 :            :                 // Repeated backslashes must be interpreted as pairs
#     229 [ +  + ][ +  + ]:        412 :                 escape_next = (s[ptr] == '\\' && !escape_next);
#     230                 :        412 :                 value.push_back(s[ptr]);
#     231                 :        412 :                 ++ptr;
#     232                 :        412 :             }
#     233         [ +  + ]:         36 :             if (ptr == s.size()) // unexpected end of line
#     234                 :          2 :                 return std::map<std::string,std::string>();
#     235                 :         34 :             ++ptr; // skip closing '"'
#     236                 :            :             /**
#     237                 :            :              * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
#     238                 :            :              *
#     239                 :            :              *   For future-proofing, controller implementors MAY use the following
#     240                 :            :              *   rules to be compatible with buggy Tor implementations and with
#     241                 :            :              *   future ones that implement the spec as intended:
#     242                 :            :              *
#     243                 :            :              *     Read \n \t \r and \0 ... \377 as C escapes.
#     244                 :            :              *     Treat a backslash followed by any other character as that character.
#     245                 :            :              */
#     246                 :         34 :             std::string escaped_value;
#     247         [ +  + ]:        366 :             for (size_t i = 0; i < value.size(); ++i) {
#     248         [ +  + ]:        332 :                 if (value[i] == '\\') {
#     249                 :            :                     // This will always be valid, because if the QuotedString
#     250                 :            :                     // ended in an odd number of backslashes, then the parser
#     251                 :            :                     // would already have returned above, due to a missing
#     252                 :            :                     // terminating double-quote.
#     253                 :         46 :                     ++i;
#     254         [ +  + ]:         46 :                     if (value[i] == 'n') {
#     255                 :          2 :                         escaped_value.push_back('\n');
#     256         [ +  + ]:         44 :                     } else if (value[i] == 't') {
#     257                 :          2 :                         escaped_value.push_back('\t');
#     258         [ +  + ]:         42 :                     } else if (value[i] == 'r') {
#     259                 :          2 :                         escaped_value.push_back('\r');
#     260 [ +  + ][ +  + ]:         40 :                     } else if ('0' <= value[i] && value[i] <= '7') {
#     261                 :         22 :                         size_t j;
#     262                 :            :                         // Octal escape sequences have a limit of three octal digits,
#     263                 :            :                         // but terminate at the first character that is not a valid
#     264                 :            :                         // octal digit if encountered sooner.
#     265 [ +  + ][ +  + ]:         42 :                         for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
#         [ +  - ][ +  + ]
#     266                 :            :                         // Tor restricts first digit to 0-3 for three-digit octals.
#     267                 :            :                         // A leading digit of 4-7 would therefore be interpreted as
#     268                 :            :                         // a two-digit octal.
#     269 [ +  + ][ +  + ]:         22 :                         if (j == 3 && value[i] > '3') {
#     270                 :          2 :                             j--;
#     271                 :          2 :                         }
#     272                 :         22 :                         escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
#     273                 :            :                         // Account for automatic incrementing at loop end
#     274                 :         22 :                         i += j - 1;
#     275                 :         22 :                     } else {
#     276                 :         18 :                         escaped_value.push_back(value[i]);
#     277                 :         18 :                     }
#     278                 :        286 :                 } else {
#     279                 :        286 :                     escaped_value.push_back(value[i]);
#     280                 :        286 :                 }
#     281                 :        332 :             }
#     282                 :         34 :             value = escaped_value;
#     283                 :         34 :         } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
#     284 [ +  + ][ +  + ]:        264 :             while (ptr < s.size() && s[ptr] != ' ') {
#     285                 :        236 :                 value.push_back(s[ptr]);
#     286                 :        236 :                 ++ptr;
#     287                 :        236 :             }
#     288                 :         28 :         }
#     289 [ +  + ][ +  - ]:         64 :         if (ptr < s.size() && s[ptr] == ' ')
#     290                 :         22 :             ++ptr; // skip ' ' after key=value
#     291                 :         62 :         mapping[key] = value;
#     292                 :         62 :     }
#     293                 :         54 :     return mapping;
#     294                 :         54 : }
#     295                 :            : 
#     296                 :            : TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
#     297                 :            :     base(_base),
#     298                 :            :     m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
#     299                 :            :     reconnect_timeout(RECONNECT_TIMEOUT_START),
#     300                 :            :     m_target(target)
#     301                 :          0 : {
#     302                 :          0 :     reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
#     303         [ #  # ]:          0 :     if (!reconnect_ev)
#     304                 :          0 :         LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
#     305                 :            :     // Start connection attempts immediately
#     306         [ #  # ]:          0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
#     307                 :          0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
#     308                 :          0 :         LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
#     309                 :          0 :     }
#     310                 :            :     // Read service private key if cached
#     311                 :          0 :     std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
#     312         [ #  # ]:          0 :     if (pkf.first) {
#     313         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
#     314                 :          0 :         private_key = pkf.second;
#     315                 :          0 :     }
#     316                 :          0 : }
#     317                 :            : 
#     318                 :            : TorController::~TorController()
#     319                 :          0 : {
#     320         [ #  # ]:          0 :     if (reconnect_ev) {
#     321                 :          0 :         event_free(reconnect_ev);
#     322                 :          0 :         reconnect_ev = nullptr;
#     323                 :          0 :     }
#     324         [ #  # ]:          0 :     if (service.IsValid()) {
#     325                 :          0 :         RemoveLocal(service);
#     326                 :          0 :     }
#     327                 :          0 : }
#     328                 :            : 
#     329                 :            : void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     330                 :          0 : {
#     331         [ #  # ]:          0 :     if (reply.code == 250) {
#     332         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
#     333         [ #  # ]:          0 :         for (const std::string &s : reply.lines) {
#     334                 :          0 :             std::map<std::string,std::string> m = ParseTorReplyMapping(s);
#     335                 :          0 :             std::map<std::string,std::string>::iterator i;
#     336         [ #  # ]:          0 :             if ((i = m.find("ServiceID")) != m.end())
#     337                 :          0 :                 service_id = i->second;
#     338         [ #  # ]:          0 :             if ((i = m.find("PrivateKey")) != m.end())
#     339                 :          0 :                 private_key = i->second;
#     340                 :          0 :         }
#     341         [ #  # ]:          0 :         if (service_id.empty()) {
#     342                 :          0 :             LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
#     343         [ #  # ]:          0 :             for (const std::string &s : reply.lines) {
#     344                 :          0 :                 LogPrintf("    %s\n", SanitizeString(s));
#     345                 :          0 :             }
#     346                 :          0 :             return;
#     347                 :          0 :         }
#     348                 :          0 :         service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
#     349                 :          0 :         LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
#     350         [ #  # ]:          0 :         if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
#     351         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
#     352                 :          0 :         } else {
#     353                 :          0 :             LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
#     354                 :          0 :         }
#     355                 :          0 :         AddLocal(service, LOCAL_MANUAL);
#     356                 :            :         // ... onion requested - keep connection open
#     357         [ #  # ]:          0 :     } else if (reply.code == 510) { // 510 Unrecognized command
#     358                 :          0 :         LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
#     359                 :          0 :     } else {
#     360                 :          0 :         LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
#     361                 :          0 :     }
#     362                 :          0 : }
#     363                 :            : 
#     364                 :            : void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     365                 :          0 : {
#     366         [ #  # ]:          0 :     if (reply.code == 250) {
#     367         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: Authentication successful\n");
#     368                 :            : 
#     369                 :            :         // Now that we know Tor is running setup the proxy for onion addresses
#     370                 :            :         // if -onion isn't set to something else.
#     371         [ #  # ]:          0 :         if (gArgs.GetArg("-onion", "") == "") {
#     372                 :          0 :             CService resolved(LookupNumeric("127.0.0.1", 9050));
#     373                 :          0 :             proxyType addrOnion = proxyType(resolved, true);
#     374                 :          0 :             SetProxy(NET_ONION, addrOnion);
#     375                 :          0 :             SetReachable(NET_ONION, true);
#     376                 :          0 :         }
#     377                 :            : 
#     378                 :            :         // Finally - now create the service
#     379         [ #  # ]:          0 :         if (private_key.empty()) { // No private key, generate one
#     380                 :          0 :             private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
#     381                 :          0 :         }
#     382                 :            :         // Request onion service, redirect port.
#     383                 :            :         // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
#     384                 :          0 :         _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringIPPort()),
#     385                 :          0 :             std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
#     386                 :          0 :     } else {
#     387                 :          0 :         LogPrintf("tor: Authentication failed\n");
#     388                 :          0 :     }
#     389                 :          0 : }
#     390                 :            : 
#     391                 :            : /** Compute Tor SAFECOOKIE response.
#     392                 :            :  *
#     393                 :            :  *    ServerHash is computed as:
#     394                 :            :  *      HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
#     395                 :            :  *                  CookieString | ClientNonce | ServerNonce)
#     396                 :            :  *    (with the HMAC key as its first argument)
#     397                 :            :  *
#     398                 :            :  *    After a controller sends a successful AUTHCHALLENGE command, the
#     399                 :            :  *    next command sent on the connection must be an AUTHENTICATE command,
#     400                 :            :  *    and the only authentication string which that AUTHENTICATE command
#     401                 :            :  *    will accept is:
#     402                 :            :  *
#     403                 :            :  *      HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
#     404                 :            :  *                  CookieString | ClientNonce | ServerNonce)
#     405                 :            :  *
#     406                 :            :  */
#     407                 :            : 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)
#     408                 :          0 : {
#     409                 :          0 :     CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
#     410                 :          0 :     std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
#     411                 :          0 :     computeHash.Write(cookie.data(), cookie.size());
#     412                 :          0 :     computeHash.Write(clientNonce.data(), clientNonce.size());
#     413                 :          0 :     computeHash.Write(serverNonce.data(), serverNonce.size());
#     414                 :          0 :     computeHash.Finalize(computedHash.data());
#     415                 :          0 :     return computedHash;
#     416                 :          0 : }
#     417                 :            : 
#     418                 :            : void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     419                 :          0 : {
#     420         [ #  # ]:          0 :     if (reply.code == 250) {
#     421         [ #  # ]:          0 :         LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
#     422                 :          0 :         std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
#     423         [ #  # ]:          0 :         if (l.first == "AUTHCHALLENGE") {
#     424                 :          0 :             std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     425         [ #  # ]:          0 :             if (m.empty()) {
#     426                 :          0 :                 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
#     427                 :          0 :                 return;
#     428                 :          0 :             }
#     429                 :          0 :             std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
#     430                 :          0 :             std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
#     431         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
#     432         [ #  # ]:          0 :             if (serverNonce.size() != 32) {
#     433                 :          0 :                 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
#     434                 :          0 :                 return;
#     435                 :          0 :             }
#     436                 :            : 
#     437                 :          0 :             std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
#     438         [ #  # ]:          0 :             if (computedServerHash != serverHash) {
#     439                 :          0 :                 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
#     440                 :          0 :                 return;
#     441                 :          0 :             }
#     442                 :            : 
#     443                 :          0 :             std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
#     444                 :          0 :             _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     445                 :          0 :         } else {
#     446                 :          0 :             LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
#     447                 :          0 :         }
#     448                 :          0 :     } else {
#     449                 :          0 :         LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
#     450                 :          0 :     }
#     451                 :          0 : }
#     452                 :            : 
#     453                 :            : void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
#     454                 :          0 : {
#     455         [ #  # ]:          0 :     if (reply.code == 250) {
#     456                 :          0 :         std::set<std::string> methods;
#     457                 :          0 :         std::string cookiefile;
#     458                 :            :         /*
#     459                 :            :          * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
#     460                 :            :          * 250-AUTH METHODS=NULL
#     461                 :            :          * 250-AUTH METHODS=HASHEDPASSWORD
#     462                 :            :          */
#     463         [ #  # ]:          0 :         for (const std::string &s : reply.lines) {
#     464                 :          0 :             std::pair<std::string,std::string> l = SplitTorReplyLine(s);
#     465         [ #  # ]:          0 :             if (l.first == "AUTH") {
#     466                 :          0 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     467                 :          0 :                 std::map<std::string,std::string>::iterator i;
#     468         [ #  # ]:          0 :                 if ((i = m.find("METHODS")) != m.end())
#     469                 :          0 :                     boost::split(methods, i->second, boost::is_any_of(","));
#     470         [ #  # ]:          0 :                 if ((i = m.find("COOKIEFILE")) != m.end())
#     471                 :          0 :                     cookiefile = i->second;
#     472         [ #  # ]:          0 :             } else if (l.first == "VERSION") {
#     473                 :          0 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
#     474                 :          0 :                 std::map<std::string,std::string>::iterator i;
#     475         [ #  # ]:          0 :                 if ((i = m.find("Tor")) != m.end()) {
#     476         [ #  # ]:          0 :                     LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
#     477                 :          0 :                 }
#     478                 :          0 :             }
#     479                 :          0 :         }
#     480         [ #  # ]:          0 :         for (const std::string &s : methods) {
#     481         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
#     482                 :          0 :         }
#     483                 :            :         // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
#     484                 :            :         /* Authentication:
#     485                 :            :          *   cookie:   hex-encoded ~/.tor/control_auth_cookie
#     486                 :            :          *   password: "password"
#     487                 :            :          */
#     488                 :          0 :         std::string torpassword = gArgs.GetArg("-torpassword", "");
#     489         [ #  # ]:          0 :         if (!torpassword.empty()) {
#     490         [ #  # ]:          0 :             if (methods.count("HASHEDPASSWORD")) {
#     491         [ #  # ]:          0 :                 LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
#     492                 :          0 :                 boost::replace_all(torpassword, "\"", "\\\"");
#     493                 :          0 :                 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     494                 :          0 :             } else {
#     495                 :          0 :                 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
#     496                 :          0 :             }
#     497         [ #  # ]:          0 :         } else if (methods.count("NULL")) {
#     498         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
#     499                 :          0 :             _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     500         [ #  # ]:          0 :         } else if (methods.count("SAFECOOKIE")) {
#     501                 :            :             // Cookie: hexdump -e '32/1 "%02x""\n"'  ~/.tor/control_auth_cookie
#     502         [ #  # ]:          0 :             LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
#     503                 :          0 :             std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
#     504 [ #  # ][ #  # ]:          0 :             if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
#     505                 :            :                 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
#     506                 :          0 :                 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
#     507                 :          0 :                 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
#     508                 :          0 :                 GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
#     509                 :          0 :                 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
#     510                 :          0 :             } else {
#     511         [ #  # ]:          0 :                 if (status_cookie.first) {
#     512                 :          0 :                     LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
#     513                 :          0 :                 } else {
#     514                 :          0 :                     LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
#     515                 :          0 :                 }
#     516                 :          0 :             }
#     517         [ #  # ]:          0 :         } else if (methods.count("HASHEDPASSWORD")) {
#     518                 :          0 :             LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
#     519                 :          0 :         } else {
#     520                 :          0 :             LogPrintf("tor: No supported authentication method\n");
#     521                 :          0 :         }
#     522                 :          0 :     } else {
#     523                 :          0 :         LogPrintf("tor: Requesting protocol info failed\n");
#     524                 :          0 :     }
#     525                 :          0 : }
#     526                 :            : 
#     527                 :            : void TorController::connected_cb(TorControlConnection& _conn)
#     528                 :          0 : {
#     529                 :          0 :     reconnect_timeout = RECONNECT_TIMEOUT_START;
#     530                 :            :     // First send a PROTOCOLINFO command to figure out what authentication is expected
#     531         [ #  # ]:          0 :     if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
#     532                 :          0 :         LogPrintf("tor: Error sending initial protocolinfo command\n");
#     533                 :          0 : }
#     534                 :            : 
#     535                 :            : void TorController::disconnected_cb(TorControlConnection& _conn)
#     536                 :          0 : {
#     537                 :            :     // Stop advertising service when disconnected
#     538         [ #  # ]:          0 :     if (service.IsValid())
#     539                 :          0 :         RemoveLocal(service);
#     540                 :          0 :     service = CService();
#     541         [ #  # ]:          0 :     if (!reconnect)
#     542                 :          0 :         return;
#     543                 :            : 
#     544         [ #  # ]:          0 :     LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
#     545                 :            : 
#     546                 :            :     // Single-shot timer for reconnect. Use exponential backoff.
#     547                 :          0 :     struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
#     548         [ #  # ]:          0 :     if (reconnect_ev)
#     549                 :          0 :         event_add(reconnect_ev, &time);
#     550                 :          0 :     reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
#     551                 :          0 : }
#     552                 :            : 
#     553                 :            : void TorController::Reconnect()
#     554                 :          0 : {
#     555                 :            :     /* Try to reconnect and reestablish if we get booted - for example, Tor
#     556                 :            :      * may be restarting.
#     557                 :            :      */
#     558         [ #  # ]:          0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
#     559                 :          0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
#     560                 :          0 :         LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
#     561                 :          0 :     }
#     562                 :          0 : }
#     563                 :            : 
#     564                 :            : fs::path TorController::GetPrivateKeyFile()
#     565                 :          0 : {
#     566                 :          0 :     return gArgs.GetDataDirNet() / "onion_v3_private_key";
#     567                 :          0 : }
#     568                 :            : 
#     569                 :            : void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
#     570                 :          0 : {
#     571                 :          0 :     TorController *self = static_cast<TorController*>(arg);
#     572                 :          0 :     self->Reconnect();
#     573                 :          0 : }
#     574                 :            : 
#     575                 :            : /****** Thread ********/
#     576                 :            : static struct event_base *gBase;
#     577                 :            : static std::thread torControlThread;
#     578                 :            : 
#     579                 :            : static void TorControlThread(CService onion_service_target)
#     580                 :          0 : {
#     581                 :          0 :     TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
#     582                 :            : 
#     583                 :          0 :     event_base_dispatch(gBase);
#     584                 :          0 : }
#     585                 :            : 
#     586                 :            : void StartTorControl(CService onion_service_target)
#     587                 :          0 : {
#     588                 :          0 :     assert(!gBase);
#     589                 :            : #ifdef WIN32
#     590                 :            :     evthread_use_windows_threads();
#     591                 :            : #else
#     592                 :          0 :     evthread_use_pthreads();
#     593                 :          0 : #endif
#     594                 :          0 :     gBase = event_base_new();
#     595         [ #  # ]:          0 :     if (!gBase) {
#     596                 :          0 :         LogPrintf("tor: Unable to create event_base\n");
#     597                 :          0 :         return;
#     598                 :          0 :     }
#     599                 :            : 
#     600                 :          0 :     torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
#     601                 :          0 :         TorControlThread(onion_service_target);
#     602                 :          0 :     });
#     603                 :          0 : }
#     604                 :            : 
#     605                 :            : void InterruptTorControl()
#     606                 :        663 : {
#     607         [ -  + ]:        663 :     if (gBase) {
#     608                 :          0 :         LogPrintf("tor: Thread interrupt\n");
#     609                 :          0 :         event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
#     610                 :          0 :             event_base_loopbreak(gBase);
#     611                 :          0 :         }, nullptr, nullptr);
#     612                 :          0 :     }
#     613                 :        663 : }
#     614                 :            : 
#     615                 :            : void StopTorControl()
#     616                 :        663 : {
#     617         [ -  + ]:        663 :     if (gBase) {
#     618                 :          0 :         torControlThread.join();
#     619                 :          0 :         event_base_free(gBase);
#     620                 :          0 :         gBase = nullptr;
#     621                 :          0 :     }
#     622                 :        663 : }
#     623                 :            : 
#     624                 :            : CService DefaultOnionServiceTarget()
#     625                 :        621 : {
#     626                 :        621 :     struct in_addr onion_service_target;
#     627                 :        621 :     onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
#     628                 :        621 :     return {onion_service_target, BaseParams().OnionServiceTargetPort()};
#     629                 :        621 : }

Generated by: LCOV version 1.14