Coverage Report

Created: 2026-07-23 20:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/httpserver.cpp
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
#include <bitcoin-build-config.h> // IWYU pragma: keep
6
7
#include <httpserver.h>
8
9
#include <chainparamsbase.h>
10
#include <common/args.h>
11
#include <common/messages.h>
12
#include <common/url.h>
13
#include <compat/compat.h>
14
#include <logging.h>
15
#include <netbase.h>
16
#include <node/interface_ui.h>
17
#include <rpc/protocol.h>
18
#include <span.h>
19
#include <sync.h>
20
#include <util/check.h>
21
#include <util/signalinterrupt.h>
22
#include <util/sock.h>
23
#include <util/strencodings.h>
24
#include <util/thread.h>
25
#include <util/threadnames.h>
26
#include <util/threadpool.h>
27
#include <util/time.h>
28
#include <util/translation.h>
29
30
#include <condition_variable>
31
#include <cstdio>
32
#include <cstdlib>
33
#include <deque>
34
#include <memory>
35
#include <optional>
36
#include <span>
37
#include <string>
38
#include <string_view>
39
#include <thread>
40
#include <unordered_map>
41
#include <vector>
42
43
#include <sys/types.h>
44
#include <sys/stat.h>
45
46
//! The set of sockets cannot be modified while waiting, so
47
//! the sleep time needs to be small to avoid new sockets stalling.
48
static constexpr auto SELECT_TIMEOUT{50ms};
49
50
//! Explicit alias for setting socket option methods.
51
static constexpr int SOCKET_OPTION_TRUE{1};
52
53
using common::InvalidPortErrMsg;
54
using http_bitcoin::HTTPRequest;
55
56
struct HTTPPathHandler
57
{
58
    HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
59
2.23k
        prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
60
2.23k
    {
61
2.23k
    }
62
    std::string prefix;
63
    bool exactMatch;
64
    HTTPRequestHandler handler;
65
};
66
67
/** HTTP module state */
68
69
static std::unique_ptr<http_bitcoin::HTTPServer> g_http_server{nullptr};
70
//! List of subnets to allow RPC connections from
71
static std::vector<CSubNet> rpc_allow_subnets;
72
//! Handlers for (sub)paths
73
static GlobalMutex g_httppathhandlers_mutex;
74
static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
75
/// \anchor http_pool
76
//! Http thread pool - future: encapsulate in HttpContext
77
static ThreadPool g_threadpool_http("http");
78
static int g_max_queue_depth{100};
79
80
/** Check if a network address is allowed to access the HTTP server */
81
static bool ClientAllowed(const CNetAddr& netaddr)
82
183k
{
83
183k
    if (!netaddr.IsValid())
84
0
        return false;
85
183k
    for(const CSubNet& subnet : rpc_allow_subnets)
86
183k
        if (subnet.Match(netaddr))
87
183k
            return true;
88
1
    return false;
89
183k
}
90
91
/** Initialize ACL list for HTTP server */
92
static bool InitHTTPAllowList()
93
1.12k
{
94
1.12k
    rpc_allow_subnets.clear();
95
1.12k
    rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8);  // always allow IPv4 local subnet
96
1.12k
    rpc_allow_subnets.emplace_back(LookupHost("::1", false).value());  // always allow IPv6 localhost
97
1.12k
    for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
98
13
        const CSubNet subnet{LookupSubNet(strAllow)};
99
13
        if (!subnet.IsValid()) {
100
1
            uiInterface.ThreadSafeMessageBox(
101
1
                Untranslated(strprintf("Invalid -rpcallowip subnet specification: %s. Valid values are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0.", strAllow)),
102
1
                CClientUIInterface::MSG_ERROR);
103
1
            return false;
104
1
        }
105
12
        rpc_allow_subnets.push_back(subnet);
106
12
    }
107
1.12k
    std::string strAllowed;
108
1.12k
    for (const CSubNet& subnet : rpc_allow_subnets)
109
2.25k
        strAllowed += subnet.ToString() + " ";
110
1.12k
    LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
111
1.12k
    return true;
112
1.12k
}
113
114
/** HTTP request method as string - use for logging only */
115
std::string_view RequestMethodString(HTTPRequestMethod m)
116
183k
{
117
183k
    switch (m) {
118
0
    using enum HTTPRequestMethod;
119
750
    case GET: return "GET";
120
183k
    case POST: return "POST";
121
0
    case HEAD: return "HEAD";
122
0
    case PUT: return "PUT";
123
5
    case UNKNOWN: return "unknown";
124
183k
    } // no default case, so the compiler can warn about missing cases
125
183k
    assert(false);
126
0
}
127
128
static void MaybeDispatchRequestToWorker(std::shared_ptr<HTTPRequest> hreq)
129
183k
{
130
    // Early address-based allow check
131
183k
    if (!ClientAllowed(hreq->GetPeer())) {
132
1
        LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
133
1
                 hreq->GetPeer().ToStringAddrPort());
134
1
        hreq->WriteReply(HTTP_FORBIDDEN);
135
1
        return;
136
1
    }
137
138
    // Early reject unknown HTTP methods
139
183k
    if (hreq->GetRequestMethod() == HTTPRequestMethod::UNKNOWN) {
140
5
        LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
141
5
                 hreq->GetPeer().ToStringAddrPort());
142
5
        hreq->WriteReply(HTTP_BAD_METHOD);
143
5
        return;
144
5
    }
145
146
    // Find registered handler for prefix
147
183k
    std::string strURI = hreq->GetURI();
148
183k
    std::string path;
149
183k
    LOCK(g_httppathhandlers_mutex);
150
183k
    std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
151
183k
    std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
152
212k
    for (; i != iend; ++i) {
153
212k
        bool match = false;
154
212k
        if (i->exactMatch)
155
183k
            match = (strURI == i->prefix);
156
28.2k
        else
157
28.2k
            match = strURI.starts_with(i->prefix);
158
212k
        if (match) {
159
183k
            path = strURI.substr(i->prefix.size());
160
183k
            break;
161
183k
        }
162
212k
    }
163
164
    // Dispatch to worker thread
