Branch data Line data Source code
1 : : // Copyright (c) 2015-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #ifndef BITCOIN_HTTPSERVER_H
6 : : #define BITCOIN_HTTPSERVER_H
7 : :
8 : : #include <atomic>
9 : : #include <functional>
10 : : #include <memory>
11 : : #include <optional>
12 : : #include <span>
13 : : #include <stdexcept>
14 : : #include <string>
15 : : #include <vector>
16 : :
17 : : #include <netaddress.h>
18 : : #include <rpc/protocol.h>
19 : : #include <util/byte_units.h>
20 : : #include <util/expected.h>
21 : : #include <util/sock.h>
22 : : #include <util/strencodings.h>
23 : : #include <util/string.h>
24 : : #include <util/threadinterrupt.h>
25 : : #include <util/time.h>
26 : :
27 : : namespace util {
28 : : class SignalInterrupt;
29 : : } // namespace util
30 : :
31 : : /**
32 : : * The default value for `-rpcthreads`. This number of threads will be created at startup.
33 : : */
34 : : inline constexpr int DEFAULT_HTTP_THREADS=16;
35 : :
36 : : /**
37 : : * The default value for `-rpcworkqueue`. This is the maximum depth of the work queue,
38 : : * we don't allocate this number of work queue items upfront.
39 : : */
40 : : inline constexpr int DEFAULT_HTTP_WORKQUEUE=64;
41 : :
42 : : inline constexpr int DEFAULT_HTTP_SERVER_TIMEOUT=30;
43 : :
44 : : /**
45 : : * Maximum number of connected HTTP clients
46 : : */
47 : : inline constexpr int DEFAULT_MAX_HTTP_CONNECTIONS = 16;
48 : :
49 : : enum class HTTPRequestMethod {
50 : : UNKNOWN,
51 : : GET,
52 : : POST,
53 : : HEAD,
54 : : PUT
55 : : };
56 : :
57 : : namespace http_bitcoin {
58 : : class HTTPRequest;
59 : : }
60 : : /** Handler for requests to a certain HTTP path */
61 : : using HTTPRequestHandler = std::function<void(http_bitcoin::HTTPRequest* req, const std::string&)>;
62 : :
63 : : /** Register handler for prefix.
64 : : * If multiple handlers match a prefix, the first-registered one will
65 : : * be invoked.
66 : : */
67 : : void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler);
68 : : /** Unregister handler for prefix */
69 : : void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch);
70 : :
71 : : namespace http_bitcoin {
72 : : using util::LineReader;
73 : :
74 : : //! Shortest valid request line, used by libevent in evhttp_parse_request_line()
75 : : inline constexpr size_t MIN_REQUEST_LINE_LENGTH = std::string_view("GET / HTTP/1.0").size();
76 : :
77 : : //! Maximum size of each headers line in an HTTP request,
78 : : //! also the maximum size of all headers total.
79 : : //! See https://github.com/bitcoin/bitcoin/pull/6859
80 : : //! And libevent http.c evhttp_parse_headers_()
81 : : inline constexpr size_t MAX_HEADERS_SIZE{8192};
82 : :
83 : : //! Maximum size of an HTTP request body
84 : : inline constexpr uint64_t MAX_BODY_SIZE{32_MiB};
85 : :
86 : : //! Thrown when a request body exceeds MAX_BODY_SIZE (or *will* exceed, in chunked transfer)
87 : : //! so the server can reply with more specific code 413 (content too large) vs general 400 (bad request)
88 : : struct ContentTooLargeError : std::runtime_error {
89 [ + - + - ]: 5 : using std::runtime_error::runtime_error;
90 : : };
91 : :
92 [ + - - - : 217378 : class HTTPHeaders
- - - - -
- - - - -
- - ][ + - ]
93 : : {
94 : : public:
95 : : /**
96 : : * @param[in] key The field-name of the header to search for
97 : : * @returns The value of the first header that matches the provided key
98 : : * nullopt if key is not found
99 : : */
100 : : std::optional<std::string> FindFirst(std::string_view key) const;
101 : : /**
102 : : * @param[in] key The field-name of the header to search for
103 : : * @returns Views into all values matching the provided key (valid while this object is alive)
104 : : */
105 : : std::vector<std::string_view> FindAll(std::string_view key) const;
106 : : void Write(std::string&& key, std::string&& value);
107 : : /**
108 : : * @param[in] key The field-name of the header to search for and delete
109 : : */
110 : : void RemoveAll(std::string_view key);
111 : : /**
112 : : * @param[in] reader A LineReader instance initialized with the client's receive buffer.
113 : : * @param[in] write Whether or not to write the parsed data to the object after validation.
114 : : * @returns false if LineReader hits the end of the buffer before reading an
115 : : * \n, meaning that we are still waiting on more data from the client.
116 : : * true after reading an entire HTTP headers section, terminated
117 : : * by an empty line and \n.
118 : : * @throws on exceeded read limit and on bad headers syntax (e.g. no ":" in a line)
119 : : */
120 : : bool Read(util::LineReader& reader, bool write = true);
121 : : std::string Stringify() const;
122 : :
123 : : private:
124 : : /**
125 : : * Headers can have duplicate field names, so we use a vector of key-value pairs instead of a map.
126 : : * https://httpwg.org/specs/rfc9110.html#rfc.section.5.2
127 : : */
128 : : std::vector<std::pair<std::string, std::string>> m_headers;
129 : :
130 : : //! Track total bytes consumed in Read() for limit checks
131 : : size_t m_consumed{0};
132 : : };
133 : :
134 [ + - ]: 220513 : struct HTTPVersion {
135 : : /**
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 : :
146 : 217367 : class HTTPResponse
147 : : {
148 : : public:
149 : : HTTPVersion m_version;
150 : :
151 : : HTTPStatusCode m_status{HTTP_INTERNAL_SERVER_ERROR};
152 : : HTTPHeaders m_headers;
153 : :
154 : : std::string StringifyHeaders() const;
155 : : };
156 : :
157 : : class HTTPRemoteClient;
158 : :
159 : : class HTTPRequest
160 : : {
161 : : public:
162 : : HTTPRequestMethod m_method;
163 : : std::string m_target;
164 : : HTTPVersion m_version;
165 : : HTTPHeaders m_headers;
166 : : std::string m_body;
167 : :
168 : : //! Pointer to the client that made the request so we know who to respond to.
169 : : std::weak_ptr<HTTPRemoteClient> m_client;
170 : :
171 : : //! Response headers may be set in advance before response body is known
172 : : HTTPHeaders m_response_headers;
173 : :
174 [ + - ]: 220513 : explicit HTTPRequest(const std::shared_ptr<HTTPRemoteClient>& client) : m_client{client} {}
175 : : //! Construct with a null client for unit tests
176 : 27 : explicit HTTPRequest() : m_client{} {}
177 : :
178 : : /**
179 : : * Methods that attempt to parse HTTP request fields line-by-line
180 : : * from a receive buffer.
181 : : * @param[in] reader A LineReader object constructed over a span of data.
182 : : * @returns true If the request field was parsed.
183 : : * false If there was not enough data in the buffer to complete the field.
184 : : * @throws std::runtime_error if data is invalid.
185 : : */
186 : : /// @{
187 : : bool LoadControlData(LineReader& reader);
188 : : bool LoadHeaders(LineReader& reader);
189 : : bool LoadBody(LineReader& reader);
190 : : /// @}
191 : :
192 : : void WriteReply(HTTPStatusCode status, std::span<const std::byte> reply_body = {});
193 : 217091 : void WriteReply(HTTPStatusCode status, std::string_view reply_body_view)
194 : : {
195 : 217091 : WriteReply(status, std::as_bytes(std::span{reply_body_view}));
196 : 217091 : }
197 : :
198 : : // These methods reimplement the API from http_libevent::HTTPRequest
199 : : // for downstream JSONRPC and REST modules.
200 [ - + + - : 866444 : std::string GetURI() const { return m_target; }
- - - - -
- - - ][ -
+ # # # #
# # # # #
# ][ # # #
# # # # #
# # # # ]
201 : : CService GetPeer() const;
202 [ + + ]: 433379 : HTTPRequestMethod GetRequestMethod() const { return m_method; }
203 : : std::optional<std::string> GetQueryParameter(std::string_view key) const;
204 : : std::pair<bool, std::string> GetHeader(std::string_view hdr) const;
205 [ - + - + ]: 431748 : std::string ReadBody() const { return m_body; }
206 : : void WriteHeader(std::string&& hdr, std::string&& value);
207 : :
208 : : enum class State {
209 : : Init,
210 : : NeedsHeaders,
211 : : NeedsBody,
212 : : Complete,
213 : : Error
214 : : };
215 [ + - + - : 1118287 : State GetState() const { return m_state; }
+ + + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ][ +
+ + + +
+ ]
216 : 652113 : void SetState(State state) { m_state = state; }
217 : :
218 : : // If a large request is sent with "Transfer-encoding: chunked" we may
219 : : // read the chunk size in a separate I/O loop iteration than the chunk
220 : : // of data itself. Store the chunk size value here until the chunk is read.
221 : : std::optional<uint64_t> m_chunk_size;
222 : : // We may also read a large chunk over multiple loop iterations.
223 : : // Track the progress of the chunk here.
224 : : uint64_t m_chunk_read{0};
225 : :
226 : : private:
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 : 1195 : explicit HTTPServer(std::function<void(std::unique_ptr<HTTPRequest>&&)> func)
239 [ + - ]: 1195 : : m_request_dispatcher{std::move(func)} {}
240 : :
241 : 2387 : virtual ~HTTPServer()
242 : 1195 : {
243 : 1195 : Assume(!m_thread_socket_handler.joinable()); // Missing call to JoinSocketsThreads()
244 : 1195 : Assume(m_connected.empty()); // Missing call to DisconnectClients(), or disconnect flags not set
245 : 1195 : Assume(m_listen.empty()); // Missing call to StopListening()
246 : 2387 : }
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 [ + + + + : 601357 : 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 [ + - + - : 1195 : void InterruptNet() { m_interrupt_net(); }
+ - ]
289 : :
290 : : /**
291 : : * Start disconnecting clients when possible in the I/O loop
292 : : */
293 [ + - ]: 1193 : 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 : 1192 : void SetRequestHandler(std::function<void(std::unique_ptr<HTTPRequest>&&)> func)
300 : : EXCLUSIVE_LOCKS_REQUIRED(!m_request_dispatcher_mutex)
301 : : {
302 [ + - + - ]: 2384 : WITH_LOCK(m_request_dispatcher_mutex,
303 : : m_request_dispatcher = std::move(func));
304 : 1192 : }
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 : 1192 : void StopAccepting() { m_stop_accepting = true; }
313 : :
314 : : /**
315 : : * Set the idle client timeout (-rpcservertimeout)
316 : : */
317 : 1192 : void SetServerTimeout(std::chrono::seconds seconds) { m_rpcservertimeout = seconds; }
318 : :
319 : : /**
320 : : * Set the maximum amount of connected HTTPClients (-rpcmaxconnections)
321 : : */
322 : 1192 : 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 [ + + ]: 1185152 : 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 : : * Try to read HTTPRequests from a client's receive buffer.
483 : : * Complete requests are dispatched, incomplete requests are
484 : : * left in the buffer to wait for more data. Some read errors
485 : : * will mark this client for disconnection.
486 : : * @param[in] client The HTTPRemoteClient to read requests from
487 : : */
488 : : void MaybeDispatchRequestsFromClient(const std::shared_ptr<HTTPRemoteClient>& client) const
489 : : 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 : : //! ID provided by HTTPServer upon connection and instantiation
506 : : const HTTPServer::Id m_id;
507 : :
508 : : //! Remote address of connected client
509 : : const CService m_addr;
510 : :
511 : : //! IP:port of connected client, cached for logging purposes
512 : : const std::string m_origin;
513 : :
514 : : /**
515 : : * In lieu of an intermediate transport class like p2p uses,
516 : : * we copy data from the socket buffer to the client object
517 : : * and attempt to read HTTP requests from here.
518 : : */
519 : : std::string m_recv_buffer{};
520 : :
521 : : //! Requests from a client must be processed in the order in which
522 : : //! they were received, blocking on a per-client basis. We read
523 : : //! one request at a time from the socket buffer then pass it to a worker.
524 : : std::unique_ptr<HTTPRequest> m_req;
525 : :
526 : : //! Set to true by the I/O thread when a request is popped off
527 : : //! and passed to a worker thread, reset to false by the worker thread.
528 : : std::atomic_bool m_req_busy{false};
529 : :
530 : : /**
531 : : * Response data destined for this client.
532 : : * Written to by http worker threads, read and erased by HTTPServer I/O thread
533 : : */
534 : : /// @{
535 : : Mutex m_send_mutex;
536 : : std::vector<std::byte> m_send_buffer GUARDED_BY(m_send_mutex);
537 : : /// @}
538 : :
539 : : /**
540 : : * Set true by worker threads after writing a response to m_send_buffer.
541 : : * Set false by the HTTPServer I/O thread after flushing m_send_buffer.
542 : : * Checked in the HTTPServer I/O loop to decide whether to poll the socket for
543 : : * writeability or readability.
544 : : * Guarded by m_send_mutex so it stays consistent with m_send_buffer's emptiness:
545 : : * the two must always be updated together under the same lock.
546 : : */
547 : : bool m_send_ready GUARDED_BY(m_send_mutex){false};
548 : :
549 : : /**
550 : : * Mutex that serializes the Send() and Recv() calls on `m_sock`. Reading
551 : : * from the client occurs in the I/O thread but writing back to a client
552 : : * may occur in a worker thread.
553 : : */
554 : : Mutex m_sock_mutex;
555 : :
556 : : /**
557 : : * Underlying socket.
558 : : * `shared_ptr` (instead of `unique_ptr`) is used to avoid premature close of the
559 : : * underlying file descriptor by one thread while another thread is poll(2)-ing
560 : : * it for activity.
561 : : * @see https://github.com/bitcoin/bitcoin/issues/21744 for details.
562 : : */
563 : : std::shared_ptr<Sock> m_sock GUARDED_BY(m_sock_mutex);
564 : :
565 : : //! Initialized to true while server waits for first request from client.
566 : : //! Set to false after data is written to m_send_buffer and then that buffer is flushed to client.
567 : : //! Reset to true when we receive new request data from client.
568 : : //! Checked during DisconnectClients() and set by read/write operations
569 : : //! called in either the HTTPServer I/O loop or by a worker thread during an "optimistic send".
570 : : //! `m_connection_busy=true` can be overridden by `m_disconnect=true` (we disconnect).
571 : : std::atomic_bool m_connection_busy{true};
572 : :
573 : : //! Client has requested to keep the connection open after all requests have been responded to.
574 : : //! Set by (potentially multiple) worker threads and checked in the HTTPServer I/O loop.
575 : : //! `m_keep_alive=true` can be overridden `by HTTPServer.m_disconnect_all_clients` (we disconnect).
576 : : std::atomic_bool m_keep_alive{false};
577 : :
578 : : //! Flag this client for disconnection on next loop.
579 : : //! Either we have encountered a permanent error, or both sides of the socket are done
580 : : //! with the connection, e.g. our reply to a "Connection: close" request has been sent.
581 : : //! Might be set in a worker thread or in the I/O thread. When set to `true` we disconnect,
582 : : //! possibly overriding all other disconnect flags.
583 : : std::atomic_bool m_disconnect{false};
584 : :
585 : : //! Timestamp of last send or receive activity, used for -rpcservertimeout.
586 : : //! Due to optimistic sends it may be updated in either a worker thread or in the
587 : : //! I/O thread. It is checked in the I/O thread to disconnect idle clients.
588 : : std::atomic<SteadySeconds> m_idle_since;
589 : :
590 : 3276 : explicit HTTPRemoteClient(HTTPServer::Id id, const CService& addr, std::unique_ptr<Sock> socket)
591 [ + - + - ]: 3276 : : m_id(id), m_addr(addr), m_origin(addr.ToStringAddrPort()), m_sock{std::move(socket)}, m_idle_since{Now<SteadySeconds>()} {}
592 : :
593 : : // Disable copies (should only be used as shared pointers)
594 : : HTTPRemoteClient(const HTTPRemoteClient&) = delete;
595 : : HTTPRemoteClient& operator=(const HTTPRemoteClient&) = delete;
596 : :
597 : : /**
598 : : * Try to read an HTTP request from the receive buffer.
599 : : * Updates HTTPRequest.m_state and drains buffer on error.
600 : : * @param[in] req A HTTPRequest to read into
601 : : * @throws std::runtime_error if request is unreadable or violates protocol
602 : : */
603 : : void ReadRequest(HTTPRequest& req);
604 : :
605 : : /**
606 : : * Push data (if there is any) from client's m_send_buffer to the connected socket.
607 : : * @returns false if we are done with this client and HTTPServer can skip the next read operation from it.
608 : : */
609 : : bool MaybeSendBytesFromBuffer() EXCLUSIVE_LOCKS_REQUIRED(!m_send_mutex, !m_sock_mutex);
610 : : };
611 : :
612 : : /** Initialize HTTP server.
613 : : * Call this before RegisterHTTPHandler or EventBase().
614 : : */
615 : : bool InitHTTPServer();
616 : :
617 : : /** Start HTTP server.
618 : : * This is separate from InitHTTPServer to give users race-condition-free time
619 : : * to register their handlers between InitHTTPServer and StartHTTPServer.
620 : : */
621 : : void StartHTTPServer();
622 : :
623 : : /** Interrupt HTTP server threads */
624 : : void InterruptHTTPServer();
625 : :
626 : : /** Stop HTTP server */
627 : : void StopHTTPServer();
628 : : } // namespace http_bitcoin
629 : :
630 : : #endif // BITCOIN_HTTPSERVER_H
|