Fix parameter naming inconsistencies between .h and .cpp files
[bitcoinplatinum.git] / src / httpserver.cpp
blobdbd08ff2e10c4b70c62611bdd3f1b13e8408d54d
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 "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 (true) {
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);
151 struct HTTPPathHandler
153 HTTPPathHandler() {}
154 HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
155 prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
158 std::string prefix;
159 bool exactMatch;
160 HTTPRequestHandler handler;
163 /** HTTP module state */
165 //! libevent event loop
166 static struct event_base* eventBase = 0;
167 //! HTTP server
168 struct evhttp* eventHTTP = 0;
169 //! List of subnets to allow RPC connections from
170 static std::vector<CSubNet> rpc_allow_subnets;
171 //! Work queue for handling longer requests off the event loop thread
172 static WorkQueue<HTTPClosure>* workQueue = 0;
173 //! Handlers for (sub)paths
174 std::vector<HTTPPathHandler> pathHandlers;
175 //! Bound listening sockets
176 std::vector<evhttp_bound_socket *> boundSockets;
178 /** Check if a network address is allowed to access the HTTP server */
179 static bool ClientAllowed(const CNetAddr& netaddr)
181 if (!netaddr.IsValid())
182 return false;
183 for(const CSubNet& subnet : rpc_allow_subnets)
184 if (subnet.Match(netaddr))
185 return true;
186 return false;
189 /** Initialize ACL list for HTTP server */
190 static bool InitHTTPAllowList()
192 rpc_allow_subnets.clear();
193 CNetAddr localv4;
194 CNetAddr localv6;
195 LookupHost("127.0.0.1", localv4, false);
196 LookupHost("::1", localv6, false);
197 rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
198 rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
199 if (mapMultiArgs.count("-rpcallowip")) {
200 const std::vector<std::string>& vAllow = mapMultiArgs.at("-rpcallowip");
201 for (std::string strAllow : vAllow) {
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);
213 std::string strAllowed;
214 for (const CSubNet& subnet : rpc_allow_subnets)
215 strAllowed += subnet.ToString() + " ";
216 LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
217 return true;
220 /** HTTP request method as string - use for logging only */
221 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
223 switch (m) {
224 case HTTPRequest::GET:
225 return "GET";
226 break;
227 case HTTPRequest::POST:
228 return "POST";
229 break;
230 case HTTPRequest::HEAD:
231 return "HEAD";
232 break;
233 case HTTPRequest::PUT:
234 return "PUT";
235 break;
236 default:
237 return "unknown";
241 /** HTTP request callback */
242 static void http_request_cb(struct evhttp_request* req, void* arg)
244 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
246 LogPrint("http", "Received a %s request for %s from %s\n",
247 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
249 // Early address-based allow check
250 if (!ClientAllowed(hreq->GetPeer())) {
251 hreq->WriteReply(HTTP_FORBIDDEN);
252 return;
255 // Early reject unknown HTTP methods
256 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
257 hreq->WriteReply(HTTP_BADMETHOD);
258 return;
261 // Find registered handler for prefix
262 std::string strURI = hreq->GetURI();
263 std::string path;
264 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
265 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
266 for (; i != iend; ++i) {
267 bool match = false;
268 if (i->exactMatch)
269 match = (strURI == i->prefix);
270 else
271 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
272 if (match) {
273 path = strURI.substr(i->prefix.size());
274 break;
278 // Dispatch to worker thread
279 if (i != iend) {
280 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
281 assert(workQueue);
282 if (workQueue->Enqueue(item.get()))
283 item.release(); /* if true, queue took ownership */
284 else {
285 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
286 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
288 } else {
289 hreq->WriteReply(HTTP_NOTFOUND);
293 /** Callback to reject HTTP requests after shutdown. */
294 static void http_reject_request_cb(struct evhttp_request* req, void*)
296 LogPrint("http", "Rejecting request while shutting down\n");
297 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
300 /** Event dispatcher thread */
301 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
303 RenameThread("bitcoin-http");
304 LogPrint("http", "Entering http event loop\n");
305 event_base_dispatch(base);
306 // Event loop will be interrupted by InterruptHTTPServer()
307 LogPrint("http", "Exited http event loop\n");
308 return event_base_got_break(base) == 0;
311 /** Bind HTTP server to specified addresses */
312 static bool HTTPBindAddresses(struct evhttp* http)
314 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
315 std::vector<std::pair<std::string, uint16_t> > endpoints;
317 // Determine what addresses to bind to
318 if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
319 endpoints.push_back(std::make_pair("::1", defaultPort));
320 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
321 if (IsArgSet("-rpcbind")) {
322 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
324 } else if (mapMultiArgs.count("-rpcbind")) { // Specific bind address
325 const std::vector<std::string>& vbind = mapMultiArgs.at("-rpcbind");
326 for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
327 int port = defaultPort;
328 std::string host;
329 SplitHostPort(*i, port, host);
330 endpoints.push_back(std::make_pair(host, port));
332 } else { // No specific bind address specified, bind to any
333 endpoints.push_back(std::make_pair("::", defaultPort));
334 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
337 // Bind addresses
338 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
339 LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
340 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
341 if (bind_handle) {
342 boundSockets.push_back(bind_handle);
343 } else {
344 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
347 return !boundSockets.empty();
350 /** Simple wrapper to set thread name and run work queue */
351 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
353 RenameThread("bitcoin-httpworker");
354 queue->Run();
357 /** libevent event log callback */
358 static void libevent_log_cb(int severity, const char *msg)
360 #ifndef EVENT_LOG_WARN
361 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
362 # define EVENT_LOG_WARN _EVENT_LOG_WARN
363 #endif
364 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
365 LogPrintf("libevent: %s\n", msg);
366 else
367 LogPrint("libevent", "libevent: %s\n", msg);
370 bool InitHTTPServer()
372 struct evhttp* http = 0;
373 struct event_base* base = 0;
375 if (!InitHTTPAllowList())
376 return false;
378 if (GetBoolArg("-rpcssl", false)) {
379 uiInterface.ThreadSafeMessageBox(
380 "SSL mode for RPC (-rpcssl) is no longer supported.",
381 "", CClientUIInterface::MSG_ERROR);
382 return false;
385 // Redirect libevent's logging to our own log
386 event_set_log_callback(&libevent_log_cb);
387 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
388 // If -debug=libevent, set full libevent debugging.
389 // Otherwise, disable all libevent debugging.
390 if (LogAcceptCategory("libevent"))
391 event_enable_debug_logging(EVENT_DBG_ALL);
392 else
393 event_enable_debug_logging(EVENT_DBG_NONE);
394 #endif
395 #ifdef WIN32
396 evthread_use_windows_threads();
397 #else
398 evthread_use_pthreads();
399 #endif
401 base = event_base_new(); // XXX RAII
402 if (!base) {
403 LogPrintf("Couldn't create an event_base: exiting\n");
404 return false;
407 /* Create a new evhttp object to handle requests. */
408 http = evhttp_new(base); // XXX RAII
409 if (!http) {
410 LogPrintf("couldn't create evhttp. Exiting.\n");
411 event_base_free(base);
412 return false;
415 evhttp_set_timeout(http, 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, NULL);
420 if (!HTTPBindAddresses(http)) {
421 LogPrintf("Unable to bind any endpoint for RPC server\n");
422 evhttp_free(http);
423 event_base_free(base);
424 return false;
427 LogPrint("http", "Initialized HTTP server\n");
428 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
429 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
431 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
432 eventBase = base;
433 eventHTTP = http;
434 return true;
437 std::thread threadHTTP;
438 std::future<bool> threadResult;
440 bool StartHTTPServer()
442 LogPrint("http", "Starting HTTP server\n");
443 int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
444 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
445 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
446 threadResult = task.get_future();
447 threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
449 for (int i = 0; i < rpcThreads; i++) {
450 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
451 rpc_worker.detach();
453 return true;
456 void InterruptHTTPServer()
458 LogPrint("http", "Interrupting HTTP server\n");
459 if (eventHTTP) {
460 // Unlisten sockets
461 for (evhttp_bound_socket *socket : boundSockets) {
462 evhttp_del_accept_socket(eventHTTP, socket);
464 // Reject requests on current connections
465 evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
467 if (workQueue)
468 workQueue->Interrupt();
471 void StopHTTPServer()
473 LogPrint("http", "Stopping HTTP server\n");
474 if (workQueue) {
475 LogPrint("http", "Waiting for HTTP worker threads to exit\n");
476 workQueue->WaitExit();
477 delete workQueue;
479 if (eventBase) {
480 LogPrint("http", "Waiting for HTTP event thread to exit\n");
481 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
482 // Before this was solved with event_base_loopexit, but that didn't work as expected in
483 // at least libevent 2.0.21 and always introduced a delay. In libevent
484 // master that appears to be solved, so in the future that solution
485 // could be used again (if desirable).
486 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
487 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
488 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
489 event_base_loopbreak(eventBase);
491 threadHTTP.join();
493 if (eventHTTP) {
494 evhttp_free(eventHTTP);
495 eventHTTP = 0;
497 if (eventBase) {
498 event_base_free(eventBase);
499 eventBase = 0;
501 LogPrint("http", "Stopped HTTP server\n");
504 struct event_base* EventBase()
506 return eventBase;
509 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
511 // Static handler: simply call inner handler
512 HTTPEvent *self = ((HTTPEvent*)data);
513 self->handler();
514 if (self->deleteWhenTriggered)
515 delete self;
518 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
519 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
521 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
522 assert(ev);
524 HTTPEvent::~HTTPEvent()
526 event_free(ev);
528 void HTTPEvent::trigger(struct timeval* tv)
530 if (tv == NULL)
531 event_active(ev, 0, 0); // immediately trigger event in main thread
532 else
533 evtimer_add(ev, tv); // trigger after timeval passed
535 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
536 replySent(false)
539 HTTPRequest::~HTTPRequest()
541 if (!replySent) {
542 // Keep track of whether reply was sent to avoid request leaks
543 LogPrintf("%s: Unhandled request\n", __func__);
544 WriteReply(HTTP_INTERNAL, "Unhandled request");
546 // evhttpd cleans up the request, as long as a reply was sent.
549 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
551 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
552 assert(headers);
553 const char* val = evhttp_find_header(headers, hdr.c_str());
554 if (val)
555 return std::make_pair(true, val);
556 else
557 return std::make_pair(false, "");
560 std::string HTTPRequest::ReadBody()
562 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
563 if (!buf)
564 return "";
565 size_t size = evbuffer_get_length(buf);
566 /** Trivial implementation: if this is ever a performance bottleneck,
567 * internal copying can be avoided in multi-segment buffers by using
568 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
569 * better to not copy into an intermediate string but use a stream
570 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
572 const char* data = (const char*)evbuffer_pullup(buf, size);
573 if (!data) // returns NULL in case of empty buffer
574 return "";
575 std::string rv(data, size);
576 evbuffer_drain(buf, size);
577 return rv;
580 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
582 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
583 assert(headers);
584 evhttp_add_header(headers, hdr.c_str(), value.c_str());
587 /** Closure sent to main thread to request a reply to be sent to
588 * a HTTP request.
589 * Replies must be sent in the main loop in the main http thread,
590 * this cannot be done from worker threads.
592 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
594 assert(!replySent && req);
595 // Send event to main http thread to send reply message
596 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
597 assert(evb);
598 evbuffer_add(evb, strReply.data(), strReply.size());
599 HTTPEvent* ev = new HTTPEvent(eventBase, true,
600 std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
601 ev->trigger(0);
602 replySent = true;
603 req = 0; // transferred back to main thread
606 CService HTTPRequest::GetPeer()
608 evhttp_connection* con = evhttp_request_get_connection(req);
609 CService peer;
610 if (con) {
611 // evhttp retains ownership over returned address string
612 const char* address = "";
613 uint16_t port = 0;
614 evhttp_connection_get_peer(con, (char**)&address, &port);
615 peer = LookupNumeric(address, port);
617 return peer;
620 std::string HTTPRequest::GetURI()
622 return evhttp_request_get_uri(req);
625 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
627 switch (evhttp_request_get_command(req)) {
628 case EVHTTP_REQ_GET:
629 return GET;
630 break;
631 case EVHTTP_REQ_POST:
632 return POST;
633 break;
634 case EVHTTP_REQ_HEAD:
635 return HEAD;
636 break;
637 case EVHTTP_REQ_PUT:
638 return PUT;
639 break;
640 default:
641 return UNKNOWN;
642 break;
646 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
648 LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
649 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
652 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
654 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
655 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
656 for (; i != iend; ++i)
657 if (i->prefix == prefix && i->exactMatch == exactMatch)
658 break;
659 if (i != iend)
661 LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
662 pathHandlers.erase(i);