LCOV - code coverage report
Current view: top level - src - httpserver.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 81.8 % 373 305
Test Date: 2026-05-31 07:57:02 Functions: 97.6 % 41 40
Branches: 50.5 % 519 262

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

Generated by: LCOV version 2.0-1