Bitcoin ABC  0.26.3
P2P Digital Currency
request.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2019 The Bitcoin developers
2 // Copyright (c) 2009-2019 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/request.h>
7 
8 #include <fs.h>
9 #include <logging.h>
10 #include <random.h>
11 #include <rpc/protocol.h>
12 #include <util/strencodings.h>
13 #include <util/system.h>
14 
24 UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params,
25  const UniValue &id) {
26  UniValue request(UniValue::VOBJ);
27  request.pushKV("method", strMethod);
28  request.pushKV("params", params);
29  request.pushKV("id", id);
30  return request;
31 }
32 
34  const UniValue &id) {
35  UniValue reply(UniValue::VOBJ);
36  if (!error.isNull()) {
37  reply.pushKV("result", NullUniValue);
38  } else {
39  reply.pushKV("result", result);
40  }
41  reply.pushKV("error", error);
42  reply.pushKV("id", id);
43  return reply;
44 }
45 
46 std::string JSONRPCReply(const UniValue &result, const UniValue &error,
47  const UniValue &id) {
48  UniValue reply = JSONRPCReplyObj(result, error, id);
49  return reply.write() + "\n";
50 }
51 
52 UniValue JSONRPCError(int code, const std::string &message) {
54  error.pushKV("code", code);
55  error.pushKV("message", message);
56  return error;
57 }
58 
63 static const std::string COOKIEAUTH_USER = "__cookie__";
65 static const std::string COOKIEAUTH_FILE = ".cookie";
66 
68 static fs::path GetAuthCookieFile(bool temp = false) {
69  std::string arg = gArgs.GetArg("-rpccookiefile", COOKIEAUTH_FILE);
70  if (temp) {
71  arg += ".tmp";
72  }
74 }
75 
76 bool GenerateAuthCookie(std::string *cookie_out) {
77  const size_t COOKIE_SIZE = 32;
78  uint8_t rand_pwd[COOKIE_SIZE];
79  GetRandBytes(rand_pwd, COOKIE_SIZE);
80  std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
81 
86  fsbridge::ofstream file;
87  fs::path filepath_tmp = GetAuthCookieFile(true);
88  file.open(filepath_tmp);
89  if (!file.is_open()) {
90  LogPrintf("Unable to open cookie authentication file %s for writing\n",
91  fs::PathToString(filepath_tmp));
92  return false;
93  }
94  file << cookie;
95  file.close();
96 
97  fs::path filepath = GetAuthCookieFile(false);
98  if (!RenameOver(filepath_tmp, filepath)) {
99  LogPrintf("Unable to rename cookie authentication file %s to %s\n",
100  fs::PathToString(filepath_tmp), fs::PathToString(filepath));
101  return false;
102  }
103  LogPrintf("Generated RPC authentication cookie %s\n",
104  fs::PathToString(filepath));
105 
106  if (cookie_out) {
107  *cookie_out = cookie;
108  }
109  return true;
110 }
111 
112 bool GetAuthCookie(std::string *cookie_out) {
113  fsbridge::ifstream file;
114  std::string cookie;
115  fs::path filepath = GetAuthCookieFile();
116  file.open(filepath);
117  if (!file.is_open()) {
118  return false;
119  }
120  std::getline(file, cookie);
121  file.close();
122 
123  if (cookie_out) {
124  *cookie_out = cookie;
125  }
126  return true;
127 }
128 
130  try {
131  fs::remove(GetAuthCookieFile());
132  } catch (const fs::filesystem_error &e) {
133  LogPrintf("%s: Unable to remove random auth cookie file: %s\n",
135  }
136 }
137 
138 std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue &in) {
139  if (!in.isArray()) {
140  throw std::runtime_error("Batch must be an array");
141  }
142  const size_t num{in.size()};
143  std::vector<UniValue> batch(num);
144  for (const UniValue &rec : in.getValues()) {
145  if (!rec.isObject()) {
146  throw std::runtime_error("Batch member must be an object");
147  }
148  size_t id = rec["id"].get_int();
149  if (id >= num) {
150  throw std::runtime_error(
151  "Batch member id is larger than batch size");
152  }
153  batch[id] = rec;
154  }
155  return batch;
156 }
157 
158 void JSONRPCRequest::parse(const UniValue &valRequest) {
159  // Parse request
160  if (!valRequest.isObject()) {
161  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
162  }
163 
164  const UniValue &request = valRequest.get_obj();
165 
166  // Parse id now so errors from here on will have the id
167  id = find_value(request, "id");
168 
169  // Parse method
170  UniValue valMethod = find_value(request, "method");
171  if (valMethod.isNull()) {
172  throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
173  }
174  if (!valMethod.isStr()) {
175  throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
176  }
177  strMethod = valMethod.get_str();
178  if (fLogIPs) {
179  LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n",
180  SanitizeString(strMethod), this->authUser, this->peerAddr);
181  } else {
182  LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n",
184  }
185 
186  // Parse params
187  UniValue valParams = find_value(request, "params");
188  if (valParams.isArray() || valParams.isObject()) {
189  params = valParams;
190  } else if (valParams.isNull()) {
192  } else {
194  "Params must be an array or object");
195  }
196 }
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:584
UniValue params
Definition: request.h:34
std::string strMethod
Definition: request.h:33
std::string peerAddr
Definition: request.h:38
void parse(const UniValue &valRequest)
Definition: request.cpp:158
std::string authUser
Definition: request.h:37
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:95
@ VOBJ
Definition: univalue.h:27
@ VARR
Definition: univalue.h:27
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool isNull() const
Definition: univalue.h:89
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:80
const std::vector< UniValue > & getValues() const
bool isStr() const
Definition: univalue.h:93
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool isObject() const
Definition: univalue.h:96
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
bool fLogIPs
Definition: logging.cpp:16
#define LogPrint(category,...)
Definition: logging.h:208
#define LogPrintf(...)
Definition: logging.h:204
@ RPC
Definition: logging.h:46
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:134
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:147
fs::ofstream ofstream
Definition: fs.h:247
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:139
fs::ifstream ifstream
Definition: fs.h:246
void GetRandBytes(uint8_t *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:634
static fs::path GetAuthCookieFile(bool temp=false)
Get name of RPC authentication cookie file.
Definition: request.cpp:68
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:138
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:112
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:46
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params, const UniValue &id)
JSON-RPC protocol.
Definition: request.cpp:24
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
Definition: request.cpp:129
static const std::string COOKIEAUTH_FILE
Default name for auth cookie file.
Definition: request.cpp:65
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:76
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:33
static const std::string COOKIEAUTH_USER
Username used when cookie authentication is in use (arbitrary, only for recognizability in debugging/...
Definition: request.cpp:63
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:26
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1385
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1124
ArgsManager gArgs
Definition: system.cpp:77
bool error(const char *fmt, const Args &...args)
Definition: system.h:46
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
const UniValue NullUniValue
Definition: univalue.cpp:13