22 #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;
88 while (!
queue.empty()) {
96 std::unique_lock<std::mutex> lock(
cs);
100 queue.push_back(item);
108 WorkItem* i =
nullptr;
110 std::unique_lock<std::mutex> lock(
cs);
125 std::unique_lock<std::mutex> lock(
cs);
146 static struct event_base* eventBase = 0;
150 static std::vector<CSubNet> rpc_allow_subnets;
158 static bool ClientAllowed(
const CNetAddr& netaddr)
162 for (
const CSubNet& subnet : rpc_allow_subnets)
163 if (subnet.
Match(netaddr))
169 static bool InitHTTPAllowList()
171 rpc_allow_subnets.clear();
176 rpc_allow_subnets.emplace_back(localv4, 8);
177 rpc_allow_subnets.emplace_back(localv6);
178 for (
const std::string& strAllow :
gArgs.
GetArgs(
"-rpcallowip")) {
183 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),
187 rpc_allow_subnets.push_back(subnet);
189 std::string strAllowed;
190 for (
const CSubNet& subnet : rpc_allow_subnets)
191 strAllowed += subnet.
ToString() +
" ";
218 static void http_request_cb(
struct evhttp_request* req,
void* arg)
221 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
222 evhttp_connection* conn = evhttp_request_get_connection(req);
224 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
226 bufferevent_disable(bev, EV_READ);
230 std::unique_ptr<HTTPRequest> hreq(
new HTTPRequest(req));
233 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
236 if (!ClientAllowed(hreq->GetPeer())) {
243 hreq->WriteReply(HTTP_BADMETHOD);
248 std::string strURI = hreq->GetURI();
250 std::vector<HTTPPathHandler>::const_iterator i =
pathHandlers.begin();
251 std::vector<HTTPPathHandler>::const_iterator iend =
pathHandlers.end();
252 for (; i != iend; ++i) {
255 match = (strURI == i->prefix);
257 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
259 path = strURI.substr(i->prefix.size());
266 std::unique_ptr<HTTPWorkItem> item(
new HTTPWorkItem(hreq.release(), path, i->handler));
268 if (workQueue->Enqueue(item.get()))
271 item->req->WriteReply(HTTP_INTERNAL,
"Work queue depth exceeded");
273 hreq->WriteReply(HTTP_NOTFOUND);
278 static void http_reject_request_cb(
struct evhttp_request* req,
void*)
281 evhttp_send_error(req, HTTP_SERVUNAVAIL,
nullptr);
284 static bool ThreadHTTP(
struct event_base* base,
struct evhttp* http)
288 event_base_dispatch(base);
291 return event_base_got_break(base) == 0;
295 static bool HTTPBindAddresses(
struct evhttp* http)
298 std::vector<std::pair<std::string, uint16_t> > endpoints;
302 endpoints.emplace_back(
"::1", defaultPort);
303 endpoints.emplace_back(
"127.0.0.1", defaultPort);
305 LogPrintf(
"WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
308 LogPrintf(
"WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
311 for (
const std::string& strRPCBind :
gArgs.
GetArgs(
"-rpcbind")) {
312 int port = defaultPort;
315 endpoints.emplace_back(host, port);
320 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
322 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ?
nullptr : i->first.c_str(), i->second);
326 LogPrintf(
"WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
330 LogPrintf(
"Binding RPC on address %s port %i failed.\n", i->first, i->second);
344 static void libevent_log_cb(
int severity,
const char *msg)
346 #ifndef EVENT_LOG_WARN
348 # define EVENT_LOG_WARN _EVENT_LOG_WARN
351 LogPrintf(
"libevent: %s\n", msg);
358 if (!InitHTTPAllowList())
363 "SSL mode for RPC (-rpcssl) is no longer supported.",
369 event_set_log_callback(&libevent_log_cb);
378 evthread_use_windows_threads();
380 evthread_use_pthreads();
387 struct evhttp* http = http_ctr.get();
389 LogPrintf(
"couldn't create evhttp. Exiting.\n");
393 evhttp_set_timeout(http,
gArgs.
GetArg(
"-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
394 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
395 evhttp_set_max_body_size(http, MAX_SIZE);
396 evhttp_set_gencb(http, http_request_cb,
nullptr);
398 if (!HTTPBindAddresses(http)) {
399 LogPrintf(
"Unable to bind any endpoint for RPC server\n");
404 int workQueueDepth = std::max((
long)
gArgs.
GetArg(
"-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
405 LogPrintf(
"HTTP: creating work queue of depth %d\n", workQueueDepth);
409 eventBase = base_ctr.release();
415 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
417 event_enable_debug_logging(EVENT_DBG_ALL);
419 event_enable_debug_logging(EVENT_DBG_NONE);
429 static std::vector<std::thread> g_thread_http_workers;
434 int rpcThreads = std::max((
long)
gArgs.
GetArg(
"-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
435 LogPrintf(
"HTTP: starting %d worker threads\n", rpcThreads);
438 for (
int i = 0; i < rpcThreads; i++) {
439 g_thread_http_workers.emplace_back(HTTPWorkQueueRun, workQueue);
449 evhttp_set_gencb(
eventHTTP, http_reject_request_cb,
nullptr);
452 workQueue->Interrupt();
461 for (
auto& thread : g_thread_http_workers) {
463 if (thread.joinable()) {
467 g_thread_http_workers.clear();
475 evhttp_del_accept_socket(
eventHTTP, socket);
491 event_base_free(eventBase);
506 static void httpevent_callback_fn(evutil_socket_t,
short,
void* data)
511 if (self->deleteWhenTriggered)
518 ev = event_new(base, -1, 0, httpevent_callback_fn,
this);
528 event_active(
ev, 0, 0);
540 LogPrintf(
"%s: Unhandled request\n", __func__);
541 WriteReply(HTTP_INTERNAL,
"Unhandled request");
548 const struct evkeyvalq* headers = evhttp_request_get_input_headers(
req);
550 const char* val = evhttp_find_header(headers, hdr.c_str());
552 return std::make_pair(
true, val);
554 return std::make_pair(
false,
"");
559 struct evbuffer* buf = evhttp_request_get_input_buffer(
req);
562 size_t size = evbuffer_get_length(buf);
569 const char* data = (
const char*)evbuffer_pullup(buf, size);
572 std::string rv(data, size);
573 evbuffer_drain(buf, size);
579 struct evkeyvalq* headers = evhttp_request_get_output_headers(
req);
581 evhttp_add_header(headers, hdr.c_str(), value.c_str());
596 struct evbuffer* evb = evhttp_request_get_output_buffer(
req);
598 evbuffer_add(evb, strReply.data(), strReply.size());
601 evhttp_send_reply(req_copy, nStatus,
nullptr,
nullptr);
604 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
605 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
607 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
609 bufferevent_enable(bev, EV_READ | EV_WRITE);
621 evhttp_connection* con = evhttp_request_get_connection(
req);
625 const char* address =
"";
627 evhttp_connection_get_peer(con, (
char**)&address, &port);
635 return evhttp_request_get_uri(
req);
640 switch (evhttp_request_get_command(
req)) {
644 case EVHTTP_REQ_POST:
647 case EVHTTP_REQ_HEAD:
667 std::vector<HTTPPathHandler>::iterator i =
pathHandlers.begin();
668 std::vector<HTTPPathHandler>::iterator iend =
pathHandlers.end();
669 for (; i != iend; ++i)
670 if (i->prefix ==
prefix && i->exactMatch == exactMatch)
681 if (!urlEncoded.empty()) {
682 char *decoded = evhttp_uridecode(urlEncoded.c_str(),
false,
nullptr);
684 res = std::string(decoded);
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.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
bool WillLogCategory(LogFlags category) const
void DisableCategory(LogFlags flag)
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
A combination of a network address (CNetAddr) and a (TCP) port.
std::string ToString() const
bool Match(const CNetAddr &addr) const
std::function< void(void)> handler
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void(void)> &handler)
Create a new event.
void trigger(struct timeval *tv)
Trigger the event.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
std::string GetURI()
Get requested URI.
CService GetPeer()
Get CService (address:ip) for the origin of the http request.
std::pair< bool, std::string > GetHeader(const std::string &hdr)
Get the request header specified by hdr, or an empty string.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
struct evhttp_request * req
HTTPRequest(struct evhttp_request *req)
std::string ReadBody()
Read request body.
RequestMethod GetRequestMethod()
Get request method.
std::unique_ptr< HTTPRequest > req
HTTPWorkItem(HTTPRequest *req, const std::string &path, const HTTPRequestHandler &func)
Simple work queue for distributing work over multiple threads.
bool Enqueue(WorkItem *item)
Enqueue a work item.
std::deque< WorkItem * > queue
void Run()
Thread function.
std::mutex cs
Mutex protects entire object.
~WorkQueue()
Precondition: worker threads have all stopped (they have been joined).
void Interrupt()
Interrupt and exit loops.
WorkQueue(size_t _maxDepth)
std::condition_variable cond
raii_evhttp obtain_evhttp(struct event_base *base)
raii_event_base obtain_event_base()
CClientUIInterface uiInterface
struct evhttp * eventHTTP
HTTP server.
void InterruptHTTPServer()
Interrupt HTTP server threads.
std::vector< evhttp_bound_socket * > boundSockets
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.
struct event_base * EventBase()
Return evhttp event base.
std::string urlDecode(const std::string &urlEncoded)
bool InitHTTPServer()
Initialize HTTP server.
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
bool StartHTTPServer()
Start HTTP server.
void StopHTTPServer()
Stop HTTP server.
std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
std::function< void(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
#define LogPrint(category,...)
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
CService LookupNumeric(const std::string &name, int portDefault)
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
bool(* handler)(HTTPRequest *req, const std::string &strReq)
HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler)
HTTPRequestHandler handler
void MilliSleep(int64_t n)