Update luke-jr's PGP key
[bitcoinplatinum.git] / src / httpserver.cpp
blob812940eaf9861305dc7f2bfc4e385740411ccd34
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>
23 #include <event2/event.h>
24 #include <event2/http.h>
25 #include <event2/thread.h>
26 #include <event2/buffer.h>
27 #include <event2/util.h>
28 #include <event2/keyvalq_struct.h>
30 #ifdef EVENT__HAVE_NETINET_IN_H
31 #include <netinet/in.h>
32 #ifdef _XOPEN_SOURCE_EXTENDED
33 #include <arpa/inet.h>
34 #endif
35 #endif
37 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
38 #include <boost/foreach.hpp>
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 : 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()()
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 CWaitableCriticalSection cs;
72 CConditionVariable 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 ThreadCounter(WorkQueue &w): wq(w)
85 boost::lock_guard<boost::mutex> lock(wq.cs);
86 wq.numThreads += 1;
88 ~ThreadCounter()
90 boost::lock_guard<boost::mutex> lock(wq.cs);
91 wq.numThreads -= 1;
92 wq.cond.notify_all();
96 public:
97 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 boost::unique_lock<boost::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 (running) {
124 std::unique_ptr<WorkItem> i;
126 boost::unique_lock<boost::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 boost::unique_lock<boost::mutex> lock(cs);
141 running = false;
142 cond.notify_all();
144 /** Wait for worker threads to exit */
145 void WaitExit()
147 boost::unique_lock<boost::mutex> lock(cs);
148 while (numThreads > 0)
149 cond.wait(lock);
152 /** Return current depth of queue */
153 size_t Depth()
155 boost::unique_lock<boost::mutex> lock(cs);
156 return queue.size();
160 struct HTTPPathHandler
162 HTTPPathHandler() {}
163 HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler):
164 prefix(prefix), exactMatch(exactMatch), handler(handler)
167 std::string prefix;
168 bool exactMatch;
169 HTTPRequestHandler handler;
172 /** HTTP module state */
174 //! libevent event loop
175 static struct event_base* eventBase = 0;
176 //! HTTP server
177 struct evhttp* eventHTTP = 0;
178 //! List of subnets to allow RPC connections from
179 static std::vector<CSubNet> rpc_allow_subnets;
180 //! Work queue for handling longer requests off the event loop thread
181 static WorkQueue<HTTPClosure>* workQueue = 0;
182 //! Handlers for (sub)paths
183 std::vector<HTTPPathHandler> pathHandlers;
184 //! Bound listening sockets
185 std::vector<evhttp_bound_socket *> boundSockets;
187 /** Check if a network address is allowed to access the HTTP server */
188 static bool ClientAllowed(const CNetAddr& netaddr)
190 if (!netaddr.IsValid())
191 return false;
192 BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
193 if (subnet.Match(netaddr))
194 return true;
195 return false;
198 /** Initialize ACL list for HTTP server */
199 static bool InitHTTPAllowList()
201 rpc_allow_subnets.clear();
202 rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
203 rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
204 if (mapMultiArgs.count("-rpcallowip")) {
205 const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
206 BOOST_FOREACH (std::string strAllow, vAllow) {
207 CSubNet subnet(strAllow);
208 if (!subnet.IsValid()) {
209 uiInterface.ThreadSafeMessageBox(
210 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),
211 "", CClientUIInterface::MSG_ERROR);
212 return false;
214 rpc_allow_subnets.push_back(subnet);
217 std::string strAllowed;
218 BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
219 strAllowed += subnet.ToString() + " ";
220 LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
221 return true;
224 /** HTTP request method as string - use for logging only */
225 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
227 switch (m) {
228 case HTTPRequest::GET:
229 return "GET";
230 break;
231 case HTTPRequest::POST:
232 return "POST";
233 break;
234 case HTTPRequest::HEAD:
235 return "HEAD";
236 break;
237 case HTTPRequest::PUT:
238 return "PUT";
239 break;
240 default:
241 return "unknown";
245 /** HTTP request callback */
246 static void http_request_cb(struct evhttp_request* req, void* arg)
248 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
250 LogPrint("http", "Received a %s request for %s from %s\n",
251 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
253 // Early address-based allow check
254 if (!ClientAllowed(hreq->GetPeer())) {
255 hreq->WriteReply(HTTP_FORBIDDEN);
256 return;
259 // Early reject unknown HTTP methods
260 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
261 hreq->WriteReply(HTTP_BADMETHOD);
262 return;
265 // Find registered handler for prefix
266 std::string strURI = hreq->GetURI();
267 std::string path;
268 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
269 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
270 for (; i != iend; ++i) {
271 bool match = false;
272 if (i->exactMatch)
273 match = (strURI == i->prefix);
274 else
275 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
276 if (match) {
277 path = strURI.substr(i->prefix.size());
278 break;
282 // Dispatch to worker thread
283 if (i != iend) {
284 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
285 assert(workQueue);
286 if (workQueue->Enqueue(item.get()))
287 item.release(); /* if true, queue took ownership */
288 else {
289 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
290 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
292 } else {
293 hreq->WriteReply(HTTP_NOTFOUND);
297 /** Callback to reject HTTP requests after shutdown. */
298 static void http_reject_request_cb(struct evhttp_request* req, void*)
300 LogPrint("http", "Rejecting request while shutting down\n");
301 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
304 /** Event dispatcher thread */
305 static void ThreadHTTP(struct event_base* base, struct evhttp* http)
307 RenameThread("bitcoin-http");
308 LogPrint("http", "Entering http event loop\n");
309 event_base_dispatch(base);
310 // Event loop will be interrupted by InterruptHTTPServer()
311 LogPrint("http", "Exited http event loop\n");
314 /** Bind HTTP server to specified addresses */
315 static bool HTTPBindAddresses(struct evhttp* http)
317 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
318 std::vector<std::pair<std::string, uint16_t> > endpoints;
320 // Determine what addresses to bind to
321 if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
322 endpoints.push_back(std::make_pair("::1", defaultPort));
323 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
324 if (mapArgs.count("-rpcbind")) {
325 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
327 } else if (mapArgs.count("-rpcbind")) { // Specific bind address
328 const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
329 for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
330 int port = defaultPort;
331 std::string host;
332 SplitHostPort(*i, port, host);
333 endpoints.push_back(std::make_pair(host, port));
335 } else { // No specific bind address specified, bind to any
336 endpoints.push_back(std::make_pair("::", defaultPort));
337 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
340 // Bind addresses
341 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
342 LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
343 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
344 if (bind_handle) {
345 boundSockets.push_back(bind_handle);
346 } else {
347 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
350 return !boundSockets.empty();
353 /** Simple wrapper to set thread name and run work queue */
354 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
356 RenameThread("bitcoin-httpworker");
357 queue->Run();
360 /** libevent event log callback */
361 static void libevent_log_cb(int severity, const char *msg)
363 #ifndef EVENT_LOG_WARN
364 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
365 # define EVENT_LOG_WARN _EVENT_LOG_WARN
366 #endif
367 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
368 LogPrintf("libevent: %s\n", msg);
369 else
370 LogPrint("libevent", "libevent: %s\n", msg);
373 bool InitHTTPServer()
375 struct evhttp* http = 0;
376 struct event_base* base = 0;
378 if (!InitHTTPAllowList())
379 return false;
381 if (GetBoolArg("-rpcssl", false)) {
382 uiInterface.ThreadSafeMessageBox(
383 "SSL mode for RPC (-rpcssl) is no longer supported.",
384 "", CClientUIInterface::MSG_ERROR);
385 return false;
388 // Redirect libevent's logging to our own log
389 event_set_log_callback(&libevent_log_cb);
390 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
391 // If -debug=libevent, set full libevent debugging.
392 // Otherwise, disable all libevent debugging.
393 if (LogAcceptCategory("libevent"))
394 event_enable_debug_logging(EVENT_DBG_ALL);
395 else
396 event_enable_debug_logging(EVENT_DBG_NONE);
397 #endif
398 #ifdef WIN32
399 evthread_use_windows_threads();
400 #else
401 evthread_use_pthreads();
402 #endif
404 base = event_base_new(); // XXX RAII
405 if (!base) {
406 LogPrintf("Couldn't create an event_base: exiting\n");
407 return false;
410 /* Create a new evhttp object to handle requests. */
411 http = evhttp_new(base); // XXX RAII
412 if (!http) {
413 LogPrintf("couldn't create evhttp. Exiting.\n");
414 event_base_free(base);
415 return false;
418 evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
419 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
420 evhttp_set_max_body_size(http, MAX_SIZE);
421 evhttp_set_gencb(http, http_request_cb, NULL);
423 if (!HTTPBindAddresses(http)) {
424 LogPrintf("Unable to bind any endpoint for RPC server\n");
425 evhttp_free(http);
426 event_base_free(base);
427 return false;
430 LogPrint("http", "Initialized HTTP server\n");
431 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
432 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
434 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
435 eventBase = base;
436 eventHTTP = http;
437 return true;
440 boost::thread threadHTTP;
442 bool StartHTTPServer()
444 LogPrint("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 threadHTTP = boost::thread(boost::bind(&ThreadHTTP, eventBase, eventHTTP));
449 for (int i = 0; i < rpcThreads; i++)
450 boost::thread(boost::bind(&HTTPWorkQueueRun, workQueue));
451 return true;
454 void InterruptHTTPServer()
456 LogPrint("http", "Interrupting HTTP server\n");
457 if (eventHTTP) {
458 // Unlisten sockets
459 BOOST_FOREACH (evhttp_bound_socket *socket, boundSockets) {
460 evhttp_del_accept_socket(eventHTTP, socket);
462 // Reject requests on current connections
463 evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
465 if (workQueue)
466 workQueue->Interrupt();
469 void StopHTTPServer()
471 LogPrint("http", "Stopping HTTP server\n");
472 if (workQueue) {
473 LogPrint("http", "Waiting for HTTP worker threads to exit\n");
474 workQueue->WaitExit();
475 delete workQueue;
477 if (eventBase) {
478 LogPrint("http", "Waiting for HTTP event thread to exit\n");
479 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
480 // Before this was solved with event_base_loopexit, but that didn't work as expected in
481 // at least libevent 2.0.21 and always introduced a delay. In libevent
482 // master that appears to be solved, so in the future that solution
483 // could be used again (if desirable).
484 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
485 #if BOOST_VERSION >= 105000
486 if (!threadHTTP.try_join_for(boost::chrono::milliseconds(2000))) {
487 #else
488 if (!threadHTTP.timed_join(boost::posix_time::milliseconds(2000))) {
489 #endif
490 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
491 event_base_loopbreak(eventBase);
492 threadHTTP.join();
495 if (eventHTTP) {
496 evhttp_free(eventHTTP);
497 eventHTTP = 0;
499 if (eventBase) {
500 event_base_free(eventBase);
501 eventBase = 0;
503 LogPrint("http", "Stopped HTTP server\n");
506 struct event_base* EventBase()
508 return eventBase;
511 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
513 // Static handler: simply call inner handler
514 HTTPEvent *self = ((HTTPEvent*)data);
515 self->handler();
516 if (self->deleteWhenTriggered)
517 delete self;
520 HTTPEvent::HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const boost::function<void(void)>& handler):
521 deleteWhenTriggered(deleteWhenTriggered), handler(handler)
523 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
524 assert(ev);
526 HTTPEvent::~HTTPEvent()
528 event_free(ev);
530 void HTTPEvent::trigger(struct timeval* tv)
532 if (tv == NULL)
533 event_active(ev, 0, 0); // immediately trigger event in main thread
534 else
535 evtimer_add(ev, tv); // trigger after timeval passed
537 HTTPRequest::HTTPRequest(struct evhttp_request* req) : req(req),
538 replySent(false)
541 HTTPRequest::~HTTPRequest()
543 if (!replySent) {
544 // Keep track of whether reply was sent to avoid request leaks
545 LogPrintf("%s: Unhandled request\n", __func__);
546 WriteReply(HTTP_INTERNAL, "Unhandled request");
548 // evhttpd cleans up the request, as long as a reply was sent.
551 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
553 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
554 assert(headers);
555 const char* val = evhttp_find_header(headers, hdr.c_str());
556 if (val)
557 return std::make_pair(true, val);
558 else
559 return std::make_pair(false, "");
562 std::string HTTPRequest::ReadBody()
564 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
565 if (!buf)
566 return "";
567 size_t size = evbuffer_get_length(buf);
568 /** Trivial implementation: if this is ever a performance bottleneck,
569 * internal copying can be avoided in multi-segment buffers by using
570 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
571 * better to not copy into an intermediate string but use a stream
572 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
574 const char* data = (const char*)evbuffer_pullup(buf, size);
575 if (!data) // returns NULL in case of empty buffer
576 return "";
577 std::string rv(data, size);
578 evbuffer_drain(buf, size);
579 return rv;
582 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
584 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
585 assert(headers);
586 evhttp_add_header(headers, hdr.c_str(), value.c_str());
589 /** Closure sent to main thread to request a reply to be sent to
590 * a HTTP request.
591 * Replies must be sent in the main loop in the main http thread,
592 * this cannot be done from worker threads.
594 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
596 assert(!replySent && req);
597 // Send event to main http thread to send reply message
598 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
599 assert(evb);
600 evbuffer_add(evb, strReply.data(), strReply.size());
601 HTTPEvent* ev = new HTTPEvent(eventBase, true,
602 boost::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
603 ev->trigger(0);
604 replySent = true;
605 req = 0; // transferred back to main thread
608 CService HTTPRequest::GetPeer()
610 evhttp_connection* con = evhttp_request_get_connection(req);
611 CService peer;
612 if (con) {
613 // evhttp retains ownership over returned address string
614 const char* address = "";
615 uint16_t port = 0;
616 evhttp_connection_get_peer(con, (char**)&address, &port);
617 peer = CService(address, port);
619 return peer;
622 std::string HTTPRequest::GetURI()
624 return evhttp_request_get_uri(req);
627 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
629 switch (evhttp_request_get_command(req)) {
630 case EVHTTP_REQ_GET:
631 return GET;
632 break;
633 case EVHTTP_REQ_POST:
634 return POST;
635 break;
636 case EVHTTP_REQ_HEAD:
637 return HEAD;
638 break;
639 case EVHTTP_REQ_PUT:
640 return PUT;
641 break;
642 default:
643 return UNKNOWN;
644 break;
648 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
650 LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
651 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
654 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
656 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
657 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
658 for (; i != iend; ++i)
659 if (i->prefix == prefix && i->exactMatch == exactMatch)
660 break;
661 if (i != iend)
663 LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
664 pathHandlers.erase(i);