39 tv.tv_sec = millis/1000;
40 tv.tv_usec = (millis%1000)*1000;
53 const char*
Name()
override
71 static std::vector<std::vector<std::string>>
g_rpcauth;
89 req->
WriteHeader(
"Content-Type",
"application/json");
97 if (strUserPass.find(
':') == std::string::npos) {
100 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
101 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
104 std::string strName = vFields[0];
109 std::string strSalt = vFields[1];
110 std::string strHash = vFields[2];
112 static const unsigned int KEY_SIZE = 32;
113 unsigned char out[KEY_SIZE];
115 CHMAC_SHA256(
reinterpret_cast<const unsigned char*
>(strSalt.data()), strSalt.size()).
Write(
reinterpret_cast<const unsigned char*
>(strPass.data()), strPass.size()).
Finalize(
out);
116 std::vector<unsigned char> hexvec(
out,
out+KEY_SIZE);
117 std::string strHashFromPass =
HexStr(hexvec);
126 static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
130 if (strAuth.substr(0, 6) !=
"Basic ")
132 std::string_view strUserPass64 =
TrimStringView(std::string_view{strAuth}.substr(6));
134 std::string strUserPass;
135 if (!userpass_data)
return false;
136 strUserPass.assign(userpass_data->begin(), userpass_data->end());
138 if (strUserPass.find(
':') != std::string::npos)
139 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
156 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
157 if (!authHeader.first) {
167 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n", jreq.
peerAddr);
188 std::string strReply;
197 jreq.
parse(valRequest);
209 }
else if (valRequest.
isArray()) {
210 if (user_has_whitelist) {
211 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size(); reqIdx++) {
212 if (!valRequest[reqIdx].isObject()) {
219 LogPrintf(
"RPC User %s not allowed to call method %s\n", jreq.
authUser, strMethod);
231 req->
WriteHeader(
"Content-Type",
"application/json");
233 }
catch (
const UniValue& objError) {
236 }
catch (
const std::exception& e) {
247 LogPrintf(
"Using random cookie authentication.\n");
252 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");
256 LogPrintf(
"Using rpcauth authentication.\n");
257 for (
const std::string& rpcauth :
gArgs.
GetArgs(
"-rpcauth")) {
258 std::vector<std::string> fields{
SplitString(rpcauth,
':')};
259 const std::vector<std::string> salt_hmac{
SplitString(fields.back(),
'$')};
260 if (fields.size() == 2 && salt_hmac.size() == 2) {
262 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
265 LogPrintf(
"Invalid -rpcauth argument.\n");
272 for (
const std::string& strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
273 auto pos = strRPCWhitelist.find(
':');
274 std::string strUser = strRPCWhitelist.substr(0, pos);
277 if (pos != std::string::npos) {
278 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
279 std::vector<std::string> whitelist_split =
SplitString(strWhitelist,
", ");
280 std::set<std::string> new_whitelist{
281 std::make_move_iterator(whitelist_split.begin()),
282 std::make_move_iterator(whitelist_split.end())};
284 std::set<std::string> tmp_whitelist;
285 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
286 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
287 new_whitelist = std::move(tmp_whitelist);
289 whitelist = std::move(new_whitelist);
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
A hasher class for HMAC-SHA-256.
void Finalize(unsigned char hash[OUTPUT_SIZE])
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
std::string ToStringAddrPort() const
void trigger(struct timeval *tv)
Trigger the event.
Simple one-shot callback timer to be used by the RPC mechanism to e.g.
HTTPRPCTimer(struct event_base *eventBase, std::function< void()> &func, int64_t millis)
const char * Name() override
Implementation name.
RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis) override
Factory function for timers.
HTTPRPCTimerInterface(struct event_base *_base)
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
std::string GetURI() const
Get requested URI.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
RequestMethod GetRequestMethod() const
Get request method.
std::string ReadBody()
Read request body.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
void parse(const UniValue &valRequest)
Opaque base class for timers returned by NewTimerFunc.
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
const UniValue & get_obj() const
bool read(std::string_view raw)
const UniValue & get_array() const
virtual bool HasWalletSupport() const =0
Is the wallet component enabled.
const WalletInitInterface & g_wallet_init_interface
static const char * WWW_AUTH_HEADER_DATA
WWW-Authenticate to present with 401 Unauthorized response.
void InterruptHTTPRPC()
Interrupt HTTP RPC subsystem.
void StopHTTPRPC()
Stop HTTP RPC subsystem.
static std::unique_ptr< HTTPRPCTimerInterface > httpRPCTimerInterface
static bool multiUserAuthorized(std::string strUserPass)
bool StartHTTPRPC(const std::any &context)
Start HTTP RPC subsystem.
static bool g_rpc_whitelist_default
static bool RPCAuthorized(const std::string &strAuth, std::string &strAuthUsernameOut)
static std::vector< std::vector< std::string > > g_rpcauth
static bool HTTPReq_JSONRPC(const std::any &context, HTTPRequest *req)
static std::string strRPCUserColonPass
static bool InitRPCAuthentication()
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
static void JSONErrorReply(HTTPRequest *req, const UniValue &objError, const UniValue &id)
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
struct event_base * EventBase()
Return evhttp event base.
static struct event_base * eventBase
HTTP module state.
#define LogPrint(category,...)
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
UniValue JSONRPCError(int code, const std::string &message)
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
@ HTTP_INTERNAL_SERVER_ERROR
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
bool TimingResistantEqual(const T &a, const T &b)
Timing-attack-resistant comparison.
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)