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