Merge #11722: Switched sync.{cpp,h} to std threading primitives.
[bitcoinplatinum.git] / src / httpserver.cpp
blob7d590f8e1f7eb018e96f503455e6f3a1a29c4bbc
1 // Copyright (c) 2015-2016 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <httpserver.h>
7 #include <chainparamsbase.h>
8 #include <compat.h>
9 #include <util.h>
10 #include <utilstrencodings.h>
11 #include <netbase.h>
12 #include <rpc/protocol.h> // For HTTP status codes
13 #include <sync.h>
14 #include <ui_interface.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <signal.h>
23 #include <future>
25 #include <event2/thread.h>
26 #include <event2/buffer.h>
27 #include <event2/bufferevent.h>
28 #include <event2/util.h>
29 #include <event2/keyvalq_struct.h>
31 #include <support/events.h>
33 #ifdef EVENT__HAVE_NETINET_IN_H
34 #include <netinet/in.h>
35 #ifdef _XOPEN_SOURCE_EXTENDED
36 #include <arpa/inet.h>
37 #endif
38 #endif
40 /** Maximum size of http request (request line + headers) */
41 static const size_t MAX_HEADERS_SIZE = 8192;
43 /** HTTP request work item */
44 class HTTPWorkItem final : public HTTPClosure
46 public:
47 HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
48 req(std::move(_req)), path(_path), func(_func)
51 void operator()() override
53 func(req.get(), path);
56 std::unique_ptr<HTTPRequest> req;
58 private:
59 std::string path;
60 HTTPRequestHandler func;
63 /** Simple work queue for distributing work over multiple threads.
64 * Work items are simply callable objects.
66 template <typename WorkItem>
67 class WorkQueue
69 private:
70 /** Mutex protects entire object */
71 std::mutex cs;
72 std::condition_variable cond;
73 std::deque<std::unique_ptr<WorkItem>> queue;
74 bool running;
75 size_t maxDepth;
76 int numThreads;
78 /** RAII object to keep track of number of running worker threads */
79 class ThreadCounter
81 public:
82 WorkQueue &wq;
83 explicit ThreadCounter(WorkQueue &w): wq(w)
85 std::lock_guard<std::mutex> lock(wq.cs);
86 wq.numThreads += 1;
88 ~ThreadCounter()
90 std::lock_guard<std::mutex> lock(wq.cs);
91 wq.numThreads -= 1;
92 wq.cond.notify_all();
96 public:
97 explicit WorkQueue(size_t _maxDepth) : running(true),
98 maxDepth(_maxDepth),
99 numThreads(0)
102 /** Precondition: worker threads have all stopped
103 * (call WaitExit)
105 ~WorkQueue()
108 /** Enqueue a work item */
109 bool Enqueue(WorkItem* item)
111 std::unique_lock<std::mutex> lock(cs);
112 if (queue.size() >= maxDepth) {
113 return false;
115 queue.emplace_back(std::unique_ptr<WorkItem>(item));
116 cond.notify_one();
117 return true;
119 /** Thread function */
120 void Run()
122 ThreadCounter count(*this);
123 while (true) {
124 std::unique_ptr<WorkItem> i;
126 std::unique_lock<std::mutex> lock(cs);
127 while (running && queue.empty())
128 cond.wait(lock);
129 if (!running)
130 break;
131 i = std::move(queue.front());
132 queue.pop_front();
134 (*i)();
137 /** Interrupt and exit loops */
138 void Interrupt()
140 std::unique_lock<std::mutex> lock(cs);
141 running = false;
142 cond.notify_all();
144 /** Wait for worker threads to exit */
145 void WaitExit()
147 std::unique_lock<std::mutex> lock(cs);
148 while (numThreads > 0)
149 cond.wait(lock);
153 struct HTTPPathHandler
155 HTTPPathHandler() {}
156 HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
157 prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
160 std::string prefix;
161 bool exactMatch;
162 HTTPRequestHandler handler;
165 /** HTTP module state */
167 //! libevent event loop
168 static struct event_base* eventBase = nullptr;
169 //! HTTP server
170 struct evhttp* eventHTTP = nullptr;
171 //! List of subnets to allow RPC connections from
172 static std::vector<CSubNet> rpc_allow_subnets;
173 //! Work queue for handling longer requests off the event loop thread
174 static WorkQueue<HTTPClosure>* workQueue = nullptr;
175 //! Handlers for (sub)paths
176 std::vector<HTTPPathHandler> pathHandlers;
177 //! Bound listening sockets
178 std::vector<evhttp_bound_socket *> boundSockets;
180 /** Check if a network address is allowed to access the HTTP server */
181 static bool ClientAllowed(const CNetAddr& netaddr)
183 if (!netaddr.IsValid())
184 return false;
185 for(const CSubNet& subnet : rpc_allow_subnets)
186 if (subnet.Match(netaddr))
187 return true;
188 return false;
191 /** Initialize ACL list for HTTP server */
192 static bool InitHTTPAllowList()
194 rpc_allow_subnets.clear();
195 CNetAddr localv4;
196 CNetAddr localv6;
197 LookupHost("127.0.0.1", localv4, false);
198 LookupHost("::1", localv6, false);
199 rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
200 rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
201 for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
202 CSubNet subnet;
203 LookupSubNet(strAllow.c_str(), subnet);
204 if (!subnet.IsValid()) {
205 uiInterface.ThreadSafeMessageBox(
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),
207 "", CClientUIInterface::MSG_ERROR);
208 return false;
210 rpc_allow_subnets.push_back(subnet);
212 std::string strAllowed;
213 for (const CSubNet& subnet : rpc_allow_subnets)
214 strAllowed += subnet.ToString() + " ";
215 LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
216 return true;
219 /** HTTP request method as string - use for logging only */
220 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
222 switch (m) {
223 case HTTPRequest::GET:
224 return "GET";
225 break;
226 case HTTPRequest::POST:
227 return "POST";
228 break;
229 case HTTPRequest::HEAD:
230 return "HEAD";
231 break;
232 case HTTPRequest::PUT:
233 return "PUT";
234 break;
235 default:
236 return "unknown";
240 /** HTTP request callback */
241 static void http_request_cb(struct evhttp_request* req, void* arg)
243 // Disable reading to work around a libevent bug, fixed in 2.2.0.
244 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
245 evhttp_connection* conn = evhttp_request_get_connection(req);
246 if (conn) {
247 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
248 if (bev) {
249 bufferevent_disable(bev, EV_READ);
253 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
255 LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
256 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
258 // Early address-based allow check
259 if (!ClientAllowed(hreq->GetPeer())) {
260 hreq->WriteReply(HTTP_FORBIDDEN);
261 return;
264 // Early reject unknown HTTP methods
265 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
266 hreq->WriteReply(HTTP_BADMETHOD);
267 return;
270 // Find registered handler for prefix
271 std::string strURI = hreq->GetURI();
272 std::string path;
273 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
274 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
275 for (; i != iend; ++i) {
276 bool match = false;
277 if (i->exactMatch)
278 match = (strURI == i->prefix);
279 else
280 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
281 if (match) {
282 path = strURI.substr(i->prefix.size());
283 break;
287 // Dispatch to worker thread
288 if (i != iend) {
289 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
290 assert(workQueue);
291 if (workQueue->Enqueue(item.get()))
292 item.release(); /* if true, queue took ownership */
293 else {
294 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
295 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
297 } else {
298 hreq->WriteReply(HTTP_NOTFOUND);
302 /** Callback to reject HTTP requests after shutdown. */
303 static void http_reject_request_cb(struct evhttp_request* req, void*)
305 LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
306 evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
309 /** Event dispatcher thread */
310 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
312 RenameThread("bitcoin-http");
313 LogPrint(BCLog::HTTP, "Entering http event loop\n");
314 event_base_dispatch(base);
315 // Event loop will be interrupted by InterruptHTTPServer()
316 LogPrint(BCLog::HTTP, "Exited http event loop\n");
317 return event_base_got_break(base) == 0;
320 /** Bind HTTP server to specified addresses */
321 static bool HTTPBindAddresses(struct evhttp* http)
323 int defaultPort = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
324 std::vector<std::pair<std::string, uint16_t> > endpoints;
326 // Determine what addresses to bind to
327 if (!gArgs.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
328 endpoints.push_back(std::make_pair("::1", defaultPort));
329 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
330 if (gArgs.IsArgSet("-rpcbind")) {
331 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
333 } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
334 for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
335 int port = defaultPort;
336 std::string host;
337 SplitHostPort(strRPCBind, port, host);
338 endpoints.push_back(std::make_pair(host, port));
340 } else { // No specific bind address specified, bind to any
341 endpoints.push_back(std::make_pair("::", defaultPort));
342 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
345 // Bind addresses
346 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
347 LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
348 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
349 if (bind_handle) {
350 boundSockets.push_back(bind_handle);
351 } else {
352 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
355 return !boundSockets.empty();
358 /** Simple wrapper to set thread name and run work queue */
359 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
361 RenameThread("bitcoin-httpworker");
362 queue->Run();
365 /** libevent event log callback */
366 static void libevent_log_cb(int severity, const char *msg)
368 #ifndef EVENT_LOG_WARN
369 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
370 # define EVENT_LOG_WARN _EVENT_LOG_WARN
371 #endif
372 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
373 LogPrintf("libevent: %s\n", msg);
374 else
375 LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
378 bool InitHTTPServer()
380 if (!InitHTTPAllowList())
381 return false;
383 if (gArgs.GetBoolArg("-rpcssl", false)) {
384 uiInterface.ThreadSafeMessageBox(
385 "SSL mode for RPC (-rpcssl) is no longer supported.",
386 "", CClientUIInterface::MSG_ERROR);
387 return false;
390 // Redirect libevent's logging to our own log
391 event_set_log_callback(&libevent_log_cb);
392 // Update libevent's log handling. Returns false if our version of
393 // libevent doesn't support debug logging, in which case we should
394 // clear the BCLog::LIBEVENT flag.
395 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
396 logCategories &= ~BCLog::LIBEVENT;
399 #ifdef WIN32
400 evthread_use_windows_threads();
401 #else
402 evthread_use_pthreads();
403 #endif
405 raii_event_base base_ctr = obtain_event_base();
407 /* Create a new evhttp object to handle requests. */
408 raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
409 struct evhttp* http = http_ctr.get();
410 if (!http) {
411 LogPrintf("couldn't create evhttp. Exiting.\n");
412 return false;
415 evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
416 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
417 evhttp_set_max_body_size(http, MAX_SIZE);
418 evhttp_set_gencb(http, http_request_cb, nullptr);
420 if (!HTTPBindAddresses(http)) {
421 LogPrintf("Unable to bind any endpoint for RPC server\n");
422 return false;
425 LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
426 int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
427 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
429 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
430 // transfer ownership to eventBase/HTTP via .release()
431 eventBase = base_ctr.release();
432 eventHTTP = http_ctr.release();
433 return true;
436 bool UpdateHTTPServerLogging(bool enable) {
437 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
438 if (enable) {
439 event_enable_debug_logging(EVENT_DBG_ALL);
440 } else {
441 event_enable_debug_logging(EVENT_DBG_NONE);
443 return true;
444 #else
445 // Can't update libevent logging if version < 02010100
446 return false;
447 #endif
450 std::thread threadHTTP;
451 std::future<bool> threadResult;
453 bool StartHTTPServer()
455 LogPrint(BCLog::HTTP, "Starting HTTP server\n");
456 int rpcThreads = std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
457 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
458 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
459 threadResult = task.get_future();
460 threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
462 for (int i = 0; i < rpcThreads; i++) {
463 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
464 rpc_worker.detach();
466 return true;
469 void InterruptHTTPServer()
471 LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
472 if (eventHTTP) {
473 // Unlisten sockets
474 for (evhttp_bound_socket *socket : boundSockets) {
475 evhttp_del_accept_socket(eventHTTP, socket);
477 // Reject requests on current connections
478 evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
480 if (workQueue)
481 workQueue->Interrupt();
484 void StopHTTPServer()
486 LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
487 if (workQueue) {
488 LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
489 workQueue->WaitExit();
490 delete workQueue;
491 workQueue = nullptr;
493 if (eventBase) {
494 LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
495 // Exit the event loop as soon as there are no active events.
496 event_base_loopexit(eventBase, nullptr);
497 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
498 // Before this was solved with event_base_loopexit, but that didn't work as expected in
499 // at least libevent 2.0.21 and always introduced a delay. In libevent
500 // master that appears to be solved, so in the future that solution
501 // could be used again (if desirable).
502 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
503 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
504 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
505 event_base_loopbreak(eventBase);
507 threadHTTP.join();
509 if (eventHTTP) {
510 evhttp_free(eventHTTP);
511 eventHTTP = nullptr;
513 if (eventBase) {
514 event_base_free(eventBase);
515 eventBase = nullptr;
517 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
520 struct event_base* EventBase()
522 return eventBase;
525 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
527 // Static handler: simply call inner handler
528 HTTPEvent *self = ((HTTPEvent*)data);
529 self->handler();
530 if (self->deleteWhenTriggered)
531 delete self;
534 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
535 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
537 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
538 assert(ev);
540 HTTPEvent::~HTTPEvent()
542 event_free(ev);
544 void HTTPEvent::trigger(struct timeval* tv)
546 if (tv == nullptr)
547 event_active(ev, 0, 0); // immediately trigger event in main thread
548 else
549 evtimer_add(ev, tv); // trigger after timeval passed
551 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
552 replySent(false)
555 HTTPRequest::~HTTPRequest()
557 if (!replySent) {
558 // Keep track of whether reply was sent to avoid request leaks
559 LogPrintf("%s: Unhandled request\n", __func__);
560 WriteReply(HTTP_INTERNAL, "Unhandled request");
562 // evhttpd cleans up the request, as long as a reply was sent.
565 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
567 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
568 assert(headers);
569 const char* val = evhttp_find_header(headers, hdr.c_str());
570 if (val)
571 return std::make_pair(true, val);
572 else
573 return std::make_pair(false, "");
576 std::string HTTPRequest::ReadBody()
578 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
579 if (!buf)
580 return "";
581 size_t size = evbuffer_get_length(buf);
582 /** Trivial implementation: if this is ever a performance bottleneck,
583 * internal copying can be avoided in multi-segment buffers by using
584 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
585 * better to not copy into an intermediate string but use a stream
586 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
588 const char* data = (const char*)evbuffer_pullup(buf, size);
589 if (!data) // returns nullptr in case of empty buffer
590 return "";
591 std::string rv(data, size);
592 evbuffer_drain(buf, size);
593 return rv;
596 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
598 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
599 assert(headers);
600 evhttp_add_header(headers, hdr.c_str(), value.c_str());
603 /** Closure sent to main thread to request a reply to be sent to
604 * a HTTP request.
605 * Replies must be sent in the main loop in the main http thread,
606 * this cannot be done from worker threads.
608 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
610 assert(!replySent && req);
611 // Send event to main http thread to send reply message
612 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
613 assert(evb);
614 evbuffer_add(evb, strReply.data(), strReply.size());
615 auto req_copy = req;
616 HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
617 evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
618 // Re-enable reading from the socket. This is the second part of the libevent
619 // workaround above.
620 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
621 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
622 if (conn) {
623 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
624 if (bev) {
625 bufferevent_enable(bev, EV_READ | EV_WRITE);
630 ev->trigger(nullptr);
631 replySent = true;
632 req = nullptr; // transferred back to main thread
635 CService HTTPRequest::GetPeer()
637 evhttp_connection* con = evhttp_request_get_connection(req);
638 CService peer;
639 if (con) {
640 // evhttp retains ownership over returned address string
641 const char* address = "";
642 uint16_t port = 0;
643 evhttp_connection_get_peer(con, (char**)&address, &port);
644 peer = LookupNumeric(address, port);
646 return peer;
649 std::string HTTPRequest::GetURI()
651 return evhttp_request_get_uri(req);
654 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
656 switch (evhttp_request_get_command(req)) {
657 case EVHTTP_REQ_GET:
658 return GET;
659 break;
660 case EVHTTP_REQ_POST:
661 return POST;
662 break;
663 case EVHTTP_REQ_HEAD:
664 return HEAD;
665 break;
666 case EVHTTP_REQ_PUT:
667 return PUT;
668 break;
669 default:
670 return UNKNOWN;
671 break;
675 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
677 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
678 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
681 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
683 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
684 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
685 for (; i != iend; ++i)
686 if (i->prefix == prefix && i->exactMatch == exactMatch)
687 break;
688 if (i != iend)
690 LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
691 pathHandlers.erase(i);
695 std::string urlDecode(const std::string &urlEncoded) {
696 std::string res;
697 if (!urlEncoded.empty()) {
698 char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
699 if (decoded) {
700 res = std::string(decoded);
701 free(decoded);
704 return res;