165
183k
    if (i != iend) {
166
183k
        if (static_cast<int>(g_threadpool_http.WorkQueueSize()) >= g_max_queue_depth) {
167
1
            LogWarning("Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
168
1
            hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
169
1
            return;
170
1
        }
171
172
183k
        auto item = [req = hreq, in_path = std::move(path), fn = i->handler]() {
173
183k
            std::string err_msg;
174
183k
            try {
175
183k
                fn(req.get(), in_path);
176
183k
                return;
177
183k
            } catch (const std::exception& e) {
178
0
                LogWarning("Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(), e.what());
179
0
                err_msg = e.what();
180
0
            } catch (...) {
181
0
                LogWarning("Unknown error while processing request for '%s'", req->GetURI());
182
0
                err_msg = "unknown error";
183
0
            }
184
            // Reply so the client doesn't hang waiting for the response.
185
0
            req->WriteHeader("Connection", "close");
186
            // TODO: Implement specific error formatting for the REST and JSON-RPC servers responses.
187
0
            req->WriteReply(HTTP_INTERNAL_SERVER_ERROR, err_msg);
188
0
        };
189
190
183k
        if (auto res = g_threadpool_http.Submit(std::move(item)); !res.has_value()) {
191
0
            Assume(hreq.use_count() == 1); // ensure request will be deleted
192
            // Both SubmitError::Inactive and SubmitError::Interrupted mean shutdown
193
0
            LogWarning("HTTP request rejected during server shutdown: '%s'", SubmitErrorString(res.error()));
194
0
            hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Request rejected during server shutdown");
195
0
            return;
196
0
        }
197
183k
    } else {
198
9
        hreq->WriteReply(HTTP_NOT_FOUND);
199
9
    }
200
183k
}
201
202
static void RejectRequest(std::unique_ptr<http_bitcoin::HTTPRequest> hreq)
203
0
{
204
0
    LogDebug(BCLog::HTTP, "Rejecting request while shutting down");
205
0
    hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE);
206
0
}
207
208
static std::vector<std::pair<std::string, uint16_t>> GetBindAddresses()
209
1.12k
{
210
1.12k
    uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
211
1.12k
    std::vector<std::pair<std::string, uint16_t>> endpoints;
212
213
    // Determine what addresses to bind to
214
    // To prevent misconfiguration and accidental exposure of the RPC
215
    // interface, require -rpcallowip and -rpcbind to both be specified
216
    // together. If either is missing, ignore both values, bind to localhost
217
    // instead, and log warnings.
218
1.12k
    if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
219
1.11k
        endpoints.emplace_back("::1", http_port);
220
1.11k
        endpoints.emplace_back("127.0.0.1", http_port);
221
1.11k
        if (!gArgs.GetArgs("-rpcallowip").empty()) {
222
3
            LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
223
3
        }
224
1.11k
        if (!gArgs.GetArgs("-rpcbind").empty()) {
225
0
            LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
226
0
        }
227
1.11k
    } else { // Specific bind addresses
228
14
        for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
229
14
            uint16_t port{http_port};
230
14
            std::string host;
231
14
            if (!SplitHostPort(strRPCBind, port, host)) {
232
0
                LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
233
0
                return {}; // empty
234
0
            }
235
14
            endpoints.emplace_back(host, port);
236
14
        }
237
9
    }
238
1.12k
    return endpoints;
