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

Generated by: LCOV version 2.0-1