Coverage Report

Created: 2025-02-21 14:37

/root/bitcoin/src/rpc/request.cpp
Line
Count
Source (jump to first uncovered line)
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
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: http://json-rpc.org/wiki/specification
27
 * 1.2 spec: http://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 http://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
0
{
43
0
    UniValue request(UniValue::VOBJ);
44
0
    request.pushKV("method", strMethod);
45
0
    request.pushKV("params", params);
46
0
    request.pushKV("id", id);
47
0
    request.pushKV("jsonrpc", "2.0");
48
0
    return request;
49
0
}
50
51
UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue> id, JSONRPCVersion jsonrpc_version)
52
0
{
53
0
    UniValue reply(UniValue::VOBJ);
54
    // Add JSON-RPC version number field in v2 only.
55
0
    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
0
    if (error.isNull()) {
60
0
        reply.pushKV("result", std::move(result));
61
0
        if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("error", NullUniValue);
62
0
    } else {
63
0
        if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
64
0
        reply.pushKV("error", std::move(error));
65
0
    }
66
0
    if (id.has_value()) reply.pushKV("id", std::move(id.value()));
67
0
    return reply;
68
0
}
69
70
UniValue JSONRPCError(int code, const std::string& message)
71
0
{
72
0
    UniValue error(UniValue::VOBJ);
73
0
    error.pushKV("code", code);
74
0
    error.pushKV("message", message);
75
0
    return error;
76
0
}
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
0
{
88
0
    fs::path arg = gArgs.GetPathArg("-rpccookiefile", COOKIEAUTH_FILE);
89
0
    if (arg.empty()) {
90
0
        return {}; // -norpccookiefile was specified
91
0
    }
92
0
    if (temp) {
93
0
        arg += ".tmp";
94
0
    }
95
0
    return AbsPathForConfigVal(gArgs, arg);
96
0
}
97
98
static bool g_generated_cookie = false;
99
100
bool GenerateAuthCookie(std::string* cookie_out, std::optional<fs::perms> cookie_perms)
101
0
{
102
0
    const size_t COOKIE_SIZE = 32;
103
0
    unsigned char rand_pwd[COOKIE_SIZE];
104
0
    GetRandBytes(rand_pwd);
105
0
    std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd);
106
107
    /** the umask determines what permissions are used to create this file -
108
     * these are set to 0077 in common/system.cpp.
109
     */
110
0
    std::ofstream file;
111
0
    fs::path filepath_tmp = GetAuthCookieFile(true);
112
0
    if (filepath_tmp.empty()) {
113
0
        return true; // -norpccookiefile
114
0
    }
115
0
    file.open(filepath_tmp);
116
0
    if (!file.is_open()) {
117
0
        LogWarning("Unable to open cookie authentication file %s for writing", fs::PathToString(filepath_tmp));
118
0
        return false;
119
0
    }
120
0
    file << cookie;
121
0
    file.close();
122
123
0
    fs::path filepath = GetAuthCookieFile(false);
