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