Coverage Report

Created: 2025-06-10 13:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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 <httpserver.h>
6
7
#include <chainparamsbase.h>
8
#include <common/args.h>
9
#include <common/messages.h>
10
#include <compat/compat.h>
11
#include <logging.h>
12
#include <netbase.h>
13
#include <node/interface_ui.h>
14
#include <rpc/protocol.h>
15
#include <sync.h>
16
#include <util/check.h>
17
#include <util/signalinterrupt.h>
18
#include <util/strencodings.h>
19
#include <util/threadnames.h>
20
#include <util/translation.h>
21
22
#include <condition_variable>
23
#include <cstdio>
24
#include <cstdlib>
25
#include <deque>
26
#include <memory>
27
#include <optional>
28
#include <span>
29
#include <string>
30
#include <thread>
31
#include <unordered_map>
32
#include <vector>
33
34
#include <sys/types.h>
35
#include <sys/stat.h>
36
37
#include <event2/buffer.h>
38
#include <event2/bufferevent.h>
39
#include <event2/http.h>
40
#include <event2/http_struct.h>
41
#include <event2/keyvalq_struct.h>
42
#include <event2/thread.h>
43
#include <event2/util.h>
44
45
#include <support/events.h>
46
47
using common::InvalidPortErrMsg;
48
49
/** Maximum size of http request (request line + headers) */
50
static const size_t MAX_HEADERS_SIZE = 8192;
51
52
/** HTTP request work item */
53
class HTTPWorkItem final : public HTTPClosure
54
{
55
public:
56
    HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
57
2.35M
        req(std::move(_req)), path(_path), func(_func)
58
2.35M
    {
59
2.35M
    }
60
    void operator()() override
61
2.35M
    {
62
2.35M
        func(req.get(), path);
63
2.35M
    }
64
65
    std::unique_ptr<HTTPRequest> req;
66
67
private:
68
    std::string path;
69
    HTTPRequestHandler func;
70
};
71
72
/** Simple work queue for distributing work over multiple threads.
73
 * Work items are simply callable objects.
74
 */
75
template <typename WorkItem>
76
class WorkQueue
77
{
78
private:
79
    Mutex cs;
80
    std::condition_variable cond GUARDED_BY(cs);
81
    std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs);
82
    bool running GUARDED_BY(cs){true};
83
    const size_t maxDepth;
84
85
public:
86
11.0k
    explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth)
87
11.0k
    {
88
11.0k
    }
89
    /** Precondition: worker threads have all stopped (they have been joined).
90
     */
91
11.0k
    ~WorkQueue() = default;
92
    /** Enqueue a work item */
93
    bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
94
2.35M
    {
95
2.35M
        LOCK(cs);
96
2.35M
        if (!running || queue.size() >= maxDepth) {
  Branch (96:13): [True: 0, False: 2.35M]
  Branch (96:25): [True: 0, False: 2.35M]
97
0
            return false;
98
0
        }
99
2.35M
        queue.emplace_back(std::unique_ptr<WorkItem>(item));
100
2.35M
        cond.notify_one();
101
2.35M
        return true;
102
2.35M
    }
103
    /** Thread function */
104
    void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
105
44.3k
    {
106
2.40M
        while (true) {
  Branch (106:16): [Folded - Ignored]
107
2.40M
            std::unique_ptr<WorkItem> i;
108
2.40M
            {
109
2.40M
                WAIT_LOCK(cs, lock);
110
4.80M
                while (running && queue.empty())
  Branch (110:24): [True: 4.76M, False: 44.3k]
  Branch (110:35): [True: 2.40M, False: 2.35M]
111
2.40M
                    cond.wait(lock);
112
2.40M
                if (!running && queue.empty())
  Branch (112:21): [True: 44.3k, False: 2.35M]
  Branch (112:33): [True: 44.3k, False: 0]
113
44.3k
                    break;
114
2.35M
                i = std::move(queue.front());
115
2.35M
                queue.pop_front();
116
2.35M
            }
117
0
            (*i)();
118
2.35M
        }
119
44.3k
    }
120
    /** Interrupt and exit loops */
121
    void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
122
11.0k
    {
123
11.0k
        LOCK(cs);
124
11.0k
        running = false;
125
11.0k
        cond.notify_all();
126
11.0k
    }
