2018-07-26 18:36:45 -04:00
// Copyright (c) 2015-2018 The Bitcoin Core developers
2015-01-23 07:53:17 +01:00
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2017-11-10 13:57:53 +13:00
#include <httpserver.h>
2015-01-23 07:53:17 +01:00
2017-11-10 13:57:53 +13:00
#include <chainparamsbase.h>
#include <compat.h>
#include <util.h>
#include <utilstrencodings.h>
#include <netbase.h>
#include <rpc/protocol.h> // For HTTP status codes
#include <sync.h>
#include <ui_interface.h>
2015-01-23 07:53:17 +01:00
2018-04-02 18:31:40 +00:00
#include <memory>
2015-01-23 07:53:17 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
2016-07-28 17:52:51 -04:00
#include <future>
2015-01-23 07:53:17 +01:00
#include <event2/thread.h>
#include <event2/buffer.h>
2017-11-01 12:02:57 -04:00
#include <event2/bufferevent.h>
2015-01-23 07:53:17 +01:00
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
2017-11-10 13:57:53 +13:00
#include <support/events.h>
2017-01-11 22:50:00 +09:00
2015-01-23 07:53:17 +01:00
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef _XOPEN_SOURCE_EXTENDED
#include <arpa/inet.h>
#endif
#endif
2015-10-20 11:35:10 +02:00
/** Maximum size of http request (request line + headers) */
static const size_t MAX_HEADERS_SIZE = 8192 ;
2015-01-23 07:53:17 +01:00
/** HTTP request work item */
2017-07-12 16:48:36 -04:00
class HTTPWorkItem final : public HTTPClosure
2015-01-23 07:53:17 +01:00
{
public :
2016-05-27 08:00:56 +02:00
HTTPWorkItem ( std :: unique_ptr < HTTPRequest > _req , const std :: string & _path , const HTTPRequestHandler & _func ) :
req ( std :: move ( _req )), path ( _path ), func ( _func )
2015-01-23 07:53:17 +01:00
{
}
2017-06-20 21:58:56 +02:00
void operator ()() override
2015-01-23 07:53:17 +01:00
{
func ( req . get (), path );
}
2016-05-04 15:55:23 +02:00
std :: unique_ptr < HTTPRequest > req ;
2015-01-23 07:53:17 +01:00
private :
std :: string path ;
HTTPRequestHandler func ;
};
/** Simple work queue for distributing work over multiple threads.
* Work items are simply callable objects.
*/
template < typename WorkItem >
class WorkQueue
{
private :
/** Mutex protects entire object */
2016-07-28 18:31:25 -04:00
std :: mutex cs ;
std :: condition_variable cond ;
2016-04-28 19:03:05 +02:00
std :: deque < std :: unique_ptr < WorkItem >> queue ;
2015-01-23 07:53:17 +01:00
bool running ;
size_t maxDepth ;
public :
2017-08-01 12:22:41 +02:00
explicit WorkQueue ( size_t _maxDepth ) : running ( true ),
2018-02-07 09:53:46 +01:00
maxDepth ( _maxDepth )
2015-01-23 07:53:17 +01:00
{
}
2018-02-06 20:32:33 +01:00
/** Precondition: worker threads have all stopped (they have been joined).
2015-09-25 13:49:08 +02:00
*/
2015-01-23 07:53:17 +01:00
~ WorkQueue ()
{
}
/** Enqueue a work item */
bool Enqueue ( WorkItem * item )
{
2016-07-28 18:31:25 -04:00
std :: unique_lock < std :: mutex > lock ( cs );
2015-01-23 07:53:17 +01:00
if ( queue . size () >= maxDepth ) {
return false ;
}
2016-04-28 19:03:05 +02:00
queue . emplace_back ( std :: unique_ptr < WorkItem > ( item ));
2015-01-23 07:53:17 +01:00
cond . notify_one ();
return true ;
}
/** Thread function */
void Run ()
{
2017-02-03 13:48:48 -05:00
while ( true ) {
2016-04-28 19:03:05 +02:00
std :: unique_ptr < WorkItem > i ;
2015-01-23 07:53:17 +01:00
{
2016-07-28 18:31:25 -04:00
std :: unique_lock < std :: mutex > lock ( cs );
2015-01-23 07:53:17 +01:00
while ( running && queue . empty ())
cond . wait ( lock );
if ( ! running )
break ;
2016-04-28 19:03:05 +02:00
i = std :: move ( queue . front ());
2015-01-23 07:53:17 +01:00
queue . pop_front ();
}
( * i )();
}
}
/** Interrupt and exit loops */
void Interrupt ()
{
2016-07-28 18:31:25 -04:00
std :: unique_lock < std :: mutex > lock ( cs );
2015-01-23 07:53:17 +01:00
running = false ;
cond . notify_all ();
}
};
struct HTTPPathHandler
{
HTTPPathHandler () {}
2016-05-27 08:00:56 +02:00
HTTPPathHandler ( std :: string _prefix , bool _exactMatch , HTTPRequestHandler _handler ) :
prefix ( _prefix ), exactMatch ( _exactMatch ), handler ( _handler )
2015-01-23 07:53:17 +01:00
{
}
std :: string prefix ;
bool exactMatch ;
HTTPRequestHandler handler ;
};
/** HTTP module state */
//! libevent event loop
2017-06-21 21:10:00 +02:00
static struct event_base * eventBase = nullptr ;
2015-01-23 07:53:17 +01:00
//! HTTP server
2017-06-21 21:10:00 +02:00
struct evhttp * eventHTTP = nullptr ;
2015-01-23 07:53:17 +01:00
//! List of subnets to allow RPC connections from
static std :: vector < CSubNet > rpc_allow_subnets ;
//! Work queue for handling longer requests off the event loop thread
2017-06-21 21:10:00 +02:00
static WorkQueue < HTTPClosure >* workQueue = nullptr ;
2015-01-23 07:53:17 +01:00
//! Handlers for (sub)paths
std :: vector < HTTPPathHandler > pathHandlers ;
2015-09-24 17:29:22 +02:00
//! Bound listening sockets
std :: vector < evhttp_bound_socket *> boundSockets ;
2015-01-23 07:53:17 +01:00
/** Check if a network address is allowed to access the HTTP server */
static bool ClientAllowed ( const CNetAddr & netaddr )
{
if ( ! netaddr . IsValid ())
return false ;
2016-07-28 18:31:25 -04:00
for ( const CSubNet & subnet : rpc_allow_subnets )
2015-01-23 07:53:17 +01:00
if ( subnet . Match ( netaddr ))
return true ;
return false ;
}
/** Initialize ACL list for HTTP server */
static bool InitHTTPAllowList ()
{
rpc_allow_subnets . clear ();
2016-05-31 15:50:24 -04:00
CNetAddr localv4 ;
CNetAddr localv6 ;
LookupHost ( "127.0.0.1" , localv4 , false );
LookupHost ( "::1" , localv6 , false );
2016-08-12 14:21:50 -04:00
rpc_allow_subnets . push_back ( CSubNet ( localv4 , 8 )); // always allow IPv4 local subnet
2016-05-31 15:50:24 -04:00
rpc_allow_subnets . push_back ( CSubNet ( localv6 )); // always allow IPv6 localhost
2017-03-29 17:51:41 +02:00
for ( const std :: string & strAllow : gArgs . GetArgs ( "-rpcallowip" )) {
2017-06-27 03:10:39 +02:00
CSubNet subnet ;
LookupSubNet ( strAllow . c_str (), subnet );
if ( ! subnet . IsValid ()) {
uiInterface . ThreadSafeMessageBox (
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 ),
"" , CClientUIInterface :: MSG_ERROR );
return false ;
}
rpc_allow_subnets . push_back ( subnet );
2015-01-23 07:53:17 +01:00
}
std :: string strAllowed ;
2016-07-28 18:31:25 -04:00
for ( const CSubNet & subnet : rpc_allow_subnets )
2015-01-23 07:53:17 +01:00
strAllowed += subnet . ToString () + " " ;
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Allowing HTTP connections from: %s \n " , strAllowed );
2015-01-23 07:53:17 +01:00
return true ;
}
/** HTTP request method as string - use for logging only */
static std :: string RequestMethodString ( HTTPRequest :: RequestMethod m )
{
switch ( m ) {
case HTTPRequest :: GET :
return "GET" ;
break ;
case HTTPRequest :: POST :
return "POST" ;
break ;
case HTTPRequest :: HEAD :
return "HEAD" ;
break ;
case HTTPRequest :: PUT :
return "PUT" ;
break ;
default :
return "unknown" ;
}
}
/** HTTP request callback */
static void http_request_cb ( struct evhttp_request * req , void * arg )
{
2017-11-01 12:02:57 -04:00
// Disable reading to work around a libevent bug, fixed in 2.2.0.
2017-11-02 14:37:33 -04:00
if ( event_get_version_number () >= 0x02010600 && event_get_version_number () < 0x02020001 ) {
2017-11-01 12:02:57 -04:00
evhttp_connection * conn = evhttp_request_get_connection ( req );
if ( conn ) {
bufferevent * bev = evhttp_connection_get_bufferevent ( conn );
if ( bev ) {
bufferevent_disable ( bev , EV_READ );
}
}
}
2016-04-28 13:40:20 +02:00
std :: unique_ptr < HTTPRequest > hreq ( new HTTPRequest ( req ));
2015-01-23 07:53:17 +01:00
// Early address-based allow check
if ( ! ClientAllowed ( hreq -> GetPeer ())) {
2018-10-31 11:42:01 +01:00
LogPrint ( BCLog :: HTTP , "HTTP request from %s rejected: Client network is not allowed RPC access \n " ,
hreq -> GetPeer (). ToString ());
2015-01-23 07:53:17 +01:00
hreq -> WriteReply ( HTTP_FORBIDDEN );
return ;
}
// Early reject unknown HTTP methods
if ( hreq -> GetRequestMethod () == HTTPRequest :: UNKNOWN ) {
2018-10-31 11:42:01 +01:00
LogPrint ( BCLog :: HTTP , "HTTP request from %s rejected: Unknown HTTP request method \n " ,
hreq -> GetPeer (). ToString ());
2015-01-23 07:53:17 +01:00
hreq -> WriteReply ( HTTP_BADMETHOD );
return ;
}
2018-10-31 11:42:01 +01:00
LogPrint ( BCLog :: HTTP , "Received a %s request for %s from %s \n " ,
RequestMethodString ( hreq -> GetRequestMethod ()), SanitizeString ( hreq -> GetURI ()). substr ( 0 , 100 ), hreq -> GetPeer (). ToString ());
2015-01-23 07:53:17 +01:00
// Find registered handler for prefix
std :: string strURI = hreq -> GetURI ();
std :: string path ;
std :: vector < HTTPPathHandler >:: const_iterator i = pathHandlers . begin ();
std :: vector < HTTPPathHandler >:: const_iterator iend = pathHandlers . end ();
for (; i != iend ; ++ i ) {
bool match = false ;
if ( i -> exactMatch )
match = ( strURI == i -> prefix );
else
match = ( strURI . substr ( 0 , i -> prefix . size ()) == i -> prefix );
if ( match ) {
path = strURI . substr ( i -> prefix . size ());
break ;
}
}
// Dispatch to worker thread
if ( i != iend ) {
2016-05-04 16:05:17 +02:00
std :: unique_ptr < HTTPWorkItem > item ( new HTTPWorkItem ( std :: move ( hreq ), path , i -> handler ));
2015-01-23 07:53:17 +01:00
assert ( workQueue );
if ( workQueue -> Enqueue ( item . get ()))
item . release (); /* if true, queue took ownership */
2016-05-04 15:37:26 +02:00
else {
LogPrintf ( "WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting \n " );
2015-01-23 07:53:17 +01:00
item -> req -> WriteReply ( HTTP_INTERNAL , "Work queue depth exceeded" );
2016-05-04 15:37:26 +02:00
}
2015-01-23 07:53:17 +01:00
} else {
hreq -> WriteReply ( HTTP_NOTFOUND );
}
}
2015-09-24 17:29:22 +02:00
/** Callback to reject HTTP requests after shutdown. */
static void http_reject_request_cb ( struct evhttp_request * req , void * )
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Rejecting request while shutting down \n " );
2017-08-07 07:36:37 +02:00
evhttp_send_error ( req , HTTP_SERVUNAVAIL , nullptr );
2015-09-24 17:29:22 +02:00
}
2015-01-23 07:53:17 +01:00
/** Event dispatcher thread */
2018-06-27 23:25:42 +02:00
static bool ThreadHTTP ( struct event_base * base )
2015-01-23 07:53:17 +01:00
{
RenameThread ( "bitcoin-http" );
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Entering http event loop \n " );
2015-01-23 07:53:17 +01:00
event_base_dispatch ( base );
// Event loop will be interrupted by InterruptHTTPServer()
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Exited http event loop \n " );
2016-07-28 17:52:51 -04:00
return event_base_got_break ( base ) == 0 ;
2015-01-23 07:53:17 +01:00
}
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses ( struct evhttp * http )
{
2017-08-01 21:17:40 +02:00
int defaultPort = gArgs . GetArg ( "-rpcport" , BaseParams (). RPCPort ());
2015-01-23 07:53:17 +01:00
std :: vector < std :: pair < std :: string , uint16_t > > endpoints ;
// Determine what addresses to bind to
2017-08-01 21:17:40 +02:00
if ( ! gArgs . IsArgSet ( "-rpcallowip" )) { // Default to loopback if not allowing external IPs
2015-01-23 07:53:17 +01:00
endpoints . push_back ( std :: make_pair ( "::1" , defaultPort ));
endpoints . push_back ( std :: make_pair ( "127.0.0.1" , defaultPort ));
2017-08-01 21:17:40 +02:00
if ( gArgs . IsArgSet ( "-rpcbind" )) {
2015-01-23 07:53:17 +01:00
LogPrintf ( "WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect \n " );
}
2017-05-07 18:54:43 +02:00
} else if ( gArgs . IsArgSet ( "-rpcbind" )) { // Specific bind address
2017-05-07 19:37:54 +02:00
for ( const std :: string & strRPCBind : gArgs . GetArgs ( "-rpcbind" )) {
2015-01-23 07:53:17 +01:00
int port = defaultPort ;
std :: string host ;
2017-05-07 19:37:54 +02:00
SplitHostPort ( strRPCBind , port , host );
2015-01-23 07:53:17 +01:00
endpoints . push_back ( std :: make_pair ( host , port ));
}
} else { // No specific bind address specified, bind to any
endpoints . push_back ( std :: make_pair ( "::" , defaultPort ));
endpoints . push_back ( std :: make_pair ( "0.0.0.0" , defaultPort ));
}
// Bind addresses
for ( std :: vector < std :: pair < std :: string , uint16_t > >:: iterator i = endpoints . begin (); i != endpoints . end (); ++ i ) {
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Binding RPC on address %s port %i \n " , i -> first , i -> second );
2017-08-07 07:36:37 +02:00
evhttp_bound_socket * bind_handle = evhttp_bind_socket_with_handle ( http , i -> first . empty () ? nullptr : i -> first . c_str (), i -> second );
2015-09-24 17:29:22 +02:00
if ( bind_handle ) {
boundSockets . push_back ( bind_handle );
2015-01-23 07:53:17 +01:00
} else {
LogPrintf ( "Binding RPC on address %s port %i failed. \n " , i -> first , i -> second );
}
}
2015-09-24 17:29:22 +02:00
return ! boundSockets . empty ();
2015-01-23 07:53:17 +01:00
}
/** Simple wrapper to set thread name and run work queue */
static void HTTPWorkQueueRun ( WorkQueue < HTTPClosure >* queue )
{
RenameThread ( "bitcoin-httpworker" );
queue -> Run ();
}
2015-09-18 14:58:08 +02:00
/** libevent event log callback */
static void libevent_log_cb ( int severity , const char * msg )
{
2015-11-14 13:54:21 +00:00
#ifndef EVENT_LOG_WARN
// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
# define EVENT_LOG_WARN _EVENT_LOG_WARN
#endif
2015-09-18 14:58:08 +02:00
if ( severity >= EVENT_LOG_WARN ) // Log warn messages and higher without debug category
LogPrintf ( "libevent: %s \n " , msg );
else
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: LIBEVENT , "libevent: %s \n " , msg );
2015-09-18 14:58:08 +02:00
}
2015-08-28 16:55:16 +02:00
bool InitHTTPServer ()
2015-01-23 07:53:17 +01:00
{
if ( ! InitHTTPAllowList ())
return false ;
2017-08-01 21:17:40 +02:00
if ( gArgs . GetBoolArg ( "-rpcssl" , false )) {
2015-01-23 07:53:17 +01:00
uiInterface . ThreadSafeMessageBox (
"SSL mode for RPC (-rpcssl) is no longer supported." ,
"" , CClientUIInterface :: MSG_ERROR );
return false ;
}
2015-09-18 14:58:08 +02:00
// Redirect libevent's logging to our own log
event_set_log_callback ( & libevent_log_cb );
2017-04-10 10:27:36 -04:00
// Update libevent's log handling. Returns false if our version of
// libevent doesn't support debug logging, in which case we should
// clear the BCLog::LIBEVENT flag.
2018-04-11 13:02:01 -07:00
if ( ! UpdateHTTPServerLogging ( g_logger -> WillLogCategory ( BCLog :: LIBEVENT ))) {
g_logger -> DisableCategory ( BCLog :: LIBEVENT );
2016-12-25 20:19:40 +00:00
}
2017-04-10 10:27:36 -04:00
2015-01-23 07:53:17 +01:00
#ifdef WIN32
evthread_use_windows_threads ();
#else
evthread_use_pthreads ();
#endif
2017-01-11 22:50:00 +09:00
raii_event_base base_ctr = obtain_event_base ();
2015-01-23 07:53:17 +01:00
/* Create a new evhttp object to handle requests. */
2017-01-11 22:50:00 +09:00
raii_evhttp http_ctr = obtain_evhttp ( base_ctr . get ());
struct evhttp * http = http_ctr . get ();
2015-01-23 07:53:17 +01:00
if ( ! http ) {
LogPrintf ( "couldn't create evhttp. Exiting. \n " );
return false ;
}
2017-08-01 21:17:40 +02:00
evhttp_set_timeout ( http , gArgs . GetArg ( "-rpcservertimeout" , DEFAULT_HTTP_SERVER_TIMEOUT ));
2015-10-20 11:35:10 +02:00
evhttp_set_max_headers_size ( http , MAX_HEADERS_SIZE );
2015-01-23 07:53:17 +01:00
evhttp_set_max_body_size ( http , MAX_SIZE );
2017-08-07 07:36:37 +02:00
evhttp_set_gencb ( http , http_request_cb , nullptr );
2015-01-23 07:53:17 +01:00
if ( ! HTTPBindAddresses ( http )) {
LogPrintf ( "Unable to bind any endpoint for RPC server \n " );
return false ;
}
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Initialized HTTP server \n " );
2017-08-01 21:17:40 +02:00
int workQueueDepth = std :: max (( long ) gArgs . GetArg ( "-rpcworkqueue" , DEFAULT_HTTP_WORKQUEUE ), 1L );
2015-08-28 16:55:16 +02:00
LogPrintf ( "HTTP: creating work queue of depth %d \n " , workQueueDepth );
2015-01-23 07:53:17 +01:00
2015-08-28 16:55:16 +02:00
workQueue = new WorkQueue < HTTPClosure > ( workQueueDepth );
2017-08-16 00:24:39 +02:00
// transfer ownership to eventBase/HTTP via .release()
2017-01-11 22:50:00 +09:00
eventBase = base_ctr . release ();
eventHTTP = http_ctr . release ();
2015-08-28 16:55:16 +02:00
return true ;
}
2017-04-10 10:27:36 -04:00
bool UpdateHTTPServerLogging ( bool enable ) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010100
if ( enable ) {
event_enable_debug_logging ( EVENT_DBG_ALL );
} else {
event_enable_debug_logging ( EVENT_DBG_NONE );
}
return true ;
#else
// Can't update libevent logging if version < 02010100
return false ;
#endif
}
2016-07-28 18:31:25 -04:00
std :: thread threadHTTP ;
2016-07-28 17:52:51 -04:00
std :: future < bool > threadResult ;
2018-02-06 19:27:13 +01:00
static std :: vector < std :: thread > g_thread_http_workers ;
2015-11-11 17:34:10 +01:00
2018-07-27 08:22:42 +02:00
void StartHTTPServer ()
2015-08-28 16:55:16 +02:00
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Starting HTTP server \n " );
2017-08-01 21:17:40 +02:00
int rpcThreads = std :: max (( long ) gArgs . GetArg ( "-rpcthreads" , DEFAULT_HTTP_THREADS ), 1L );
2015-08-28 16:55:16 +02:00
LogPrintf ( "HTTP: starting %d worker threads \n " , rpcThreads );
2018-06-27 23:25:42 +02:00
std :: packaged_task < bool ( event_base * ) > task ( ThreadHTTP );
2016-07-28 17:52:51 -04:00
threadResult = task . get_future ();
2018-06-27 23:25:42 +02:00
threadHTTP = std :: thread ( std :: move ( task ), eventBase );
2015-01-23 07:53:17 +01:00
2016-07-28 18:21:00 -04:00
for ( int i = 0 ; i < rpcThreads ; i ++ ) {
2018-02-06 19:27:13 +01:00
g_thread_http_workers . emplace_back ( HTTPWorkQueueRun , workQueue );
2016-07-28 18:21:00 -04:00
}
2015-01-23 07:53:17 +01:00
}
void InterruptHTTPServer ()
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Interrupting HTTP server \n " );
2015-09-24 17:29:22 +02:00
if ( eventHTTP ) {
// Unlisten sockets
2016-07-28 18:31:25 -04:00
for ( evhttp_bound_socket * socket : boundSockets ) {
2015-09-24 17:29:22 +02:00
evhttp_del_accept_socket ( eventHTTP , socket );
}
// Reject requests on current connections
2017-08-07 07:36:37 +02:00
evhttp_set_gencb ( eventHTTP , http_reject_request_cb , nullptr );
2015-09-24 17:29:22 +02:00
}
2015-01-23 07:53:17 +01:00
if ( workQueue )
workQueue -> Interrupt ();
}
void StopHTTPServer ()
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Stopping HTTP server \n " );
2015-09-25 13:49:08 +02:00
if ( workQueue ) {
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Waiting for HTTP worker threads to exit \n " );
2018-02-06 19:27:13 +01:00
for ( auto & thread : g_thread_http_workers ) {
thread . join ();
}
g_thread_http_workers . clear ();
2015-09-25 13:49:08 +02:00
delete workQueue ;
2017-03-18 12:40:58 +01:00
workQueue = nullptr ;
2015-09-25 13:49:08 +02:00
}
2015-11-11 17:34:10 +01:00
if ( eventBase ) {
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Waiting for HTTP event thread to exit \n " );
2017-08-08 13:30:04 +01:00
// Exit the event loop as soon as there are no active events.
event_base_loopexit ( eventBase , nullptr );
2015-11-11 17:34:10 +01:00
// Give event loop a few seconds to exit (to send back last RPC responses), then break it
// Before this was solved with event_base_loopexit, but that didn't work as expected in
// at least libevent 2.0.21 and always introduced a delay. In libevent
// master that appears to be solved, so in the future that solution
// could be used again (if desirable).
// (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
2016-07-28 17:52:51 -04:00
if ( threadResult . valid () && threadResult . wait_for ( std :: chrono :: milliseconds ( 2000 )) == std :: future_status :: timeout ) {
2015-11-11 17:34:10 +01:00
LogPrintf ( "HTTP event loop did not exit within allotted time, sending loopbreak \n " );
event_base_loopbreak ( eventBase );
}
2016-07-28 17:52:51 -04:00
threadHTTP . join ();
2015-11-11 17:34:10 +01:00
}
2015-01-23 07:53:17 +01:00
if ( eventHTTP ) {
evhttp_free ( eventHTTP );
2017-06-21 21:10:00 +02:00
eventHTTP = nullptr ;
2015-01-23 07:53:17 +01:00
}
if ( eventBase ) {
event_base_free ( eventBase );
2017-06-21 21:10:00 +02:00
eventBase = nullptr ;
2015-01-23 07:53:17 +01:00
}
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Stopped HTTP server \n " );
2015-01-23 07:53:17 +01:00
}
struct event_base * EventBase ()
{
return eventBase ;
}
static void httpevent_callback_fn ( evutil_socket_t , short , void * data )
{
2015-08-28 16:46:20 +02:00
// Static handler: simply call inner handler
2017-06-01 16:13:35 +02:00
HTTPEvent * self = static_cast < HTTPEvent *> ( data );
2015-08-28 16:46:20 +02:00
self -> handler ();
if ( self -> deleteWhenTriggered )
delete self ;
2015-01-23 07:53:17 +01:00
}
2016-05-27 08:00:56 +02:00
HTTPEvent :: HTTPEvent ( struct event_base * base , bool _deleteWhenTriggered , const std :: function < void ( void ) >& _handler ) :
deleteWhenTriggered ( _deleteWhenTriggered ), handler ( _handler )
2015-01-23 07:53:17 +01:00
{
ev = event_new ( base , - 1 , 0 , httpevent_callback_fn , this );
assert ( ev );
}
HTTPEvent ::~ HTTPEvent ()
{
event_free ( ev );
}
void HTTPEvent :: trigger ( struct timeval * tv )
{
2017-08-07 07:36:37 +02:00
if ( tv == nullptr )
2015-01-23 07:53:17 +01:00
event_active ( ev , 0 , 0 ); // immediately trigger event in main thread
else
evtimer_add ( ev , tv ); // trigger after timeval passed
}
2016-05-27 08:00:56 +02:00
HTTPRequest :: HTTPRequest ( struct evhttp_request * _req ) : req ( _req ),
2015-01-23 07:53:17 +01:00
replySent ( false )
{
}
HTTPRequest ::~ HTTPRequest ()
{
if ( ! replySent ) {
// Keep track of whether reply was sent to avoid request leaks
LogPrintf ( "%s: Unhandled request \n " , __func__ );
WriteReply ( HTTP_INTERNAL , "Unhandled request" );
}
// evhttpd cleans up the request, as long as a reply was sent.
}
std :: pair < bool , std :: string > HTTPRequest :: GetHeader ( const std :: string & hdr )
{
const struct evkeyvalq * headers = evhttp_request_get_input_headers ( req );
assert ( headers );
const char * val = evhttp_find_header ( headers , hdr . c_str ());
if ( val )
return std :: make_pair ( true , val );
else
return std :: make_pair ( false , "" );
}
std :: string HTTPRequest :: ReadBody ()
{
struct evbuffer * buf = evhttp_request_get_input_buffer ( req );
if ( ! buf )
return "" ;
size_t size = evbuffer_get_length ( buf );
/** Trivial implementation: if this is ever a performance bottleneck,
* internal copying can be avoided in multi-segment buffers by using
* evbuffer_peek and an awkward loop. Though in that case, it'd be even
* better to not copy into an intermediate string but use a stream
* abstraction to consume the evbuffer on the fly in the parsing algorithm.
*/
const char * data = ( const char * ) evbuffer_pullup ( buf , size );
2017-08-07 07:36:37 +02:00
if ( ! data ) // returns nullptr in case of empty buffer
2015-01-23 07:53:17 +01:00
return "" ;
std :: string rv ( data , size );
evbuffer_drain ( buf , size );
return rv ;
}
void HTTPRequest :: WriteHeader ( const std :: string & hdr , const std :: string & value )
{
struct evkeyvalq * headers = evhttp_request_get_output_headers ( req );
assert ( headers );
evhttp_add_header ( headers , hdr . c_str (), value . c_str ());
}
/** Closure sent to main thread to request a reply to be sent to
* a HTTP request.
* Replies must be sent in the main loop in the main http thread,
* this cannot be done from worker threads.
*/
void HTTPRequest :: WriteReply ( int nStatus , const std :: string & strReply )
{
assert ( ! replySent && req );
// Send event to main http thread to send reply message
struct evbuffer * evb = evhttp_request_get_output_buffer ( req );
assert ( evb );
evbuffer_add ( evb , strReply . data (), strReply . size ());
2017-11-01 12:02:57 -04:00
auto req_copy = req ;
HTTPEvent * ev = new HTTPEvent ( eventBase , true , [ req_copy , nStatus ]{
evhttp_send_reply ( req_copy , nStatus , nullptr , nullptr );
// Re-enable reading from the socket. This is the second part of the libevent
// workaround above.
2017-11-02 14:37:33 -04:00
if ( event_get_version_number () >= 0x02010600 && event_get_version_number () < 0x02020001 ) {
2017-11-01 12:02:57 -04:00
evhttp_connection * conn = evhttp_request_get_connection ( req_copy );
if ( conn ) {
bufferevent * bev = evhttp_connection_get_bufferevent ( conn );
if ( bev ) {
bufferevent_enable ( bev , EV_READ | EV_WRITE );
}
}
}
});
2017-06-21 21:10:00 +02:00
ev -> trigger ( nullptr );
2015-01-23 07:53:17 +01:00
replySent = true ;
2017-06-21 21:10:00 +02:00
req = nullptr ; // transferred back to main thread
2015-01-23 07:53:17 +01:00
}
CService HTTPRequest :: GetPeer ()
{
evhttp_connection * con = evhttp_request_get_connection ( req );
CService peer ;
if ( con ) {
// evhttp retains ownership over returned address string
const char * address = "" ;
uint16_t port = 0 ;
evhttp_connection_get_peer ( con , ( char ** ) & address , & port );
2016-08-04 16:37:49 -04:00
peer = LookupNumeric ( address , port );
2015-01-23 07:53:17 +01:00
}
return peer ;
}
std :: string HTTPRequest :: GetURI ()
{
return evhttp_request_get_uri ( req );
}
HTTPRequest :: RequestMethod HTTPRequest :: GetRequestMethod ()
{
switch ( evhttp_request_get_command ( req )) {
case EVHTTP_REQ_GET :
return GET ;
break ;
case EVHTTP_REQ_POST :
return POST ;
break ;
case EVHTTP_REQ_HEAD :
return HEAD ;
break ;
case EVHTTP_REQ_PUT :
return PUT ;
break ;
default :
return UNKNOWN ;
break ;
}
}
void RegisterHTTPHandler ( const std :: string & prefix , bool exactMatch , const HTTPRequestHandler & handler )
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Registering HTTP handler for %s (exactmatch %d) \n " , prefix , exactMatch );
2015-01-23 07:53:17 +01:00
pathHandlers . push_back ( HTTPPathHandler ( prefix , exactMatch , handler ));
}
void UnregisterHTTPHandler ( const std :: string & prefix , bool exactMatch )
{
std :: vector < HTTPPathHandler >:: iterator i = pathHandlers . begin ();
std :: vector < HTTPPathHandler >:: iterator iend = pathHandlers . end ();
for (; i != iend ; ++ i )
if ( i -> prefix == prefix && i -> exactMatch == exactMatch )
break ;
if ( i != iend )
{
2016-12-25 20:19:40 +00:00
LogPrint ( BCLog :: HTTP , "Unregistering HTTP handler for %s (exactmatch %d) \n " , prefix , exactMatch );
2015-01-23 07:53:17 +01:00
pathHandlers . erase ( i );
}
}
2017-07-13 17:06:27 +02:00
std :: string urlDecode ( const std :: string & urlEncoded ) {
std :: string res ;
if ( ! urlEncoded . empty ()) {
2017-08-07 07:36:37 +02:00
char * decoded = evhttp_uridecode ( urlEncoded . c_str (), false , nullptr );
2017-07-13 17:06:27 +02:00
if ( decoded ) {
res = std :: string ( decoded );
free ( decoded );
}
}
return res ;
}