Bitcoin Core  24.99.0
P2P Digital Currency
settings.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019-2022 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 <fs.h>
6 #include <util/settings.h>
7 
8 #include <tinyformat.h>
9 #include <univalue.h>
10 
11 #include <fstream>
12 #include <map>
13 #include <string>
14 #include <vector>
15 
16 namespace util {
17 namespace {
18 
19 enum class Source {
20  FORCED,
21  COMMAND_LINE,
22  RW_SETTINGS,
23  CONFIG_FILE_NETWORK_SECTION,
24  CONFIG_FILE_DEFAULT_SECTION
25 };
26 
32 template <typename Fn>
33 static void MergeSettings(const Settings& settings, const std::string& section, const std::string& name, Fn&& fn)
34 {
35  // Merge in the forced settings
36  if (auto* value = FindKey(settings.forced_settings, name)) {
37  fn(SettingsSpan(*value), Source::FORCED);
38  }
39  // Merge in the command-line options
40  if (auto* values = FindKey(settings.command_line_options, name)) {
41  fn(SettingsSpan(*values), Source::COMMAND_LINE);
42  }
43  // Merge in the read-write settings
44  if (const SettingsValue* value = FindKey(settings.rw_settings, name)) {
45  fn(SettingsSpan(*value), Source::RW_SETTINGS);
46  }
47  // Merge in the network-specific section of the config file
48  if (!section.empty()) {
49  if (auto* map = FindKey(settings.ro_config, section)) {
50  if (auto* values = FindKey(*map, name)) {
51  fn(SettingsSpan(*values), Source::CONFIG_FILE_NETWORK_SECTION);
52  }
53  }
54  }
55  // Merge in the default section of the config file
56  if (auto* map = FindKey(settings.ro_config, "")) {
57  if (auto* values = FindKey(*map, name)) {
58  fn(SettingsSpan(*values), Source::CONFIG_FILE_DEFAULT_SECTION);
59  }
60  }
61 }
62 } // namespace
63 
64 bool ReadSettings(const fs::path& path, std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors)
65 {
66  values.clear();
67  errors.clear();
68 
69  // Ok for file to not exist
70  if (!fs::exists(path)) return true;
71 
72  std::ifstream file;
73  file.open(path);
74  if (!file.is_open()) {
75  errors.emplace_back(strprintf("%s. Please check permissions.", fs::PathToString(path)));
76  return false;
77  }
78 
79  SettingsValue in;
80  if (!in.read(std::string{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()})) {
81  errors.emplace_back(strprintf("Unable to parse settings file %s", fs::PathToString(path)));
82  return false;
83  }
84 
85  if (file.fail()) {
86  errors.emplace_back(strprintf("Failed reading settings file %s", fs::PathToString(path)));
87  return false;
88  }
89  file.close(); // Done with file descriptor. Release while copying data.
90 
91  if (!in.isObject()) {
92  errors.emplace_back(strprintf("Found non-object value %s in settings file %s", in.write(), fs::PathToString(path)));
93  return false;
94  }
95 
96  const std::vector<std::string>& in_keys = in.getKeys();
97  const std::vector<SettingsValue>& in_values = in.getValues();
98  for (size_t i = 0; i < in_keys.size(); ++i) {
99  auto inserted = values.emplace(in_keys[i], in_values[i]);
100  if (!inserted.second) {
101  errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path)));
102  }
103  }
104  return errors.empty();
105 }
106 
107 bool WriteSettings(const fs::path& path,
108  const std::map<std::string, SettingsValue>& values,
109  std::vector<std::string>& errors)
110 {
112  for (const auto& value : values) {
113  out.__pushKV(value.first, value.second);
114  }
115  std::ofstream file;
116  file.open(path);
117  if (file.fail()) {
118  errors.emplace_back(strprintf("Error: Unable to open settings file %s for writing", fs::PathToString(path)));
119  return false;
120  }
121  file << out.write(/* prettyIndent= */ 4, /* indentLevel= */ 1) << std::endl;
122  file.close();
123  return true;
124 }
125 
127  const std::string& section,
128  const std::string& name,
129  bool ignore_default_section_config,
130  bool ignore_nonpersistent,
131  bool get_chain_name)
132 {
133  SettingsValue result;
134  bool done = false; // Done merging any more settings sources.
135  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
136  // Weird behavior preserved for backwards compatibility: Apply negated
137  // setting even if non-negated setting would be ignored. A negated
138  // value in the default section is applied to network specific options,
139  // even though normal non-negated values there would be ignored.
140  const bool never_ignore_negated_setting = span.last_negated();
141 
142  // Weird behavior preserved for backwards compatibility: Take first
143  // assigned value instead of last. In general, later settings take
144  // precedence over early settings, but for backwards compatibility in
145  // the config file the precedence is reversed for all settings except
146  // chain name settings.
147  const bool reverse_precedence =
148  (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
149  !get_chain_name;
150 
151  // Weird behavior preserved for backwards compatibility: Negated
152  // -regtest and -testnet arguments which you would expect to override
153  // values set in the configuration file are currently accepted but
154  // silently ignored. It would be better to apply these just like other
155  // negated values, or at least warn they are ignored.
156  const bool skip_negated_command_line = get_chain_name;
157 
158  if (done) return;
159 
160  // Ignore settings in default config section if requested.
161  if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION &&
162  !never_ignore_negated_setting) {
163  return;
164  }
165 
166  // Ignore nonpersistent settings if requested.
167  if (ignore_nonpersistent && (source == Source::COMMAND_LINE || source == Source::FORCED)) return;
168 
169  // Skip negated command line settings.
170  if (skip_negated_command_line && span.last_negated()) return;
171 
172  if (!span.empty()) {
173  result = reverse_precedence ? span.begin()[0] : span.end()[-1];
174  done = true;
175  } else if (span.last_negated()) {
176  result = false;
177  done = true;
178  }
179  });
180  return result;
181 }
182 
183 std::vector<SettingsValue> GetSettingsList(const Settings& settings,
184  const std::string& section,
185  const std::string& name,
186  bool ignore_default_section_config)
187 {
188  std::vector<SettingsValue> result;
189  bool done = false; // Done merging any more settings sources.
190  bool prev_negated_empty = false;
191  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
192  // Weird behavior preserved for backwards compatibility: Apply config
193  // file settings even if negated on command line. Negating a setting on
194  // command line will ignore earlier settings on the command line and
195  // ignore settings in the config file, unless the negated command line
196  // value is followed by non-negated value, in which case config file
197  // settings will be brought back from the dead (but earlier command
198  // line settings will still be ignored).
199  const bool add_zombie_config_values =
200  (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
201  !prev_negated_empty;
202 
203  // Ignore settings in default config section if requested.
204  if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION) return;
205 
206  // Add new settings to the result if isn't already complete, or if the
207  // values are zombies.
208  if (!done || add_zombie_config_values) {
209  for (const auto& value : span) {
210  if (value.isArray()) {
211  result.insert(result.end(), value.getValues().begin(), value.getValues().end());
212  } else {
213  result.push_back(value);
214  }
215  }
216  }
217 
218  // If a setting was negated, or if a setting was forced, set
219  // done to true to ignore any later lower priority settings.
220  done |= span.negated() > 0 || source == Source::FORCED;
221 
222  // Update the negated and empty state used for the zombie values check.
223  prev_negated_empty |= span.last_negated() && result.empty();
224  });
225  return result;
226 }
227 
228 bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name)
229 {
230  bool has_default_section_setting = false;
231  bool has_other_setting = false;
232  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
233  if (span.empty()) return;
234  else if (source == Source::CONFIG_FILE_DEFAULT_SECTION) has_default_section_setting = true;
235  else has_other_setting = true;
236  });
237  // If a value is set in the default section and not explicitly overwritten by the
238  // user on the command line or in a different section, then we want to enable
239  // warnings about the value being ignored.
240  return has_default_section_setting && !has_other_setting;
241 }
242 
243 SettingsSpan::SettingsSpan(const std::vector<SettingsValue>& vec) noexcept : SettingsSpan(vec.data(), vec.size()) {}
244 const SettingsValue* SettingsSpan::begin() const { return data + negated(); }
245 const SettingsValue* SettingsSpan::end() const { return data + size; }
246 bool SettingsSpan::empty() const { return size == 0 || last_negated(); }
247 bool SettingsSpan::last_negated() const { return size > 0 && data[size - 1].isFalse(); }
248 size_t SettingsSpan::negated() const
249 {
250  for (size_t i = size; i > 0; --i) {
251  if (data[i - 1].isFalse()) return i; // Return number of negated values (position of last false value)
252  }
253  return 0;
254 }
255 
256 } // namespace util
if(!SetupNetworking())
@ VOBJ
Definition: univalue.h:20
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void __pushKV(std::string key, UniValue val)
Definition: univalue.cpp:118
const std::vector< UniValue > & getValues() const
const std::vector< std::string > & getKeys() const
bool isFalse() const
Definition: univalue.h:77
bool read(const char *raw, size_t len)
bool isObject() const
Definition: univalue.h:82
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:31
static bool exists(const path &p)
Definition: fs.h:88
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:150
Definition: overloaded.h:8
std::vector< SettingsValue > GetSettingsList(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config)
Get combined setting value similar to GetSetting(), except if setting was specified multiple times,...
Definition: settings.cpp:183
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool ignore_nonpersistent, bool get_chain_name)
Get settings value from combined sources: forced settings, command line arguments,...
Definition: settings.cpp:126
bool ReadSettings(const fs::path &path, std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Read settings file.
Definition: settings.cpp:64
UniValue SettingsValue
Settings value type (string/integer/boolean/null variant).
Definition: settings.h:27
bool OnlyHasDefaultSectionSetting(const Settings &settings, const std::string &section, const std::string &name)
Return true if a setting is set in the default config file section, and not overridden by a higher pr...
Definition: settings.cpp:228
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:107
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:106
const char * name
Definition: rest.cpp:46
const char * source
Definition: rpcconsole.cpp:59
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
Stored settings.
Definition: settings.h:31
Accessor for list of settings that skips negated values when iterated over.
Definition: settings.h:89
size_t negated() const
Number of negated values.
Definition: settings.cpp:248
const SettingsValue * end() const
Pointer to end of values.
Definition: settings.cpp:245
bool empty() const
True if there are any non-negated values.
Definition: settings.cpp:246
SettingsSpan()=default
const SettingsValue * data
Definition: settings.h:100
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:247
const SettingsValue * begin() const
Pointer to first non-negated value.
Definition: settings.cpp:244
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162