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