Bitcoin Core 28.99.0
P2P Digital Currency
request.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 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 <common/args.h>
9#include <logging.h>
10#include <random.h>
11#include <rpc/protocol.h>
12#include <util/fs.h>
13#include <util/fs_helpers.h>
14#include <util/strencodings.h>
15
16#include <fstream>
17#include <stdexcept>
18#include <string>
19#include <vector>
20
41UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
42{
43 UniValue request(UniValue::VOBJ);
44 request.pushKV("method", strMethod);
45 request.pushKV("params", params);
46 request.pushKV("id", id);
47 request.pushKV("jsonrpc", "2.0");
48 return request;
49}
50
51UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version)
52{
54 // Add JSON-RPC version number field in v2 only.
55 if (jsonrpc_version == JSONRPCVersion::V2) reply.pushKV("jsonrpc", "2.0");
56
57 // Add both result and error fields in v1, even though one will be null.
58 // Omit the null field in v2.
59 if (error.isNull()) {
60 reply.pushKV("result", std::move(result));
61 if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue);
62 } else {
63 if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
64 reply.pushKV("error", std::move(error));
65 }
66 if (id.has_value()) reply.pushKV("id", std::move(id.value()));
67 return reply;
68}
69
70UniValue JSONRPCError(int code, const std::string& message)
71{
73 error.pushKV("code", code);
74 error.pushKV("message", message);
75 return error;
76}
77
81static const std::string COOKIEAUTH_USER = "__cookie__";
83static const char* const COOKIEAUTH_FILE = ".cookie";
84
86static fs::path GetAuthCookieFile(bool temp=false)
87{
88 fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE);
89 if (arg.empty()) {
90 return {}; // -norpccookiefile was specified
91 }
92 if (temp) {
93 arg += ".tmp";
94 }
95 return AbsPathForConfigVal(gArgs, arg);
96}
97
98static bool g_generated_cookie = false;
99
100bool GenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
101{
102 const size_t COOKIE_SIZE = 32;
103 unsigned char rand_pwd[COOKIE_SIZE];
104 GetRandBytes(rand_pwd);
105 std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
106
110 std::ofstream file;
111 fs::path filepath_tmp = GetAuthCookieFile(true);
112 if (filepath_tmp.empty()) {
113 return true; // -norpccookiefile
114 }
115 file.open(filepath_tmp);
116 if (!file.is_open()) {
117 LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118 return false;
119 }
120 file << cookie;
121 file.close();
122
123 fs::path filepath = GetAuthCookieFile(false);
124 if (!RenameOver(filepath_tmp, filepath)) {
125 LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126 return false;
127 }
128 if (cookie_perms) {
129 std::error_code code;
130 fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131 if (code) {
132 LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133 return false;
134 }
135 }
136
137 g_generated_cookie = true;
138 LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139 LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140
141 if (cookie_out)
142 *cookie_out = cookie;
143 return true;
144}
145
146bool GetAuthCookie(std::string *cookie_out)
147{
148 std::ifstream file;
149 std::string cookie;
150 fs::path filepath = GetAuthCookieFile();
151 if (filepath.empty()) {
152 return true; // -norpccookiefile
153 }
154 file.open(filepath);
155 if (!file.is_open())
156 return false;
157 std::getline(file, cookie);
158 file.close();
159
160 if (cookie_out)
161 *cookie_out = cookie;
162 return true;
163}
164
166{
167 try {
168 if (g_generated_cookie) {
169 // Delete the cookie file if it was generated by this process
170 fs::remove(GetAuthCookieFile());
171 }
172 } catch (const fs::filesystem_error& e) {
173 LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
174 }
175}
176
177std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
178{
179 if (!in.isArray()) {
180 throw std::runtime_error("Batch must be an array");
181 }
182 const size_t num {in.size()};
183 std::vector<UniValue> batch(num);
184 for (const UniValue& rec : in.getValues()) {
185 if (!rec.isObject()) {
186 throw std::runtime_error("Batch member must be an object");
187 }
188 size_t id = rec["id"].getInt<int>();
189 if (id >= num) {
190 throw std::runtime_error("Batch member id is larger than batch size");
191 }
192 batch[id] = rec;
193 }
194 return batch;
195}
196
197void JSONRPCRequest::parse(const UniValue& valRequest)
198{
199 // Parse request
200 if (!valRequest.isObject())
201 throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
202 const UniValue& request = valRequest.get_obj();
203
204 // Parse id now so errors from here on will have the id
205 if (request.exists("id")) {
206 id = request.find_value("id");
207 } else {
208 id = std::nullopt;
209 }
210
211 // Check for JSON-RPC 2.0 (default 1.1)
213 const UniValue& jsonrpc_version = request.find_value("jsonrpc");
214 if (!jsonrpc_version.isNull()) {
215 if (!jsonrpc_version.isStr()) {
216 throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string");
217 }
218 // The "jsonrpc" key was added in the 2.0 spec, but some older documentation
219 // incorrectly included {"jsonrpc":"1.0"} in a request object, so we
220 // maintain that for backwards compatibility.
221 if (jsonrpc_version.get_str() == "1.0") {
223 } else if (jsonrpc_version.get_str() == "2.0") {
225 } else {
226 throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported");
227 }
228 }
229
230 // Parse method
231 const UniValue& valMethod{request.find_value("method")};
232 if (valMethod.isNull())
233 throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
234 if (!valMethod.isStr())
235 throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
236 strMethod = valMethod.get_str();
237 if (fLogIPs)
238 LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n", SanitizeString(strMethod),
239 this->authUser, this->peerAddr);
240 else
241 LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n", SanitizeString(strMethod), this->authUser);
242
243 // Parse params
244 const UniValue& valParams{request.find_value("params")};
245 if (valParams.isArray() || valParams.isObject())
246 params = valParams;
247 else if (valParams.isNull())
249 else
250 throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
251}
ArgsManager gArgs
Definition: args.cpp:42
fs::path AbsPathForConfigVal(const ArgsManager &args, const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: config.cpp:226
fs::path GetPathArg(std::string arg, const fs::path &default_value={}) const
Return path argument or default value.
Definition: args.cpp:272
UniValue params
Definition: request.h:40
std::string strMethod
Definition: request.h:39
JSONRPCVersion m_json_version
Definition: request.h:46
std::string peerAddr
Definition: request.h:44
void parse(const UniValue &valRequest)
Definition: request.cpp:197
std::string authUser
Definition: request.h:43
const std::string & get_str() const
bool isArray() const
Definition: univalue.h:85
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
bool isNull() const
Definition: univalue.h:79
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:71
const std::vector< UniValue > & getValues() const
bool isStr() const
Definition: univalue.h:83
bool exists(const std::string &key) const
Definition: univalue.h:77
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
bool isObject() const
Definition: univalue.h:86
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:249
std::string PermsToSymbolicString(fs::perms p)
Convert fs::perms to symbolic string of the form 'rwxrwxrwx'.
Definition: fs_helpers.cpp:274
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:29
bool fLogIPs
Definition: logging.cpp:45
#define LogWarning(...)
Definition: logging.h:262
#define LogInfo(...)
Definition: logging.h:261
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
@ RPC
Definition: logging.h:50
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Definition: fs.cpp:118
void GetRandBytes(Span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:676
static fs::path GetAuthCookieFile(bool temp=false)
Get name of RPC authentication cookie file.
Definition: request.cpp:86
std::vector< UniValue > JSONRPCProcessBatchReply(const UniValue &in)
Parse JSON-RPC batch reply into a vector.
Definition: request.cpp:177
bool GetAuthCookie(std::string *cookie_out)
Read the RPC authentication cookie from disk.
Definition: request.cpp:146
UniValue JSONRPCRequestObj(const std::string &strMethod, const UniValue &params, const UniValue &id)
JSON-RPC protocol.
Definition: request.cpp:41
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
static const char *const COOKIEAUTH_FILE
Default name for auth cookie file.
Definition: request.cpp:83
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional< UniValue > id, JSONRPCVersion jsonrpc_version)
Definition: request.cpp:51
bool GenerateAuthCookie(std::string *cookie_out, std::optional< fs::perms > cookie_perms)
Generate a new RPC authentication cookie and write it to disk.
Definition: request.cpp:100
void DeleteAuthCookie()
Delete RPC authentication cookie from disk.
Definition: request.cpp:165
static const std::string COOKIEAUTH_USER
Username used when cookie authentication is in use (arbitrary, only for recognizability in debugging/...
Definition: request.cpp:81
static bool g_generated_cookie
Definition: request.cpp:98
JSONRPCVersion
Definition: request.h:16
@ RPC_INVALID_REQUEST
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:29
const UniValue NullUniValue
Definition: univalue.cpp:16
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.