PageRenderTime 87ms CodeModel.GetById 38ms RepoModel.GetById 2ms app.codeStats 0ms

/src/rpcserver.cpp

https://gitlab.com/m0gliE/litecoin
C++ | 1033 lines | 834 code | 127 blank | 72 comment | 164 complexity | 9e565232016b671e2e41f9d340528663 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, 0BSD
  1. // Copyright (c) 2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "rpcserver.h"
  6. #include "base58.h"
  7. #include "init.h"
  8. #include "main.h"
  9. #include "ui_interface.h"
  10. #include "util.h"
  11. #ifdef ENABLE_WALLET
  12. #include "wallet.h"
  13. #endif
  14. #include <boost/algorithm/string.hpp>
  15. #include <boost/asio.hpp>
  16. #include <boost/asio/ssl.hpp>
  17. #include <boost/bind.hpp>
  18. #include <boost/filesystem.hpp>
  19. #include <boost/foreach.hpp>
  20. #include <boost/iostreams/concepts.hpp>
  21. #include <boost/iostreams/stream.hpp>
  22. #include <boost/shared_ptr.hpp>
  23. #include <boost/thread.hpp>
  24. #include "json/json_spirit_writer_template.h"
  25. using namespace boost;
  26. using namespace boost::asio;
  27. using namespace json_spirit;
  28. using namespace std;
  29. static std::string strRPCUserColonPass;
  30. static bool fRPCRunning = false;
  31. static bool fRPCInWarmup = true;
  32. static std::string rpcWarmupStatus("RPC server started");
  33. static CCriticalSection cs_rpcWarmup;
  34. //! These are created by StartRPCThreads, destroyed in StopRPCThreads
  35. static asio::io_service* rpc_io_service = NULL;
  36. static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers;
  37. static ssl::context* rpc_ssl_context = NULL;
  38. static boost::thread_group* rpc_worker_group = NULL;
  39. static boost::asio::io_service::work *rpc_dummy_work = NULL;
  40. static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from
  41. static std::vector< boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors;
  42. void RPCTypeCheck(const Array& params,
  43. const list<Value_type>& typesExpected,
  44. bool fAllowNull)
  45. {
  46. unsigned int i = 0;
  47. BOOST_FOREACH(Value_type t, typesExpected)
  48. {
  49. if (params.size() <= i)
  50. break;
  51. const Value& v = params[i];
  52. if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
  53. {
  54. string err = strprintf("Expected type %s, got %s",
  55. Value_type_name[t], Value_type_name[v.type()]);
  56. throw JSONRPCError(RPC_TYPE_ERROR, err);
  57. }
  58. i++;
  59. }
  60. }
  61. void RPCTypeCheck(const Object& o,
  62. const map<string, Value_type>& typesExpected,
  63. bool fAllowNull)
  64. {
  65. BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
  66. {
  67. const Value& v = find_value(o, t.first);
  68. if (!fAllowNull && v.type() == null_type)
  69. throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
  70. if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
  71. {
  72. string err = strprintf("Expected type %s for %s, got %s",
  73. Value_type_name[t.second], t.first, Value_type_name[v.type()]);
  74. throw JSONRPCError(RPC_TYPE_ERROR, err);
  75. }
  76. }
  77. }
  78. static inline int64_t roundint64(double d)
  79. {
  80. return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
  81. }
  82. CAmount AmountFromValue(const Value& value)
  83. {
  84. double dAmount = value.get_real();
  85. if (dAmount <= 0.0 || dAmount > 84000000.0)
  86. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
  87. CAmount nAmount = roundint64(dAmount * COIN);
  88. if (!MoneyRange(nAmount))
  89. throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
  90. return nAmount;
  91. }
  92. Value ValueFromAmount(const CAmount& amount)
  93. {
  94. return (double)amount / (double)COIN;
  95. }
  96. uint256 ParseHashV(const Value& v, string strName)
  97. {
  98. string strHex;
  99. if (v.type() == str_type)
  100. strHex = v.get_str();
  101. if (!IsHex(strHex)) // Note: IsHex("") is false
  102. throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
  103. uint256 result;
  104. result.SetHex(strHex);
  105. return result;
  106. }
  107. uint256 ParseHashO(const Object& o, string strKey)
  108. {
  109. return ParseHashV(find_value(o, strKey), strKey);
  110. }
  111. vector<unsigned char> ParseHexV(const Value& v, string strName)
  112. {
  113. string strHex;
  114. if (v.type() == str_type)
  115. strHex = v.get_str();
  116. if (!IsHex(strHex))
  117. throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
  118. return ParseHex(strHex);
  119. }
  120. vector<unsigned char> ParseHexO(const Object& o, string strKey)
  121. {
  122. return ParseHexV(find_value(o, strKey), strKey);
  123. }
  124. /**
  125. * Note: This interface may still be subject to change.
  126. */
  127. string CRPCTable::help(string strCommand) const
  128. {
  129. string strRet;
  130. string category;
  131. set<rpcfn_type> setDone;
  132. vector<pair<string, const CRPCCommand*> > vCommands;
  133. for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
  134. vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second));
  135. sort(vCommands.begin(), vCommands.end());
  136. BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands)
  137. {
  138. const CRPCCommand *pcmd = command.second;
  139. string strMethod = pcmd->name;
  140. // We already filter duplicates, but these deprecated screw up the sort order
  141. if (strMethod.find("label") != string::npos)
  142. continue;
  143. if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
  144. continue;
  145. #ifdef ENABLE_WALLET
  146. if (pcmd->reqWallet && !pwalletMain)
  147. continue;
  148. #endif
  149. try
  150. {
  151. Array params;
  152. rpcfn_type pfn = pcmd->actor;
  153. if (setDone.insert(pfn).second)
  154. (*pfn)(params, true);
  155. }
  156. catch (std::exception& e)
  157. {
  158. // Help text is returned in an exception
  159. string strHelp = string(e.what());
  160. if (strCommand == "")
  161. {
  162. if (strHelp.find('\n') != string::npos)
  163. strHelp = strHelp.substr(0, strHelp.find('\n'));
  164. if (category != pcmd->category)
  165. {
  166. if (!category.empty())
  167. strRet += "\n";
  168. category = pcmd->category;
  169. string firstLetter = category.substr(0,1);
  170. boost::to_upper(firstLetter);
  171. strRet += "== " + firstLetter + category.substr(1) + " ==\n";
  172. }
  173. }
  174. strRet += strHelp + "\n";
  175. }
  176. }
  177. if (strRet == "")
  178. strRet = strprintf("help: unknown command: %s\n", strCommand);
  179. strRet = strRet.substr(0,strRet.size()-1);
  180. return strRet;
  181. }
  182. Value help(const Array& params, bool fHelp)
  183. {
  184. if (fHelp || params.size() > 1)
  185. throw runtime_error(
  186. "help ( \"command\" )\n"
  187. "\nList all commands, or get help for a specified command.\n"
  188. "\nArguments:\n"
  189. "1. \"command\" (string, optional) The command to get help on\n"
  190. "\nResult:\n"
  191. "\"text\" (string) The help text\n"
  192. );
  193. string strCommand;
  194. if (params.size() > 0)
  195. strCommand = params[0].get_str();
  196. return tableRPC.help(strCommand);
  197. }
  198. Value stop(const Array& params, bool fHelp)
  199. {
  200. // Accept the deprecated and ignored 'detach' boolean argument
  201. if (fHelp || params.size() > 1)
  202. throw runtime_error(
  203. "stop\n"
  204. "\nStop Fastcoin server.");
  205. // Shutdown will take long enough that the response should get back
  206. StartShutdown();
  207. return "Fastcoin server stopping";
  208. }
  209. /**
  210. * Call Table
  211. */
  212. static const CRPCCommand vRPCCommands[] =
  213. { // category name actor (function) okSafeMode threadSafe reqWallet
  214. // --------------------- ------------------------ ----------------------- ---------- ---------- ---------
  215. /* Overall control/query calls */
  216. { "control", "getinfo", &getinfo, true, false, false }, /* uses wallet if enabled */
  217. { "control", "help", &help, true, true, false },
  218. { "control", "stop", &stop, true, true, false },
  219. /* P2P networking */
  220. { "network", "getnetworkinfo", &getnetworkinfo, true, false, false },
  221. { "network", "addnode", &addnode, true, true, false },
  222. { "network", "getaddednodeinfo", &getaddednodeinfo, true, true, false },
  223. { "network", "getconnectioncount", &getconnectioncount, true, false, false },
  224. { "network", "getnettotals", &getnettotals, true, true, false },
  225. { "network", "getpeerinfo", &getpeerinfo, true, false, false },
  226. { "network", "ping", &ping, true, false, false },
  227. /* Block chain and UTXO */
  228. { "blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false },
  229. { "blockchain", "getbestblockhash", &getbestblockhash, true, false, false },
  230. { "blockchain", "getblockcount", &getblockcount, true, false, false },
  231. { "blockchain", "getblock", &getblock, true, false, false },
  232. { "blockchain", "getblockhash", &getblockhash, true, false, false },
  233. { "blockchain", "getchaintips", &getchaintips, true, false, false },
  234. { "blockchain", "getdifficulty", &getdifficulty, true, false, false },
  235. { "blockchain", "getmempoolinfo", &getmempoolinfo, true, true, false },
  236. { "blockchain", "getrawmempool", &getrawmempool, true, false, false },
  237. { "blockchain", "gettxout", &gettxout, true, false, false },
  238. { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
  239. { "blockchain", "verifychain", &verifychain, true, false, false },
  240. { "blockchain", "invalidateblock", &invalidateblock, true, true, false },
  241. { "blockchain", "reconsiderblock", &reconsiderblock, true, true, false },
  242. /* Mining */
  243. { "mining", "getblocktemplate", &getblocktemplate, true, false, false },
  244. { "mining", "getmininginfo", &getmininginfo, true, false, false },
  245. { "mining", "getnetworkhashps", &getnetworkhashps, true, false, false },
  246. { "mining", "prioritisetransaction", &prioritisetransaction, true, false, false },
  247. { "mining", "submitblock", &submitblock, true, true, false },
  248. #ifdef ENABLE_WALLET
  249. /* Coin generation */
  250. { "generating", "getgenerate", &getgenerate, true, false, false },
  251. { "generating", "gethashespersec", &gethashespersec, true, false, false },
  252. { "generating", "setgenerate", &setgenerate, true, true, false },
  253. #endif
  254. /* Raw transactions */
  255. { "rawtransactions", "createrawtransaction", &createrawtransaction, true, false, false },
  256. { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, false, false },
  257. { "rawtransactions", "decodescript", &decodescript, true, false, false },
  258. { "rawtransactions", "getrawtransaction", &getrawtransaction, true, false, false },
  259. { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, false, false },
  260. { "rawtransactions", "signrawtransaction", &signrawtransaction, false, false, false }, /* uses wallet if enabled */
  261. /* Utility functions */
  262. { "util", "createmultisig", &createmultisig, true, true , false },
  263. { "util", "validateaddress", &validateaddress, true, false, false }, /* uses wallet if enabled */
  264. { "util", "verifymessage", &verifymessage, true, false, false },
  265. { "util", "estimatefee", &estimatefee, true, true, false },
  266. { "util", "estimatepriority", &estimatepriority, true, true, false },
  267. /* Not shown in help */
  268. { "hidden", "invalidateblock", &invalidateblock, true, true, false },
  269. { "hidden", "reconsiderblock", &reconsiderblock, true, true, false },
  270. { "hidden", "setmocktime", &setmocktime, true, false, false },
  271. #ifdef ENABLE_WALLET
  272. /* Wallet */
  273. { "wallet", "addmultisigaddress", &addmultisigaddress, true, false, true },
  274. { "wallet", "backupwallet", &backupwallet, true, false, true },
  275. { "wallet", "dumpprivkey", &dumpprivkey, true, false, true },
  276. { "wallet", "dumpwallet", &dumpwallet, true, false, true },
  277. { "wallet", "encryptwallet", &encryptwallet, true, false, true },
  278. { "wallet", "getaccountaddress", &getaccountaddress, true, false, true },
  279. { "wallet", "getaccount", &getaccount, true, false, true },
  280. { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
  281. { "wallet", "getbalance", &getbalance, false, false, true },
  282. { "wallet", "getnewaddress", &getnewaddress, true, false, true },
  283. { "wallet", "getrawchangeaddress", &getrawchangeaddress, true, false, true },
  284. { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
  285. { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
  286. { "wallet", "gettransaction", &gettransaction, false, false, true },
  287. { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, false, true },
  288. { "wallet", "getwalletinfo", &getwalletinfo, false, false, true },
  289. { "wallet", "importprivkey", &importprivkey, true, false, true },
  290. { "wallet", "importwallet", &importwallet, true, false, true },
  291. { "wallet", "importaddress", &importaddress, true, false, true },
  292. { "wallet", "keypoolrefill", &keypoolrefill, true, false, true },
  293. { "wallet", "listaccounts", &listaccounts, false, false, true },
  294. { "wallet", "listaddressgroupings", &listaddressgroupings, false, false, true },
  295. { "wallet", "listlockunspent", &listlockunspent, false, false, true },
  296. { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
  297. { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
  298. { "wallet", "listsinceblock", &listsinceblock, false, false, true },
  299. { "wallet", "listtransactions", &listtransactions, false, false, true },
  300. { "wallet", "listunspent", &listunspent, false, false, true },
  301. { "wallet", "lockunspent", &lockunspent, true, false, true },
  302. { "wallet", "move", &movecmd, false, false, true },
  303. { "wallet", "sendfrom", &sendfrom, false, false, true },
  304. { "wallet", "sendmany", &sendmany, false, false, true },
  305. { "wallet", "sendtoaddress", &sendtoaddress, false, false, true },
  306. { "wallet", "setaccount", &setaccount, true, false, true },
  307. { "wallet", "settxfee", &settxfee, true, false, true },
  308. { "wallet", "signmessage", &signmessage, true, false, true },
  309. { "wallet", "walletlock", &walletlock, true, false, true },
  310. { "wallet", "walletpassphrasechange", &walletpassphrasechange, true, false, true },
  311. { "wallet", "walletpassphrase", &walletpassphrase, true, false, true },
  312. #endif // ENABLE_WALLET
  313. };
  314. CRPCTable::CRPCTable()
  315. {
  316. unsigned int vcidx;
  317. for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
  318. {
  319. const CRPCCommand *pcmd;
  320. pcmd = &vRPCCommands[vcidx];
  321. mapCommands[pcmd->name] = pcmd;
  322. }
  323. }
  324. const CRPCCommand *CRPCTable::operator[](string name) const
  325. {
  326. map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
  327. if (it == mapCommands.end())
  328. return NULL;
  329. return (*it).second;
  330. }
  331. bool HTTPAuthorized(map<string, string>& mapHeaders)
  332. {
  333. string strAuth = mapHeaders["authorization"];
  334. if (strAuth.substr(0,6) != "Basic ")
  335. return false;
  336. string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
  337. string strUserPass = DecodeBase64(strUserPass64);
  338. return TimingResistantEqual(strUserPass, strRPCUserColonPass);
  339. }
  340. void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
  341. {
  342. // Send error reply from json-rpc error object
  343. int nStatus = HTTP_INTERNAL_SERVER_ERROR;
  344. int code = find_value(objError, "code").get_int();
  345. if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
  346. else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
  347. string strReply = JSONRPCReply(Value::null, objError, id);
  348. stream << HTTPReply(nStatus, strReply, false) << std::flush;
  349. }
  350. CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address)
  351. {
  352. CNetAddr netaddr;
  353. // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
  354. if (address.is_v6()
  355. && (address.to_v6().is_v4_compatible()
  356. || address.to_v6().is_v4_mapped()))
  357. address = address.to_v6().to_v4();
  358. if(address.is_v4())
  359. {
  360. boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes();
  361. netaddr.SetRaw(NET_IPV4, &bytes[0]);
  362. }
  363. else
  364. {
  365. boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes();
  366. netaddr.SetRaw(NET_IPV6, &bytes[0]);
  367. }
  368. return netaddr;
  369. }
  370. bool ClientAllowed(const boost::asio::ip::address& address)
  371. {
  372. CNetAddr netaddr = BoostAsioToCNetAddr(address);
  373. BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
  374. if (subnet.Match(netaddr))
  375. return true;
  376. return false;
  377. }
  378. template <typename Protocol>
  379. class AcceptedConnectionImpl : public AcceptedConnection
  380. {
  381. public:
  382. AcceptedConnectionImpl(
  383. asio::io_service& io_service,
  384. ssl::context &context,
  385. bool fUseSSL) :
  386. sslStream(io_service, context),
  387. _d(sslStream, fUseSSL),
  388. _stream(_d)
  389. {
  390. }
  391. virtual std::iostream& stream()
  392. {
  393. return _stream;
  394. }
  395. virtual std::string peer_address_to_string() const
  396. {
  397. return peer.address().to_string();
  398. }
  399. virtual void close()
  400. {
  401. _stream.close();
  402. }
  403. typename Protocol::endpoint peer;
  404. asio::ssl::stream<typename Protocol::socket> sslStream;
  405. private:
  406. SSLIOStreamDevice<Protocol> _d;
  407. iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
  408. };
  409. void ServiceConnection(AcceptedConnection *conn);
  410. //! Forward declaration required for RPCListen
  411. template <typename Protocol, typename SocketAcceptorService>
  412. static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  413. ssl::context& context,
  414. bool fUseSSL,
  415. boost::shared_ptr< AcceptedConnection > conn,
  416. const boost::system::error_code& error);
  417. /**
  418. * Sets up I/O resources to accept and handle a new connection.
  419. */
  420. template <typename Protocol, typename SocketAcceptorService>
  421. static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  422. ssl::context& context,
  423. const bool fUseSSL)
  424. {
  425. // Accept connection
  426. boost::shared_ptr< AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL));
  427. acceptor->async_accept(
  428. conn->sslStream.lowest_layer(),
  429. conn->peer,
  430. boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
  431. acceptor,
  432. boost::ref(context),
  433. fUseSSL,
  434. conn,
  435. _1));
  436. }
  437. /**
  438. * Accept and handle incoming connection.
  439. */
  440. template <typename Protocol, typename SocketAcceptorService>
  441. static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
  442. ssl::context& context,
  443. const bool fUseSSL,
  444. boost::shared_ptr< AcceptedConnection > conn,
  445. const boost::system::error_code& error)
  446. {
  447. // Immediately start accepting new connections, except when we're cancelled or our socket is closed.
  448. if (error != asio::error::operation_aborted && acceptor->is_open())
  449. RPCListen(acceptor, context, fUseSSL);
  450. AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn.get());
  451. if (error)
  452. {
  453. // TODO: Actually handle errors
  454. LogPrintf("%s: Error: %s\n", __func__, error.message());
  455. }
  456. // Restrict callers by IP. It is important to
  457. // do this before starting client thread, to filter out
  458. // certain DoS and misbehaving clients.
  459. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
  460. {
  461. // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
  462. if (!fUseSSL)
  463. conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush;
  464. conn->close();
  465. }
  466. else {
  467. ServiceConnection(conn.get());
  468. conn->close();
  469. }
  470. }
  471. static ip::tcp::endpoint ParseEndpoint(const std::string &strEndpoint, int defaultPort)
  472. {
  473. std::string addr;
  474. int port = defaultPort;
  475. SplitHostPort(strEndpoint, port, addr);
  476. return ip::tcp::endpoint(asio::ip::address::from_string(addr), port);
  477. }
  478. void StartRPCThreads()
  479. {
  480. rpc_allow_subnets.clear();
  481. rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet
  482. rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost
  483. if (mapMultiArgs.count("-rpcallowip"))
  484. {
  485. const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
  486. BOOST_FOREACH(string strAllow, vAllow)
  487. {
  488. CSubNet subnet(strAllow);
  489. if(!subnet.IsValid())
  490. {
  491. uiInterface.ThreadSafeMessageBox(
  492. strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow),
  493. "", CClientUIInterface::MSG_ERROR);
  494. StartShutdown();
  495. return;
  496. }
  497. rpc_allow_subnets.push_back(subnet);
  498. }
  499. }
  500. std::string strAllowed;
  501. BOOST_FOREACH(const CSubNet &subnet, rpc_allow_subnets)
  502. strAllowed += subnet.ToString() + " ";
  503. LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed);
  504. strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
  505. if (((mapArgs["-rpcpassword"] == "") ||
  506. (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword())
  507. {
  508. unsigned char rand_pwd[32];
  509. GetRandBytes(rand_pwd, 32);
  510. uiInterface.ThreadSafeMessageBox(strprintf(
  511. _("To use fastcoind, or the -server option to fastcoin-qt, you must set an rpcpassword in the configuration file:\n"
  512. "%s\n"
  513. "It is recommended you use the following random password:\n"
  514. "rpcuser=fastcoinrpc\n"
  515. "rpcpassword=%s\n"
  516. "(you do not need to remember this password)\n"
  517. "The username and password MUST NOT be the same.\n"
  518. "If the file does not exist, create it with owner-readable-only file permissions.\n"
  519. "It is also recommended to set alertnotify so you are notified of problems;\n"
  520. "for example: alertnotify=echo %%s | mail -s \"Fastcoin Alert\" admin@foo.com\n"),
  521. GetConfigFile().string(),
  522. EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)),
  523. "", CClientUIInterface::MSG_ERROR | CClientUIInterface::SECURE);
  524. StartShutdown();
  525. return;
  526. }
  527. assert(rpc_io_service == NULL);
  528. rpc_io_service = new asio::io_service();
  529. rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
  530. const bool fUseSSL = GetBoolArg("-rpcssl", false);
  531. if (fUseSSL)
  532. {
  533. rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3);
  534. filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
  535. if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
  536. if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
  537. else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
  538. filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
  539. if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
  540. if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
  541. else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
  542. string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
  543. SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
  544. }
  545. std::vector<ip::tcp::endpoint> vEndpoints;
  546. bool bBindAny = false;
  547. int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
  548. if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs
  549. {
  550. vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::loopback(), defaultPort));
  551. vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::loopback(), defaultPort));
  552. if (mapArgs.count("-rpcbind"))
  553. {
  554. LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
  555. }
  556. } else if (mapArgs.count("-rpcbind")) // Specific bind address
  557. {
  558. BOOST_FOREACH(const std::string &addr, mapMultiArgs["-rpcbind"])
  559. {
  560. try {
  561. vEndpoints.push_back(ParseEndpoint(addr, defaultPort));
  562. }
  563. catch(const boost::system::system_error &)
  564. {
  565. uiInterface.ThreadSafeMessageBox(
  566. strprintf(_("Could not parse -rpcbind value %s as network address"), addr),
  567. "", CClientUIInterface::MSG_ERROR);
  568. StartShutdown();
  569. return;
  570. }
  571. }
  572. } else { // No specific bind address specified, bind to any
  573. vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::any(), defaultPort));
  574. vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::any(), defaultPort));
  575. // Prefer making the socket dual IPv6/IPv4 instead of binding
  576. // to both addresses seperately.
  577. bBindAny = true;
  578. }
  579. bool fListening = false;
  580. std::string strerr;
  581. std::string straddress;
  582. BOOST_FOREACH(const ip::tcp::endpoint &endpoint, vEndpoints)
  583. {
  584. try {
  585. asio::ip::address bindAddress = endpoint.address();
  586. straddress = bindAddress.to_string();
  587. LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny);
  588. boost::system::error_code v6_only_error;
  589. boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
  590. acceptor->open(endpoint.protocol());
  591. acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
  592. // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address
  593. acceptor->set_option(boost::asio::ip::v6_only(
  594. !bBindAny || bindAddress != asio::ip::address_v6::any()), v6_only_error);
  595. acceptor->bind(endpoint);
  596. acceptor->listen(socket_base::max_connections);
  597. RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
  598. fListening = true;
  599. rpc_acceptors.push_back(acceptor);
  600. // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately
  601. if(bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error)
  602. break;
  603. }
  604. catch(boost::system::system_error &e)
  605. {
  606. LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what());
  607. strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what());
  608. }
  609. }
  610. if (!fListening) {
  611. uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
  612. StartShutdown();
  613. return;
  614. }
  615. rpc_worker_group = new boost::thread_group();
  616. for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
  617. rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
  618. fRPCRunning = true;
  619. }
  620. void StartDummyRPCThread()
  621. {
  622. if(rpc_io_service == NULL)
  623. {
  624. rpc_io_service = new asio::io_service();
  625. /* Create dummy "work" to keep the thread from exiting when no timeouts active,
  626. * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */
  627. rpc_dummy_work = new asio::io_service::work(*rpc_io_service);
  628. rpc_worker_group = new boost::thread_group();
  629. rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
  630. fRPCRunning = true;
  631. }
  632. }
  633. void StopRPCThreads()
  634. {
  635. if (rpc_io_service == NULL) return;
  636. // Set this to false first, so that longpolling loops will exit when woken up
  637. fRPCRunning = false;
  638. // First, cancel all timers and acceptors
  639. // This is not done automatically by ->stop(), and in some cases the destructor of
  640. // asio::io_service can hang if this is skipped.
  641. boost::system::error_code ec;
  642. BOOST_FOREACH(const boost::shared_ptr<ip::tcp::acceptor> &acceptor, rpc_acceptors)
  643. {
  644. acceptor->cancel(ec);
  645. if (ec)
  646. LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message());
  647. }
  648. rpc_acceptors.clear();
  649. BOOST_FOREACH(const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) &timer, deadlineTimers)
  650. {
  651. timer.second->cancel(ec);
  652. if (ec)
  653. LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message());
  654. }
  655. deadlineTimers.clear();
  656. rpc_io_service->stop();
  657. cvBlockChange.notify_all();
  658. if (rpc_worker_group != NULL)
  659. rpc_worker_group->join_all();
  660. delete rpc_dummy_work; rpc_dummy_work = NULL;
  661. delete rpc_worker_group; rpc_worker_group = NULL;
  662. delete rpc_ssl_context; rpc_ssl_context = NULL;
  663. delete rpc_io_service; rpc_io_service = NULL;
  664. }
  665. bool IsRPCRunning()
  666. {
  667. return fRPCRunning;
  668. }
  669. void SetRPCWarmupStatus(const std::string& newStatus)
  670. {
  671. LOCK(cs_rpcWarmup);
  672. rpcWarmupStatus = newStatus;
  673. }
  674. void SetRPCWarmupFinished()
  675. {
  676. LOCK(cs_rpcWarmup);
  677. assert(fRPCInWarmup);
  678. fRPCInWarmup = false;
  679. }
  680. bool RPCIsInWarmup(std::string *outStatus)
  681. {
  682. LOCK(cs_rpcWarmup);
  683. if (outStatus)
  684. *outStatus = rpcWarmupStatus;
  685. return fRPCInWarmup;
  686. }
  687. void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func)
  688. {
  689. if (!err)
  690. func();
  691. }
  692. void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds)
  693. {
  694. assert(rpc_io_service != NULL);
  695. if (deadlineTimers.count(name) == 0)
  696. {
  697. deadlineTimers.insert(make_pair(name,
  698. boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service))));
  699. }
  700. deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds));
  701. deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func));
  702. }
  703. class JSONRequest
  704. {
  705. public:
  706. Value id;
  707. string strMethod;
  708. Array params;
  709. JSONRequest() { id = Value::null; }
  710. void parse(const Value& valRequest);
  711. };
  712. void JSONRequest::parse(const Value& valRequest)
  713. {
  714. // Parse request
  715. if (valRequest.type() != obj_type)
  716. throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
  717. const Object& request = valRequest.get_obj();
  718. // Parse id now so errors from here on will have the id
  719. id = find_value(request, "id");
  720. // Parse method
  721. Value valMethod = find_value(request, "method");
  722. if (valMethod.type() == null_type)
  723. throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
  724. if (valMethod.type() != str_type)
  725. throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
  726. strMethod = valMethod.get_str();
  727. if (strMethod != "getblocktemplate")
  728. LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod);
  729. // Parse params
  730. Value valParams = find_value(request, "params");
  731. if (valParams.type() == array_type)
  732. params = valParams.get_array();
  733. else if (valParams.type() == null_type)
  734. params = Array();
  735. else
  736. throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
  737. }
  738. static Object JSONRPCExecOne(const Value& req)
  739. {
  740. Object rpc_result;
  741. JSONRequest jreq;
  742. try {
  743. jreq.parse(req);
  744. Value result = tableRPC.execute(jreq.strMethod, jreq.params);
  745. rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
  746. }
  747. catch (Object& objError)
  748. {
  749. rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
  750. }
  751. catch (std::exception& e)
  752. {
  753. rpc_result = JSONRPCReplyObj(Value::null,
  754. JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
  755. }
  756. return rpc_result;
  757. }
  758. static string JSONRPCExecBatch(const Array& vReq)
  759. {
  760. Array ret;
  761. for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
  762. ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
  763. return write_string(Value(ret), false) + "\n";
  764. }
  765. static bool HTTPReq_JSONRPC(AcceptedConnection *conn,
  766. string& strRequest,
  767. map<string, string>& mapHeaders,
  768. bool fRun)
  769. {
  770. // Check authorization
  771. if (mapHeaders.count("authorization") == 0)
  772. {
  773. conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
  774. return false;
  775. }
  776. if (!HTTPAuthorized(mapHeaders))
  777. {
  778. LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
  779. /* Deter brute-forcing
  780. If this results in a DoS the user really
  781. shouldn't have their RPC port exposed. */
  782. MilliSleep(250);
  783. conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush;
  784. return false;
  785. }
  786. JSONRequest jreq;
  787. try
  788. {
  789. // Parse request
  790. Value valRequest;
  791. if (!read_string(strRequest, valRequest))
  792. throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
  793. // Return immediately if in warmup
  794. {
  795. LOCK(cs_rpcWarmup);
  796. if (fRPCInWarmup)
  797. throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
  798. }
  799. string strReply;
  800. // singleton request
  801. if (valRequest.type() == obj_type) {
  802. jreq.parse(valRequest);
  803. Value result = tableRPC.execute(jreq.strMethod, jreq.params);
  804. // Send reply
  805. strReply = JSONRPCReply(result, Value::null, jreq.id);
  806. // array of requests
  807. } else if (valRequest.type() == array_type)
  808. strReply = JSONRPCExecBatch(valRequest.get_array());
  809. else
  810. throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
  811. conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush;
  812. }
  813. catch (Object& objError)
  814. {
  815. ErrorReply(conn->stream(), objError, jreq.id);
  816. return false;
  817. }
  818. catch (std::exception& e)
  819. {
  820. ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
  821. return false;
  822. }
  823. return true;
  824. }
  825. void ServiceConnection(AcceptedConnection *conn)
  826. {
  827. bool fRun = true;
  828. while (fRun && !ShutdownRequested())
  829. {
  830. int nProto = 0;
  831. map<string, string> mapHeaders;
  832. string strRequest, strMethod, strURI;
  833. // Read HTTP request line
  834. if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
  835. break;
  836. // Read HTTP message headers and body
  837. ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE);
  838. // HTTP Keep-Alive is false; close connection immediately
  839. if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true)))
  840. fRun = false;
  841. // Process via JSON-RPC API
  842. if (strURI == "/") {
  843. if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun))
  844. break;
  845. // Process via HTTP REST API
  846. } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) {
  847. if (!HTTPReq_REST(conn, strURI, mapHeaders, fRun))
  848. break;
  849. } else {
  850. conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush;
  851. break;
  852. }
  853. }
  854. }
  855. json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const
  856. {
  857. // Find method
  858. const CRPCCommand *pcmd = tableRPC[strMethod];
  859. if (!pcmd)
  860. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
  861. #ifdef ENABLE_WALLET
  862. if (pcmd->reqWallet && !pwalletMain)
  863. throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
  864. #endif
  865. // Observe safe mode
  866. string strWarning = GetWarnings("rpc");
  867. if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
  868. !pcmd->okSafeMode)
  869. throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
  870. try
  871. {
  872. // Execute
  873. Value result;
  874. {
  875. if (pcmd->threadSafe)
  876. result = pcmd->actor(params, false);
  877. #ifdef ENABLE_WALLET
  878. else if (!pwalletMain) {
  879. LOCK(cs_main);
  880. result = pcmd->actor(params, false);
  881. } else {
  882. LOCK2(cs_main, pwalletMain->cs_wallet);
  883. result = pcmd->actor(params, false);
  884. }
  885. #else // ENABLE_WALLET
  886. else {
  887. LOCK(cs_main);
  888. result = pcmd->actor(params, false);
  889. }
  890. #endif // !ENABLE_WALLET
  891. }
  892. return result;
  893. }
  894. catch (std::exception& e)
  895. {
  896. throw JSONRPCError(RPC_MISC_ERROR, e.what());
  897. }
  898. }
  899. std::string HelpExampleCli(string methodname, string args){
  900. return "> fastcoin-cli " + methodname + " " + args + "\n";
  901. }
  902. std::string HelpExampleRpc(string methodname, string args){
  903. return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", "
  904. "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:9332/\n";
  905. }
  906. const CRPCTable tableRPC;