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"
10 #include "utilstrencodings.h"
12 #include "rpc/protocol.h" // For HTTP status codes
14 #include "ui_interface.h"
20 #include <sys/types.h>
25 #include <event2/thread.h>
26 #include <event2/buffer.h>
27 #include <event2/util.h>
28 #include <event2/keyvalq_struct.h>
30 #include "support/events.h"
32 #ifdef EVENT__HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #ifdef _XOPEN_SOURCE_EXTENDED
35 #include <arpa/inet.h>
39 /** Maximum size of http request (request line + headers) */
40 static const size_t MAX_HEADERS_SIZE
= 8192;
42 /** HTTP request work item */
43 class HTTPWorkItem final
: public HTTPClosure
46 HTTPWorkItem(std::unique_ptr
<HTTPRequest
> _req
, const std::string
&_path
, const HTTPRequestHandler
& _func
):
47 req(std::move(_req
)), path(_path
), func(_func
)
50 void operator()() override
52 func(req
.get(), path
);
55 std::unique_ptr
<HTTPRequest
> req
;
59 HTTPRequestHandler func
;
62 /** Simple work queue for distributing work over multiple threads.
63 * Work items are simply callable objects.
65 template <typename WorkItem
>
69 /** Mutex protects entire object */
71 std::condition_variable cond
;
72 std::deque
<std::unique_ptr
<WorkItem
>> queue
;
77 /** RAII object to keep track of number of running worker threads */
82 explicit ThreadCounter(WorkQueue
&w
): wq(w
)
84 std::lock_guard
<std::mutex
> lock(wq
.cs
);
89 std::lock_guard
<std::mutex
> lock(wq
.cs
);
96 explicit WorkQueue(size_t _maxDepth
) : running(true),
101 /** Precondition: worker threads have all stopped
107 /** Enqueue a work item */
108 bool Enqueue(WorkItem
* item
)
110 std::unique_lock
<std::mutex
> lock(cs
);
111 if (queue
.size() >= maxDepth
) {
114 queue
.emplace_back(std::unique_ptr
<WorkItem
>(item
));
118 /** Thread function */
121 ThreadCounter
count(*this);
123 std::unique_ptr
<WorkItem
> i
;
125 std::unique_lock
<std::mutex
> lock(cs
);
126 while (running
&& queue
.empty())
130 i
= std::move(queue
.front());
136 /** Interrupt and exit loops */
139 std::unique_lock
<std::mutex
> lock(cs
);
143 /** Wait for worker threads to exit */
146 std::unique_lock
<std::mutex
> lock(cs
);
147 while (numThreads
> 0)
152 struct HTTPPathHandler
155 HTTPPathHandler(std::string _prefix
, bool _exactMatch
, HTTPRequestHandler _handler
):
156 prefix(_prefix
), exactMatch(_exactMatch
), handler(_handler
)
161 HTTPRequestHandler handler
;
164 /** HTTP module state */
166 //! libevent event loop
167 static struct event_base
* eventBase
= nullptr;
169 struct evhttp
* eventHTTP
= nullptr;
170 //! List of subnets to allow RPC connections from
171 static std::vector
<CSubNet
> rpc_allow_subnets
;
172 //! Work queue for handling longer requests off the event loop thread
173 static WorkQueue
<HTTPClosure
>* workQueue
= nullptr;
174 //! Handlers for (sub)paths
175 std::vector
<HTTPPathHandler
> pathHandlers
;
176 //! Bound listening sockets
177 std::vector
<evhttp_bound_socket
*> boundSockets
;
179 /** Check if a network address is allowed to access the HTTP server */
180 static bool ClientAllowed(const CNetAddr
& netaddr
)
182 if (!netaddr
.IsValid())
184 for(const CSubNet
& subnet
: rpc_allow_subnets
)
185 if (subnet
.Match(netaddr
))
190 /** Initialize ACL list for HTTP server */
191 static bool InitHTTPAllowList()
193 rpc_allow_subnets
.clear();
196 LookupHost("127.0.0.1", localv4
, false);
197 LookupHost("::1", localv6
, false);
198 rpc_allow_subnets
.push_back(CSubNet(localv4
, 8)); // always allow IPv4 local subnet
199 rpc_allow_subnets
.push_back(CSubNet(localv6
)); // always allow IPv6 localhost
200 for (const std::string
& strAllow
: gArgs
.GetArgs("-rpcallowip")) {
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
);
209 rpc_allow_subnets
.push_back(subnet
);
211 std::string strAllowed
;
212 for (const CSubNet
& subnet
: rpc_allow_subnets
)
213 strAllowed
+= subnet
.ToString() + " ";
214 LogPrint(BCLog::HTTP
, "Allowing HTTP connections from: %s\n", strAllowed
);
218 /** HTTP request method as string - use for logging only */
219 static std::string
RequestMethodString(HTTPRequest::RequestMethod m
)
222 case HTTPRequest::GET
:
225 case HTTPRequest::POST
:
228 case HTTPRequest::HEAD
:
231 case HTTPRequest::PUT
:
239 /** HTTP request callback */
240 static void http_request_cb(struct evhttp_request
* req
, void* arg
)
242 std::unique_ptr
<HTTPRequest
> hreq(new HTTPRequest(req
));
244 LogPrint(BCLog::HTTP
, "Received a %s request for %s from %s\n",
245 RequestMethodString(hreq
->GetRequestMethod()), hreq
->GetURI(), hreq
->GetPeer().ToString());
247 // Early address-based allow check
248 if (!ClientAllowed(hreq
->GetPeer())) {
249 hreq
->WriteReply(HTTP_FORBIDDEN
);
253 // Early reject unknown HTTP methods
254 if (hreq
->GetRequestMethod() == HTTPRequest::UNKNOWN
) {
255 hreq
->WriteReply(HTTP_BADMETHOD
);
259 // Find registered handler for prefix
260 std::string strURI
= hreq
->GetURI();
262 std::vector
<HTTPPathHandler
>::const_iterator i
= pathHandlers
.begin();
263 std::vector
<HTTPPathHandler
>::const_iterator iend
= pathHandlers
.end();
264 for (; i
!= iend
; ++i
) {
267 match
= (strURI
== i
->prefix
);
269 match
= (strURI
.substr(0, i
->prefix
.size()) == i
->prefix
);
271 path
= strURI
.substr(i
->prefix
.size());
276 // Dispatch to worker thread
278 std::unique_ptr
<HTTPWorkItem
> item(new HTTPWorkItem(std::move(hreq
), path
, i
->handler
));
280 if (workQueue
->Enqueue(item
.get()))
281 item
.release(); /* if true, queue took ownership */
283 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
284 item
->req
->WriteReply(HTTP_INTERNAL
, "Work queue depth exceeded");
287 hreq
->WriteReply(HTTP_NOTFOUND
);
291 /** Callback to reject HTTP requests after shutdown. */
292 static void http_reject_request_cb(struct evhttp_request
* req
, void*)
294 LogPrint(BCLog::HTTP
, "Rejecting request while shutting down\n");
295 evhttp_send_error(req
, HTTP_SERVUNAVAIL
, nullptr);
298 /** Event dispatcher thread */
299 static bool ThreadHTTP(struct event_base
* base
, struct evhttp
* http
)
301 RenameThread("bitcoin-http");
302 LogPrint(BCLog::HTTP
, "Entering http event loop\n");
303 event_base_dispatch(base
);
304 // Event loop will be interrupted by InterruptHTTPServer()
305 LogPrint(BCLog::HTTP
, "Exited http event loop\n");
306 return event_base_got_break(base
) == 0;
309 /** Bind HTTP server to specified addresses */
310 static bool HTTPBindAddresses(struct evhttp
* http
)
312 int defaultPort
= gArgs
.GetArg("-rpcport", BaseParams().RPCPort());
313 std::vector
<std::pair
<std::string
, uint16_t> > endpoints
;
315 // Determine what addresses to bind to
316 if (!gArgs
.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
317 endpoints
.push_back(std::make_pair("::1", defaultPort
));
318 endpoints
.push_back(std::make_pair("127.0.0.1", defaultPort
));
319 if (gArgs
.IsArgSet("-rpcbind")) {
320 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
322 } else if (gArgs
.IsArgSet("-rpcbind")) { // Specific bind address
323 for (const std::string
& strRPCBind
: gArgs
.GetArgs("-rpcbind")) {
324 int port
= defaultPort
;
326 SplitHostPort(strRPCBind
, port
, host
);
327 endpoints
.push_back(std::make_pair(host
, port
));
329 } else { // No specific bind address specified, bind to any
330 endpoints
.push_back(std::make_pair("::", defaultPort
));
331 endpoints
.push_back(std::make_pair("0.0.0.0", defaultPort
));
335 for (std::vector
<std::pair
<std::string
, uint16_t> >::iterator i
= endpoints
.begin(); i
!= endpoints
.end(); ++i
) {
336 LogPrint(BCLog::HTTP
, "Binding RPC on address %s port %i\n", i
->first
, i
->second
);
337 evhttp_bound_socket
*bind_handle
= evhttp_bind_socket_with_handle(http
, i
->first
.empty() ? nullptr : i
->first
.c_str(), i
->second
);
339 boundSockets
.push_back(bind_handle
);
341 LogPrintf("Binding RPC on address %s port %i failed.\n", i
->first
, i
->second
);
344 return !boundSockets
.empty();
347 /** Simple wrapper to set thread name and run work queue */
348 static void HTTPWorkQueueRun(WorkQueue
<HTTPClosure
>* queue
)
350 RenameThread("bitcoin-httpworker");
354 /** libevent event log callback */
355 static void libevent_log_cb(int severity
, const char *msg
)
357 #ifndef EVENT_LOG_WARN
358 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
359 # define EVENT_LOG_WARN _EVENT_LOG_WARN
361 if (severity
>= EVENT_LOG_WARN
) // Log warn messages and higher without debug category
362 LogPrintf("libevent: %s\n", msg
);
364 LogPrint(BCLog::LIBEVENT
, "libevent: %s\n", msg
);
367 bool InitHTTPServer()
369 if (!InitHTTPAllowList())
372 if (gArgs
.GetBoolArg("-rpcssl", false)) {
373 uiInterface
.ThreadSafeMessageBox(
374 "SSL mode for RPC (-rpcssl) is no longer supported.",
375 "", CClientUIInterface::MSG_ERROR
);
379 // Redirect libevent's logging to our own log
380 event_set_log_callback(&libevent_log_cb
);
381 // Update libevent's log handling. Returns false if our version of
382 // libevent doesn't support debug logging, in which case we should
383 // clear the BCLog::LIBEVENT flag.
384 if (!UpdateHTTPServerLogging(logCategories
& BCLog::LIBEVENT
)) {
385 logCategories
&= ~BCLog::LIBEVENT
;
389 evthread_use_windows_threads();
391 evthread_use_pthreads();
394 raii_event_base base_ctr
= obtain_event_base();
396 /* Create a new evhttp object to handle requests. */
397 raii_evhttp http_ctr
= obtain_evhttp(base_ctr
.get());
398 struct evhttp
* http
= http_ctr
.get();
400 LogPrintf("couldn't create evhttp. Exiting.\n");
404 evhttp_set_timeout(http
, gArgs
.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT
));
405 evhttp_set_max_headers_size(http
, MAX_HEADERS_SIZE
);
406 evhttp_set_max_body_size(http
, MAX_SIZE
);
407 evhttp_set_gencb(http
, http_request_cb
, nullptr);
409 if (!HTTPBindAddresses(http
)) {
410 LogPrintf("Unable to bind any endpoint for RPC server\n");
414 LogPrint(BCLog::HTTP
, "Initialized HTTP server\n");
415 int workQueueDepth
= std::max((long)gArgs
.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE
), 1L);
416 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth
);
418 workQueue
= new WorkQueue
<HTTPClosure
>(workQueueDepth
);
419 // transfer ownership to eventBase/HTTP via .release()
420 eventBase
= base_ctr
.release();
421 eventHTTP
= http_ctr
.release();
425 bool UpdateHTTPServerLogging(bool enable
) {
426 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
428 event_enable_debug_logging(EVENT_DBG_ALL
);
430 event_enable_debug_logging(EVENT_DBG_NONE
);
434 // Can't update libevent logging if version < 02010100
439 std::thread threadHTTP
;
440 std::future
<bool> threadResult
;
442 bool StartHTTPServer()
444 LogPrint(BCLog::HTTP
, "Starting HTTP server\n");
445 int rpcThreads
= std::max((long)gArgs
.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS
), 1L);
446 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads
);
447 std::packaged_task
<bool(event_base
*, evhttp
*)> task(ThreadHTTP
);
448 threadResult
= task
.get_future();
449 threadHTTP
= std::thread(std::move(task
), eventBase
, eventHTTP
);
451 for (int i
= 0; i
< rpcThreads
; i
++) {
452 std::thread
rpc_worker(HTTPWorkQueueRun
, workQueue
);
458 void InterruptHTTPServer()
460 LogPrint(BCLog::HTTP
, "Interrupting HTTP server\n");
463 for (evhttp_bound_socket
*socket
: boundSockets
) {
464 evhttp_del_accept_socket(eventHTTP
, socket
);
466 // Reject requests on current connections
467 evhttp_set_gencb(eventHTTP
, http_reject_request_cb
, nullptr);
470 workQueue
->Interrupt();
473 void StopHTTPServer()
475 LogPrint(BCLog::HTTP
, "Stopping HTTP server\n");
477 LogPrint(BCLog::HTTP
, "Waiting for HTTP worker threads to exit\n");
478 workQueue
->WaitExit();
483 LogPrint(BCLog::HTTP
, "Waiting for HTTP event thread to exit\n");
484 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
485 // Before this was solved with event_base_loopexit, but that didn't work as expected in
486 // at least libevent 2.0.21 and always introduced a delay. In libevent
487 // master that appears to be solved, so in the future that solution
488 // could be used again (if desirable).
489 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
490 if (threadResult
.valid() && threadResult
.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout
) {
491 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
492 event_base_loopbreak(eventBase
);
497 evhttp_free(eventHTTP
);
501 event_base_free(eventBase
);
504 LogPrint(BCLog::HTTP
, "Stopped HTTP server\n");
507 struct event_base
* EventBase()
512 static void httpevent_callback_fn(evutil_socket_t
, short, void* data
)
514 // Static handler: simply call inner handler
515 HTTPEvent
*self
= ((HTTPEvent
*)data
);
517 if (self
->deleteWhenTriggered
)
521 HTTPEvent::HTTPEvent(struct event_base
* base
, bool _deleteWhenTriggered
, const std::function
<void(void)>& _handler
):
522 deleteWhenTriggered(_deleteWhenTriggered
), handler(_handler
)
524 ev
= event_new(base
, -1, 0, httpevent_callback_fn
, this);
527 HTTPEvent::~HTTPEvent()
531 void HTTPEvent::trigger(struct timeval
* tv
)
534 event_active(ev
, 0, 0); // immediately trigger event in main thread
536 evtimer_add(ev
, tv
); // trigger after timeval passed
538 HTTPRequest::HTTPRequest(struct evhttp_request
* _req
) : req(_req
),
542 HTTPRequest::~HTTPRequest()
545 // Keep track of whether reply was sent to avoid request leaks
546 LogPrintf("%s: Unhandled request\n", __func__
);
547 WriteReply(HTTP_INTERNAL
, "Unhandled request");
549 // evhttpd cleans up the request, as long as a reply was sent.
552 std::pair
<bool, std::string
> HTTPRequest::GetHeader(const std::string
& hdr
)
554 const struct evkeyvalq
* headers
= evhttp_request_get_input_headers(req
);
556 const char* val
= evhttp_find_header(headers
, hdr
.c_str());
558 return std::make_pair(true, val
);
560 return std::make_pair(false, "");
563 std::string
HTTPRequest::ReadBody()
565 struct evbuffer
* buf
= evhttp_request_get_input_buffer(req
);
568 size_t size
= evbuffer_get_length(buf
);
569 /** Trivial implementation: if this is ever a performance bottleneck,
570 * internal copying can be avoided in multi-segment buffers by using
571 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
572 * better to not copy into an intermediate string but use a stream
573 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
575 const char* data
= (const char*)evbuffer_pullup(buf
, size
);
576 if (!data
) // returns nullptr in case of empty buffer
578 std::string
rv(data
, size
);
579 evbuffer_drain(buf
, size
);
583 void HTTPRequest::WriteHeader(const std::string
& hdr
, const std::string
& value
)
585 struct evkeyvalq
* headers
= evhttp_request_get_output_headers(req
);
587 evhttp_add_header(headers
, hdr
.c_str(), value
.c_str());
590 /** Closure sent to main thread to request a reply to be sent to
592 * Replies must be sent in the main loop in the main http thread,
593 * this cannot be done from worker threads.
595 void HTTPRequest::WriteReply(int nStatus
, const std::string
& strReply
)
597 assert(!replySent
&& req
);
598 // Send event to main http thread to send reply message
599 struct evbuffer
* evb
= evhttp_request_get_output_buffer(req
);
601 evbuffer_add(evb
, strReply
.data(), strReply
.size());
602 HTTPEvent
* ev
= new HTTPEvent(eventBase
, true,
603 std::bind(evhttp_send_reply
, req
, nStatus
, (const char*)nullptr, (struct evbuffer
*)nullptr));
604 ev
->trigger(nullptr);
606 req
= nullptr; // transferred back to main thread
609 CService
HTTPRequest::GetPeer()
611 evhttp_connection
* con
= evhttp_request_get_connection(req
);
614 // evhttp retains ownership over returned address string
615 const char* address
= "";
617 evhttp_connection_get_peer(con
, (char**)&address
, &port
);
618 peer
= LookupNumeric(address
, port
);
623 std::string
HTTPRequest::GetURI()
625 return evhttp_request_get_uri(req
);
628 HTTPRequest::RequestMethod
HTTPRequest::GetRequestMethod()
630 switch (evhttp_request_get_command(req
)) {
634 case EVHTTP_REQ_POST
:
637 case EVHTTP_REQ_HEAD
:
649 void RegisterHTTPHandler(const std::string
&prefix
, bool exactMatch
, const HTTPRequestHandler
&handler
)
651 LogPrint(BCLog::HTTP
, "Registering HTTP handler for %s (exactmatch %d)\n", prefix
, exactMatch
);
652 pathHandlers
.push_back(HTTPPathHandler(prefix
, exactMatch
, handler
));
655 void UnregisterHTTPHandler(const std::string
&prefix
, bool exactMatch
)
657 std::vector
<HTTPPathHandler
>::iterator i
= pathHandlers
.begin();
658 std::vector
<HTTPPathHandler
>::iterator iend
= pathHandlers
.end();
659 for (; i
!= iend
; ++i
)
660 if (i
->prefix
== prefix
&& i
->exactMatch
== exactMatch
)
664 LogPrint(BCLog::HTTP
, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix
, exactMatch
);
665 pathHandlers
.erase(i
);
669 std::string
urlDecode(const std::string
&urlEncoded
) {
671 if (!urlEncoded
.empty()) {
672 char *decoded
= evhttp_uridecode(urlEncoded
.c_str(), false, nullptr);
674 res
= std::string(decoded
);