Coverage Report

Created: 2026-09-15 16:03

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