Coverage Report

Created: 2026-11-13 17:38

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