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  RPCResult::Type::STR, "", "The help text"
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  static const std::string RESULT{PACKAGE_NAME " stopping"};
157  // Accept the deprecated and ignored 'detach' boolean argument
158  // Also accept the hidden 'wait' integer argument (milliseconds)
159  // For instance, 'stop 1000' makes the call wait 1 second before returning
160  // to the client (intended for testing)
161  if (jsonRequest.fHelp || jsonRequest.params.size() > 1)
162  throw std::runtime_error(
163  RPCHelpMan{"stop",
164  "\nRequest a graceful shutdown of " PACKAGE_NAME ".",
165  {},
166  RPCResult{RPCResult::Type::STR, "", "A string with the content '" + RESULT + "'"},
167  RPCExamples{""},
168  }.ToString());
169  // Event loop will exit after current HTTP requests have been handled, so
170  // this reply will get back to the client.
171  StartShutdown();
172  if (jsonRequest.params[0].isNum()) {
173  UninterruptibleSleep(std::chrono::milliseconds{jsonRequest.params[0].get_int()});
174  }
175  return RESULT;
176 }
177 
178 static UniValue uptime(const JSONRPCRequest& jsonRequest)
179 {
180  RPCHelpMan{"uptime",
181  "\nReturns the total uptime of the server.\n",
182  {},
183  RPCResult{
184  RPCResult::Type::NUM, "", "The number of seconds that the server has been running"
185  },
186  RPCExamples{
187  HelpExampleCli("uptime", "")
188  + HelpExampleRpc("uptime", "")
189  },
190  }.Check(jsonRequest);
191 
192  return GetTime() - GetStartupTime();
193 }
194 
195 static UniValue getrpcinfo(const JSONRPCRequest& request)
196 {
197  RPCHelpMan{"getrpcinfo",
198  "\nReturns details of the RPC server.\n",
199  {},
200  RPCResult{
201  RPCResult::Type::OBJ, "", "",
202  {
203  {RPCResult::Type::ARR, "active_commands", "All active commands",
204  {
205  {RPCResult::Type::OBJ, "", "Information about an active command",
206  {
207  {RPCResult::Type::STR, "method", "The name of the RPC command"},
208  {RPCResult::Type::NUM, "duration", "The running time in microseconds"},
209  }},
210  }},
211  {RPCResult::Type::STR, "logpath", "The complete file path to the debug log"},
212  }
213  },
214  RPCExamples{
215  HelpExampleCli("getrpcinfo", "")
216  + HelpExampleRpc("getrpcinfo", "")},
217  }.Check(request);
218 
219  LOCK(g_rpc_server_info.mutex);
220  UniValue active_commands(UniValue::VARR);
221  for (const RPCCommandExecutionInfo& info : g_rpc_server_info.active_commands) {
222  UniValue entry(UniValue::VOBJ);
223  entry.pushKV("method", info.method);
224  entry.pushKV("duration", GetTimeMicros() - info.start);
225  active_commands.push_back(entry);
226  }
227 
228  UniValue result(UniValue::VOBJ);
229  result.pushKV("active_commands", active_commands);
230 
231  const std::string path = LogInstance().m_file_path.string();
232  UniValue log_path(UniValue::VSTR, path);
233  result.pushKV("logpath", log_path);
234 
235  return result;
236 }
237 
238 // clang-format off
239 static const CRPCCommand vRPCCommands[] =
240 { // category name actor (function) argNames
241  // --------------------- ------------------------ ----------------------- ----------
242  /* Overall control/query calls */
243  { "control", "getrpcinfo", &getrpcinfo, {} },
244  { "control", "help", &help, {"command"} },
245  { "control", "stop", &stop, {"wait"} },
246  { "control", "uptime", &uptime, {} },
247 };
248 // clang-format on
249 
251 {
252  unsigned int vcidx;
253  for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
254  {
255  const CRPCCommand *pcmd;
256 
257  pcmd = &vRPCCommands[vcidx];
258  mapCommands[pcmd->name].push_back(pcmd);
259  }
260 }
261 
262 bool CRPCTable::appendCommand(const std::string& name, const CRPCCommand* pcmd)
263 {
264  if (IsRPCRunning())
265  return false;
266 
267  mapCommands[name].push_back(pcmd);
268  return true;
269 }
270 
271 bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
272 {
273  auto it = mapCommands.find(name);
274  if (it != mapCommands.end()) {
275  auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
276  if (it->second.end() != new_end) {
277  it->second.erase(new_end, it->second.end());
278  return true;
279  }
280  }
281  return false;
282 }
283 
284 void StartRPC()
285 {
286  LogPrint(BCLog::RPC, "Starting RPC\n");
287  g_rpc_running = true;
289 }
290 
292 {
293  LogPrint(BCLog::RPC, "Interrupting RPC\n");
294  // Interrupt e.g. running longpolls
295  g_rpc_running = false;
296 }
297 
298 void StopRPC()
299 {
300  LogPrint(BCLog::RPC, "Stopping RPC\n");
301  deadlineTimers.clear();
304 }
305 
307 {
308  return g_rpc_running;
309 }
310 
311 void SetRPCWarmupStatus(const std::string& newStatus)
312 {
313  LOCK(cs_rpcWarmup);
314  rpcWarmupStatus = newStatus;
315 }
316 
318 {
319  LOCK(cs_rpcWarmup);
320  assert(fRPCInWarmup);
321  fRPCInWarmup = false;
322 }
323 
324 bool RPCIsInWarmup(std::string *outStatus)
325 {
326  LOCK(cs_rpcWarmup);
327  if (outStatus)
328  *outStatus = rpcWarmupStatus;
329  return fRPCInWarmup;
330 }
331 
332 bool IsDeprecatedRPCEnabled(const std::string& method)
333 {
334  const std::vector<std::string> enabled_methods = gArgs.GetArgs("-deprecatedrpc");
335 
336  return find(enabled_methods.begin(), enabled_methods.end(), method) != enabled_methods.end();
337 }
338 
340 {
341  UniValue rpc_result(UniValue::VOBJ);
342 
343  try {
344  jreq.parse(req);
345 
346  UniValue result = tableRPC.execute(jreq);
347  rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id);
348  }
349  catch (const UniValue& objError)
350  {
351  rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id);
352  }
353  catch (const std::exception& e)
354  {
355  rpc_result = JSONRPCReplyObj(NullUniValue,
356  JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
357  }
358 
359  return rpc_result;
360 }
361 
362 std::string JSONRPCExecBatch(const JSONRPCRequest& jreq, const UniValue& vReq)
363 {
365  for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
366  ret.push_back(JSONRPCExecOne(jreq, vReq[reqIdx]));
367 
368  return ret.write() + "\n";
369 }
370 
375 static inline JSONRPCRequest transformNamedArguments(const JSONRPCRequest& in, const std::vector<std::string>& argNames)
376 {
377  JSONRPCRequest out = in;
379  // Build a map of parameters, and remove ones that have been processed, so that we can throw a focused error if
380  // there is an unknown one.
381  const std::vector<std::string>& keys = in.params.getKeys();
382  const std::vector<UniValue>& values = in.params.getValues();
383  std::unordered_map<std::string, const UniValue*> argsIn;
384  for (size_t i=0; i<keys.size(); ++i) {
385  argsIn[keys[i]] = &values[i];
386  }
387  // Process expected parameters.
388  int hole = 0;
389  for (const std::string &argNamePattern: argNames) {
390  std::vector<std::string> vargNames;
391  boost::algorithm::split(vargNames, argNamePattern, boost::algorithm::is_any_of("|"));
392  auto fr = argsIn.end();
393  for (const std::string & argName : vargNames) {
394  fr = argsIn.find(argName);
395  if (fr != argsIn.end()) {
396  break;
397  }
398  }
399  if (fr != argsIn.end()) {
400  for (int i = 0; i < hole; ++i) {
401  // Fill hole between specified parameters with JSON nulls,
402  // but not at the end (for backwards compatibility with calls
403  // that act based on number of specified parameters).
404  out.params.push_back(UniValue());
405  }
406  hole = 0;
407  out.params.push_back(*fr->second);
408  argsIn.erase(fr);
409  } else {
410  hole += 1;
411  }
412  }
413  // If there are still arguments in the argsIn map, this is an error.
414  if (!argsIn.empty()) {
415  throw JSONRPCError(RPC_INVALID_PARAMETER, "Unknown named parameter " + argsIn.begin()->first);
416  }
417  // Return request with named arguments transformed to positional arguments
418  return out;
419 }
420 
422 {
423  // Return immediately if in warmup
424  {
425  LOCK(cs_rpcWarmup);
426  if (fRPCInWarmup)
427  throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus);
428  }
429 
430  // Find method
431  auto it = mapCommands.find(request.strMethod);
432  if (it != mapCommands.end()) {
433  UniValue result;
434  for (const auto& command : it->second) {
435  if (ExecuteCommand(*command, request, result, &command == &it->second.back())) {
436  return result;
437  }
438  }
439  }
440  throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
441 }
442 
443 static bool ExecuteCommand(const CRPCCommand& command, const JSONRPCRequest& request, UniValue& result, bool last_handler)
444 {
445  try
446  {
447  RPCCommandExecution execution(request.strMethod);
448  // Execute, convert arguments to array if necessary
449  if (request.params.isObject()) {
450  return command.actor(transformNamedArguments(request, command.argNames), result, last_handler);
451  } else {
452  return command.actor(request, result, last_handler);
453  }
454  }
455  catch (const std::exception& e)
456  {
457  throw JSONRPCError(RPC_MISC_ERROR, e.what());
458  }
459 }
460 
461 std::vector<std::string> CRPCTable::listCommands() const
462 {
463  std::vector<std::string> commandList;
464  for (const auto& i : mapCommands) commandList.emplace_back(i.first);
465  return commandList;
466 }
467 
469 {
470  if (!timerInterface)
471  timerInterface = iface;
472 }
473 
475 {
476  timerInterface = iface;
477 }
478 
480 {
481  if (timerInterface == iface)
482  timerInterface = nullptr;
483 }
484 
485 void RPCRunLater(const std::string& name, std::function<void()> func, int64_t nSeconds)
486 {
487  if (!timerInterface)
488  throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC");
489  deadlineTimers.erase(name);
490  LogPrint(BCLog::RPC, "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name());
491  deadlineTimers.emplace(name, std::unique_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)));
492 }
493 
495 {
496  int flag = 0;
497  if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) == 0)
499  return flag;
500 }
501 
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:375
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:306
void SetRPCWarmupStatus(const std::string &newStatus)
Set the RPC warmup status.
Definition: server.cpp:311
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 OnStopped(std::function< void()> slot)
Definition: server.cpp:71
bool removeCommand(const std::string &name, const CRPCCommand *pcmd)
Definition: server.cpp:271
#define PACKAGE_NAME
void InterruptRPC()
Definition: server.cpp:291
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:82
static UniValue uptime(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:178
const std::vector< std::string > & getKeys() const
static const CRPCCommand vRPCCommands[]
Definition: server.cpp:239
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:485
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:262
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:479
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:443
UniValue execute(const JSONRPCRequest &request) const
Execute a method.
Definition: server.cpp:421
boost::signals2::signal< void()> Stopped
Definition: server.cpp:63
std::string strMethod
Definition: request.h:31
void SetRPCWarmupFinished()
Definition: server.cpp:317
std::string name
Definition: server.h:110
CRPCTable tableRPC
Definition: server.cpp:502
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:195
UniValue params
Definition: request.h:32
#define LOCK(cs)
Definition: sync.h:218
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:362
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:284
UniValue help(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:130
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:332
static UniValue JSONRPCExecOne(JSONRPCRequest jreq, const UniValue &req)
Definition: server.cpp:339
static struct CRPCSignals g_rpcSignals
void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface)
Set the factory function for timer, but only, if unset.
Definition: server.cpp:468
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:65
bool fHelp
Definition: request.h:33
void parse(const UniValue &valRequest)
Definition: request.cpp:153
void StopRPC()
Definition: server.cpp:298
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers, startup time.
Definition: system.cpp:1141
void UninterruptibleSleep(const std::chrono::microseconds &n)
Definition: time.cpp:19
int RPCSerializationFlags()
Definition: server.cpp:494
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:474
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:324
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:23
std::vector< std::string > listCommands() const
Returns a list of registered commands.
Definition: server.cpp:461
auto it
Definition: validation.cpp:361
CRPCTable()
Definition: server.cpp:250
UniValue stop(const JSONRPCRequest &jsonRequest)
Definition: server.cpp:154