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