aboutsummaryrefslogtreecommitdiff
path: root/src/rpcserver.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/rpcserver.cpp')
-rw-r--r--src/rpcserver.cpp412
1 files changed, 249 insertions, 163 deletions
diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp
index d771a4242..5deb6a4e0 100644
--- a/src/rpcserver.cpp
+++ b/src/rpcserver.cpp
@@ -25,19 +25,22 @@
#include <boost/shared_ptr.hpp>
#include "json/json_spirit_writer_template.h"
-using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
+using namespace std;
static std::string strRPCUserColonPass;
+static bool fRPCRunning = false;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static boost::asio::io_service::work *rpc_dummy_work = NULL;
+static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from
+static std::vector< boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors;
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
@@ -95,16 +98,6 @@ Value ValueFromAmount(int64_t amount)
return (double)amount / (double)COIN;
}
-std::string HexBits(unsigned int nBits)
-{
- union {
- int32_t nBits;
- char cBits[4];
- } uBits;
- uBits.nBits = htonl((int32_t)nBits);
- return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
-}
-
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
@@ -228,6 +221,7 @@ static const CRPCCommand vRPCCommands[] =
{ "stop", &stop, true, true, false },
/* P2P networking */
+ { "getnetworkinfo", &getnetworkinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
@@ -236,10 +230,11 @@ static const CRPCCommand vRPCCommands[] =
{ "ping", &ping, true, false, false },
/* Block chain and UTXO */
+ { "getblockchaininfo", &getblockchaininfo, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getblockcount", &getblockcount, true, false, false },
- { "getblock", &getblock, false, false, false },
- { "getblockhash", &getblockhash, false, false, false },
+ { "getblock", &getblock, true, false, false },
+ { "getblockhash", &getblockhash, true, false, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "gettxout", &gettxout, true, false, false },
@@ -250,30 +245,33 @@ static const CRPCCommand vRPCCommands[] =
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
- { "submitblock", &submitblock, false, false, false },
+ { "prioritisetransaction", &prioritisetransaction, true, false, false },
+ { "submitblock", &submitblock, true, true, false },
/* Raw transactions */
- { "createrawtransaction", &createrawtransaction, false, false, false },
- { "decoderawtransaction", &decoderawtransaction, false, false, false },
- { "decodescript", &decodescript, false, false, false },
- { "getrawtransaction", &getrawtransaction, false, false, false },
+ { "createrawtransaction", &createrawtransaction, true, false, false },
+ { "decoderawtransaction", &decoderawtransaction, true, false, false },
+ { "decodescript", &decodescript, true, false, false },
+ { "getrawtransaction", &getrawtransaction, true, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false }, /* uses wallet if enabled */
/* Utility functions */
{ "createmultisig", &createmultisig, true, true , false },
{ "validateaddress", &validateaddress, true, false, false }, /* uses wallet if enabled */
- { "verifymessage", &verifymessage, false, false, false },
+ { "verifymessage", &verifymessage, true, false, false },
+ { "estimatefee", &estimatefee, true, true, false },
+ { "estimatepriority", &estimatepriority, true, true, false },
#ifdef ENABLE_WALLET
/* Wallet */
- { "addmultisigaddress", &addmultisigaddress, false, false, true },
+ { "addmultisigaddress", &addmultisigaddress, true, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "dumpwallet", &dumpwallet, true, false, true },
- { "encryptwallet", &encryptwallet, false, false, true },
+ { "encryptwallet", &encryptwallet, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
- { "getaccount", &getaccount, false, false, true },
+ { "getaccount", &getaccount, true, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "getbalance", &getbalance, false, false, true },
{ "getnewaddress", &getnewaddress, true, false, true },
@@ -282,9 +280,10 @@ static const CRPCCommand vRPCCommands[] =
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "gettransaction", &gettransaction, false, false, true },
{ "getunconfirmedbalance", &getunconfirmedbalance, false, false, true },
- { "getwalletinfo", &getwalletinfo, true, false, true },
- { "importprivkey", &importprivkey, false, false, true },
- { "importwallet", &importwallet, false, false, true },
+ { "getwalletinfo", &getwalletinfo, false, false, true },
+ { "importprivkey", &importprivkey, true, false, true },
+ { "importwallet", &importwallet, true, false, true },
+ { "importaddress", &importaddress, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
@@ -294,22 +293,21 @@ static const CRPCCommand vRPCCommands[] =
{ "listsinceblock", &listsinceblock, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listunspent", &listunspent, false, false, true },
- { "lockunspent", &lockunspent, false, false, true },
+ { "lockunspent", &lockunspent, true, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "setaccount", &setaccount, true, false, true },
- { "settxfee", &settxfee, false, false, true },
- { "signmessage", &signmessage, false, false, true },
+ { "settxfee", &settxfee, true, false, true },
+ { "signmessage", &signmessage, true, false, true },
{ "walletlock", &walletlock, true, false, true },
- { "walletpassphrasechange", &walletpassphrasechange, false, false, true },
+ { "walletpassphrasechange", &walletpassphrasechange, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
/* Wallet-enabled mining */
{ "getgenerate", &getgenerate, true, false, false },
{ "gethashespersec", &gethashespersec, true, false, false },
- { "getwork", &getwork, true, false, true },
{ "setgenerate", &setgenerate, true, true, false },
#endif // ENABLE_WALLET
};
@@ -356,38 +354,36 @@ void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
-bool ClientAllowed(const boost::asio::ip::address& address)
+CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address)
{
+ CNetAddr netaddr;
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
- return ClientAllowed(address.to_v6().to_v4());
-
- if (address == asio::ip::address_v4::loopback()
- || address == asio::ip::address_v6::loopback()
- || (address.is_v4()
- // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
- && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
- return true;
-
- const string strAddress = address.to_string();
- const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
- BOOST_FOREACH(string strAllow, vAllow)
- if (WildcardMatch(strAddress, strAllow))
- return true;
- return false;
+ address = address.to_v6().to_v4();
+
+ if(address.is_v4())
+ {
+ boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes();
+ netaddr.SetRaw(NET_IPV4, &bytes[0]);
+ }
+ else
+ {
+ boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes();
+ netaddr.SetRaw(NET_IPV6, &bytes[0]);
+ }
+ return netaddr;
}
-class AcceptedConnection
+bool ClientAllowed(const boost::asio::ip::address& address)
{
-public:
- virtual ~AcceptedConnection() {}
-
- virtual std::iostream& stream() = 0;
- virtual std::string peer_address_to_string() const = 0;
- virtual void close() = 0;
-};
+ CNetAddr netaddr = BoostAsioToCNetAddr(address);
+ BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
+ if (subnet.Match(netaddr))
+ return true;
+ return false;
+}
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
@@ -433,7 +429,7 @@ template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
- AcceptedConnection* conn,
+ boost::shared_ptr< AcceptedConnection > conn,
const boost::system::error_code& error);
/**
@@ -445,7 +441,7 @@ static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketA
const bool fUseSSL)
{
// Accept connection
- AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
+ boost::shared_ptr< AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL));
acceptor->async_accept(
conn->sslStream.lowest_layer(),
@@ -455,7 +451,7 @@ static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketA
boost::ref(context),
fUseSSL,
conn,
- boost::asio::placeholders::error));
+ _1));
}
@@ -466,21 +462,20 @@ template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
- AcceptedConnection* conn,
+ boost::shared_ptr< AcceptedConnection > conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
- AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
+ AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn.get());
- // TODO: Actually handle errors
if (error)
{
- delete conn;
+ // TODO: Actually handle errors
+ LogPrintf("%s: Error: %s\n", __func__, error.message());
}
-
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
@@ -488,24 +483,56 @@ static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol,
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
- conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
- delete conn;
+ conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush;
+ conn->close();
}
else {
- ServiceConnection(conn);
+ ServiceConnection(conn.get());
conn->close();
- delete conn;
}
}
+static ip::tcp::endpoint ParseEndpoint(const std::string &strEndpoint, int defaultPort)
+{
+ std::string addr;
+ int port = defaultPort;
+ SplitHostPort(strEndpoint, port, addr);
+ return ip::tcp::endpoint(asio::ip::address::from_string(addr), port);
+}
+
void StartRPCThreads()
{
+ rpc_allow_subnets.clear();
+ rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
+ rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
+ if (mapMultiArgs.count("-rpcallowip"))
+ {
+ const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
+ BOOST_FOREACH(string strAllow, vAllow)
+ {
+ CSubNet subnet(strAllow);
+ 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);
+ StartShutdown();
+ return;
+ }
+ rpc_allow_subnets.push_back(subnet);
+ }
+ }
+ std::string strAllowed;
+ BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
+ strAllowed += subnet.ToString() + " ";
+ LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed);
+
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if (((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
{
unsigned char rand_pwd[32];
- RAND_bytes(rand_pwd, 32);
+ GetRandBytes(rand_pwd, 32);
string strWhatAmI = "To use bitcoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
@@ -554,56 +581,74 @@ void StartRPCThreads()
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
- // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
- const bool loopback = !mapArgs.count("-rpcallowip");
- asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
- ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort()));
- boost::system::error_code v6_only_error;
- boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
-
- bool fListening = false;
- std::string strerr;
- try
+ std::vector<ip::tcp::endpoint> vEndpoints;
+ bool bBindAny = false;
+ int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
+ if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs
{
- acceptor->open(endpoint.protocol());
- acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
-
- // Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
- acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
-
- acceptor->bind(endpoint);
- acceptor->listen(socket_base::max_connections);
-
- RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
-
- fListening = true;
- }
- catch(boost::system::system_error &e)
+ vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::loopback(), defaultPort));
+ vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::loopback(), defaultPort));
+ if (mapArgs.count("-rpcbind"))
+ {
+ LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
+ }
+ } else if (mapArgs.count("-rpcbind")) // Specific bind address
{
- strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
+ BOOST_FOREACH(const std::string &addr, mapMultiArgs["-rpcbind"])
+ {
+ try {
+ vEndpoints.push_back(ParseEndpoint(addr, defaultPort));
+ }
+ catch(boost::system::system_error &e)
+ {
+ uiInterface.ThreadSafeMessageBox(
+ strprintf(_("Could not parse -rpcbind value %s as network address"), addr),
+ "", CClientUIInterface::MSG_ERROR);
+ StartShutdown();
+ return;
+ }
+ }
+ } else { // No specific bind address specified, bind to any
+ vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::any(), defaultPort));
+ vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::any(), defaultPort));
+ // Prefer making the socket dual IPv6/IPv4 instead of binding
+ // to both addresses seperately.
+ bBindAny = true;
}
- try {
- // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
- if (!fListening || loopback || v6_only_error)
- {
- bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
- endpoint.address(bindAddress);
+ bool fListening = false;
+ std::string strerr;
+ BOOST_FOREACH(const ip::tcp::endpoint &endpoint, vEndpoints)
+ {
+ asio::ip::address bindAddress = endpoint.address();
+ LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", bindAddress.to_string(), endpoint.port(), bBindAny);
+ boost::system::error_code v6_only_error;
+ boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
- acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
+ try {
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
+
+ // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address
+ acceptor->set_option(boost::asio::ip::v6_only(
+ !bBindAny || bindAddress != asio::ip::address_v6::any()), v6_only_error);
+
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
+ rpc_acceptors.push_back(acceptor);
+ // If dual IPv6/IPv4 bind succesful, skip binding to IPv4 separately
+ if(bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error)
+ break;
+ }
+ catch(boost::system::system_error &e)
+ {
+ LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", bindAddress.to_string(), endpoint.port(), e.what());
+ strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), bindAddress.to_string(), endpoint.port(), e.what());
}
- }
- catch(boost::system::system_error &e)
- {
- strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
@@ -615,6 +660,7 @@ void StartRPCThreads()
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
+ fRPCRunning = true;
}
void StartDummyRPCThread()
@@ -627,15 +673,37 @@ void StartDummyRPCThread()
rpc_dummy_work = new asio::io_service::work(*rpc_io_service);
rpc_worker_group = new boost::thread_group();
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
+ fRPCRunning = true;
}
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
-
+ // Set this to false first, so that longpolling loops will exit when woken up
+ fRPCRunning = false;
+
+ // First, cancel all timers and acceptors
+ // This is not done automatically by ->stop(), and in some cases the destructor of
+ // asio::io_service can hang if this is skipped.
+ boost::system::error_code ec;
+ BOOST_FOREACH(const boost::shared_ptr<ip::tcp::acceptor> &acceptor, rpc_acceptors)
+ {
+ acceptor->cancel(ec);
+ if (ec)
+ LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message());
+ }
+ rpc_acceptors.clear();
+ BOOST_FOREACH(const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) &timer, deadlineTimers)
+ {
+ timer.second->cancel(ec);
+ if (ec)
+ LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message());
+ }
deadlineTimers.clear();
+
rpc_io_service->stop();
+ cvBlockChange.notify_all();
if (rpc_worker_group != NULL)
rpc_worker_group->join_all();
delete rpc_dummy_work; rpc_dummy_work = NULL;
@@ -644,6 +712,11 @@ void StopRPCThreads()
delete rpc_io_service; rpc_io_service = NULL;
}
+bool IsRPCRunning()
+{
+ return fRPCRunning;
+}
+
void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
{
if (!err)
@@ -691,7 +764,7 @@ void JSONRequest::parse(const Value& valRequest)
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
- if (strMethod != "getwork" && strMethod != "getblocktemplate")
+ if (strMethod != "getblocktemplate")
LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod);
// Parse params
@@ -738,6 +811,71 @@ static string JSONRPCExecBatch(const Array& vReq)
return write_string(Value(ret), false) + "\n";
}
+static bool HTTPReq_JSONRPC(AcceptedConnection *conn,
+ string& strRequest,
+ map<string, string>& mapHeaders,
+ bool fRun)
+{
+ // Check authorization
+ if (mapHeaders.count("authorization") == 0)
+ {
+ conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
+ return false;
+ }
+
+ if (!HTTPAuthorized(mapHeaders))
+ {
+ LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
+ /* Deter brute-forcing short passwords.
+ If this results in a DoS the user really
+ shouldn't have their RPC port exposed. */
+ if (mapArgs["-rpcpassword"].size() < 20)
+ MilliSleep(250);
+
+ conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
+ return false;
+ }
+
+ JSONRequest jreq;
+ try
+ {
+ // Parse request
+ Value valRequest;
+ if (!read_string(strRequest, valRequest))
+ throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
+
+ string strReply;
+
+ // singleton request
+ if (valRequest.type() == obj_type) {
+ jreq.parse(valRequest);
+
+ Value result = tableRPC.execute(jreq.strMethod, jreq.params);
+
+ // Send reply
+ strReply = JSONRPCReply(result, Value::null, jreq.id);
+
+ // array of requests
+ } else if (valRequest.type() == array_type)
+ strReply = JSONRPCExecBatch(valRequest.get_array());
+ else
+ throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
+
+ conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
+ }
+ catch (Object& objError)
+ {
+ ErrorReply(conn->stream(), objError, jreq.id);
+ return false;
+ }
+ catch (std::exception& e)
+ {
+ ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
+ return false;
+ }
+ return true;
+}
+
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
@@ -754,67 +892,15 @@ void ServiceConnection(AcceptedConnection *conn)
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
- if (strURI != "/") {
- conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
- break;
- }
-
- // Check authorization
- if (mapHeaders.count("authorization") == 0)
- {
- conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
- break;
- }
- if (!HTTPAuthorized(mapHeaders))
- {
- LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
- /* Deter brute-forcing short passwords.
- If this results in a DoS the user really
- shouldn't have their RPC port exposed. */
- if (mapArgs["-rpcpassword"].size() < 20)
- MilliSleep(250);
-
- conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
- break;
- }
+ // HTTP Keep-Alive is false; close connection immediately
if (mapHeaders["connection"] == "close")
fRun = false;
- JSONRequest jreq;
- try
- {
- // Parse request
- Value valRequest;
- if (!read_string(strRequest, valRequest))
- throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
-
- string strReply;
-
- // singleton request
- if (valRequest.type() == obj_type) {
- jreq.parse(valRequest);
-
- Value result = tableRPC.execute(jreq.strMethod, jreq.params);
-
- // Send reply
- strReply = JSONRPCReply(result, Value::null, jreq.id);
-
- // array of requests
- } else if (valRequest.type() == array_type)
- strReply = JSONRPCExecBatch(valRequest.get_array());
- else
- throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
-
- conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
- }
- catch (Object& objError)
- {
- ErrorReply(conn->stream(), objError, jreq.id);
- break;
- }
- catch (std::exception& e)
- {
- ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
+ if (strURI == "/") {
+ if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun))
+ break;
+ } else {
+ conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
break;
}
}