[Qt] hide bump context menu action if tx already has been bumped
[bitcoinplatinum.git] / src / httpserver.cpp
blob0d1cba3fd2bddb728475cfedc873c09b7a8655f2
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 (gArgs.IsArgSet("-rpcallowip")) {
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);
212 std::string strAllowed;
213 for (const CSubNet& subnet : rpc_allow_subnets)
214 strAllowed += subnet.ToString() + " ";
215 LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
216 return true;
219 /** HTTP request method as string - use for logging only */
220 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
222 switch (m) {
223 case HTTPRequest::GET:
224 return "GET";
225 break;
226 case HTTPRequest::POST:
227 return "POST";
228 break;
229 case HTTPRequest::HEAD:
230 return "HEAD";
231 break;
232 case HTTPRequest::PUT:
233 return "PUT";
234 break;
235 default:
236 return "unknown";
240 /** HTTP request callback */
241 static void http_request_cb(struct evhttp_request* req, void* arg)
243 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
245 LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
246 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
248 // Early address-based allow check
249 if (!ClientAllowed(hreq->GetPeer())) {
250 hreq->WriteReply(HTTP_FORBIDDEN);
251 return;
254 // Early reject unknown HTTP methods
255 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
256 hreq->WriteReply(HTTP_BADMETHOD);
257 return;
260 // Find registered handler for prefix
261 std::string strURI = hreq->GetURI();
262 std::string path;
263 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
264 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
265 for (; i != iend; ++i) {
266 bool match = false;
267 if (i->exactMatch)
268 match = (strURI == i->prefix);
269 else
270 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
271 if (match) {
272 path = strURI.substr(i->prefix.size());
273 break;
277 // Dispatch to worker thread
278 if (i != iend) {
279 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
280 assert(workQueue);
281 if (workQueue->Enqueue(item.get()))
282 item.release(); /* if true, queue took ownership */
283 else {
284 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
285 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
287 } else {
288 hreq->WriteReply(HTTP_NOTFOUND);
292 /** Callback to reject HTTP requests after shutdown. */
293 static void http_reject_request_cb(struct evhttp_request* req, void*)
295 LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
296 evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
299 /** Event dispatcher thread */
300 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
302 RenameThread("bitcoin-http");
303 LogPrint(BCLog::HTTP, "Entering http event loop\n");
304 event_base_dispatch(base);
305 // Event loop will be interrupted by InterruptHTTPServer()
306 LogPrint(BCLog::HTTP, "Exited http event loop\n");
307 return event_base_got_break(base) == 0;
310 /** Bind HTTP server to specified addresses */
311 static bool HTTPBindAddresses(struct evhttp* http)
313 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
314 std::vector<std::pair<std::string, uint16_t> > endpoints;
316 // Determine what addresses to bind to
317 if (!IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
318 endpoints.push_back(std::make_pair("::1", defaultPort));
319 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
320 if (IsArgSet("-rpcbind")) {
321 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
323 } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
324 for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
325 int port = defaultPort;
326 std::string host;
327 SplitHostPort(strRPCBind, port, host);
328 endpoints.push_back(std::make_pair(host, port));
330 } else { // No specific bind address specified, bind to any
331 endpoints.push_back(std::make_pair("::", defaultPort));
332 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
335 // Bind addresses
336 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
337 LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
338 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
339 if (bind_handle) {
340 boundSockets.push_back(bind_handle);
341 } else {
342 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
345 return !boundSockets.empty();
348 /** Simple wrapper to set thread name and run work queue */
349 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
351 RenameThread("bitcoin-httpworker");
352 queue->Run();
355 /** libevent event log callback */
356 static void libevent_log_cb(int severity, const char *msg)
358 #ifndef EVENT_LOG_WARN
359 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
360 # define EVENT_LOG_WARN _EVENT_LOG_WARN
361 #endif
362 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
363 LogPrintf("libevent: %s\n", msg);
364 else
365 LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
368 bool InitHTTPServer()
370 struct evhttp* http = 0;
371 struct event_base* base = 0;
373 if (!InitHTTPAllowList())
374 return false;
376 if (GetBoolArg("-rpcssl", false)) {
377 uiInterface.ThreadSafeMessageBox(
378 "SSL mode for RPC (-rpcssl) is no longer supported.",
379 "", CClientUIInterface::MSG_ERROR);
380 return false;
383 // Redirect libevent's logging to our own log
384 event_set_log_callback(&libevent_log_cb);
385 // Update libevent's log handling. Returns false if our version of
386 // libevent doesn't support debug logging, in which case we should
387 // clear the BCLog::LIBEVENT flag.
388 if (!UpdateHTTPServerLogging(logCategories & BCLog::LIBEVENT)) {
389 logCategories &= ~BCLog::LIBEVENT;
392 #ifdef WIN32
393 evthread_use_windows_threads();
394 #else
395 evthread_use_pthreads();
396 #endif
398 base = event_base_new(); // XXX RAII
399 if (!base) {
400 LogPrintf("Couldn't create an event_base: exiting\n");
401 return false;
404 /* Create a new evhttp object to handle requests. */
405 http = evhttp_new(base); // XXX RAII
406 if (!http) {
407 LogPrintf("couldn't create evhttp. Exiting.\n");
408 event_base_free(base);
409 return false;
412 evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
413 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
414 evhttp_set_max_body_size(http, MAX_SIZE);
415 evhttp_set_gencb(http, http_request_cb, NULL);
417 if (!HTTPBindAddresses(http)) {
418 LogPrintf("Unable to bind any endpoint for RPC server\n");
419 evhttp_free(http);
420 event_base_free(base);
421 return false;
424 LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
425 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
426 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
428 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
429 eventBase = base;
430 eventHTTP = http;
431 return true;
434 bool UpdateHTTPServerLogging(bool enable) {
435 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
436 if (enable) {
437 event_enable_debug_logging(EVENT_DBG_ALL);
438 } else {
439 event_enable_debug_logging(EVENT_DBG_NONE);
441 return true;
442 #else
443 // Can't update libevent logging if version < 02010100
444 return false;
445 #endif
448 std::thread threadHTTP;
449 std::future<bool> threadResult;
451 bool StartHTTPServer()
453 LogPrint(BCLog::HTTP, "Starting HTTP server\n");
454 int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
455 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
456 std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
457 threadResult = task.get_future();
458 threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
460 for (int i = 0; i < rpcThreads; i++) {
461 std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
462 rpc_worker.detach();
464 return true;
467 void InterruptHTTPServer()
469 LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
470 if (eventHTTP) {
471 // Unlisten sockets
472 for (evhttp_bound_socket *socket : boundSockets) {
473 evhttp_del_accept_socket(eventHTTP, socket);
475 // Reject requests on current connections
476 evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
478 if (workQueue)
479 workQueue->Interrupt();
482 void StopHTTPServer()
484 LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
485 if (workQueue) {
486 LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
487 workQueue->WaitExit();
488 delete workQueue;
489 workQueue = nullptr;
491 if (eventBase) {
492 LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
493 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
494 // Before this was solved with event_base_loopexit, but that didn't work as expected in
495 // at least libevent 2.0.21 and always introduced a delay. In libevent
496 // master that appears to be solved, so in the future that solution
497 // could be used again (if desirable).
498 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
499 if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
500 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
501 event_base_loopbreak(eventBase);
503 threadHTTP.join();
505 if (eventHTTP) {
506 evhttp_free(eventHTTP);
507 eventHTTP = 0;
509 if (eventBase) {
510 event_base_free(eventBase);
511 eventBase = 0;
513 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
516 struct event_base* EventBase()
518 return eventBase;
521 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
523 // Static handler: simply call inner handler
524 HTTPEvent *self = ((HTTPEvent*)data);
525 self->handler();
526 if (self->deleteWhenTriggered)
527 delete self;
530 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void(void)>& _handler):
531 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
533 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
534 assert(ev);
536 HTTPEvent::~HTTPEvent()
538 event_free(ev);
540 void HTTPEvent::trigger(struct timeval* tv)
542 if (tv == NULL)
543 event_active(ev, 0, 0); // immediately trigger event in main thread
544 else
545 evtimer_add(ev, tv); // trigger after timeval passed
547 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
548 replySent(false)
551 HTTPRequest::~HTTPRequest()
553 if (!replySent) {
554 // Keep track of whether reply was sent to avoid request leaks
555 LogPrintf("%s: Unhandled request\n", __func__);
556 WriteReply(HTTP_INTERNAL, "Unhandled request");
558 // evhttpd cleans up the request, as long as a reply was sent.
561 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
563 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
564 assert(headers);
565 const char* val = evhttp_find_header(headers, hdr.c_str());
566 if (val)
567 return std::make_pair(true, val);
568 else
569 return std::make_pair(false, "");
572 std::string HTTPRequest::ReadBody()
574 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
575 if (!buf)
576 return "";
577 size_t size = evbuffer_get_length(buf);
578 /** Trivial implementation: if this is ever a performance bottleneck,
579 * internal copying can be avoided in multi-segment buffers by using
580 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
581 * better to not copy into an intermediate string but use a stream
582 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
584 const char* data = (const char*)evbuffer_pullup(buf, size);
585 if (!data) // returns NULL in case of empty buffer
586 return "";
587 std::string rv(data, size);
588 evbuffer_drain(buf, size);
589 return rv;
592 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
594 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
595 assert(headers);
596 evhttp_add_header(headers, hdr.c_str(), value.c_str());
599 /** Closure sent to main thread to request a reply to be sent to
600 * a HTTP request.
601 * Replies must be sent in the main loop in the main http thread,
602 * this cannot be done from worker threads.
604 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
606 assert(!replySent && req);
607 // Send event to main http thread to send reply message
608 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
609 assert(evb);
610 evbuffer_add(evb, strReply.data(), strReply.size());
611 HTTPEvent* ev = new HTTPEvent(eventBase, true,
612 std::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
613 ev->trigger(0);
614 replySent = true;
615 req = 0; // transferred back to main thread
618 CService HTTPRequest::GetPeer()
620 evhttp_connection* con = evhttp_request_get_connection(req);
621 CService peer;
622 if (con) {
623 // evhttp retains ownership over returned address string
624 const char* address = "";
625 uint16_t port = 0;
626 evhttp_connection_get_peer(con, (char**)&address, &port);
627 peer = LookupNumeric(address, port);
629 return peer;
632 std::string HTTPRequest::GetURI()
634 return evhttp_request_get_uri(req);
637 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
639 switch (evhttp_request_get_command(req)) {
640 case EVHTTP_REQ_GET:
641 return GET;
642 break;
643 case EVHTTP_REQ_POST:
644 return POST;
645 break;
646 case EVHTTP_REQ_HEAD:
647 return HEAD;
648 break;
649 case EVHTTP_REQ_PUT:
650 return PUT;
651 break;
652 default:
653 return UNKNOWN;
654 break;
658 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
660 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
661 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
664 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
666 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
667 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
668 for (; i != iend; ++i)
669 if (i->prefix == prefix && i->exactMatch == exactMatch)
670 break;
671 if (i != iend)
673 LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
674 pathHandlers.erase(i);