4 #include "chainparams.h"
5 #include "httpserver.h"
6 #include "rpcprotocol.h"
11 #include "utilstrencodings.h"
12 #include "ui_interface.h"
14 #include <boost/algorithm/string.hpp> // boost::trim
16 /** WWW-Authenticate to present with 401 Unauthorized response */
17 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
19 /** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
22 class HTTPRPCTimer : public RPCTimerBase
25 HTTPRPCTimer(struct event_base* eventBase, boost::function<void(void)>& func, int64_t millis) :
26 ev(eventBase, false, func)
29 tv.tv_sec = millis/1000;
30 tv.tv_usec = (millis%1000)*1000;
37 class HTTPRPCTimerInterface : public RPCTimerInterface
40 HTTPRPCTimerInterface(struct event_base* base) : base(base)
47 RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis)
49 return new HTTPRPCTimer(base, func, millis);
52 struct event_base* base;
56 /* Pre-base64-encoded authentication token */
57 static std::string strRPCUserColonPass;
58 /* Stored RPC timer interface (for unregistration) */
59 static HTTPRPCTimerInterface* httpRPCTimerInterface = 0;
61 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
63 // Send error reply from json-rpc error object
64 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
65 int code = find_value(objError, "code").get_int();
67 if (code == RPC_INVALID_REQUEST)
68 nStatus = HTTP_BAD_REQUEST;
69 else if (code == RPC_METHOD_NOT_FOUND)
70 nStatus = HTTP_NOT_FOUND;
72 std::string strReply = JSONRPCReply(NullUniValue, objError, id);
74 req->WriteHeader("Content-Type", "application/json");
75 req->WriteReply(nStatus, strReply);
78 static bool RPCAuthorized(const std::string& strAuth)
80 if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
82 if (strAuth.substr(0, 6) != "Basic ")
84 std::string strUserPass64 = strAuth.substr(6);
85 boost::trim(strUserPass64);
86 std::string strUserPass = DecodeBase64(strUserPass64);
87 return TimingResistantEqual(strUserPass, strRPCUserColonPass);
90 static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
92 // JSONRPC handles only POST
93 if (req->GetRequestMethod() != HTTPRequest::POST) {
94 req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
97 // Check authorization
98 std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
99 if (!authHeader.first) {
100 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
101 req->WriteReply(HTTP_UNAUTHORIZED);
105 if (!RPCAuthorized(authHeader.second)) {
106 LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
108 /* Deter brute-forcing
109 If this results in a DoS the user really
110 shouldn't have their RPC port exposed. */
113 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
114 req->WriteReply(HTTP_UNAUTHORIZED);
122 if (!valRequest.read(req->ReadBody()))
123 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
125 std::string strReply;
127 if (valRequest.isObject()) {
128 jreq.parse(valRequest);
130 UniValue result = tableRPC.execute(jreq.strMethod, jreq.params);
133 strReply = JSONRPCReply(result, NullUniValue, jreq.id);
136 } else if (valRequest.isArray())
137 strReply = JSONRPCExecBatch(valRequest.get_array());
139 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
141 req->WriteHeader("Content-Type", "application/json");
142 req->WriteReply(HTTP_OK, strReply);
143 } catch (const UniValue& objError) {
144 JSONErrorReply(req, objError, jreq.id);
146 } catch (const std::exception& e) {
147 JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
153 static bool InitRPCAuthentication()
155 if (mapArgs["-rpcpassword"] == "")
157 LogPrintf("No rpcpassword set - using random cookie authentication\n");
158 if (!GenerateAuthCookie(&strRPCUserColonPass)) {
159 uiInterface.ThreadSafeMessageBox(
160 _("Error: A fatal internal error occurred, see debug.log for details"), // Same message as AbortNode
161 "", CClientUIInterface::MSG_ERROR);
165 strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
172 LogPrint("rpc", "Starting HTTP RPC server\n");
173 if (!InitRPCAuthentication())
176 RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
179 httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
180 RPCRegisterTimerInterface(httpRPCTimerInterface);
184 void InterruptHTTPRPC()
186 LogPrint("rpc", "Interrupting HTTP RPC server\n");
191 LogPrint("rpc", "Stopping HTTP RPC server\n");
192 UnregisterHTTPHandler("/", true);
193 if (httpRPCTimerInterface) {
194 RPCUnregisterTimerInterface(httpRPCTimerInterface);
195 delete httpRPCTimerInterface;
196 httpRPCTimerInterface = 0;