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/bufferevent.h>
28 #include <event2/util.h>
29 #include <event2/keyvalq_struct.h>
31 #include <support/events.h>
33 #ifdef EVENT__HAVE_NETINET_IN_H
34 #include <netinet/in.h>
35 #ifdef _XOPEN_SOURCE_EXTENDED
36 #include <arpa/inet.h>
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 final
: public HTTPClosure
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()() override
53 func(req
.get(), path
);
56 std::unique_ptr
<HTTPRequest
> req
;
60 HTTPRequestHandler func
;
63 /** Simple work queue for distributing work over multiple threads.
64 * Work items are simply callable objects.
66 template <typename WorkItem
>
70 /** Mutex protects entire object */
72 std::condition_variable cond
;
73 std::deque
<std::unique_ptr
<WorkItem
>> queue
;
78 /** RAII object to keep track of number of running worker threads */
83 explicit ThreadCounter(WorkQueue
&w
): wq(w
)
85 std::lock_guard
<std::mutex
> lock(wq
.cs
);
90 std::lock_guard
<std::mutex
> lock(wq
.cs
);
97 explicit WorkQueue(size_t _maxDepth
) : running(true),
102 /** Precondition: worker threads have all stopped
108 /** Enqueue a work item */
109 bool Enqueue(WorkItem
* item
)
111 std::unique_lock
<std::mutex
> lock(cs
);
112 if (queue
.size() >= maxDepth
) {
115 queue
.emplace_back(std::unique_ptr
<WorkItem
>(item
));
119 /** Thread function */
122 ThreadCounter
count(*this);
124 std::unique_ptr
<WorkItem
> i
;
126 std::unique_lock
<std::mutex
> lock(cs
);
127 while (running
&& queue
.empty())
131 i
= std::move(queue
.front());
137 /** Interrupt and exit loops */
140 std::unique_lock
<std::mutex
> lock(cs
);
144 /** Wait for worker threads to exit */
147 std::unique_lock
<std::mutex
> lock(cs
);
148 while (numThreads
> 0)
153 struct HTTPPathHandler
156 HTTPPathHandler(std::string _prefix
, bool _exactMatch
, HTTPRequestHandler _handler
):
157 prefix(_prefix
), exactMatch(_exactMatch
), handler(_handler
)
162 HTTPRequestHandler handler
;
165 /** HTTP module state */
167 //! libevent event loop
168 static struct event_base
* eventBase
= nullptr;
170 struct evhttp
* eventHTTP
= nullptr;
171 //! List of subnets to allow RPC connections from
172 static std::vector
<CSubNet
> rpc_allow_subnets
;
173 //! Work queue for handling longer requests off the event loop thread
174 static WorkQueue
<HTTPClosure
>* workQueue
= nullptr;
175 //! Handlers for (sub)paths
176 std::vector
<HTTPPathHandler
> pathHandlers
;
177 //! Bound listening sockets
178 std::vector
<evhttp_bound_socket
*> boundSockets
;
180 /** Check if a network address is allowed to access the HTTP server */
181 static bool ClientAllowed(const CNetAddr
& netaddr
)
183 if (!netaddr
.IsValid())
185 for(const CSubNet
& subnet
: rpc_allow_subnets
)
186 if (subnet
.Match(netaddr
))
191 /** Initialize ACL list for HTTP server */
192 static bool InitHTTPAllowList()
194 rpc_allow_subnets
.clear();
197 LookupHost("127.0.0.1", localv4
, false);
198 LookupHost("::1", localv6
, false);
199 rpc_allow_subnets
.push_back(CSubNet(localv4
, 8)); // always allow IPv4 local subnet
200 rpc_allow_subnets
.push_back(CSubNet(localv6
)); // always allow IPv6 localhost
201 for (const std::string
& strAllow
: gArgs
.GetArgs("-rpcallowip")) {
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
);
210 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
);
219 /** HTTP request method as string - use for logging only */
220 static std::string
RequestMethodString(HTTPRequest::RequestMethod m
)
223 case HTTPRequest::GET
:
226 case HTTPRequest::POST
:
229 case HTTPRequest::HEAD
:
232 case HTTPRequest::PUT
:
240 /** HTTP request callback */
241 static void http_request_cb(struct evhttp_request
* req
, void* arg
)
243 // Disable reading to work around a libevent bug, fixed in 2.2.0.
244 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
245 evhttp_connection
* conn
= evhttp_request_get_connection(req
);
247 bufferevent
* bev
= evhttp_connection_get_bufferevent(conn
);
249 bufferevent_disable(bev
, EV_READ
);
253 std::unique_ptr
<HTTPRequest
> hreq(new HTTPRequest(req
));
255 LogPrint(BCLog::HTTP
, "Received a %s request for %s from %s\n",
256 RequestMethodString(hreq
->GetRequestMethod()), hreq
->GetURI(), hreq
->GetPeer().ToString());
258 // Early address-based allow check
259 if (!ClientAllowed(hreq
->GetPeer())) {
260 hreq
->WriteReply(HTTP_FORBIDDEN
);
264 // Early reject unknown HTTP methods
265 if (hreq
->GetRequestMethod() == HTTPRequest::UNKNOWN
) {
266 hreq
->WriteReply(HTTP_BADMETHOD
);
270 // Find registered handler for prefix
271 std::string strURI
= hreq
->GetURI();
273 std::vector
<HTTPPathHandler
>::const_iterator i
= pathHandlers
.begin();
274 std::vector
<HTTPPathHandler
>::const_iterator iend
= pathHandlers
.end();
275 for (; i
!= iend
; ++i
) {
278 match
= (strURI
== i
->prefix
);
280 match
= (strURI
.substr(0, i
->prefix
.size()) == i
->prefix
);
282 path
= strURI
.substr(i
->prefix
.size());
287 // Dispatch to worker thread
289 std::unique_ptr
<HTTPWorkItem
> item(new HTTPWorkItem(std::move(hreq
), path
, i
->handler
));
291 if (workQueue
->Enqueue(item
.get()))
292 item
.release(); /* if true, queue took ownership */
294 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
295 item
->req
->WriteReply(HTTP_INTERNAL
, "Work queue depth exceeded");
298 hreq
->WriteReply(HTTP_NOTFOUND
);
302 /** Callback to reject HTTP requests after shutdown. */
303 static void http_reject_request_cb(struct evhttp_request
* req
, void*)
305 LogPrint(BCLog::HTTP
, "Rejecting request while shutting down\n");
306 evhttp_send_error(req
, HTTP_SERVUNAVAIL
, nullptr);
309 /** Event dispatcher thread */
310 static bool ThreadHTTP(struct event_base
* base
, struct evhttp
* http
)
312 RenameThread("bitcoin-http");
313 LogPrint(BCLog::HTTP
, "Entering http event loop\n");
314 event_base_dispatch(base
);
315 // Event loop will be interrupted by InterruptHTTPServer()
316 LogPrint(BCLog::HTTP
, "Exited http event loop\n");
317 return event_base_got_break(base
) == 0;
320 /** Bind HTTP server to specified addresses */
321 static bool HTTPBindAddresses(struct evhttp
* http
)
323 int defaultPort
= gArgs
.GetArg("-rpcport", BaseParams().RPCPort());
324 std::vector
<std::pair
<std::string
, uint16_t> > endpoints
;
326 // Determine what addresses to bind to
327 if (!gArgs
.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
328 endpoints
.push_back(std::make_pair("::1", defaultPort
));
329 endpoints
.push_back(std::make_pair("127.0.0.1", defaultPort
));
330 if (gArgs
.IsArgSet("-rpcbind")) {
331 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
333 } else if (gArgs
.IsArgSet("-rpcbind")) { // Specific bind address
334 for (const std::string
& strRPCBind
: gArgs
.GetArgs("-rpcbind")) {
335 int port
= defaultPort
;
337 SplitHostPort(strRPCBind
, port
, host
);
338 endpoints
.push_back(std::make_pair(host
, port
));
340 } else { // No specific bind address specified, bind to any
341 endpoints
.push_back(std::make_pair("::", defaultPort
));
342 endpoints
.push_back(std::make_pair("0.0.0.0", defaultPort
));
346 for (std::vector
<std::pair
<std::string
, uint16_t> >::iterator i
= endpoints
.begin(); i
!= endpoints
.end(); ++i
) {
347 LogPrint(BCLog::HTTP
, "Binding RPC on address %s port %i\n", i
->first
, i
->second
);
348 evhttp_bound_socket
*bind_handle
= evhttp_bind_socket_with_handle(http
, i
->first
.empty() ? nullptr : i
->first
.c_str(), i
->second
);
350 boundSockets
.push_back(bind_handle
);
352 LogPrintf("Binding RPC on address %s port %i failed.\n", i
->first
, i
->second
);
355 return !boundSockets
.empty();
358 /** Simple wrapper to set thread name and run work queue */
359 static void HTTPWorkQueueRun(WorkQueue
<HTTPClosure
>* queue
)
361 RenameThread("bitcoin-httpworker");
365 /** libevent event log callback */
366 static void libevent_log_cb(int severity
, const char *msg
)
368 #ifndef EVENT_LOG_WARN
369 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
370 # define EVENT_LOG_WARN _EVENT_LOG_WARN
372 if (severity
>= EVENT_LOG_WARN
) // Log warn messages and higher without debug category
373 LogPrintf("libevent: %s\n", msg
);
375 LogPrint(BCLog::LIBEVENT
, "libevent: %s\n", msg
);
378 bool InitHTTPServer()
380 if (!InitHTTPAllowList())
383 if (gArgs
.GetBoolArg("-rpcssl", false)) {
384 uiInterface
.ThreadSafeMessageBox(
385 "SSL mode for RPC (-rpcssl) is no longer supported.",
386 "", CClientUIInterface::MSG_ERROR
);
390 // Redirect libevent's logging to our own log
391 event_set_log_callback(&libevent_log_cb
);
392 // Update libevent's log handling. Returns false if our version of
393 // libevent doesn't support debug logging, in which case we should
394 // clear the BCLog::LIBEVENT flag.
395 if (!UpdateHTTPServerLogging(logCategories
& BCLog::LIBEVENT
)) {
396 logCategories
&= ~BCLog::LIBEVENT
;
400 evthread_use_windows_threads();
402 evthread_use_pthreads();
405 raii_event_base base_ctr
= obtain_event_base();
407 /* Create a new evhttp object to handle requests. */
408 raii_evhttp http_ctr
= obtain_evhttp(base_ctr
.get());
409 struct evhttp
* http
= http_ctr
.get();
411 LogPrintf("couldn't create evhttp. Exiting.\n");
415 evhttp_set_timeout(http
, gArgs
.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
, nullptr);
420 if (!HTTPBindAddresses(http
)) {
421 LogPrintf("Unable to bind any endpoint for RPC server\n");
425 LogPrint(BCLog::HTTP
, "Initialized HTTP server\n");
426 int workQueueDepth
= std::max((long)gArgs
.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE
), 1L);
427 LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth
);
429 workQueue
= new WorkQueue
<HTTPClosure
>(workQueueDepth
);
430 // transfer ownership to eventBase/HTTP via .release()
431 eventBase
= base_ctr
.release();
432 eventHTTP
= http_ctr
.release();
436 bool UpdateHTTPServerLogging(bool enable
) {
437 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
439 event_enable_debug_logging(EVENT_DBG_ALL
);
441 event_enable_debug_logging(EVENT_DBG_NONE
);
445 // Can't update libevent logging if version < 02010100
450 std::thread threadHTTP
;
451 std::future
<bool> threadResult
;
453 bool StartHTTPServer()
455 LogPrint(BCLog::HTTP
, "Starting HTTP server\n");
456 int rpcThreads
= std::max((long)gArgs
.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS
), 1L);
457 LogPrintf("HTTP: starting %d worker threads\n", rpcThreads
);
458 std::packaged_task
<bool(event_base
*, evhttp
*)> task(ThreadHTTP
);
459 threadResult
= task
.get_future();
460 threadHTTP
= std::thread(std::move(task
), eventBase
, eventHTTP
);
462 for (int i
= 0; i
< rpcThreads
; i
++) {
463 std::thread
rpc_worker(HTTPWorkQueueRun
, workQueue
);
469 void InterruptHTTPServer()
471 LogPrint(BCLog::HTTP
, "Interrupting HTTP server\n");
474 for (evhttp_bound_socket
*socket
: boundSockets
) {
475 evhttp_del_accept_socket(eventHTTP
, socket
);
477 // Reject requests on current connections
478 evhttp_set_gencb(eventHTTP
, http_reject_request_cb
, nullptr);
481 workQueue
->Interrupt();
484 void StopHTTPServer()
486 LogPrint(BCLog::HTTP
, "Stopping HTTP server\n");
488 LogPrint(BCLog::HTTP
, "Waiting for HTTP worker threads to exit\n");
489 workQueue
->WaitExit();
494 LogPrint(BCLog::HTTP
, "Waiting for HTTP event thread to exit\n");
495 // Exit the event loop as soon as there are no active events.
496 event_base_loopexit(eventBase
, nullptr);
497 // Give event loop a few seconds to exit (to send back last RPC responses), then break it
498 // Before this was solved with event_base_loopexit, but that didn't work as expected in
499 // at least libevent 2.0.21 and always introduced a delay. In libevent
500 // master that appears to be solved, so in the future that solution
501 // could be used again (if desirable).
502 // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
503 if (threadResult
.valid() && threadResult
.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout
) {
504 LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
505 event_base_loopbreak(eventBase
);
510 evhttp_free(eventHTTP
);
514 event_base_free(eventBase
);
517 LogPrint(BCLog::HTTP
, "Stopped HTTP server\n");
520 struct event_base
* EventBase()
525 static void httpevent_callback_fn(evutil_socket_t
, short, void* data
)
527 // Static handler: simply call inner handler
528 HTTPEvent
*self
= ((HTTPEvent
*)data
);
530 if (self
->deleteWhenTriggered
)
534 HTTPEvent::HTTPEvent(struct event_base
* base
, bool _deleteWhenTriggered
, const std::function
<void(void)>& _handler
):
535 deleteWhenTriggered(_deleteWhenTriggered
), handler(_handler
)
537 ev
= event_new(base
, -1, 0, httpevent_callback_fn
, this);
540 HTTPEvent::~HTTPEvent()
544 void HTTPEvent::trigger(struct timeval
* tv
)
547 event_active(ev
, 0, 0); // immediately trigger event in main thread
549 evtimer_add(ev
, tv
); // trigger after timeval passed
551 HTTPRequest::HTTPRequest(struct evhttp_request
* _req
) : req(_req
),
555 HTTPRequest::~HTTPRequest()
558 // Keep track of whether reply was sent to avoid request leaks
559 LogPrintf("%s: Unhandled request\n", __func__
);
560 WriteReply(HTTP_INTERNAL
, "Unhandled request");
562 // evhttpd cleans up the request, as long as a reply was sent.
565 std::pair
<bool, std::string
> HTTPRequest::GetHeader(const std::string
& hdr
)
567 const struct evkeyvalq
* headers
= evhttp_request_get_input_headers(req
);
569 const char* val
= evhttp_find_header(headers
, hdr
.c_str());
571 return std::make_pair(true, val
);
573 return std::make_pair(false, "");
576 std::string
HTTPRequest::ReadBody()
578 struct evbuffer
* buf
= evhttp_request_get_input_buffer(req
);
581 size_t size
= evbuffer_get_length(buf
);
582 /** Trivial implementation: if this is ever a performance bottleneck,
583 * internal copying can be avoided in multi-segment buffers by using
584 * evbuffer_peek and an awkward loop. Though in that case, it'd be even
585 * better to not copy into an intermediate string but use a stream
586 * abstraction to consume the evbuffer on the fly in the parsing algorithm.
588 const char* data
= (const char*)evbuffer_pullup(buf
, size
);
589 if (!data
) // returns nullptr in case of empty buffer
591 std::string
rv(data
, size
);
592 evbuffer_drain(buf
, size
);
596 void HTTPRequest::WriteHeader(const std::string
& hdr
, const std::string
& value
)
598 struct evkeyvalq
* headers
= evhttp_request_get_output_headers(req
);
600 evhttp_add_header(headers
, hdr
.c_str(), value
.c_str());
603 /** Closure sent to main thread to request a reply to be sent to
605 * Replies must be sent in the main loop in the main http thread,
606 * this cannot be done from worker threads.
608 void HTTPRequest::WriteReply(int nStatus
, const std::string
& strReply
)
610 assert(!replySent
&& req
);
611 // Send event to main http thread to send reply message
612 struct evbuffer
* evb
= evhttp_request_get_output_buffer(req
);
614 evbuffer_add(evb
, strReply
.data(), strReply
.size());
616 HTTPEvent
* ev
= new HTTPEvent(eventBase
, true, [req_copy
, nStatus
]{
617 evhttp_send_reply(req_copy
, nStatus
, nullptr, nullptr);
618 // Re-enable reading from the socket. This is the second part of the libevent
620 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
621 evhttp_connection
* conn
= evhttp_request_get_connection(req_copy
);
623 bufferevent
* bev
= evhttp_connection_get_bufferevent(conn
);
625 bufferevent_enable(bev
, EV_READ
| EV_WRITE
);
630 ev
->trigger(nullptr);
632 req
= nullptr; // transferred back to main thread
635 CService
HTTPRequest::GetPeer()
637 evhttp_connection
* con
= evhttp_request_get_connection(req
);
640 // evhttp retains ownership over returned address string
641 const char* address
= "";
643 evhttp_connection_get_peer(con
, (char**)&address
, &port
);
644 peer
= LookupNumeric(address
, port
);
649 std::string
HTTPRequest::GetURI()
651 return evhttp_request_get_uri(req
);
654 HTTPRequest::RequestMethod
HTTPRequest::GetRequestMethod()
656 switch (evhttp_request_get_command(req
)) {
660 case EVHTTP_REQ_POST
:
663 case EVHTTP_REQ_HEAD
:
675 void RegisterHTTPHandler(const std::string
&prefix
, bool exactMatch
, const HTTPRequestHandler
&handler
)
677 LogPrint(BCLog::HTTP
, "Registering HTTP handler for %s (exactmatch %d)\n", prefix
, exactMatch
);
678 pathHandlers
.push_back(HTTPPathHandler(prefix
, exactMatch
, handler
));
681 void UnregisterHTTPHandler(const std::string
&prefix
, bool exactMatch
)
683 std::vector
<HTTPPathHandler
>::iterator i
= pathHandlers
.begin();
684 std::vector
<HTTPPathHandler
>::iterator iend
= pathHandlers
.end();
685 for (; i
!= iend
; ++i
)
686 if (i
->prefix
== prefix
&& i
->exactMatch
== exactMatch
)
690 LogPrint(BCLog::HTTP
, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix
, exactMatch
);
691 pathHandlers
.erase(i
);
695 std::string
urlDecode(const std::string
&urlEncoded
) {
697 if (!urlEncoded
.empty()) {
698 char *decoded
= evhttp_uridecode(urlEncoded
.c_str(), false, nullptr);
700 res
= std::string(decoded
);