LCOV - code coverage report
Current view: top level - src - httpserver.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 0.0 % 400 0
Test Date: 2024-11-22 13:43:01 Functions: 0.0 % 47 0
Branches: 0.0 % 513 0

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

Generated by: LCOV version 2.0-1