Branch data Line data Source code
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 : 201649 : HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
57 [ - + + - ]: 403298 : req(std::move(_req)), path(_path), func(_func)
58 : : {
59 : 201649 : }
60 : 201648 : void operator()() override
61 : : {
62 : 201648 : func(req.get(), path);
63 : 201648 : }
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 [ + - ]: 2242 : explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth)
87 : : {
88 : 1121 : }
89 : : /** Precondition: worker threads have all stopped (they have been joined).
90 : : */
91 : 1121 : ~WorkQueue() = default;
92 : : /** Enqueue a work item */
93 : 201649 : bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
94 : : {
95 : 201649 : LOCK(cs);
96 [ + - - + : 201649 : if (!running || queue.size() >= maxDepth) {
+ + ]
97 : : return false;
98 : : }
99 [ + - ]: 201648 : queue.emplace_back(std::unique_ptr<WorkItem>(item));
100 : 201648 : cond.notify_one();
101 : 201648 : return true;
102 : 201649 : }
103 : : /** Thread function */
104 : 2217 : void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
105 : : {
106 : 201648 : while (true) {
107 : 203865 : std::unique_ptr<WorkItem> i;
108 : : {
109 [ + - ]: 203865 : WAIT_LOCK(cs, lock);
110 [ + + + + ]: 407079 : while (running && queue.empty())
111 [ + - ]: 203214 : cond.wait(lock);
112 [ + + - + ]: 203865 : if (!running && queue.empty())
113 : : break;
114 : 201648 : i = std::move(queue.front());
115 [ + - ]: 201648 : queue.pop_front();
116 [ + - ]: 203865 : }
117 [ + - ]: 201648 : (*i)();
118 : : }
119 : 2217 : }
120 : : /** Interrupt and exit loops */
121 : 1121 : void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
122 : : {
123 : 1121 : LOCK(cs);
124 : 1121 : running = false;
125 [ + - ]: 1121 : cond.notify_all();
126 : 1121 : }
127 : : };
128 : :
129 : 3355 : struct HTTPPathHandler
130 : : {
131 : 2232 : HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
132 [ - + + - ]: 4464 : prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
133 : : {
134 : 2232 : }
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 : 201652 : void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
169 : : {
170 : 201652 : m_tracker.erase(it);
171 [ + + ]: 201652 : if (m_tracker.empty()) m_cv.notify_all();
172 : 201652 : }
173 : : public:
174 : : //! Increase request counter for the associated connection by 1
175 : 201652 : void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
176 : : {
177 [ - + - + ]: 201652 : const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
178 [ + - + - ]: 604956 : WITH_LOCK(m_mutex, ++m_tracker[conn]);
179 : 201652 : }
180 : : //! Decrease request counter for the associated connection by 1, remove connection if counter is 0
181 : 201652 : void RemoveRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
182 : : {
183 [ - + - + ]: 201652 : const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
184 : 201652 : LOCK(m_mutex);
185 : 201652 : auto it{m_tracker.find(conn)};
186 [ + - + - : 403304 : if (it != m_tracker.end() && it->second > 0) {
+ - ]
187 [ + - ]: 201652 : if (--(it->second) == 0) RemoveConnectionInternal(it);
188 : : }
189 : 201652 : }
190 : : //! Remove a connection entirely
191 : 3891 : void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
192 : : {
193 : 3891 : LOCK(m_mutex);
194 [ - + ]: 3891 : auto it{m_tracker.find(Assert(conn))};
195 [ - + + - ]: 3891 : if (it != m_tracker.end()) RemoveConnectionInternal(it);
196 : 3891 : }
197 : 1162 : size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
198 : : {
199 [ + - ]: 1162 : return WITH_LOCK(m_mutex, return m_tracker.size());
200 : : }
201 : : //! Wait until there are no more connections with active requests in the tracker
202 : 1162 : void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
203 : : {
204 : 1162 : WAIT_LOCK(m_mutex, lock);
205 [ + + + - ]: 1173 : m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); });
206 : 1162 : }
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 : 201652 : static bool ClientAllowed(const CNetAddr& netaddr)
213 : : {
214 [ + - ]: 201652 : if (!netaddr.IsValid())
215 : : return false;
216 [ + + ]: 201663 : for(const CSubNet& subnet : rpc_allow_subnets)
217 [ + + ]: 201662 : if (subnet.Match(netaddr))
218 : : return true;
219 : : return false;
220 : : }
221 : :
222 : : /** Initialize ACL list for HTTP server */
223 : 1121 : static bool InitHTTPAllowList()
224 : : {
225 : 1121 : rpc_allow_subnets.clear();
226 [ + - + - : 3363 : rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8); // always allow IPv4 local subnet
+ - ]
227 [ + - + - : 3363 : rpc_allow_subnets.emplace_back(LookupHost("::1", false).value()); // always allow IPv6 localhost
+ - ]
228 [ + - + + ]: 1128 : for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
229 [ + - ]: 7 : const CSubNet subnet{LookupSubNet(strAllow)};
230 [ + - - + ]: 7 : if (!subnet.IsValid()) {
231 [ # # ]: 0 : uiInterface.ThreadSafeMessageBox(
232 [ # # # # ]: 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)),
233 [ # # ]: 0 : "", CClientUIInterface::MSG_ERROR);
234 : 0 : return false;
235 : : }
236 [ + - ]: 7 : rpc_allow_subnets.push_back(subnet);
237 : 1128 : }
238 : 1121 : std::string strAllowed;
239 [ + + ]: 3370 : for (const CSubNet& subnet : rpc_allow_subnets)
240 [ + - - + ]: 6747 : strAllowed += subnet.ToString() + " ";
241 [ + - + + : 1121 : LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
+ - ]
242 : 1121 : return true;
243 : 1121 : }
244 : :
245 : : /** HTTP request method as string - use for logging only */
246 : 201639 : std::string RequestMethodString(HTTPRequest::RequestMethod m)
247 : : {
248 [ + + - - : 201639 : switch (m) {
- - ]
249 : 737 : case HTTPRequest::GET:
250 : 737 : return "GET";
251 : 200902 : case HTTPRequest::POST:
252 : 200902 : return "POST";
253 : 0 : case HTTPRequest::HEAD:
254 : 0 : return "HEAD";
255 : 0 : case HTTPRequest::PUT:
256 : 0 : return "PUT";
257 : 0 : case HTTPRequest::UNKNOWN:
258 : 0 : return "unknown";
259 : : } // no default case, so the compiler can warn about missing cases
260 : 0 : assert(false);
261 : : }
262 : :
263 : : /** HTTP request callback */
264 : 201652 : static void http_request_cb(struct evhttp_request* req, void* arg)
265 : : {
266 : 201652 : evhttp_connection* conn{evhttp_request_get_connection(req)};
267 : : // Track active requests
268 : 201652 : {
269 : 201652 : g_requests.AddRequest(req);
270 : 201652 : evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) {
271 : : g_requests.RemoveRequest(req);
272 : : }, nullptr);
273 : 201652 : evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) {
274 : : g_requests.RemoveConnection(conn);
275 : : }, nullptr);
276 : : }
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 [ + - - + ]: 201652 : if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
282 [ # # ]: 0 : if (conn) {
283 : 0 : bufferevent* bev = evhttp_connection_get_bufferevent(conn);
284 [ # # ]: 0 : if (bev) {
285 : 0 : bufferevent_disable(bev, EV_READ);
286 : : }
287 : : }
288 : : }
289 : 201652 : auto hreq{std::make_unique<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))};
290 : :
291 : : // Early address-based allow check
292 [ + - + - : 201652 : if (!ClientAllowed(hreq->GetPeer())) {
+ + ]
293 [ + - + - : 2 : LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
+ - + - +
- ]
294 : : hreq->GetPeer().ToStringAddrPort());
295 [ + - ]: 1 : hreq->WriteReply(HTTP_FORBIDDEN);
296 : : return;
297 : : }
298 : :
299 : : // Early reject unknown HTTP methods
300 [ + - - + ]: 201651 : if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
301 [ # # # # : 0 : LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
# # # # #
# ]
302 : : hreq->GetPeer().ToStringAddrPort());
303 [ # # ]: 0 : hreq->WriteReply(HTTP_BAD_METHOD);
304 : : return;
305 : : }
306 : :
307 [ + - + + : 604929 : LogDebug(BCLog::HTTP, "Received a %s request for %s from %s\n",
+ - + - +
- + - + -
+ - + - +
- ]
308 : : RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort());
309 : :
310 : : // Find registered handler for prefix
311 [ + - ]: 201651 : std::string strURI = hreq->GetURI();
312 [ + - ]: 201651 : std::string path;
313 [ + - ]: 201651 : LOCK(g_httppathhandlers_mutex);
314 : 201651 : std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
315 : 201651 : std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
316 [ + + ]: 227211 : for (; i != iend; ++i) {
317 : 227209 : bool match = false;
318 [ + + ]: 227209 : if (i->exactMatch)
319 : 201651 : match = (strURI == i->prefix);
320 : : else
321 [ - + - + ]: 25558 : match = strURI.starts_with(i->prefix);
322 [ + + ]: 227209 : if (match) {
323 [ - + + - ]: 201649 : path = strURI.substr(i->prefix.size());
324 : 201649 : break;
325 : : }
326 : : }
327 : :
328 : : // Dispatch to worker thread
329 [ + + ]: 201651 : if (i != iend) {
330 [ + - + - ]: 201649 : std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
331 [ - + ]: 201649 : assert(g_work_queue);
332 [ + - + + ]: 201649 : if (g_work_queue->Enqueue(item.get())) {
333 : 201648 : [[maybe_unused]] auto _{item.release()}; /* if true, queue took ownership */
334 : : } else {
335 [ + - ]: 1 : LogWarning("Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
336 [ + - ]: 1 : item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
337 : : }
338 : 201649 : } else {
339 [ + - ]: 2 : hreq->WriteReply(HTTP_NOT_FOUND);
340 : : }
341 : 201652 : }
342 : :
343 : : /** Callback to reject HTTP requests after shutdown. */
344 : 0 : static void http_reject_request_cb(struct evhttp_request* req, void*)
345 : : {
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 : 1109 : static void ThreadHTTP(struct event_base* base)
352 : : {
353 [ + - ]: 1109 : util::ThreadRename("http");
354 [ + + ]: 1109 : LogDebug(BCLog::HTTP, "Entering http event loop\n");
355 : 1109 : event_base_dispatch(base);
356 : : // Event loop will be interrupted by InterruptHTTPServer()
357 [ + + ]: 1109 : LogDebug(BCLog::HTTP, "Exited http event loop\n");
358 : 1109 : }
359 : :
360 : : /** Bind HTTP server to specified addresses */
361 : 1121 : static bool HTTPBindAddresses(struct evhttp* http)
362 : : {
363 [ + - ]: 1121 : uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
364 : 1121 : 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 [ + - + - : 2256 : if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
+ + + - +
- + - + +
+ + - - -
- - - ]
372 [ + - ]: 1114 : endpoints.emplace_back("::1", http_port);
373 [ + - ]: 1114 : endpoints.emplace_back("127.0.0.1", http_port);
374 [ + - + - : 1114 : if (!gArgs.GetArgs("-rpcallowip").empty()) {
- + ]
375 [ # # ]: 0 : LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
376 : : }
377 [ + - + - : 1114 : if (!gArgs.GetArgs("-rpcbind").empty()) {
- + ]
378 [ # # ]: 0 : LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
379 : : }
380 : : } else { // Specific bind addresses
381 [ + - + - : 25 : for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
+ + ]
382 : 11 : uint16_t port{http_port};
383 [ - + ]: 11 : std::string host;
384 [ - + + - : 11 : if (!SplitHostPort(strRPCBind, port, host)) {
- + ]
385 [ # # # # : 0 : LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
# # ]
386 : 0 : return false;
387 : : }
388 [ + - ]: 11 : endpoints.emplace_back(host, port);
389 : 18 : }
390 : : }
391 : :
392 : : // Bind addresses
393 [ + + ]: 3360 : for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
394 [ + - ]: 2239 : LogInfo("Binding RPC on address %s port %i", i->first, i->second);
395 [ + - + - ]: 2239 : evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
396 [ + + ]: 2239 : if (bind_handle) {
397 [ + - + - ]: 1125 : const std::optional<CNetAddr> addr{LookupHost(i->first, false)};
398 [ + - + - : 1125 : if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
+ - - + ]
399 [ # # ]: 0 : LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
400 : : }
401 : : // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
402 [ + - ]: 1125 : evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle);
403 : 1125 : int one = 1;
404 [ - + ]: 1125 : if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&one), sizeof(one)) == SOCKET_ERROR) {
405 [ # # ]: 0 : LogInfo("WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
406 : : }
407 [ + - ]: 1125 : boundSockets.push_back(bind_handle);
408 : 1125 : } else {
409 [ + - ]: 1114 : LogWarning("Binding RPC on address %s port %i failed.", i->first, i->second);
410 : : }
411 : : }
412 : 1121 : return !boundSockets.empty();
413 : 1121 : }
414 : :
415 : : /** Simple wrapper to set thread name and run work queue */
416 : 2217 : static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
417 : : {
418 [ + - ]: 2217 : util::ThreadRename(strprintf("httpworker.%i", worker_num));
419 : 2217 : queue->Run();
420 : 2217 : }
421 : :
422 : : /** libevent event log callback */
423 : 1114 : static void libevent_log_cb(int severity, const char *msg)
424 : : {
425 [ - - + - ]: 1114 : switch (severity) {
426 : 0 : case EVENT_LOG_DEBUG:
427 [ # # ]: 0 : LogDebug(BCLog::LIBEVENT, "%s", msg);
428 : : break;
429 : 0 : case EVENT_LOG_MSG:
430 : 0 : LogInfo("libevent: %s", msg);
431 : 0 : break;
432 : 1114 : case EVENT_LOG_WARN:
433 : 1114 : LogWarning("libevent: %s", msg);
434 : 1114 : break;
435 : 0 : default: // EVENT_LOG_ERR and others are mapped to error
436 : 0 : LogError("libevent: %s", msg);
437 : 0 : break;
438 : : }
439 : 1114 : }
440 : :
441 : 1121 : bool InitHTTPServer(const util::SignalInterrupt& interrupt)
442 : : {
443 [ + - ]: 1121 : if (!InitHTTPAllowList())
444 : : return false;
445 : :
446 : : // Redirect libevent's logging to our own log
447 : 1121 : event_set_log_callback(&libevent_log_cb);
448 : : // Update libevent's log handling.
449 : 1121 : UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT));
450 : :
451 : : #ifdef WIN32
452 : : evthread_use_windows_threads();
453 : : #else
454 : 1121 : evthread_use_pthreads();
455 : : #endif
456 : :
457 : 1121 : raii_event_base base_ctr = obtain_event_base();
458 : :
459 : : /* Create a new evhttp object to handle requests. */
460 [ + - ]: 1121 : raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
461 [ - + ]: 1121 : struct evhttp* http = http_ctr.get();
462 [ - + ]: 1121 : if (!http) {
463 [ # # ]: 0 : LogError("Couldn't create evhttp. Exiting.");
464 : : return false;
465 : : }
466 : :
467 [ + - + - : 1121 : evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
+ - ]
468 [ + - ]: 1121 : evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
469 [ + - ]: 1121 : evhttp_set_max_body_size(http, MAX_SIZE);
470 [ + - ]: 1121 : evhttp_set_gencb(http, http_request_cb, (void*)&interrupt);
471 : :
472 [ + - - + ]: 1121 : if (!HTTPBindAddresses(http)) {
473 [ # # ]: 0 : LogError("Unable to bind any endpoint for RPC server");
474 : : return false;
475 : : }
476 : :
477 [ + - + + : 1121 : LogDebug(BCLog::HTTP, "Initialized HTTP server\n");
+ - ]
478 [ + - + - : 2242 : int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
+ - ]
479 [ + - + + : 1121 : LogDebug(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth);
+ - ]
480 : :
481 [ + - ]: 2242 : g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
482 : : // transfer ownership to eventBase/HTTP via .release()
483 : 1121 : eventBase = base_ctr.release();
484 : 1121 : eventHTTP = http_ctr.release();
485 : 1121 : return true;
486 [ - + ]: 1121 : }
487 : :
488 : 1121 : void UpdateHTTPServerLogging(bool enable) {
489 [ - + ]: 1121 : if (enable) {
490 : 0 : event_enable_debug_logging(EVENT_DBG_ALL);
491 : : } else {
492 : 1121 : event_enable_debug_logging(EVENT_DBG_NONE);
493 : : }
494 : 1121 : }
495 : :
496 : : static std::thread g_thread_http;
497 : : static std::vector<std::thread> g_thread_http_workers;
498 : :
499 : 1109 : void StartHTTPServer()
500 : : {
501 [ + - + - ]: 2218 : int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
502 : 1109 : LogInfo("Starting HTTP server with %d worker threads\n", rpcThreads);
503 : 1109 : g_thread_http = std::thread(ThreadHTTP, eventBase);
504 : :
505 [ + + ]: 3326 : for (int i = 0; i < rpcThreads; i++) {
506 : 2217 : g_thread_http_workers.emplace_back(HTTPWorkQueueRun, g_work_queue.get(), i);
507 : : }
508 : 1109 : }
509 : :
510 : 1162 : void InterruptHTTPServer()
511 : : {
512 [ + + ]: 1162 : LogDebug(BCLog::HTTP, "Interrupting HTTP server\n");
513 [ + + ]: 1162 : if (eventHTTP) {
514 : : // Reject requests on current connections
515 : 1121 : evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
516 : : }
517 [ + + ]: 1162 : if (g_work_queue) {
518 : 1121 : g_work_queue->Interrupt();
519 : : }
520 : 1162 : }
521 : :
522 : 1162 : void StopHTTPServer()
523 : : {
524 [ + + ]: 1162 : LogDebug(BCLog::HTTP, "Stopping HTTP server\n");
525 [ + + ]: 1162 : if (g_work_queue) {
526 [ + + ]: 1121 : LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
527 [ + + ]: 3338 : for (auto& thread : g_thread_http_workers) {
528 : 2217 : thread.join();
529 : : }
530 : 1121 : g_thread_http_workers.clear();
531 : : }
532 : : // Unlisten sockets, these are what make the event loop running, which means
533 : : // that after this and all connections are closed the event loop will quit.
534 [ + + ]: 2287 : for (evhttp_bound_socket *socket : boundSockets) {
535 : 1125 : evhttp_del_accept_socket(eventHTTP, socket);
536 : : }
537 [ + + ]: 1162 : boundSockets.clear();
538 : 1162 : {
539 [ + + ]: 1162 : if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) {
540 [ + - ]: 13 : LogDebug(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections);
541 : : }
542 : 1162 : g_requests.WaitUntilEmpty();
543 : : }
544 [ + + ]: 1162 : if (eventHTTP) {
545 : : // Schedule a callback to call evhttp_free in the event base thread, so
546 : : // that evhttp_free does not need to be called again after the handling
547 : : // of unfinished request connections that follows.
548 : 1121 : event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
549 : : evhttp_free(eventHTTP);
550 : : eventHTTP = nullptr;
551 : : }, nullptr, nullptr);
552 : : }
553 [ + + ]: 1162 : if (eventBase) {
554 [ + + ]: 1121 : LogDebug(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
555 [ + + ]: 1121 : if (g_thread_http.joinable()) g_thread_http.join();
556 : 1121 : event_base_free(eventBase);
557 : 1121 : eventBase = nullptr;
558 : : }
559 [ + + ]: 1162 : g_work_queue.reset();
560 [ + + ]: 1162 : LogDebug(BCLog::HTTP, "Stopped HTTP server\n");
561 : 1162 : }
562 : :
563 : 1109 : struct event_base* EventBase()
564 : : {
565 : 1109 : return eventBase;
566 : : }
567 : :
568 : 201652 : static void httpevent_callback_fn(evutil_socket_t, short, void* data)
569 : : {
570 : : // Static handler: simply call inner handler
571 : 201652 : HTTPEvent *self = static_cast<HTTPEvent*>(data);
572 : 201652 : self->handler();
573 [ + - ]: 201652 : if (self->deleteWhenTriggered)
574 : 201652 : delete self;
575 : 201652 : }
576 : :
577 : 201652 : HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
578 : 201652 : deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
579 : : {
580 [ + - ]: 201652 : ev = event_new(base, -1, 0, httpevent_callback_fn, this);
581 [ - + ]: 201652 : assert(ev);
582 : 201652 : }
583 : 201652 : HTTPEvent::~HTTPEvent()
584 : : {
585 : 201652 : event_free(ev);
586 : 201652 : }
587 : 201652 : void HTTPEvent::trigger(struct timeval* tv)
588 : : {
589 [ + - ]: 201652 : if (tv == nullptr)
590 : 201652 : event_active(ev, 0, 0); // immediately trigger event in main thread
591 : : else
592 : 0 : evtimer_add(ev, tv); // trigger after timeval passed
593 : 201652 : }
594 : 201652 : HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent)
595 : 201652 : : req(_req), m_interrupt(interrupt), replySent(_replySent)
596 : : {
597 : 201652 : }
598 : :
599 : 201652 : HTTPRequest::~HTTPRequest()
600 : : {
601 [ - + ]: 201652 : if (!replySent) {
602 : : // Keep track of whether reply was sent to avoid request leaks
603 : 0 : LogWarning("Unhandled HTTP request");
604 : 0 : WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
605 : : }
606 : : // evhttpd cleans up the request, as long as a reply was sent.
607 : 201652 : }
608 : :
609 : 200907 : std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
610 : : {
611 : 200907 : const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
612 [ - + ]: 200907 : assert(headers);
613 : 200907 : const char* val = evhttp_find_header(headers, hdr.c_str());
614 [ + - ]: 200907 : if (val)
615 : 200907 : return std::make_pair(true, val);
616 : : else
617 : 0 : return std::make_pair(false, "");
618 : : }
619 : :
620 : 200907 : std::string HTTPRequest::ReadBody()
621 : : {
622 : 200907 : struct evbuffer* buf = evhttp_request_get_input_buffer(req);
623 [ - + ]: 200907 : if (!buf)
624 : 0 : return "";
625 : 200907 : size_t size = evbuffer_get_length(buf);
626 : : /** Trivial implementation: if this is ever a performance bottleneck,
627 : : * internal copying can be avoided in multi-segment buffers by using
628 : : * evbuffer_peek and an awkward loop. Though in that case, it'd be even
629 : : * better to not copy into an intermediate string but use a stream
630 : : * abstraction to consume the evbuffer on the fly in the parsing algorithm.
631 : : */
632 : 200907 : const char* data = (const char*)evbuffer_pullup(buf, size);
633 [ + + ]: 200907 : if (!data) // returns nullptr in case of empty buffer
634 : 18 : return "";
635 : 200889 : std::string rv(data, size);
636 [ + - ]: 200889 : evbuffer_drain(buf, size);
637 : 200889 : return rv;
638 : 200889 : }
639 : :
640 : 202626 : void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
641 : : {
642 : 202626 : struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
643 [ - + ]: 202626 : assert(headers);
644 : 202626 : evhttp_add_header(headers, hdr.c_str(), value.c_str());
645 : 202626 : }
646 : :
647 : : /** Closure sent to main thread to request a reply to be sent to
648 : : * a HTTP request.
649 : : * Replies must be sent in the main loop in the main http thread,
650 : : * this cannot be done from worker threads.
651 : : */
652 : 201652 : void HTTPRequest::WriteReply(int nStatus, std::span<const std::byte> reply)
653 : : {
654 [ + - - + ]: 201652 : assert(!replySent && req);
655 [ + + ]: 201652 : if (m_interrupt) {
656 [ + - + - ]: 1994 : WriteHeader("Connection", "close");
657 : : }
658 : : // Send event to main http thread to send reply message
659 : 201652 : struct evbuffer* evb = evhttp_request_get_output_buffer(req);
660 [ - + ]: 201652 : assert(evb);
661 : 201652 : evbuffer_add(evb, reply.data(), reply.size());
662 : 201652 : auto req_copy = req;
663 [ + - ]: 201652 : HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
664 : 201652 : evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
665 : : // Re-enable reading from the socket. This is the second part of the libevent
666 : : // workaround above.
667 [ + - - + ]: 201652 : if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
668 : 0 : evhttp_connection* conn = evhttp_request_get_connection(req_copy);
669 [ # # ]: 0 : if (conn) {
670 : 0 : bufferevent* bev = evhttp_connection_get_bufferevent(conn);
671 [ # # ]: 0 : if (bev) {
672 : 0 : bufferevent_enable(bev, EV_READ | EV_WRITE);
673 : : }
674 : : }
675 : : }
676 [ + - ]: 201652 : });
677 : 201652 : ev->trigger(nullptr);
678 : 201652 : replySent = true;
679 : 201652 : req = nullptr; // transferred back to main thread
680 : 201652 : }
681 : :
682 : 604199 : CService HTTPRequest::GetPeer() const
683 : : {
684 : 604199 : evhttp_connection* con = evhttp_request_get_connection(req);
685 : 604199 : CService peer;
686 [ + - ]: 604199 : if (con) {
687 : : // evhttp retains ownership over returned address string
688 : 604199 : const char* address = "";
689 : 604199 : uint16_t port = 0;
690 : :
691 : : #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
692 : : evhttp_connection_get_peer(con, &address, &port);
693 : : #else
694 [ + - ]: 604199 : evhttp_connection_get_peer(con, (char**)&address, &port);
695 : : #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
696 : :
697 [ + - + - : 1208398 : peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port));
+ - + - ]
698 : : }
699 : 604199 : return peer;
700 : 0 : }
701 : :
702 : 604175 : std::string HTTPRequest::GetURI() const
703 : : {
704 : 604175 : return evhttp_request_get_uri(req);
705 : : }
706 : :
707 : 604198 : HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const
708 : : {
709 [ + - - - : 604198 : switch (evhttp_request_get_command(req)) {
+ ]
710 : : case EVHTTP_REQ_GET:
711 : : return GET;
712 : 602723 : case EVHTTP_REQ_POST:
713 : 602723 : return POST;
714 : 0 : case EVHTTP_REQ_HEAD:
715 : 0 : return HEAD;
716 : 0 : case EVHTTP_REQ_PUT:
717 : 0 : return PUT;
718 : 0 : default:
719 : 0 : return UNKNOWN;
720 : : }
721 : : }
722 : :
723 : 85 : std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const
724 : : {
725 : 85 : const char* uri{evhttp_request_get_uri(req)};
726 : :
727 : 85 : return GetQueryParameterFromUri(uri, key);
728 : : }
729 : :
730 : 93 : std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key)
731 : : {
732 : 93 : evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
733 [ + + ]: 93 : if (!uri_parsed) {
734 [ + - ]: 6 : throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters");
735 : : }
736 : 87 : const char* query{evhttp_uri_get_query(uri_parsed)};
737 : 87 : std::optional<std::string> result;
738 : :
739 [ + + ]: 87 : if (query) {
740 : : // Parse the query string into a key-value queue and iterate over it
741 : 80 : struct evkeyvalq params_q;
742 [ + - ]: 80 : evhttp_parse_query_str(query, ¶ms_q);
743 : :
744 [ + + ]: 112 : for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) {
745 [ + + ]: 104 : if (param->key == key) {
746 [ + - ]: 72 : result = param->value;
747 : : break;
748 : : }
749 : : }
750 [ + - ]: 80 : evhttp_clear_headers(¶ms_q);
751 : : }
752 [ + - ]: 87 : evhttp_uri_free(uri_parsed);
753 : :
754 : 87 : return result;
755 : 0 : }
756 : :
757 : 2232 : void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
758 : : {
759 [ + + ]: 2232 : LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
760 : 2232 : LOCK(g_httppathhandlers_mutex);
761 [ + - ]: 2232 : pathHandlers.emplace_back(prefix, exactMatch, handler);
762 : 2232 : }
763 : :
764 : 18592 : void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
765 : : {
766 : 18592 : LOCK(g_httppathhandlers_mutex);
767 : 18592 : std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
768 : 18592 : std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
769 [ + + ]: 18592 : for (; i != iend; ++i)
770 [ + - - + ]: 2232 : if (i->prefix == prefix && i->exactMatch == exactMatch)
771 : : break;
772 [ + + ]: 18592 : if (i != iend)
773 : : {
774 [ + - + + : 2232 : LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
+ - ]
775 : 2232 : pathHandlers.erase(i);
776 : : }
777 : 18592 : }
|