Remove unused var UNLIKELY_PCT from fees.h
[bitcoinplatinum.git] / src / httpserver.cpp
blobb296b28503026447846334a76fff26954d3398ab
1 // Copyright (c) 2015 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 "netbase.h"
11 #include "rpc/protocol.h" // For HTTP status codes
12 #include "sync.h"
13 #include "ui_interface.h"
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <signal.h>
22 #include <future>
24 #include <event2/event.h>
25 #include <event2/http.h>
26 #include <event2/thread.h>
27 #include <event2/buffer.h>
28 #include <event2/util.h>
29 #include <event2/keyvalq_struct.h>
31 #ifdef EVENT__HAVE_NETINET_IN_H
32 #include <netinet/in.h>
33 #ifdef _XOPEN_SOURCE_EXTENDED
34 #include <arpa/inet.h>
35 #endif
36 #endif
38 /** Maximum size of http request (request line + headers) */
39 static const size_t MAX_HEADERS_SIZE = 8192;
41 /** HTTP request work item */
42 class HTTPWorkItem : public HTTPClosure
44 public:
45 HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
46 req(std::move(_req)), path(_path), func(_func)
49 void operator()()
51 func(req.get(), path);
54 std::unique_ptr<HTTPRequest> req;
56 private:
57 std::string path;
58 HTTPRequestHandler func;
61 /** Simple work queue for distributing work over multiple threads.
62 * Work items are simply callable objects.
64 template <typename WorkItem>
65 class WorkQueue
67 private:
68 /** Mutex protects entire object */
69 std::mutex cs;
70 std::condition_variable cond;
71 std::deque<std::unique_ptr<WorkItem>> queue;
72 bool running;
73 size_t maxDepth;
74 int numThreads;
76 /** RAII object to keep track of number of running worker threads */
77 class ThreadCounter
79 public:
80 WorkQueue &wq;
81 ThreadCounter(WorkQueue &w): wq(w)
83 std::lock_guard<std::mutex> lock(wq.cs);
84 wq.numThreads += 1;
86 ~ThreadCounter()
88 std::lock_guard<std::mutex> lock(wq.cs);
89 wq.numThreads -= 1;
90 wq.cond.notify_all();
94 public:
95 WorkQueue(size_t _maxDepth) : running(true),
96 maxDepth(_maxDepth),
97 numThreads(0)
100 /** Precondition: worker threads have all stopped
101 * (call WaitExit)
103 ~WorkQueue()
106 /** Enqueue a work item */
107 bool Enqueue(WorkItem* item)
109 std::unique_lock<std::mutex> lock(cs);
110 if (queue.size() >= maxDepth) {
111 return false;
113 queue.emplace_back(std::unique_ptr<WorkItem>(item));
114 cond.notify_one();
115 return true;
117 /** Thread function */
118 void Run()
120 ThreadCounter count(*this);
121 while (running) {
122 std::unique_ptr<WorkItem> i;
124 std::unique_lock<std::mutex> lock(cs);
125 while (running && queue.empty())
126 cond.wait(lock);
127 if (!running)
128 break;
129 i = std::move(queue.front());
130 queue.pop_front();
132 (*i)();
135 /** Interrupt and exit loops */
136 void Interrupt()
138 std::unique_lock<std::mutex> lock(cs);
139 running = false;
140 cond.notify_all();
142 /** Wait for worker threads to exit */
143 void WaitExit()
145 std::unique_lock<std::mutex> lock(cs);
146 while (numThreads > 0)
147 cond.wait(lock);
150 /** Return current depth of queue */
151 size_t Depth()
153 std::unique_lock<std::mutex> lock(cs);
154 return queue.size();
158 struct HTTPPathHandler
160 HTTPPathHandler() {}
161 HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
162 prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
165 std::string prefix;
166 bool exactMatch;
167 HTTPRequestHandler handler;
170 /** HTTP module state */
172 //! libevent event loop
173 static struct event_base* eventBase = 0;
174 //! HTTP server
175 struct evhttp* eventHTTP = 0;
176 //! List of subnets to allow RPC connections from
177 static std::vector<CSubNet> rpc_allow_subnets;
178 //! Work queue for handling longer requests off the event loop thread
179 static WorkQueue<HTTPClosure>* workQueue = 0;
180 //! Handlers for (sub)paths
181 std::vector<HTTPPathHandler> pathHandlers;
182 //! Bound listening sockets
183 std::vector<evhttp_bound_socket *> boundSockets;
185 /** Check if a network address is allowed to access the HTTP server */
186 static bool ClientAllowed(const CNetAddr& netaddr)
188 if (!netaddr.IsValid())
189 return false;
190 for(const CSubNet& subnet : rpc_allow_subnets)
191 if (subnet.Match(netaddr))
192 return true;
193 return false;
196 /** Initialize ACL list for HTTP server */
197 static bool InitHTTPAllowList()
199 rpc_allow_subnets.clear();
200 CNetAddr localv4;
201 CNetAddr localv6;
202 LookupHost("127.0.0.1", localv4, false);
203 LookupHost("::1", localv6, false);
204 rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
205 rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
206 if (mapMultiArgs.count("-rpcallowip")) {
207 const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
208 for (std::string strAllow : vAllow) {
209 CSubNet subnet;
210 LookupSubNet(strAllow.c_str(), subnet);
211 if (!subnet.IsValid()) {
212 uiInterface.ThreadSafeMessageBox(
213 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),
214 "", CClientUIInterface::MSG_ERROR);
215 return false;
217 rpc_allow_subnets.push_back(subnet);
220 std::string strAllowed;
221 for (const CSubNet& subnet : rpc_allow_subnets)
222 strAllowed += subnet.ToString() + " ";
223 LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
224 return true;
227 /** HTTP request method as string - use for logging only */
228 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
230 switch (m) {
231 case HTTPRequest::GET:
232 return "GET";
233 break;
234 case HTTPRequest::POST:
235 return "POST";
236 break;
237 case HTTPRequest::HEAD:
238 return "HEAD";
239 break;
240 case HTTPRequest::PUT:
241 return "PUT";
242 break;
243 default:
244 return "unknown";
248 /** HTTP request callback */
249 static void http_request_cb(struct evhttp_request* req, void* arg)
251 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
253 LogPrint("http", "Received a %s request for %s from %s\n",
254 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
256 // Early address-based allow check
257 if (!ClientAllowed(hreq->GetPeer())) {
258 hreq->WriteReply(HTTP_FORBIDDEN);
259 return;
262 // Early reject unknown HTTP methods
263 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
264 hreq->WriteReply(HTTP_BADMETHOD);
265 return;
268 // Find registered handler for prefix
269 std::string strURI = hreq->GetURI();
270 std::string path;
271 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
272 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
273 for (; i != iend; ++i) {
274 bool match = false;
275 if (i->exactMatch)
276 match = (strURI == i->prefix);
277 else
278 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
279 if (match) {
280 path = strURI.substr(i->prefix.size());
281 break;
285 // Dispatch to worker thread
286 if (i != iend) {
287 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
288 assert(workQueue);
289 if (workQueue->Enqueue(item.get()))
290 item.release(); /* if true, queue took ownership */
291 else {
292 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
293 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
295 } else {
296 hreq->WriteReply(HTTP_NOTFOUND);
300 /** Callback to reject HTTP requests after shutdown. */
301 static void http_reject_request_cb(struct evhttp_request* req, void*)
303 LogPrint("http", "Rejecting request while shutting down\n");
304 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
307 /** Event dispatcher thread */
308 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
310 RenameThread("bitcoin-http");
311 LogPrint("http", "Entering http event loop\n");
312 event_base_dispatch(base);
313 // Event loop will be interrupted by InterruptHTTPServer()
314 LogPrint("http", "Exited http event loop\n");
315 return event_base_got_break(base) == 0;
318 /** Bind HTTP server to specified addresses */
319 static bool HTTPBindAddresses(struct evhttp* http)
321 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
322 std::vector<std::pair<std::string, uint16_t> > endpoints;
324 // Determine what addresses to bind to
325 if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
326 endpoints.push_back(std::make_pair("::1", defaultPort));
327 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
328 if (mapArgs.count("-rpcbind")) {
329 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
331 } else if (mapArgs.count("-rpcbind")) { // Specific bind address
332 const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
333 for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
334 int port = defaultPort;
335 std::string host;
336 SplitHostPort(*i, port, host);
337 endpoints.push_back(std::make_pair(host, port));
339 } else { // No specific bind address specified, bind to any
340 endpoints.push_back(std::make_pair("::", defaultPort));
341 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
344 // Bind addresses
345 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
346 LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
347 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
348 if (bind_handle) {
349 boundSockets.push_back(bind_handle);
350 } else {
351 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
354 return !boundSockets.empty();
357 /** Simple wrapper to set thread name and run work queue */
358 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
360 RenameThread("bitcoin-httpworker");
361 queue->Run();
364 /** libevent event log callback */
365 static void libevent_log_cb(int severity, const char *msg)
367 #ifndef EVENT_LOG_WARN
368 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
369 # define EVENT_LOG_WARN _EVENT_LOG_WARN
370 #endif
371 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
372 LogPrintf("libevent: %s\n", msg);
373 else
374 LogPrint("libevent", "libevent: %s\n", msg);
377 bool InitHTTPServer()
379 struct evhttp* http = 0;
380 struct event_base* base = 0;
382 if (!InitHTTPAllowList())
383 return false;
385 if (GetBoolArg("-rpcssl", false)) {
386 uiInterface.ThreadSafeMessageBox(
387 "SSL mode for RPC (-rpcssl) is no longer supported.",
388 "", CClientUIInterface::MSG_ERROR);
389 return false;
392 // Redirect libevent's logging to our own log
393 event_set_log_callback(&libevent_log_cb);
394 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
395 // If -debug=libevent, set full libevent debugging.
396 // Otherwise, disable all libevent debugging.
397 if (LogAcceptCategory("libevent"))
398 event_enable_debug_logging(EVENT_DBG_ALL);
399 else
400 event_enable_debug_logging(EVENT_DBG_NONE);
401 #endif
402 #ifdef WIN32
403 evthread_use_windows_threads();
404 #else
405 evthread_use_pthreads();
406 #endif
408 base = event_base_new(); // XXX RAII
409 if (!base) {
410 LogPrintf("Couldn't create an event_base: exiting\n");
411 return false;
414 /* Create a new evhttp object to handle requests. */
415 http = evhttp_new(base); // XXX RAII
416 if (!http) {
417 LogPrintf("couldn't create evhttp. Exiting.\n");
418 event_base_free(base);
419 return false;
422 evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
423 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
424 evhttp_set_max_body_size(http, MAX_SIZE);
425 evhttp_set_gencb(http, http_request_cb, NULL);
427 if (!HTTPBindAddresses(http)) {
428 LogPrintf("Unable to bind any endpoint for RPC server\n");
429 evhttp_free(http);
430 event_base_free(base);
431 return false;
434 LogPrint("http", "Initialized HTTP server\n");
435 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
436 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
438 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
439 eventBase = base;
440 eventHTTP = http;
441 return true;
444 std::thread threadHTTP;
445 std::future<bool> threadResult;
447 bool StartHTTPServer()
449 LogPrint("http", "Starting HTTP server\n");
450 int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
451 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
452 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
453 threadResult = task.get_future();
454 threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
456 for (int i = 0; i < rpcThreads; i++) {
457 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
458 rpc_worker.detach();
460 return true;
463 void InterruptHTTPServer()
465 LogPrint("http", "Interrupting HTTP server\n");
466 if (eventHTTP) {
467 // Unlisten sockets
468 for (evhttp_bound_socket *socket : boundSockets) {
469 evhttp_del_accept_socket(eventHTTP, socket);
471 // Reject requests on current connections
472 evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
474 if (workQueue)
475 workQueue->Interrupt();
478 void StopHTTPServer()
480 LogPrint("http", "Stopping HTTP server\n");
481 if (workQueue) {
482 LogPrint("http", "Waiting for HTTP worker threads to exit\n");
483 workQueue->WaitExit();
484 delete workQueue;
486 if (eventBase) {
487 LogPrint("http", "Waiting for HTTP event thread to exit\n");
488 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
489 // Before this was solved with event_base_loopexit, but that didn't work as expected in
490 // at least libevent 2.0.21 and always introduced a delay. In libevent
491 // master that appears to be solved, so in the future that solution
492 // could be used again (if desirable).
493 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
494 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
495 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
496 event_base_loopbreak(eventBase);
498 threadHTTP.join();
500 if (eventHTTP) {
501 evhttp_free(eventHTTP);
502 eventHTTP = 0;
504 if (eventBase) {
505 event_base_free(eventBase);
506 eventBase = 0;
508 LogPrint("http", "Stopped HTTP server\n");
511 struct event_base* EventBase()
513 return eventBase;
516 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
518 // Static handler: simply call inner handler
519 HTTPEvent *self = ((HTTPEvent*)data);
520 self->handler();
521 if (self->deleteWhenTriggered)
522 delete self;
525 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
526 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
528 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
529 assert(ev);
531 HTTPEvent::~HTTPEvent()
533 event_free(ev);
535 void HTTPEvent::trigger(struct timeval* tv)
537 if (tv == NULL)
538 event_active(ev, 0, 0); // immediately trigger event in main thread
539 else
540 evtimer_add(ev, tv); // trigger after timeval passed
542 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
543 replySent(false)
546 HTTPRequest::~HTTPRequest()
548 if (!replySent) {
549 // Keep track of whether reply was sent to avoid request leaks
550 LogPrintf("%s: Unhandled request\n", __func__);
551 WriteReply(HTTP_INTERNAL, "Unhandled request");
553 // evhttpd cleans up the request, as long as a reply was sent.
556 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
558 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
559 assert(headers);
560 const char* val = evhttp_find_header(headers, hdr.c_str());
561 if (val)
562 return std::make_pair(true, val);
563 else
564 return std::make_pair(false, "");
567 std::string HTTPRequest::ReadBody()
569 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
570 if (!buf)
571 return "";
572 size_t size = evbuffer_get_length(buf);
573 /** Trivial implementation: if this is ever a performance bottleneck,
574 * internal copying can be avoided in multi-segment buffers by using
575 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
576 * better to not copy into an intermediate string but use a stream
577 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
579 const char* data = (const char*)evbuffer_pullup(buf, size);
580 if (!data) // returns NULL in case of empty buffer
581 return "";
582 std::string rv(data, size);
583 evbuffer_drain(buf, size);
584 return rv;
587 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
589 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
590 assert(headers);
591 evhttp_add_header(headers, hdr.c_str(), value.c_str());
594 /** Closure sent to main thread to request a reply to be sent to
595 * a HTTP request.
596 * Replies must be sent in the main loop in the main http thread,
597 * this cannot be done from worker threads.
599 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
601 assert(!replySent && req);
602 // Send event to main http thread to send reply message
603 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
604 assert(evb);
605 evbuffer_add(evb, strReply.data(), strReply.size());
606 HTTPEvent* ev = new HTTPEvent(eventBase, true,
607 std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
608 ev->trigger(0);
609 replySent = true;
610 req = 0; // transferred back to main thread
613 CService HTTPRequest::GetPeer()
615 evhttp_connection* con = evhttp_request_get_connection(req);
616 CService peer;
617 if (con) {
618 // evhttp retains ownership over returned address string
619 const char* address = "";
620 uint16_t port = 0;
621 evhttp_connection_get_peer(con, (char**)&address, &port);
622 peer = LookupNumeric(address, port);
624 return peer;
627 std::string HTTPRequest::GetURI()
629 return evhttp_request_get_uri(req);
632 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
634 switch (evhttp_request_get_command(req)) {
635 case EVHTTP_REQ_GET:
636 return GET;
637 break;
638 case EVHTTP_REQ_POST:
639 return POST;
640 break;
641 case EVHTTP_REQ_HEAD:
642 return HEAD;
643 break;
644 case EVHTTP_REQ_PUT:
645 return PUT;
646 break;
647 default:
648 return UNKNOWN;
649 break;
653 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
655 LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
656 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
659 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
661 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
662 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
663 for (; i != iend; ++i)
664 if (i->prefix == prefix && i->exactMatch == exactMatch)
665 break;
666 if (i != iend)
668 LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
669 pathHandlers.erase(i);