5 #if defined(HAVE_CONFIG_H) 31 #include <sys/types.h> 34 #include <event2/buffer.h> 35 #include <event2/bufferevent.h> 36 #include <event2/http.h> 37 #include <event2/keyvalq_struct.h> 38 #include <event2/thread.h> 39 #include <event2/util.h> 59 std::unique_ptr<HTTPRequest>
req;
69 template <
typename WorkItem>
75 std::deque<std::unique_ptr<WorkItem>> queue
GUARDED_BY(
cs);
90 if (!running || queue.size() >=
maxDepth) {
93 queue.emplace_back(std::unique_ptr<WorkItem>(item));
101 std::unique_ptr<WorkItem> i;
104 while (running && queue.empty())
106 if (!running && queue.empty())
108 i = std::move(queue.front());
136 static struct event_base*
eventBase =
nullptr;
156 if (subnet.Match(netaddr))
171 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
176 strprintf(
Untranslated(
"Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24)."), strAllow),
182 std::string strAllowed;
184 strAllowed += subnet.ToString() +
" ";
214 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
215 evhttp_connection* conn = evhttp_request_get_connection(req);
217 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
219 bufferevent_disable(bev, EV_READ);
223 std::unique_ptr<HTTPRequest> hreq(
new HTTPRequest(req));
227 LogPrint(
BCLog::HTTP,
"HTTP request from %s rejected: Client network is not allowed RPC access\n",
228 hreq->GetPeer().ToString());
236 hreq->GetPeer().ToString());
245 std::string strURI = hreq->GetURI();
248 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
249 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
250 for (; i != iend; ++i) {
253 match = (strURI == i->prefix);
255 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
257 path = strURI.substr(i->prefix.size());
264 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(std::move(hreq), path, i->handler));
269 LogPrintf(
"WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
281 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
290 event_base_dispatch(base);
293 return event_base_got_break(base) == 0;
300 std::vector<std::pair<std::string, uint16_t>> endpoints;
304 endpoints.push_back(std::make_pair(
"::1", http_port));
305 endpoints.push_back(std::make_pair(
"127.0.0.1", http_port));
307 LogPrintf(
"WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
310 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
313 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
314 uint16_t port{http_port};
317 endpoints.push_back(std::make_pair(host, port));
322 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
324 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
328 LogPrintf(
"WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
332 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
351 case EVENT_LOG_DEBUG:
378 evthread_use_windows_threads();
380 evthread_use_pthreads();
387 struct evhttp* http = http_ctr.get();
389 LogPrintf(
"couldn't create evhttp. Exiting.\n");
395 evhttp_set_max_body_size(http,
MAX_SIZE);
399 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
407 g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
416 event_enable_debug_logging(EVENT_DBG_ALL);
418 event_enable_debug_logging(EVENT_DBG_NONE);
432 for (
int i = 0; i < rpcThreads; i++) {
462 evhttp_del_accept_socket(
eventHTTP, socket);
491 if (self->deleteWhenTriggered)
495 HTTPEvent::HTTPEvent(
struct event_base* base,
bool _deleteWhenTriggered,
const std::function<
void()>& _handler):
496 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler)
508 event_active(
ev, 0, 0);
520 LogPrintf(
"%s: Unhandled request\n", __func__);
528 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
530 const char* val = evhttp_find_header(headers, hdr.c_str());
532 return std::make_pair(
true, val);
534 return std::make_pair(
false,
"");
539 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
542 size_t size = evbuffer_get_length(buf);
549 const char* data = (
const char*)evbuffer_pullup(buf, size);
552 std::string rv(data, size);
553 evbuffer_drain(buf, size);
559 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
561 evhttp_add_header(headers, hdr.c_str(), value.c_str());
576 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
578 evbuffer_add(evb, strReply.data(), strReply.size());
581 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
584 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
585 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
587 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
589 bufferevent_enable(bev, EV_READ | EV_WRITE);
601 evhttp_connection* con = evhttp_request_get_connection(
req);
605 const char* address =
"";
608 #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR 609 evhttp_connection_get_peer(con, &address, &port);
611 evhttp_connection_get_peer(con, (
char**)&address, &port);
612 #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR 621 return evhttp_request_get_uri(
req);
626 switch (evhttp_request_get_command(
req)) {
630 case EVHTTP_REQ_POST:
633 case EVHTTP_REQ_HEAD:
647 const char* uri{evhttp_request_get_uri(
req)};
654 evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
656 throw std::runtime_error(
"URI parsing failed, it likely contained RFC 3986 invalid characters");
658 const char* query{evhttp_uri_get_query(uri_parsed)};
659 std::optional<std::string> result;
663 struct evkeyvalq params_q;
664 evhttp_parse_query_str(query, ¶ms_q);
666 for (
struct evkeyval* param{params_q.tqh_first}; param !=
nullptr; param = param->next.tqe_next) {
667 if (param->key == key) {
668 result = param->value;
672 evhttp_clear_headers(¶ms_q);
674 evhttp_uri_free(uri_parsed);
689 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
690 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
691 for (; i != iend; ++i)
692 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
697 pathHandlers.erase(i);
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
raii_event_base obtain_event_base()
BCLog::Logger & LogInstance()
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
CClientUIInterface uiInterface
#define LogPrint(category,...)
static const int DEFAULT_HTTP_SERVER_TIMEOUT
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
std::condition_variable cond GUARDED_BY(cs)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
raii_evhttp obtain_evhttp(struct event_base *base)
static const int DEFAULT_HTTP_WORKQUEUE
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
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...
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
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)
bool Enqueue(WorkItem *item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Enqueue a work item.
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.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Thread function.
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
bool InitHTTPServer()
Initialize HTTP server.
static std::thread g_thread_http
void StopHTTPServer()
Stop HTTP server.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
RequestMethod GetRequestMethod() const
Get request method.
static std::vector< HTTPPathHandler > pathHandlers GUARDED_BY(g_httppathhandlers_mutex)
A combination of a network address (CNetAddr) and a (TCP) port.
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
#define LogPrintLevel(category, level,...)
#define LogPrintfCategory(category,...)
#define WAIT_LOCK(cs, name)
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
static GlobalMutex g_httppathhandlers_mutex
Handlers for (sub)paths.
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
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.
Simple work queue for distributing work over multiple threads.
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
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
Return integer argument or default value.
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
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.
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
void operator()() override
std::string ReadBody()
Read request body.
void StartHTTPServer()
Start HTTP server.
WorkQueue(size_t _maxDepth)
std::unique_ptr< HTTPRequest > req
~WorkQueue()=default
Precondition: worker threads have all stopped (they have been joined).
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 std::vector< std::thread > g_thread_http_workers
static struct evhttp * eventHTTP
HTTP server.
static const int DEFAULT_HTTP_THREADS
HTTPRequest(struct evhttp_request *req, bool replySent=false)
std::string GetURI() const
Get requested URI.
static struct event_base * eventBase
HTTP module state.
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)