LCOV - code coverage report
Current view: top level - src - httpserver.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 16.2 % 37 6
Test Date: 2026-08-29 05:53:03 Functions: 10.0 % 10 1
Branches: 4.8 % 84 4

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2015-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #ifndef BITCOIN_HTTPSERVER_H
       6                 :             : #define BITCOIN_HTTPSERVER_H
       7                 :             : 
       8                 :             : #include <atomic>
       9                 :             : #include <functional>
      10                 :             : #include <memory>
      11                 :             : #include <optional>
      12                 :             : #include <span>
      13                 :             : #include <stdexcept>
      14                 :             : #include <string>
      15                 :             : #include <vector>
      16                 :             : 
      17                 :             : #include <netaddress.h>
      18                 :             : #include <rpc/protocol.h>
      19                 :             : #include <util/byte_units.h>
      20                 :             : #include <util/expected.h>
      21                 :             : #include <util/sock.h>
      22                 :             : #include <util/strencodings.h>
      23                 :             : #include <util/string.h>
      24                 :             : #include <util/threadinterrupt.h>
      25                 :             : #include <util/time.h>
      26                 :             : 
      27                 :             : namespace util {
      28                 :             : class SignalInterrupt;
      29                 :             : } // namespace util
      30                 :             : 
      31                 :             : /**
      32                 :             :  * The default value for `-rpcthreads`. This number of threads will be created at startup.
      33                 :             :  */
      34                 :             : inline constexpr int DEFAULT_HTTP_THREADS=16;
      35                 :             : 
      36                 :             : /**
      37                 :             :  * The default value for `-rpcworkqueue`. This is the maximum depth of the work queue,
      38                 :             :  * we don't allocate this number of work queue items upfront.
      39                 :             :  */
      40                 :             : inline constexpr int DEFAULT_HTTP_WORKQUEUE=64;
      41                 :             : 
      42                 :             : inline constexpr int DEFAULT_HTTP_SERVER_TIMEOUT=30;
      43                 :             : 
      44                 :             : /**
      45                 :             :  * Maximum number of connected HTTP clients
      46                 :             :  */
      47                 :             : inline constexpr int DEFAULT_MAX_HTTP_CONNECTIONS = 16;
      48                 :             : 
      49                 :             : enum class HTTPRequestMethod {
      50                 :             :     UNKNOWN,
      51                 :             :     GET,
      52                 :             :     POST,
      53                 :             :     HEAD,
      54                 :             :     PUT
      55                 :             : };
      56                 :             : 
      57                 :             : class HTTPRequest;
      58                 :             : 
      59                 :             : /** Handler for requests to a certain HTTP path */
      60                 :             : using HTTPRequestHandler = std::function<void(HTTPRequest* req, const std::string&)>;
      61                 :             : 
      62                 :             : /** Register handler for prefix.
      63                 :             :  * If multiple handlers match a prefix, the first-registered one will
      64                 :             :  * be invoked.
      65                 :             :  */
      66                 :             : void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler);
      67                 :             : /** Unregister handler for prefix */
      68                 :             : void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch);
      69                 :             : 
      70                 :             : namespace bitcoin_http {
      71                 :             : //! Shortest valid request line, used by libevent in evhttp_parse_request_line()
      72                 :             : inline constexpr size_t MIN_REQUEST_LINE_LENGTH = std::string_view("GET / HTTP/1.0").size();
      73                 :             : 
      74                 :             : //! Maximum size of each headers line in an HTTP request,
      75                 :             : //! also the maximum size of all headers total.
      76                 :             : //! See https://github.com/bitcoin/bitcoin/pull/6859
      77                 :             : //! And libevent http.c evhttp_parse_headers_()
      78                 :             : inline constexpr size_t MAX_HEADERS_SIZE{8192};
      79                 :             : 
      80                 :             : //! Maximum size of an HTTP request body
      81                 :             : inline constexpr uint64_t MAX_BODY_SIZE{32_MiB};
      82                 :             : 
      83                 :             : //! Thrown when a request body exceeds MAX_BODY_SIZE (or *will* exceed, in chunked transfer)
      84                 :             : //! so the server can reply with more specific code 413 (content too large) vs general 400 (bad request)
      85                 :             : struct ContentTooLargeError : std::runtime_error {
      86   [ #  #  #  # ]:           0 :     using std::runtime_error::runtime_error;
      87                 :             : };
      88                 :             : } // namespace bitcoin_http
      89                 :             : 
      90         [ #  # ]:         312 : class HTTPHeaders
      91                 :             : {
      92                 :             : public:
      93                 :             :     /**
      94                 :             :      * @param[in] key The field-name of the header to search for
      95                 :             :      * @returns The value of the first header that matches the provided key
      96                 :             :      *          nullopt if key is not found
      97                 :             :      */
      98                 :             :     std::optional<std::string> FindFirst(std::string_view key) const;
      99                 :             :     /**
     100                 :             :      * @param[in] key The field-name of the header to search for
     101                 :             :      * @returns Views into all values matching the provided key (valid while this object is alive)
     102                 :             :      */
     103                 :             :     std::vector<std::string_view> FindAll(std::string_view key) const;
     104                 :             :     void Write(std::string&& key, std::string&& value);
     105                 :             :     /**
     106                 :             :      * @param[in] key The field-name of the header to search for and delete
     107                 :             :      */
     108                 :             :     void RemoveAll(std::string_view key);
     109                 :             :     /**
     110                 :             :      * @param[in] reader A LineReader instance initialized with the client's receive buffer.
     111                 :             :      * @param[in] write  Whether or not to write the parsed data to the object after validation.
     112                 :             :      * @returns false if LineReader hits the end of the buffer before reading an
     113                 :             :      *                \n, meaning that we are still waiting on more data from the client.
     114                 :             :      *          true  after reading an entire HTTP headers section, terminated
     115                 :             :      *                by an empty line and \n.
     116                 :             :      * @throws on exceeded read limit and on bad headers syntax (e.g. no ":" in a line)
     117                 :             :      */
     118                 :             :     bool Read(util::LineReader& reader, bool write = true);
     119                 :             :     std::string Stringify() const;
     120                 :             : 
     121                 :             : private:
     122                 :             :     /**
     123                 :             :      * Headers can have duplicate field names, so we use a vector of key-value pairs instead of a map.
     124                 :             :      * https://httpwg.org/specs/rfc9110.html#rfc.section.5.2
     125                 :             :      */
     126                 :             :     std::vector<std::pair<std::string, std::string>> m_headers;
     127                 :             : 
     128                 :             :     //! Track total bytes consumed in Read() for limit checks
     129                 :             :     size_t m_consumed{0};
     130                 :             : };
     131                 :             : 
     132         [ #  # ]:         312 : struct HTTPVersion {
     133                 :             :     /**
     134                 :             :      * Default HTTP protocol version 1.1 is used by error responses
     135                 :             :      * when a request is unreadable.
     136                 :             :      */
     137                 :             :     /// @{
     138                 :             :     uint8_t major{1};
     139                 :             :     uint8_t minor{1};
     140                 :             :     /// @}
     141                 :             : };
     142                 :             : 
     143                 :           0 : struct HTTPResponse {
     144                 :             :     HTTPVersion version;
     145                 :             :     HTTPStatusCode status{HTTP_INTERNAL_SERVER_ERROR};
     146                 :             :     HTTPHeaders headers;
     147                 :             : 
     148                 :             :     std::string StringifyHeaders() const;
     149                 :             : };
     150                 :             : 
     151                 :             : class HTTPRemoteClient;
     152                 :             : 
     153                 :             : class HTTPRequest
     154                 :             : {
     155                 :             : public:
     156         [ #  # ]:           0 :     explicit HTTPRequest(const std::shared_ptr<HTTPRemoteClient>& client) : m_client{client} {}
     157                 :             :     //! Construct with a null client for unit tests
     158                 :         312 :     explicit HTTPRequest() : m_client{} {}
     159                 :             : 
     160                 :             :     /**
     161                 :             :      * Methods that attempt to parse HTTP request fields line-by-line
     162                 :             :      * from a receive buffer.
     163                 :             :      * @param[in]   reader  A LineReader object constructed over a span of data.
     164                 :             :      * @returns     true    If the request field was parsed.
     165                 :             :      *              false   If there was not enough data in the buffer to complete the field.
     166                 :             :      * @throws      std::runtime_error if data is invalid.
     167                 :             :      */
     168                 :             :     /// @{
     169                 :             :     bool LoadControlData(util::LineReader& reader);
     170                 :             :     bool LoadHeaders(util::LineReader& reader);
     171                 :             :     bool LoadBody(util::LineReader& reader);
     172                 :             :     /// @}
     173                 :             : 
     174                 :             :     void WriteReply(HTTPStatusCode status, std::span<const std::byte> reply_body = {});
     175                 :           0 :     void WriteReply(HTTPStatusCode status, std::string_view reply_body_view)
     176                 :             :     {
     177                 :           0 :         WriteReply(status, std::as_bytes(std::span{reply_body_view}));
     178                 :           0 :     }
     179                 :             : 
     180                 :             :     const HTTPVersion& GetVersion() const { return m_version; }
     181                 :             :     std::shared_ptr<HTTPRemoteClient> GetClient() const { return m_client.lock(); }
     182                 :             : 
     183                 :             :     // These methods reimplement the API from http_libevent::HTTPRequest
     184                 :             :     // for downstream JSONRPC and REST modules.
     185         [ -  + ]:         188 :     std::string GetURI() const { return m_target; }
           [ #  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     186                 :             :     CService GetPeer() const;
     187 [ #  # ][ +  - ]:          94 :     HTTPRequestMethod GetRequestMethod() const { return m_method; }
           [ #  #  #  # ]
     188                 :             :     std::optional<std::string> GetQueryParameter(std::string_view key) const;
     189                 :             :     std::optional<std::string> GetHeader(std::string_view hdr) const;
     190   [ #  #  #  # ]:         188 :     std::string ReadBody() const { return m_body; }
           [ -  +  +  - ]
     191                 :             :     void WriteHeader(std::string&& hdr, std::string&& value);
     192                 :             :     std::optional<uint64_t> GetChunkSize() const { return m_chunk_size; }
     193                 :             :     uint64_t GetChunkProgress() const { return m_chunk_read; }
     194                 :             : 
     195                 :             :     enum class State {
     196                 :             :         Init,
     197                 :             :         NeedsHeaders,
     198                 :             :         NeedsBody,
     199                 :             :         Complete,
     200                 :             :         Error
     201                 :             :     };
     202   [ #  #  #  #  :           0 :     State GetState() const { return m_state; }
                   #  # ]
     203                 :           0 :     void SetState(State state) { m_state = state; }
     204                 :             : 
     205                 :             : private:
     206                 :             :     HTTPRequestMethod m_method;
     207                 :             :     std::string m_target;
     208                 :             :     HTTPVersion m_version;
     209                 :             :     HTTPHeaders m_headers;
     210                 :             :     std::string m_body;
     211                 :             : 
     212                 :             :     //! Pointer to the client that made the request so we know who to respond to.
     213                 :             :     std::weak_ptr<HTTPRemoteClient> m_client;
     214                 :             : 
     215                 :             :     //! Response headers may be set in advance before response body is known
     216                 :             :     HTTPHeaders m_response_headers;
     217                 :             : 
     218                 :             :     // If a large request is sent with "Transfer-encoding: chunked" we may
     219                 :             :     // read the chunk size in a separate I/O loop iteration than the chunk
     220                 :             :     // of data itself. Store the chunk size value here until the chunk is read.
     221                 :             :     std::optional<uint64_t> m_chunk_size;
     222                 :             :     // We may also read a large chunk over multiple loop iterations.
     223                 :             :     // Track the progress of the chunk here.
     224                 :             :     uint64_t m_chunk_read{0};
     225                 :             : 
     226                 :             :     State m_state = State::Init;
     227                 :             : };
     228                 :             : 
     229                 :             : class HTTPServer
     230                 :             : {
     231                 :             : public:
     232                 :             :     /**
     233                 :             :      * Each connection is assigned an unique id of this type.
     234                 :             :      */
     235                 :             :     using Id = uint64_t;
     236                 :             : 
     237                 :           0 :     explicit HTTPServer(std::function<void(std::unique_ptr<HTTPRequest>&&)> func)
     238         [ #  # ]:           0 :         : m_request_dispatcher{std::move(func)} {}
     239                 :             : 
     240                 :           0 :     virtual ~HTTPServer()
     241                 :           0 :     {
     242         [ #  # ]:           0 :         Assume(!m_thread_socket_handler.joinable()); // Missing call to JoinSocketsThreads()
     243         [ #  # ]:           0 :         Assume(m_connected.empty()); // Missing call to DisconnectClients(), or disconnect flags not set
     244         [ #  # ]:           0 :         Assume(m_listen.empty()); // Missing call to StopListening()
     245                 :           0 :     }
     246                 :             : 
     247                 :             :     /**
     248                 :             :      * Parse the user's -rpcallowip settings and populate m_allow_subnets
     249                 :             :      */
     250                 :             :     bool InitHTTPAllowList();
     251                 :             : 
     252                 :             :     /**
     253                 :             :      * Bind to a new address:port, start listening and add the listen socket to `m_listen`.
     254                 :             :      * @param[in] to Where to bind.
     255                 :             :      * @returns {} or the reason for failure.
     256                 :             :      */
     257                 :             :     util::Expected<void, std::string> BindAndStartListening(const CService& to);
     258                 :             : 
     259                 :             :     /**
     260                 :             :      * Stop listening by closing all listening sockets.
     261                 :             :      */
     262                 :             :     void StopListening();
     263                 :             : 
     264                 :             :     /**
     265                 :             :      * Get the number of sockets the server is bound to and listening on
     266                 :             :      */
     267                 :             :     size_t GetListeningSocketCount() const { return m_listen.size(); }
     268                 :             : 
     269                 :             :     /**
     270                 :             :      * Get the number of HTTPRemoteClients we are connected to
     271                 :             :      */
     272   [ #  #  #  #  :           0 :     size_t GetConnectionsCount() const { return m_connected_size.load(std::memory_order_acquire); }
                   #  # ]
     273                 :             : 
     274                 :             :     /**
     275                 :             :      * Start the necessary threads for sockets IO.
     276                 :             :      */
     277                 :             :     void StartSocketsThreads();
     278                 :             : 
     279                 :             :     /**
     280                 :             :      * Join (wait for) the threads started by `StartSocketsThreads()` to exit.
     281                 :             :      */
     282                 :             :     void JoinSocketsThreads();
     283                 :             : 
     284                 :             :     /**
     285                 :             :      * Stop network activity
     286                 :             :      */
     287                 :           0 :     void InterruptNet() { m_interrupt_net(); }
     288                 :             : 
     289                 :             :     /**
     290                 :             :      * Start disconnecting clients when possible in the I/O loop
     291                 :             :      */
     292                 :           0 :     void DisconnectAllClients() { m_disconnect_all_clients = true; }
     293                 :             : 
     294                 :             :     /**
     295                 :             :      * Update the request handler method.
     296                 :             :      * Used for shutdown to reject new requests.
     297                 :             :      */
     298                 :           0 :     void SetRequestHandler(std::function<void(std::unique_ptr<HTTPRequest>&&)> func)
     299                 :             :         EXCLUSIVE_LOCKS_REQUIRED(!m_request_dispatcher_mutex)
     300                 :             :     {
     301   [ #  #  #  # ]:           0 :         WITH_LOCK(m_request_dispatcher_mutex,
     302                 :             :                   m_request_dispatcher = std::move(func));
     303                 :           0 :     }
     304                 :             : 
     305                 :             :     /**
     306                 :             :      * Stop accepting new connections in the I/O loop.
     307                 :             :      * Must be called first in StopHTTPServer() before DisconnectAllClients().
     308                 :             :      * A connection accepted after the "wait for 0 connections" loop exits would
     309                 :             :      * remain in m_connected when the destructor is called.
     310                 :             :      */
     311                 :           0 :     void StopAccepting() { m_stop_accepting = true; }
     312                 :             : 
     313                 :             :     /**
     314                 :             :      * Set the idle client timeout (-rpcservertimeout)
     315                 :             :      */
     316                 :           0 :     void SetServerTimeout(std::chrono::seconds seconds) { m_rpcservertimeout = seconds; }
     317                 :             : 
     318                 :             :     /**
     319                 :             :      * Set the maximum amount of connected HTTPClients (-rpcmaxconnections)
     320                 :             :      */
     321                 :           0 :     void SetMaxConnections(int max_conn) { m_rpcmaxconnections = max_conn; }
     322                 :             : 
     323                 :             :     /**
     324                 :             :      * Force-remove all remaining clients from m_connected without waiting for
     325                 :             :      * graceful disconnection. Must only be called after JoinSocketsThreads().
     326                 :             :      */
     327                 :             :     void ClearConnectedClients();
     328                 :             : 
     329                 :             : private:
     330                 :             :     /**
     331                 :             :      * List of listening sockets.
     332                 :             :      */
     333                 :             :     std::vector<std::shared_ptr<Sock>> m_listen;
     334                 :             : 
     335                 :             :     /**
     336                 :             :      * The id to assign to the next created connection.
     337                 :             :      */
     338                 :             :     std::atomic<Id> m_next_id{0};
     339                 :             : 
     340                 :             :     /**
     341                 :             :      * List of HTTPRemoteClients with connected sockets.
     342                 :             :      * Connections will only be added and removed in the I/O thread, but
     343                 :             :      * weak pointers may be passed to worker threads to handle requests
     344                 :             :      * and send replies.
     345                 :             :      */
     346                 :             :     std::vector<std::shared_ptr<HTTPRemoteClient>> m_connected;
     347                 :             : 
     348                 :             :     /**
     349                 :             :      * Flag used during shutdown to stop accepting new connections.
     350                 :             :      * Set by main thread and read by the I/O thread.
     351                 :             :      */
     352                 :             :     std::atomic_bool m_stop_accepting{false};
     353                 :             : 
     354                 :             :     /**
     355                 :             :      * Flag used during shutdown.
     356                 :             :      * Overrides HTTPRemoteClient flags m_keep_alive and m_connection_busy.
     357                 :             :      * Set by main thread and read by the I/O thread.
     358                 :             :      */
     359                 :             :     std::atomic_bool m_disconnect_all_clients{false};
     360                 :             : 
     361                 :             :     /**
     362                 :             :      * The number of connected sockets.
     363                 :             :      * Updated from the I/O thread but safely readable from
     364                 :             :      * the main thread without locks.
     365                 :             :      */
     366                 :             :     std::atomic<size_t> m_connected_size{0};
     367                 :             : 
     368                 :             :     /**
     369                 :             :      * Info about which socket has which event ready and a reverse map
     370                 :             :      * back to the HTTPRemoteClient that owns the socket.
     371                 :             :      */
     372         [ #  # ]:           0 :     struct IOReadiness {
     373                 :             :         /**
     374                 :             :          * Map of socket -> socket events. For example:
     375                 :             :          * socket1 -> { requested = SendEvent|RecvEvent, occurred = RecvEvent }
     376                 :             :          * socket2 -> { requested = SendEvent, occurred = SendEvent }
     377                 :             :          */
     378                 :             :         Sock::EventsPerSock events_per_sock;
     379                 :             : 
     380                 :             :         /**
     381                 :             :          * Map of socket -> HTTPRemoteClient. For example:
     382                 :             :          * socket1 -> HTTPRemoteClient{ id=23 }
     383                 :             :          * socket2 -> HTTPRemoteClient{ id=56 }
     384                 :             :          */
     385                 :             :         std::unordered_map<Sock::EventsPerSock::key_type,
     386                 :             :                            std::shared_ptr<HTTPRemoteClient>,
     387                 :             :                            Sock::HashSharedPtrSock,
     388                 :             :                            Sock::EqualSharedPtrSock>
     389                 :             :             httpclients_per_sock;
     390                 :             :     };
     391                 :             : 
     392                 :             :     /**
     393                 :             :      * This is signaled when network activity should cease.
     394                 :             :      */
     395                 :             :     CThreadInterrupt m_interrupt_net;
     396                 :             : 
     397                 :             :     /**
     398                 :             :      * Thread that sends to and receives from sockets and accepts connections.
     399                 :             :      * Executes the I/O loop of the server.
     400                 :             :      */
     401                 :             :     std::thread m_thread_socket_handler;
     402                 :             : 
     403                 :             :     /*
     404                 :             :      * What to do with HTTP requests once received, validated and parsed.
     405                 :             :      * Set in main thread by server start and interrupt but read in
     406                 :             :      * worker threads.
     407                 :             :      */
     408                 :             :     /// @{
     409                 :             :     mutable Mutex m_request_dispatcher_mutex;
     410                 :             :     std::function<void(std::unique_ptr<HTTPRequest>&&)> m_request_dispatcher GUARDED_BY(m_request_dispatcher_mutex);
     411                 :             :     /// @}
     412                 :             : 
     413                 :             :     /**
     414                 :             :      * Idle timeout after which clients are disconnected
     415                 :             :      */
     416                 :             :     std::chrono::seconds m_rpcservertimeout{DEFAULT_HTTP_SERVER_TIMEOUT};
     417                 :             : 
     418                 :             :     /**
     419                 :             :      * List of subnets to allow HTTP connections from
     420                 :             :      */
     421                 :             :     std::vector<CSubNet> m_allow_subnets;
     422                 :             : 
     423                 :             :     /**
     424                 :             :      * Check an incoming connection's source IP against the allow list
     425                 :             :      */
     426                 :             :     bool ClientAllowed(const CNetAddr& netaddr) const;
     427                 :             : 
     428                 :             :     /**
     429                 :             :      * Maximum amount of concurrent connections
     430                 :             :      */
     431                 :             :     int m_rpcmaxconnections{DEFAULT_MAX_HTTP_CONNECTIONS};
     432                 :             : 
     433                 :             :     /**
     434                 :             :      * Accept a connection.
     435                 :             :      * @param[in] listen_sock Socket on which to accept the connection.
     436                 :             :      * @param[out] addr Address of the peer that was accepted.
     437                 :             :      * @return Newly created socket for the accepted connection.
     438                 :             :      */
     439                 :             :     std::unique_ptr<Sock> AcceptConnection(const Sock& listen_sock, CService& addr);
     440                 :             : 
     441                 :             :     /**
     442                 :             :      * Generate an id for a newly created connection.
     443                 :             :      */
     444                 :             :     Id GetNewId();
     445                 :             : 
     446                 :             :     /**
     447                 :             :      * After a new socket with a client has been created, configure its flags,
     448                 :             :      * make a new HTTPRemoteClient and Id and save its shared pointer.
     449                 :             :      * @param[in] sock The newly created socket.
     450                 :             :      * @param[in] addr Address of the new peer.
     451                 :             :      */
     452                 :             :     void NewSockAccepted(std::unique_ptr<Sock>&& sock, const CService& addr);
     453                 :             : 
     454                 :             :     /**
     455                 :             :      * Do the read/write for connected sockets that are ready for IO.
     456                 :             :      * @param[in] io_readiness Which sockets are ready and their corresponding HTTPRemoteClients.
     457                 :             :      */
     458                 :             :     void SocketHandlerConnected(const IOReadiness& io_readiness) const
     459                 :             :         EXCLUSIVE_LOCKS_REQUIRED(!m_request_dispatcher_mutex);
     460                 :             : 
     461                 :             :     /**
     462                 :             :      * Accept incoming connections, one from each read-ready listening socket.
     463                 :             :      * @param[in] events_per_sock Sockets that are ready for IO.
     464                 :             :      */
     465                 :             :     void SocketHandlerListening(const Sock::EventsPerSock& events_per_sock);
     466                 :             : 
     467                 :             :     /**
     468                 :             :      * Generate a collection of sockets to check for IO readiness.
     469                 :             :      * @return Sockets to check for readiness plus an aux map to find the
     470                 :             :      * corresponding HTTPRemoteClient given a socket.
     471                 :             :      */
     472                 :             :     IOReadiness GenerateWaitSockets() const;
     473                 :             : 
     474                 :             :     /**
     475                 :             :      * Check connected and listening sockets for IO readiness and process them accordingly.
     476                 :             :      * This is the main I/O loop of the server.
     477                 :             :      */
     478                 :             :     void ThreadSocketHandler() EXCLUSIVE_LOCKS_REQUIRED(!m_request_dispatcher_mutex);
     479                 :             : 
     480                 :             :     /**
     481                 :             :      * Close underlying socket connections for flagged clients
     482                 :             :      * by removing their shared pointer from m_connected. If an HTTPRemoteClient
     483                 :             :      * is busy in a worker thread, its connection will be closed once that
     484                 :             :      * job is done.
     485                 :             :      */
     486                 :             :     void DisconnectClients();
     487                 :             : };
     488                 :             : 
     489                 :             : std::optional<std::string> GetQueryParameterFromUri(std::string_view uri, std::string_view key);
     490                 :             : 
     491                 :             : class HTTPRemoteClient
     492                 :             : {
     493                 :             : public:
     494                 :           0 :     explicit HTTPRemoteClient(HTTPServer::Id id, const CService& addr, std::unique_ptr<Sock> socket)
     495   [ #  #  #  # ]:           0 :         : m_id(id), m_addr(addr), m_origin(addr.ToStringAddrPort()), m_sock{std::move(socket)}, m_idle_since{Now<SteadySeconds>()} {}
     496                 :             : 
     497                 :             :     // Disable copies (should only be used as shared pointers)
     498                 :             :     HTTPRemoteClient(const HTTPRemoteClient&) = delete;
     499                 :             :     HTTPRemoteClient& operator=(const HTTPRemoteClient&) = delete;
     500                 :             : 
     501                 :             :     const std::string& GetOrigin() const { return m_origin; }
     502                 :           0 :     const CService& GetPeer() const { return m_addr; }
     503   [ #  #  #  #  :           0 :     std::shared_ptr<Sock> GetSock() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex) { return WITH_LOCK(m_sock_mutex, return m_sock;); }
                   #  # ]
     504   [ #  #  #  # ]:           0 :     bool ReadyToSend() const EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex) { return WITH_LOCK(m_send_mutex, return m_send_ready;); }
     505                 :             : 
     506                 :             :     void Send(const HTTPResponse& res, std::span<const std::byte> reply_body, bool keep_alive) EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex, !m_sock_mutex);
     507                 :             :     void Receive() EXCLUSIVE_LOCKS_REQUIRED(!m_sock_mutex);
     508                 :             : 
     509                 :             :     bool MaybeDisconnect(std::chrono::time_point<SteadyClock> now, std::chrono::seconds rpcservertimeout, bool disconnect_all);
     510                 :             : 
     511                 :             :     /**
     512                 :             :      * Try to read an HTTPRequest from a client's receive buffer.
     513                 :             :      * Only complete requests are returned, incomplete requests are
     514                 :             :      * left in the buffer to wait for more data. Some read errors
     515                 :             :      * will mark this client for disconnection.
     516                 :             :      */
     517                 :             :     static std::unique_ptr<HTTPRequest> TryReadRequest(const std::shared_ptr<HTTPRemoteClient>& client);
     518                 :             : 
     519                 :             :     /**
     520                 :             :      * Push data (if there is any) from client's m_send_buffer to the connected socket.
     521                 :             :      * @returns false if we are done with this client and HTTPServer can skip the next read operation from it.
     522                 :             :      */
     523                 :             :     bool MaybeSendBytesFromBuffer() EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex, !m_sock_mutex);
     524                 :             : 
     525                 :             :     //! Used for tests.
     526                 :             :     //! @{
     527                 :             :     const std::string& GetRecvBuffer() const { return m_recv_buffer; }
     528                 :             :     const HTTPRequest* GetRequest() const { return m_req.get(); }
     529                 :             :     //! @}
     530                 :             : 
     531                 :             : protected:
     532                 :             :     //! Used for tests.
     533                 :             :     std::string& MutateRecvBuffer() { return m_recv_buffer; }
     534                 :             : 
     535                 :             : private:
     536                 :             :     /**
     537                 :             :      * Try to read an HTTP request from the receive buffer.
     538                 :             :      * Updates HTTPRequest.m_state and drains buffer on error.
     539                 :             :      * @param[in]   req     A HTTPRequest to read into
     540                 :             :      * @throws std::runtime_error if request is unreadable or violates protocol
     541                 :             :      */
     542                 :             :     void ReadRequest(HTTPRequest& req);
     543                 :             : 
     544                 :             :     //! ID provided by HTTPServer upon connection and instantiation
     545                 :             :     const HTTPServer::Id m_id;
     546                 :             : 
     547                 :             :     //! Remote address of connected client
     548                 :             :     const CService m_addr;
     549                 :             : 
     550                 :             :     //! IP:port of connected client, cached for logging purposes
     551                 :             :     const std::string m_origin;
     552                 :             : 
     553                 :             :     /**
     554                 :             :      * In lieu of an intermediate transport class like p2p uses,
     555                 :             :      * we copy data from the socket buffer to the client object
     556                 :             :      * and attempt to read HTTP requests from here.
     557                 :             :      */
     558                 :             :     std::string m_recv_buffer{};
     559                 :             : 
     560                 :             :     //! Requests from a client must be processed in the order in which
     561                 :             :     //! they were received, blocking on a per-client basis. We read
     562                 :             :     //! one request at a time from the socket buffer then pass it to a worker.
     563                 :             :     std::unique_ptr<HTTPRequest> m_req;
     564                 :             : 
     565                 :             :     //! Set to true by the I/O thread when a request is popped off
     566                 :             :     //! and passed to a worker thread, reset to false by the worker thread.
     567                 :             :     std::atomic_bool m_req_busy{false};
     568                 :             : 
     569                 :             :     /**
     570                 :             :      * Response data destined for this client.
     571                 :             :      * Written to by http worker threads, read and erased by HTTPServer I/O thread
     572                 :             :      */
     573                 :             :     /// @{
     574                 :             :     mutable Mutex m_send_mutex;
     575                 :             :     std::vector<std::byte> m_send_buffer GUARDED_BY(m_send_mutex);
     576                 :             :     /// @}
     577                 :             : 
     578                 :             :     /**
     579                 :             :     * Set true by worker threads after writing a response to m_send_buffer.
     580                 :             :     * Set false by the HTTPServer I/O thread after flushing m_send_buffer.
     581                 :             :     * Checked in the HTTPServer I/O loop to decide whether to poll the socket for
     582                 :             :     * writeability or readability.
     583                 :             :     * Guarded by m_send_mutex so it stays consistent with m_send_buffer's emptiness:
     584                 :             :     * the two must always be updated together under the same lock.
     585                 :             :     */
     586                 :             :     bool m_send_ready GUARDED_BY(m_send_mutex){false};
     587                 :             : 
     588                 :             :     /**
     589                 :             :      * Mutex that serializes the Send() and Recv() calls on `m_sock`. Reading
     590                 :             :      * from the client occurs in the I/O thread but writing back to a client
     591                 :             :      * may occur in a worker thread.
     592                 :             :      */
     593                 :             :     Mutex m_sock_mutex;
     594                 :             : 
     595                 :             :     /**
     596                 :             :      * Underlying socket.
     597                 :             :      * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of the
     598                 :             :      * underlying file descriptor by one thread while another thread is poll(2)-ing
     599                 :             :      * it for activity.
     600                 :             :      * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
     601                 :             :      */
     602                 :             :     std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
     603                 :             : 
     604                 :             :     //! Initialized to true while server waits for first request from client.
     605                 :             :     //! Set to false after data is written to m_send_buffer and then that buffer is flushed to client.
     606                 :             :     //! Reset to true when we receive new request data from client.
     607                 :             :     //! Checked during DisconnectClients() and set by read/write operations
     608                 :             :     //! called in either the HTTPServer I/O loop or by a worker thread during an "optimistic send".
     609                 :             :     //! `m_connection_busy=true` can be overridden by `m_disconnect=true` (we disconnect).
     610                 :             :     std::atomic_bool m_connection_busy{true};
     611                 :             : 
     612                 :             :     //! Client has requested to keep the connection open after all requests have been responded to.
     613                 :             :     //! Set by (potentially multiple) worker threads and checked in the HTTPServer I/O loop.
     614                 :             :     //! `m_keep_alive=true` can be overridden `by HTTPServer.m_disconnect_all_clients` (we disconnect).
     615                 :             :     std::atomic_bool m_keep_alive{false};
     616                 :             : 
     617                 :             :     //! Flag this client for disconnection on next loop.
     618                 :             :     //! Either we have encountered a permanent error, or both sides of the socket are done
     619                 :             :     //! with the connection, e.g. our reply to a "Connection: close" request has been sent.
     620                 :             :     //! Might be set in a worker thread or in the I/O thread. When set to `true` we disconnect,
     621                 :             :     //! possibly overriding all other disconnect flags.
     622                 :             :     std::atomic_bool m_disconnect{false};
     623                 :             : 
     624                 :             :     //! Timestamp of last send or receive activity, used for -rpcservertimeout.
     625                 :             :     //! Due to optimistic sends it may be updated in either a worker thread or in the
     626                 :             :     //! I/O thread. It is checked in the I/O thread to disconnect idle clients.
     627                 :             :     std::atomic<SteadySeconds> m_idle_since;
     628                 :             : };
     629                 :             : 
     630                 :             : /** Initialize HTTP server.
     631                 :             :  * Call this before RegisterHTTPHandler or EventBase().
     632                 :             :  */
     633                 :             : bool InitHTTPServer();
     634                 :             : 
     635                 :             : /** Start HTTP server.
     636                 :             :  * This is separate from InitHTTPServer to give users race-condition-free time
     637                 :             :  * to register their handlers between InitHTTPServer and StartHTTPServer.
     638                 :             :  */
     639                 :             : void StartHTTPServer();
     640                 :             : 
     641                 :             : /** Interrupt HTTP server threads */
     642                 :             : void InterruptHTTPServer();
     643                 :             : 
     644                 :             : /** Stop HTTP server */
     645                 :             : void StopHTTPServer();
     646                 :             : 
     647                 :             : #endif // BITCOIN_HTTPSERVER_H
        

Generated by: LCOV version 2.5.0-full