23#include <condition_variable>
32#include <unordered_map>
38#include <event2/buffer.h>
39#include <event2/bufferevent.h>
40#include <event2/http.h>
41#include <event2/http_struct.h>
42#include <event2/keyvalq_struct.h>
43#include <event2/thread.h>
44#include <event2/util.h>
89 mutable std::condition_variable
m_cv;
96 if (m_tracker.empty())
m_cv.notify_all();
110 auto it{m_tracker.find(conn)};
111 if (it != m_tracker.end() && it->second > 0) {
119 auto it{m_tracker.find(
Assert(conn))};
155 if (!subnet.IsValid()) {
157 Untranslated(
strprintf(
"Invalid -rpcallowip subnet specification: %s. Valid values are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0.",
strAllow)),
218 LogDebug(
BCLog::HTTP,
"HTTP request from %s rejected: Client network is not allowed RPC access\n",
219 hreq->GetPeer().ToStringAddrPort());
227 hreq->GetPeer().ToStringAddrPort());
239 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
241 for (; i !=
iend; ++i) {
248 path =
strURI.substr(i->prefix.size());
256 LogWarning(
"Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
261 auto item = [req =
hreq,
in_path = std::move(path), fn = i->handler]() {
266 }
catch (
const std::exception&
e) {
267 LogWarning(
"Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(),
e.what());
270 LogWarning(
"Unknown error while processing request for '%s'", req->GetURI());
274 req->WriteHeader(
"Connection",
"close");
312 std::vector<std::pair<std::string, uint16_t>>
endpoints;
323 LogWarning(
"Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
326 LogWarning(
"Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
341 for (std::vector<std::pair<std::string, uint16_t> >::iterator i =
endpoints.begin(); i !=
endpoints.end(); ++i) {
342 LogInfo(
"Binding RPC on address %s port %i", i->first, i->second);
345 const std::optional<CNetAddr> addr{
LookupHost(i->first,
false)};
346 if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
347 LogWarning(
"The RPC server is not safe to expose to untrusted networks such as the public internet");
353 LogInfo(
"WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
357 LogWarning(
"Binding RPC on address %s port %i failed.", i->first, i->second);
404 LogError(
"Couldn't create evhttp. Exiting.");
414 LogError(
"Unable to bind any endpoint for RPC server");
483 },
nullptr,
nullptr);
504 if (
self->deleteWhenTriggered)
546 return std::make_pair(
true, val);
548 return std::make_pair(
false,
"");
566 std::string
rv(data, size);
619 const char* address =
"";
622#ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
665 throw std::runtime_error(
"URI parsing failed, it likely contained RFC 3986 invalid characters");
668 std::optional<std::string> result;
675 for (
struct evkeyval* param{
params_q.tqh_first}; param !=
nullptr; param = param->next.tqe_next) {
676 if (param->key == key) {
677 result = param->value;
698 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
700 for (; i !=
iend; ++i)
701 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
event_set_log_callback & libevent_log_cb
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
A combination of a network address (CNetAddr) and a (TCP) port.
Different type to mark Mutex at global scope.
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, std::string_view reply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
HTTPRequest(struct evhttp_request *req, const util::SignalInterrupt &interrupt, bool replySent=false)
struct evhttp_request * req
RequestMethod GetRequestMethod() const
Get request method.
const util::SignalInterrupt & m_interrupt
std::string ReadBody()
Read request body.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
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)
Fixed-size thread pool for running arbitrary tasks concurrently.
void Start(int num_workers) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start worker threads.
void Stop() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop all worker threads and wait for them to exit.
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Stop accepting new tasks and begin asynchronous shutdown.
size_t WorkQueueSize() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
util::Expected< std::future< std::invoke_result_t< F > >, SubmitError > Submit(F &&fn) noexcept EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Enqueues a new task for asynchronous execution.
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
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 ThreadPool g_threadpool_http("http")
Http thread pool - future: encapsulate in HttpContext.
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
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 HTTPRequestTracker g_requests
Track active requests.
bool InitHTTPServer(const util::SignalInterrupt &interrupt)
Initialize HTTP server.
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
static int g_max_queue_depth
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 void ThreadHTTP(struct event_base *base)
Event dispatcher thread.
static GlobalMutex g_httppathhandlers_mutex
Handlers for (sub)paths.
static const int DEFAULT_HTTP_SERVER_TIMEOUT
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...
static const int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
static const int DEFAULT_HTTP_THREADS
The default value for -rpcthreads.
std::function< bool(HTTPRequest *req, const std::string &) HTTPRequestHandler)
Handler for requests to a certain HTTP path.
CClientUIInterface uiInterface
#define LogDebug(category,...)
BCLog::Logger & LogInstance()
is a home for simple string functions returning descriptive messages that are used in RPC and GUI int...
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
CSubNet LookupSubNet(const std::string &subnet_str)
Parse and resolve a specified subnet string into the appropriate internal representation.
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.
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
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)(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...
@ 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.
constexpr std::string_view SubmitErrorString(const ThreadPool::SubmitError err) noexcept
#define EXCLUSIVE_LOCKS_REQUIRED(...)
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
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.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.