127
};
128
129
struct HTTPPathHandler
130
{
131
    HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
132
22.1k
        prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
133
22.1k
    {
134
22.1k
    }
135
    std::string prefix;
136
    bool exactMatch;
137
    HTTPRequestHandler handler;
138
};
139
140
/** HTTP module state */
141
142
//! libevent event loop
143
static struct event_base* eventBase = nullptr;
144
//! HTTP server
145
static struct evhttp* eventHTTP = nullptr;
146
//! List of subnets to allow RPC connections from
147
static std::vector<CSubNet> rpc_allow_subnets;
148
//! Work queue for handling longer requests off the event loop thread
149
static std::unique_ptr<WorkQueue<HTTPClosure>> g_work_queue{nullptr};
150
//! Handlers for (sub)paths
151
static GlobalMutex g_httppathhandlers_mutex;
152
static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
153
//! Bound listening sockets
154
static std::vector<evhttp_bound_socket *> boundSockets;
155
156
/**
157
 * @brief Helps keep track of open `evhttp_connection`s with active `evhttp_requests`
158
 *
159
 */
160
class HTTPRequestTracker
161
{
162
private:
163
    mutable Mutex m_mutex;
164
    mutable std::condition_variable m_cv;
165
    //! For each connection, keep a counter of how many requests are open
166
    std::unordered_map<const evhttp_connection*, size_t> m_tracker GUARDED_BY(m_mutex);
167
168
    void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
169
2.35M
    {
170
2.35M
        m_tracker.erase(it);
171
2.35M
        if (m_tracker.empty()) m_cv.notify_all();
  Branch (171:13): [True: 2.35M, False: 0]
172
2.35M
    }
173
public:
174
    //! Increase request counter for the associated connection by 1
175
    void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
176
2.35M
    {
177
2.35M
        const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
178
2.35M
        WITH_LOCK(m_mutex, ++m_tracker[conn]);
179
2.35M
    }
180
    //! Decrease request counter for the associated connection by 1, remove connection if counter is 0
181
    void RemoveRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
182
2.35M
    {
183
2.35M
        const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
184
2.35M
        LOCK(m_mutex);
185
2.35M
        auto it{m_tracker.find(conn)};
186
2.35M
        if (it != m_tracker.end() && it->second > 0) {
  Branch (186:13): [True: 2.35M, False: 0]
  Branch (186:13): [True: 2.35M, False: 0]
  Branch (186:38): [True: 2.35M, False: 0]
187
2.35M
            if (--(it->second) == 0) RemoveConnectionInternal(it);
  Branch (187:17): [True: 2.35M, False: 0]
188
2.35M
        }
189
2.35M
    }
190
    //! Remove a connection entirely
191
    void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
192
2.35M
    {
193
2.35M
        LOCK(m_mutex);
194
2.35M
        auto it{m_tracker.find(Assert(conn))};
195
2.35M
        if (it != m_tracker.end()) RemoveConnectionInternal(it);
  Branch (195:13): [True: 0, False: 2.35M]
196
2.35M
    }
197
    size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
198
11.0k
    {
199
11.0k
        return WITH_LOCK(m_mutex, return m_tracker.size());
200
11.0k
    }
201
    //! Wait until there are no more connections with active requests in the tracker
202
    void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
203
11.0k
    {
204
11.0k
        WAIT_LOCK(m_mutex, lock);
205
11.0k
        m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); });
206
11.0k
    }
207
};
208
//! Track active requests
209
static HTTPRequestTracker g_requests;
210
211
/** Check if a network address is allowed to access the HTTP server */
212
static bool ClientAllowed(const CNetAddr& netaddr)
213
2.35M
{
214
2.35M
    if (!netaddr.IsValid())
  Branch (214:9): [True: 0, False: 2.35M]
215
0
        return false;
216
2.35M
    for(const CSubNet& subnet : rpc_allow_subnets)
  Branch (216:31): [True: 2.35M, False: 0]
217
2.35M
        if (subnet.Match(netaddr))
  Branch (217:13): [True: 2.35M, False: 0]
218
2.35M
            return true;
219
0
    return false;
220
2.35M
}
221
222
/** Initialize ACL list for HTTP server */
223
static bool InitHTTPAllowList()
224
11.0k
{
225
11.0k
    rpc_allow_subnets.clear();
226
11.0k
    rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8);  // always allow IPv4 local subnet
227
11.0k
    rpc_allow_subnets.emplace_back(LookupHost("::1", false).value());  // always allow IPv6 localhost
228
11.0k
    for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
  Branch (228:38): [True: 0, False: 11.0k]
229
0
        const CSubNet subnet{LookupSubNet(strAllow)};
