23 #include <boost/algorithm/string.hpp> 26 static const char* WWW_AUTH_HEADER_DATA =
"Basic realm=\"jsonrpc\"";
34 HTTPRPCTimer(
struct event_base* eventBase, std::function<
void()>& func, int64_t millis) :
35 ev(eventBase, false, func)
38 tv.tv_sec = millis/1000;
39 tv.tv_usec = (millis%1000)*1000;
52 const char*
Name()
override 66 static std::string strRPCUserColonPass;
68 static std::unique_ptr<HTTPRPCTimerInterface> httpRPCTimerInterface;
83 req->
WriteHeader(
"Content-Type",
"application/json");
89 static bool multiUserAuthorized(std::string strUserPass)
91 if (strUserPass.find(
':') == std::string::npos) {
94 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
95 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
97 for (
const std::string& strRPCAuth :
gArgs.
GetArgs(
"-rpcauth")) {
99 std::vector<std::string> vFields;
100 boost::split(vFields, strRPCAuth, boost::is_any_of(
":$"));
101 if (vFields.size() != 3) {
106 std::string strName = vFields[0];
111 std::string strSalt = vFields[1];
112 std::string strHash = vFields[2];
114 static const unsigned int KEY_SIZE = 32;
115 unsigned char out[KEY_SIZE];
117 CHMAC_SHA256(reinterpret_cast<const unsigned char*>(strSalt.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);
118 std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
119 std::string strHashFromPass =
HexStr(hexvec);
128 static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
130 if (strRPCUserColonPass.empty())
132 if (strAuth.substr(0, 6) !=
"Basic ")
134 std::string strUserPass64 = strAuth.substr(6);
135 boost::trim(strUserPass64);
138 if (strUserPass.find(
':') != std::string::npos)
139 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
145 return multiUserAuthorized(strUserPass);
148 static bool HTTPReq_JSONRPC(
HTTPRequest* req,
const std::string &)
156 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
157 if (!authHeader.first) {
158 req->
WriteHeader(
"WWW-Authenticate", WWW_AUTH_HEADER_DATA);
165 if (!RPCAuthorized(authHeader.second, jreq.
authUser)) {
166 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n", jreq.
peerAddr);
173 req->
WriteHeader(
"WWW-Authenticate", WWW_AUTH_HEADER_DATA);
187 std::string strReply;
190 jreq.
parse(valRequest);
198 }
else if (valRequest.
isArray())
203 req->
WriteHeader(
"Content-Type",
"application/json");
205 }
catch (
const UniValue& objError) {
206 JSONErrorReply(req, objError, jreq.
id);
208 }
catch (
const std::exception& e) {
215 static bool InitRPCAuthentication()
219 LogPrintf(
"No rpcpassword set - using random cookie authentication.\n");
222 _(
"Error: A fatal internal error occurred, see debug.log for details"),
227 LogPrintf(
"Config options rpcuser and rpcpassword will soon be deprecated. Locally-run instances may remove rpcuser to use cookie-based auth, or may be replaced with rpcauth. Please see share/rpcauth for rpcauth auth generation.\n");
232 LogPrintf(
"Using rpcauth authentication.\n");
239 LogPrint(
BCLog::RPC,
"Starting HTTP RPC server\n");
240 if (!InitRPCAuthentication())
247 struct event_base* eventBase =
EventBase();
249 httpRPCTimerInterface = MakeUnique<HTTPRPCTimerInterface>(eventBase);
256 LogPrint(
BCLog::RPC,
"Interrupting HTTP RPC server\n");
261 LogPrint(
BCLog::RPC,
"Stopping HTTP RPC server\n");
266 if (httpRPCTimerInterface) {
268 httpRPCTimerInterface.reset();
std::vector< unsigned char > DecodeBase64(const char *p, bool *pfInvalid)
HTTPRPCTimerInterface(struct event_base *_base)
void MilliSleep(int64_t n)
const char * Name() override
Implementation name.
bool read(const char *raw, size_t len)
bool StartHTTPRPC()
Start HTTP RPC subsystem.
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
A hasher class for HMAC-SHA-256.
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
const UniValue & get_array() const
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
const UniValue & find_value(const UniValue &obj, const std::string &name)
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
RequestMethod GetRequestMethod() const
Get request method.
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
struct event_base * EventBase()
Return evhttp event base.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
const WalletInitInterface & g_wallet_init_interface
void parse(const UniValue &valRequest)
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
void trigger(struct timeval *tv)
Trigger the event.
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
Opaque base class for timers returned by NewTimerFunc.
const UniValue NullUniValue
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
std::string ReadBody()
Read request body.
Standard JSON-RPC 2.0 errors.
std::string ToString() const
UniValue JSONRPCError(int code, const std::string &message)
CClientUIInterface uiInterface
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
std::string GetURI() const
Get requested URI.
std::string _(const char *psz)
Translation function.