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"
11 #include "rpcprotocol.h" // For HTTP status codes
13 #include "ui_interface.h"
19 #include <sys/types.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>
37 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
38 #include <boost/foreach.hpp>
39 #include <boost/scoped_ptr.hpp>
41 /** HTTP request work item */
42 class HTTPWorkItem : public HTTPClosure
45 HTTPWorkItem(HTTPRequest* req, const std::string &path, const HTTPRequestHandler& func):
46 req(req), path(path), func(func)
51 func(req.get(), path);
54 boost::scoped_ptr<HTTPRequest> req;
58 HTTPRequestHandler func;
61 /** Simple work queue for distributing work over multiple threads.
62 * Work items are simply callable objects.
64 template <typename WorkItem>
68 /** Mutex protects entire object */
69 CWaitableCriticalSection cs;
70 CConditionVariable cond;
71 /* XXX in C++11 we can use std::unique_ptr here and avoid manual cleanup */
72 std::deque<WorkItem*> queue;
77 WorkQueue(size_t maxDepth) : running(true),
81 /* Precondition: worker threads have all stopped */
84 while (!queue.empty()) {
89 /** Enqueue a work item */
90 bool Enqueue(WorkItem* item)
92 boost::unique_lock<boost::mutex> lock(cs);
93 if (queue.size() >= maxDepth) {
96 queue.push_back(item);
100 /** Thread function */
106 boost::unique_lock<boost::mutex> lock(cs);
107 while (running && queue.empty())
118 /** Interrupt and exit loops */
121 boost::unique_lock<boost::mutex> lock(cs);
126 /** Return current depth of queue */
129 boost::unique_lock<boost::mutex> lock(cs);
134 struct HTTPPathHandler
137 HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler):
138 prefix(prefix), exactMatch(exactMatch), handler(handler)
143 HTTPRequestHandler handler;
146 /** HTTP module state */
148 //! libevent event loop
149 static struct event_base* eventBase = 0;
151 struct evhttp* eventHTTP = 0;
152 //! List of subnets to allow RPC connections from
153 static std::vector<CSubNet> rpc_allow_subnets;
154 //! Work queue for handling longer requests off the event loop thread
155 static WorkQueue<HTTPClosure>* workQueue = 0;
156 //! Handlers for (sub)paths
157 std::vector<HTTPPathHandler> pathHandlers;
159 /** Check if a network address is allowed to access the HTTP server */
160 static bool ClientAllowed(const CNetAddr& netaddr)
162 if (!netaddr.IsValid())
164 BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
165 if (subnet.Match(netaddr))
170 /** Initialize ACL list for HTTP server */
171 static bool InitHTTPAllowList()
173 rpc_allow_subnets.clear();
174 rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
175 rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
176 if (mapMultiArgs.count("-rpcallowip")) {
177 const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
178 BOOST_FOREACH (std::string strAllow, vAllow) {
179 CSubNet subnet(strAllow);
180 if (!subnet.IsValid()) {
181 uiInterface.ThreadSafeMessageBox(
182 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),
183 "", CClientUIInterface::MSG_ERROR);
186 rpc_allow_subnets.push_back(subnet);
189 std::string strAllowed;
190 BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets)
191 strAllowed += subnet.ToString() + " ";
192 LogPrint("http", "Allowing HTTP connections from: %s\n", strAllowed);
196 /** HTTP request method as string - use for logging only */
197 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
200 case HTTPRequest::GET:
203 case HTTPRequest::POST:
206 case HTTPRequest::HEAD:
209 case HTTPRequest::PUT:
217 /** HTTP request callback */
218 static void http_request_cb(struct evhttp_request* req, void* arg)
220 std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
222 LogPrint("http", "Received a %s request for %s from %s\n",
223 RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
225 // Early address-based allow check
226 if (!ClientAllowed(hreq->GetPeer())) {
227 hreq->WriteReply(HTTP_FORBIDDEN);
231 // Early reject unknown HTTP methods
232 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
233 hreq->WriteReply(HTTP_BADMETHOD);
237 // Find registered handler for prefix
238 std::string strURI = hreq->GetURI();
240 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
241 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
242 for (; i != iend; ++i) {
245 match = (strURI == i->prefix);
247 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
249 path = strURI.substr(i->prefix.size());
254 // Dispatch to worker thread
256 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(hreq.release(), path, i->handler));
258 if (workQueue->Enqueue(item.get()))
259 item.release(); /* if true, queue took ownership */
261 item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
263 hreq->WriteReply(HTTP_NOTFOUND);
267 /** Event dispatcher thread */
268 static void ThreadHTTP(struct event_base* base, struct evhttp* http)
270 RenameThread("bitcoin-http");
271 LogPrint("http", "Entering http event loop\n");
272 event_base_dispatch(base);
273 // Event loop will be interrupted by InterruptHTTPServer()
274 LogPrint("http", "Exited http event loop\n");
277 /** Bind HTTP server to specified addresses */
278 static bool HTTPBindAddresses(struct evhttp* http)
280 int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
282 std::vector<std::pair<std::string, uint16_t> > endpoints;
284 // Determine what addresses to bind to
285 if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
286 endpoints.push_back(std::make_pair("::1", defaultPort));
287 endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
288 if (mapArgs.count("-rpcbind")) {
289 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
291 } else if (mapArgs.count("-rpcbind")) { // Specific bind address
292 const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
293 for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
294 int port = defaultPort;
296 SplitHostPort(*i, port, host);
297 endpoints.push_back(std::make_pair(host, port));
299 } else { // No specific bind address specified, bind to any
300 endpoints.push_back(std::make_pair("::", defaultPort));
301 endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
305 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
306 LogPrint("http", "Binding RPC on address %s port %i\n", i->first, i->second);
307 if (evhttp_bind_socket(http, i->first.empty() ? NULL : i->first.c_str(), i->second) == 0) {
310 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
316 /** Simple wrapper to set thread name and run work queue */
317 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
319 RenameThread("bitcoin-httpworker");
323 /** libevent event log callback */
324 static void libevent_log_cb(int severity, const char *msg)
326 #ifndef EVENT_LOG_WARN
327 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
328 # define EVENT_LOG_WARN _EVENT_LOG_WARN
330 if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
331 LogPrintf("libevent: %s\n", msg);
333 LogPrint("libevent", "libevent: %s\n", msg);
336 bool InitHTTPServer()
338 struct evhttp* http = 0;
339 struct event_base* base = 0;
341 if (!InitHTTPAllowList())
344 if (GetBoolArg("-rpcssl", false)) {
345 uiInterface.ThreadSafeMessageBox(
346 "SSL mode for RPC (-rpcssl) is no longer supported.",
347 "", CClientUIInterface::MSG_ERROR);
351 // Redirect libevent's logging to our own log
352 event_set_log_callback(&libevent_log_cb);
353 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
354 // If -debug=libevent, set full libevent debugging.
355 // Otherwise, disable all libevent debugging.
356 if (LogAcceptCategory("libevent"))
357 event_enable_debug_logging(EVENT_DBG_ALL);
359 event_enable_debug_logging(EVENT_DBG_NONE);
362 evthread_use_windows_threads();
364 evthread_use_pthreads();
367 base = event_base_new(); // XXX RAII
369 LogPrintf("Couldn't create an event_base: exiting\n");
373 /* Create a new evhttp object to handle requests. */
374 http = evhttp_new(base); // XXX RAII
376 LogPrintf("couldn't create evhttp. Exiting.\n");
377 event_base_free(base);
381 evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
382 evhttp_set_max_body_size(http, MAX_SIZE);
383 evhttp_set_gencb(http, http_request_cb, NULL);
385 if (!HTTPBindAddresses(http)) {
386 LogPrintf("Unable to bind any endpoint for RPC server\n");
388 event_base_free(base);
392 LogPrint("http", "Initialized HTTP server\n");
393 int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
394 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
396 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
402 bool StartHTTPServer(boost::thread_group& threadGroup)
404 LogPrint("http", "Starting HTTP server\n");
405 int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
406 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
407 threadGroup.create_thread(boost::bind(&ThreadHTTP, eventBase, eventHTTP));
409 for (int i = 0; i < rpcThreads; i++)
410 threadGroup.create_thread(boost::bind(&HTTPWorkQueueRun, workQueue));
414 void InterruptHTTPServer()
416 LogPrint("http", "Interrupting HTTP server\n");
418 event_base_loopbreak(eventBase);
420 workQueue->Interrupt();
423 void StopHTTPServer()
425 LogPrint("http", "Stopping HTTP server\n");
428 evhttp_free(eventHTTP);
432 event_base_free(eventBase);
437 struct event_base* EventBase()
442 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
444 // Static handler: simply call inner handler
445 HTTPEvent *self = ((HTTPEvent*)data);
447 if (self->deleteWhenTriggered)
451 HTTPEvent::HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const boost::function<void(void)>& handler):
452 deleteWhenTriggered(deleteWhenTriggered), handler(handler)
454 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
457 HTTPEvent::~HTTPEvent()
461 void HTTPEvent::trigger(struct timeval* tv)
464 event_active(ev, 0, 0); // immediately trigger event in main thread
466 evtimer_add(ev, tv); // trigger after timeval passed
468 HTTPRequest::HTTPRequest(struct evhttp_request* req) : req(req),
472 HTTPRequest::~HTTPRequest()
475 // Keep track of whether reply was sent to avoid request leaks
476 LogPrintf("%s: Unhandled request\n", __func__);
477 WriteReply(HTTP_INTERNAL, "Unhandled request");
479 // evhttpd cleans up the request, as long as a reply was sent.
482 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
484 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
486 const char* val = evhttp_find_header(headers, hdr.c_str());
488 return std::make_pair(true, val);
490 return std::make_pair(false, "");
493 std::string HTTPRequest::ReadBody()
495 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
498 size_t size = evbuffer_get_length(buf);
499 /** Trivial implementation: if this is ever a performance bottleneck,
500 * internal copying can be avoided in multi-segment buffers by using
501 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
502 * better to not copy into an intermediate string but use a stream
503 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
505 const char* data = (const char*)evbuffer_pullup(buf, size);
506 if (!data) // returns NULL in case of empty buffer
508 std::string rv(data, size);
509 evbuffer_drain(buf, size);
513 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
515 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
517 evhttp_add_header(headers, hdr.c_str(), value.c_str());
520 /** Closure sent to main thread to request a reply to be sent to
522 * Replies must be sent in the main loop in the main http thread,
523 * this cannot be done from worker threads.
525 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
527 assert(!replySent && req);
528 // Send event to main http thread to send reply message
529 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
531 evbuffer_add(evb, strReply.data(), strReply.size());
532 HTTPEvent* ev = new HTTPEvent(eventBase, true,
533 boost::bind(evhttp_send_reply, req, nStatus, (const char*)NULL, (struct evbuffer *)NULL));
536 req = 0; // transferred back to main thread
539 CService HTTPRequest::GetPeer()
541 evhttp_connection* con = evhttp_request_get_connection(req);
544 // evhttp retains ownership over returned address string
545 const char* address = "";
547 evhttp_connection_get_peer(con, (char**)&address, &port);
548 peer = CService(address, port);
553 std::string HTTPRequest::GetURI()
555 return evhttp_request_get_uri(req);
558 HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod()
560 switch (evhttp_request_get_command(req)) {
564 case EVHTTP_REQ_POST:
567 case EVHTTP_REQ_HEAD:
579 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
581 LogPrint("http", "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
582 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
585 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
587 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
588 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
589 for (; i != iend; ++i)
590 if (i->prefix == prefix && i->exactMatch == exactMatch)
594 LogPrint("http", "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
595 pathHandlers.erase(i);