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

Generated by: LCOV version 1.16