LCOV - code coverage report
Current view: top level - src - httpserver.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 82.4 % 34 28
Test Date: 2026-08-23 07:26:31 Functions: 75.0 % 8 6
Branches: 39.1 % 174 68

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

Generated by: LCOV version 2.0-1