Bitcoin ABC  0.27.2
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 <compat.h>
18 #include <compat/assumptions.h>
19 #include <fs.h>
20 #include <logging.h>
21 #include <sync.h>
22 #include <tinyformat.h>
23 #include <util/settings.h>
24 #include <util/time.h>
25 
26 #include <any>
27 #include <cstdint>
28 #include <exception>
29 #include <map>
30 #include <optional>
31 #include <set>
32 #include <string>
33 #include <utility>
34 #include <vector>
35 
36 // Application startup time (used for uptime calculation)
37 int64_t GetStartupTime();
38 
39 extern const char *const BITCOIN_CONF_FILENAME;
40 extern const char *const BITCOIN_SETTINGS_FILENAME;
41 
42 void SetupEnvironment();
43 bool SetupNetworking();
44 
45 template <typename... Args> bool error(const char *fmt, const Args &...args) {
46  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
47  return false;
48 }
49 
50 void PrintExceptionContinue(const std::exception *pex, const char *pszThread);
51 bool FileCommit(FILE *file);
52 bool TruncateFile(FILE *file, unsigned int length);
53 int RaiseFileDescriptorLimit(int nMinFD);
54 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
55 [[nodiscard]] bool RenameOver(fs::path src, fs::path dest);
56 bool LockDirectory(const fs::path &directory, const std::string lockfile_name,
57  bool probe_only = false);
58 void UnlockDirectory(const fs::path &directory,
59  const std::string &lockfile_name);
60 bool DirIsWritable(const fs::path &directory);
61 bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes = 0);
62 
70 std::streampos
71 GetFileSize(const char *path,
72  std::streamsize max = std::numeric_limits<std::streamsize>::max());
73 
79 
80 bool TryCreateDirectories(const fs::path &p);
82 // Return true if -datadir option points to a valid directory or is not
83 // specified.
84 bool CheckDataDirOption();
85 fs::path GetConfigFile(const std::string &confPath);
86 #ifdef WIN32
87 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
88 #endif
89 #ifndef WIN32
90 std::string ShellEscape(const std::string &arg);
91 #endif
92 #if defined(HAVE_SYSTEM)
93 void runCommand(const std::string &strCommand);
94 #endif
95 
96 [[nodiscard]] bool ParseKeyValue(std::string &key, std::string &val);
97 
106 fs::path AbsPathForConfigVal(const fs::path &path, bool net_specific = true);
107 
108 inline bool IsSwitchChar(char c) {
109 #ifdef WIN32
110  return c == '-' || c == '/';
111 #else
112  return c == '-';
113 #endif
114 }
115 
116 enum class OptionsCategory {
117  OPTIONS,
118  CONNECTION,
119  WALLET,
121  ZMQ,
122  DEBUG_TEST,
123  CHAINPARAMS,
124  NODE_RELAY,
126  RPC,
127  GUI,
128  COMMANDS,
130  AVALANCHE,
131 
132  // Always the last option to avoid printing these in the help
133  HIDDEN,
134 
135  // Hide Chronik for now
136  CHRONIK,
137 };
138 
139 struct SectionInfo {
140  std::string m_name;
141  std::string m_file;
142  int m_line;
143 };
144 
145 class ArgsManager {
146 public:
147  enum Flags {
148  // Boolean options can accept negation syntax -noOPTION or -noOPTION=1
149  ALLOW_BOOL = 0x01,
150  ALLOW_INT = 0x02,
151  ALLOW_STRING = 0x04,
153  DEBUG_ONLY = 0x100,
154  /* Some options would cause cross-contamination if values for
155  * mainnet were used while running on regtest/testnet (or vice-versa).
156  * Setting them as NETWORK_ONLY ensures that sharing a config file
157  * between mainnet and regtest/testnet won't cause problems due to these
158  * parameters by accident. */
159  NETWORK_ONLY = 0x200,
160  // This argument's value is sensitive (such as a password).
161  SENSITIVE = 0x400,
162  };
163 
164 protected:
165  struct Arg {
166  std::string m_help_param;
167  std::string m_help_text;
168  unsigned int m_flags;
169  };
170 
173  std::string m_network GUARDED_BY(cs_args);
174  std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
175  std::map<OptionsCategory, std::map<std::string, Arg>>
176  m_available_args GUARDED_BY(cs_args);
177  std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
178  mutable fs::path m_cached_blocks_path GUARDED_BY(cs_args);
179  mutable fs::path m_cached_datadir_path GUARDED_BY(cs_args);
180  mutable fs::path m_cached_network_datadir_path GUARDED_BY(cs_args);
181 
182  [[nodiscard]] bool ReadConfigStream(std::istream &stream,
183  const std::string &filepath,
184  std::string &error,
185  bool ignore_invalid_keys = false);
186 
192  bool UseDefaultSection(const std::string &arg) const
194 
202  util::SettingsValue GetSetting(const std::string &arg) const;
203 
207  std::vector<util::SettingsValue>
208  GetSettingsList(const std::string &arg) const;
209 
210 public:
211  ArgsManager();
212  ~ArgsManager();
213 
217  void SelectConfigNetwork(const std::string &network);
218 
219  [[nodiscard]] bool ParseParameters(int argc, const char *const argv[],
220  std::string &error);
221  [[nodiscard]] bool ReadConfigFiles(std::string &error,
222  bool ignore_invalid_keys = false);
223 
229  const std::set<std::string> GetUnsuitableSectionOnlyArgs() const;
230 
234  const std::list<SectionInfo> GetUnrecognizedSections() const;
235 
241  const fs::path &GetBlocksDirPath() const;
242 
250  const fs::path &GetDataDirBase() const { return GetDataDir(false); }
251 
259  const fs::path &GetDataDirNet() const { return GetDataDir(true); }
260 
264  void ClearPathCache();
265 
272  std::vector<std::string> GetArgs(const std::string &strArg) const;
273 
280  bool IsArgSet(const std::string &strArg) const;
281 
289  bool IsArgNegated(const std::string &strArg) const;
290 
298  std::string GetArg(const std::string &strArg,
299  const std::string &strDefault) const;
300 
308  int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const;
309 
317  bool GetBoolArg(const std::string &strArg, bool fDefault) const;
318 
326  bool SoftSetArg(const std::string &strArg, const std::string &strValue);
327 
335  bool SoftSetBoolArg(const std::string &strArg, bool fValue);
336 
337  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
338  // been set. Also called directly in testing.
339  void ForceSetArg(const std::string &strArg, const std::string &strValue);
340 
341  // Forces a multi arg setting, used only in testing
342  void ForceSetMultiArg(const std::string &strArg,
343  const std::vector<std::string> &values);
344 
351  std::string GetChainName() const;
352 
356  void AddArg(const std::string &name, const std::string &help,
357  unsigned int flags, const OptionsCategory &cat);
358 
362  void ClearForcedArg(const std::string &strArg);
363 
367  void AddHiddenArgs(const std::vector<std::string> &args);
368 
372  void ClearArgs() {
373  LOCK(cs_args);
374  m_available_args.clear();
375  m_network_only_args.clear();
376  }
377 
381  std::string GetHelpMessage() const;
382 
387  std::optional<unsigned int> GetArgFlags(const std::string &name) const;
388 
394  bool InitSettings(std::string &error);
395 
400  bool GetSettingsPath(fs::path *filepath = nullptr, bool temp = false) const;
401 
405  bool ReadSettingsFile(std::vector<std::string> *errors = nullptr);
406 
410  bool WriteSettingsFile(std::vector<std::string> *errors = nullptr) const;
411 
415  template <typename Fn> void LockSettings(Fn &&fn) {
416  LOCK(cs_args);
417  fn(m_settings);
418  }
419 
424  void LogArgs() const;
425 
426 private:
435  const fs::path &GetDataDir(bool net_specific) const;
436 
437  // Helper function for LogArgs().
438  void
439  logArgsPrefix(const std::string &prefix, const std::string &section,
440  const std::map<std::string, std::vector<util::SettingsValue>>
441  &args) const;
442 };
443 
444 extern ArgsManager gArgs;
445 
449 bool HelpRequested(const ArgsManager &args);
450 
452 void SetupHelpOptions(ArgsManager &args);
453 
460 std::string HelpMessageGroup(const std::string &message);
461 
469 std::string HelpMessageOpt(const std::string &option,
470  const std::string &message);
471 
477 int GetNumCores();
478 
479 std::string CopyrightHolders(const std::string &strPrefix);
480 
486 void ScheduleBatchPriority();
487 
488 namespace util {
489 
491 template <typename Tdst, typename Tsrc>
492 inline void insert(Tdst &dst, const Tsrc &src) {
493  dst.insert(dst.begin(), src.begin(), src.end());
494 }
495 template <typename TsetT, typename Tsrc>
496 inline void insert(std::set<TsetT> &dst, const Tsrc &src) {
497  dst.insert(src.begin(), src.end());
498 }
499 
505 template <typename T> T *AnyPtr(const std::any &any) noexcept {
506  T *const *ptr = std::any_cast<T *>(&any);
507  return ptr ? *ptr : nullptr;
508 }
509 
510 #ifdef WIN32
511 class WinCmdLineArgs {
512 public:
513  WinCmdLineArgs();
514  ~WinCmdLineArgs();
515  std::pair<int, char **> get();
516 
517 private:
518  int argc;
519  char **argv;
520  std::vector<std::string> args;
521 };
522 #endif
523 
524 } // namespace util
525 
526 #endif // BITCOIN_UTIL_SYSTEM_H
int flags
Definition: bitcoin-tx.cpp:538
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:261
const fs::path & GetBlocksDirPath() const
Get blocks directory path.
Definition: system.cpp:403
bool IsArgNegated(const std::string &strArg) const
Return true if the argument was originally passed as a negated option, i.e.
Definition: system.cpp:578
@ NETWORK_ONLY
Definition: system.h:159
@ ALLOW_ANY
Definition: system.h:152
@ DEBUG_ONLY
Definition: system.h:153
@ ALLOW_INT
Definition: system.h:150
@ ALLOW_BOOL
Definition: system.h:149
@ ALLOW_STRING
Definition: system.h:151
@ SENSITIVE
Definition: system.h:161
bool ReadSettingsFile(std::vector< std::string > *errors=nullptr)
Read settings file.
Definition: system.cpp:529
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: system.cpp:626
void logArgsPrefix(const std::string &prefix, const std::string &section, const std::map< std::string, std::vector< util::SettingsValue >> &args) const
Definition: system.cpp:1093
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:486
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:554
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:329
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:472
std::optional< unsigned int > GetArgFlags(const std::string &name) const
Return Flags for known arg.
Definition: system.cpp:392
const fs::path & GetDataDirBase() const
Get data directory path.
Definition: system.h:250
std::string m_network GUARDED_BY(cs_args)
~ArgsManager()
Definition: system.cpp:259
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:415
bool SoftSetArg(const std::string &strArg, const std::string &strValue)
Set an argument if it doesn't already have a value.
Definition: system.cpp:608
void SelectConfigNetwork(const std::string &network)
Select the network in use.
Definition: system.cpp:300
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:682
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:637
void ClearPathCache()
Clear cached directory paths.
Definition: system.cpp:464
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:482
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: system.h:259
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:591
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:431
void ClearArgs()
Clear available arguments.
Definition: system.h:372
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:677
std::vector< util::SettingsValue > GetSettingsList(const std::string &arg) const
Get list of setting values.
Definition: system.cpp:1087
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:505
void LogArgs() const
Log the config file options and the command line arguments, useful for troubleshooting.
Definition: system.cpp:1110
RecursiveMutex cs_args
Definition: system.h:171
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:1074
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
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:1079
bool ReadConfigStream(std::istream &stream, const std::string &filepath, std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:907
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:618
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:942
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:601
void AddHiddenArgs(const std::vector< std::string > &args)
Add many hidden arguments.
Definition: system.cpp:671
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
Definition: system.cpp:649
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:285
std::string GetChainName() const
Looks for -regtest, -testnet and returns the appropriate BIP70 chain name.
Definition: system.cpp:1045
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:505
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: system.h:492
const char * prefix
Definition: rest.cpp:821
const char * name
Definition: rest.cpp:49
static RPCHelpMan help()
Definition: server.cpp:177
std::string m_help_param
Definition: system.h:166
unsigned int m_flags
Definition: system.h:168
std::string m_help_text
Definition: system.h:167
int m_line
Definition: system.h:142
std::string m_file
Definition: system.h:141
std::string m_name
Definition: system.h:140
Stored settings.
Definition: settings.h:31
#define LOCK(cs)
Definition: sync.h:243
bool error(const char *fmt, const Args &...args)
Definition: system.h:45
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:761
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:766
fs::path GetDefaultDataDir()
Definition: system.cpp:812
int64_t GetStartupTime()
Server/client environment: argument handling, config file parsing, thread wrappers,...
Definition: system.cpp:1379
OptionsCategory
Definition: system.h:116
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:73
bool ParseKeyValue(std::string &key, std::string &val)
Definition: system.cpp:305
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1373
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:115
bool CheckDataDirOption()
Definition: system.cpp:837
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:126
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:1122
bool SetupNetworking()
Definition: system.cpp:1356
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1391
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1200
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:148
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:121
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
Definition: system.cpp:1137
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:1226
ArgsManager gArgs
Definition: system.cpp:75
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:1383
void SetupEnvironment()
Definition: system.cpp:1318
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: system.cpp:87
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:843
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:806
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:776
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:72
bool IsSwitchChar(char c)
Definition: system.h:108
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1187
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes=0)
Definition: system.cpp:140
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1369
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:780
bool FileCommit(FILE *file)
Definition: system.cpp:1151
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1291
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56