You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rpcserver.cpp 39KB

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