230
0
        if (!subnet.IsValid()) {
  Branch (230:13): [True: 0, False: 0]
231
0
            uiInterface.ThreadSafeMessageBox(
232
0
                Untranslated(strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow)),
233
0
                "", CClientUIInterface::MSG_ERROR);
234
0
            return false;
235
0
        }
236
0
        rpc_allow_subnets.push_back(subnet);
237
0
    }
238
11.0k
    std::string strAllowed;
239
11.0k
    for (const CSubNet& subnet : rpc_allow_subnets)
  Branch (239:32): [True: 22.1k, False: 11.0k]
240
22.1k
        strAllowed += subnet.ToString() + " ";
241
11.0k
    LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
242
11.0k
    return true;
243
11.0k
}
244
245
/** HTTP request method as string - use for logging only */
246
std::string RequestMethodString(HTTPRequest::RequestMethod m)
247
2.35M
{
248
2.35M
    switch (m) {
  Branch (248:13): [True: 0, False: 2.35M]
249
0
    case HTTPRequest::GET:
  Branch (249:5): [True: 0, False: 2.35M]
250
0
        return "GET";
251
2.35M
    case HTTPRequest::POST:
  Branch (251:5): [True: 2.35M, False: 0]
252
2.35M
        return "POST";
253
0
    case HTTPRequest::HEAD:
  Branch (253:5): [True: 0, False: 2.35M]
254
0
        return "HEAD";
255
0
    case HTTPRequest::PUT:
  Branch (255:5): [True: 0, False: 2.35M]
256
0
        return "PUT";
257
0
    case HTTPRequest::UNKNOWN:
  Branch (257:5): [True: 0, False: 2.35M]
258
0
        return "unknown";
259
2.35M
    } // no default case, so the compiler can warn about missing cases
260
2.35M
    assert(false);
  Branch (260:5): [Folded - Ignored]
261
0
}
262
263
/** HTTP request callback */
264
static void http_request_cb(struct evhttp_request* req, void* arg)
265
2.35M
{
266
2.35M
    evhttp_connection* conn{evhttp_request_get_connection(req)};
267
    // Track active requests
268
2.35M
    {
269
2.35M
        g_requests.AddRequest(req);
270
2.35M
        evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) {
271
2.35M
            g_requests.RemoveRequest(req);
272
2.35M
        }, nullptr);
273
2.35M
        evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) {
274
2.35M
            g_requests.RemoveConnection(conn);
275
2.35M
        }, nullptr);
276
2.35M
    }
277
278
    // Disable reading to work around a libevent bug, fixed in 2.1.9
279
    // See https://github.com/libevent/libevent/commit/5ff8eb26371c4dc56f384b2de35bea2d87814779
280
    // and https://github.com/bitcoin/bitcoin/pull/11593.
281
2.35M
    if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
  Branch (281:9): [True: 2.35M, False: 0]
  Branch (281:53): [True: 0, False: 2.35M]
282
0
        if (conn) {
  Branch (282:13): [True: 0, False: 0]
283
0
            bufferevent* bev = evhttp_connection_get_bufferevent(conn);
284
0
            if (bev) {
  Branch (284:17): [True: 0, False: 0]
285
0
                bufferevent_disable(bev, EV_READ);
286
0
            }
287
0
        }
288
0
    }
289
2.35M
    auto hreq{std::make_unique<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))};
290
291
    // Early address-based allow check
292
2.35M
    if (!ClientAllowed(hreq->GetPeer())) {
  Branch (292:9): [True: 0, False: 2.35M]
293
0
        LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
294
0
                 hreq->GetPeer().ToStringAddrPort());
295
0
        hreq->WriteReply(HTTP_FORBIDDEN);
296
0
        return;
297
0
    }
298
299
    // Early reject unknown HTTP methods
300
2.35M
    if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
  Branch (300:9): [True: 0, False: 2.35M]
301
0
        LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
302
0
                 hreq->GetPeer().ToStringAddrPort());
303
0
        hreq->WriteReply(HTTP_BAD_METHOD);
304
0
        return;
305
0
    }
306
307
2.35M
    LogDebug(BCLog::HTTP, "Received a %s request for %s from %s\n",
308
2.35M
             RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort());
309
310
    // Find registered handler for prefix
311
2.35M
    std::string strURI = hreq->GetURI();
312
2.35M
    std::string path;
313
2.35M
    LOCK(g_httppathhandlers_mutex);
314
2.35M
    std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
315
2.35M
    std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
