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