Branch data Line data Source code
1 : : // Copyright (c) 2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present 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 <crypto/hex_base.h>
10 : : #include <logging.h>
11 : : #include <random.h>
12 : : #include <rpc/protocol.h>
13 : : #include <util/fs.h>
14 : : #include <util/fs_helpers.h>
15 : : #include <util/strencodings.h>
16 : :
17 : : #include <cstddef>
18 : : #include <fstream>
19 : : #include <span>
20 : : #include <stdexcept>
21 : : #include <string>
22 : : #include <system_error>
23 : : #include <utility>
24 : : #include <vector>
25 : :
26 : : /**
27 : : * JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
28 : : * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
29 : : * unspecified (HTTP errors and contents of 'error').
30 : : *
31 : : * 1.0 spec: https://www.jsonrpc.org/specification_v1
32 : : * 1.2 spec: https://jsonrpc.org/historical/json-rpc-over-http.html
33 : : *
34 : : * If the server receives a request with the JSON-RPC 2.0 marker `{"jsonrpc": "2.0"}`
35 : : * then Bitcoin will respond with a strictly specified response.
36 : : * It will only return an HTTP error code if an actual HTTP error is encountered
37 : : * such as the endpoint is not found (404) or the request is not formatted correctly (500).
38 : : * Otherwise the HTTP code is always OK (200) and RPC errors will be included in the
39 : : * response body.
40 : : *
41 : : * 2.0 spec: https://www.jsonrpc.org/specification
42 : : *
43 : : * Also see https://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0
44 : : */
45 : :
46 : 1047 : UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id)
47 : : {
48 : 1047 : UniValue request(UniValue::VOBJ);
49 [ + - + - : 2094 : request.pushKV("method", strMethod);
+ - ]
50 [ + - + - : 2094 : request.pushKV("params", params);
+ - ]
51 [ + - + - : 2094 : request.pushKV("id", id);
+ - ]
52 [ + - + - : 2094 : request.pushKV("jsonrpc", "2.0");
+ - ]
53 : 1047 : return request;
54 : 0 : }
55 : :
56 : 253009 : UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version)
57 : : {
58 : 253009 : UniValue reply(UniValue::VOBJ);
59 : : // Add JSON-RPC version number field in v2 only.
60 [ + + + - : 505768 : if (jsonrpc_version == JSONRPCVersion::V2) reply.pushKV("jsonrpc", "2.0");
+ - + - ]
61 : :
62 : : // Add both result and error fields in v1, even though one will be null.
63 : : // Omit the null field in v2.
64 [ + + ]: 253009 : if (error.isNull()) {
65 [ + - + - ]: 488972 : reply.pushKV("result", std::move(result));
66 [ + + + - : 244629 : if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue);
+ - + - ]
67 : : } else {
68 [ + + + - : 8630 : if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
+ - + - ]
69 [ + - + - ]: 17046 : reply.pushKV("error", std::move(error));
70 : : }
71 [ + + ]: 253009 : if (id.has_value()) {
72 [ + - + - ]: 505750 : reply.pushKVEnd("id", std::move(id.value()));
73 [ + + ]: 134 : } else if (jsonrpc_version == JSONRPCVersion::V2) {
74 : : // The request had no "id" member. This happens for notifications, and
75 : : // for invalid requests that left out the id (for example with a missing
76 : : // or non-string method name). The JSON-RPC 2.0 spec requires every
77 : : // response to have an "id", set to null when the request's id could not
78 : : // be determined, so add "id": null. For notifications this is harmless,
79 : : // because their replies are never sent.
80 [ + - + - : 22 : reply.pushKVEnd("id", NullUniValue);
+ - ]
81 : : }
82 : 253009 : return reply;
83 : 0 : }
84 : :
85 : 8604 : UniValue JSONRPCError(int code, const std::string& message)
86 : : {
87 : 8604 : UniValue error(UniValue::VOBJ);
88 [ + - + - : 17208 : error.pushKV("code", code);
+ - ]
89 [ + - + - : 17208 : error.pushKV("message", message);
+ - ]
90 : 8604 : return error;
91 : 0 : }
92 : :
93 : : /** Username used when cookie authentication is in use (arbitrary, only for
94 : : * recognizability in debugging/logging purposes)
95 : : */
96 : : static const std::string COOKIEAUTH_USER = "__cookie__";
97 : : /** Default name for auth cookie file */
98 : : static const char* const COOKIEAUTH_FILE = ".cookie";
99 : :
100 : : /** Get name of RPC authentication cookie file */
101 : 4799 : static fs::path GetAuthCookieFile(bool temp=false)
102 : : {
103 [ + - + - ]: 9598 : fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE);
104 [ + + ]: 4799 : if (arg.empty()) {
105 : 1 : return {}; // -norpccookiefile was specified
106 : : }
107 [ + + ]: 4798 : if (temp) {
108 [ + - ]: 1255 : arg += ".tmp";
109 : : }
110 [ + - ]: 4798 : return AbsPathForConfigVal(gArgs, arg);
111 : 4799 : }
112 : :
113 : : static bool g_generated_cookie = false;
114 : :
115 : 1256 : AuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms,
116 : : std::string& user,
117 : : std::string& pass)
118 : : {
119 : 1256 : const size_t COOKIE_SIZE = 32;
120 : 1256 : unsigned char rand_pwd[COOKIE_SIZE];
121 : 1256 : GetRandBytes(rand_pwd);
122 : 1256 : const std::string rand_pwd_hex{HexStr(rand_pwd)};
123 : :
124 : : /** the umask determines what permissions are used to create this file -
125 : : * these are set to 0077 in common/system.cpp.
126 : : */
127 [ + - ]: 1256 : std::ofstream file;
128 [ + - ]: 1256 : fs::path filepath_tmp = GetAuthCookieFile(true);
129 [ + + ]: 1256 : if (filepath_tmp.empty()) {
130 : : return AuthCookieResult::Disabled; // -norpccookiefile
131 : : }
132 [ + - ]: 1255 : file.open(filepath_tmp.std_path());
133 [ + + ]: 1255 : if (!file.is_open()) {
134 [ - + + - ]: 2 : LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
135 : 1 : return AuthCookieResult::Error;
136 : : }
137 [ - + + - : 2508 : file << COOKIEAUTH_USER << ":" << rand_pwd_hex;
- + ]
138 [ + - ]: 1254 : file.close();
139 : :
140 [ + - ]: 1254 : fs::path filepath = GetAuthCookieFile(false);
141 [ + - + - : 3762 : if (!RenameOver(filepath_tmp, filepath)) {
+ - - + ]
142 [ # # # # : 0 : LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
# # ]
143 : 0 : return AuthCookieResult::Error;
144 : : }
145 [ + + ]: 1254 : if (cookie_perms) {
146 [ + - ]: 3 : std::error_code code;
147 [ + - ]: 3 : fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
148 [ - + ]: 3 : if (code) {
149 [ # # # # ]: 0 : LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
150 : 0 : return AuthCookieResult::Error;
151 : : }
152 : : }
153 : :
154 : 1254 : g_generated_cookie = true;
155 [ - + + - ]: 2508 : LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
156 [ + - + - : 1254 : LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
+ - ]
157 : :
158 [ + - ]: 1254 : user = COOKIEAUTH_USER;
159 [ + - ]: 2508 : pass = rand_pwd_hex;
160 : : return AuthCookieResult::Ok;
161 : 2510 : }
162 : :
163 : 1035 : AuthCookieResult GetAuthCookie(std::string& cookie_out)
164 : : {
165 : 1035 : std::ifstream file;
166 [ + - ]: 1035 : fs::path filepath = GetAuthCookieFile();
167 [ + - ]: 1035 : if (filepath.empty()) {
168 : : return AuthCookieResult::Disabled; // -norpccookiefile
169 : : }
170 [ + - ]: 1035 : file.open(filepath.std_path());
171 [ + + ]: 1035 : if (!file.is_open()) {
172 : : return AuthCookieResult::Error;
173 : : }
174 [ + - ]: 1033 : std::getline(file, cookie_out);
175 [ + - ]: 1033 : file.close();
176 : : return AuthCookieResult::Ok;
177 : 1035 : }
178 : :
179 : 1306 : void DeleteAuthCookie()
180 : : {
181 : 1306 : try {
182 [ + + ]: 1306 : if (g_generated_cookie) {
183 : : // Delete the cookie file if it was generated by this process
184 [ + - + - ]: 2508 : fs::remove(GetAuthCookieFile());
185 : : }
186 [ - - ]: 0 : } catch (const fs::filesystem_error& e) {
187 [ - - - - : 0 : LogWarning("Unable to remove random auth cookie file %s: %s\n", fs::PathToString(e.path1()), e.code().message());
- - - - ]
188 : 0 : }
189 : 1306 : }
190 : :
191 : 0 : std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
192 : : {
193 [ # # ]: 0 : if (!in.isArray()) {
194 [ # # ]: 0 : throw std::runtime_error("Batch must be an array");
195 : : }
196 [ # # ]: 0 : const size_t num {in.size()};
197 : 0 : std::vector<UniValue> batch(num);
198 [ # # # # ]: 0 : for (const UniValue& rec : in.getValues()) {
199 [ # # ]: 0 : if (!rec.isObject()) {
200 [ # # ]: 0 : throw std::runtime_error("Batch member must be an object");
201 : : }
202 [ # # # # : 0 : size_t id = rec["id"].getInt<int>();
# # ]
203 [ # # ]: 0 : if (id >= num) {
204 [ # # ]: 0 : throw std::runtime_error("Batch member id is larger than batch size");
205 : : }
206 [ # # ]: 0 : batch[id] = rec;
207 : : }
208 : 0 : return batch;
209 : 0 : }
210 : :
211 : 253020 : void JSONRPCRequest::parse(const UniValue& valRequest)
212 : : {
213 : : // Parse request
214 [ + + ]: 253020 : if (!valRequest.isObject())
215 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
216 : 253018 : const UniValue& request = valRequest.get_obj();
217 : :
218 : : // Parse id now so errors from here on will have the id
219 [ + + ]: 506036 : if (request.exists("id")) {
220 : 252871 : id = request.find_value("id");
221 : : } else {
222 : 147 : id = std::nullopt;
223 : : }
224 : :
225 : : // Check for JSON-RPC 2.0 (default 1.1)
226 : 253018 : m_json_version = JSONRPCVersion::V1_LEGACY;
227 : 253018 : const UniValue& jsonrpc_version = request.find_value("jsonrpc");
228 [ + + ]: 253018 : if (!jsonrpc_version.isNull()) {
229 [ + + ]: 252769 : if (!jsonrpc_version.isStr()) {
230 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string");
231 : : }
232 : : // The "jsonrpc" key was added in the 2.0 spec, but some older documentation
233 : : // incorrectly included {"jsonrpc":"1.0"} in a request object, so we
234 : : // maintain that for backwards compatibility.
235 [ + + ]: 252768 : if (jsonrpc_version.get_str() == "1.0") {
236 : 4 : m_json_version = JSONRPCVersion::V1_LEGACY;
237 [ + + ]: 252764 : } else if (jsonrpc_version.get_str() == "2.0") {
238 : 252759 : m_json_version = JSONRPCVersion::V2;
239 : : } else {
240 [ + - + - ]: 10 : throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported");
241 : : }
242 : : }
243 : :
244 : : // Parse method
245 : 253012 : const UniValue& valMethod{request.find_value("method")};
246 [ + + ]: 253012 : if (valMethod.isNull())
247 [ + - + - ]: 22 : throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
248 [ + + ]: 253001 : if (!valMethod.isStr())
249 [ + - + - ]: 6 : throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
250 : 252998 : strMethod = valMethod.get_str();
251 [ + + + + : 252998 : const std::string log_id{id && !id->isNull() ? SanitizeString(id->getValStr()) : ""};
- + ]
252 [ + + ]: 252998 : if (fLogIPs)
253 [ + - + - : 46 : LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s id=%s", SanitizeString(strMethod),
- + + - +
- ]
254 : : this->authUser, this->peerAddr, log_id);
255 : : else
256 [ + - + - : 252952 : LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s id=%s", SanitizeString(strMethod), this->authUser,
- + + - +
- ]
257 : : log_id);
258 : :
259 : : // Parse params
260 [ + - ]: 252998 : const UniValue& valParams{request.find_value("params")};
261 [ + + + + ]: 252998 : if (valParams.isArray() || valParams.isObject())
262 [ + - ]: 252854 : params = valParams;
263 [ + + ]: 144 : else if (valParams.isNull())
264 : 141 : params = UniValue(UniValue::VARR);
265 : : else
266 [ + - + - ]: 6 : throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
267 : :
268 : : // A notification is a valid JSON-RPC 2.0 request without an "id" member.
269 : : // Invalid requests are not notifications, and get an error reply even
270 : : // without an id.
271 [ + + + + ]: 505738 : m_notification = m_json_version == JSONRPCVersion::V2 && !id.has_value();
272 : 252995 : }
|