239
1.12k
}
240
241
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
242
2.23k
{
243
2.23k
    LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
244
2.23k
    LOCK(g_httppathhandlers_mutex);
245
2.23k
    pathHandlers.emplace_back(prefix, exactMatch, handler);
246
2.23k
}
247
248
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
249
18.6k
{
250
18.6k
    LOCK(g_httppathhandlers_mutex);
251
18.6k
    std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
252
18.6k
    std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
253
18.6k
    for (; i != iend; ++i)
254
2.23k
        if (i->prefix == prefix && i->exactMatch == exactMatch)
255
2.23k
            break;
256
18.6k
    if (i != iend)
257
2.23k
    {
258
2.23k
        LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
259
2.23k
        pathHandlers.erase(i);
260
2.23k
    }
261
18.6k
}
262
263
namespace http_bitcoin {
264
using util::Split;
265
266
std::optional<std::string> HTTPHeaders::FindFirst(const std::string_view key) const
267
778k
{
268
3.55M
    for (const auto& item : m_headers) {
269
3.55M
        if (CaseInsensitiveEqual(key, item.first)) {
270
368k
            return item.second;
271
368k
        }
272
3.55M
    }
273
409k
    return std::nullopt;
274
778k
}
275
276
std::vector<std::string_view> HTTPHeaders::FindAll(const std::string_view key) const
277
227k
{
278
227k
    std::vector<std::string_view> ret;
279
1.35M
    for (const auto& item : m_headers) {
280
1.35M
        if (CaseInsensitiveEqual(key, item.first)) {
281
226k
            ret.push_back(item.second);
282
226k
        }
283
1.35M
    }
284
227k
    return ret;
285
227k
}
286
287
void HTTPHeaders::Write(std::string&& key, std::string&& value)
288
1.91M
{
289
1.91M
    m_headers.emplace_back(std::move(key), std::move(value));
290
1.91M
}
291
292
void HTTPHeaders::RemoveAll(std::string_view key)
293
1.10k
{
294
3.32k
    auto moved = std::ranges::remove_if(m_headers, [key] (auto& pair) {
295
3.32k
        return CaseInsensitiveEqual(key, pair.first);
296
3.32k
    });
297
1.10k
    m_headers.erase(moved.begin(), moved.end());
298
1.10k
}
299
300
bool HTTPHeaders::Read(util::LineReader& reader)
301
227k
{
302
    // Headers https://httpwg.org/specs/rfc9110.html#rfc.section.6.3
303
    // A sequence of Field Lines https://httpwg.org/specs/rfc9110.html#rfc.section.5.2
304
1.58M
    while (auto maybe_line = reader.ReadLine()) {
305
1.58M
        if (reader.Consumed() > MAX_HEADERS_SIZE) throw std::runtime_error("HTTP headers exceed size limit");
306
307
1.58M
        const std::string_view& line = *maybe_line;
308
309
        // An empty line indicates end of the headers section https://www.rfc-editor.org/rfc/rfc2616#section-4
310
1.58M
        if (line.empty()) return true;
311
312
        // "Field values containing CR, LF, or NUL characters are invalid and dangerous"
313
        // https://httpwg.org/specs/rfc9110.html#rfc.section.5.5
314
        // A sender MUST NOT generate a bare CR (a CR character not immediately followed by LF)
315
        // within any protocol elements other than the content.
316
        // A recipient of such a bare CR MUST consider that element to be invalid...
317
        // https://httpwg.org/specs/rfc9112.html#rfc.section.2.2
318
1.36M
        if (line.find_first_of("\r\n\0", 0, 3) != std::string_view::npos) throw std::runtime_error("Header contains invalid character");
319
320
        // Header line must have at least one ":"
321
        // keys are not allowed to have delimiters like ":" but values are
322
        // https://httpwg.org/specs/rfc9110.html#rfc.section.5.6.2
323
1.36M
        const size_t pos{line.find(':')};
324
1.36M
        if (pos == std::string_view::npos) throw std::runtime_error("HTTP header missing colon (:)");
325
326
        // Whitespace is strictly not allowed in the field-name (key)
327
        // https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2
328
1.36M
        std::string_view key = line.substr(0, pos);
329
1.36M
        if (key.find_first_of(" \t\n\r\f\v") != std::string_view::npos) throw std::runtime_error("Invalid header field-name contains whitespace");
330
        // Whitespace is optional in the value and can be trimmed
331
1.36M
        std::string value = util::TrimString(std::string_view(line).substr(pos + 1));
332
333
        // Header keys are Field Names: https://httpwg.org/specs/rfc9110.html#fields.names
334
        // which consist of "tokens": https://httpwg.org/specs/rfc9110.html#rfc.section.5.6.2
335
        // that can not be empty.
336
1.36M
        if (key.empty()) throw std::runtime_error("Empty HTTP header name");
337
338
1.36M
        Write(std::string(key), std::move(value));
339
1.36M
    }
340
341
54
    return false;
342
227k
}
343
344
std::string HTTPHeaders::Stringify() const
345
183k
{
346
183k
    std::string out;
347
552k
    for (const auto& [key, value] : m_headers) {
348
552k
        out += key + ": " + value + "\r\n";
349
552k
    }
350
351
    // Headers are terminated by an empty line
352
183k
    out += "\r\n";
353
354
183k
    return out;
355
183k
}
356
357
std::string HTTPResponse::StringifyHeaders() const
358
183k
{
359
183k
    return strprintf("HTTP/%d.%d %d %s\r\n%s",
360
183k
                     m_version.major,
361
183k
                     m_version.minor,
362
183k
                     m_status,
363
183k
                     HTTPStatusReasonString(m_status),
364
183k
                     m_headers.Stringify());
365
183k
}
366
367
bool HTTPRequest::LoadControlData(LineReader& reader)
368
227k
{
369
227k
    auto maybe_line = reader.ReadLine();
370
227k
    if (!maybe_line) return false;
371
227k
    const std::string_view& request_line = *maybe_line;
372
373
    // Request Line aka Control Data https://httpwg.org/specs/rfc9110.html#rfc.section.6.2
374
    // Three words separated by spaces, terminated by \n or \r\n
375
227k
    if (request_line.length() < MIN_REQUEST_LINE_LENGTH) throw std::runtime_error("HTTP request line too short");
376
377
    // NUL is not a valid tchar and would silently truncate
378
    // C-string-based parsers rather than being rejected as malformed.
379
    // tchar: https://www.rfc-editor.org/info/rfc7230/#section-3.2.6
380
227k
    if (request_line.find('\0') != std::string_view::npos) throw std::runtime_error("Invalid request line contains NUL");
381
382
227k
    const std::vector<std::string_view> parts{Split<std::string_view>(request_line, " ")};
383
227k
    if (parts.size() != 3) throw std::runtime_error("HTTP request line malformed");
384
385
227k
    if (parts[0] == "GET") {
386
828
        m_method = HTTPRequestMethod::GET;
387
226k
    } else if (parts[0] == "POST") {
388
226k
        m_method = HTTPRequestMethod::POST;
389
226k
    } else if (parts[0] == "HEAD") {
390
0
        m_method = HTTPRequestMethod::HEAD;
391
6
    } else if (parts[0] == "PUT") {
392
0
        m_method = HTTPRequestMethod::PUT;
393
6
    } else {
394
6
        m_method = HTTPRequestMethod::UNKNOWN;
395
6
    }
396
397
227k
    m_target = parts[1];
398
399
227k
    if (parts[2].rfind("HTTP/") != 0) throw std::runtime_error("HTTP request line malformed");
400
401
    // Version is exactly two decimal digits separated by a decimal point
402
    // https://httpwg.org/specs/rfc9110.html#rfc.section.2.5
403
227k
    const std::vector<std::string_view> version_parts{Split<std::string_view>(parts[2].substr(5), ".")};
404
227k
    if (version_parts.size() != 2) throw std::runtime_error("HTTP request line malformed");
405
227k
    if (version_parts[0].size() != 1 || version_parts[1].size() != 1) throw std::runtime_error("HTTP bad version");
406
227k
    auto major = ToIntegral<uint8_t>(version_parts[0]);
407
227k
    auto minor = ToIntegral<uint8_t>(version_parts[1]);
408
227k
    if (!major || !minor || major != 1 || minor > 9) throw std::runtime_error("HTTP bad version");
409
227k
    m_version.major = major.value();
410
227k
    m_version.minor = minor.value();
411
412
227k
    return true;
413
227k
}
414
415
bool HTTPRequest::LoadHeaders(LineReader& reader)
416
227k
{
417
227k
    return m_headers.Read(reader);
418
227k
}
419
420
bool HTTPRequest::LoadBody(LineReader& reader)
421
227k
{
422
    // https://httpwg.org/specs/rfc9112.html#message.body
423
227k
    auto transfer_encoding_header = m_headers.FindFirst("Transfer-Encoding");
424
227k
    if (transfer_encoding_header && ToLower(transfer_encoding_header.value()) == "chunked") {
425
        // Transfer-Encoding: https://datatracker.ietf.org/doc/html/rfc7230.html#section-3.3.1
426
        // Chunked Transfer Coding: https://datatracker.ietf.org/doc/html/rfc7230.html#section-4.1
427
        // see evhttp_handle_chunked_read() in libevent http.c
428
1.61k
        while (reader.Remaining() > 0) {
429
1.61k
            auto maybe_chunk_size = reader.ReadLine();
430
1.61k
            if (!maybe_chunk_size) return false;
431
432
            // Allow (but ignore) Chunk Extensions
433
            // See https://www.rfc-editor.org/rfc/rfc9112.html#name-chunk-extensions
434
1.61k
            std::string_view chunk_size_noext{maybe_chunk_size.value()};
435
1.61k
            const auto semicolon_pos = chunk_size_noext.find(';');
436
1.61k
            if (semicolon_pos != chunk_size_noext.npos) {
437
3
                chunk_size_noext.remove_suffix(chunk_size_noext.size() - semicolon_pos);
438
3
            }
439
440
1.61k
            const auto chunk_size{ToIntegral<uint64_t>(util::TrimStringView(chunk_size_noext), /*base=*/16)};
441
1.61k
            if (!chunk_size) throw std::runtime_error("Cannot parse chunk length value");
442
443
1.61k
            if ((m_body.size() > MAX_BODY_SIZE) ||
444
1.61k
                (*chunk_size > MAX_BODY_SIZE - m_body.size()))
445
2
                throw ContentTooLargeError("Chunk will exceed max body size");
446
447
            // Last chunk has size 0
448
1.61k
            if (*chunk_size == 0) {
449
                // Allow (but ignore) Chunked Trailer section, by
450
                // reading CRLF-terminated lines until we read an empty line,
451
                // which indicates the end of this request.
452
                // See https://httpwg.org/specs/rfc9112.html#rfc.section.7.1.2
453
5
                const size_t trailer_start{reader.Consumed()};
454
6
                while (true) {
455
6
                    auto maybe_trailer = reader.ReadLine();
456
6
                    if (reader.Consumed() - trailer_start > MAX_HEADERS_SIZE) {
457
0
                        throw std::runtime_error("HTTP chunked trailer exceeds size limit");
458
0
                    }
459
6
                    if (!maybe_trailer) return false;
460
6
                    if (maybe_trailer->empty()) break;
461
6
                }
462
                // Complete request has been parsed, reader is now pointing
463
                // to beginning of next request or end of the buffer.
464
5
                return true;
465
5
            }
466
467
            // We are still expecting more data for this chunk
468
1.60k
            if (reader.Remaining() < *chunk_size) {
469
518
                return false;
470
518
            }
471
472
            // Pack chunk onto body
473
1.08k
            m_body += reader.ReadLength(*chunk_size);
474
475
            // Even though every chunk size is explicitly declared,
476
            // they are still terminated by a CRLF we don't need,
477
            // just consume it here.
478
1.08k
            auto crlf = reader.ReadLine();
479
1.08k
            if (!crlf) {
480
                // CRLF not found before end of buffer: it has not been received by our socket yet.
481
1
                return false;
482
1
            }
483
            // CRLF was found but there was unexpected data after the chunk_sized chunk
484
1.08k
            if (!crlf.value().empty()) throw std::runtime_error("Improperly terminated chunk");
485
1.08k
        }
486
487
        // We read all the chunks but never got the last chunk, wait for client to send more
488
0
        return false;
489
227k
    } else {
490
        // No Content-length or Transfer-Encoding header means no body, see libevent evhttp_get_body()
491
227k
        auto content_length_values{m_headers.FindAll("Content-Length")};
492
227k
        if (content_length_values.empty()) return true;
493
494
        // Duplicate Content-Length headers are allowed only if they all have the same value
495
        // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.3
496
226k
        const auto& first_content_length_value{content_length_values[0]};
497
226k
        for (size_t i = 1; i < content_length_values.size(); ++i) {
498
3
            if (content_length_values[i] != first_content_length_value) throw std::runtime_error("Differing Content-Length values");
499
3
        }
500
501
226k
        const auto content_length{ToIntegral<uint64_t>(first_content_length_value)};
502
226k
        if (!content_length) throw std::runtime_error("Cannot parse Content-Length value");
503
504
226k
        if (*content_length > MAX_BODY_SIZE) throw ContentTooLargeError("Max body size exceeded");
505
506
        // Not enough data in buffer for expected body
507
226k
        if (reader.Remaining() < *content_length) return false;
508
509
183k
        m_body = reader.ReadLength(*content_length);
510
511
183k
        return true;
512
226k
    }
513
227k
}
514
515
void HTTPRequest::WriteReply(HTTPStatusCode status, std::span<const std::byte> reply_body)
516
183k
{
517
183k
    HTTPResponse res;
518
519
    // Some response headers are determined in advance and stored in the request
520
183k
    res.m_headers = std::move(m_response_headers);
521
522
    // Response version matches request version
523
183k
    res.m_version = m_version;
524
525
    // Add response code
526
183k
    res.m_status = status;
527
528
    // See libevent evhttp_response_needs_body()
529
    // Response headers are different if no body is needed
530
183k
    bool needs_body{status != HTTP_NO_CONTENT && (status < 100 || status >= 200)};
531
183k
    bool needs_content_length{false};
532
533
183k
    bool keep_alive{false};
534
535
    // See libevent evhttp_make_header_response()
536
    // Expected response headers depend on protocol version
537
183k
    if (m_version.major == 1) {
538
        // HTTP/1.0
539
183k
        if (m_version.minor == 0) {
540
0
            auto connection_header{m_headers.FindFirst("Connection")};
541
0
            if (connection_header && ToLower(connection_header.value()) == "keep-alive") {
542
0
                res.m_headers.Write("Connection", "keep-alive");
543
0
                keep_alive = true;
544
                // HTTP/1.0 connections are closed by default so EOF is sufficient
545
                // to indicate end of the body. Adding Content-Length a special case.
546
0
                if (needs_body) needs_content_length = true;
547
0
            }
548
0
        }
549
550
        // HTTP/1.1
551
183k
        if (m_version.minor >= 1) {
552
183k
            const int64_t now_seconds{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};
553
183k
            res.m_headers.Write("Date", FormatRFC1123DateTime(now_seconds));
554
555
            // HTTP/1.1 connections are kept alive by default and always require Content-Length.
556
183k
            if (needs_body) needs_content_length = true;
557
558
            // Default for HTTP/1.1
559
183k
            keep_alive = true;
560
183k
        }
561
183k
    }
562
563
183k
    if (needs_content_length) {
564
183k
        res.m_headers.Write("Content-Length", util::ToString(reply_body.size()));
565
183k
    }
566
567
183k
    if (needs_body && !res.m_headers.FindFirst("Content-Type")) {
568
        // Default type from libevent evhttp_new_object()
569
87
        res.m_headers.Write("Content-Type", "text/html; charset=ISO-8859-1");
570
87
    }
571
572
183k
    auto connection_header{m_headers.FindFirst("Connection")};
573
183k
    if (connection_header && ToLower(connection_header.value()) == "close") {
574
        // Might not exist already but we need to replace it, not append to it
575
1.10k
        res.m_headers.RemoveAll("Connection");
576
577
1.10k
        res.m_headers.Write("Connection", "close");
578
1.10k
        keep_alive = false;
579
1.10k
    }
580
581
183k
    m_client->m_keep_alive = keep_alive;
582
583
    // Serialize the response headers
584
183k
    const std::string headers{res.StringifyHeaders()};
585
183k
    const auto headers_bytes{std::as_bytes(std::span{headers})};
586
587
183k
    bool send_buffer_was_empty{false};
588
    // Fill the send buffer with the complete serialized response headers + body
589
183k
    {
590
183k
        LOCK(m_client->m_send_mutex);
591
183k
        send_buffer_was_empty = m_client->m_send_buffer.empty();
592
183k
        m_client->m_send_buffer.insert(m_client->m_send_buffer.end(), headers_bytes.begin(), headers_bytes.end());
593
594
        // We've been using std::span up until now but it is finally time to copy
595
        // data. The original data will go out of scope when WriteReply() returns.
596
        // This is analogous to the memcpy() in libevent's evbuffer_add()
597
183k
        m_client->m_send_buffer.insert(m_client->m_send_buffer.end(), reply_body.begin(), reply_body.end());
598
599
        // If the buffer already held data, the I/O thread is (or soon will be)
600
        // draining it, so flag that there is more data to send. This must happen
601
        // while holding m_send_mutex and while the buffer is known non-empty:
602
        // setting m_send_ready after releasing the lock would race with the I/O
603
        // thread draining the buffer to empty and clearing m_send_ready in
604
        // between, leaving m_send_ready set on an empty buffer. The I/O loop would
605
        // then only ever poll the socket for writeability, never read the client's
606
        // next request, and wedge the connection.
607
183k
        if (!send_buffer_was_empty) m_client->m_send_ready = true;
608
183k
    }
609
610
183k
    LogDebug(
611
183k
        BCLog::HTTP,
612
183k
        "HTTPResponse (status code: %d size: %lld) added to send buffer for client %s (id=%llu)",
613
183k
        status,
614
183k
        headers_bytes.size() + reply_body.size(),
615
183k
        m_client->m_origin,
616
183k
        m_client->m_id);
617
618
    // If the send buffer was empty before we wrote this reply, we can try an
619
    // optimistic send akin to CConnman::PushMessage() in which we
620
    // push the data directly out the socket to client right now, instead
621
    // of waiting for the next iteration of the I/O loop.
622
183k
    if (send_buffer_was_empty) {
623
183k
        m_client->MaybeSendBytesFromBuffer();
624
183k
    }
625
626
    // Signal to the I/O loop that we are ready to handle the next request.
627
183k
    m_client->m_req_busy = false;
628
183k
}
629
630
CService HTTPRequest::GetPeer() const
631
366k
{
632
366k
    return m_client->m_addr;
633
366k
}
634
635
std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string_view key) const
636
86
{
637
86
    return GetQueryParameterFromUri(m_target, key);
638
86
}
639
640
// See libevent http.c evhttp_parse_query_impl()
641
// and https://www.rfc-editor.org/rfc/rfc3986#section-3.4
642
std::optional<std::string> GetQueryParameterFromUri(const std::string_view uri, const std::string_view key)
643
100
{
644
    // find query in URI
645
100
    size_t start = uri.find('?');
646
100
    if (start == std::string::npos) return std::nullopt;
647
90
    size_t end = uri.find('#', start);
648
90
    if (end == std::string::npos) {
649
90
        end = uri.length();
650
90
    }
651
90
    const std::string_view query{uri.data() + start + 1, end - start - 1};
652
    // find requested parameter in query
653
90
    const std::vector<std::string_view> params{Split<std::string_view>(query, "&")};
654
117
    for (const std::string_view& param : params) {
655
117
        size_t delim = param.find('=');
656
117
        if (key == UrlDecode(param.substr(0, delim))) {
657
78
            if (delim == std::string::npos) {
658
0
                return "";
659
78
            } else {
660
78
                return std::string(UrlDecode(param.substr(delim + 1)));
661
78
            }
662
78
        }
663
117
    }
664
12
    return std::nullopt;
665
90
}
666
667
std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string_view hdr) const
668
183k
{
669
183k
    std::optional<std::string> found{m_headers.FindFirst(hdr)};
670
183k
    return std::pair{found.has_value(), std::move(found).value_or("")};
671
183k
}
672
673
void HTTPRequest::WriteHeader(std::string&& hdr, std::string&& value)
674
183k
{
675
183k
    m_response_headers.Write(std::move(hdr), std::move(value));
676
183k
}
677
678
util::Expected<void, std::string> HTTPServer::BindAndStartListening(const CService& to)
679
2.24k
{
680
    // Create socket for listening for incoming connections
681
2.24k
    sockaddr_storage storage;
682
2.24k
    auto sa = reinterpret_cast<sockaddr*>(&storage);
683
2.24k
    socklen_t len{sizeof(storage)};
684
2.24k
    if (!to.GetSockAddr(sa, &len)) {
685
1
        return util::Unexpected{strprintf("Bind address family for %s not supported", to.ToStringAddrPort())};
686
1
    }
687
688
2.24k
    std::unique_ptr<Sock> sock{CreateSock(to.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP)};
689
2.24k
    if (!sock) {
690
0
        return util::Unexpected{strprintf("Cannot create %s listen socket: %s",
691
0
                                          to.ToStringAddrPort(),
692
0
                                          NetworkErrorString(WSAGetLastError()))};
693
0
    }
694
695
    // Allow binding if the port is still in TIME_WAIT state after
696
    // the program was closed and restarted.
697
2.24k
    if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
698
0
        LogDebug(BCLog::HTTP,
699
0
                 "Cannot set SO_REUSEADDR on %s listen socket: %s, continuing anyway",
700
0
                 to.ToStringAddrPort(),
701
0
                 NetworkErrorString(WSAGetLastError()));
702
0
    }