316
4.69M
    for (; i != iend; ++i) {
  Branch (316:12): [True: 4.69M, False: 0]
317
4.69M
        bool match = false;
318
4.69M
        if (i->exactMatch)
  Branch (318:13): [True: 2.35M, False: 2.33M]
319
2.35M
            match = (strURI == i->prefix);
320
2.33M
        else
321
2.33M
            match = strURI.starts_with(i->prefix);
322
4.69M
        if (match) {
  Branch (322:13): [True: 2.35M, False: 2.33M]
323
2.35M
            path = strURI.substr(i->prefix.size());
324
2.35M
            break;
325
2.35M
        }
326
4.69M
    }
327
328
    // Dispatch to worker thread
329
2.35M
    if (i != iend) {
  Branch (329:9): [True: 2.35M, False: 0]
330
2.35M
        std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
331
2.35M
        assert(g_work_queue);
  Branch (331:9): [True: 2.35M, False: 0]
332
2.35M
        if (g_work_queue->Enqueue(item.get())) {
  Branch (332:13): [True: 2.35M, False: 0]
333
2.35M
            item.release(); /* if true, queue took ownership */
334
2.35M
        } else {
335
0
            LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
336
0
            item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
337
0
        }
338
2.35M
    } else {
339
0
        hreq->WriteReply(HTTP_NOT_FOUND);
340
0
    }
341
2.35M
}
342
343
/** Callback to reject HTTP requests after shutdown. */
344
static void http_reject_request_cb(struct evhttp_request* req, void*)
345
0
{
346
0
    LogDebug(BCLog::HTTP, "Rejecting request while shutting down\n");
347
0
    evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
348
0
}
349
350
/** Event dispatcher thread */
351
static void ThreadHTTP(struct event_base* base)
352
11.0k
{
353
11.0k
    util::ThreadRename("http");
354
11.0k
    LogDebug(BCLog::HTTP, "Entering http event loop\n");
355
11.0k
    event_base_dispatch(base);
356
    // Event loop will be interrupted by InterruptHTTPServer()
357
11.0k
    LogDebug(BCLog::HTTP, "Exited http event loop\n");
358
11.0k
}
359
360
/** Bind HTTP server to specified addresses */
361
static bool HTTPBindAddresses(struct evhttp* http)
362
11.0k
{
363
11.0k
    uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
364
11.0k
    std::vector<std::pair<std::string, uint16_t>> endpoints;
365
366
    // Determine what addresses to bind to
367
    // To prevent misconfiguration and accidental exposure of the RPC
368
    // interface, require -rpcallowip and -rpcbind to both be specified
369
    // together. If either is missing, ignore both values, bind to localhost
370
    // instead, and log warnings.
371
11.0k
    if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
  Branch (371:9): [True: 11.0k, False: 0]
  Branch (371:9): [True: 11.0k, False: 0]
  Branch (371:49): [True: 0, False: 0]
372
11.0k
        endpoints.emplace_back("::1", http_port);
373
11.0k
        endpoints.emplace_back("127.0.0.1", http_port);
374
11.0k
        if (!gArgs.GetArgs("-rpcallowip").empty()) {
  Branch (374:13): [True: 0, False: 11.0k]
375
0
            LogPrintf("WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
376
0
        }
377
11.0k
        if (!gArgs.GetArgs("-rpcbind").empty()) {
  Branch (377:13): [True: 0, False: 11.0k]
378
0
            LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
379
0
        }
380
11.0k
    } else { // Specific bind addresses
381
0
        for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
  Branch (381:44): [True: 0, False: 0]
382
0
            uint16_t port{http_port};
383
0
            std::string host;
384
0
            if (!SplitHostPort(strRPCBind, port, host)) {
  Branch (384:17): [True: 0, False: 0]
385
0
                LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
386
0
                return false;
387
0
            }
388
0
            endpoints.emplace_back(host, port);
389
0
        }
390
0
    }
391
392
    // Bind addresses
393
33.2k
    for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
  Branch (393:90): [True: 22.1k, False: 11.0k]
394
22.1k
        LogPrintf("Binding RPC on address %s port %i\n", i->first, i->second);
395
22.1k
        evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
  Branch (395:81): [True: 0, False: 22.1k]
396
22.1k
        if (bind_handle) {
  Branch (396:13): [True: 11.0k, False: 11.0k]
397
11.0k
            const std::optional<CNetAddr> addr{LookupHost(i->first, false)};
398
11.0k
            if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
  Branch (398:17): [True: 0, False: 11.0k]
  Branch (398:38): [True: 11.0k, False: 0]
  Branch (398:58): [True: 0, False: 11.0k]
399
0
                LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
400
0
            }
