Bitcoin ABC  0.22.13
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  }
73  return AbsPathForConfigVal(fs::path(arg));
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 =
81  COOKIEAUTH_USER + ":" + HexStr(rand_pwd, rand_pwd + COOKIE_SIZE);
82 
87  fsbridge::ofstream file;
88  fs::path filepath_tmp = GetAuthCookieFile(true);
89  file.open(filepath_tmp);
90  if (!file.is_open()) {
91  LogPrintf("Unable to open cookie authentication file %s for writing\n",
92  filepath_tmp.string());
93  return false;
94  }
95  file << cookie;
96  file.close();
97 
98  fs::path filepath = GetAuthCookieFile(false);
99  if (!RenameOver(filepath_tmp, filepath)) {
100  LogPrintf("Unable to rename cookie authentication file %s to %s\n",
101  filepath_tmp.string(), filepath.string());
102  return false;
103  }
104  LogPrintf("Generated RPC authentication cookie %s\n", filepath.string());
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, size_t num) {
139  if (!in.isArray()) {
140  throw std::runtime_error("Batch must be an array");
141  }
142  std::vector<UniValue> batch(num);
143  for (size_t i = 0; i < in.size(); ++i) {
144  const UniValue &rec = in[i];
145  if (!rec.isObject()) {
146  throw std::runtime_error("Batch member must be object");
147  }
148  size_t id = rec["id"].get_int();
149  if (id >= num) {
150  throw std::runtime_error("Batch member id larger than size");
151  }
152  batch[id] = rec;
153  }
154  return batch;
155 }
156 
157 void JSONRPCRequest::parse(const UniValue &valRequest) {
158  // Parse request
159  if (!valRequest.isObject()) {
160  throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
161  }
162 
163  const UniValue &request = valRequest.get_obj();
164 
165  // Parse id now so errors from here on will have the id
166  id = find_value(request, "id");
167 
168  // Parse method
169  UniValue valMethod = find_value(request, "method");
170  if (valMethod.isNull()) {
171  throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
172  }
173  if (!valMethod.isStr()) {
174  throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
175  }
176  strMethod = valMethod.get_str();
177  if (fLogIPs) {
178  LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n",
179  SanitizeString(strMethod), this->authUser, this->peerAddr);
180  } else {
181  LogPrint(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n",
183  }
184 
185  // Parse params
186  UniValue valParams = find_value(request, "params");
187  if (valParams.isArray() || valParams.isObject()) {
188  params = valParams;
189  } else if (valParams.isNull()) {
191  } else {
193  "Params must be an array or object");
194  }
195 }
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
bool isObject() const
Definition: univalue.h:96
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in, size_t num)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:138
#define LogPrint(category,...)
Definition: logging.h:192
fs::ifstream ifstream
Definition: fs.h:98
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:174
const std::string & get_str() const
bool isStr() const
Definition: univalue.h:93
fs::ofstream ofstream
Definition: fs.h:99
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
Definition: request.cpp:129
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
void GetRandBytes(uint8_t *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:625
static const std::string COOKIEAUTH_FILE
Default name for auth cookie file.
Definition: request.cpp:65
std::string strMethod
Definition: request.h:36
std::string peerAddr
Definition: request.h:41
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
UniValue params
Definition: request.h:37
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
int get_int() const
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:1352
bool isNull() const
Definition: univalue.h:89
std::string JSONRPCReply(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:46
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1091
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:129
void parse(const UniValue &valRequest)
Definition: request.cpp:157
const UniValue & get_obj() const
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:479
bool fLogIPs
Definition: logging.cpp:12
std::string authUser
Definition: request.h:40
UniValue JSONRPCReplyObj(const UniValue &result, const UniValue &error, const UniValue &id)
Definition: request.cpp:33
bool GenerateAuthCookie(std::string *cookie_out)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:76
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
ArgsManager gArgs
Definition: system.cpp:76
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params, const UniValue &id)
JSON-RPC protocol.
Definition: request.cpp:24
const UniValue NullUniValue
Definition: univalue.cpp:13
static fs::path GetAuthCookieFile(bool temp=false)
Get name of RPC authentication cookie file.
Definition: request.cpp:68
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:26
size_t size() const
Definition: univalue.h:80
bool error(const char *fmt, const Args &... args)
Definition: system.h:47
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:112
bool isArray() const
Definition: univalue.h:95
static const std::string COOKIEAUTH_USER
Username used when cookie authentication is in use (arbitrary, only for recognizability in debugging/...
Definition: request.cpp:63