LCOV - code coverage report
Current view: top level - src - httpserver.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 3.8 % 394 15
Test Date: 2024-08-28 04:44:32 Functions: 2.1 % 47 1
Branches: 2.6 % 501 13

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

Generated by: LCOV version 2.0-1