703
704
    // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
705
    // and enable it by default or not. Try to enable it, if possible.
706
2.24k
    if (to.IsIPv6()) {
707
1.11k
#ifdef IPV6_V6ONLY
708
1.11k
        if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
709
0
            LogDebug(BCLog::HTTP,
710
0
                     "Cannot set IPV6_V6ONLY on %s listen socket: %s, continuing anyway",
711
0
                     to.ToStringAddrPort(),
712
0
                     NetworkErrorString(WSAGetLastError()));
713
0
        }
714
1.11k
#endif
715
#ifdef WIN32
716
        int prot_level{PROTECTION_LEVEL_UNRESTRICTED};
717
        if (sock->SetSockOpt(IPPROTO_IPV6,
718
                             IPV6_PROTECTION_LEVEL,
719
                             &prot_level,
720
                             sizeof(prot_level)) == SOCKET_ERROR) {
721
            LogDebug(BCLog::HTTP,
722
                     "Cannot set IPV6_PROTECTION_LEVEL on %s listen socket: %s, continuing anyway",
723
                     to.ToStringAddrPort(),
724
                     NetworkErrorString(WSAGetLastError()));
725
        }
726
#endif
727
1.11k
    }
728
729
2.24k
    if (sock->Bind(sa, len) == SOCKET_ERROR) {
730
0
        const int err{WSAGetLastError()};
731
0
        if (err == WSAEADDRINUSE) {
732
0
            return util::Unexpected{strprintf("Unable to bind to %s on this computer. %s is probably already running.",
733
0
                                              to.ToStringAddrPort(),
734
0
                                              CLIENT_NAME)};
735
0
        } else {
736
0
            return util::Unexpected{strprintf("Unable to bind to %s on this computer (bind returned error %s)",
737
0
                                              to.ToStringAddrPort(),
738
0
                                              NetworkErrorString(err))};
739
0
        }
740
0
    }