401
            // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
402
11.0k
            evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle);
403
11.0k
            int one = 1;
404
11.0k
            if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (sockopt_arg_type)&one, sizeof(one)) == SOCKET_ERROR) {
  Branch (404:17): [True: 0, False: 11.0k]
405
0
                LogInfo("WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
406
0
            }
407
11.0k
            boundSockets.push_back(bind_handle);
408
11.0k
        } else {
409
11.0k
            LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
410
11.0k
        }
411
22.1k
    }
412
11.0k
    return !boundSockets.empty();
413
11.0k
}
414
415
/** Simple wrapper to set thread name and run work queue */
416
static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
417
44.3k
{
418
44.3k
    util::ThreadRename(strprintf("httpworker.%i", worker_num));
419
44.3k
    queue->Run();
420
44.3k
}
421
422
/** libevent event log callback */
423
static void libevent_log_cb(int severity, const char *msg)
424
11.0k
{
425
11.0k
    BCLog::Level level;
426
11.0k
    switch (severity) {
427
0
    case EVENT_LOG_DEBUG:
  Branch (427:5): [True: 0, False: 11.0k]
428
0
        level = BCLog::Level::Debug;
429
0
        break;
430
0
    case EVENT_LOG_MSG:
  Branch (430:5): [True: 0, False: 11.0k]
431
0
        level = BCLog::Level::Info;
432
0
        break;
433
11.0k
    case EVENT_LOG_WARN:
  Branch (433:5): [True: 11.0k, False: 0]
434
11.0k
        level = BCLog::Level::Warning;
435
11.0k
        break;
436
0
    default: // EVENT_LOG_ERR and others are mapped to error
  Branch (436:5): [True: 0, False: 11.0k]
437
0
        level = BCLog::Level::Error;
438
0
        break;
439
11.0k
    }
440
11.0k
    LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg);
441
11.0k
}
442
443
bool InitHTTPServer(const util::SignalInterrupt& interrupt)
444
11.0k
{
445
11.0k
    if (!InitHTTPAllowList())
  Branch (445:9): [True: 0, False: 11.0k]
446
0
        return false;
447
448
    // Redirect libevent's logging to our own log
449
11.0k
    event_set_log_callback(&libevent_log_cb);
450
    // Update libevent's log handling.
451
11.0k
    UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT));
452
453
#ifdef WIN32
454
    evthread_use_windows_threads();
455
#else
456
11.0k
    evthread_use_pthreads();
457
11.0k
#endif
458
459
11.0k
    raii_event_base base_ctr = obtain_event_base();
460
461
    /* Create a new evhttp object to handle requests. */
462
11.0k
    raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
463
11.0k
    struct evhttp* http = http_ctr.get();
464
11.0k
    if (!http) {
  Branch (464:9): [True: 0, False: 11.0k]
465
0
        LogPrintf("couldn't create evhttp. Exiting.\n");
466
0
        return false;
467
0
    }
468
469
11.0k
    evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
470
11.0k
    evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
471
11.0k
    evhttp_set_max_body_size(http, MAX_SIZE);
472
11.0k
    evhttp_set_gencb(http, http_request_cb, (void*)&interrupt);
473
474
11.0k
    if (!HTTPBindAddresses(http)) {
  Branch (474:9): [True: 0, False: 11.0k]
475
0
        LogPrintf("Unable to bind any endpoint for RPC server\n");
476
0
        return false;
477
0
    }
478
479
11.0k
    LogDebug(BCLog::HTTP, "Initialized HTTP server\n");
480
11.0k
    int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
481
11.0k
    LogDebug(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth);
482
483
11.0k
    g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
484
    // transfer ownership to eventBase/HTTP via .release()
485
11.0k
    eventBase = base_ctr.release();
486
11.0k
    eventHTTP = http_ctr.release();
487
11.0k
    return true;
