Use the variable name _ for unused return values
[bitcoinplatinum.git] / src / httpserver.cpp
blob5923871691e972fe22730ab773d3ed641e12e1af
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 final : 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 explicit 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 explicit 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 = nullptr;
168 //! HTTP server
169 struct evhttp* eventHTTP = nullptr;
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 = nullptr;
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, nullptr);
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 = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
313 std::vector<std::pair<std::string, uint16_t> > endpoints;
315 // Determine what addresses to bind to
316 if (!gArgs.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 (gArgs.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() ? nullptr : 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 (gArgs.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, gArgs.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, nullptr);
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)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
416 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
418 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
419 // transfer 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)gArgs.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, nullptr);
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 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
485 // Before this was solved with event_base_loopexit, but that didn't work as expected in
486 // at least libevent 2.0.21 and always introduced a delay. In libevent
487 // master that appears to be solved, so in the future that solution
488 // could be used again (if desirable).
489 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
490 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
491 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
492 event_base_loopbreak(eventBase);
494 threadHTTP.join();
496 if (eventHTTP) {
497 evhttp_free(eventHTTP);
498 eventHTTP = nullptr;
500 if (eventBase) {
501 event_base_free(eventBase);
502 eventBase = nullptr;
504 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
507 struct event_base* EventBase()
509 return eventBase;
512 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
514 // Static handler: simply call inner handler
515 HTTPEvent *self = ((HTTPEvent*)data);
516 self->handler();
517 if (self->deleteWhenTriggered)
518 delete self;
521 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
522 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
524 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
525 assert(ev);
527 HTTPEvent::~HTTPEvent()
529 event_free(ev);
531 void HTTPEvent::trigger(struct timeval* tv)
533 if (tv == nullptr)
534 event_active(ev, 0, 0); // immediately trigger event in main thread
535 else
536 evtimer_add(ev, tv); // trigger after timeval passed
538 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
539 replySent(false)
542 HTTPRequest::~HTTPRequest()
544 if (!replySent) {
545 // Keep track of whether reply was sent to avoid request leaks
546 LogPrintf("%s: Unhandled request\n", __func__);
547 WriteReply(HTTP_INTERNAL, "Unhandled request");
549 // evhttpd cleans up the request, as long as a reply was sent.
552 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
554 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
555 assert(headers);
556 const char* val = evhttp_find_header(headers, hdr.c_str());
557 if (val)
558 return std::make_pair(true, val);
559 else
560 return std::make_pair(false, "");
563 std::string HTTPRequest::ReadBody()
565 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
566 if (!buf)
567 return "";
568 size_t size = evbuffer_get_length(buf);
569 /** Trivial implementation: if this is ever a performance bottleneck,
570 * internal copying can be avoided in multi-segment buffers by using
571 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
572 * better to not copy into an intermediate string but use a stream
573 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
575 const char* data = (const char*)evbuffer_pullup(buf, size);
576 if (!data) // returns nullptr in case of empty buffer
577 return "";
578 std::string rv(data, size);
579 evbuffer_drain(buf, size);
580 return rv;
583 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
585 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
586 assert(headers);
587 evhttp_add_header(headers, hdr.c_str(), value.c_str());
590 /** Closure sent to main thread to request a reply to be sent to
591 * a HTTP request.
592 * Replies must be sent in the main loop in the main http thread,
593 * this cannot be done from worker threads.
595 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
597 assert(!replySent && req);
598 // Send event to main http thread to send reply message
599 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
600 assert(evb);
601 evbuffer_add(evb, strReply.data(), strReply.size());
602 HTTPEvent* ev = new HTTPEvent(eventBase, true,
603 std::bind(evhttp_send_reply, req, nStatus, (const char*)nullptr, (struct evbuffer *)nullptr));
604 ev->trigger(nullptr);
605 replySent = true;
606 req = nullptr; // transferred back to main thread
609 CService HTTPRequest::GetPeer()
611 evhttp_connection* con = evhttp_request_get_connection(req);
612 CService peer;
613 if (con) {
614 // evhttp retains ownership over returned address string
615 const char* address = "";
616 uint16_t port = 0;
617 evhttp_connection_get_peer(con, (char**)&address, &port);
618 peer = LookupNumeric(address, port);
620 return peer;
623 std::string HTTPRequest::GetURI()
625 return evhttp_request_get_uri(req);
628 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
630 switch (evhttp_request_get_command(req)) {
631 case EVHTTP_REQ_GET:
632 return GET;
633 break;
634 case EVHTTP_REQ_POST:
635 return POST;
636 break;
637 case EVHTTP_REQ_HEAD:
638 return HEAD;
639 break;
640 case EVHTTP_REQ_PUT:
641 return PUT;
642 break;
643 default:
644 return UNKNOWN;
645 break;
649 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
651 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
652 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
655 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
657 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
658 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
659 for (; i != iend; ++i)
660 if (i->prefix == prefix && i->exactMatch == exactMatch)
661 break;
662 if (i != iend)
664 LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
665 pathHandlers.erase(i);
669 std::string urlDecode(const std::string &urlEncoded) {
670 std::string res;
671 if (!urlEncoded.empty()) {
672 char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
673 if (decoded) {
674 res = std::string(decoded);
675 free(decoded);
678 return res;