Coverage Report

Created: 2026-11-13 17:38

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