18#include <boost/algorithm/string.hpp>
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 {
93 req->
WriteHeader(
"Content-Type",
"application/json");
102 if (strUserPass.find(
':') == std::string::npos) {
105 std::string strUser = strUserPass.substr(0, strUserPass.find(
':'));
106 std::string strPass = strUserPass.substr(strUserPass.find(
':') + 1);
108 for (
const std::string &strRPCAuth :
gArgs.
GetArgs(
"-rpcauth")) {
110 std::vector<std::string> vFields;
111 boost::split(vFields, strRPCAuth, boost::is_any_of(
":$"));
112 if (vFields.size() != 3) {
117 std::string strName = vFields[0];
122 std::string strSalt = vFields[1];
123 std::string strHash = vFields[2];
125 static const unsigned int KEY_SIZE = 32;
126 uint8_t out[KEY_SIZE];
128 CHMAC_SHA256(
reinterpret_cast<const uint8_t *
>(strSalt.data()),
130 .
Write(
reinterpret_cast<const uint8_t *
>(strPass.data()),
133 std::vector<uint8_t> hexvec(out, out + KEY_SIZE);
134 std::string strHashFromPass =
HexStr(hexvec);
144 std::string &strAuthUsernameOut) {
150 if (strAuth.substr(0, 6) !=
"Basic ") {
154 std::string_view strUserPass64 =
157 std::string strUserPass;
158 if (!userpass_data) {
161 strUserPass.assign(userpass_data->begin(), userpass_data->end());
163 if (strUserPass.find(
':') != std::string::npos) {
164 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(
':'));
179 std::pair<bool, std::string> origin = req->
GetHeader(
"origin");
207 std::pair<bool, std::string> method =
208 req->
GetHeader(
"access-control-request-method");
220 std::pair<bool, std::string> header_field_names =
221 req->
GetHeader(
"access-control-request-headers");
228 if (method.second !=
"POST") {
237 const std::string &list_of_headers =
"authorization,content-type";
244 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
245 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
259 req->
WriteHeader(
"Access-Control-Allow-Methods", method.second);
266 header_field_names.first ? header_field_names.second
284 req->
WriteHeader(
"Access-Control-Allow-Origin", origin.second);
285 req->
WriteHeader(
"Access-Control-Allow-Credentials",
"true");
290 req->
WriteHeader(
"Access-Control-Expose-Headers",
"WWW-Authenticate");
304 "JSONRPC server handles only POST requests");
308 std::pair<bool, std::string> authHeader = req->
GetHeader(
"authorization");
309 if (!authHeader.first) {
319 LogPrintf(
"ThreadRPCServer incorrect password attempt from %s\n",
345 std::string strReply;
348 LogPrintf(
"RPC User %s not allowed to call any methods\n",
355 jreq.
parse(valRequest);
356 if (user_has_whitelist &&
358 LogPrintf(
"RPC User %s not allowed to call method %s\n",
369 }
else if (valRequest.
isArray()) {
370 if (user_has_whitelist) {
371 for (
unsigned int reqIdx = 0; reqIdx < valRequest.
size();
373 if (!valRequest[reqIdx].isObject()) {
375 "Invalid Request object");
379 std::string strMethod =
383 "RPC User %s not allowed to call method %s\n",
397 req->
WriteHeader(
"Content-Type",
"application/json");
399 }
catch (
const UniValue &objError) {
402 }
catch (
const std::exception &e) {
411 LogPrintf(
"Using random cookie authentication.\n");
416 LogPrintf(
"Config options rpcuser and rpcpassword will soon be "
417 "deprecated. Locally-run instances may remove rpcuser to use "
418 "cookie-based auth, or may be replaced with rpcauth. Please "
419 "see share/rpcauth for rpcauth auth generation.\n");
427 LogPrintf(
"Using rpcauth authentication.\n");
432 for (
const std::string &strRPCWhitelist :
gArgs.
GetArgs(
"-rpcwhitelist")) {
433 auto pos = strRPCWhitelist.find(
':');
434 std::string strUser = strRPCWhitelist.substr(0, pos);
437 if (pos != std::string::npos) {
438 std::string strWhitelist = strRPCWhitelist.substr(pos + 1);
439 std::set<std::string> new_whitelist;
440 boost::split(new_whitelist, strWhitelist, boost::is_any_of(
", "));
442 std::set<std::string> tmp_whitelist;
443 std::set_intersection(
444 new_whitelist.begin(), new_whitelist.end(),
445 whitelist.begin(), whitelist.end(),
446 std::inserter(tmp_whitelist, tmp_whitelist.end()));
447 new_whitelist = std::move(tmp_whitelist);
449 whitelist = std::move(new_whitelist);
465 &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 ToString() 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
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::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::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.
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< uint8_t > > DecodeBase64(std::string_view str)