21 #include <sys/types.h> 26 #include <event2/thread.h> 27 #include <event2/buffer.h> 28 #include <event2/util.h> 29 #include <event2/keyvalq_struct.h> 33 #ifdef EVENT__HAVE_NETINET_IN_H 34 #include <netinet/in.h> 35 #ifdef _XOPEN_SOURCE_EXTENDED 36 #include <arpa/inet.h> 41 static const size_t MAX_HEADERS_SIZE = 8192;
56 std::unique_ptr<HTTPRequest>
req;
66 template <
typename WorkItem>
72 std::condition_variable
cond;
73 std::deque<std::unique_ptr<WorkItem>>
queue;
85 std::lock_guard<std::mutex> lock(wq.
cs);
90 std::lock_guard<std::mutex> lock(wq.
cs);
97 explicit WorkQueue(
size_t _maxDepth) : running(true),
111 std::unique_lock<std::mutex> lock(cs);
112 if (queue.size() >= maxDepth) {
115 queue.emplace_back(std::unique_ptr<WorkItem>(item));
124 std::unique_ptr<WorkItem> i;
126 std::unique_lock<std::mutex> lock(cs);
127 while (running && queue.empty())
131 i = std::move(queue.front());
140 std::unique_lock<std::mutex> lock(cs);
147 std::unique_lock<std::mutex> lock(cs);
148 while (numThreads > 0)
167 static struct event_base* eventBase =
nullptr;
172 static std::vector<CSubNet> rpc_allow_subnets;
181 static bool ClientAllowed(
const CNetAddr& netaddr)
185 for(
const CSubNet& subnet : rpc_allow_subnets)
186 if (subnet.Match(netaddr))
192 static bool InitHTTPAllowList()
194 rpc_allow_subnets.clear();
199 rpc_allow_subnets.push_back(
CSubNet(localv4, 8));
200 rpc_allow_subnets.push_back(
CSubNet(localv6));
201 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
206 strprintf(
"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),
210 rpc_allow_subnets.push_back(subnet);
212 std::string strAllowed;
213 for (
const CSubNet& subnet : rpc_allow_subnets)
214 strAllowed += subnet.ToString() +
" ";
241 static void http_request_cb(
struct evhttp_request*
req,
void* arg)
246 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
249 if (!ClientAllowed(hreq->GetPeer())) {
256 hreq->WriteReply(HTTP_BADMETHOD);
261 std::string strURI = hreq->GetURI();
263 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
264 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
265 for (; i != iend; ++i) {
268 match = (strURI == i->prefix);
270 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
272 path = strURI.substr(i->prefix.size());
279 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(std::move(hreq), path, i->handler));
281 if (workQueue->
Enqueue(item.get()))
284 LogPrintf(
"WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
285 item->req->WriteReply(HTTP_INTERNAL,
"Work queue depth exceeded");
288 hreq->WriteReply(HTTP_NOTFOUND);
293 static void http_reject_request_cb(
struct evhttp_request*
req,
void*)
296 evhttp_send_error(
req, HTTP_SERVUNAVAIL,
nullptr);
300 static bool ThreadHTTP(
struct event_base* base,
struct evhttp* http)
304 event_base_dispatch(base);
307 return event_base_got_break(base) == 0;
311 static bool HTTPBindAddresses(
struct evhttp* http)
314 std::vector<std::pair<std::string, uint16_t> > endpoints;
318 endpoints.push_back(std::make_pair(
"::1", defaultPort));
319 endpoints.push_back(std::make_pair(
"127.0.0.1", defaultPort));
321 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
324 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
325 int port = defaultPort;
328 endpoints.push_back(std::make_pair(host, port));
331 endpoints.push_back(std::make_pair(
"::", defaultPort));
332 endpoints.push_back(std::make_pair(
"0.0.0.0", defaultPort));
336 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
338 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
342 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
356 static void libevent_log_cb(
int severity,
const char *msg)
358 #ifndef EVENT_LOG_WARN 360 # define EVENT_LOG_WARN _EVENT_LOG_WARN 370 if (!InitHTTPAllowList())
375 "SSL mode for RPC (-rpcssl) is no longer supported.",
381 event_set_log_callback(&libevent_log_cb);
390 evthread_use_windows_threads();
392 evthread_use_pthreads();
399 struct evhttp* http = http_ctr.get();
401 LogPrintf(
"couldn't create evhttp. Exiting.\n");
405 evhttp_set_timeout(http,
gArgs.
GetArg(
"-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
406 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
407 evhttp_set_max_body_size(http, MAX_SIZE);
408 evhttp_set_gencb(http, http_request_cb,
nullptr);
410 if (!HTTPBindAddresses(http)) {
411 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
416 int workQueueDepth = std::max((
long)
gArgs.
GetArg(
"-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1
L);
417 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
421 eventBase = base_ctr.release();
427 #if LIBEVENT_VERSION_NUMBER >= 0x02010100 429 event_enable_debug_logging(EVENT_DBG_ALL);
431 event_enable_debug_logging(EVENT_DBG_NONE);
446 int rpcThreads = std::max((
long)
gArgs.
GetArg(
"-rpcthreads", DEFAULT_HTTP_THREADS), 1
L);
447 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
448 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
452 for (
int i = 0; i < rpcThreads; i++) {
453 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
465 evhttp_del_accept_socket(
eventHTTP, socket);
468 evhttp_set_gencb(
eventHTTP, http_reject_request_cb,
nullptr);
486 event_base_loopexit(eventBase,
nullptr);
493 if (
threadResult.valid() &&
threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
494 LogPrintf(
"HTTP event loop did not exit within allotted time, sending loopbreak\n");
495 event_base_loopbreak(eventBase);
504 event_base_free(eventBase);
515 static void httpevent_callback_fn(evutil_socket_t,
short,
void* data)
520 if (self->deleteWhenTriggered)
524 HTTPEvent::HTTPEvent(
struct event_base* base,
bool _deleteWhenTriggered,
const std::function<
void(
void)>& _handler):
525 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler)
527 ev = event_new(base, -1, 0, httpevent_callback_fn,
this);
537 event_active(
ev, 0, 0);
549 LogPrintf(
"%s: Unhandled request\n", __func__);
550 WriteReply(HTTP_INTERNAL,
"Unhandled request");
557 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
559 const char* val = evhttp_find_header(headers, hdr.c_str());
561 return std::make_pair(
true, val);
563 return std::make_pair(
false,
"");
568 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
571 size_t size = evbuffer_get_length(buf);
578 const char* data = (
const char*)evbuffer_pullup(buf, size);
581 std::string rv(data, size);
582 evbuffer_drain(buf, size);
588 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
590 evhttp_add_header(headers, hdr.c_str(), value.c_str());
602 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
604 evbuffer_add(evb, strReply.data(), strReply.size());
606 std::bind(evhttp_send_reply,
req, nStatus, (
const char*)
nullptr, (
struct evbuffer *)
nullptr));
607 ev->trigger(
nullptr);
614 evhttp_connection* con = evhttp_request_get_connection(
req);
618 const char* address =
"";
620 evhttp_connection_get_peer(con, (
char**)&address, &port);
628 return evhttp_request_get_uri(
req);
633 switch (evhttp_request_get_command(
req)) {
637 case EVHTTP_REQ_POST:
640 case EVHTTP_REQ_HEAD:
654 LogPrint(
BCLog::HTTP,
"Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
660 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
661 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
662 for (; i != iend; ++i)
663 if (i->prefix == prefix && i->exactMatch == exactMatch)
667 LogPrint(
BCLog::HTTP,
"Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
674 if (!urlEncoded.empty()) {
675 char *decoded = evhttp_uridecode(urlEncoded.c_str(),
false,
nullptr);
677 res = std::string(decoded);
bool(* handler)(HTTPRequest *req, const std::string &strReq)
ThreadCounter(WorkQueue &w)
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
raii_event_base obtain_event_base()
void WaitExit()
Wait for worker threads to exit.
std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
bool StartHTTPServer()
Start HTTP server.
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
HTTPRequest(struct evhttp_request *req)
raii_evhttp obtain_evhttp(struct event_base *base)
std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
std::pair< bool, std::string > GetHeader(const std::string &hdr)
Get the request header specified by hdr, or an empty string.
CService LookupNumeric(const char *pszName, int portDefault)
std::string urlDecode(const std::string &urlEncoded)
std::string GetURI()
Get requested URI.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
std::atomic< uint32_t > logCategories
struct evhttp_request * req
std::deque< std::unique_ptr< WorkItem > > queue
void InterruptHTTPServer()
Interrupt HTTP server threads.
RequestMethod GetRequestMethod()
Get request method.
void RenameThread(const char *name)
bool Enqueue(WorkItem *item)
Enqueue a work item.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
#define L(x0, x1, x2, x3, x4, x5, x6, x7)
void Run()
Thread function.
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
bool InitHTTPServer()
Initialize HTTP server.
void StopHTTPServer()
Stop HTTP server.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
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.
std::function< void(void)> handler
std::future< bool > threadResult
std::mutex cs
Mutex protects entire object.
CService GetPeer()
Get CService (address:ip) for the origin of the http request.
struct event_base * EventBase()
Return evhttp event base.
bool LookupSubNet(const char *pszName, CSubNet &ret)
#define LogPrint(category,...)
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Simple work queue for distributing work over multiple threads.
RAII object to keep track of number of running worker threads.
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
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.
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void(void)> &handler)
Create a new event.
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
void operator()() override
std::string ReadBody()
Read request body.
WorkQueue(size_t _maxDepth)
std::unique_ptr< HTTPRequest > req
CClientUIInterface uiInterface
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
HTTPRequestHandler handler
struct evhttp * eventHTTP
HTTP server.
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
~WorkQueue()
Precondition: worker threads have all stopped (call WaitExit)
void Interrupt()
Interrupt and exit loops.