124
0
    if (!RenameOver(filepath_tmp, filepath)) {
125
0
        LogWarning("Unable to rename cookie authentication file %s to %s", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
126
0
        return false;
127
0
    }
128
0
    if (cookie_perms) {
129
0
        std::error_code code;
130
0
        fs::permissions(filepath, cookie_perms.value(), fs::perm_options::replace, code);
131
0
        if (code) {
132
0
            LogWarning("Unable to set permissions on cookie authentication file %s", fs::PathToString(filepath));
133
0
            return false;
134
0
        }
135
0
    }
136
137
0
    g_generated_cookie = true;
138
0
    LogInfo("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
139
0
    LogInfo("Permissions used for cookie: %s\n", PermsToSymbolicString(fs::status(filepath).permissions()));
140
141
0
    if (cookie_out)
142
0
        *cookie_out = cookie;
143
0
    return true;
144
0
}
145
146
bool GetAuthCookie(std::string *cookie_out)
147
0
{
148
0
    std::ifstream file;
149
0
    std::string cookie;
150
0
    fs::path filepath = GetAuthCookieFile();
151
0
    if (filepath.empty()) {
152
0
        return true; // -norpccookiefile
153
0
    }
154
0
    file.open(filepath);
155
0
    if (!file.is_open())
156
0
        return false;
157
0
    std::getline(file, cookie);
158
0
    file.close();
159
160
0
    if (cookie_out)
161
0
        *cookie_out = cookie;
162
0
    return true;
163
0
}
164
165
void DeleteAuthCookie()
166
0
{
167
0
    try {
168
0
        if (g_generated_cookie) {
169
            // Delete the cookie file if it was generated by this process
170
0
            fs::remove(GetAuthCookieFile());
171
0
        }
172
0
    } catch (const fs::filesystem_error& e) {
173
0
        LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
174
0
    }
175
0
}
176
177
std::vector<UniValue> JSONRPCProcessBatchReply(const UniValue& in)
178
0
{
179
0
    if (!in.isArray()) {
180
0
        throw std::runtime_error("Batch must be an array");
181
0
    }
182
0
    const size_t num {in.size()};
183
0
    std::vector<UniValue> batch(num);
184
0
    for (const UniValue& rec : in.getValues()) {
185
0
        if (!rec.isObject()) {
186
0
            throw std::runtime_error("Batch member must be an object");
187
0
        }
188
0
        size_t id = rec["id"].getInt<int>();
189
0
        if (id >= num) {
190
0
            throw std::runtime_error("Batch member id is larger than batch size");
191
0
        }
192
0
        batch[id] = rec;
193
0
    }
194
0
    return batch;
195
0
}
196
197
void JSONRPCRequest::parse(const UniValue& valRequest)
198
0
{
199
    // Parse request
200
0
    if (!valRequest.isObject())
201
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
202
0
    const UniValue& request = valRequest.get_obj();
203
204
    // Parse id now so errors from here on will have the id
205
0
    if (request.exists("id")) {
206
0
        id = request.find_value("id");
207
0
    } else {
208
0
        id = std::nullopt;
209
0
    }
210
211
    // Check for JSON-RPC 2.0 (default 1.1)
212
0
    m_json_version = JSONRPCVersion::V1_LEGACY;
213
0
    const UniValue& jsonrpc_version = request.find_value("jsonrpc");
214
0
    if (!jsonrpc_version.isNull()) {
215
0
        if (!jsonrpc_version.isStr()) {
216
0
            throw JSONRPCError(RPC_INVALID_REQUEST, "jsonrpc field must be a string");
217
0
        }
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
0
        if (jsonrpc_version.get_str() == "1.0") {
222
0
            m_json_version = JSONRPCVersion::V1_LEGACY;
223
0
        } else if (jsonrpc_version.get_str() == "2.0") {
224
0
            m_json_version = JSONRPCVersion::V2;
225
0
        } else {
226
0
            throw JSONRPCError(RPC_INVALID_REQUEST, "JSON-RPC version not supported");
227
0
        }
228
0
    }
229
230
    // Parse method
231
0
    const UniValue& valMethod{request.find_value("method")};
232
0
    if (valMethod.isNull())
233
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
234
0
    if (!valMethod.isStr())
235
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
236
0
    strMethod = valMethod.get_str();
237
0
    if (fLogIPs)
238
0
        LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s peeraddr=%s\n", SanitizeString(strMethod),
239
0
            this->authUser, this->peerAddr);
240
0
    else
241
0
        LogDebug(BCLog::RPC, "ThreadRPCServer method=%s user=%s\n", SanitizeString(strMethod), this->authUser);
242
243
    // Parse params
244
0
    const UniValue& valParams{request.find_value("params")};
245
0
    if (valParams.isArray() || valParams.isObject())
246
0
        params = valParams;
247
0
    else if (valParams.isNull())
248
0
        params = UniValue(UniValue::VARR);
249
0
    else
250
0
        throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
251
0
}