23 #include <condition_variable> 32 #include <unordered_map> 35 #include <sys/types.h> 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> 66 static struct event_base*
eventBase =
nullptr;
89 mutable std::condition_variable
m_cv;
91 std::unordered_map<const evhttp_connection*, size_t> m_tracker
GUARDED_BY(
m_mutex);
96 if (m_tracker.empty())
m_cv.notify_all();
102 const evhttp_connection* conn{
Assert(evhttp_request_get_connection(
Assert(req)))};
108 const evhttp_connection* conn{
Assert(evhttp_request_get_connection(
Assert(req)))};
110 auto it{m_tracker.find(conn)};
111 if (it != m_tracker.end() && it->second > 0) {
119 auto it{m_tracker.find(
Assert(conn))};
142 if (subnet.Match(netaddr))
153 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
155 if (!subnet.IsValid()) {
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)),
163 std::string strAllowed;
165 strAllowed += subnet.ToString() +
" ";
191 evhttp_connection* conn{evhttp_request_get_connection(req)};
195 evhttp_request_set_on_complete_cb(req, [](
struct evhttp_request* req,
void*) {
198 evhttp_connection_set_closecb(conn, [](evhttp_connection* conn,
void* arg) {
206 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
208 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
210 bufferevent_disable(bev, EV_READ);
218 LogDebug(
BCLog::HTTP,
"HTTP request from %s rejected: Client network is not allowed RPC access\n",
219 hreq->GetPeer().ToStringAddrPort());
227 hreq->GetPeer().ToStringAddrPort());
236 std::string strURI = hreq->GetURI();
239 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
240 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
241 for (; i != iend; ++i) {
244 match = (strURI == i->prefix);
246 match = strURI.starts_with(i->prefix);
248 path = strURI.substr(i->prefix.size());
256 LogWarning(
"Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
261 auto item = [req = hreq, in_path = std::move(path), fn = i->handler]() {
264 fn(req.get(), in_path);
266 }
catch (
const std::exception& e) {
267 LogWarning(
"Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(), e.what());
270 LogWarning(
"Unknown error while processing request for '%s'", req->GetURI());
271 err_msg =
"unknown error";
274 req->WriteHeader(
"Connection",
"close");
280 Assume(hreq.use_count() == 1);
295 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
303 event_base_dispatch(base);
312 std::vector<std::pair<std::string, uint16_t>> endpoints;
320 endpoints.emplace_back(
"::1", http_port);
321 endpoints.emplace_back(
"127.0.0.1", http_port);
323 LogWarning(
"Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
326 LogWarning(
"Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
329 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
330 uint16_t port{http_port};
336 endpoints.emplace_back(host, port);
341 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
342 LogInfo(
"Binding RPC on address %s port %i", i->first, i->second);
343 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
345 const std::optional<CNetAddr> addr{
LookupHost(i->first,
false)};
346 if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
347 LogWarning(
"The RPC server is not safe to expose to untrusted networks such as the public internet");
350 evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle);
352 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&one),
sizeof(one)) ==
SOCKET_ERROR) {
353 LogInfo(
"WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
357 LogWarning(
"Binding RPC on address %s port %i failed.", i->first, i->second);
367 case EVENT_LOG_DEBUG:
393 evthread_use_windows_threads();
395 evthread_use_pthreads();
402 struct evhttp* http = http_ctr.get();
404 LogError(
"Couldn't create evhttp. Exiting.");
410 evhttp_set_max_body_size(http,
MAX_SIZE);
414 LogError(
"Unable to bind any endpoint for RPC server");
430 event_enable_debug_logging(EVENT_DBG_ALL);
432 event_enable_debug_logging(EVENT_DBG_NONE);
441 LogInfo(
"Starting HTTP server with %d worker threads", rpcThreads);
467 evhttp_del_accept_socket(
eventHTTP, socket);
480 event_base_once(
eventBase, -1, EV_TIMEOUT, [](evutil_socket_t,
short,
void*) {
483 },
nullptr,
nullptr);
504 if (self->deleteWhenTriggered)
508 HTTPEvent::HTTPEvent(
struct event_base* base,
bool _deleteWhenTriggered,
const std::function<
void()>& _handler):
509 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler)
521 event_active(
ev, 0, 0);
526 : req(_req), m_interrupt(interrupt), replySent(_replySent)
542 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
544 const char* val = evhttp_find_header(headers, hdr.c_str());
546 return std::make_pair(
true, val);
548 return std::make_pair(
false,
"");
553 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
556 size_t size = evbuffer_get_length(buf);
563 const char*
data = (
const char*)evbuffer_pullup(buf, size);
566 std::string rv(
data, size);
567 evbuffer_drain(buf, size);
573 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
575 evhttp_add_header(headers, hdr.c_str(), value.c_str());
590 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
592 evbuffer_add(evb, reply.data(), reply.size());
595 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
598 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
599 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
601 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
603 bufferevent_enable(bev, EV_READ | EV_WRITE);
615 evhttp_connection* con = evhttp_request_get_connection(
req);
619 const char* address =
"";
622 #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR 623 evhttp_connection_get_peer(con, &address, &port);
625 evhttp_connection_get_peer(con, (
char**)&address, &port);
626 #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR 635 return evhttp_request_get_uri(
req);
640 switch (evhttp_request_get_command(
req)) {
643 case EVHTTP_REQ_POST:
645 case EVHTTP_REQ_HEAD:
656 const char* uri{evhttp_request_get_uri(
req)};
663 evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
665 throw std::runtime_error(
"URI parsing failed, it likely contained RFC 3986 invalid characters");
667 const char* query{evhttp_uri_get_query(uri_parsed)};
668 std::optional<std::string>
result;
672 struct evkeyvalq params_q;
673 evhttp_parse_query_str(query, ¶ms_q);
675 for (
struct evkeyval* param{params_q.tqh_first}; param !=
nullptr; param = param->next.tqe_next) {
676 if (param->key == key) {
681 evhttp_clear_headers(¶ms_q);
683 evhttp_uri_free(uri_parsed);
698 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
699 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
700 for (; i != iend; ++i)
701 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
706 pathHandlers.erase(i);
HTTPRequest(struct evhttp_request *req, const util::SignalInterrupt &interrupt, bool replySent=false)
static HTTPRequestTracker g_requests
Track active requests.
raii_event_base obtain_event_base()
bool InitHTTPServer(const util::SignalInterrupt &interrupt)
Initialize HTTP server.
BCLog::Logger & LogInstance()
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
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.
CClientUIInterface uiInterface
void WriteReply(int nStatus, std::string_view reply="")
Write HTTP reply.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
raii_evhttp obtain_evhttp(struct event_base *base)
is a home for simple string functions returning descriptive messages that are used in RPC and GUI int...
static const int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
Helps keep track of open evhttp_connections with active evhttp_requests
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
static ThreadPool g_threadpool_http("http")
Http thread pool - future: encapsulate in HttpContext.
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
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...
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...
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
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...
void RemoveConnection(const evhttp_connection *conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Remove a connection entirely.
struct evhttp_request * req
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.
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
void InterruptHTTPServer()
Interrupt HTTP server threads.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
void AddRequest(evhttp_request *req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Increase request counter for the associated connection by 1.
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Fixed-size thread pool for running arbitrary tasks concurrently.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait until there are no more connections with active requests in the tracker.
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
static int g_max_queue_depth
static std::thread g_thread_http
void StopHTTPServer()
Stop HTTP server.
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.
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
RequestMethod GetRequestMethod() const
Get request method.
constexpr std::string_view SubmitErrorString(const ThreadPool::SubmitError err) noexcept
static std::vector< HTTPPathHandler > pathHandlers GUARDED_BY(g_httppathhandlers_mutex)
A combination of a network address (CNetAddr) and a (TCP) port.
static void ThreadHTTP(struct event_base *base)
Event dispatcher thread.
void Start(int num_workers) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start worker threads.
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
#define WAIT_LOCK(cs, name)
void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
const util::SignalInterrupt & m_interrupt
static GlobalMutex g_httppathhandlers_mutex
Handlers for (sub)paths.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define Assume(val)
Assume is the identity function.
struct event_base * EventBase()
Return evhttp event base.
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
#define LogDebug(category,...)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop accepting new tasks and begin asynchronous shutdown.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
util::Expected< std::future< std::invoke_result_t< F > >, SubmitError > Submit(F &&fn) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Enqueues a new task for asynchronous execution.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
void trigger(struct timeval *tv)
Trigger the event.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop all worker threads and wait for them to exit.
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
std::function< void()> handler
std::condition_variable m_cv
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...
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...
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
static const size_t MAX_HEADERS_SIZE
Maximum size of http request (request line + headers)
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
size_t WorkQueueSize() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
std::string ReadBody()
Read request body.
void StartHTTPServer()
Start HTTP server.
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
Different type to mark Mutex at global scope.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
HTTPRequestHandler handler
Chars allowed in URIs (RFC 3986)
static struct evhttp * eventHTTP
HTTP server.
static const int DEFAULT_HTTP_THREADS
The default value for -rpcthreads.
std::string GetURI() const
Get requested URI.
CSubNet LookupSubNet(const std::string &subnet_str)
Parse and resolve a specified subnet string into the appropriate internal representation.
#define Assert(val)
Identity function.
static struct event_base * eventBase
HTTP module state.