Coverage Report

Created: 2026-09-14 20:36

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