488
11.0k
}
489
490
11.0k
void UpdateHTTPServerLogging(bool enable) {
491
11.0k
    if (enable) {
  Branch (491:9): [True: 0, False: 11.0k]
492
0
        event_enable_debug_logging(EVENT_DBG_ALL);
493
11.0k
    } else {
494
11.0k
        event_enable_debug_logging(EVENT_DBG_NONE);
495
11.0k
    }
496
11.0k
}
497
498
static std::thread g_thread_http;
499
static std::vector<std::thread> g_thread_http_workers;
500
501
void StartHTTPServer()
502
11.0k
{
503
11.0k
    int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
504
11.0k
    LogInfo("Starting HTTP server with %d worker threads\n", rpcThreads);
505
11.0k
    g_thread_http = std::thread(ThreadHTTP, eventBase);
506
507
55.4k
    for (int i = 0; i < rpcThreads; i++) {
  Branch (507:21): [True: 44.3k, False: 11.0k]
508
44.3k
        g_thread_http_workers.emplace_back(HTTPWorkQueueRun, g_work_queue.get(), i);
509
44.3k
    }
510
11.0k
}
511
512
void InterruptHTTPServer()
513
11.0k
{
514
11.0k
    LogDebug(BCLog::HTTP, "Interrupting HTTP server\n");
515
11.0k
    if (eventHTTP) {
  Branch (515:9): [True: 11.0k, False: 0]
516
        // Reject requests on current connections
517
11.0k
        evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
518
11.0k
    }
519
11.0k
    if (g_work_queue) {
  Branch (519:9): [True: 11.0k, False: 0]
520
11.0k
        g_work_queue->Interrupt();
521
11.0k
    }
522
11.0k
}
523
524
void StopHTTPServer()
525
11.0k
{
526
11.0k
    LogDebug(BCLog::HTTP, "Stopping HTTP server\n");
527
11.0k
    if (g_work_queue) {
  Branch (527:9): [True: 11.0k, False: 0]
528
11.0k
        LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
529
44.3k
        for (auto& thread : g_thread_http_workers) {
  Branch (529:27): [True: 44.3k, False: 11.0k]
530
44.3k
            thread.join();
531
44.3k
        }
532
11.0k
        g_thread_http_workers.clear();
533
11.0k
    }
534
    // Unlisten sockets, these are what make the event loop running, which means
535
    // that after this and all connections are closed the event loop will quit.
536
11.0k
    for (evhttp_bound_socket *socket : boundSockets) {
  Branch (536:38): [True: 11.0k, False: 11.0k]
537
11.0k
        evhttp_del_accept_socket(eventHTTP, socket);
538
11.0k
    }
539
11.0k
    boundSockets.clear();
540
11.0k
    {
541
11.0k
        if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) {
  Branch (541:76): [True: 4, False: 11.0k]
542
4
            LogDebug(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections);
543
4
        }
544
11.0k
        g_requests.WaitUntilEmpty();
545
11.0k
    }
546
11.0k
    if (eventHTTP) {
  Branch (546:9): [True: 11.0k, False: 0]
547
        // Schedule a callback to call evhttp_free in the event base thread, so
548
        // that evhttp_free does not need to be called again after the handling
549
        // of unfinished request connections that follows.
550
11.0k
        event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
551
2.15k
            evhttp_free(eventHTTP);
552
2.15k
            eventHTTP = nullptr;
553
2.15k
        }, nullptr, nullptr);
554
11.0k
    }
555
11.0k
    if (eventBase) {
  Branch (555:9): [True: 11.0k, False: 0]
556
11.0k
        LogDebug(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
557
11.0k
        if (g_thread_http.joinable()) g_thread_http.join();
  Branch (557:13): [True: 11.0k, False: 0]
558
11.0k
        event_base_free(eventBase);
559
11.0k
        eventBase = nullptr;
560
11.0k
    }
561
11.0k
    g_work_queue.reset();
562
11.0k
    LogDebug(BCLog::HTTP, "Stopped HTTP server\n");
563
11.0k
}
564
565
struct event_base* EventBase()
566
11.0k
{
567
11.0k
    return eventBase;
568
11.0k
}
569
570
static void httpevent_callback_fn(evutil_socket_t, short, void* data)
571
2.35M
{
572
    // Static handler: simply call inner handler
573
2.35M
    HTTPEvent *self = static_cast<HTTPEvent*>(data);
574
2.35M
    self->handler();
575
2.35M
    if (self->deleteWhenTriggered)
  Branch (575:9): [True: 2.35M, False: 0]
576
2.35M
        delete self;
577
2.35M
}
578
579
HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
580
2.35M
    deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
