LCOV - code coverage report
Current view: top level - src - httpserver.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 82.7 % 369 305
Test Date: 2026-02-16 05:51:08 Functions: 97.6 % 41 40
Branches: 50.7 % 515 261

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2015-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <httpserver.h>
       6                 :             : 
       7                 :             : #include <chainparamsbase.h>
       8                 :             : #include <common/args.h>
       9                 :             : #include <common/messages.h>
      10                 :             : #include <compat/compat.h>
      11                 :             : #include <logging.h>
      12                 :             : #include <netbase.h>
      13                 :             : #include <node/interface_ui.h>
      14                 :             : #include <rpc/protocol.h>
      15                 :             : #include <sync.h>
      16                 :             : #include <util/check.h>
      17                 :             : #include <util/signalinterrupt.h>
      18                 :             : #include <util/strencodings.h>
      19                 :             : #include <util/threadnames.h>
      20                 :             : #include <util/threadpool.h>
      21                 :             : #include <util/translation.h>
      22                 :             : 
      23                 :             : #include <condition_variable>
      24                 :             : #include <cstdio>
      25                 :             : #include <cstdlib>
      26                 :             : #include <deque>
      27                 :             : #include <memory>
      28                 :             : #include <optional>
      29                 :             : #include <span>
      30                 :             : #include <string>
      31                 :             : #include <thread>
      32                 :             : #include <unordered_map>
      33                 :             : #include <vector>
      34                 :             : 
      35                 :             : #include <sys/types.h>
      36                 :             : #include <sys/stat.h>
      37                 :             : 
      38                 :             : #include <event2/buffer.h>
      39                 :             : #include <event2/bufferevent.h>
      40                 :             : #include <event2/http.h>
      41                 :             : #include <event2/http_struct.h>
      42                 :             : #include <event2/keyvalq_struct.h>
      43                 :             : #include <event2/thread.h>
      44                 :             : #include <event2/util.h>
      45                 :             : 
      46                 :             : #include <support/events.h>
      47                 :             : 
      48                 :             : using common::InvalidPortErrMsg;
      49                 :             : 
      50                 :             : /** Maximum size of http request (request line + headers) */
      51                 :             : static const size_t MAX_HEADERS_SIZE = 8192;
      52                 :             : 
      53                 :        3385 : struct HTTPPathHandler
      54                 :             : {
      55                 :        2252 :     HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
      56   [ -  +  +  - ]:        4504 :         prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
      57                 :             :     {
      58                 :        2252 :     }
      59                 :             :     std::string prefix;
      60                 :             :     bool exactMatch;
      61                 :             :     HTTPRequestHandler handler;
      62                 :             : };
      63                 :             : 
      64                 :             : /** HTTP module state */
      65                 :             : 
      66                 :             : //! libevent event loop
      67                 :             : static struct event_base* eventBase = nullptr;
      68                 :             : //! HTTP server
      69                 :             : static struct evhttp* eventHTTP = nullptr;
      70                 :             : //! List of subnets to allow RPC connections from
      71                 :             : static std::vector<CSubNet> rpc_allow_subnets;
      72                 :             : //! Handlers for (sub)paths
      73                 :             : static GlobalMutex g_httppathhandlers_mutex;
      74                 :             : static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
      75                 :             : //! Bound listening sockets
      76                 :             : static std::vector<evhttp_bound_socket *> boundSockets;
      77                 :             : //! Http thread pool - future: encapsulate in HttpContext
      78                 :             : static ThreadPool g_threadpool_http("http");
      79                 :             : static int g_max_queue_depth{100};
      80                 :             : 
      81                 :             : /**
      82                 :             :  * @brief Helps keep track of open `evhttp_connection`s with active `evhttp_requests`
      83                 :             :  *
      84                 :             :  */
      85                 :             : class HTTPRequestTracker
      86                 :             : {
      87                 :             : private:
      88                 :             :     mutable Mutex m_mutex;
      89                 :             :     mutable std::condition_variable m_cv;
      90                 :             :     //! For each connection, keep a counter of how many requests are open
      91                 :             :     std::unordered_map<const evhttp_connection*, size_t> m_tracker GUARDED_BY(m_mutex);
      92                 :             : 
      93                 :      204575 :     void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
      94                 :             :     {
      95                 :      204575 :         m_tracker.erase(it);
      96         [ +  + ]:      204575 :         if (m_tracker.empty()) m_cv.notify_all();
      97                 :      204575 :     }
      98                 :             : public:
      99                 :             :     //! Increase request counter for the associated connection by 1
     100                 :      204575 :     void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     101                 :             :     {
     102   [ -  +  -  + ]:      204575 :         const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
     103   [ +  -  +  - ]:      613725 :         WITH_LOCK(m_mutex, ++m_tracker[conn]);
     104                 :      204575 :     }
     105                 :             :     //! Decrease request counter for the associated connection by 1, remove connection if counter is 0
     106                 :      204575 :     void RemoveRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     107                 :             :     {
     108   [ -  +  -  + ]:      204575 :         const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
     109                 :      204575 :         LOCK(m_mutex);
     110                 :      204575 :         auto it{m_tracker.find(conn)};
     111   [ +  -  +  -  :      409150 :         if (it != m_tracker.end() && it->second > 0) {
                   +  - ]
     112         [ +  - ]:      204575 :             if (--(it->second) == 0) RemoveConnectionInternal(it);
     113                 :             :         }
     114                 :      204575 :     }
     115                 :             :     //! Remove a connection entirely
     116                 :        4270 :     void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     117                 :             :     {
     118                 :        4270 :         LOCK(m_mutex);
     119         [ -  + ]:        4270 :         auto it{m_tracker.find(Assert(conn))};
     120   [ -  +  +  - ]:        4270 :         if (it != m_tracker.end()) RemoveConnectionInternal(it);
     121                 :        4270 :     }
     122                 :        1172 :     size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     123                 :             :     {
     124         [ +  - ]:        1172 :         return WITH_LOCK(m_mutex, return m_tracker.size());
     125                 :             :     }
     126                 :             :     //! Wait until there are no more connections with active requests in the tracker
     127                 :        1172 :     void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
     128                 :             :     {
     129                 :        1172 :         WAIT_LOCK(m_mutex, lock);
     130   [ +  +  +  - ]:        1200 :         m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); });
     131                 :        1172 :     }
     132                 :             : };
     133                 :             : //! Track active requests
     134                 :             : static HTTPRequestTracker g_requests;
     135                 :             : 
     136                 :             : /** Check if a network address is allowed to access the HTTP server */
     137                 :      204575 : static bool ClientAllowed(const CNetAddr& netaddr)
     138                 :             : {
     139         [ +  - ]:      204575 :     if (!netaddr.IsValid())
     140                 :             :         return false;
     141         [ +  + ]:      204588 :     for(const CSubNet& subnet : rpc_allow_subnets)
     142         [ +  + ]:      204587 :         if (subnet.Match(netaddr))
     143                 :             :             return true;
     144                 :             :     return false;
     145                 :             : }
     146                 :             : 
     147                 :             : /** Initialize ACL list for HTTP server */
     148                 :        1131 : static bool InitHTTPAllowList()
     149                 :             : {
     150                 :        1131 :     rpc_allow_subnets.clear();
     151   [ +  -  +  -  :        3393 :     rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8);  // always allow IPv4 local subnet
                   +  - ]
     152   [ +  -  +  -  :        3393 :     rpc_allow_subnets.emplace_back(LookupHost("::1", false).value());  // always allow IPv6 localhost
                   +  - ]
     153   [ +  -  +  + ]:        1138 :     for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
     154         [ +  - ]:           7 :         const CSubNet subnet{LookupSubNet(strAllow)};
     155   [ +  -  -  + ]:           7 :         if (!subnet.IsValid()) {
     156         [ #  # ]:           0 :             uiInterface.ThreadSafeMessageBox(
     157   [ #  #  #  # ]:           0 :                 Untranslated(strprintf("Invalid -rpcallowip subnet specification: %s. Valid values are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0.", strAllow)),
     158                 :             :                 CClientUIInterface::MSG_ERROR);
     159                 :           0 :             return false;
     160                 :             :         }
     161         [ +  - ]:           7 :         rpc_allow_subnets.push_back(subnet);
     162                 :        1138 :     }
     163                 :        1131 :     std::string strAllowed;
     164         [ +  + ]:        3400 :     for (const CSubNet& subnet : rpc_allow_subnets)
     165   [ +  -  -  + ]:        6807 :         strAllowed += subnet.ToString() + " ";
     166   [ +  -  +  +  :        1131 :     LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
                   +  - ]
     167                 :        1131 :     return true;
     168                 :        1131 : }
     169                 :             : 
     170                 :             : /** HTTP request method as string - use for logging only */
     171                 :      204558 : std::string RequestMethodString(HTTPRequest::RequestMethod m)
     172                 :             : {
     173   [ +  +  -  -  :      204558 :     switch (m) {
                   -  - ]
     174                 :         737 :     case HTTPRequest::GET:
     175                 :         737 :         return "GET";
     176                 :      203821 :     case HTTPRequest::POST:
     177                 :      203821 :         return "POST";
     178                 :           0 :     case HTTPRequest::HEAD:
     179                 :           0 :         return "HEAD";
     180                 :           0 :     case HTTPRequest::PUT:
     181                 :           0 :         return "PUT";
     182                 :           0 :     case HTTPRequest::UNKNOWN:
     183                 :           0 :         return "unknown";
     184                 :             :     } // no default case, so the compiler can warn about missing cases
     185                 :           0 :     assert(false);
     186                 :             : }
     187                 :             : 
     188                 :             : /** HTTP request callback */
     189                 :      204575 : static void http_request_cb(struct evhttp_request* req, void* arg)
     190                 :             : {
     191                 :      204575 :     evhttp_connection* conn{evhttp_request_get_connection(req)};
     192                 :             :     // Track active requests
     193                 :      204575 :     {
     194                 :      204575 :         g_requests.AddRequest(req);
     195                 :      204575 :         evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) {
     196                 :             :             g_requests.RemoveRequest(req);
     197                 :             :         }, nullptr);
     198                 :      204575 :         evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) {
     199                 :             :             g_requests.RemoveConnection(conn);
     200                 :             :         }, nullptr);
     201                 :             :     }
     202                 :             : 
     203                 :             :     // Disable reading to work around a libevent bug, fixed in 2.1.9
     204                 :             :     // See https://github.com/libevent/libevent/commit/5ff8eb26371c4dc56f384b2de35bea2d87814779
     205                 :             :     // and https://github.com/bitcoin/bitcoin/pull/11593.
     206   [ +  -  -  + ]:      204575 :     if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
     207         [ #  # ]:           0 :         if (conn) {
     208                 :           0 :             bufferevent* bev = evhttp_connection_get_bufferevent(conn);
     209         [ #  # ]:           0 :             if (bev) {
     210                 :           0 :                 bufferevent_disable(bev, EV_READ);
     211                 :             :             }
     212                 :             :         }
     213                 :             :     }
     214                 :      204575 :     auto hreq{std::make_unique<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))};
     215                 :             : 
     216                 :             :     // Early address-based allow check
     217   [ +  -  +  -  :      204575 :     if (!ClientAllowed(hreq->GetPeer())) {
                   +  + ]
     218   [ +  -  +  -  :           2 :         LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
          +  -  +  -  +  
                      - ]
     219                 :             :                  hreq->GetPeer().ToStringAddrPort());
     220         [ +  - ]:           1 :         hreq->WriteReply(HTTP_FORBIDDEN);
     221                 :             :         return;
     222                 :             :     }
     223                 :             : 
     224                 :             :     // Early reject unknown HTTP methods
     225   [ +  -  -  + ]:      204574 :     if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
     226   [ #  #  #  #  :           0 :         LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
          #  #  #  #  #  
                      # ]
     227                 :             :                  hreq->GetPeer().ToStringAddrPort());
     228         [ #  # ]:           0 :         hreq->WriteReply(HTTP_BAD_METHOD);
     229                 :             :         return;
     230                 :             :     }
     231                 :             : 
     232   [ +  -  +  +  :      613690 :     LogDebug(BCLog::HTTP, "Received a %s request for %s from %s\n",
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
     233                 :             :              RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort());
     234                 :             : 
     235                 :             :     // Find registered handler for prefix
     236         [ +  - ]:      204574 :     std::string strURI = hreq->GetURI();
     237         [ +  - ]:      204574 :     std::string path;
     238         [ +  - ]:      204574 :     LOCK(g_httppathhandlers_mutex);
     239                 :      204574 :     std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
     240                 :      204574 :     std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
     241         [ +  + ]:      230160 :     for (; i != iend; ++i) {
     242                 :      230158 :         bool match = false;
     243         [ +  + ]:      230158 :         if (i->exactMatch)
     244                 :      204574 :             match = (strURI == i->prefix);
     245                 :             :         else
     246   [ -  +  -  + ]:       25584 :             match = strURI.starts_with(i->prefix);
     247         [ +  + ]:      230158 :         if (match) {
     248   [ -  +  +  - ]:      204572 :             path = strURI.substr(i->prefix.size());
     249                 :      204572 :             break;
     250                 :             :         }
     251                 :             :     }
     252                 :             : 
     253                 :             :     // Dispatch to worker thread
     254         [ +  + ]:      204574 :     if (i != iend) {
     255   [ +  -  +  + ]:      204572 :         if (static_cast<int>(g_threadpool_http.WorkQueueSize()) >= g_max_queue_depth) {
     256         [ +  - ]:           1 :             LogWarning("Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
     257         [ +  - ]:           1 :             hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
     258         [ +  - ]:           1 :             return;
     259                 :             :         }
     260                 :             : 
     261                 :      204571 :         auto item = [req = std::move(hreq), in_path = std::move(path), fn = i->handler]() {
     262         [ +  - ]:      204571 :             std::string err_msg;
     263                 :      204571 :             try {
     264         [ +  - ]:      204571 :                 fn(req.get(), in_path);
     265                 :      204571 :                 return;
     266         [ -  - ]:           0 :             } catch (const std::exception& e) {
     267   [ -  -  -  - ]:           0 :                 LogWarning("Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(), e.what());
     268         [ -  - ]:           0 :                 err_msg = e.what();
     269                 :           0 :             } catch (...) {
     270   [ -  -  -  - ]:           0 :                 LogWarning("Unknown error while processing request for '%s'", req->GetURI());
     271         [ -  - ]:           0 :                 err_msg = "unknown error";
     272         [ -  - ]:           0 :             }
     273                 :             :             // Reply so the client doesn't hang waiting for the response.
     274   [ -  -  -  -  :           0 :             req->WriteHeader("Connection", "close");
                   -  - ]
     275                 :             :             // TODO: Implement specific error formatting for the REST and JSON-RPC servers responses.
     276   [ -  -  -  - ]:           0 :             req->WriteReply(HTTP_INTERNAL_SERVER_ERROR, err_msg);
     277         [ +  - ]:      409142 :         };
     278                 :             : 
     279         [ +  - ]:      204571 :         [[maybe_unused]] auto _{g_threadpool_http.Submit(std::move(item))};
     280                 :      204571 :     } else {
     281         [ +  - ]:           2 :         hreq->WriteReply(HTTP_NOT_FOUND);
     282                 :             :     }
     283                 :      204575 : }
     284                 :             : 
     285                 :             : /** Callback to reject HTTP requests after shutdown. */
     286                 :           0 : static void http_reject_request_cb(struct evhttp_request* req, void*)
     287                 :             : {
     288         [ #  # ]:           0 :     LogDebug(BCLog::HTTP, "Rejecting request while shutting down\n");
     289                 :           0 :     evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
     290                 :           0 : }
     291                 :             : 
     292                 :             : /** Event dispatcher thread */
     293                 :        1119 : static void ThreadHTTP(struct event_base* base)
     294                 :             : {
     295         [ +  - ]:        1119 :     util::ThreadRename("http");
     296         [ +  + ]:        1119 :     LogDebug(BCLog::HTTP, "Entering http event loop\n");
     297                 :        1119 :     event_base_dispatch(base);
     298                 :             :     // Event loop will be interrupted by InterruptHTTPServer()
     299         [ +  + ]:        1119 :     LogDebug(BCLog::HTTP, "Exited http event loop\n");
     300                 :        1119 : }
     301                 :             : 
     302                 :             : /** Bind HTTP server to specified addresses */
     303                 :        1131 : static bool HTTPBindAddresses(struct evhttp* http)
     304                 :             : {
     305         [ +  - ]:        1131 :     uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
     306                 :        1131 :     std::vector<std::pair<std::string, uint16_t>> endpoints;
     307                 :             : 
     308                 :             :     // Determine what addresses to bind to
     309                 :             :     // To prevent misconfiguration and accidental exposure of the RPC
     310                 :             :     // interface, require -rpcallowip and -rpcbind to both be specified
     311                 :             :     // together. If either is missing, ignore both values, bind to localhost
     312                 :             :     // instead, and log warnings.
     313   [ +  -  +  -  :        2276 :     if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
          +  +  +  -  +  
          -  +  -  +  +  
          +  +  -  -  -  
                -  -  - ]
     314         [ +  - ]:        1124 :         endpoints.emplace_back("::1", http_port);
     315         [ +  - ]:        1124 :         endpoints.emplace_back("127.0.0.1", http_port);
     316   [ +  -  +  -  :        1124 :         if (!gArgs.GetArgs("-rpcallowip").empty()) {
                   -  + ]
     317         [ #  # ]:           0 :             LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
     318                 :             :         }
     319   [ +  -  +  -  :        1124 :         if (!gArgs.GetArgs("-rpcbind").empty()) {
                   -  + ]
     320         [ #  # ]:           0 :             LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
     321                 :             :         }
     322                 :             :     } else { // Specific bind addresses
     323   [ +  -  +  -  :          25 :         for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
                   +  + ]
     324                 :          11 :             uint16_t port{http_port};
     325         [ -  + ]:          11 :             std::string host;
     326   [ -  +  +  -  :          11 :             if (!SplitHostPort(strRPCBind, port, host)) {
                   -  + ]
     327   [ #  #  #  #  :           0 :                 LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
                   #  # ]
     328                 :           0 :                 return false;
     329                 :             :             }
     330         [ +  - ]:          11 :             endpoints.emplace_back(host, port);
     331                 :          18 :         }
     332                 :             :     }
     333                 :             : 
     334                 :             :     // Bind addresses
     335         [ +  + ]:        3390 :     for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
     336         [ +  - ]:        2259 :         LogInfo("Binding RPC on address %s port %i", i->first, i->second);
     337   [ +  -  +  - ]:        2259 :         evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
     338         [ +  + ]:        2259 :         if (bind_handle) {
     339   [ +  -  +  - ]:        1135 :             const std::optional<CNetAddr> addr{LookupHost(i->first, false)};
     340   [ +  -  +  -  :        1135 :             if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
             +  -  -  + ]
     341         [ #  # ]:           0 :                 LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
     342                 :             :             }
     343                 :             :             // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
     344         [ +  - ]:        1135 :             evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle);
     345                 :        1135 :             int one = 1;
     346         [ -  + ]:        1135 :             if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&one), sizeof(one)) == SOCKET_ERROR) {
     347         [ #  # ]:           0 :                 LogInfo("WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
     348                 :             :             }
     349         [ +  - ]:        1135 :             boundSockets.push_back(bind_handle);
     350                 :        1135 :         } else {
     351         [ +  - ]:        1124 :             LogWarning("Binding RPC on address %s port %i failed.", i->first, i->second);
     352                 :             :         }
     353                 :             :     }
     354                 :        1131 :     return !boundSockets.empty();
     355                 :        1131 : }
     356                 :             : 
     357                 :             : /** libevent event log callback */
     358                 :        1124 : static void libevent_log_cb(int severity, const char *msg)
     359                 :             : {
     360   [ -  -  +  - ]:        1124 :     switch (severity) {
     361                 :           0 :     case EVENT_LOG_DEBUG:
     362         [ #  # ]:           0 :         LogDebug(BCLog::LIBEVENT, "%s", msg);
     363                 :             :         break;
     364                 :           0 :     case EVENT_LOG_MSG:
     365                 :           0 :         LogInfo("libevent: %s", msg);
     366                 :           0 :         break;
     367                 :        1124 :     case EVENT_LOG_WARN:
     368                 :        1124 :         LogWarning("libevent: %s", msg);
     369                 :        1124 :         break;
     370                 :           0 :     default: // EVENT_LOG_ERR and others are mapped to error
     371                 :           0 :         LogError("libevent: %s", msg);
     372                 :           0 :         break;
     373                 :             :     }
     374                 :        1124 : }
     375                 :             : 
     376                 :        1131 : bool InitHTTPServer(const util::SignalInterrupt& interrupt)
     377                 :             : {
     378         [ +  - ]:        1131 :     if (!InitHTTPAllowList())
     379                 :             :         return false;
     380                 :             : 
     381                 :             :     // Redirect libevent's logging to our own log
     382                 :        1131 :     event_set_log_callback(&libevent_log_cb);
     383                 :             :     // Update libevent's log handling.
     384                 :        1131 :     UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT));
     385                 :             : 
     386                 :             : #ifdef WIN32
     387                 :             :     evthread_use_windows_threads();
     388                 :             : #else
     389                 :        1131 :     evthread_use_pthreads();
     390                 :             : #endif
     391                 :             : 
     392                 :        1131 :     raii_event_base base_ctr = obtain_event_base();
     393                 :             : 
     394                 :             :     /* Create a new evhttp object to handle requests. */
     395         [ +  - ]:        1131 :     raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
     396         [ -  + ]:        1131 :     struct evhttp* http = http_ctr.get();
     397         [ -  + ]:        1131 :     if (!http) {
     398         [ #  # ]:           0 :         LogError("Couldn't create evhttp. Exiting.");
     399                 :             :         return false;
     400                 :             :     }
     401                 :             : 
     402   [ +  -  +  -  :        1131 :     evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
                   +  - ]
     403         [ +  - ]:        1131 :     evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
     404         [ +  - ]:        1131 :     evhttp_set_max_body_size(http, MAX_SIZE);
     405         [ +  - ]:        1131 :     evhttp_set_gencb(http, http_request_cb, (void*)&interrupt);
     406                 :             : 
     407   [ +  -  -  + ]:        1131 :     if (!HTTPBindAddresses(http)) {
     408         [ #  # ]:           0 :         LogError("Unable to bind any endpoint for RPC server");
     409                 :             :         return false;
     410                 :             :     }
     411                 :             : 
     412   [ +  -  +  +  :        1131 :     LogDebug(BCLog::HTTP, "Initialized HTTP server\n");
                   +  - ]
     413   [ +  -  +  -  :        2262 :     g_max_queue_depth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
                   +  - ]
     414   [ +  -  +  +  :        1131 :     LogDebug(BCLog::HTTP, "set work queue of depth %d\n", g_max_queue_depth);
                   +  - ]
     415                 :             : 
     416                 :             :     // transfer ownership to eventBase/HTTP via .release()
     417                 :        1131 :     eventBase = base_ctr.release();
     418                 :        1131 :     eventHTTP = http_ctr.release();
     419                 :        1131 :     return true;
     420         [ -  + ]:        1131 : }
     421                 :             : 
     422                 :        1131 : void UpdateHTTPServerLogging(bool enable) {
     423         [ -  + ]:        1131 :     if (enable) {
     424                 :           0 :         event_enable_debug_logging(EVENT_DBG_ALL);
     425                 :             :     } else {
     426                 :        1131 :         event_enable_debug_logging(EVENT_DBG_NONE);
     427                 :             :     }
     428                 :        1131 : }
     429                 :             : 
     430                 :             : static std::thread g_thread_http;
     431                 :             : 
     432                 :        1119 : void StartHTTPServer()
     433                 :             : {
     434   [ +  -  +  - ]:        2238 :     int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
     435                 :        1119 :     LogInfo("Starting HTTP server with %d worker threads\n", rpcThreads);
     436                 :        1119 :     g_threadpool_http.Start(rpcThreads);
     437                 :        1119 :     g_thread_http = std::thread(ThreadHTTP, eventBase);
     438                 :        1119 : }
     439                 :             : 
     440                 :        1172 : void InterruptHTTPServer()
     441                 :             : {
     442         [ +  + ]:        1172 :     LogDebug(BCLog::HTTP, "Interrupting HTTP server\n");
     443         [ +  + ]:        1172 :     if (eventHTTP) {
     444                 :             :         // Reject requests on current connections
     445                 :        1131 :         evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
     446                 :             :     }
     447                 :             :     // Interrupt pool after disabling requests
     448                 :        1172 :     g_threadpool_http.Interrupt();
     449                 :        1172 : }
     450                 :             : 
     451                 :        1172 : void StopHTTPServer()
     452                 :             : {
     453         [ +  + ]:        1172 :     LogDebug(BCLog::HTTP, "Stopping HTTP server\n");
     454                 :             : 
     455         [ +  + ]:        1172 :     LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
     456                 :        1172 :     g_threadpool_http.Stop();
     457                 :             : 
     458                 :             :     // Unlisten sockets, these are what make the event loop running, which means
     459                 :             :     // that after this and all connections are closed the event loop will quit.
     460         [ +  + ]:        2307 :     for (evhttp_bound_socket *socket : boundSockets) {
     461                 :        1135 :         evhttp_del_accept_socket(eventHTTP, socket);
     462                 :             :     }
     463         [ +  + ]:        1172 :     boundSockets.clear();
     464                 :        1172 :     {
     465         [ +  + ]:        1172 :         if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) {
     466         [ +  - ]:          28 :             LogDebug(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections);
     467                 :             :         }
     468                 :        1172 :         g_requests.WaitUntilEmpty();
     469                 :             :     }
     470         [ +  + ]:        1172 :     if (eventHTTP) {
     471                 :             :         // Schedule a callback to call evhttp_free in the event base thread, so
     472                 :             :         // that evhttp_free does not need to be called again after the handling
     473                 :             :         // of unfinished request connections that follows.
     474                 :        1131 :         event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
     475                 :             :             evhttp_free(eventHTTP);
     476                 :             :             eventHTTP = nullptr;
     477                 :             :         }, nullptr, nullptr);
     478                 :             :     }
     479         [ +  + ]:        1172 :     if (eventBase) {
     480         [ +  + ]:        1131 :         LogDebug(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
     481         [ +  + ]:        1131 :         if (g_thread_http.joinable()) g_thread_http.join();
     482                 :        1131 :         event_base_free(eventBase);
     483                 :        1131 :         eventBase = nullptr;
     484                 :             :     }
     485         [ +  + ]:        1172 :     LogDebug(BCLog::HTTP, "Stopped HTTP server\n");
     486                 :        1172 : }
     487                 :             : 
     488                 :        1119 : struct event_base* EventBase()
     489                 :             : {
     490                 :        1119 :     return eventBase;
     491                 :             : }
     492                 :             : 
     493                 :      204575 : static void httpevent_callback_fn(evutil_socket_t, short, void* data)
     494                 :             : {
     495                 :             :     // Static handler: simply call inner handler
     496                 :      204575 :     HTTPEvent *self = static_cast<HTTPEvent*>(data);
     497                 :      204575 :     self->handler();
     498         [ +  - ]:      204575 :     if (self->deleteWhenTriggered)
     499                 :      204575 :         delete self;
     500                 :      204575 : }
     501                 :             : 
     502                 :      204575 : HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
     503                 :      204575 :     deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
     504                 :             : {
     505         [ +  - ]:      204575 :     ev = event_new(base, -1, 0, httpevent_callback_fn, this);
     506         [ -  + ]:      204575 :     assert(ev);
     507                 :      204575 : }
     508                 :      204575 : HTTPEvent::~HTTPEvent()
     509                 :             : {
     510                 :      204575 :     event_free(ev);
     511                 :      204575 : }
     512                 :      204575 : void HTTPEvent::trigger(struct timeval* tv)
     513                 :             : {
     514         [ +  - ]:      204575 :     if (tv == nullptr)
     515                 :      204575 :         event_active(ev, 0, 0); // immediately trigger event in main thread
     516                 :             :     else
     517                 :           0 :         evtimer_add(ev, tv); // trigger after timeval passed
     518                 :      204575 : }
     519                 :      204575 : HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent)
     520                 :      204575 :     : req(_req), m_interrupt(interrupt), replySent(_replySent)
     521                 :             : {
     522                 :      204575 : }
     523                 :             : 
     524                 :      204575 : HTTPRequest::~HTTPRequest()
     525                 :             : {
     526         [ -  + ]:      204575 :     if (!replySent) {
     527                 :             :         // Keep track of whether reply was sent to avoid request leaks
     528                 :           0 :         LogWarning("Unhandled HTTP request");
     529                 :           0 :         WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
     530                 :             :     }
     531                 :             :     // evhttpd cleans up the request, as long as a reply was sent.
     532                 :      204575 : }
     533                 :             : 
     534                 :      203830 : std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
     535                 :             : {
     536                 :      203830 :     const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
     537         [ -  + ]:      203830 :     assert(headers);
     538                 :      203830 :     const char* val = evhttp_find_header(headers, hdr.c_str());
     539         [ +  - ]:      203830 :     if (val)
     540                 :      203830 :         return std::make_pair(true, val);
     541                 :             :     else
     542                 :           0 :         return std::make_pair(false, "");
     543                 :             : }
     544                 :             : 
     545                 :      203830 : std::string HTTPRequest::ReadBody()
     546                 :             : {
     547                 :      203830 :     struct evbuffer* buf = evhttp_request_get_input_buffer(req);
     548         [ -  + ]:      203830 :     if (!buf)
     549                 :           0 :         return "";
     550                 :      203830 :     size_t size = evbuffer_get_length(buf);
     551                 :             :     /** Trivial implementation: if this is ever a performance bottleneck,
     552                 :             :      * internal copying can be avoided in multi-segment buffers by using
     553                 :             :      * evbuffer_peek and an awkward loop. Though in that case, it'd be even
     554                 :             :      * better to not copy into an intermediate string but use a stream
     555                 :             :      * abstraction to consume the evbuffer on the fly in the parsing algorithm.
     556                 :             :      */
     557                 :      203830 :     const char* data = (const char*)evbuffer_pullup(buf, size);
     558         [ +  + ]:      203830 :     if (!data) // returns nullptr in case of empty buffer
     559                 :          18 :         return "";
     560                 :      203812 :     std::string rv(data, size);
     561         [ +  - ]:      203812 :     evbuffer_drain(buf, size);
     562                 :      203812 :     return rv;
     563                 :      203812 : }
     564                 :             : 
     565                 :      205557 : void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
     566                 :             : {
     567                 :      205557 :     struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
     568         [ -  + ]:      205557 :     assert(headers);
     569                 :      205557 :     evhttp_add_header(headers, hdr.c_str(), value.c_str());
     570                 :      205557 : }
     571                 :             : 
     572                 :             : /** Closure sent to main thread to request a reply to be sent to
     573                 :             :  * a HTTP request.
     574                 :             :  * Replies must be sent in the main loop in the main http thread,
     575                 :             :  * this cannot be done from worker threads.
     576                 :             :  */
     577                 :      204575 : void HTTPRequest::WriteReply(int nStatus, std::span<const std::byte> reply)
     578                 :             : {
     579   [ +  -  -  + ]:      204575 :     assert(!replySent && req);
     580         [ +  + ]:      204575 :     if (m_interrupt) {
     581   [ +  -  +  - ]:        2010 :         WriteHeader("Connection", "close");
     582                 :             :     }
     583                 :             :     // Send event to main http thread to send reply message
     584                 :      204575 :     struct evbuffer* evb = evhttp_request_get_output_buffer(req);
     585         [ -  + ]:      204575 :     assert(evb);
     586                 :      204575 :     evbuffer_add(evb, reply.data(), reply.size());
     587                 :      204575 :     auto req_copy = req;
     588         [ +  - ]:      204575 :     HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
     589                 :      204575 :         evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
     590                 :             :         // Re-enable reading from the socket. This is the second part of the libevent
     591                 :             :         // workaround above.
     592   [ +  -  -  + ]:      204575 :         if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
     593                 :           0 :             evhttp_connection* conn = evhttp_request_get_connection(req_copy);
     594         [ #  # ]:           0 :             if (conn) {
     595                 :           0 :                 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
     596         [ #  # ]:           0 :                 if (bev) {
     597                 :           0 :                     bufferevent_enable(bev, EV_READ | EV_WRITE);
     598                 :             :                 }
     599                 :             :             }
     600                 :             :         }
     601         [ +  - ]:      204575 :     });
     602                 :      204575 :     ev->trigger(nullptr);
     603                 :      204575 :     replySent = true;
     604                 :      204575 :     req = nullptr; // transferred back to main thread
     605                 :      204575 : }
     606                 :             : 
     607                 :      612964 : CService HTTPRequest::GetPeer() const
     608                 :             : {
     609                 :      612964 :     evhttp_connection* con = evhttp_request_get_connection(req);
     610                 :      612964 :     CService peer;
     611         [ +  - ]:      612964 :     if (con) {
     612                 :             :         // evhttp retains ownership over returned address string
     613                 :      612964 :         const char* address = "";
     614                 :      612964 :         uint16_t port = 0;
     615                 :             : 
     616                 :             : #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
     617                 :             :         evhttp_connection_get_peer(con, &address, &port);
     618                 :             : #else
     619         [ +  - ]:      612964 :         evhttp_connection_get_peer(con, (char**)&address, &port);
     620                 :             : #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
     621                 :             : 
     622   [ +  -  +  -  :     1225928 :         peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port));
             +  -  +  - ]
     623                 :             :     }
     624                 :      612964 :     return peer;
     625                 :           0 : }
     626                 :             : 
     627                 :      612940 : std::string HTTPRequest::GetURI() const
     628                 :             : {
     629                 :      612940 :     return evhttp_request_get_uri(req);
     630                 :             : }
     631                 :             : 
     632                 :      612963 : HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const
     633                 :             : {
     634   [ +  -  -  -  :      612963 :     switch (evhttp_request_get_command(req)) {
                      + ]
     635                 :             :     case EVHTTP_REQ_GET:
     636                 :             :         return GET;
     637                 :      611488 :     case EVHTTP_REQ_POST:
     638                 :      611488 :         return POST;
     639                 :           0 :     case EVHTTP_REQ_HEAD:
     640                 :           0 :         return HEAD;
     641                 :           0 :     case EVHTTP_REQ_PUT:
     642                 :           0 :         return PUT;
     643                 :           0 :     default:
     644                 :           0 :         return UNKNOWN;
     645                 :             :     }
     646                 :             : }
     647                 :             : 
     648                 :          85 : std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const
     649                 :             : {
     650                 :          85 :     const char* uri{evhttp_request_get_uri(req)};
     651                 :             : 
     652                 :          85 :     return GetQueryParameterFromUri(uri, key);
     653                 :             : }
     654                 :             : 
     655                 :          93 : std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key)
     656                 :             : {
     657                 :          93 :     evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
     658         [ +  + ]:          93 :     if (!uri_parsed) {
     659         [ +  - ]:           6 :         throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters");
     660                 :             :     }
     661                 :          87 :     const char* query{evhttp_uri_get_query(uri_parsed)};
     662                 :          87 :     std::optional<std::string> result;
     663                 :             : 
     664         [ +  + ]:          87 :     if (query) {
     665                 :             :         // Parse the query string into a key-value queue and iterate over it
     666                 :          80 :         struct evkeyvalq params_q;
     667         [ +  - ]:          80 :         evhttp_parse_query_str(query, &params_q);
     668                 :             : 
     669         [ +  + ]:         112 :         for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) {
     670         [ +  + ]:         104 :             if (param->key == key) {
     671         [ +  - ]:          72 :                 result = param->value;
     672                 :             :                 break;
     673                 :             :             }
     674                 :             :         }
     675         [ +  - ]:          80 :         evhttp_clear_headers(&params_q);
     676                 :             :     }
     677         [ +  - ]:          87 :     evhttp_uri_free(uri_parsed);
     678                 :             : 
     679                 :          87 :     return result;
     680                 :           0 : }
     681                 :             : 
     682                 :        2252 : void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
     683                 :             : {
     684         [ +  + ]:        2252 :     LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
     685                 :        2252 :     LOCK(g_httppathhandlers_mutex);
     686         [ +  - ]:        2252 :     pathHandlers.emplace_back(prefix, exactMatch, handler);
     687                 :        2252 : }
     688                 :             : 
     689                 :       18752 : void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
     690                 :             : {
     691                 :       18752 :     LOCK(g_httppathhandlers_mutex);
     692                 :       18752 :     std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
     693                 :       18752 :     std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
     694         [ +  + ]:       18752 :     for (; i != iend; ++i)
     695   [ +  -  -  + ]:        2252 :         if (i->prefix == prefix && i->exactMatch == exactMatch)
     696                 :             :             break;
     697         [ +  + ]:       18752 :     if (i != iend)
     698                 :             :     {
     699   [ +  -  +  +  :        2252 :         LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
                   +  - ]
     700                 :        2252 :         pathHandlers.erase(i);
     701                 :             :     }
     702                 :       18752 : }
        

Generated by: LCOV version 2.0-1