Improve shutdown process
[bitcoinplatinum.git] / src / httpserver.cpp
blobadb64a65d75d552425842089ee268d1aea377dd5
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/util.h>
28 #include <event2/keyvalq_struct.h>
30 #include "support/events.h"
32 #ifdef EVENT__HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #ifdef _XOPEN_SOURCE_EXTENDED
35 #include <arpa/inet.h>
36 #endif
37 #endif
39 /** Maximum size of http request (request line + headers) */
40 static const size_t MAX_HEADERS_SIZE = 8192;
42 /** HTTP request work item */
43 class HTTPWorkItem : public HTTPClosure
45 public:
46 HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
47 req(std::move(_req)), path(_path), func(_func)
50 void operator()() override
52 func(req.get(), path);
55 std::unique_ptr<HTTPRequest> req;
57 private:
58 std::string path;
59 HTTPRequestHandler func;
62 /** Simple work queue for distributing work over multiple threads.
63 * Work items are simply callable objects.
65 template <typename WorkItem>
66 class WorkQueue
68 private:
69 /** Mutex protects entire object */
70 std::mutex cs;
71 std::condition_variable cond;
72 std::deque<std::unique_ptr<WorkItem>> queue;
73 bool running;
74 size_t maxDepth;
75 int numThreads;
77 /** RAII object to keep track of number of running worker threads */
78 class ThreadCounter
80 public:
81 WorkQueue &wq;
82 ThreadCounter(WorkQueue &w): wq(w)
84 std::lock_guard<std::mutex> lock(wq.cs);
85 wq.numThreads += 1;
87 ~ThreadCounter()
89 std::lock_guard<std::mutex> lock(wq.cs);
90 wq.numThreads -= 1;
91 wq.cond.notify_all();
95 public:
96 WorkQueue(size_t _maxDepth) : running(true),
97 maxDepth(_maxDepth),
98 numThreads(0)
101 /** Precondition: worker threads have all stopped
102 * (call WaitExit)
104 ~WorkQueue()
107 /** Enqueue a work item */
108 bool Enqueue(WorkItem* item)
110 std::unique_lock<std::mutex> lock(cs);
111 if (queue.size() >= maxDepth) {
112 return false;
114 queue.emplace_back(std::unique_ptr<WorkItem>(item));
115 cond.notify_one();
116 return true;
118 /** Thread function */
119 void Run()
121 ThreadCounter count(*this);
122 while (true) {
123 std::unique_ptr<WorkItem> i;
125 std::unique_lock<std::mutex> lock(cs);
126 while (running && queue.empty())
127 cond.wait(lock);
128 if (!running)
129 break;
130 i = std::move(queue.front());
131 queue.pop_front();
133 (*i)();
136 /** Interrupt and exit loops */
137 void Interrupt()
139 std::unique_lock<std::mutex> lock(cs);
140 running = false;
141 cond.notify_all();
143 /** Wait for worker threads to exit */
144 void WaitExit()
146 std::unique_lock<std::mutex> lock(cs);
147 while (numThreads > 0)
148 cond.wait(lock);
152 struct HTTPPathHandler
154 HTTPPathHandler() {}
155 HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
156 prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
159 std::string prefix;
160 bool exactMatch;
161 HTTPRequestHandler handler;
164 /** HTTP module state */
166 //! libevent event loop
167 static struct event_base* eventBase = 0;
168 //! HTTP server
169 struct evhttp* eventHTTP = 0;
170 //! List of subnets to allow RPC connections from
171 static std::vector<CSubNet> rpc_allow_subnets;
172 //! Work queue for handling longer requests off the event loop thread
173 static WorkQueue<HTTPClosure>* workQueue = 0;
174 //! Handlers for (sub)paths
175 std::vector<HTTPPathHandler> pathHandlers;
176 //! Bound listening sockets
177 std::vector<evhttp_bound_socket *> boundSockets;
179 /** Check if a network address is allowed to access the HTTP server */
180 static bool ClientAllowed(const CNetAddr& netaddr)
182 if (!netaddr.IsValid())
183 return false;
184 for(const CSubNet& subnet : rpc_allow_subnets)
185 if (subnet.Match(netaddr))
186 return true;
187 return false;
190 /** Initialize ACL list for HTTP server */
191 static bool InitHTTPAllowList()
193 rpc_allow_subnets.clear();
194 CNetAddr localv4;
195 CNetAddr localv6;
196 LookupHost("127.0.0.1", localv4, false);
197 LookupHost("::1", localv6, false);
198 rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
199 rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
200 for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
201 CSubNet subnet;
202 LookupSubNet(strAllow.c_str(), subnet);
203 if (!subnet.IsValid()) {
204 uiInterface.ThreadSafeMessageBox(
205 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),
206 "", CClientUIInterface::MSG_ERROR);
207 return false;
209 rpc_allow_subnets.push_back(subnet);
211 std::string strAllowed;
212 for (const CSubNet& subnet : rpc_allow_subnets)
213 strAllowed += subnet.ToString() + " ";
214 LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
215 return true;
218 /** HTTP request method as string - use for logging only */
219 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
221 switch (m) {
222 case HTTPRequest::GET:
223 return "GET";
224 break;
225 case HTTPRequest::POST:
226 return "POST";
227 break;
228 case HTTPRequest::HEAD:
229 return "HEAD";
230 break;
231 case HTTPRequest::PUT:
232 return "PUT";
233 break;
234 default:
235 return "unknown";
239 /** HTTP request callback */
240 static void http_request_cb(struct evhttp_request* req, void* arg)
242 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
244 LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
245 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
247 // Early address-based allow check
248 if (!ClientAllowed(hreq->GetPeer())) {
249 hreq->WriteReply(HTTP_FORBIDDEN);
250 return;
253 // Early reject unknown HTTP methods
254 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
255 hreq->WriteReply(HTTP_BADMETHOD);
256 return;
259 // Find registered handler for prefix
260 std::string strURI = hreq->GetURI();
261 std::string path;
262 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
263 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
264 for (; i != iend; ++i) {
265 bool match = false;
266 if (i->exactMatch)
267 match = (strURI == i->prefix);
268 else
269 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
270 if (match) {
271 path = strURI.substr(i->prefix.size());
272 break;
276 // Dispatch to worker thread
277 if (i != iend) {
278 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
279 assert(workQueue);
280 if (workQueue->Enqueue(item.get()))
281 item.release(); /* if true, queue took ownership */
282 else {
283 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
284 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
286 } else {
287 hreq->WriteReply(HTTP_NOTFOUND);
291 /** Callback to reject HTTP requests after shutdown. */
292 static void http_reject_request_cb(struct evhttp_request* req, void*)
294 LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
295 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
298 /** Event dispatcher thread */
299 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
301 RenameThread("bitcoin-http");
302 LogPrint(BCLog::HTTP, "Entering http event loop\n");
303 event_base_dispatch(base);
304 // Event loop will be interrupted by InterruptHTTPServer()
305 LogPrint(BCLog::HTTP, "Exited http event loop\n");
306 return event_base_got_break(base) == 0;
309 /** Bind HTTP server to specified addresses */
310 static bool HTTPBindAddresses(struct evhttp* http)
312 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
313 std::vector<std::pair<std::string, uint16_t> > endpoints;
315 // Determine what addresses to bind to
316 if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
317 endpoints.push_back(std::make_pair("::1", defaultPort));
318 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
319 if (IsArgSet("-rpcbind")) {
320 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
322 } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
323 for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
324 int port = defaultPort;
325 std::string host;
326 SplitHostPort(strRPCBind, port, host);
327 endpoints.push_back(std::make_pair(host, port));
329 } else { // No specific bind address specified, bind to any
330 endpoints.push_back(std::make_pair("::", defaultPort));
331 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
334 // Bind addresses
335 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
336 LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
337 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
338 if (bind_handle) {
339 boundSockets.push_back(bind_handle);
340 } else {
341 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
344 return !boundSockets.empty();
347 /** Simple wrapper to set thread name and run work queue */
348 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
350 RenameThread("bitcoin-httpworker");
351 queue->Run();
354 /** libevent event log callback */
355 static void libevent_log_cb(int severity, const char *msg)
357 #ifndef EVENT_LOG_WARN
358 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
359 # define EVENT_LOG_WARN _EVENT_LOG_WARN
360 #endif
361 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
362 LogPrintf("libevent: %s\n", msg);
363 else
364 LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
367 bool InitHTTPServer()
369 if (!InitHTTPAllowList())
370 return false;
372 if (GetBoolArg("-rpcssl", false)) {
373 uiInterface.ThreadSafeMessageBox(
374 "SSL mode for RPC (-rpcssl) is no longer supported.",
375 "", CClientUIInterface::MSG_ERROR);
376 return false;
379 // Redirect libevent's logging to our own log
380 event_set_log_callback(&libevent_log_cb);
381 // Update libevent's log handling. Returns false if our version of
382 // libevent doesn't support debug logging, in which case we should
383 // clear the BCLog::LIBEVENT flag.
384 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
385 logCategories &= ~BCLog::LIBEVENT;
388 #ifdef WIN32
389 evthread_use_windows_threads();
390 #else
391 evthread_use_pthreads();
392 #endif
394 raii_event_base base_ctr = obtain_event_base();
396 /* Create a new evhttp object to handle requests. */
397 raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
398 struct evhttp* http = http_ctr.get();
399 if (!http) {
400 LogPrintf("couldn't create evhttp. Exiting.\n");
401 return false;
404 evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
405 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
406 evhttp_set_max_body_size(http, MAX_SIZE);
407 evhttp_set_gencb(http, http_request_cb, NULL);
409 if (!HTTPBindAddresses(http)) {
410 LogPrintf("Unable to bind any endpoint for RPC server\n");
411 return false;
414 LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
415 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
416 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
418 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
419 // tranfer ownership to eventBase/HTTP via .release()
420 eventBase = base_ctr.release();
421 eventHTTP = http_ctr.release();
422 return true;
425 bool UpdateHTTPServerLogging(bool enable) {
426 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
427 if (enable) {
428 event_enable_debug_logging(EVENT_DBG_ALL);
429 } else {
430 event_enable_debug_logging(EVENT_DBG_NONE);
432 return true;
433 #else
434 // Can't update libevent logging if version < 02010100
435 return false;
436 #endif
439 std::thread threadHTTP;
440 std::future<bool> threadResult;
442 bool StartHTTPServer()
444 LogPrint(BCLog::HTTP, "Starting HTTP server\n");
445 int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
446 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
447 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
448 threadResult = task.get_future();
449 threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
451 for (int i = 0; i < rpcThreads; i++) {
452 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
453 rpc_worker.detach();
455 return true;
458 void InterruptHTTPServer()
460 LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
461 if (eventHTTP) {
462 // Unlisten sockets
463 for (evhttp_bound_socket *socket : boundSockets) {
464 evhttp_del_accept_socket(eventHTTP, socket);
466 // Reject requests on current connections
467 evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
469 if (workQueue)
470 workQueue->Interrupt();
473 void StopHTTPServer()
475 LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
476 if (workQueue) {
477 LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
478 workQueue->WaitExit();
479 delete workQueue;
480 workQueue = nullptr;
482 if (eventBase) {
483 LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
484 // Exit the event loop as soon as there are no active events.
485 event_base_loopexit(eventBase, nullptr);
486 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
487 // Before this was solved with event_base_loopexit, but that didn't work as expected in
488 // at least libevent 2.0.21 and always introduced a delay. In libevent
489 // master that appears to be solved, so in the future that solution
490 // could be used again (if desirable).
491 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
492 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
493 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
494 event_base_loopbreak(eventBase);
496 threadHTTP.join();
498 if (eventHTTP) {
499 evhttp_free(eventHTTP);
500 eventHTTP = 0;
502 if (eventBase) {
503 event_base_free(eventBase);
504 eventBase = 0;
506 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
509 struct event_base* EventBase()
511 return eventBase;
514 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
516 // Static handler: simply call inner handler
517 HTTPEvent *self = ((HTTPEvent*)data);
518 self->handler();
519 if (self->deleteWhenTriggered)
520 delete self;
523 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
524 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
526 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
527 assert(ev);
529 HTTPEvent::~HTTPEvent()
531 event_free(ev);
533 void HTTPEvent::trigger(struct timeval* tv)
535 if (tv == NULL)
536 event_active(ev, 0, 0); // immediately trigger event in main thread
537 else
538 evtimer_add(ev, tv); // trigger after timeval passed
540 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
541 replySent(false)
544 HTTPRequest::~HTTPRequest()
546 if (!replySent) {
547 // Keep track of whether reply was sent to avoid request leaks
548 LogPrintf("%s: Unhandled request\n", __func__);
549 WriteReply(HTTP_INTERNAL, "Unhandled request");
551 // evhttpd cleans up the request, as long as a reply was sent.
554 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
556 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
557 assert(headers);
558 const char* val = evhttp_find_header(headers, hdr.c_str());
559 if (val)
560 return std::make_pair(true, val);
561 else
562 return std::make_pair(false, "");
565 std::string HTTPRequest::ReadBody()
567 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
568 if (!buf)
569 return "";
570 size_t size = evbuffer_get_length(buf);
571 /** Trivial implementation: if this is ever a performance bottleneck,
572 * internal copying can be avoided in multi-segment buffers by using
573 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
574 * better to not copy into an intermediate string but use a stream
575 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
577 const char* data = (const char*)evbuffer_pullup(buf, size);
578 if (!data) // returns NULL in case of empty buffer
579 return "";
580 std::string rv(data, size);
581 evbuffer_drain(buf, size);
582 return rv;
585 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
587 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
588 assert(headers);
589 evhttp_add_header(headers, hdr.c_str(), value.c_str());
592 /** Closure sent to main thread to request a reply to be sent to
593 * a HTTP request.
594 * Replies must be sent in the main loop in the main http thread,
595 * this cannot be done from worker threads.
597 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
599 assert(!replySent && req);
600 // Send event to main http thread to send reply message
601 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
602 assert(evb);
603 evbuffer_add(evb, strReply.data(), strReply.size());
604 HTTPEvent* ev = new HTTPEvent(eventBase, true,
605 std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
606 ev->trigger(0);
607 replySent = true;
608 req = 0; // transferred back to main thread
611 CService HTTPRequest::GetPeer()
613 evhttp_connection* con = evhttp_request_get_connection(req);
614 CService peer;
615 if (con) {
616 // evhttp retains ownership over returned address string
617 const char* address = "";
618 uint16_t port = 0;
619 evhttp_connection_get_peer(con, (char**)&address, &port);
620 peer = LookupNumeric(address, port);
622 return peer;
625 std::string HTTPRequest::GetURI()
627 return evhttp_request_get_uri(req);
630 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
632 switch (evhttp_request_get_command(req)) {
633 case EVHTTP_REQ_GET:
634 return GET;
635 break;
636 case EVHTTP_REQ_POST:
637 return POST;
638 break;
639 case EVHTTP_REQ_HEAD:
640 return HEAD;
641 break;
642 case EVHTTP_REQ_PUT:
643 return PUT;
644 break;
645 default:
646 return UNKNOWN;
647 break;
651 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
653 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
654 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
657 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
659 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
660 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
661 for (; i != iend; ++i)
662 if (i->prefix == prefix && i->exactMatch == exactMatch)
663 break;
664 if (i != iend)
666 LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
667 pathHandlers.erase(i);
671 std::string urlDecode(const std::string &urlEncoded) {
672 std::string res;
673 if (!urlEncoded.empty()) {
674 char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, NULL);
675 if (decoded) {
676 res = std::string(decoded);
677 free(decoded);
680 return res;