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> 30 #ifdef EVENT__HAVE_NETINET_IN_H 31 #include <netinet/in.h> 32 #ifdef _XOPEN_SOURCE_EXTENDED 33 #include <arpa/inet.h> 38 #include <sys/types.h> 64 std::unique_ptr<HTTPRequest>
req;
80 std::condition_variable
cond;
81 std::deque<std::unique_ptr<WorkItem>>
queue;
86 explicit WorkQueue(
size_t _maxDepth) : running(true), maxDepth(_maxDepth) {}
95 if (queue.size() >= maxDepth) {
98 queue.emplace_back(std::unique_ptr<WorkItem>(item));
106 std::unique_ptr<WorkItem> i;
109 while (running && queue.empty()) {
115 i = std::move(queue.front());
133 :
prefix(_prefix), exactMatch(_exactMatch),
handler(_handler) {}
141 static struct event_base *
eventBase =
nullptr;
160 if (subnet.Match(netaddr)) {
178 for (
const std::string &strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
184 Untranslated(
"Invalid -rpcallowip subnet specification: " 185 "%s. Valid are a single IP (e.g. 1.2.3.4), a " 186 "network/netmask (e.g. 1.2.3.4/255.255.255.0) " 187 "or a network/CIDR (e.g. 1.2.3.4/24)."),
194 std::string strAllowed;
196 strAllowed += subnet.ToString() +
" ";
225 if (event_get_version_number() >= 0x02010600 &&
226 event_get_version_number() < 0x02020001) {
227 evhttp_connection *conn = evhttp_request_get_connection(req);
229 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
231 bufferevent_disable(bev, EV_READ);
235 auto hreq = std::make_unique<HTTPRequest>(
req);
240 "HTTP request from %s rejected: Client network is not allowed " 242 hreq->GetPeer().ToString());
250 "HTTP request from %s rejected: Unknown HTTP request method\n",
251 hreq->GetPeer().ToString());
259 hreq->GetPeer().ToString());
262 std::string strURI = hreq->GetURI();
264 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
265 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
266 for (; i != iend; ++i) {
269 match = (strURI == i->prefix);
271 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
274 path = strURI.substr(i->prefix.size());
281 std::unique_ptr<HTTPWorkItem> item(
282 new HTTPWorkItem(config, std::move(hreq), path, i->handler));
284 if (workQueue->
Enqueue(item.get())) {
288 LogPrintf(
"WARNING: request rejected because http work queue depth " 289 "exceeded, it can be increased with the -rpcworkqueue= " 292 "Work queue depth exceeded");
302 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
309 event_base_dispatch(base);
312 return event_base_got_break(base) == 0;
318 std::vector<std::pair<std::string, uint16_t>> endpoints;
323 endpoints.push_back(std::make_pair(
"::1", http_port));
324 endpoints.push_back(std::make_pair(
"127.0.0.1", http_port));
326 LogPrintf(
"WARNING: option -rpcallowip was specified without " 327 "-rpcbind; this doesn't usually make sense\n");
330 LogPrintf(
"WARNING: option -rpcbind was ignored because " 331 "-rpcallowip was not specified, refusing to allow " 332 "everyone to connect\n");
336 for (
const std::string &strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
337 int port = http_port;
340 endpoints.push_back(std::make_pair(host, port));
345 for (std::vector<std::pair<std::string, uint16_t>>::iterator i =
347 i != endpoints.end(); ++i) {
350 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(
351 http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
354 if (i->first.empty() ||
356 LogPrintf(
"WARNING: the RPC server is not safe to expose to " 357 "untrusted networks such as the public internet\n");
361 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first,
376 #ifndef EVENT_LOG_WARN 378 #define EVENT_LOG_WARN _EVENT_LOG_WARN 404 evthread_use_windows_threads();
406 evthread_use_pthreads();
413 struct evhttp *http = http_ctr.get();
415 LogPrintf(
"couldn't create evhttp. Exiting.\n");
428 evhttp_set_allowed_methods(
429 http, EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD |
430 EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
433 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
438 int workQueueDepth = std::max(
440 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
450 #if LIBEVENT_VERSION_NUMBER >= 0x02010100 452 event_enable_debug_logging(EVENT_DBG_ALL);
454 event_enable_debug_logging(EVENT_DBG_NONE);
470 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
473 for (
int i = 0; i < rpcThreads; i++) {
496 g_thread_http_workers.clear();
503 evhttp_del_accept_socket(
eventHTTP, socket);
505 boundSockets.clear();
529 if (self->deleteWhenTriggered) {
535 const std::function<
void()> &_handler)
536 : deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler) {
546 event_active(
ev, 0, 0);
553 : req(_req), replySent(_replySent) {}
557 LogPrintf(
"%s: Unhandled request\n", __func__);
563 std::pair<bool, std::string>
565 const struct evkeyvalq *headers = evhttp_request_get_input_headers(
req);
567 const char *val = evhttp_find_header(headers, hdr.c_str());
569 return std::make_pair(
true, val);
571 return std::make_pair(
false,
"");
576 struct evbuffer *buf = evhttp_request_get_input_buffer(
req);
580 size_t size = evbuffer_get_length(buf);
588 const char *data = (
const char *)evbuffer_pullup(buf, size);
594 std::string rv(data, size);
595 evbuffer_drain(buf, size);
600 const std::string &value) {
601 struct evkeyvalq *headers = evhttp_request_get_output_headers(
req);
603 evhttp_add_header(headers, hdr.c_str(), value.c_str());
617 struct evbuffer *evb = evhttp_request_get_output_buffer(
req);
619 evbuffer_add(evb, strReply.data(), strReply.size());
622 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
625 if (event_get_version_number() >= 0x02010600 &&
626 event_get_version_number() < 0x02020001) {
627 evhttp_connection *conn = evhttp_request_get_connection(req_copy);
629 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
631 bufferevent_enable(bev, EV_READ | EV_WRITE);
643 evhttp_connection *con = evhttp_request_get_connection(
req);
647 const char *address =
"";
649 evhttp_connection_get_peer(con, (
char **)&address, &port);
656 return evhttp_request_get_uri(
req);
660 switch (evhttp_request_get_command(
req)) {
663 case EVHTTP_REQ_POST:
665 case EVHTTP_REQ_HEAD:
669 case EVHTTP_REQ_OPTIONS:
684 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
685 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
686 for (; i != iend; ++i) {
687 if (i->prefix == prefix && i->exactMatch == exactMatch) {
693 "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix,
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
raii_event_base obtain_event_base()
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
BCLog::Logger & LogInstance()
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
#define LogPrint(category,...)
static const int DEFAULT_HTTP_SERVER_TIMEOUT
raii_evhttp obtain_evhttp(struct event_base *base)
static const int DEFAULT_HTTP_WORKQUEUE
static std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
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...
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
static void LogPrintf(const char *fmt, const Args &... args)
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
struct evhttp_request * req
std::deque< std::unique_ptr< WorkItem > > queue
static std::thread threadHTTP
void DisableCategory(LogFlags category)
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
void InterruptHTTPServer()
Interrupt HTTP server threads.
bool Enqueue(WorkItem *item)
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.
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
Parse and resolve a specified subnet string into the appropriate internal representation.
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Mutex cs
Mutex protects entire object.
void Run()
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.
virtual uint64_t GetMaxBlockSize() const =0
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.
A combination of a network address (CNetAddr) and a (TCP) port.
std::condition_variable cond
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
#define WAIT_LOCK(cs, name)
HTTPWorkItem(Config &_config, std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
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.
std::function< bool(Config &config, HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
bool(* handler)(Config &config, const util::Ref &context, HTTPRequest *req, const std::string &strReq)
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Resolve a host string to its corresponding network addresses.
Simple work queue for distributing work over multiple threads.
static WorkQueue< HTTPClosure > * workQueue
Work queue for handling longer requests off the event loop thread.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
void trigger(struct timeval *tv)
Trigger the event.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string 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 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.
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
CClientUIInterface uiInterface
static const size_t MIN_SUPPORTED_BODY_SIZE
Maximum HTTP post body size.
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
bool InitHTTPServer(Config &config)
Initialize HTTP server.
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.
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
static struct event_base * eventBase
HTTP module state.
~WorkQueue()
Precondition: worker threads have all stopped (they have all been joined)
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
void Interrupt()
Interrupt and exit loops.