581
2.35M
{
582
2.35M
    ev = event_new(base, -1, 0, httpevent_callback_fn, this);
583
2.35M
    assert(ev);
  Branch (583:5): [True: 2.35M, False: 0]
584
2.35M
}
585
HTTPEvent::~HTTPEvent()
586
2.35M
{
587
2.35M
    event_free(ev);
588
2.35M
}
589
void HTTPEvent::trigger(struct timeval* tv)
590
2.35M
{
591
2.35M
    if (tv == nullptr)
  Branch (591:9): [True: 2.35M, False: 0]
592
2.35M
        event_active(ev, 0, 0); // immediately trigger event in main thread
593
0
    else
594
2.35M
        evtimer_add(ev, tv); // trigger after timeval passed
595
2.35M
}
596
HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent)
597
2.35M
    : req(_req), m_interrupt(interrupt), replySent(_replySent)
598
2.35M
{
599
2.35M
}
600
601
HTTPRequest::~HTTPRequest()
602
2.35M
{
603
2.35M
    if (!replySent) {
  Branch (603:9): [True: 0, False: 2.35M]
604
        // Keep track of whether reply was sent to avoid request leaks
605
0
        LogPrintf("%s: Unhandled request\n", __func__);
606
0
        WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
607
0
    }
608
    // evhttpd cleans up the request, as long as a reply was sent.
609
2.35M
}
610
611
std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
612
2.35M
{
613
2.35M
    const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
614
2.35M
    assert(headers);
  Branch (614:5): [True: 2.35M, False: 0]
615
2.35M
    const char* val = evhttp_find_header(headers, hdr.c_str());
616
2.35M
    if (val)
  Branch (616:9): [True: 2.35M, False: 0]
617
2.35M
        return std::make_pair(true, val);
618
0
    else
619
0
        return std::make_pair(false, "");
620
2.35M
}
621
622
std::string HTTPRequest::ReadBody()
623
2.35M
{
624
2.35M
    struct evbuffer* buf = evhttp_request_get_input_buffer(req);
625
2.35M
    if (!buf)
  Branch (625:9): [True: 0, False: 2.35M]
626
0
        return "";
627
2.35M
    size_t size = evbuffer_get_length(buf);
628
    /** Trivial implementation: if this is ever a performance bottleneck,
629
     * internal copying can be avoided in multi-segment buffers by using
630
     * evbuffer_peek and an awkward loop. Though in that case, it'd be even
631
     * better to not copy into an intermediate string but use a stream
632
     * abstraction to consume the evbuffer on the fly in the parsing algorithm.
633
     */
634
2.35M
    const char* data = (const char*)evbuffer_pullup(buf, size);
635
2.35M
    if (!data) // returns nullptr in case of empty buffer
  Branch (635:9): [True: 0, False: 2.35M]
636
0
        return "";
637
2.35M
    std::string rv(data, size);
638
2.35M
    evbuffer_drain(buf, size);
639
2.35M
    return rv;
640
2.35M
}
641
642
void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
643
2.36M
{
644
2.36M
    struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
645
2.36M
    assert(headers);
  Branch (645:5): [True: 2.36M, False: 0]
646
2.36M
    evhttp_add_header(headers, hdr.c_str(), value.c_str());
647
2.36M
}
648
649
/** Closure sent to main thread to request a reply to be sent to
650
 * a HTTP request.
651
 * Replies must be sent in the main loop in the main http thread,
652
 * this cannot be done from worker threads.
653
 */
654
void HTTPRequest::WriteReply(int nStatus, std::span<const std::byte> reply)
655
2.35M
{
656
2.35M
    assert(!replySent && req);
  Branch (656:5): [True: 2.35M, False: 0]
  Branch (656:5): [True: 2.35M, False: 0]
  Branch (656:5): [True: 2.35M, False: 0]
657
2.35M
    if (m_interrupt) {
  Branch (657:9): [True: 11.0k, False: 2.34M]
658
11.0k
        WriteHeader("Connection", "close");
659
11.0k
    }
660
    // Send event to main http thread to send reply message
661
2.35M
    struct evbuffer* evb = evhttp_request_get_output_buffer(req);
662
2.35M
    assert(evb);
  Branch (662:5): [True: 2.35M, False: 0]
663
2.35M
    evbuffer_add(evb, reply.data(), reply.size());
664
2.35M
    auto req_copy = req;
665
2.35M
    HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
666
2.35M
        evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
667
        // Re-enable reading from the socket. This is the second part of the libevent
668
        // workaround above.
669
2.35M
        if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
  Branch (669:13): [True: 2.35M, False: 0]
  Branch (669:57): [True: 0, False: 2.35M]
670
0
            evhttp_connection* conn = evhttp_request_get_connection(req_copy);
671
0
            if (conn) {
  Branch (671:17): [True: 0, False: 0]
672
0
                bufferevent* bev = evhttp_connection_get_bufferevent(conn);
673
0
                if (bev) {
  Branch (673:21): [True: 0, False: 0]
674
0
                    bufferevent_enable(bev, EV_READ | EV_WRITE);
675
0
                }
676
0
            }
677
0
        }
