Bitcoin Core  0.19.99
P2P Digital Currency
server.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <rpc/server.h>
7 
8 #include <rpc/util.h>
9 #include <shutdown.h>
10 #include <sync.h>
11 #include <util/strencodings.h>
12 #include <util/system.h>
13 
14 #include <boost/signals2/signal.hpp>
15 #include <boost/algorithm/string/classification.hpp>
16 #include <boost/algorithm/string/split.hpp>
17 
18 #include <memory> // for unique_ptr
19 #include <unordered_map>
20 
22 static std::atomic<bool> g_rpc_running{false};
23 static bool fRPCInWarmup GUARDED_BY(cs_rpcWarmup) = true;
24 static std::string rpcWarmupStatus GUARDED_BY(cs_rpcWarmup) = "RPC server started";
25 /* Timer-creating functions */
27 /* Map of name to timer. */
28 static std::map<std::string, std::unique_ptr<RPCTimerBase> > deadlineTimers;
29 static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler);
30 
32 {
33  std::string method;
34  int64_t start;
35 };
36 
38 {
40  std::list<RPCCommandExecutionInfo> active_commands GUARDED_BY(mutex);
41 };
42 
44 
46 {
47  std::list<RPCCommandExecutionInfo>::iterator it;
48  explicit RPCCommandExecution(const std::string& method)
49  {
50  LOCK(g_rpc_server_info.mutex);
51  it = g_rpc_server_info.active_commands.insert(g_rpc_server_info.active_commands.end(), {method, GetTimeMicros()});
52  }
54  {
55  LOCK(g_rpc_server_info.mutex);
56  g_rpc_server_info.active_commands.erase(it);
57  }
58 };
59 
60 static struct CRPCSignals
61 {
62  boost::signals2::signal<void ()> Started;
63  boost::signals2::signal<void ()> Stopped;
64 } g_rpcSignals;
65 
66 void RPCServer::OnStarted(std::function<void ()> slot)
67 {
68  g_rpcSignals.Started.connect(slot);
69 }
70 
71 void RPCServer::OnStopped(std::function<void ()> slot)
72 {
73  g_rpcSignals.Stopped.connect(slot);
74 }
75 
76 std::string CRPCTable::help(const std::string& strCommand, const JSONRPCRequest& helpreq) const
77 {
78  std::string strRet;
79  std::string category;
80  std::set<intptr_t> setDone;
81  std::vector<std::pair<std::string, const CRPCCommand*> > vCommands;
82 
83  for (const auto& entry : mapCommands)
84  vCommands.push_back(make_pair(entry.second.front()->category + entry.first, entry.second.front()));
85  sort(vCommands.begin(), vCommands.end());
86 
87  JSONRPCRequest jreq(helpreq);
88  jreq.fHelp = true;
89  jreq.params = UniValue();
90 
91  for (const std::pair<std::string, const CRPCCommand*>& command : vCommands)
92  {
93  const CRPCCommand *pcmd = command.second;
94  std::string strMethod = pcmd->name;
95  if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand)
96  continue;
97  jreq.strMethod = strMethod;
98  try
99  {
100  UniValue unused_result;
101  if (setDone.insert(pcmd->unique_id).second)
102  pcmd->actor(jreq, unused_result, true /* last_handler */);
103  }
104  catch (const std::exception& e)
105  {
106  // Help text is returned in an exception
107  std::string strHelp = std::string(e.what());
108  if (strCommand == "")
109  {
110  if (strHelp.find('\n') != std::string::npos)
111  strHelp = strHelp.substr(0, strHelp.find('\n'));
112 
113  if (category != pcmd->category)
114  {
115  if (!category.empty())
116  strRet += "\n";
117  category = pcmd->category;
118  strRet += "== " + Capitalize(category) + " ==\n";
119  }
120  }
121  strRet += strHelp + "\n";
122  }
123  }
124  if (strRet == "")
125  strRet = strprintf("help: unknown command: %s\n", strCommand);
126  strRet = strRet.substr(0,strRet.size()-1);
127  return strRet;
128 }
129 
130 UniValue help(const JSONRPCRequest& jsonRequest)
131 {
132  if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
133  throw std::runtime_error(
134  RPCHelpMan{"help",
135  "\nList all commands, or get help for a specified command.\n",
136  {
137  {"command", RPCArg::Type::STR, /* default */ "all commands", "The command to get help on"},
138  },
139  RPCResult{
140  "\"text\" (string) The help text\n"
141  },
142  RPCExamples{""},
143  }.ToString()
144  );
145 
146  std::string strCommand;
147  if (jsonRequest.params.size() > 0)
148  strCommand = jsonRequest.params[0].get_str();
149 
150  return tableRPC.help(strCommand, jsonRequest);
151 }
152 
153 
154 UniValue stop(const JSONRPCRequest& jsonRequest)
155 {
156  // Accept the deprecated and ignored 'detach' boolean argument
157  // Also accept the hidden 'wait' integer argument (milliseconds)
158  // For instance, 'stop 1000' makes the call wait 1 second before returning
159  // to the client (intended for testing)
160  if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
161  throw std::runtime_error(
162  RPCHelpMan{"stop",
163  "\nRequest a graceful shutdown of " PACKAGE_NAME ".",
164  {},
165  RPCResults{},
166  RPCExamples{""},
167  }.ToString());
168  // Event loop will exit after current HTTP requests have been handled, so
169  // this reply will get back to the client.
170  StartShutdown();
171  if (jsonRequest.params[0].isNum()) {
172  MilliSleep(jsonRequest.params[0].get_int());
173  }
174  return PACKAGE_NAME " stopping";
175 }
176 
177 static UniValue uptime(const JSONRPCRequest& jsonRequest)
178 {
179  RPCHelpMan{"uptime",
180  "\nReturns the total uptime of the server.\n",
181  {},
182  RPCResult{
183  "ttt (numeric) The number of seconds that the server has been running\n"
184  },
185  RPCExamples{
186  HelpExampleCli("uptime", "")
187  + HelpExampleRpc("uptime", "")
188  },
189  }.Check(jsonRequest);
190 
191  return GetTime() - GetStartupTime();
192 }
193 
194 static UniValue getrpcinfo(const JSONRPCRequest& request)
195 {
196  RPCHelpMan{"getrpcinfo",
197  "\nReturns details of the RPC server.\n",
198  {},
199  RPCResult{
200  "{\n"
201  " \"active_commands\" (json array) All active commands\n"
202  " [\n"
203  " { (json object) Information about an active command\n"
204  " \"method\" (string) The name of the RPC command \n"
205  " \"duration\" (numeric) The running time in microseconds\n"
206  " },...\n"
207  " ],\n"
208  " \"logpath\" : \"xxx\" (string) The complete file path to the debug log\n"
209  "}\n"
210  },
211  RPCExamples{
212  HelpExampleCli("getrpcinfo", "")
213  + HelpExampleRpc("getrpcinfo", "")},
214  }.Check(request);
215 
216  LOCK(g_rpc_server_info.mutex);
217  UniValue active_commands(UniValue::VARR);
218  for (const RPCCommandExecutionInfo& info : g_rpc_server_info.active_commands) {
219  UniValue entry(UniValue::VOBJ);
220  entry.pushKV("method", info.method);
221  entry.pushKV("duration", GetTimeMicros() - info.start);
222  active_commands.push_back(entry);
223  }
224 
225  UniValue result(UniValue::VOBJ);
226  result.pushKV("active_commands", active_commands);
227 
228  const std::string path = LogInstance().m_file_path.string();
229  UniValue log_path(UniValue::VSTR, path);
230  result.pushKV("logpath", log_path);
231 
232  return result;
233 }
234 
235 // clang-format off
236 static const CRPCCommand vRPCCommands[] =
237 { // category name actor (function) argNames
238  // --------------------- ------------------------ ----------------------- ----------
239  /* Overall control/query calls */
240  { "control", "getrpcinfo", &getrpcinfo, {} },
241  { "control", "help", &help, {"command"} },
242  { "control", "stop", &stop, {"wait"} },
243  { "control", "uptime", &uptime, {} },
244 };
245 // clang-format on
246 
248 {
249  unsigned int vcidx;
250  for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
251  {
252  const CRPCCommand *pcmd;
253 
254  pcmd = &vRPCCommands[vcidx];
255  mapCommands[pcmd->name].push_back(pcmd);
256  }
257 }
258 
259 bool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
260 {
261  if (IsRPCRunning())
262  return false;
263 
264  mapCommands[name].push_back(pcmd);
265  return true;
266 }
267 
268 bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
269 {
270  auto it = mapCommands.find(name);
271  if (it != mapCommands.end()) {
272  auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
273  if (it->second.end() != new_end) {
274  it->second.erase(new_end, it->second.end());
275  return true;
276  }
277  }
278  return false;
279 }
280 
281 void StartRPC()
282 {
283  LogPrint(BCLog::RPC, "Starting RPC\n");
284  g_rpc_running = true;
286 }
287 
289 {
290  LogPrint(BCLog::RPC, "Interrupting RPC\n");
291  // Interrupt e.g. running longpolls
292  g_rpc_running = false;
293 }
294 
295 void StopRPC()
296 {
297  LogPrint(BCLog::RPC, "Stopping RPC\n");
298  deadlineTimers.clear();
301 }
302 
304 {
305  return g_rpc_running;
306 }
307 
308 void SetRPCWarmupStatus(const std::string& newStatus)
309 {
310  LOCK(cs_rpcWarmup);
311  rpcWarmupStatus = newStatus;
312 }
313 
315 {
316  LOCK(cs_rpcWarmup);
317  assert(fRPCInWarmup);
318  fRPCInWarmup = false;
319 }
320 
321 bool RPCIsInWarmup(std::string *outStatus)
322 {
323  LOCK(cs_rpcWarmup);
324  if (outStatus)
325  *outStatus = rpcWarmupStatus;
326  return fRPCInWarmup;
327 }
328 
329 bool IsDeprecatedRPCEnabled(const std::string& method)
330 {
331  const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
332 
333  return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
334 }
335 
337 {
338  UniValue rpc_result(UniValue::VOBJ);
339 
340  try {
341  jreq.parse(req);
342 
343  UniValue result = tableRPC.execute(jreq);
344  rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
345  }
346  catch (const UniValue& objError)
347  {
348  rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
349  }
350  catch (const std::exception& e)
351  {
352  rpc_result = JSONRPCReplyObj(NullUniValue,
353  JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
354  }
355 
356  return rpc_result;
357 }
358 
359 std::string JSONRPCExecBatch(const JSONRPCRequest& jreq, const UniValue& vReq)
360 {
362  for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
363  ret.push_back(JSONRPCExecOne(jreq, vReq[reqIdx]));
364 
365  return ret.write() + "\n";
366 }
367 
372 static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::string>& argNames)
373 {
374  JSONRPCRequest out = in;
376  // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
377  // there is an unknown one.
378  const std::vector<std::string>& keys = in.params.getKeys();
379  const std::vector<UniValue>& values = in.params.getValues();
380  std::unordered_map<std::string, const UniValue*> argsIn;
381  for (size_t i=0; i<keys.size(); ++i) {
382  argsIn[keys[i]] = &values[i];
383  }
384  // Process expected parameters.
385  int hole = 0;
386  for (const std::string &argNamePattern: argNames) {
387  std::vector<std::string> vargNames;
388  boost::algorithm::split(vargNames, argNamePattern, boost::algorithm::is_any_of("|"));
389  auto fr = argsIn.end();
390  for (const std::string & argName : vargNames) {
391  fr = argsIn.find(argName);
392  if (fr != argsIn.end()) {
393  break;
394  }
395  }
396  if (fr != argsIn.end()) {
397  for (int i = 0; i < hole; ++i) {
398  // Fill hole between specified parameters with JSON nulls,
399  // but not at the end (for backwards compatibility with calls
400  // that act based on number of specified parameters).
401  out.params.push_back(UniValue());
402  }
403  hole = 0;
404  out.params.push_back(*fr->second);
405  argsIn.erase(fr);
406  } else {
407  hole += 1;
408  }
409  }
410  // If there are still arguments in the argsIn map, this is an error.
411  if (!argsIn.empty()) {
412  throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
413  }
414  // Return request with named arguments transformed to positional arguments
415  return out;
416 }
417 
419 {
420  // Return immediately if in warmup
421  {
422  LOCK(cs_rpcWarmup);
423  if (fRPCInWarmup)
424  throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
425  }
426 
427  // Find method
428  auto it = mapCommands.find(request.strMethod);
429  if (it != mapCommands.end()) {
430  UniValue result;
431  for (const auto& command : it->second) {
432  if (ExecuteCommand(*command, request, result, &command == &it->second.back())) {
433  return result;
434  }
435  }
436  }
437  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
438 }
439 
440 static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler)
441 {
442  try
443  {
444  RPCCommandExecution execution(request.strMethod);
445  // Execute, convert arguments to array if necessary
446  if (request.params.isObject()) {
447  return command.actor(transformNamedArguments(request, command.argNames), result, last_handler);
448  } else {
449  return command.actor(request, result, last_handler);
450  }
451  }
452  catch (const std::exception& e)
453  {
454  throw JSONRPCError(RPC_MISC_ERROR, e.what());
455  }
456 }
457 
458 std::vector<std::string> CRPCTable::listCommands() const
459 {
460  std::vector<std::string> commandList;
461  for (const auto& i : mapCommands) commandList.emplace_back(i.first);
462  return commandList;
463 }
464 
466 {
467  if (!timerInterface)
468  timerInterface = iface;
469 }
470 
472 {
473  timerInterface = iface;
474 }
475 
477 {
478  if (timerInterface == iface)
479  timerInterface = nullptr;
480 }
481 
482 void RPCRunLater(const std::string& name, std::function<void()> func, int64_t nSeconds)
483 {
484  if (!timerInterface)
485  throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
486  deadlineTimers.erase(name);
487  LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
488  deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
489 }
490 
492 {
493  int flag = 0;
494  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
496  return flag;
497 }
498 
bool isObject() const
Definition: univalue.h:84
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
RPC timer "driver".
Definition: server.h:56
static const int SERIALIZE_TRANSACTION_NO_WITNESS
Definition: transaction.h:15
std::string help(const std::string &name, const JSONRPCRequest &helpreq) const
Definition: server.cpp:76
std::string category
Definition: server.h:109
const std::vector< UniValue > & getValues() const
static JSONRPCRequest transformNamedArguments(const JSONRPCRequest &in, const std::vector< std::string > &argNames)
Process named arguments into a vector of positional arguments, based on the passed-in specification f...
Definition: server.cpp:372
BCLog::Logger & LogInstance()
Definition: logging.cpp:14
Bitcoin RPC command dispatcher.
Definition: server.h:119
#define LogPrint(category,...)
Definition: logging.h:179
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:303
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:308
static const unsigned int DEFAULT_RPC_SERIALIZE_VERSION
Definition: server.h:19
Actor actor
Definition: server.h:111
fs::path m_file_path
Definition: logging.h:92
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static bool fRPCInWarmup GUARDED_BY(cs_rpcWarmup)
static std::atomic< bool > g_rpc_running
Definition: server.cpp:22
void MilliSleep(int64_t n)
Definition: time.cpp:75
void OnStopped(std::function< void()> slot)
Definition: server.cpp:71
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:268
#define PACKAGE_NAME
void InterruptRPC()
Definition: server.cpp:288
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:82
static UniValue uptime(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:177
const std::vector< std::string > & getKeys() const
static const CRPCCommand vRPCCommands[]
Definition: server.cpp:236
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:482
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:259
Client still warming up.
Definition: protocol.h:49
std::string method
Definition: server.cpp:33
std::vector< std::string > argNames
Definition: server.h:112
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
static RPCServerInfo g_rpc_server_info
Definition: server.cpp:43
void RPCUnsetTimerInterface(RPCTimerInterface *iface)
Unset factory function for timers.
Definition: server.cpp:476
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
Definition: request.cpp:124
static bool ExecuteCommand(const CRPCCommand &command, const JSONRPCRequest &request, UniValue &result, bool last_handler)
Definition: server.cpp:440
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:418
boost::signals2::signal< void()> Stopped
Definition: server.cpp:63
std::string strMethod
Definition: request.h:31
void SetRPCWarmupFinished()
Definition: server.cpp:314
std::string name
Definition: server.h:110
CRPCTable tableRPC
Definition: server.cpp:499
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:51
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
Mutex mutex
Definition: server.cpp:39
static UniValue getrpcinfo(const JSONRPCRequest &request)
Definition: server.cpp:194
UniValue params
Definition: request.h:32
#define LOCK(cs)
Definition: sync.h:179
const char * name
Definition: rest.cpp:40
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:117
static RPCTimerInterface * timerInterface
Definition: server.cpp:26
boost::signals2::signal< void()> Started
Definition: server.cpp:62
std::string JSONRPCExecBatch(const JSONRPCRequest &jreq, const UniValue &vReq)
Definition: server.cpp:359
UniValue id
Definition: request.h:30
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
General application defined errors.
Definition: protocol.h:39
RPCCommandExecution(const std::string &method)
Definition: server.cpp:48
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
int get_int() const
void StartRPC()
Definition: server.cpp:281
UniValue help(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:130
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:329
static UniValue JSONRPCExecOne(JSONRPCRequest jreq, const UniValue &req)
Definition: server.cpp:336
static struct CRPCSignals g_rpcSignals
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:465
static std::map< std::string, std::unique_ptr< RPCTimerBase > > deadlineTimers
Definition: server.cpp:28
virtual RPCTimerBase * NewTimer(std::function< void()> &func, int64_t millis)=0
Factory function for timers.
int64_t GetTimeMicros()
Returns the system time (not mockable)
Definition: time.cpp:62
bool fHelp
Definition: request.h:33
void parse(const UniValue &valRequest)
Definition: request.cpp:153
void StopRPC()
Definition: server.cpp:295
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers, startup time.
Definition: system.cpp:1141
int RPCSerializationFlags()
Definition: server.cpp:491
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:372
void RPCSetTimerInterface(RPCTimerInterface *iface)
Set the factory function for timers.
Definition: server.cpp:471
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:33
std::list< RPCCommandExecutionInfo >::iterator it
Definition: server.cpp:47
ArgsManager gArgs
Definition: system.cpp:76
bool RPCIsInWarmup(std::string *outStatus)
Definition: server.cpp:321
const UniValue NullUniValue
Definition: univalue.cpp:13
void StartShutdown()
Definition: shutdown.cpp:12
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:112
virtual const char * Name()=0
Implementation name.
void OnStarted(std::function< void()> slot)
Definition: server.cpp:66
size_t size() const
Definition: univalue.h:68
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:353
static RecursiveMutex cs_rpcWarmup
Definition: server.cpp:21
intptr_t unique_id
Definition: server.h:113
int64_t GetTime()
Return system time (or mocked time, if set)
Definition: time.cpp:20
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:458
auto it
Definition: validation.cpp:362
CRPCTable()
Definition: server.cpp:247
UniValue stop(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:154