Coverage Report

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