Bitcoin Core 31.99.0
P2P Digital Currency
config.cpp
Go to the documentation of this file.
1// Copyright (c) 2023-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <common/args.h> // IWYU pragma: associated
6
7#include <common/settings.h>
8#include <sync.h>
9#include <tinyformat.h>
10#include <univalue.h>
11#include <util/check.h>
12#include <util/fs.h>
13#include <util/log.h>
14#include <util/string.h>
15
16#include <algorithm>
17#include <cstdlib>
18#include <fstream>
19#include <iostream>
20#include <list>
21#include <map>
22#include <optional>
23#include <sstream>
24#include <string>
25#include <string_view>
26#include <utility>
27#include <vector>
28
31
32static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
33{
34 std::string str, prefix;
35 std::string::size_type pos;
36 int linenr = 1;
37 while (std::getline(stream, str)) {
38 bool used_hash = false;
39 if ((pos = str.find('#')) != std::string::npos) {
40 str = str.substr(0, pos);
41 used_hash = true;
42 }
43 const static std::string pattern = " \t\r\n";
44 str = TrimString(str, pattern);
45 if (!str.empty()) {
46 if (*str.begin() == '[' && *str.rbegin() == ']') {
47 const std::string section = str.substr(1, str.size() - 2);
48 sections.emplace_back(SectionInfo{section, filepath, linenr});
49 prefix = section + '.';
50 } else if (*str.begin() == '-') {
51 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
52 return false;
53 } else if ((pos = str.find('=')) != std::string::npos) {
54 std::string name = prefix + TrimString(std::string_view{str}.substr(0, pos), pattern);
55 std::string_view value = TrimStringView(std::string_view{str}.substr(pos + 1), pattern);
56 if (used_hash && name.find("rpcpassword") != std::string::npos) {
57 error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
58 return false;
59 }
60 options.emplace_back(name, value);
61 if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
62 sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
63 }
64 } else {
65 error = strprintf("parse error on line %i: %s", linenr, str);
66 if (str.size() >= 2 && str.starts_with("no")) {
67 error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
68 }
69 return false;
70 }
71 }
72 ++linenr;
73 }
74 return true;
75}
76
77bool IsConfSupported(KeyInfo& key, std::string& error) {
78 if (key.name == "conf") {
79 error = "conf cannot be set in the configuration file; use includeconf= if you want to include additional config files";
80 return false;
81 }
82 if (key.name == "reindex") {
83 // reindex can be set in a config file but it is strongly discouraged as this will cause the node to reindex on
84 // every restart. Allow the config but throw a warning
85 LogWarning("reindex=1 is set in the configuration file, which will significantly slow down startup. Consider removing or commenting out this option for better performance, unless there is currently a condition which makes rebuilding the indexes necessary");
86 return true;
87 }
88 return true;
89}
90
91bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
92{
94 std::vector<std::pair<std::string, std::string>> options;
95 if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
96 return false;
97 }
98 for (const std::pair<std::string, std::string>& option : options) {
99 KeyInfo key = InterpretKey(option.first);
100 std::optional<unsigned int> flags = GetArgFlags_('-' + key.name);
101 if (!IsConfSupported(key, error)) return false;
102 if (flags) {
103 std::optional<common::SettingsValue> value = InterpretValue(key, &option.second, *flags, error);
104 if (!value) {
105 return false;
106 }
107 m_settings.ro_config[key.section][key.name].push_back(*value);
108 } else {
109 if (ignore_invalid_keys) {
110 LogWarning("Ignoring unknown configuration value %s", option.first);
111 } else {
112 error = strprintf("Invalid configuration value %s", option.first);
113 return false;
114 }
115 }
116 }
117 return true;
118}
119
120bool ArgsManager::ReadConfigString(const std::string& str_config)
121{
122 std::istringstream streamConfig(str_config);
123 {
124 LOCK(cs_args);
125 m_settings.ro_config.clear();
126 m_config_sections.clear();
127 }
128 std::string error;
129 return ReadConfigStream(streamConfig, "", error);
130}
131
132bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
133{
134 {
135 LOCK(cs_args);
136 m_settings.ro_config.clear();
137 m_config_sections.clear();
138 const auto conf_val = GetPathArg_("-conf", BITCOIN_CONF_FILENAME);
139 m_config_path = (conf_val.is_absolute() || conf_val.empty()) ? conf_val : fsbridge::AbsPathJoin(GetDataDir(/*net_specific=*/false), conf_val);
140 }
141
142 const auto conf_path{GetConfigFilePath()};
143 std::ifstream stream;
144 if (!conf_path.empty()) { // path is empty when -noconf is specified
145 if (fs::is_directory(conf_path)) {
146 error = strprintf("Config file \"%s\" is a directory.", fs::PathToString(conf_path));
147 return false;
148 }
149 stream = std::ifstream{conf_path.std_path()};
150 // If the file is explicitly specified, it must be readable
151 if (IsArgSet("-conf") && !stream.good()) {
152 error = strprintf("specified config file \"%s\" could not be opened.", fs::PathToString(conf_path));
153 return false;
154 }
155 }
156 // ok to not have a config file
157 if (stream.good()) {
158 if (!ReadConfigStream(stream, fs::PathToString(conf_path), error, ignore_invalid_keys)) {
159 return false;
160 }
161 // `-includeconf` cannot be included in the command line arguments except
162 // as `-noincludeconf` (which indicates that no included conf file should be used).
163 bool use_conf_file{true};
164 {
166 if (auto* includes = common::FindKey(m_settings.command_line_options, "includeconf")) {
167 // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
169 use_conf_file = false;
170 }
171 }
172 if (use_conf_file) {
173 std::string chain_id = GetChainTypeString();
174 std::vector<std::string> conf_file_names;
175
176 auto add_includes = [&](const std::string& network, size_t skip = 0) {
177 size_t num_values = 0;
178 LOCK(cs_args);
179 if (auto* section = common::FindKey(m_settings.ro_config, network)) {
180 if (auto* values = common::FindKey(*section, "includeconf")) {
181 for (size_t i = std::max(skip, common::SettingsSpan(*values).negated()); i < values->size(); ++i) {
182 conf_file_names.push_back((*values)[i].get_str());
183 }
184 num_values = values->size();
185 }
186 }
187 return num_values;
188 };
189
190 // We haven't set m_network yet (that happens in SelectParams()), so manually check
191 // for network.includeconf args.
192 const size_t chain_includes = add_includes(chain_id);
193 const size_t default_includes = add_includes({});
194
195 for (const std::string& conf_file_name : conf_file_names) {
196 const auto include_conf_path{AbsPathForConfigVal(*this, fs::PathFromString(conf_file_name), /*net_specific=*/false)};
197 if (fs::is_directory(include_conf_path)) {
198 error = strprintf("Included config file \"%s\" is a directory.", fs::PathToString(include_conf_path));
199 return false;
200 }
201 std::ifstream conf_file_stream{include_conf_path.std_path()};
202 if (conf_file_stream.good()) {
203 if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
204 return false;
205 }
206 LogInfo("Included configuration file %s\n", conf_file_name);
207 } else {
208 error = "Failed to include configuration file " + conf_file_name;
209 return false;
210 }
211 }
212
213 // Warn about recursive -includeconf
214 conf_file_names.clear();
215 add_includes(chain_id, /* skip= */ chain_includes);
216 add_includes({}, /* skip= */ default_includes);
217 std::string chain_id_final = GetChainTypeString();
218 if (chain_id_final != chain_id) {
219 // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
220 add_includes(chain_id_final);
221 }
222 for (const std::string& conf_file_name : conf_file_names) {
223 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
224 }
225 }
226 }
227
228 // If datadir is changed in .conf file:
230 if (!CheckDataDirOption(*this)) {
231 error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
232 return false;
233 }
234 return true;
235}
236
237fs::path AbsPathForConfigVal(const ArgsManager& args, const fs::path& path, bool net_specific)
238{
239 if (path.is_absolute() || path.empty()) {
240 return path;
241 }
242 return fsbridge::AbsPathJoin(net_specific ? args.GetDataDirNet() : args.GetDataDirBase(), path);
243}
std::optional< common::SettingsValue > InterpretValue(const KeyInfo &key, const std::string *value, unsigned int flags, std::string &error)
Interpret settings value based on registered flags.
Definition: args.cpp:103
bool CheckDataDirOption(const ArgsManager &args)
Definition: args.cpp:891
KeyInfo InterpretKey(std::string key)
Parse "name", "section.name", "noname", "section.noname" settings keys.
Definition: args.cpp:75
const char *const BITCOIN_CONF_FILENAME
Definition: args.cpp:35
int flags
Definition: bitcoin-tx.cpp:530
ArgsManager & args
Definition: bitcoind.cpp:280
bool ReadConfigString(const std::string &str_config) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: config.cpp:120
fs::path GetDataDirBase() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path.
Definition: args.cpp:323
fs::path GetConfigFilePath() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return config file path (read-only)
Definition: args.cpp:897
fs::path GetPathArg_(std::string arg, const fs::path &default_value={}) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition: args.cpp:280
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: config.cpp:132
void ClearPathCache() EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Clear cached directory paths.
Definition: args.cpp:359
fs::path GetDataDir(bool net_specific) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Get data directory path.
Definition: args.cpp:333
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
Definition: args.cpp:517
std::string GetChainTypeString() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Returns the appropriate chain type string from the program arguments.
Definition: args.cpp:917
bool IsArgSet(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return true if the given argument has been manually set.
Definition: args.cpp:431
Mutex cs_args
Definition: args.h:142
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition: args.cpp:328
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false) EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Definition: config.cpp:91
std::optional< unsigned int > GetArgFlags_(const std::string &name) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Definition: args.cpp:256
static bool GetConfigOptions(std::istream &stream, const std::string &filepath, std::string &error, std::vector< std::pair< std::string, std::string > > &options, std::list< SectionInfo > &sections)
Definition: config.cpp:32
bool IsConfSupported(KeyInfo &key, std::string &error)
Definition: config.cpp:77
fs::path AbsPathForConfigVal(const ArgsManager &args, 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: config.cpp:237
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:162
#define LogWarning(...)
Definition: log.h:126
#define LogInfo(...)
Definition: log.h:125
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:109
fs::path AbsPathJoin(const fs::path &base, const fs::path &path)
Helper function for joining two paths.
Definition: fs.cpp:32
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:162
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
Definition: string.h:172
const char * prefix
Definition: rest.cpp:1180
const char * name
Definition: rest.cpp:56
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Definition: args.h:77
std::string name
Definition: args.h:78
std::string section
Definition: args.h:79
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:92
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:274
size_t negated() const
Number of negated values.
Definition: settings.cpp:275
#define LOCK(cs)
Definition: sync.h:268
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
assert(!tx.IsCoinBase())