741
742
    // Listen for incoming connections
743
2.24k
    if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) {
744
0
        return util::Unexpected{strprintf("Cannot listen on %s: %s",
745
0
                                          to.ToStringAddrPort(),
746
0
                                          NetworkErrorString(WSAGetLastError()))};
747
0
    }
748
749
2.24k
    m_listen.emplace_back(std::move(sock));
750
751
2.24k
    return {};
752
2.24k
}
753
754
void HTTPServer::StopListening()
755
1.12k
{
756
1.12k
    m_listen.clear();
757
1.12k
}
758
759
void HTTPServer::StartSocketsThreads()
760
1.11k
{
761
1.11k
    m_thread_socket_handler = std::thread(&util::TraceThread,
762
1.11k
                                          "http",
763
1.11k
                                          [this] { ThreadSocketHandler(); });
764
1.11k
}
765
766
void HTTPServer::JoinSocketsThreads()
767
1.12k
{
768
1.12k
    if (m_thread_socket_handler.joinable()) {
769
1.11k
        m_thread_socket_handler.join();
770
1.11k
    }
771
1.12k
}
772
773
std::unique_ptr<Sock> HTTPServer::AcceptConnection(const Sock& listen_sock, CService& addr)
774
3.20k
{
775
    // Make sure we only operate on our own listening sockets
776
3.20k
    Assume(std::ranges::any_of(m_listen, [&](const auto& sock) { return sock.get() == &listen_sock; }));
777
778
3.20k
    sockaddr_storage storage;
779
3.20k
    socklen_t len{sizeof(storage)};
780
3.20k
    auto sa = reinterpret_cast<sockaddr*>(&storage);
781
782
3.20k
    auto sock{listen_sock.Accept(sa, &len)};
783
784
3.20k
    if (!sock) {
785
0
        const int err{WSAGetLastError()};
786
0
        if (err != WSAEWOULDBLOCK) {
787
0
            LogDebug(BCLog::HTTP,
788
0
                     "Cannot accept new connection: %s",
789
0
                     NetworkErrorString(err));
790
0
        }
791
0
        return {};
792
0
    }
793
794
    // The OS handed us a valid socket but we can't determine its source address.
795
    // In the unlikely event this occurs, the invalid address will be rejected
796
    // by the downstream ClientAllowed() check.
797
3.20k
    if (!addr.SetSockAddr(sa, len)) {
798
0
        LogDebug(BCLog::HTTP,
799
0
                 "Unknown socket family");
800
0
    }
801
802
3.20k
    return sock;
803
3.20k
}
804
805
HTTPServer::Id HTTPServer::GetNewId()
806
3.20k
{
807
3.20k
    return m_next_id.fetch_add(1, std::memory_order_relaxed);
808
3.20k
}
809
810
void HTTPServer::NewSockAccepted(std::unique_ptr<Sock>&& sock, const CService& addr)
811
3.20k
{
812
3.20k
    if (!sock->IsSelectable()) {
813
0
        LogDebug(BCLog::HTTP,
814
0
                 "connection from %s dropped: non-selectable socket",
815
0
                 addr.ToStringAddrPort());
816
0
        return;
817
0
    }
818
819
    // According to the internet TCP_NODELAY is not carried into accepted sockets
820
    // on all platforms.  Set it again here just to be sure.
821
3.20k
    if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
822
0
        LogDebug(BCLog::HTTP, "connection from %s: unable to set TCP_NODELAY, continuing anyway",
823
0
                 addr.ToStringAddrPort());
824
0
    }
825
826
3.20k
    const Id id{GetNewId()};
827
828
3.20k
    m_connected.push_back(std::make_shared<HTTPRemoteClient>(id, addr, std::move(sock)));
829
    // Report back to the main thread
830
3.20k
    m_connected_size.fetch_add(1, std::memory_order_relaxed);
831
832
3.20k
    LogDebug(BCLog::HTTP,
833
3.20k
             "HTTP Connection accepted from %s (id=%llu)",
834
3.20k
             addr.ToStringAddrPort(), id);
