Bitcoin ABC  0.26.3
P2P Digital Currency
system.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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 
10 #ifndef BITCOIN_UTIL_SYSTEM_H
11 #define BITCOIN_UTIL_SYSTEM_H
12 
13 #if defined(HAVE_CONFIG_H)
14 #include <config/bitcoin-config.h>
15 #endif
16 
17 #include <attributes.h>
18 #include <compat.h>
19 #include <compat/assumptions.h>
20 #include <fs.h>
21 #include <logging.h>
22 #include <sync.h>
23 #include <tinyformat.h>
24 #include <util/settings.h>
25 #include <util/time.h>
26 
27 #include <any>
28 #include <cstdint>
29 #include <exception>
30 #include <map>
31 #include <optional>
32 #include <set>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 // Application startup time (used for uptime calculation)
38 int64_t GetStartupTime();
39 
40 extern const char *const BITCOIN_CONF_FILENAME;
41 extern const char *const BITCOIN_SETTINGS_FILENAME;
42 
43 void SetupEnvironment();
44 bool SetupNetworking();
45 
46 template <typename... Args> bool error(const char *fmt, const Args &...args) {
47  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
48  return false;
49 }
50 
51 void PrintExceptionContinue(const std::exception *pex, const char *pszThread);
52 bool FileCommit(FILE *file);
53 bool TruncateFile(FILE *file, unsigned int length);
54 int RaiseFileDescriptorLimit(int nMinFD);
55 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
56 [[nodiscard]] bool RenameOver(fs::path src, fs::path dest);
57 bool LockDirectory(const fs::path &directory, const std::string lockfile_name,
58  bool probe_only = false);
59 void UnlockDirectory(const fs::path &directory,
60  const std::string &lockfile_name);
61 bool DirIsWritable(const fs::path &directory);
62 bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes = 0);
63 
71 std::streampos
72 GetFileSize(const char *path,
73  std::streamsize max = std::numeric_limits<std::streamsize>::max());
74 
80 
81 bool TryCreateDirectories(const fs::path &p);
83 // Return true if -datadir option points to a valid directory or is not
84 // specified.
85 bool CheckDataDirOption();
86 fs::path GetConfigFile(const std::string &confPath);
87 #ifdef WIN32
88 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
89 #endif
90 #ifndef WIN32
91 std::string ShellEscape(const std::string &arg);
92 #endif
93 #if defined(HAVE_SYSTEM)
94 void runCommand(const std::string &strCommand);
95 #endif
96 
97 [[nodiscard]] bool ParseKeyValue(std::string &key, std::string &val);
98 
107 fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific = true);
108 
109 inline bool IsSwitchChar(char c) {
110 #ifdef WIN32
111  return c == '-' || c == '/';
112 #else
113  return c == '-';
114 #endif
115 }
116 
117 enum class OptionsCategory {
118  OPTIONS,
119  CONNECTION,
120  WALLET,
122  ZMQ,
123  DEBUG_TEST,
124  CHAINPARAMS,
125  NODE_RELAY,
127  RPC,
128  GUI,
129  COMMANDS,
131  AVALANCHE,
132 
133  // Always the last option to avoid printing these in the help
134  HIDDEN,
135 
136  // Hide Chronik for now
137  CHRONIK,
138 };
139 
140 struct SectionInfo {
141  std::string m_name;
142  std::string m_file;
143  int m_line;
144 };
145 
146 class ArgsManager {
147 public:
148  enum Flags {
149  // Boolean options can accept negation syntax -noOPTION or -noOPTION=1
150  ALLOW_BOOL = 0x01,
151  ALLOW_INT = 0x02,
152  ALLOW_STRING = 0x04,
154  DEBUG_ONLY = 0x100,
155  /* Some options would cause cross-contamination if values for
156  * mainnet were used while running on regtest/testnet (or vice-versa).
157  * Setting them as NETWORK_ONLY ensures that sharing a config file
158  * between mainnet and regtest/testnet won't cause problems due to these
159  * parameters by accident. */
160  NETWORK_ONLY = 0x200,
161  // This argument's value is sensitive (such as a password).
162  SENSITIVE = 0x400,
163  };
164 
165 protected:
166  struct Arg {
167  std::string m_help_param;
168  std::string m_help_text;
169  unsigned int m_flags;
170  };
171 
174  std::string m_network GUARDED_BY(cs_args);
175  std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
176  std::map<OptionsCategory, std::map<std::string, Arg>>
177  m_available_args GUARDED_BY(cs_args);
178  std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
179  mutable fs::path m_cached_blocks_path GUARDED_BY(cs_args);
180  mutable fs::path m_cached_datadir_path GUARDED_BY(cs_args);
181  mutable fs::path m_cached_network_datadir_path GUARDED_BY(cs_args);
182 
183  [[nodiscard]] bool ReadConfigStream(std::istream &stream,
184  const std::string &filepath,
185  std::string &error,
186  bool ignore_invalid_keys = false);
187 
193  bool UseDefaultSection(const std::string &arg) const
195 
203  util::SettingsValue GetSetting(const std::string &arg) const;
204 
208  std::vector<util::SettingsValue>
209  GetSettingsList(const std::string &arg) const;
210 
211 public:
212  ArgsManager();
213  ~ArgsManager();
214 
218  void SelectConfigNetwork(const std::string &network);
219 
220  [[nodiscard]] bool ParseParameters(int argc, const char *const argv[],
221  std::string &error);
222  [[nodiscard]] bool ReadConfigFiles(std::string &error,
223  bool ignore_invalid_keys = false);
224 
230  const std::set<std::string> GetUnsuitableSectionOnlyArgs() const;
231 
235  const std::list<SectionInfo> GetUnrecognizedSections() const;
236 
242  const fs::path &GetBlocksDirPath() const;
243 
251  const fs::path &GetDataDirBase() const { return GetDataDir(false); }
252 
260  const fs::path &GetDataDirNet() const { return GetDataDir(true); }
261 
265  void ClearPathCache();
266 
273  std::vector<std::string> GetArgs(const std::string &strArg) const;
274 
281  bool IsArgSet(const std::string &strArg) const;
282 
290  bool IsArgNegated(const std::string &strArg) const;
291 
299  std::string GetArg(const std::string &strArg,
300  const std::string &strDefault) const;
301 
309  int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const;
310 
318  bool GetBoolArg(const std::string &strArg, bool fDefault) const;
319 
327  bool SoftSetArg(const std::string &strArg, const std::string &strValue);
328 
336  bool SoftSetBoolArg(const std::string &strArg, bool fValue);
337 
338  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
339  // been set. Also called directly in testing.
340  void ForceSetArg(const std::string &strArg, const std::string &strValue);
341 
342  // Forces a multi arg setting, used only in testing
343  void ForceSetMultiArg(const std::string &strArg,
344  const std::vector<std::string> &values);
345 
352  std::string GetChainName() const;
353 
357  void AddArg(const std::string &name, const std::string &help,
358  unsigned int flags, const OptionsCategory &cat);
359 
363  void ClearForcedArg(const std::string &strArg);
364 
368  void AddHiddenArgs(const std::vector<std::string> &args);
369 
373  void ClearArgs() {
374  LOCK(cs_args);
375  m_available_args.clear();
376  m_network_only_args.clear();
377  }
378 
382  std::string GetHelpMessage() const;
383 
388  std::optional<unsigned int> GetArgFlags(const std::string &name) const;
389 
395  bool InitSettings(std::string &error);
396 
401  bool GetSettingsPath(fs::path *filepath = nullptr, bool temp = false) const;
402 
406  bool ReadSettingsFile(std::vector<std::string> *errors = nullptr);
407 
411  bool WriteSettingsFile(std::vector<std::string> *errors = nullptr) const;
412 
416  template <typename Fn> void LockSettings(Fn &&fn) {
417  LOCK(cs_args);
418  fn(m_settings);
419  }
420 
425  void LogArgs() const;
426 
427 private:
436  const fs::path &GetDataDir(bool net_specific) const;
437 
438  // Helper function for LogArgs().
439  void
440  logArgsPrefix(const std::string &prefix, const std::string &section,
441  const std::map<std::string, std::vector<util::SettingsValue>>
442  &args) const;
443 };
444 
445 extern ArgsManager gArgs;
446 
450 bool HelpRequested(const ArgsManager &args);
451 
453 void SetupHelpOptions(ArgsManager &args);
454 
461 std::string HelpMessageGroup(const std::string &message);
462 
470 std::string HelpMessageOpt(const std::string &option,
471  const std::string &message);
472 
478 int GetNumCores();
479 
480 std::string CopyrightHolders(const std::string &strPrefix);
481 
487 void ScheduleBatchPriority();
488 
489 namespace util {
490 
492 template <typename Tdst, typename Tsrc>
493 inline void insert(Tdst &dst, const Tsrc &src) {
494  dst.insert(dst.begin(), src.begin(), src.end());
495 }
496 template <typename TsetT, typename Tsrc>
497 inline void insert(std::set<TsetT> &dst, const Tsrc &src) {
498  dst.insert(src.begin(), src.end());
499 }
500 
506 template <typename T> T *AnyPtr(const std::any &any) noexcept {
507  T *const *ptr = std::any_cast<T *>(&any);
508  return ptr ? *ptr : nullptr;
509 }
510 
511 #ifdef WIN32
512 class WinCmdLineArgs {
513 public:
514  WinCmdLineArgs();
515  ~WinCmdLineArgs();
516  std::pair<int, char **> get();
517 
518 private:
519  int argc;
520  char **argv;
521  std::vector<std::string> args;
522 };
523 #endif
524 
525 } // namespace util
526 
527 #endif // BITCOIN_UTIL_SYSTEM_H
int flags
Definition: bitcoin-tx.cpp:534
const std::set< std::string > GetUnsuitableSectionOnlyArgs() const
Log warnings for options in m_section_only_args when they are specified in the default section but no...
Definition: system.cpp:263
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:405
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:580
@ NETWORK_ONLY
Definition: system.h:160
@ ALLOW_ANY
Definition: system.h:153
@ DEBUG_ONLY
Definition: system.h:154
@ ALLOW_INT
Definition: system.h:151
@ ALLOW_BOOL
Definition: system.h:150
@ ALLOW_STRING
Definition: system.h:152
@ SENSITIVE
Definition: system.h:162
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: system.cpp:531
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:628
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< util::SettingsValue >> &args) const
Definition: system.cpp:1095
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:488
fs::path m_cached_datadir_path GUARDED_BY(cs_args)
bool WriteSettingsFile(std::vector< std::string > *errors=nullptr) const
Write settings file.
Definition: system.cpp:556
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:331
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:474
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: system.cpp:394
const fs::path & GetDataDirBase() const
Get data directory path.
Definition: system.h:251
std::string m_network GUARDED_BY(cs_args)
~ArgsManager()
Definition: system.cpp:261
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:416
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: system.cpp:610
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: system.cpp:302
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:684
void ForceSetMultiArg(const std::string &strArg, const std::vector< std::string > &values)
This function is only used for testing purpose so so we should not worry about element uniqueness and...
Definition: system.cpp:639
void ClearPathCache()
Clear cached directory paths.
Definition: system.cpp:466
fs::path m_cached_blocks_path GUARDED_BY(cs_args)
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:484
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:260
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:593
std::map< OptionsCategory, std::map< std::string, Arg > > m_available_args GUARDED_BY(cs_args)
const fs::path & GetDataDir(bool net_specific) const
Get data directory path.
Definition: system.cpp:433
void ClearArgs()
Clear available arguments.
Definition: system.h:373
util::Settings m_settings GUARDED_BY(cs_args)
void ClearForcedArg(const std::string &strArg)
Remove a forced arg setting, used only in testing.
Definition: system.cpp:679
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:1089
bool GetSettingsPath(fs::path *filepath=nullptr, bool temp=false) const
Get settings file path, or return false if read-write settings were disabled with -nosettings.
Definition: system.cpp:507
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1112
RecursiveMutex cs_args
Definition: system.h:172
fs::path m_cached_network_datadir_path GUARDED_BY(cs_args)
bool UseDefaultSection(const std::string &arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args)
Returns true if settings values from the default section should be used, depending on the current net...
Definition: system.cpp:1076
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:584
std::set< std::string > m_network_only_args GUARDED_BY(cs_args)
util::SettingsValue GetSetting(const std::string &arg) const
Get setting value.
Definition: system.cpp:1081
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:909
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:620
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:944
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:603
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:673
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:651
std::list< SectionInfo > m_config_sections GUARDED_BY(cs_args)
const std::list< SectionInfo > GetUnrecognizedSections() const
Log warnings for unrecognized section names in the config file.
Definition: system.cpp:287
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1047
Path class wrapper to prepare application code for transition from boost::filesystem library to std::...
Definition: fs.h:33
#define LogPrintf(...)
Definition: logging.h:204
void format(std::ostream &out, const char *fmt, const Args &...args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1111
T * AnyPtr(const std::any &any) noexcept
Helper function to access the contained object of a std::any instance.
Definition: system.h:506
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:493
const char * prefix
Definition: rest.cpp:823
const char * name
Definition: rest.cpp:50
static RPCHelpMan help()
Definition: server.cpp:177
std::string m_help_param
Definition: system.h:167
unsigned int m_flags
Definition: system.h:169
std::string m_help_text
Definition: system.h:168
int m_line
Definition: system.h:143
std::string m_file
Definition: system.h:142
std::string m_name
Definition: system.h:141
Stored settings.
Definition: settings.h:31
#define LOCK(cs)
Definition: sync.h:243
bool error(const char *fmt, const Args &...args)
Definition: system.h:46
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:763
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:768
fs::path GetDefaultDataDir()
Definition: system.cpp:814
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers,...
Definition: system.cpp:1381
OptionsCategory
Definition: system.h:117
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:75
bool ParseKeyValue(std::string &key, std::string &val)
Definition: system.cpp:307
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1375
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:117
bool CheckDataDirOption()
Definition: system.cpp:839
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:128
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1124
bool SetupNetworking()
Definition: system.cpp:1358
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1393
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1202
std::streampos GetFileSize(const char *path, std::streamsize max=std::numeric_limits< std::streamsize >::max())
Get the size of a file by scanning it.
Definition: system.cpp:150
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:123
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
Definition: system.cpp:1139
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
This function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: system.cpp:1228
ArgsManager gArgs
Definition: system.cpp:77
fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific=true)
Most paths passed as configuration arguments are treated as relative to the datadir if they are not a...
Definition: system.cpp:1385
void SetupEnvironment()
Definition: system.cpp:1320
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: system.cpp:89
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:845
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:808
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:778
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:74
bool IsSwitchChar(char c)
Definition: system.h:109
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1189
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes=0)
Definition: system.cpp:142
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1371
std::string HelpMessageOpt(const std::string &option, const std::string &message)
Format a string to be used as option description in help messages.
Definition: system.cpp:782
bool FileCommit(FILE *file)
Definition: system.cpp:1153
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1293
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56