 |
Bitcoin Core
22.99.0
P2P Digital Currency
|
Go to the documentation of this file.
5 #if defined(HAVE_CONFIG_H)
30 #include <sys/types.h>
33 #include <event2/thread.h>
34 #include <event2/buffer.h>
35 #include <event2/bufferevent.h>
36 #include <event2/util.h>
37 #include <event2/keyvalq_struct.h>
57 std::unique_ptr<HTTPRequest>
req;
67 template <
typename WorkItem>
73 std::deque<std::unique_ptr<WorkItem>> queue
GUARDED_BY(
cs);
78 explicit WorkQueue(
size_t _maxDepth) : running(true),
91 if (!running || queue.size() >=
maxDepth) {
94 queue.emplace_back(std::unique_ptr<WorkItem>(item));
102 std::unique_ptr<WorkItem> i;
105 while (running && queue.empty())
107 if (!running && queue.empty())
109 i = std::move(queue.front());
137 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();
247 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
248 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
249 for (; i != iend; ++i) {
252 match = (strURI == i->prefix);
254 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
256 path = strURI.substr(i->prefix.size());
263 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(std::move(hreq), path, i->handler));
268 LogPrintf(
"WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
280 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
289 event_base_dispatch(base);
292 return event_base_got_break(base) == 0;
299 std::vector<std::pair<std::string, uint16_t>> endpoints;
303 endpoints.push_back(std::make_pair(
"::1", http_port));
304 endpoints.push_back(std::make_pair(
"127.0.0.1", http_port));
306 LogPrintf(
"WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
309 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
312 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
313 uint16_t port{http_port};
316 endpoints.push_back(std::make_pair(host, port));
321 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
323 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
327 LogPrintf(
"WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
331 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
348 if (severity >= EVENT_LOG_WARN)
369 evthread_use_windows_threads();
371 evthread_use_pthreads();
378 struct evhttp* http = http_ctr.get();
380 LogPrintf(
"couldn't create evhttp. Exiting.\n");
386 evhttp_set_max_body_size(http,
MAX_SIZE);
390 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
396 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
398 g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
406 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
408 event_enable_debug_logging(EVENT_DBG_ALL);
410 event_enable_debug_logging(EVENT_DBG_NONE);
426 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
429 for (
int i = 0; i < rpcThreads; i++) {
459 evhttp_del_accept_socket(
eventHTTP, socket);
488 if (self->deleteWhenTriggered)
492 HTTPEvent::HTTPEvent(
struct event_base* base,
bool _deleteWhenTriggered,
const std::function<
void()>& _handler):
493 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler)
505 event_active(
ev, 0, 0);
517 LogPrintf(
"%s: Unhandled request\n", __func__);
525 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
527 const char* val = evhttp_find_header(headers, hdr.c_str());
529 return std::make_pair(
true, val);
531 return std::make_pair(
false,
"");
536 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
539 size_t size = evbuffer_get_length(buf);
546 const char* data = (
const char*)evbuffer_pullup(buf, size);
549 std::string rv(data, size);
550 evbuffer_drain(buf, size);
556 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
558 evhttp_add_header(headers, hdr.c_str(), value.c_str());
573 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
575 evbuffer_add(evb, strReply.data(), strReply.size());
578 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
581 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
582 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
584 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
586 bufferevent_enable(bev, EV_READ | EV_WRITE);
598 evhttp_connection* con = evhttp_request_get_connection(
req);
602 const char* address =
"";
605 #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
606 evhttp_connection_get_peer(con, &address, &port);
608 evhttp_connection_get_peer(con, (
char**)&address, &port);
609 #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
618 return evhttp_request_get_uri(
req);
623 switch (evhttp_request_get_command(
req)) {
627 case EVHTTP_REQ_POST:
630 case EVHTTP_REQ_HEAD:
650 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
651 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
652 for (; i != iend; ++i)
653 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
A combination of a network address (CNetAddr) and a (TCP) port.
RequestMethod GetRequestMethod() const
Get request method.
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.
@ HTTP_SERVICE_UNAVAILABLE
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
static const int DEFAULT_HTTP_WORKQUEUE
CClientUIInterface uiInterface
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
struct event_base * EventBase()
Return evhttp event base.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
bool Enqueue(WorkItem *item)
Enqueue a work item.
std::condition_variable cond GUARDED_BY(cs)
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
void StartHTTPServer()
Start HTTP server.
std::string GetURI() const
Get requested URI.
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
std::unique_ptr< HTTPRequest > req
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
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.
Simple work queue for distributing work over multiple threads.
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...
static struct evhttp * eventHTTP
HTTP server.
void SplitHostPort(std::string in, uint16_t &portOut, std::string &hostOut)
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
void operator()() override
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
static struct event_base * eventBase
HTTP module state.
static std::vector< std::thread > g_thread_http_workers
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
std::string ReadBody()
Read request body.
HTTPRequest(struct evhttp_request *req, bool replySent=false)
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
void Run()
Thread function.
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
#define LogPrint(category,...)
struct evhttp_request * req
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
static std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
raii_event_base obtain_event_base()
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
void trigger(struct timeval *tv)
Trigger the event.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
void InterruptHTTPServer()
Interrupt HTTP server threads.
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
BCLog::Logger & LogInstance()
WorkQueue(size_t _maxDepth)
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
void Interrupt()
Interrupt and exit loops.
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 void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
void DisableCategory(LogFlags flag)
void StopHTTPServer()
Stop HTTP server.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
static std::thread g_thread_http
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
static const int DEFAULT_HTTP_THREADS
~WorkQueue()
Precondition: worker threads have all stopped (they have been joined).
#define WAIT_LOCK(cs, name)
HTTPRequestHandler handler
bool InitHTTPServer()
Initialize HTTP server.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
std::function< void()> handler
raii_evhttp obtain_evhttp(struct event_base *base)
@ HTTP_INTERNAL_SERVER_ERROR