835
3.20k
}
836
837
void HTTPServer::SocketHandlerConnected(const IOReadiness& io_readiness) const
838
400k
{
839
1.21M
    for (const auto& [sock, events] : io_readiness.events_per_sock) {
840
1.21M
        if (m_interrupt_net) {
841
1.11k
            return;
842
1.11k
        }
843
844
1.21M
        auto it{io_readiness.httpclients_per_sock.find(sock)};
845
1.21M
        if (it == io_readiness.httpclients_per_sock.end()) {
846
798k
            continue;
847
798k
        }
848
419k
        const std::shared_ptr<HTTPRemoteClient>& client{it->second};
849
850
419k
        bool send_ready = events.occurred & Sock::SendEvent;
851
419k
        bool recv_ready = events.occurred & Sock::RecvEvent;
852
419k
        bool err_ready = events.occurred & Sock::ErrorEvent;
853
854
419k
        if (send_ready) {
855
            // Try to send as much data as is ready for this client.
856
            // If there's an error we can skip the receive phase for this client
857
            // because we need to disconnect.
858
434
            if (!client->MaybeSendBytesFromBuffer()) {
859
0
                recv_ready = false;
860
0
            }
861
434
        }
862
863
419k
        if (recv_ready || err_ready) {
864
229k
            std::byte buf[0x10000]; // typical socket buffer is 8K-64K
865
866
229k
            const ssize_t nrecv{WITH_LOCK(
867
229k
                client->m_sock_mutex,
868
229k
                return client->m_sock->Recv(buf, sizeof(buf), MSG_DONTWAIT);)};
869
870
229k
            if (nrecv < 0) {
871
0
                const int err = WSAGetLastError();
872
0
                if (IOErrorIsPermanent(err)) {
873
0
                    LogDebug(
874
0
                        BCLog::HTTP,
875
0
                        "Permanent read error from %s (id=%llu): %s",
876
0
                        client->m_origin,
877
0
                        client->m_id,
878
0
                        NetworkErrorString(err));
879
0
                    client->m_disconnect = true;
880
0
                }
881
229k
            } else if (nrecv == 0) {
882
2.11k
                LogDebug(
883
2.11k
                    BCLog::HTTP,
884
2.11k
                    "Received EOF from %s (id=%llu)",
885
2.11k
                    client->m_origin,
886
2.11k
                    client->m_id);
887
2.11k
                client->m_disconnect = true;
888
227k
            } else {
889
                // Reset idle timeout
890
227k
                client->m_idle_since = Now<SteadySeconds>();
891
892
                // Prevent disconnect until all requests are completely handled.
893
227k
                client->m_connection_busy = true;
894
895
                // Copy data from socket buffer to client receive buffer
896
227k
                client->m_recv_buffer.insert(
897
227k
                    client->m_recv_buffer.end(),
898
227k
                    buf,
899
227k
                    buf + nrecv);
900
227k
            }
901
229k
        }
902
        // Process as much received data as we can.
903
        // This executes for every client whether or not reading or writing
904
        // took place because it also (might) parse a request we have already
905
        // received and pass it to a worker thread.
906
419k
        MaybeDispatchRequestsFromClient(client);
907
419k
    }
908
400k
}
909
910
void HTTPServer::SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
911
400k
{
912
400k
    if (m_stop_accepting) return;
913
796k
    for (const auto& sock : m_listen) {
914
796k
        if (m_interrupt_net) {
915
2
            return;
916
2
        }
917
796k
        const auto it = events_per_sock.find(sock);
918
796k
        if (it != events_per_sock.end() && it->second.occurred & Sock::RecvEvent) {
919
3.20k
            CService addr_accepted;
920
921
3.20k
            auto sock_accepted{AcceptConnection(*sock, addr_accepted)};
922
923
3.20k
            if (sock_accepted) {
924
3.20k
                NewSockAccepted(std::move(sock_accepted), addr_accepted);
925
3.20k
            }
926
3.20k
        }
927
796k
    }
928
398k
}
929
930
HTTPServer::IOReadiness HTTPServer::GenerateWaitSockets() const
931
400k
{
932
400k
    IOReadiness io_readiness;
933
934
800k
    for (const auto& sock : m_listen) {
935
800k
        io_readiness.events_per_sock.emplace(sock, Sock::Events{Sock::RecvEvent});
936
800k
    }
937
938
419k
    for (const auto& http_client : m_connected) {
939
        // Safely copy the shared pointer to the socket
940
419k
        std::shared_ptr<Sock> sock{WITH_LOCK(http_client->m_sock_mutex, return http_client->m_sock;)};
941
942
        // Check if client is ready to send data. Don't try to receive again
943
        // until the send buffer is cleared (all data sent to client).
944
        // Keep this as a separate critical section from the m_sock_mutex one above:
945
        // never hold m_sock_mutex and m_send_mutex at the same time here.
946
        // MaybeSendBytesFromBuffer() locks m_send_mutex then m_sock_mutex, so nesting
947
        // them in the opposite order here would risk a lock-order inversion deadlock.
948
419k
        const bool send_ready{WITH_LOCK(http_client->m_send_mutex, return http_client->m_send_ready;)};
949
419k
        Sock::Event event = (send_ready ? Sock::SendEvent : Sock::RecvEvent);
950
419k
        io_readiness.events_per_sock.emplace(sock, Sock::Events{event});
951
419k
        io_readiness.httpclients_per_sock.emplace(sock, http_client);
952
419k
    }
953
954
400k
    return io_readiness;
955
400k
}
956
957
/// \anchor http
958
void HTTPServer::ThreadSocketHandler()
959
1.11k
{
960
401k
    while (!m_interrupt_net) {
961
        // Check for the readiness of the already connected sockets and the
962
        // listening sockets in one call ("readiness" as in poll(2) or
963
        // select(2)). If none are ready, wait for a short while and return
964
        // empty sets.
965
400k
        auto io_readiness{GenerateWaitSockets()};
966
400k
        if (io_readiness.events_per_sock.empty() ||
967
            // WaitMany() may as well be a static method, the context of the first Sock in the vector is not relevant.
968
400k
            !io_readiness.events_per_sock.begin()->first->WaitMany(SELECT_TIMEOUT,
969
400k
                                                                   io_readiness.events_per_sock)) {
970
0
            m_interrupt_net.sleep_for(SELECT_TIMEOUT);
971
0
        }
972
973
        // Service (send/receive) each of the already connected sockets.
974
400k
        SocketHandlerConnected(io_readiness);
975
976
        // Accept new connections from listening sockets.
977
400k
        SocketHandlerListening(io_readiness.events_per_sock);
978
979
        // Disconnect any clients that have been flagged.
980
400k
        DisconnectClients();
981
400k
    }
982
1.11k
}
983
984
void HTTPServer::MaybeDispatchRequestsFromClient(const std::shared_ptr<HTTPRemoteClient>& client) const
985
419k
{
986
    // Try reading (potentially multiple) HTTP requests from the buffer
987
603k
    while (!client->m_recv_buffer.empty()) {
988
        // Create a new request object and try to fill it with data from the receive buffer
989
227k
        auto req = std::make_unique<HTTPRequest>(client);
990
227k
        try {
991
            // Stop reading if we need more data from the client to parse a complete request
992
227k
            if (!client->ReadRequest(*req)) break;
993
227k
        } catch (const ContentTooLargeError& e) {
994
2
            LogDebug(
995
2
                BCLog::HTTP,
996
2
                "HTTP request body too large from client %s (id=%llu): %s",
997
2
                client->m_origin,
998
2
                client->m_id,
999
2
                e.what());
1000
1001
2
            req->WriteReply(HTTP_CONTENT_TOO_LARGE);
1002
2
            client->m_disconnect = true;
1003
2
            return;
1004
10
        } catch (const std::runtime_error& e) {
1005
10
            LogDebug(
1006
10
                BCLog::HTTP,
1007
10
                "Error reading HTTP request from client %s (id=%llu): %s",
1008
10
                client->m_origin,
1009
10
                client->m_id,
1010
10
                e.what());
1011
1012
            // We failed to read a complete request from the buffer
1013
10
            req->WriteReply(HTTP_BAD_REQUEST);
1014
10
            client->m_disconnect = true;
1015
10
            return;
1016
10
        }
1017
1018
        // We read a complete request from the buffer into the queue
1019
183k
        LogDebug(
1020
183k
            BCLog::HTTP,
1021
183k
            "Received a %s request for %s from %s (id=%llu)",
1022
183k
            RequestMethodString(req->m_method),
1023
183k
            req->m_target,
1024
183k
            client->m_origin,
1025
183k
            client->m_id);
1026
1027
        // add request to client queue
1028
183k
        client->m_req_queue.push_back(std::move(req));
1029
183k
    }
1030
1031
    // If we are already handling a request from
1032
    // this client, do nothing. We'll check again on the next I/O
1033
    // loop iteration.
1034
419k
    if (client->m_req_busy) return;
1035
1036
    // Otherwise, if there is a pending request in the queue, handle it.
1037
372k
    if (!client->m_req_queue.empty()) {
1038
183k
        LOCK(m_request_dispatcher_mutex);
1039
183k
        client->m_req_busy = true;
1040
183k
        m_request_dispatcher(std::move(client->m_req_queue.front()));
1041
183k
        client->m_req_queue.pop_front();
1042
183k
    }
1043
372k
}
1044
1045
void HTTPServer::DisconnectClients()
1046
400k
{
1047
400k
    const auto now{Now<SteadySeconds>()};
1048
400k
    size_t erased = std::erase_if(m_connected,
1049
422k
                                  [&](auto& client) {
1050
                                        // First check for idle timeout. We reset the timer when we send and receive data,
1051
                                        // but if the server is busy handling a request we should ignore the timeout until
1052
                                        // the reply is sent. If we did erase the shared_ptr<HTTPRemoteClient> reference in m_connected
1053
                                        // while the server is busy with a request, there would still be a reference in a worker
1054
                                        // thread keeping the socket open even after "disconnecting".
1055
422k
                                        const bool is_idle{m_rpcservertimeout.count() > 0 &&
1056
422k
                                                           now - client->m_idle_since.load() > m_rpcservertimeout &&
1057
422k
                                                           !client->m_req_busy};
1058
1059
                                        // Disconnect this client due to error, end of communication, or idle timeout.
1060
                                        // May drop unsent data if we are closing due to error.
1061
422k
                                        if (client->m_disconnect || is_idle) {
1062
2.22k
                                            if (is_idle) {
1063
5
                                                LogDebug(BCLog::HTTP,
1064
5
                                                         "HTTP client idle timeout %s (id=%llu)",
1065
5
                                                         client->m_origin,
1066
5
                                                         client->m_id);
1067
5
                                            }
1068
420k
                                        } else {
1069
                                            // Disconnect this client because the server is shutting
1070
                                            // down and we need to disconnect all clients...
1071
420k
                                            if (m_disconnect_all_clients) {
1072
                                                // ...unless we still have data for this client.
1073
981
                                                if (client->m_connection_busy) {
1074
                                                    // There is still data for this healthy-connected client.
1075
                                                    // Continue the I/O loop until all data is sent or an error is encountered.
1076
0
                                                    return false;
1077
981
                                                } else {
1078
                                                    // This is a healthy persistent connection (e.g. keep-alive)
1079
                                                    // but it's time to say goodbye.
1080
981
                                                    ;
1081
981
                                                }
1082
419k
                                            } else {
1083
                                                // No reason to disconnect.
1084
419k
                                                return false;
1085
419k
                                            }
1086
420k
                                        }
1087
                                        // No reason NOT to disconnect, log and remove.
1088
3.20k
                                        LogDebug(BCLog::HTTP,
1089
3.20k
                                                 "Disconnecting HTTP client %s (id=%llu)",
1090
3.20k
                                                 client->m_origin,
1091
3.20k
                                                 client->m_id);
1092
3.20k
                                        return true;
1093
422k
                                    });
1094
400k
    if (erased > 0) {
1095
        // Report back to the main thread
1096
3.09k
        m_connected_size.fetch_sub(erased, std::memory_order_relaxed);
1097
3.09k
    }
1098
400k
}
1099
1100
void HTTPServer::ClearConnectedClients()
1101
1.12k
{
1102
1.12k
    Assume(!m_thread_socket_handler.joinable()); // must be called after JoinSocketsThreads()
1103
1.12k
    if (m_connected.empty()) return;
1104
0
    LogWarning("Force-disconnecting %d HTTP client(s) that did not disconnect gracefully", m_connected.size());
1105
0
    m_connected_size.fetch_sub(m_connected.size(), std::memory_order_relaxed);
1106
0
    m_connected.clear();
1107
0
}
1108
1109
bool HTTPRemoteClient::ReadRequest(HTTPRequest& req)
1110
227k
{
1111
227k
    LineReader reader(m_recv_buffer, MAX_HEADERS_SIZE);
1112
1113
227k
    if (!req.LoadControlData(reader)) return false;
1114
227k
    if (!req.LoadHeaders(reader)) return false;
1115
227k
    if (!req.LoadBody(reader)) return false;
1116
1117
    // Remove the bytes read out of the buffer.
1118
    // If one of the above calls throws an error, the caller must
1119
    // catch it and disconnect the client.
1120
183k
    m_recv_buffer.erase(
1121
183k
        m_recv_buffer.begin(),
1122
183k
        m_recv_buffer.begin() + reader.Consumed());
1123
1124
183k
    return true;
1125
227k
}
1126
1127
bool HTTPRemoteClient::MaybeSendBytesFromBuffer()
1128
184k
{
1129
    // Send as much data from this client's buffer as we can
1130
184k
    LOCK(m_send_mutex);
1131
184k
    if (!m_send_buffer.empty()) {
1132
        // Socket flags (See kernel docs for send(2) and tcp(7) for more details).
1133
        // MSG_NOSIGNAL: If the remote end of the connection is closed,
1134
        //               fail with EPIPE (an error) as opposed to triggering
1135
        //               SIGPIPE which terminates the process.
1136
        // MSG_DONTWAIT: Makes the send operation non-blocking regardless of socket blocking mode.
1137
        // MSG_MORE:     We do not set this flag here because http responses are usually
1138
        //               small and we want the kernel to send them right away. Setting MSG_MORE
1139
        //               would "cork" the socket to prevent sending out partial frames.
1140
184k
        int flags{MSG_NOSIGNAL | MSG_DONTWAIT};
1141
1142
        // Try to send bytes through socket
1143
184k
        ssize_t bytes_sent;
1144
184k
        {
1145
184k
            LOCK(m_sock_mutex);
1146
184k
            bytes_sent = m_sock->Send(m_send_buffer.data(),
1147
184k
                                      m_send_buffer.size(),
1148
184k
                                      flags);
1149
184k
        }
1150
1151
184k
        if (bytes_sent < 0) {
1152
            // Something went wrong
1153
430
            const int err{WSAGetLastError()};
1154
430
            if (!IOErrorIsPermanent(err)) {
1155
                // The error can be safely ignored, try the send again on the next I/O loop.
1156
430
                m_send_ready = true;
1157
430
                m_connection_busy = true;
1158
430
                return true;
1159
430
            } else {
1160
                // Unrecoverable error, log and disconnect client.
1161
0
                LogDebug(
1162
0
                    BCLog::HTTP,
1163
0
                    "Error sending HTTP response data to client %s (id=%llu): %s",
1164
0
                    m_origin,
1165
0
                    m_id,
1166
0
                    NetworkErrorString(err));
1167
0
                m_send_ready = false;
1168
0
                m_disconnect = true;
1169
1170
                // Do not attempt to read from this client.
1171
0
                return false;
1172
0
            }
1173
430
        }
1174
1175
        // Successful send, remove sent bytes from our local buffer.
1176
183k
        Assume(static_cast<size_t>(bytes_sent) <= m_send_buffer.size());
1177
183k
        m_send_buffer.erase(m_send_buffer.begin(),
1178
183k
                            m_send_buffer.begin() + bytes_sent);
1179
1180
183k
        LogDebug(
1181
183k
            BCLog::HTTP,
1182
183k
            "Sent %d bytes to client %s (id=%llu)",
1183
183k
            bytes_sent,
1184
183k
            m_origin,
1185
183k
            m_id);
1186
1187
        // This check is inside the if(!empty) block meaning "there was data but now its gone".
1188
        // We wouldn't want to change the flags if MaybeSendBytesFromBuffer() was called
1189
        // on an already-empty m_send_buffer because the connection might have just been opened.
1190
183k
        if (m_send_buffer.empty()) {
1191
183k
            m_send_ready = false;
1192
183k
            m_connection_busy = false;
1193
1194
            // Our work is done here
1195
183k
            if (!m_keep_alive) {
1196
1.10k
                m_disconnect = true;
1197
                // Do not attempt to read from this client.
1198
1.10k
                return false;
1199
1.10k
            }
1200
183k
        } else {
1201
            // The send buffer isn't flushed yet, try to push more on the next loop.
1202
4
            m_send_ready = true;
1203
4
            m_connection_busy = true;
1204
4
        }
1205
1206
        // Finally, reset idle timeout
1207
182k
        m_idle_since = Now<SteadySeconds>();
1208
182k
    }
1209
1210
182k
    return true;
1211
184k
}
1212
1213
bool InitHTTPServer()
1214
1.12k
{
1215
1.12k
    if (!InitHTTPAllowList()) {
1216
1
        return false;
1217
1
    }
1218
1219
    // Create HTTPServer
1220
1.12k
    g_http_server = std::make_unique<HTTPServer>(MaybeDispatchRequestToWorker);
1221
1222
1.12k
    g_http_server->SetServerTimeout(std::chrono::seconds(gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)));
