Bitcoin Core  0.20.99
P2P Digital Currency
system.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <optional.h>
23 #include <sync.h>
24 #include <tinyformat.h>
25 #include <util/memory.h>
26 #include <util/settings.h>
27 #include <util/threadnames.h>
28 #include <util/time.h>
29 
30 #include <exception>
31 #include <map>
32 #include <set>
33 #include <stdint.h>
34 #include <string>
35 #include <utility>
36 #include <vector>
37 
38 #include <boost/thread/condition_variable.hpp> // for boost::thread_interrupted
39 
40 class UniValue;
41 
42 // Application startup time (used for uptime calculation)
43 int64_t GetStartupTime();
44 
45 extern const char * const BITCOIN_CONF_FILENAME;
46 extern const char * const BITCOIN_SETTINGS_FILENAME;
47 
48 void SetupEnvironment();
49 bool SetupNetworking();
50 
51 template<typename... Args>
52 bool error(const char* fmt, const Args&... args)
53 {
54  LogPrintf("ERROR: %s\n", tfm::format(fmt, args...));
55  return false;
56 }
57 
58 void PrintExceptionContinue(const std::exception *pex, const char* pszThread);
59 bool FileCommit(FILE *file);
60 bool TruncateFile(FILE *file, unsigned int length);
61 int RaiseFileDescriptorLimit(int nMinFD);
62 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length);
63 bool RenameOver(fs::path src, fs::path dest);
64 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only=false);
65 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name);
66 bool DirIsWritable(const fs::path& directory);
67 bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0);
68 
75 std::streampos GetFileSize(const char* path, std::streamsize max = std::numeric_limits<std::streamsize>::max());
76 
81 
82 bool TryCreateDirectories(const fs::path& p);
83 fs::path GetDefaultDataDir();
84 // The blocks directory is always net specific.
85 const fs::path &GetBlocksDir();
86 const fs::path &GetDataDir(bool fNetSpecific = true);
87 // Return true if -datadir option points to a valid directory or is not specified.
88 bool CheckDataDirOption();
90 void ClearDatadirCache();
91 fs::path GetConfigFile(const std::string& confPath);
92 #ifdef WIN32
93 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true);
94 #endif
95 #ifndef WIN32
96 std::string ShellEscape(const std::string& arg);
97 #endif
98 #if HAVE_SYSTEM
99 void runCommand(const std::string& strCommand);
100 #endif
101 #ifdef HAVE_BOOST_PROCESS
102 
109 UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in="");
110 #endif // HAVE_BOOST_PROCESS
111 
120 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific = true);
121 
122 inline bool IsSwitchChar(char c)
123 {
124 #ifdef WIN32
125  return c == '-' || c == '/';
126 #else
127  return c == '-';
128 #endif
129 }
130 
131 enum class OptionsCategory {
132  OPTIONS,
133  CONNECTION,
134  WALLET,
136  ZMQ,
137  DEBUG_TEST,
138  CHAINPARAMS,
139  NODE_RELAY,
141  RPC,
142  GUI,
143  COMMANDS,
145 
146  HIDDEN // Always the last option to avoid printing these in the help
147 };
148 
150 {
151  std::string m_name;
152  std::string m_file;
153  int m_line;
154 };
155 
157 {
158 public:
159  enum Flags {
160  // Boolean options can accept negation syntax -noOPTION or -noOPTION=1
161  ALLOW_BOOL = 0x01,
162  ALLOW_INT = 0x02,
163  ALLOW_STRING = 0x04,
164  ALLOW_ANY = ALLOW_BOOL | ALLOW_INT | ALLOW_STRING,
165  DEBUG_ONLY = 0x100,
166  /* Some options would cause cross-contamination if values for
167  * mainnet were used while running on regtest/testnet (or vice-versa).
168  * Setting them as NETWORK_ONLY ensures that sharing a config file
169  * between mainnet and regtest/testnet won't cause problems due to these
170  * parameters by accident. */
171  NETWORK_ONLY = 0x200,
172  // This argument's value is sensitive (such as a password).
173  SENSITIVE = 0x400,
174  };
175 
176 protected:
177  struct Arg
178  {
179  std::string m_help_param;
180  std::string m_help_text;
181  unsigned int m_flags;
182  };
183 
185  util::Settings m_settings GUARDED_BY(cs_args);
186  std::string m_network GUARDED_BY(cs_args);
187  std::set<std::string> m_network_only_args GUARDED_BY(cs_args);
188  std::map<OptionsCategory, std::map<std::string, Arg>> m_available_args GUARDED_BY(cs_args);
189  std::list<SectionInfo> m_config_sections GUARDED_BY(cs_args);
190 
191  NODISCARD bool ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys = false);
192 
198  bool UseDefaultSection(const std::string& arg) const EXCLUSIVE_LOCKS_REQUIRED(cs_args);
199 
207  util::SettingsValue GetSetting(const std::string& arg) const;
208 
212  std::vector<util::SettingsValue> GetSettingsList(const std::string& arg) const;
213 
214 public:
215  ArgsManager();
216  ~ArgsManager();
217 
221  void SelectConfigNetwork(const std::string& network);
222 
223  NODISCARD bool ParseParameters(int argc, const char* const argv[], std::string& error);
224  NODISCARD bool ReadConfigFiles(std::string& error, bool ignore_invalid_keys = false);
225 
232  const std::set<std::string> GetUnsuitableSectionOnlyArgs() const;
233 
237  const std::list<SectionInfo> GetUnrecognizedSections() const;
238 
245  std::vector<std::string> GetArgs(const std::string& strArg) const;
246 
253  bool IsArgSet(const std::string& strArg) const;
254 
262  bool IsArgNegated(const std::string& strArg) const;
263 
271  std::string GetArg(const std::string& strArg, const std::string& strDefault) const;
272 
280  int64_t GetArg(const std::string& strArg, int64_t nDefault) const;
281 
289  bool GetBoolArg(const std::string& strArg, bool fDefault) const;
290 
298  bool SoftSetArg(const std::string& strArg, const std::string& strValue);
299 
307  bool SoftSetBoolArg(const std::string& strArg, bool fValue);
308 
309  // Forces an arg setting. Called by SoftSetArg() if the arg hasn't already
310  // been set. Also called directly in testing.
311  void ForceSetArg(const std::string& strArg, const std::string& strValue);
312 
317  std::string GetChainName() const;
318 
322  void AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat);
323 
327  void AddHiddenArgs(const std::vector<std::string>& args);
328 
332  void ClearArgs() {
333  LOCK(cs_args);
334  m_available_args.clear();
335  m_network_only_args.clear();
336  }
337 
341  std::string GetHelpMessage() const;
342 
347  Optional<unsigned int> GetArgFlags(const std::string& name) const;
348 
354  bool InitSettings(std::string& error);
355 
360  bool GetSettingsPath(fs::path* filepath = nullptr, bool temp = false) const;
361 
365  bool ReadSettingsFile(std::vector<std::string>* errors = nullptr);
366 
370  bool WriteSettingsFile(std::vector<std::string>* errors = nullptr) const;
371 
375  template <typename Fn>
376  void LockSettings(Fn&& fn)
377  {
378  LOCK(cs_args);
379  fn(m_settings);
380  }
381 
386  void LogArgs() const;
387 
388 private:
389  // Helper function for LogArgs().
390  void logArgsPrefix(
391  const std::string& prefix,
392  const std::string& section,
393  const std::map<std::string, std::vector<util::SettingsValue>>& args) const;
394 };
395 
396 extern ArgsManager gArgs;
397 
401 bool HelpRequested(const ArgsManager& args);
402 
404 void SetupHelpOptions(ArgsManager& args);
405 
412 std::string HelpMessageGroup(const std::string& message);
413 
421 std::string HelpMessageOpt(const std::string& option, const std::string& message);
422 
427 int GetNumCores();
428 
432 template <typename Callable> void TraceThread(const char* name, Callable func)
433 {
434  util::ThreadRename(name);
435  try
436  {
437  LogPrintf("%s thread start\n", name);
438  func();
439  LogPrintf("%s thread exit\n", name);
440  }
441  catch (const boost::thread_interrupted&)
442  {
443  LogPrintf("%s thread interrupt\n", name);
444  throw;
445  }
446  catch (const std::exception& e) {
447  PrintExceptionContinue(&e, name);
448  throw;
449  }
450  catch (...) {
451  PrintExceptionContinue(nullptr, name);
452  throw;
453  }
454 }
455 
456 std::string CopyrightHolders(const std::string& strPrefix);
457 
463 void ScheduleBatchPriority();
464 
465 namespace util {
466 
468 template <typename Tdst, typename Tsrc>
469 inline void insert(Tdst& dst, const Tsrc& src) {
470  dst.insert(dst.begin(), src.begin(), src.end());
471 }
472 template <typename TsetT, typename Tsrc>
473 inline void insert(std::set<TsetT>& dst, const Tsrc& src) {
474  dst.insert(src.begin(), src.end());
475 }
476 
477 #ifdef WIN32
478 class WinCmdLineArgs
479 {
480 public:
481  WinCmdLineArgs();
482  ~WinCmdLineArgs();
483  std::pair<int, char**> get();
484 
485 private:
486  int argc;
487  char** argv;
488  std::vector<std::string> args;
489 };
490 #endif
491 
492 } // namespace util
493 
494 #endif // BITCOIN_UTIL_SYSTEM_H
Stored settings.
Definition: settings.h:31
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:1277
bool TruncateFile(FILE *file, unsigned int length)
Definition: system.cpp:1048
Definition: httprpc.h:8
void SetupEnvironment()
Definition: system.cpp:1205
unsigned int m_flags
Definition: system.h:181
fs::path GetConfigFile(const std::string &confPath)
Definition: system.cpp:743
const char * prefix
Definition: rest.cpp:670
SettingsValue GetSetting(const Settings &settings, const std::string &section, const std::string &name, bool ignore_default_section_config, bool get_chain_name)
Get settings value from combined sources: forced settings, command line arguments, runtime read-write settings, and the read-only config file.
Definition: settings.cpp:114
void ThreadRename(std::string &&)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name...
Definition: threadnames.cpp:57
int m_line
Definition: system.h:153
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
Definition: system.cpp:1285
RecursiveMutex cs_args
Definition: system.h:184
bool RenameOver(fs::path src, fs::path dest)
Definition: system.cpp:985
const fs::path & GetBlocksDir()
Definition: system.cpp:673
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
Definition: system.cpp:598
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:144
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:1083
std::string m_name
Definition: system.h:151
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
Definition: system.cpp:635
bool DirIsWritable(const fs::path &directory)
Definition: system.cpp:123
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: system.cpp:1060
const fs::path & GetDataDir(bool fNetSpecific=true)
Definition: system.cpp:698
int64_t GetStartupTime()
Definition: system.cpp:1272
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:167
const char *const BITCOIN_CONF_FILENAME
Definition: system.cpp:73
bool FileCommit(FILE *file)
Definition: system.cpp:1015
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes=0)
Definition: system.cpp:136
#define NODISCARD
Definition: attributes.h:18
#define LOCK(cs)
Definition: sync.h:230
const char * name
Definition: rest.cpp:41
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:1062
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:593
bool CheckDataDirOption()
Definition: system.cpp:728
std::string m_file
Definition: system.h:152
void ClearArgs()
Clear available arguments.
Definition: system.h:332
std::string m_help_text
Definition: system.h:180
void TraceThread(const char *name, Callable func)
Definition: system.h:432
std::string HelpMessageGroup(const std::string &message)
Format a string to be used as group of options in help messages.
Definition: system.cpp:608
int flags
Definition: bitcoin-tx.cpp:506
const char *const BITCOIN_SETTINGS_FILENAME
Definition: system.cpp:74
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
fs::path GetDefaultDataDir()
Definition: system.cpp:642
void ClearDatadirCache()
Tests only.
Definition: system.cpp:734
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: system.cpp:111
#define GUARDED_BY(x)
Definition: threadsafety.h:38
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by Boost&#39;s create_directories if the requested directory exists...
Definition: system.cpp:1001
bool IsSwitchChar(char c)
Definition: system.h:122
OptionsCategory
Definition: system.h:131
boost::optional< T > Optional
Substitute for C++17 std::optional.
Definition: optional.h:14
std::string CopyrightHolders(const std::string &strPrefix)
Definition: system.cpp:1259
void LockSettings(Fn &&fn)
Access settings with lock held.
Definition: system.h:376
std::string m_help_param
Definition: system.h:179
void insert(std::set< TsetT > &dst, const Tsrc &src)
Definition: system.h:473
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:612
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only=false)
Definition: system.cpp:87
static RPCHelpMan help()
Definition: server.cpp:133
ArgsManager gArgs
Definition: system.cpp:76
bool error(const char *fmt, const Args &... args)
Definition: system.h:52
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: system.cpp:117
std::string ShellEscape(const std::string &arg)
Definition: system.cpp:1146
int GetNumCores()
Return the number of cores available on the current system.
Definition: system.cpp:1254
bool SetupNetworking()
Definition: system.cpp:1242
UniValue RunCommandParseJSON(const std::string &str_command, const std::string &str_std_in="")
Execute a command which returns JSON, and parse the result.
Definition: system.cpp:1169