23#include <event2/buffer.h>
24#include <event2/bufferevent.h>
25#include <event2/event.h>
26#include <event2/http.h>
27#include <event2/keyvalq_struct.h>
28#include <event2/thread.h>
29#include <event2/util.h>
36#include <condition_variable>
42#include <unordered_map>
62 std::unique_ptr<HTTPRequest>
req;
92 if (!running || queue.size() >=
maxDepth) {
95 queue.emplace_back(std::unique_ptr<WorkItem>(item));
103 std::unique_ptr<WorkItem> i;
106 while (running && queue.empty()) {
109 if (!running && queue.empty()) {
112 i = std::move(queue.front());
158 mutable std::condition_variable
m_cv;
160 std::unordered_map<const evhttp_connection *, size_t>
166 if (m_tracker.empty()) {
174 const evhttp_connection *conn{
181 const evhttp_connection *conn{
184 auto it{m_tracker.find(conn)};
185 if (it != m_tracker.end() && it->second > 0) {
186 if (--(it->second) == 0) {
195 auto it{m_tracker.find(
Assert(conn))};
196 if (it != m_tracker.end()) {
208 return m_tracker.empty();
221 if (subnet.Match(netaddr)) {
236 for (
const std::string &strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
242 Untranslated(
"Invalid -rpcallowip subnet specification: "
243 "%s. Valid are a single IP (e.g. 1.2.3.4), a "
244 "network/netmask (e.g. 1.2.3.4/255.255.255.0) "
245 "or a network/CIDR (e.g. 1.2.3.4/24)."),
252 std::string strAllowed;
254 strAllowed += subnet.ToString() +
" ";
282 evhttp_connection *conn{evhttp_request_get_connection(req)};
286 evhttp_request_set_on_complete_cb(
288 [](
struct evhttp_request *req,
void *) {
292 evhttp_connection_set_closecb(
294 [](evhttp_connection *conn,
void *arg) {
301 if (event_get_version_number() >= 0x02010600 &&
302 event_get_version_number() < 0x02020001) {
304 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
306 bufferevent_disable(bev, EV_READ);
310 auto hreq = std::make_unique<HTTPRequest>(req);
315 "HTTP request from %s rejected: Client network is not allowed "
317 hreq->GetPeer().ToStringAddrPort());
325 "HTTP request from %s rejected: Unknown HTTP request method\n",
326 hreq->GetPeer().ToStringAddrPort());
334 hreq->GetPeer().ToStringAddrPort());
337 std::string strURI = hreq->GetURI();
339 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
340 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
341 for (; i != iend; ++i) {
344 match = (strURI == i->prefix);
346 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
349 path = strURI.substr(i->prefix.size());
356 std::unique_ptr<HTTPWorkItem> item(
357 new HTTPWorkItem(config, std::move(hreq), path, i->handler));
363 LogPrintf(
"WARNING: request rejected because http work queue depth "
364 "exceeded, it can be increased with the -rpcworkqueue= "
367 "Work queue depth exceeded");
377 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
384 event_base_dispatch(base);
387 return event_base_got_break(base) == 0;
392 uint16_t http_port{
static_cast<uint16_t
>(
394 std::vector<std::pair<std::string, uint16_t>> endpoints;
399 endpoints.push_back(std::make_pair(
"::1", http_port));
400 endpoints.push_back(std::make_pair(
"127.0.0.1", http_port));
402 LogPrintf(
"WARNING: option -rpcallowip was specified without "
403 "-rpcbind; this doesn't usually make sense\n");
406 LogPrintf(
"WARNING: option -rpcbind was ignored because "
407 "-rpcallowip was not specified, refusing to allow "
408 "everyone to connect\n");
412 for (
const std::string &strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
413 uint16_t port{http_port};
416 endpoints.push_back(std::make_pair(host, port));
421 for (std::vector<std::pair<std::string, uint16_t>>::iterator i =
423 i != endpoints.end(); ++i) {
426 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(
427 http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
429 const std::optional<CNetAddr> addr{
LookupHost(i->first,
false)};
430 if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
431 LogPrintf(
"WARNING: the RPC server is not safe to expose to "
432 "untrusted networks such as the public internet\n");
436 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first,
453 case EVENT_LOG_DEBUG:
480 evthread_use_windows_threads();
482 evthread_use_pthreads();
489 struct evhttp *http = http_ctr.get();
491 LogPrintf(
"couldn't create evhttp. Exiting.\n");
504 evhttp_set_allowed_methods(
505 http, EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD |
506 EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
509 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
514 int workQueueDepth = std::max(
518 g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
527 event_enable_debug_logging(EVENT_DBG_ALL);
529 event_enable_debug_logging(EVENT_DBG_NONE);
537 int rpcThreads = std::max(
539 LogInfo(
"Starting HTTP server with %d worker threads\n", rpcThreads);
542 for (
int i = 0; i < rpcThreads; i++) {
571 evhttp_del_accept_socket(
eventHTTP, socket);
576 n_connections != 0) {
578 "Waiting for %d connections to stop HTTP server\n",
589 [](evutil_socket_t,
short,
void *) {
621 const std::function<
void()> &_handler)
622 : deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler) {
632 event_active(
ev, 0, 0);
639 : req(_req), replySent(_replySent) {}
643 LogPrintf(
"%s: Unhandled request\n", __func__);
649std::pair<bool, std::string>
651 const struct evkeyvalq *headers = evhttp_request_get_input_headers(
req);
653 const char *val = evhttp_find_header(headers, hdr.c_str());
655 return std::make_pair(
true, val);
657 return std::make_pair(
false,
"");
662 struct evbuffer *buf = evhttp_request_get_input_buffer(
req);
666 size_t size = evbuffer_get_length(buf);
674 const char *data = (
const char *)evbuffer_pullup(buf, size);
680 std::string rv(data, size);
681 evbuffer_drain(buf, size);
686 const std::string &value) {
687 struct evkeyvalq *headers = evhttp_request_get_output_headers(
req);
689 evhttp_add_header(headers, hdr.c_str(), value.c_str());
703 struct evbuffer *evb = evhttp_request_get_output_buffer(
req);
705 evbuffer_add(evb, strReply.data(), strReply.size());
708 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
711 if (event_get_version_number() >= 0x02010600 &&
712 event_get_version_number() < 0x02020001) {
713 evhttp_connection *conn = evhttp_request_get_connection(req_copy);
715 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
717 bufferevent_enable(bev, EV_READ | EV_WRITE);
729 evhttp_connection *con = evhttp_request_get_connection(
req);
733 const char *address =
"";
735 evhttp_connection_get_peer(con, (
char **)&address, &port);
742 return evhttp_request_get_uri(
req);
746 switch (evhttp_request_get_command(
req)) {
749 case EVHTTP_REQ_POST:
751 case EVHTTP_REQ_HEAD:
755 case EVHTTP_REQ_OPTIONS:
762std::optional<std::string>
764 const char *uri{evhttp_request_get_uri(
req)};
770 const std::string &key) {
771 evhttp_uri *uri_parsed{evhttp_uri_parse(uri)};
773 throw std::runtime_error(
"URI parsing failed, it likely contained RFC "
774 "3986 invalid characters");
776 const char *query{evhttp_uri_get_query(uri_parsed)};
777 std::optional<std::string> result;
781 struct evkeyvalq params_q;
782 evhttp_parse_query_str(query, ¶ms_q);
784 for (
struct evkeyval *param{params_q.tqh_first}; param !=
nullptr;
785 param = param->next.tqe_next) {
786 if (param->key == key) {
787 result = param->value;
791 evhttp_clear_headers(¶ms_q);
793 evhttp_uri_free(uri_parsed);
805 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
806 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
807 for (; i != iend; ++i) {
808 if (i->prefix ==
prefix && i->exactMatch == exactMatch) {
814 "Unregistering HTTP handler for %s (exactmatch %d)\n",
prefix,
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assert(val)
Identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
A combination of a network address (CNetAddr) and a (TCP) port.
virtual uint64_t GetMaxBlockSize() const =0
std::function< void()> handler
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
void trigger(struct timeval *tv)
Trigger the event.
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...
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
std::string GetURI() const
Get requested URI.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
struct evhttp_request * req
RequestMethod GetRequestMethod() const
Get request method.
std::string ReadBody()
Read request body.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Helps keep track of open evhttp_connections with active evhttp_requests
void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait until there are no more connections with active requests in the tracker.
size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void AddRequest(evhttp_request *req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Increase request counter for the associated connection by 1.
void RemoveConnection(const evhttp_connection *conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Remove a connection entirely.
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.
std::condition_variable m_cv
void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
void operator()() override
std::unique_ptr< HTTPRequest > req
HTTPWorkItem(Config &_config, std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Simple work queue for distributing work over multiple threads.
bool Enqueue(WorkItem *item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Enqueue a work item.
~WorkQueue()=default
Precondition: worker threads have all stopped (they have all been joined)
std::deque< std::unique_ptr< WorkItem > > queue GUARDED_BY(cs)
std::condition_variable cond GUARDED_BY(cs)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
bool running GUARDED_BY(cs)
WorkQueue(size_t _maxDepth)
void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Thread function.
raii_evhttp obtain_evhttp(struct event_base *base)
raii_event_base obtain_event_base()
static struct evhttp * eventHTTP
HTTP server.
void InterruptHTTPServer()
Interrupt HTTP server threads.
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
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...
void StartHTTPServer()
Start HTTP server.
static struct event_base * eventBase
HTTP module state.
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
static std::thread g_thread_http
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
struct event_base * EventBase()
Return evhttp event base.
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
static const size_t MIN_SUPPORTED_BODY_SIZE
Maximum HTTP post body size.
static HTTPRequestTracker g_requests
Track active requests.
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
static const size_t MAX_HEADERS_SIZE
Maximum size of http request (request line + headers)
void StopHTTPServer()
Stop HTTP server.
static std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
static std::vector< std::thread > g_thread_http_workers
bool InitHTTPServer(Config &config)
Initialize HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_THREADS
std::function< bool(Config &config, HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
BCLog::Logger & LogInstance()
#define LogPrintLevel(category, level,...)
#define LogDebug(category,...)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
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.
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret, DNSLookupFn dns_lookup_function)
Parse and resolve a specified subnet string into the appropriate internal representation.
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.
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
@ HTTP_SERVICE_UNAVAILABLE
@ HTTP_INTERNAL_SERVER_ERROR
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
HTTPRequestHandler handler
#define WAIT_LOCK(cs, name)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
CClientUIInterface uiInterface
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.