37 tv.tv_sec = millis/1000;
38 tv.tv_usec = (millis%1000)*1000;
51 const char*
Name()
override
69 static std::vector<std::vector<std::string>>
g_rpcauth;
87 req->
WriteHeader(
"Content-Type",
"application/json");
95 if (strUserPass.find(
':') == std::string::npos) {
98 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
99 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
102 std::string strName = vFields[0];
107 std::string strSalt = vFields[1];
108 std::string strHash = vFields[2];
110 static const unsigned int KEY_SIZE = 32;
111 unsigned char out[KEY_SIZE];
113 CHMAC_SHA256(
reinterpret_cast<const unsigned char*
>(strSalt.data()), strSalt.size()).
Write(
reinterpret_cast<const unsigned char*
>(strPass.data()), strPass.size()).
Finalize(out);
114 std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
115 std::string strHashFromPass =
HexStr(hexvec);
124 static bool RPCAuthorized(
const std::string& strAuth, std::string& strAuthUsernameOut)
128 if (strAuth.substr(0, 6) !=
"Basic ")
130 std::string_view strUserPass64 =
TrimStringView(std::string_view{strAuth}.substr(6));
132 std::string strUserPass;
133 if (!userpass_data)
return false;
134 strUserPass.assign(userpass_data->begin(), userpass_data->end());
136 if (strUserPass.find(
':') != std::string::npos)
137 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
154 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
155 if (!authHeader.first) {
165 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n", jreq.
peerAddr);
186 std::string strReply;
195 jreq.
parse(valRequest);
207 }
else if (valRequest.
isArray()) {
208 if (user_has_whitelist) {
209 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size(); reqIdx++) {
210 if (!valRequest[reqIdx].isObject()) {
217 LogPrintf(
"RPC User %s not allowed to call method %s\n", jreq.
authUser, strMethod);
229 req->
WriteHeader(
"Content-Type",
"application/json");
231 }
catch (
const UniValue& objError) {
234 }
catch (
const std::exception& e) {
245 LogPrintf(
"Using random cookie authentication.\n");
250 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");
254 LogPrintf(
"Using rpcauth authentication.\n");
255 for (
const std::string& rpcauth :
gArgs.
GetArgs(
"-rpcauth")) {
256 std::vector<std::string> fields{
SplitString(rpcauth,
':')};
257 const std::vector<std::string> salt_hmac{
SplitString(fields.back(),
'$')};
258 if (fields.size() == 2 && salt_hmac.size() == 2) {
260 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
263 LogPrintf(
"Invalid -rpcauth argument.\n");
270 for (
const std::string& strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
271 auto pos = strRPCWhitelist.find(
':');
272 std::string strUser = strRPCWhitelist.substr(0, pos);
275 if (pos != std::string::npos) {
276 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
277 std::vector<std::string> whitelist_split =
SplitString(strWhitelist,
", ");
278 std::set<std::string> new_whitelist{
279 std::make_move_iterator(whitelist_split.begin()),
280 std::make_move_iterator(whitelist_split.end())};
282 std::set<std::string> tmp_whitelist;
283 std::set_intersection(new_whitelist.begin(), new_whitelist.end(),
284 whitelist.begin(), whitelist.end(), std::inserter(tmp_whitelist, tmp_whitelist.end()));
285 new_whitelist = std::move(tmp_whitelist);
287 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 ToString() 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 & get_obj() const
const UniValue & get_array() const
bool read(const char *raw, size_t len)
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 & find_value(const UniValue &obj, const std::string &name)
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)