Refactor RPCServer

This commit is contained in:
Vinnie Falco
2013-07-09 15:05:11 -07:00
parent 040c8f4de1
commit b343b0929a
17 changed files with 350 additions and 232 deletions

View File

@@ -1,39 +0,0 @@
//------------------------------------------------------------------------------
/*
Copyright (c) 2011-2013, OpenCoin, Inc.
*/
//==============================================================================
#ifndef RIPPLE_RPCSERVER_H_INCLUDED
#define RIPPLE_RPCSERVER_H_INCLUDED
// VFALCO NOTE This looks like intrusve shared object?
//
class RPCServer
: public boost::enable_shared_from_this <RPCServer>
, LeakChecked <RPCServer>
{
public:
typedef boost::shared_ptr <RPCServer> pointer;
public:
static pointer New (
boost::asio::io_service& io_service,
boost::asio::ssl::context& context,
NetworkOPs* mNetOps);
virtual AutoSocket& getSocket () = 0;
// VFALCO TODO Remove this since it exposes boost
virtual boost::asio::ip::tcp::socket& getRawSocket () = 0;
virtual void connected () = 0;
/** Retrieve the remote address as a string.
@return A std::string representing the remote address.
*/
virtual std::string getRemoteAddressText () = 0;
};
#endif

View File

@@ -0,0 +1,98 @@
//------------------------------------------------------------------------------
/*
Copyright (c) 2011-2013, OpenCoin, Inc.
*/
//==============================================================================
RPCServerHandler::RPCServerHandler (NetworkOPs& networkOPs)
: m_networkOPs (networkOPs)
{
}
std::string RPCServerHandler::createResponse (
int statusCode,
std::string const& description)
{
return HTTPReply (statusCode, description);
}
bool RPCServerHandler::isAuthorized (
std::map <std::string, std::string> const& headers)
{
return HTTPAuthorized (headers);
}
std::string RPCServerHandler::processRequest (std::string const& request, std::string const& remoteAddress)
{
Json::Value jvRequest;
{
Json::Reader reader;
if (! reader.parse (request, jvRequest) ||
jvRequest.isNull () ||
! jvRequest.isObject ())
{
return createResponse (400, "Unable to parse request");
}
}
int role = iAdminGet (jvRequest, remoteAddress);
// Parse id now so errors from here on will have the id
//
// VFALCO NOTE Except that "id" isn't included in the following errors...
//
Json::Value const id = jvRequest ["id"];
Json::Value const method = jvRequest ["method"];
if (method.isNull ())
{
return createResponse (400, "Null method");
}
else if (! method.isString ())
{
return createResponse (400, "method is not string");
}
std::string strMethod = method.asString ();
// Parse params
Json::Value params = jvRequest ["params"];
if (params.isNull ())
{
params = Json::Value (Json::arrayValue);
}
else if (!params.isArray ())
{
return HTTPReply (400, "params unparseable");
}
// VFALCO TODO Shouldn't we handle this earlier?
//
if (role == RPCHandler::FORBID)
{
// VFALCO TODO Needs implementing
// FIXME Needs implementing
// XXX This needs rate limiting to prevent brute forcing password.
return HTTPReply (403, "Forbidden");
}
std::string response;
WriteLog (lsINFO, RPCServer) << params;
RPCHandler rpcHandler (&m_networkOPs);
LoadType loadType = LT_RPCReference;
Json::Value const result = rpcHandler.doRpcCommand (strMethod, params, role, &loadType);
// VFALCO NOTE We discard loadType since there is no endpoint to punish
WriteLog (lsINFO, RPCServer) << result;
response = JSONRPCReply (result, Json::Value (), id);
return createResponse (200, response);
}

View File

@@ -0,0 +1,27 @@
//------------------------------------------------------------------------------
/*
Copyright (c) 2011-2013, OpenCoin, Inc.
*/
//==============================================================================
#ifndef RIPPLE_RPCSERVERHANDLER_H_INCLUDED
#define RIPPLE_RPCSERVERHANDLER_H_INCLUDED
/** Handles RPC requests.
*/
class RPCServerHandler : public RPCServer::Handler
{
public:
explicit RPCServerHandler (NetworkOPs& networkOPs);
std::string createResponse (int statusCode, std::string const& description);
bool isAuthorized (std::map <std::string, std::string> const& headers);
std::string processRequest (std::string const& request, std::string const& remoteAddress);
private:
NetworkOPs& m_networkOPs;
};
#endif