1223
1224
    // Bind HTTP server to specified addresses
1225
1.12k
    std::vector<std::pair<std::string, uint16_t>> endpoints{GetBindAddresses()};
1226
1.12k
    bool bind_success{false};
1227
2.24k
    for (const auto& [address_string, port] : endpoints) {
1228
2.24k
        LogInfo("Binding RPC on address %s port %i", address_string, port);
1229
2.24k
        const std::optional<CService> addr{Lookup(address_string, port, false)};
1230
2.24k
        if (addr) {
1231
2.24k
            if (addr->IsBindAny()) {
1232
0
                LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
1233
0
            }
1234
2.24k
            auto result{g_http_server->BindAndStartListening(addr.value())};
1235
2.24k
            if (!result) {
1236
0
                LogWarning("Binding RPC on address %s failed: %s", addr->ToStringAddrPort(), result.error());
1237
2.24k
            } else {
1238
2.24k
                bind_success = true;
1239
2.24k
            }
1240
2.24k
        } else {
1241
0
            LogWarning("Could not bind RPC on address %s port %i: Address lookup failed.", address_string, port);
1242
0
        }
1243
2.24k
    }
1244
1245
1.12k
    if (!bind_success) {
1246
0
        LogError("Unable to bind any endpoint for RPC server");
1247
0
        return false;
1248
0
    }
