29#include <event2/thread.h>
30#include <event2/buffer.h>
31#include <event2/bufferevent.h>
32#include <event2/util.h>
33#include <event2/keyvalq_struct.h>
53 std::unique_ptr<HTTPRequest>
req;
63template <
typename WorkItem>
74 explicit WorkQueue(
size_t _maxDepth) : running(true),
87 if (!running || queue.size() >=
maxDepth) {
90 queue.emplace_back(std::unique_ptr<WorkItem>(item));
98 std::unique_ptr<WorkItem> i;
101 while (running && queue.empty())
103 if (!running && queue.empty())
105 i = std::move(queue.front());
152 if (subnet.Match(netaddr))
167 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
172 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),
178 std::string strAllowed;
180 strAllowed += subnet.ToString() +
" ";
210 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
211 evhttp_connection* conn = evhttp_request_get_connection(req);
213 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
215 bufferevent_disable(bev, EV_READ);
219 std::unique_ptr<HTTPRequest> hreq(
new HTTPRequest(req));
223 LogPrint(
BCLog::HTTP,
"HTTP request from %s rejected: Client network is not allowed RPC access\n",
224 hreq->GetPeer().ToString());
232 hreq->GetPeer().ToString());
241 std::string strURI = hreq->GetURI();
243 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
244 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
245 for (; i != iend; ++i) {
248 match = (strURI == i->prefix);
250 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
252 path = strURI.substr(i->prefix.size());
259 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(std::move(hreq), path, i->handler));
264 LogPrintf(
"WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
276 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
285 event_base_dispatch(base);
288 return event_base_got_break(base) == 0;
295 std::vector<std::pair<std::string, uint16_t>> endpoints;
299 endpoints.push_back(std::make_pair(
"::1", http_port));
300 endpoints.push_back(std::make_pair(
"127.0.0.1", http_port));
302 LogPrintf(
"WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
305 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
308 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
309 uint16_t port{http_port};
312 endpoints.push_back(std::make_pair(host, port));
317 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
319 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
323 LogPrintf(
"WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
327 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
344 if (severity >= EVENT_LOG_WARN)
365 evthread_use_windows_threads();
367 evthread_use_pthreads();
374 struct evhttp* http = http_ctr.get();
376 LogPrintf(
"couldn't create evhttp. Exiting.\n");
382 evhttp_set_max_body_size(http,
MAX_SIZE);
386 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
392 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
394 g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
402#if LIBEVENT_VERSION_NUMBER >= 0x02010100
404 event_enable_debug_logging(EVENT_DBG_ALL);
406 event_enable_debug_logging(EVENT_DBG_NONE);
422 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
425 for (
int i = 0; i < rpcThreads; i++) {
455 evhttp_del_accept_socket(
eventHTTP, socket);
484 if (self->deleteWhenTriggered)
488HTTPEvent::HTTPEvent(
struct event_base* base,
bool _deleteWhenTriggered,
const std::function<
void()>& _handler):
489 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler)
501 event_active(
ev, 0, 0);
513 LogPrintf(
"%s: Unhandled request\n", __func__);
521 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
523 const char* val = evhttp_find_header(headers, hdr.c_str());
525 return std::make_pair(
true, val);
527 return std::make_pair(
false,
"");
532 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
535 size_t size = evbuffer_get_length(buf);
542 const char* data = (
const char*)evbuffer_pullup(buf, size);
545 std::string rv(data, size);
546 evbuffer_drain(buf, size);
552 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
554 evhttp_add_header(headers, hdr.c_str(), value.c_str());
569 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
571 evbuffer_add(evb, strReply.data(), strReply.size());
574 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
577 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
578 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
580 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
582 bufferevent_enable(bev, EV_READ | EV_WRITE);
594 evhttp_connection* con = evhttp_request_get_connection(
req);
598 const char* address =
"";
600 evhttp_connection_get_peer(con, (
char**)&address, &port);
608 return evhttp_request_get_uri(
req);
613 switch (evhttp_request_get_command(
req)) {
617 case EVHTTP_REQ_POST:
620 case EVHTTP_REQ_HEAD:
640 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
641 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
642 for (; i != iend; ++i)
643 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
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.
void DisableCategory(LogFlags flag)
A combination of a network address (CNetAddr) and a (TCP) port.
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::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)
void operator()() override
std::unique_ptr< HTTPRequest > req
HTTPWorkItem(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)
Enqueue a work item.
std::deque< std::unique_ptr< WorkItem > > queue GUARDED_BY(cs)
void Run()
Thread function.
std::condition_variable cond GUARDED_BY(cs)
~WorkQueue()
Precondition: worker threads have all stopped (they have been joined).
bool running GUARDED_BY(cs)
void Interrupt()
Interrupt and exit loops.
WorkQueue(size_t _maxDepth)
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.
void StartHTTPServer()
Start HTTP server.
static struct event_base * eventBase
HTTP module state.
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.
bool InitHTTPServer()
Initialize HTTP server.
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.
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
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
static const int DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_THREADS
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
BCLog::Logger & LogInstance()
#define LogPrint(category,...)
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
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 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.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
@ HTTP_SERVICE_UNAVAILABLE
@ HTTP_INTERNAL_SERVER_ERROR
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...
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
HTTPRequestHandler handler
#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...
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
CClientUIInterface uiInterface