22#include <event2/buffer.h>
23#include <event2/bufferevent.h>
24#include <event2/keyvalq_struct.h>
25#include <event2/thread.h>
26#include <event2/util.h>
57 std::unique_ptr<HTTPRequest>
req;
73 std::condition_variable
cond;
74 std::deque<std::unique_ptr<WorkItem>>
queue;
91 queue.emplace_back(std::unique_ptr<WorkItem>(item));
99 std::unique_ptr<WorkItem> i;
108 i = std::move(
queue.front());
177 Untranslated(
"Invalid -rpcallowip subnet specification: "
178 "%s. Valid are a single IP (e.g. 1.2.3.4), a "
179 "network/netmask (e.g. 1.2.3.4/255.255.255.0) "
180 "or a network/CIDR (e.g. 1.2.3.4/24)."),
228 auto hreq = std::make_unique<HTTPRequest>(req);
233 "HTTP request from %s rejected: Client network is not allowed "
235 hreq->GetPeer().ToString());
243 "HTTP request from %s rejected: Unknown HTTP request method\n",
244 hreq->GetPeer().ToString());
252 hreq->GetPeer().ToString());
257 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
259 for (; i !=
iend; ++i) {
264 match = (
strURI.substr(0, i->prefix.size()) == i->prefix);
267 path =
strURI.substr(i->prefix.size());
274 std::unique_ptr<HTTPWorkItem> item(
281 LogPrintf(
"WARNING: request rejected because http work queue depth "
282 "exceeded, it can be increased with the -rpcworkqueue= "
285 "Work queue depth exceeded");
312 std::vector<std::pair<std::string, uint16_t>>
endpoints;
320 LogPrintf(
"WARNING: option -rpcallowip was specified without "
321 "-rpcbind; this doesn't usually make sense\n");
324 LogPrintf(
"WARNING: option -rpcbind was ignored because "
325 "-rpcallowip was not specified, refusing to allow "
326 "everyone to connect\n");
334 endpoints.push_back(std::make_pair(host, port));
339 for (std::vector<std::pair<std::string, uint16_t>>::iterator i =
345 http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
348 if (i->first.empty() ||
350 LogPrintf(
"WARNING: the RPC server is not safe to expose to "
351 "untrusted networks such as the public internet\n");
355 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first,
370#ifndef EVENT_LOG_WARN
372#define EVENT_LOG_WARN _EVENT_LOG_WARN
409 LogPrintf(
"couldn't create evhttp. Exiting.\n");
427 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
444#if LIBEVENT_VERSION_NUMBER >= 0x02010100
525 if (
self->deleteWhenTriggered) {
531 const std::function<
void()> &
_handler)
559std::pair<bool, std::string>
565 return std::make_pair(
true, val);
567 return std::make_pair(
false,
"");
590 std::string
rv(data, size);
596 const std::string &value) {
643 const char *address =
"";
680 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
682 for (; i !=
iend; ++i) {
683 if (i->prefix ==
prefix && i->exactMatch == exactMatch) {
689 "Unregistering HTTP handler for %s (exactmatch %d)\n",
prefix,
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 category)
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::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(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.
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
~WorkQueue()
Precondition: worker threads have all stopped (they have all been joined)
Mutex cs
Mutex protects entire object.
std::deque< std::unique_ptr< WorkItem > > queue
WorkQueue(size_t _maxDepth)
std::condition_variable cond
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 WorkQueue< HTTPClosure > * workQueue
Work queue for handling longer requests off the event loop thread.
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
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.
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
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 LogPrint(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.
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.
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
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 EXCLUSIVE_LOCKS_REQUIRED(...)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
CClientUIInterface uiInterface
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.