1249
1250
1.12k
    LogDebug(BCLog::HTTP, "Initialized HTTP server");
1251
1252
1.12k
    g_max_queue_depth = std::max(gArgs.GetArg<int>("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1);
1253
1.12k
    LogDebug(BCLog::HTTP, "set work queue of depth %d\n", g_max_queue_depth);
1254
1255
1.12k
    return true;
1256
1.12k
}
1257
1258
void StartHTTPServer()
1259
1.11k
{
1260
1.11k
    auto rpcThreads{std::max(gArgs.GetArg<int>("-rpcthreads", DEFAULT_HTTP_THREADS), 1)};
1261
1.11k
    LogInfo("Starting HTTP server with %d worker threads", rpcThreads);
1262
1.11k
    g_threadpool_http.Start(rpcThreads);
1263
1.11k
    g_http_server->StartSocketsThreads();
1264
1.11k
}
1265
1266
void InterruptHTTPServer()
1267
1.16k
{
1268
1.16k
    LogDebug(BCLog::HTTP, "Interrupting HTTP server");
1269
1.16k
    if (g_http_server) {
1270
        // Reject all new requests
1271
1.12k
        g_http_server->SetRequestHandler(RejectRequest);
1272
1.12k
    }
1273
1274
    // Interrupt pool after disabling requests
1275
1.16k
    g_threadpool_http.Interrupt();
1276
1.16k
}
1277
1278
void StopHTTPServer()
1279
1.16k
{
1280
1.16k
    LogDebug(BCLog::HTTP, "Stopping HTTP server");
1281
1282
1.16k
    LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
1283
1.16k
    g_threadpool_http.Stop();
1284
1285
1.16k
    if (g_http_server) {
1286
        // Must precede DisconnectAllClients(): a connection accepted after
1287
        // GetConnectionsCount() returns 0 would survive into the destructor.
1288
1.12k
        g_http_server->StopAccepting();
1289
        // Disconnect clients as their remaining responses are flushed
1290
1.12k
        g_http_server->DisconnectAllClients();
1291
        // Wait 30 seconds for all disconnections
1292
1.12k
        LogDebug(BCLog::HTTP, "Waiting for HTTP clients to disconnect gracefully");
1293
1.12k
        const auto deadline{NodeClock::now() + 30s};
1294
2.10k
        while (g_http_server->GetConnectionsCount() != 0) {
1295
985
            if (NodeClock::now() > deadline) {
1296
0
                LogWarning("Timeout waiting for HTTP clients to disconnect gracefully, continuing shutdown");
1297
0
                break;
1298
0
            }
1299
985
            std::this_thread::sleep_for(50ms);
1300
985
        }
1301
        // Break HTTPServer I/O loop: stop accepting connections, sending and receiving data
1302
1.12k
        g_http_server->InterruptNet();
1303
        // Wait for HTTPServer I/O thread to exit
1304
1.12k
        g_http_server->JoinSocketsThreads();
1305
        // Force-remove any clients that survived the graceful wait
1306
1.12k
        g_http_server->ClearConnectedClients();
1307
        // Close all listening sockets
1308
1.12k
        g_http_server->StopListening();
1309
1.12k
    }
1310
1.16k
    LogDebug(BCLog::HTTP, "Stopped HTTP server");
1311
1.16k
}
1312
} // namespace http_bitcoin