45 tv.tv_sec = millis / 1000;
46 tv.tv_usec = (millis % 1000) * 1000;
58 const char *
Name()
override {
return "HTTP"; }
61 int64_t millis)
override {
76static std::vector<std::vector<std::string>>
g_rpcauth;
95 req->
WriteHeader(
"Content-Type",
"application/json");
104 if (strUserPass.find(
':') == std::string::npos) {
107 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
108 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
111 std::string strName = vFields[0];
116 std::string strSalt = vFields[1];
117 std::string strHash = vFields[2];
119 static const unsigned int KEY_SIZE = 32;
120 uint8_t
out[KEY_SIZE];
122 CHMAC_SHA256(
reinterpret_cast<const uint8_t *
>(strSalt.data()),
124 .
Write(
reinterpret_cast<const uint8_t *
>(strPass.data()),
127 std::vector<uint8_t> hexvec(
out,
out + KEY_SIZE);
128 std::string strHashFromPass =
HexStr(hexvec);
138 std::string &strAuthUsernameOut) {
144 if (strAuth.substr(0, 6) !=
"Basic ") {
148 std::string_view strUserPass64 =
151 std::string strUserPass;
152 if (!userpass_data) {
155 strUserPass.assign(userpass_data->begin(), userpass_data->end());
157 if (strUserPass.find(
':') != std::string::npos) {
158 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
173 std::pair<bool, std::string> origin = req->
GetHeader(
"origin");
201 std::pair<bool, std::string> method =
202 req->
GetHeader(
"access-control-request-method");
214 std::pair<bool, std::string> header_field_names =
215 req->
GetHeader(
"access-control-request-headers");
222 if (method.second !=
"POST") {
231 const std::string &list_of_headers =
"authorization,content-type";
238 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
239 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
253 req->
WriteHeader(
"Access-Control-Allow-Methods", method.second);
260 header_field_names.first ? header_field_names.second
278 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
279 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
284 req->
WriteHeader(
"Access-Control-Expose-Headers",
"WWW-Authenticate");
298 "JSONRPC server handles only POST requests");
302 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
303 if (!authHeader.first) {
313 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n",
339 std::string strReply;
342 LogPrintf(
"RPC User %s not allowed to call any methods\n",
349 jreq.
parse(valRequest);
350 if (user_has_whitelist &&
352 LogPrintf(
"RPC User %s not allowed to call method %s\n",
363 }
else if (valRequest.
isArray()) {
364 if (user_has_whitelist) {
365 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size();
367 if (!valRequest[reqIdx].isObject()) {
369 "Invalid Request object");
373 std::string strMethod =
377 "RPC User %s not allowed to call method %s\n",
391 req->
WriteHeader(
"Content-Type",
"application/json");
393 }
catch (
const UniValue &objError) {
396 }
catch (
const std::exception &e) {
405 LogPrintf(
"Using random cookie authentication.\n");
410 LogPrintf(
"Config options rpcuser and rpcpassword will soon be "
411 "deprecated. Locally-run instances may remove rpcuser to use "
412 "cookie-based auth, or may be replaced with rpcauth. Please "
413 "see share/rpcauth for rpcauth auth generation.\n");
421 LogPrintf(
"Using rpcauth authentication.\n");
422 for (
const std::string &rpcauth :
gArgs.
GetArgs(
"-rpcauth")) {
423 std::vector<std::string> fields{
SplitString(rpcauth,
':')};
424 const std::vector<std::string> salt_hmac{
426 if (fields.size() == 2 && salt_hmac.size() == 2) {
428 fields.insert(fields.end(), salt_hmac.begin(), salt_hmac.end());
431 LogPrintf(
"Invalid -rpcauth argument.\n");
439 for (
const std::string &strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
440 auto pos = strRPCWhitelist.find(
':');
441 std::string strUser = strRPCWhitelist.substr(0, pos);
444 if (pos != std::string::npos) {
445 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
446 std::vector<std::string> whitelist_split =
448 std::set<std::string> new_whitelist{
449 std::make_move_iterator(whitelist_split.begin()),
450 std::make_move_iterator(whitelist_split.end())};
452 std::set<std::string> tmp_whitelist;
453 std::set_intersection(
454 new_whitelist.begin(), new_whitelist.end(),
455 whitelist.begin(), whitelist.end(),
456 std::inserter(tmp_whitelist, tmp_whitelist.end()));
457 new_whitelist = std::move(tmp_whitelist);
459 whitelist = std::move(new_whitelist);
475 &httpRPCRequestProcessor, std::placeholders::_2);
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.
CHMAC_SHA256 & Write(const uint8_t *data, size_t len)
void Finalize(uint8_t hash[OUTPUT_SIZE])
std::string ToStringAddrPort() const
void trigger(struct timeval *tv)
Trigger the event.
bool ProcessHTTPRequest(HTTPRequest *request)
static bool DelegateHTTPRequest(HTTPRPCRequestProcessor *requestProcessor, HTTPRequest *request)
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)
UniValue ExecuteCommand(const Config &config, const JSONRPCRequest &request) const
Attempts to execute an RPC command from the given request.
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
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static bool checkCORS(HTTPRequest *req)
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 std::string strRPCCORSDomain
static bool multiUserAuthorized(std::string strUserPass)
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 std::string strRPCUserColonPass
static bool InitRPCAuthentication()
static std::map< std::string, std::set< std::string > > g_rpc_whitelist
bool StartHTTPRPC(HTTPRPCRequestProcessor &httpRPCRequestProcessor)
Start HTTP RPC subsystem.
static const int64_t RPC_AUTH_BRUTE_FORCE_DELAY
RPC auth failure delay to make brute-forcing expensive.
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.
static struct event_base * eventBase
HTTP module state.
struct event_base * EventBase()
Return evhttp event base.
#define LogPrint(category,...)
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")
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 Config &config, RPCServer &rpcServer, 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.
void UninterruptibleSleep(const std::chrono::microseconds &n)
const UniValue NullUniValue
std::optional< std::vector< uint8_t > > DecodeBase64(std::string_view str)