21 #include <sys/types.h> 26 #include <event2/thread.h> 27 #include <event2/buffer.h> 28 #include <event2/bufferevent.h> 29 #include <event2/util.h> 30 #include <event2/keyvalq_struct.h> 34 #ifdef EVENT__HAVE_NETINET_IN_H 35 #include <netinet/in.h> 36 #ifdef _XOPEN_SOURCE_EXTENDED 37 #include <arpa/inet.h> 42 static const size_t MAX_HEADERS_SIZE = 8192;
57 std::unique_ptr<HTTPRequest>
req;
67 template <
typename WorkItem>
73 std::condition_variable
cond;
74 std::deque<std::unique_ptr<WorkItem>>
queue;
86 std::lock_guard<std::mutex> lock(wq.
cs);
91 std::lock_guard<std::mutex> lock(wq.
cs);
112 std::unique_lock<std::mutex> lock(cs);
113 if (queue.size() >= maxDepth) {
116 queue.emplace_back(std::unique_ptr<WorkItem>(item));
125 std::unique_ptr<WorkItem> i;
127 std::unique_lock<std::mutex> lock(cs);
128 while (running && queue.empty())
132 i = std::move(queue.front());
141 std::unique_lock<std::mutex> lock(cs);
148 std::unique_lock<std::mutex> lock(cs);
149 while (numThreads > 0)
168 static struct event_base* eventBase = 0;
173 static std::vector<CSubNet> rpc_allow_subnets;
182 static bool ClientAllowed(
const CNetAddr& netaddr)
186 for(
const CSubNet& subnet : rpc_allow_subnets)
187 if (subnet.Match(netaddr))
193 static bool InitHTTPAllowList()
195 rpc_allow_subnets.clear();
200 rpc_allow_subnets.push_back(
CSubNet(localv4, 8));
201 rpc_allow_subnets.push_back(
CSubNet(localv6));
202 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
207 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),
211 rpc_allow_subnets.push_back(subnet);
213 std::string strAllowed;
214 for (
const CSubNet& subnet : rpc_allow_subnets)
215 strAllowed += subnet.ToString() +
" ";
242 static void http_request_cb(
struct evhttp_request*
req,
void* arg)
245 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
246 evhttp_connection* conn = evhttp_request_get_connection(
req);
248 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
250 bufferevent_disable(bev, EV_READ);
257 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
260 if (!ClientAllowed(hreq->GetPeer())) {
267 hreq->WriteReply(HTTP_BADMETHOD);
272 std::string strURI = hreq->GetURI();
274 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
275 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
276 for (; i != iend; ++i) {
279 match = (strURI == i->prefix);
281 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
283 path = strURI.substr(i->prefix.size());
290 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(std::move(hreq), path, i->handler));
292 if (workQueue->
Enqueue(item.get()))
295 LogPrintf(
"WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
296 item->req->WriteReply(HTTP_INTERNAL,
"Work queue depth exceeded");
299 hreq->WriteReply(HTTP_NOTFOUND);
304 static void http_reject_request_cb(
struct evhttp_request*
req,
void*)
307 evhttp_send_error(
req, HTTP_SERVUNAVAIL,
nullptr);
311 static bool ThreadHTTP(
struct event_base* base,
struct evhttp* http)
315 event_base_dispatch(base);
318 return event_base_got_break(base) == 0;
322 static bool HTTPBindAddresses(
struct evhttp* http)
325 std::vector<std::pair<std::string, uint16_t> > endpoints;
329 endpoints.push_back(std::make_pair(
"::1", defaultPort));
330 endpoints.push_back(std::make_pair(
"127.0.0.1", defaultPort));
332 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
335 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
336 int port = defaultPort;
339 endpoints.push_back(std::make_pair(host, port));
342 endpoints.push_back(std::make_pair(
"::", defaultPort));
343 endpoints.push_back(std::make_pair(
"0.0.0.0", defaultPort));
347 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
349 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
353 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
367 static void libevent_log_cb(
int severity,
const char *msg)
369 #ifndef EVENT_LOG_WARN 371 # define EVENT_LOG_WARN _EVENT_LOG_WARN 381 if (!InitHTTPAllowList())
386 "SSL mode for RPC (-rpcssl) is no longer supported.",
392 event_set_log_callback(&libevent_log_cb);
401 evthread_use_windows_threads();
403 evthread_use_pthreads();
410 struct evhttp* http = http_ctr.get();
412 LogPrintf(
"couldn't create evhttp. Exiting.\n");
416 evhttp_set_timeout(http,
gArgs.
GetArg(
"-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
417 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
418 evhttp_set_max_body_size(http, MAX_SIZE);
419 evhttp_set_gencb(http, http_request_cb,
nullptr);
421 if (!HTTPBindAddresses(http)) {
422 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
427 int workQueueDepth =
std::max((
long)
gArgs.
GetArg(
"-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
428 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
432 eventBase = base_ctr.release();
438 #if LIBEVENT_VERSION_NUMBER >= 0x02010100 440 event_enable_debug_logging(EVENT_DBG_ALL);
442 event_enable_debug_logging(EVENT_DBG_NONE);
458 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
459 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
463 for (
int i = 0; i < rpcThreads; i++) {
464 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
476 evhttp_del_accept_socket(
eventHTTP, socket);
479 evhttp_set_gencb(
eventHTTP, http_reject_request_cb,
nullptr);
502 if (
threadResult.valid() &&
threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
503 LogPrintf(
"HTTP event loop did not exit within allotted time, sending loopbreak\n");
504 event_base_loopbreak(eventBase);
513 event_base_free(eventBase);
524 static void httpevent_callback_fn(evutil_socket_t,
short,
void*
data)
529 if (self->deleteWhenTriggered)
534 deleteWhenTriggered(_deleteWhenTriggered),
handler(_handler), databuf(_databuf)
536 ev = event_new(base, -1, 0, httpevent_callback_fn,
this);
549 event_active(
ev, 0, 0);
555 startedChunkTransfer(false),
563 LogPrintf(
"%s: Unhandled request\n", __func__);
564 WriteReply(HTTP_INTERNAL,
"Unhandled request");
574 std::unique_lock<std::mutex> lock(
cs);
575 closeCv.wait_for(lock, std::chrono::milliseconds(500));
590 auto conn = evhttp_request_get_connection(
req);
604 evhttp_connection_set_closecb(conn, [](
struct evhttp_connection *conn,
void *
data) {
609 req->setConnClosed();
615 std::lock_guard<std::mutex> lock(
cs);
621 std::lock_guard<std::mutex> lock(
cs);
631 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
633 const char* val = evhttp_find_header(headers, hdr.c_str());
635 return std::make_pair(
true, val);
637 return std::make_pair(
false,
"");
642 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
645 size_t size = evbuffer_get_length(buf);
652 const char*
data = (
const char*)evbuffer_pullup(buf, size);
655 std::string rv(data, size);
656 evbuffer_drain(buf, size);
666 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
668 evhttp_add_header(headers, hdr.c_str(), value.c_str());
675 std::bind(evhttp_send_reply_end,
req));
696 std::bind(evhttp_send_reply_start,
req, status,
697 (
const char*) NULL));
705 if (chunk.size() > 0) {
706 auto databuf = evbuffer_new();
707 evbuffer_add(databuf, chunk.data(), chunk.size());
709 std::bind(evhttp_send_reply_chunk,
req, databuf));
723 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
725 evbuffer_add(evb, strReply.data(), strReply.size());
728 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
731 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
732 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
734 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
736 bufferevent_enable(bev, EV_READ | EV_WRITE);
748 evhttp_connection* con = evhttp_request_get_connection(
req);
754 evhttp_connection_get_peer(con, (
char**)&address, &port);
762 return evhttp_request_get_uri(
req);
767 switch (evhttp_request_get_command(
req)) {
771 case EVHTTP_REQ_POST:
774 case EVHTTP_REQ_HEAD:
788 LogPrint(
BCLog::HTTP,
"Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
794 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
795 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
796 for (; i != iend; ++i)
797 if (i->prefix == prefix && i->exactMatch == exactMatch)
801 LogPrint(
BCLog::HTTP,
"Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
808 if (!urlEncoded.empty()) {
809 char *decoded = evhttp_uridecode(urlEncoded.c_str(),
false,
nullptr);
811 res = std::string(decoded);
bool(* handler)(HTTPRequest *req, const std::string &strReq)
ThreadCounter(WorkQueue &w)
raii_event_base obtain_event_base()
#define function(a, b, c, d, k, s)
bool ReplySent()
Is reply sent?
void WaitExit()
Wait for worker threads to exit.
std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
bool StartHTTPServer()
Start HTTP server.
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
bool IsRPCRunning()
Query whether RPC is running.
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.
void Chunk(const std::string &chunk)
Start chunk transfer.
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
std::hash for asio::adress
std::vector< std::string > GetArgs(const std::string &strArg)
assert(len-trim+(2 *lenIndices)<=WIDTH)
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 ChunkEnd()
End chunk transfer.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
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.
void startDetectClientClose()
A combination of a network address (CNetAddr) and a (TCP) port.
struct evbuffer * databuf
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.
uint8_t const size_t const size
void trigger(struct timeval *tv)
Trigger the event.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
bool startedChunkTransfer
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
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
struct evm_uint160be address(struct evm_env *env)
CClientUIInterface uiInterface
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, struct evbuffer *_databuf, const std::function< void(void)> &handler)
Create a new event.
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
HTTPRequestHandler handler
std::condition_variable closeCv
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.