678
2.35M
    });
679
2.35M
    ev->trigger(nullptr);
680
2.35M
    replySent = true;
681
2.35M
    req = nullptr; // transferred back to main thread
682
2.35M
}
683
684
CService HTTPRequest::GetPeer() const
685
7.07M
{
686
7.07M
    evhttp_connection* con = evhttp_request_get_connection(req);
687
7.07M
    CService peer;
688
7.07M
    if (con) {
  Branch (688:9): [True: 7.07M, False: 0]
689
        // evhttp retains ownership over returned address string
690
7.07M
        const char* address = "";
691
7.07M
        uint16_t port = 0;
692
693
#ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
694
        evhttp_connection_get_peer(con, &address, &port);
695
#else
696
7.07M
        evhttp_connection_get_peer(con, (char**)&address, &port);
697
7.07M
#endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
698
699
7.07M
        peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port));
700
7.07M
    }
701
7.07M
    return peer;
702
7.07M
}
703
704
std::string HTTPRequest::GetURI() const
705
7.07M
{
706
7.07M
    return evhttp_request_get_uri(req);
707
7.07M
}
708
709
HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const
710
7.07M
{
711
7.07M
    switch (evhttp_request_get_command(req)) {
712
0
    case EVHTTP_REQ_GET:
  Branch (712:5): [True: 0, False: 7.07M]
713
0
        return GET;
714
7.07M
    case EVHTTP_REQ_POST:
  Branch (714:5): [True: 7.07M, False: 0]
715
7.07M
        return POST;
716
0
    case EVHTTP_REQ_HEAD:
  Branch (716:5): [True: 0, False: 7.07M]
717
0
        return HEAD;
718
0
    case EVHTTP_REQ_PUT:
  Branch (718:5): [True: 0, False: 7.07M]
719
0
        return PUT;
720
0
    default:
  Branch (720:5): [True: 0, False: 7.07M]
721
0
        return UNKNOWN;
722
7.07M
    }
723
7.07M
}
724
725
std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const
726
0
{
727
0
    const char* uri{evhttp_request_get_uri(req)};
728
729
0
    return GetQueryParameterFromUri(uri, key);
730
0
}
731
732
std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key)
733
0
{
734
0
    evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
735
0
    if (!uri_parsed) {
  Branch (735:9): [True: 0, False: 0]
736
0
        throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters");
737
0
    }
738
0
    const char* query{evhttp_uri_get_query(uri_parsed)};
739
0
    std::optional<std::string> result;
740
741
0
    if (query) {
  Branch (741:9): [True: 0, False: 0]
742
        // Parse the query string into a key-value queue and iterate over it
743
0
        struct evkeyvalq params_q;
744
0
        evhttp_parse_query_str(query, &params_q);
745
746
0
        for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) {
  Branch (746:58): [True: 0, False: 0]
747
0
            if (param->key == key) {
  Branch (747:17): [True: 0, False: 0]
748
0
                result = param->value;
749
0
                break;
750
0
            }
751
0
        }
752
0
        evhttp_clear_headers(&params_q);
753
0
    }
754
0
    evhttp_uri_free(uri_parsed);
755
756
0
    return result;
757
0
}
758
759
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
760
22.1k
{
761
22.1k
    LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
762
22.1k
    LOCK(g_httppathhandlers_mutex);
763
22.1k
    pathHandlers.emplace_back(prefix, exactMatch, handler);
764
22.1k
}
765
766
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
767
155k
{
768
155k
    LOCK(g_httppathhandlers_mutex);
769
155k
    std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
770
155k
    std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
771
155k
    for (; i != iend; ++i)
  Branch (771:12): [True: 22.1k, False: 133k]
772
22.1k
        if (i->prefix == prefix && i->exactMatch == exactMatch)
  Branch (772:13): [True: 22.1k, False: 0]
  Branch (772:36): [True: 22.1k, False: 0]
773
22.1k
            break;
774
155k
    if (i != iend)
  Branch (774:9): [True: 22.1k, False: 133k]
775
22.1k
    {
776
22.1k
        LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
777
22.1k
        pathHandlers.erase(i);
778
22.1k
    }
779
155k
}