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 <util/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  values.clear();
103  break;
104  }
105  }
106  return errors.empty();
107 }
108 
109 bool WriteSettings(const fs::path& path,
110  const std::map<std::string, SettingsValue>& values,
111  std::vector<std::string>& errors)
112 {
114  for (const auto& value : values) {
115  out.__pushKV(value.first, value.second);
116  }
117  std::ofstream file;
118  file.open(path);
119  if (file.fail()) {
120  errors.emplace_back(strprintf("Error: Unable to open settings file %s for writing", fs::PathToString(path)));
121  return false;
122  }
123  file << out.write(/* prettyIndent= */ 4, /* indentLevel= */ 1) << std::endl;
124  file.close();
125  return true;
126 }
127 
129  const std::string& section,
130  const std::string& name,
131  bool ignore_default_section_config,
132  bool ignore_nonpersistent,
133  bool get_chain_type)
134 {
135  SettingsValue result;
136  bool done = false; // Done merging any more settings sources.
137  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
138  // Weird behavior preserved for backwards compatibility: Apply negated
139  // setting even if non-negated setting would be ignored. A negated
140  // value in the default section is applied to network specific options,
141  // even though normal non-negated values there would be ignored.
142  const bool never_ignore_negated_setting = span.last_negated();
143 
144  // Weird behavior preserved for backwards compatibility: Take first
145  // assigned value instead of last. In general, later settings take
146  // precedence over early settings, but for backwards compatibility in
147  // the config file the precedence is reversed for all settings except
148  // chain type settings.
149  const bool reverse_precedence =
150  (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
151  !get_chain_type;
152 
153  // Weird behavior preserved for backwards compatibility: Negated
154  // -regtest and -testnet arguments which you would expect to override
155  // values set in the configuration file are currently accepted but
156  // silently ignored. It would be better to apply these just like other
157  // negated values, or at least warn they are ignored.
158  const bool skip_negated_command_line = get_chain_type;
159 
160  if (done) return;
161 
162  // Ignore settings in default config section if requested.
163  if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION &&
164  !never_ignore_negated_setting) {
165  return;
166  }
167 
168  // Ignore nonpersistent settings if requested.
169  if (ignore_nonpersistent && (source == Source::COMMAND_LINE || source == Source::FORCED)) return;
170 
171  // Skip negated command line settings.
172  if (skip_negated_command_line && span.last_negated()) return;
173 
174  if (!span.empty()) {
175  result = reverse_precedence ? span.begin()[0] : span.end()[-1];
176  done = true;
177  } else if (span.last_negated()) {
178  result = false;
179  done = true;
180  }
181  });
182  return result;
183 }
184 
185 std::vector<SettingsValue> GetSettingsList(const Settings& settings,
186  const std::string& section,
187  const std::string& name,
188  bool ignore_default_section_config)
189 {
190  std::vector<SettingsValue> result;
191  bool done = false; // Done merging any more settings sources.
192  bool prev_negated_empty = false;
193  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
194  // Weird behavior preserved for backwards compatibility: Apply config
195  // file settings even if negated on command line. Negating a setting on
196  // command line will ignore earlier settings on the command line and
197  // ignore settings in the config file, unless the negated command line
198  // value is followed by non-negated value, in which case config file
199  // settings will be brought back from the dead (but earlier command
200  // line settings will still be ignored).
201  const bool add_zombie_config_values =
202  (source == Source::CONFIG_FILE_NETWORK_SECTION || source == Source::CONFIG_FILE_DEFAULT_SECTION) &&
203  !prev_negated_empty;
204 
205  // Ignore settings in default config section if requested.
206  if (ignore_default_section_config && source == Source::CONFIG_FILE_DEFAULT_SECTION) return;
207 
208  // Add new settings to the result if isn't already complete, or if the
209  // values are zombies.
210  if (!done || add_zombie_config_values) {
211  for (const auto& value : span) {
212  if (value.isArray()) {
213  result.insert(result.end(), value.getValues().begin(), value.getValues().end());
214  } else {
215  result.push_back(value);
216  }
217  }
218  }
219 
220  // If a setting was negated, or if a setting was forced, set
221  // done to true to ignore any later lower priority settings.
222  done |= span.negated() > 0 || source == Source::FORCED;
223 
224  // Update the negated and empty state used for the zombie values check.
225  prev_negated_empty |= span.last_negated() && result.empty();
226  });
227  return result;
228 }
229 
230 bool OnlyHasDefaultSectionSetting(const Settings& settings, const std::string& section, const std::string& name)
231 {
232  bool has_default_section_setting = false;
233  bool has_other_setting = false;
234  MergeSettings(settings, section, name, [&](SettingsSpan span, Source source) {
235  if (span.empty()) return;
236  else if (source == Source::CONFIG_FILE_DEFAULT_SECTION) has_default_section_setting = true;
237  else has_other_setting = true;
238  });
239  // If a value is set in the default section and not explicitly overwritten by the
240  // user on the command line or in a different section, then we want to enable
241  // warnings about the value being ignored.
242  return has_default_section_setting && !has_other_setting;
243 }
244 
245 SettingsSpan::SettingsSpan(const std::vector<SettingsValue>& vec) noexcept : SettingsSpan(vec.data(), vec.size()) {}
246 const SettingsValue* SettingsSpan::begin() const { return data + negated(); }
247 const SettingsValue* SettingsSpan::end() const { return data + size; }
248 bool SettingsSpan::empty() const { return size == 0 || last_negated(); }
249 bool SettingsSpan::last_negated() const { return size > 0 && data[size - 1].isFalse(); }
250 size_t SettingsSpan::negated() const
251 {
252  for (size_t i = size; i > 0; --i) {
253  if (data[i - 1].isFalse()) return i; // Return number of negated values (position of last false value)
254  }
255  return 0;
256 }
257 
258 } // namespace util
if(!SetupNetworking())
@ VOBJ
Definition: univalue.h:21
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 isFalse() const
Definition: univalue.h:78
bool read(const char *raw, size_t len)
bool isObject() const
Definition: univalue.h:83
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: any.h:10
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:185
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:230
bool WriteSettings(const fs::path &path, const std::map< std::string, SettingsValue > &values, std::vector< std::string > &errors)
Write settings file.
Definition: settings.cpp:109
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:128
auto FindKey(Map &&map, Key &&key) -> decltype(&map.at(key))
Map lookup helper.
Definition: settings.h:106
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: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:250
const SettingsValue * end() const
Pointer to end of values.
Definition: settings.cpp:247
bool empty() const
True if there are any non-negated values.
Definition: settings.cpp:248
SettingsSpan()=default
const SettingsValue * data
Definition: settings.h:100
bool last_negated() const
True if the last value is negated.
Definition: settings.cpp:249
const SettingsValue * begin() const
Pointer to first non-negated value.
Definition: settings.cpp:246
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162