Use the override specifier (C++11) where we expect to be overriding the virtual funct...
[bitcoinplatinum.git] / src / httprpc.cpp
blob8c2e0da32fd166f9af9a787e360d7697b81379f4
1 // Copyright (c) 2015-2016 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include "httprpc.h"
7 #include "base58.h"
8 #include "chainparams.h"
9 #include "httpserver.h"
10 #include "rpc/protocol.h"
11 #include "rpc/server.h"
12 #include "random.h"
13 #include "sync.h"
14 #include "util.h"
15 #include "utilstrencodings.h"
16 #include "ui_interface.h"
17 #include "crypto/hmac_sha256.h"
18 #include <stdio.h>
20 #include <boost/algorithm/string.hpp> // boost::trim
21 #include <boost/foreach.hpp>
23 /** WWW-Authenticate to present with 401 Unauthorized response */
24 static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";
26 /** Simple one-shot callback timer to be used by the RPC mechanism to e.g.
27 * re-lock the wallet.
29 class HTTPRPCTimer : public RPCTimerBase
31 public:
32 HTTPRPCTimer(struct event_base* eventBase, std::function<void(void)>& func, int64_t millis) :
33 ev(eventBase, false, func)
35 struct timeval tv;
36 tv.tv_sec = millis/1000;
37 tv.tv_usec = (millis%1000)*1000;
38 ev.trigger(&tv);
40 private:
41 HTTPEvent ev;
44 class HTTPRPCTimerInterface : public RPCTimerInterface
46 public:
47 HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
50 const char* Name() override
52 return "HTTP";
54 RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) override
56 return new HTTPRPCTimer(base, func, millis);
58 private:
59 struct event_base* base;
63 /* Pre-base64-encoded authentication token */
64 static std::string strRPCUserColonPass;
65 /* Stored RPC timer interface (for unregistration) */
66 static HTTPRPCTimerInterface* httpRPCTimerInterface = 0;
68 static void JSONErrorReply(HTTPRequest* req, const UniValue& objError, const UniValue& id)
70 // Send error reply from json-rpc error object
71 int nStatus = HTTP_INTERNAL_SERVER_ERROR;
72 int code = find_value(objError, "code").get_int();
74 if (code == RPC_INVALID_REQUEST)
75 nStatus = HTTP_BAD_REQUEST;
76 else if (code == RPC_METHOD_NOT_FOUND)
77 nStatus = HTTP_NOT_FOUND;
79 std::string strReply = JSONRPCReply(NullUniValue, objError, id);
81 req->WriteHeader("Content-Type", "application/json");
82 req->WriteReply(nStatus, strReply);
85 //This function checks username and password against -rpcauth
86 //entries from config file.
87 static bool multiUserAuthorized(std::string strUserPass)
89 if (strUserPass.find(":") == std::string::npos) {
90 return false;
92 std::string strUser = strUserPass.substr(0, strUserPass.find(":"));
93 std::string strPass = strUserPass.substr(strUserPass.find(":") + 1);
95 for (const std::string& strRPCAuth : gArgs.GetArgs("-rpcauth")) {
96 //Search for multi-user login/pass "rpcauth" from config
97 std::vector<std::string> vFields;
98 boost::split(vFields, strRPCAuth, boost::is_any_of(":$"));
99 if (vFields.size() != 3) {
100 //Incorrect formatting in config file
101 continue;
104 std::string strName = vFields[0];
105 if (!TimingResistantEqual(strName, strUser)) {
106 continue;
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.c_str()), strSalt.size()).Write(reinterpret_cast<const unsigned char*>(strPass.c_str()), strPass.size()).Finalize(out);
116 std::vector<unsigned char> hexvec(out, out+KEY_SIZE);
117 std::string strHashFromPass = HexStr(hexvec);
119 if (TimingResistantEqual(strHashFromPass, strHash)) {
120 return true;
123 return false;
126 static bool RPCAuthorized(const std::string& strAuth, std::string& strAuthUsernameOut)
128 if (strRPCUserColonPass.empty()) // Belt-and-suspenders measure if InitRPCAuthentication was not called
129 return false;
130 if (strAuth.substr(0, 6) != "Basic ")
131 return false;
132 std::string strUserPass64 = strAuth.substr(6);
133 boost::trim(strUserPass64);
134 std::string strUserPass = DecodeBase64(strUserPass64);
136 if (strUserPass.find(":") != std::string::npos)
137 strAuthUsernameOut = strUserPass.substr(0, strUserPass.find(":"));
139 //Check if authorized under single-user field
140 if (TimingResistantEqual(strUserPass, strRPCUserColonPass)) {
141 return true;
143 return multiUserAuthorized(strUserPass);
146 static bool HTTPReq_JSONRPC(HTTPRequest* req, const std::string &)
148 // JSONRPC handles only POST
149 if (req->GetRequestMethod() != HTTPRequest::POST) {
150 req->WriteReply(HTTP_BAD_METHOD, "JSONRPC server handles only POST requests");
151 return false;
153 // Check authorization
154 std::pair<bool, std::string> authHeader = req->GetHeader("authorization");
155 if (!authHeader.first) {
156 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
157 req->WriteReply(HTTP_UNAUTHORIZED);
158 return false;
161 JSONRPCRequest jreq;
162 if (!RPCAuthorized(authHeader.second, jreq.authUser)) {
163 LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", req->GetPeer().ToString());
165 /* Deter brute-forcing
166 If this results in a DoS the user really
167 shouldn't have their RPC port exposed. */
168 MilliSleep(250);
170 req->WriteHeader("WWW-Authenticate", WWW_AUTH_HEADER_DATA);
171 req->WriteReply(HTTP_UNAUTHORIZED);
172 return false;
175 try {
176 // Parse request
177 UniValue valRequest;
178 if (!valRequest.read(req->ReadBody()))
179 throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
181 // Set the URI
182 jreq.URI = req->GetURI();
184 std::string strReply;
185 // singleton request
186 if (valRequest.isObject()) {
187 jreq.parse(valRequest);
189 UniValue result = tableRPC.execute(jreq);
191 // Send reply
192 strReply = JSONRPCReply(result, NullUniValue, jreq.id);
194 // array of requests
195 } else if (valRequest.isArray())
196 strReply = JSONRPCExecBatch(valRequest.get_array());
197 else
198 throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
200 req->WriteHeader("Content-Type", "application/json");
201 req->WriteReply(HTTP_OK, strReply);
202 } catch (const UniValue& objError) {
203 JSONErrorReply(req, objError, jreq.id);
204 return false;
205 } catch (const std::exception& e) {
206 JSONErrorReply(req, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
207 return false;
209 return true;
212 static bool InitRPCAuthentication()
214 if (GetArg("-rpcpassword", "") == "")
216 LogPrintf("No rpcpassword set - using random cookie authentication\n");
217 if (!GenerateAuthCookie(&strRPCUserColonPass)) {
218 uiInterface.ThreadSafeMessageBox(
219 _("Error: A fatal internal error occurred, see debug.log for details"), // Same message as AbortNode
220 "", CClientUIInterface::MSG_ERROR);
221 return false;
223 } else {
224 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/rpcuser for rpcauth auth generation.\n");
225 strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
227 return true;
230 bool StartHTTPRPC()
232 LogPrint(BCLog::RPC, "Starting HTTP RPC server\n");
233 if (!InitRPCAuthentication())
234 return false;
236 RegisterHTTPHandler("/", true, HTTPReq_JSONRPC);
238 assert(EventBase());
239 httpRPCTimerInterface = new HTTPRPCTimerInterface(EventBase());
240 RPCSetTimerInterface(httpRPCTimerInterface);
241 return true;
244 void InterruptHTTPRPC()
246 LogPrint(BCLog::RPC, "Interrupting HTTP RPC server\n");
249 void StopHTTPRPC()
251 LogPrint(BCLog::RPC, "Stopping HTTP RPC server\n");
252 UnregisterHTTPHandler("/", true);
253 if (httpRPCTimerInterface) {
254 RPCUnsetTimerInterface(httpRPCTimerInterface);
255 delete httpRPCTimerInterface;
256 httpRPCTimerInterface = 0;