/tmp/bitcoin/src/rpc/request.cpp
Line | Count | Source |
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 <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 | | |
21 | | /** |
22 | | * JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, |
23 | | * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were |
24 | | * unspecified (HTTP errors and contents of 'error'). |
25 | | * |
26 | | * 1.0 spec: https://www.jsonrpc.org/specification_v1 |
27 | | * 1.2 spec: https://jsonrpc.org/historical/json-rpc-over-http.html |
28 | | * |
29 | | * If the server receives a request with the JSON-RPC 2.0 marker `{"jsonrpc": "2.0"}` |
30 | | * then Bitcoin will respond with a strictly specified response. |
31 | | * It will only return an HTTP error code if an actual HTTP error is encountered |
32 | | * such as the endpoint is not found (404) or the request is not formatted correctly (500). |
33 | | * Otherwise the HTTP code is always OK (200) and RPC errors will be included in the |
34 | | * response body. |
35 | | * |
36 | | * 2.0 spec: https://www.jsonrpc.org/specification |
37 | | * |
38 | | * Also see https://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0 |
39 | | */ |
40 | | |
41 | | UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id) |
42 | 1.15k | { |
43 | 1.15k | UniValue request(UniValue::VOBJ); |
44 | 1.15k | request.pushKV("method", strMethod); |
45 | 1.15k | request.pushKV("params", params); |
46 | 1.15k | request.pushKV("id", id); |
47 | 1.15k | request.pushKV("jsonrpc", "2.0"); |
48 | 1.15k | return request; |
49 | 1.15k | } |
50 | | |
51 | | UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version) |
52 | 184k | { |
53 | 184k | UniValue reply(UniValue::VOBJ); |
54 | | // Add JSON-RPC version number field in v2 only. |
55 | 184k | 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 | 184k | if (error.isNull()) { |
60 | 177k | reply.pushKV("result", std::move(result)); |
61 | 177k | if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue); |
62 | 177k | } else { |
63 | 6.16k | if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue); |
64 | 6.16k | reply.pushKV("error", std::move(error)); |
65 | 6.16k | } |
66 | 184k | if (id.has_value()) reply.pushKV("id", std::move(id.value())); |
67 | 184k | return reply; |
68 | 184k | } |
69 | | |
70 | | UniValue JSONRPCError(int code, const std::string& message) |
71 | 6.24k | { |
72 | 6.24k | UniValue error(UniValue::VOBJ); |
73 | 6.24k | error.pushKV("code", code); |
74 | 6.24k | error.pushKV("message", message); |
75 | 6.24k | return error; |
76 | 6.24k | } |
77 | | |
78 | | /** Username used when cookie authentication is in use (arbitrary, only for |
79 | | * recognizability in debugging/logging purposes) |
80 | | */ |
81 | | static const std::string COOKIEAUTH_USER = "__cookie__"; |
82 | | /** Default name for auth cookie file */ |
83 | | static const char* const COOKIEAUTH_FILE = ".cookie"; |
84 | | |
85 | | /** Get name of RPC authentication cookie file */ |
86 | | static fs::path GetAuthCookieFile(bool temp=false) |
87 | 4.36k | { |
88 | 4.36k | fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE); |
89 | 4.36k | if (arg.empty()) { |
90 | 3 | return {}; // -norpccookiefile was specified |
91 | 3 | } |
92 | 4.36k | if (temp) { |
93 | 1.09k | arg += ".tmp"; |
94 | 1.09k | } |
95 | 4.36k | return AbsPathForConfigVal(gArgs, arg); |
96 | 4.36k | } |
97 | | |
98 | | static bool g_generated_cookie = false; |
99 | | |
100 | | AuthCookieResult GenerateAuthCookie(const std::optional<fs::perms>& cookie_perms, |
101 | | std::string& user, |
102 | | std::string& pass) |
103 | 1.09k | { |
104 | 1.09k | const size_t COOKIE_SIZE = 32; |
105 | 1.09k | unsigned char rand_pwd[COOKIE_SIZE]; |
106 | 1.09k | GetRandBytes(rand_pwd); |
107 | 1.09k | const std::string rand_pwd_hex{HexStr(rand_pwd)}; |
108 | | |
109 | | /** the umask determines what permissions are used to create this file - |
110 | | * these are set to 0077 in common/system.cpp. |
111 | | */ |
112 | 1.09k | std::ofstream file; |
113 | 1.09k | fs::path filepath_tmp = GetAuthCookieFile(true); |
114 | 1.09k | if (filepath_tmp.empty()) { |
115 | 1 | return AuthCookieResult::Disabled; // -norpccookiefile |
116 | 1 | } |
117 | 1.09k | file.open(filepath_tmp.std_path()); |
118 | 1.09k | if (!file.is_open()) { |
119 | 1 | LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp)); |
120 | 1 | return AuthCookieResult::Error; |
121 | 1 | } |
122 | 1.09k | file << COOKIEAUTH_USER << ":" << rand_pwd_hex; |
123 | 1.09k | file.close(); |
124 | | |
125 | 1.09k | fs::path filepath = GetAuthCookieFile(false); |
126 | 1.09k | if (!RenameOver(filepath_tmp, filepath)) { |
127 | 0 | LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath)); |
128 | 0 | return AuthCookieResult::Error; |
129 | 0 | } |
130 | 1.09k | if (cookie_perms) { |
131 | 3 | std::error_code code; |
132 | 3 | fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code); |
133 | 3 | if (code) { |
134 | 0 | LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath)); |
135 | 0 | return AuthCookieResult::Error; |
136 | 0 | } |
137 | 3 | } |
138 | | |
139 | 1.09k | g_generated_cookie = true; |
140 | 1.09k | LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath)); |
141 | 1.09k | LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions())); |
142 | | |
143 | 1.09k | user = COOKIEAUTH_USER; |
144 | 1.09k | pass = rand_pwd_hex; |
145 | 1.09k | return AuthCookieResult::Ok; |
146 | 1.09k | } |
147 | | |
148 | | AuthCookieResult GetAuthCookie(std::string& cookie_out) |
149 | 1.09k | { |
150 | 1.09k | std::ifstream file; |
151 | 1.09k | fs::path filepath = GetAuthCookieFile(); |
152 | 1.09k | if (filepath.empty()) { |
153 | 2 | return AuthCookieResult::Disabled; // -norpccookiefile |
154 | 2 | } |
155 | 1.09k | file.open(filepath.std_path()); |
156 | 1.09k | if (!file.is_open()) { |
157 | 7 | return AuthCookieResult::Error; |
158 | 7 | } |
159 | 1.08k | std::getline(file, cookie_out); |
160 | 1.08k | file.close(); |
161 | 1.08k | return AuthCookieResult::Ok; |
162 | 1.09k | } |
163 | | |
164 | | void DeleteAuthCookie() |
165 | 1.13k | { |
166 | 1.13k | try { |
167 | 1.13k | if (g_generated_cookie) { |
168 | | // Delete the cookie file if it was generated by this process |
169 | 1.09k | fs::remove(GetAuthCookieFile()); |
170 | 1.09k | } |
171 | 1.13k | } catch (const fs::filesystem_error& e) { |
172 | 0 | LogWarning("Unable to remove random auth cookie file %s: %s\n", fs::PathToString(e.path1()), e.code().message()); |
173 | 0 | } |
174 | 1.13k | } |
175 | | |
176 | | std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in) |
177 | 17 | { |
178 | 17 | if (!in.isArray()) { |
179 | 0 | throw std::runtime_error("Batch must be an array"); |
180 | 0 | } |
181 | 17 | const size_t num {in.size()}; |
182 | 17 | std::vector<UniValue> batch(num); |
183 | 64 | for (const UniValue& rec : in.getValues()) { |
184 | 64 | if (!rec.isObject()) { |
185 | 0 | throw std::runtime_error("Batch member must be an object"); |
186 | 0 | } |
187 | 64 | size_t id = rec["id"].getInt<int>(); |
188 | 64 | if (id >= num) { |
189 | 0 | throw std::runtime_error("Batch member id is larger than batch size"); |
190 | 0 | } |
191 | 64 | batch[id] = rec; |
192 | 64 | } |
193 | 17 | return batch; |
194 | 17 | } |
195 | | |
196 | | void JSONRPCRequest::parse(const UniValue& valRequest) |
197 | 184k | { |
198 | | // Parse request |
199 | 184k | if (!valRequest.isObject()) |
200 | 0 | throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); |
201 | 184k | const UniValue& request = valRequest.get_obj(); |
202 | | |
203 | | // Parse id now so errors from here on will have the id |
204 | 184k | if (request.exists("id")) { |
205 | 184k | id = request.find_value("id"); |
206 | 184k | } else { |
207 | 53 | id = std::nullopt; |
208 | 53 | } |
209 | | |
210 | | // Check for JSON-RPC 2.0 (default 1.1) |
211 | 184k | m_json_version = JSONRPCVersion::V1_LEGACY; |
212 | 184k | const UniValue& jsonrpc_version = request.find_value("jsonrpc"); |
213 | 184k | if (!jsonrpc_version.isNull()) { |
214 | 183k | if (!jsonrpc_version.isStr()) { |
215 | 1 | throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string"); |
216 | 1 | } |
217 | | // The "jsonrpc" key was added in the 2.0 spec, but some older documentation |
218 | | // incorrectly included {"jsonrpc":"1.0"} in a request object, so we |
219 | | // maintain that for backwards compatibility. |
220 | 183k | if (jsonrpc_version.get_str() == "1.0") { |
221 | 4 | m_json_version = JSONRPCVersion::V1_LEGACY; |
222 | 183k | } else if (jsonrpc_version.get_str() == "2.0") { |
223 | 183k | m_json_version = JSONRPCVersion::V2; |
224 | 183k | } else { |
225 | 5 | throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported"); |
226 | 5 | } |
227 | 183k | } |
228 | | |
229 | | // Parse method |
230 | 184k | const UniValue& valMethod{request.find_value("method")}; |
231 | 184k | if (valMethod.isNull()) |
232 | 8 | throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); |
233 | 184k | if (!valMethod.isStr()) |
234 | 0 | throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); |
235 | 184k | strMethod = valMethod.get_str(); |
236 | 184k | const std::string log_id{id && !id->isNull() ? SanitizeString(id->getValStr()) : ""}; |
237 | 184k | if (fLogIPs) |
238 | 184k | LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s id=%s", SanitizeString(strMethod), |
239 | 184k | this->authUser, this->peerAddr, log_id); |
240 | 184k | else |
241 | 184k | LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s id=%s", SanitizeString(strMethod), this->authUser, |
242 | 184k | log_id); |
243 | | |
244 | | // Parse params |
245 | 184k | const UniValue& valParams{request.find_value("params")}; |
246 | 184k | if (valParams.isArray() || valParams.isObject()) |
247 | 183k | params = valParams; |
248 | 118 | else if (valParams.isNull()) |
249 | 118 | params = UniValue(UniValue::VARR); |
250 | 0 | else |
251 | 0 | throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object"); |
252 | 184k | } |