View File

@@ -182,7 +182,7 @@ namespace ripple
#include "basics/ripple_Version.h" // VFALCO TODO Should this be private?
#include "basics/ripple_BuildVersion.h" // private
#include "basics/ripple_RPCServer.h"
#include "basics/ripple_RPCServerHandler.h"
#include "src/cpp/ripple/RPCDoor.h" // needs RPCServer
@@ -229,7 +229,7 @@ static const uint64 tenTo17m1 = tenTo17 - 1;
#if ! defined (RIPPLE_MAIN_PART) || RIPPLE_MAIN_PART == 1
#include "basics/ripple_RPCServer.cpp"
#include "basics/ripple_RPCServerHandler.cpp"
#include "src/cpp/ripple/Ledger.cpp"
#include "src/cpp/ripple/ripple_SHAMapDelta.cpp"

View File

@@ -6,35 +6,42 @@
SETUP_LOG (RPCServer)
// VFALCO TODO Make this a language constant
#ifndef RPC_MAXIMUM_QUERY
#define RPC_MAXIMUM_QUERY (1024*1024)
#endif
class RPCServerImp
: public RPCServer
class RPCServerImp : public RPCServer, LeakChecked <RPCServerImp>
{
public:
typedef boost::shared_ptr<RPCServer> pointer;
RPCServerImp (
boost::asio::io_service& io_service,
boost::asio::ssl::context& context,
NetworkOPs* nopNetwork)
: mNetOps (nopNetwork)
Handler& handler)
: m_handler (handler)
, mSocket (io_service, context)
, mStrand (io_service)
{
mRole = RPCHandler::GUEST;
}
//--------------------------------------------------------------------------
private:
enum
{
maxQueryBytes = 1024 * 1024
};
void connected ()
{
boost::asio::async_read_until (
mSocket,
mLineBuffer,
"\r\n",
mStrand.wrap (boost::bind (
&RPCServerImp::handle_read_line,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
//--------------------------------------------------------------------------
private:
void handle_write (const boost::system::error_code& e)
{
//Log::out() << "async_write complete " << e;
if (!e)
{
HTTPRequest::Action action = mHTTPRequest.requestDone (false);
@@ -61,7 +68,9 @@ private:
if (e != boost::asio::error::operation_aborted)
{
//connection_manager_.stop(shared_from_this());
// VFALCO TODO What is this for? It was commented out.
//
//connection_manager_.stop (shared_from_this ());
}
}
@@ -69,80 +78,79 @@ private:
void handle_read_line (const boost::system::error_code& e)
{
if (e)
return;
HTTPRequest::Action action = mHTTPRequest.consume (mLineBuffer);
if (action == HTTPRequest::haDO_REQUEST)
if (! e)
{
// request with no body
WriteLog (lsWARNING, RPCServer) << "RPC HTTP request with no body";
HTTPRequest::Action action = mHTTPRequest.consume (mLineBuffer);
mSocket.async_shutdown (mStrand.wrap (boost::bind (
&RPCServerImp::handle_shutdown,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
return;
}
else if (action == HTTPRequest::haREAD_LINE)
{
boost::asio::async_read_until (
mSocket,
mLineBuffer,
"\r\n",
mStrand.wrap (boost::bind (
&RPCServerImp::handle_read_line,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
else if (action == HTTPRequest::haREAD_RAW)
{
int rLen = mHTTPRequest.getDataSize ();
if ((rLen < 0) || (rLen > RPC_MAXIMUM_QUERY))
if (action == HTTPRequest::haDO_REQUEST)
{
WriteLog (lsWARNING, RPCServer) << "Illegal RPC request length " << rLen;
// request with no body
WriteLog (lsWARNING, RPCServer) << "RPC HTTP request with no body";
mSocket.async_shutdown (mStrand.wrap (boost::bind (
&RPCServerImp::handle_shutdown,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
return;
}
int alreadyHave = mLineBuffer.size ();
if (alreadyHave < rLen)
else if (action == HTTPRequest::haREAD_LINE)
{
mQueryVec.resize (rLen - alreadyHave);
boost::asio::async_read (
boost::asio::async_read_until (
mSocket,
boost::asio::buffer (mQueryVec),
mLineBuffer,
"\r\n",
mStrand.wrap (boost::bind (
&RPCServerImp::handle_read_req,
&RPCServerImp::handle_read_line,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
else if (action == HTTPRequest::haREAD_RAW)
{
int rLen = mHTTPRequest.getDataSize ();
WriteLog (lsTRACE, RPCServer) << "Waiting for completed request: " << rLen;
if ((rLen < 0) || (rLen > maxQueryBytes))
{
WriteLog (lsWARNING, RPCServer) << "Illegal RPC request length " << rLen;
mSocket.async_shutdown (mStrand.wrap (boost::bind (
&RPCServerImp::handle_shutdown,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
else
{
int alreadyHave = mLineBuffer.size ();
if (alreadyHave < rLen)
{
mQueryVec.resize (rLen - alreadyHave);
boost::asio::async_read (
mSocket,
boost::asio::buffer (mQueryVec),
mStrand.wrap (boost::bind (
&RPCServerImp::handle_read_req,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
WriteLog (lsTRACE, RPCServer) << "Waiting for completed request: " << rLen;
}
else
{
// we have the whole thing
mQueryVec.resize (0);
handle_read_req (e);
}
}
}
else
{
// we have the whole thing
mQueryVec.resize (0);
handle_read_req (e);
mSocket.async_shutdown (mStrand.wrap (boost::bind (
&RPCServerImp::handle_shutdown,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
}
else
{
mSocket.async_shutdown (mStrand.wrap (boost::bind (
&RPCServerImp::handle_shutdown,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
}
//--------------------------------------------------------------------------
@@ -153,16 +161,21 @@ private:
if (mLineBuffer.size ())
{
req.assign (boost::asio::buffer_cast<const char*> (mLineBuffer.data ()), mLineBuffer.size ());
req.assign (boost::asio::buffer_cast <const char*> (mLineBuffer.data ()), mLineBuffer.size ());
mLineBuffer.consume (mLineBuffer.size ());
}
req += strCopy (mQueryVec);
if (!HTTPAuthorized (mHTTPRequest.peekHeaders ()))
mReplyStr = HTTPReply (403, "Forbidden");
if (! m_handler.isAuthorized (mHTTPRequest.peekHeaders ()))
{
mReplyStr = m_handler.createResponse (403, "Forbidden");
}
else
{
mReplyStr = handleRequest (req);
}
boost::asio::async_write (
mSocket,
@@ -182,48 +195,20 @@ private:
//--------------------------------------------------------------------------
std::string handleRequest (const std::string& requestStr)
// JSON-RPC request must contain "method", "params", and "id" fields.
//
std::string handleRequest (const std::string& request)
{
WriteLog (lsTRACE, RPCServer) << "handleRequest " << requestStr;
WriteLog (lsTRACE, RPCServer) << "handleRequest " << request;
Json::Value id;
// Parse request
Json::Value jvRequest;
Json::Reader reader;
if (!reader.parse (requestStr, jvRequest) || jvRequest.isNull () || !jvRequest.isObject ())
return (HTTPReply (400, "unable to parse request"));
// Parse id now so errors from here on will have the id
id = jvRequest["id"];
// Parse method
Json::Value valMethod = jvRequest["method"];
if (valMethod.isNull ())
return (HTTPReply (400, "null method"));
if (!valMethod.isString ())
return (HTTPReply (400, "method is not string"));
std::string strMethod = valMethod.asString ();
// Parse params
Json::Value valParams = jvRequest["params"];
if (valParams.isNull ())
{
valParams = Json::Value (Json::arrayValue);
}
else if (!valParams.isArray ())
{
return HTTPReply (400, "params unparseable");
}
// Figure out the remote address.
// VFALCO TODO Clean up this try/catch nonsense.
//
std::string remoteAddress;
try
{
mRole = iAdminGet (jvRequest, mSocket.PlainSocket ().remote_endpoint ().address ().to_string ());
remoteAddress = mSocket.PlainSocket ().remote_endpoint ().address ().to_string ();
}
catch (...)
{
@@ -231,25 +216,7 @@ private:
return "";
}
if (RPCHandler::FORBID == mRole)
{
// XXX This needs rate limiting to prevent brute forcing password.
return HTTPReply (403, "Forbidden");
}
RPCHandler mRPCHandler (mNetOps);
WriteLog (lsINFO, RPCServer) << valParams;
LoadType loadType = LT_RPCReference;
Json::Value result = mRPCHandler.doRpcCommand (strMethod, valParams, mRole, &loadType);
// VFALCO NOTE We discard loadType since there is no endpoint to punish
WriteLog (lsINFO, RPCServer) << result;
std::string strReply = JSONRPCReply (result, Json::Value (), id);
return HTTPReply (200, strReply);
return m_handler.processRequest (request, remoteAddress);
}
//--------------------------------------------------------------------------
@@ -268,21 +235,6 @@ private:
//--------------------------------------------------------------------------
void connected ()
{
//Log::out() << "RPC request";
boost::asio::async_read_until (
mSocket,
mLineBuffer,
"\r\n",
mStrand.wrap (boost::bind (
&RPCServerImp::handle_read_line,
boost::static_pointer_cast <RPCServerImp> (shared_from_this ()),
boost::asio::placeholders::error)));
}
//--------------------------------------------------------------------------
std::string getRemoteAddressText ()
{
std::string address;
@@ -293,7 +245,7 @@ private:
}
private:
NetworkOPs* const mNetOps;
Handler& m_handler;
AutoSocket mSocket;
boost::asio::io_service::strand mStrand;
@@ -303,8 +255,6 @@ private:
std::string mReplyStr;
HTTPRequest mHTTPRequest;
int mRole;
};
//------------------------------------------------------------------------------
@@ -312,7 +262,7 @@ private:
RPCServer::pointer RPCServer::New (
boost::asio::io_service& io_service,
boost::asio::ssl::context& context,
NetworkOPs* mNetOps)
Handler& handler)
{
return pointer (new RPCServerImp (io_service, context, mNetOps));
return pointer (new RPCServerImp (io_service, context, handler));
}

View File

@@ -0,0 +1,68 @@
//------------------------------------------------------------------------------
/*
Copyright (c) 2011-2013, OpenCoin, Inc.
*/
//==============================================================================
#ifndef RIPPLE_RPCSERVER_H_INCLUDED
#define RIPPLE_RPCSERVER_H_INCLUDED
/** Provides RPC services to a client.
Each client has a separate instance of this object.
*/
// VFALCO NOTE This looks like intrusve shared object?
//
class RPCServer : public boost::enable_shared_from_this <RPCServer>
{
public:
typedef boost::shared_ptr <RPCServer> pointer;
public:
/** Handles a RPC client request.
*/
class Handler
{
public:
virtual ~Handler () { }
/** Construct a HTTP response string.
*/
virtual std::string createResponse (int statusCode, std::string const& description) = 0;
/** Determine if the connection is authorized.
*/
virtual bool isAuthorized (std::map <std::string, std::string> const& headers) = 0;
/** Produce a response for a given request.
@param request The RPC request string.
@return The server's response.
*/
virtual std::string processRequest (std::string const& request, std::string const& remoteAddress) = 0;
};
static pointer New (
boost::asio::io_service& io_service,
boost::asio::ssl::context& context,
Handler& handler);
/** Called when the connection is established.
*/
virtual void connected () = 0;
// VFALCO TODO AutoSocket exposes all sorts of boost::asio interface
virtual AutoSocket& getSocket () = 0;
// VFALCO TODO Remove this since it exposes boost
virtual boost::asio::ip::tcp::socket& getRawSocket () = 0;
/** Retrieve the remote address as a string.
@return A std::string representing the remote address.
*/
// VFALCO TODO Replace the return type with a dedicated class.
virtual std::string getRemoteAddressText () = 0;
};
#endif

View File

@@ -22,5 +22,6 @@ namespace ripple
#include "basics/ripple_HTTPRequest.cpp"
#include "basics/ripple_HttpsClient.cpp"
#include "basics/ripple_RPCServer.cpp"
}

View File

@@ -29,6 +29,7 @@ namespace ripple
#include "basics/ripple_HTTPRequest.h"
#include "basics/ripple_HttpsClient.h"
#include "basics/ripple_RPCServer.h"
}