fuzz coverage

Coverage Report

Created: 2026-04-24 13:48

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