Bitcoin Core  24.99.0
P2P Digital Currency
bitcoind.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2021 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 
6 #if defined(HAVE_CONFIG_H)
8 #endif
9 
10 #include <chainparams.h>
11 #include <clientversion.h>
12 #include <compat/compat.h>
13 #include <init.h>
14 #include <interfaces/chain.h>
15 #include <interfaces/init.h>
16 #include <node/context.h>
17 #include <node/interface_ui.h>
18 #include <noui.h>
19 #include <shutdown.h>
20 #include <util/check.h>
21 #include <util/strencodings.h>
22 #include <util/syscall_sandbox.h>
23 #include <util/syserror.h>
24 #include <util/system.h>
25 #include <util/threadnames.h>
26 #include <util/tokenpipe.h>
27 #include <util/translation.h>
28 #include <util/url.h>
29 
30 #include <any>
31 #include <functional>
32 #include <optional>
33 
34 using node::NodeContext;
35 
36 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
38 
39 #if HAVE_DECL_FORK
40 
51 int fork_daemon(bool nochdir, bool noclose, TokenPipeEnd& endpoint)
52 {
53  // communication pipe with child process
54  std::optional<TokenPipe> umbilical = TokenPipe::Make();
55  if (!umbilical) {
56  return -1; // pipe or pipe2 failed.
57  }
58 
59  int pid = fork();
60  if (pid < 0) {
61  return -1; // fork failed.
62  }
63  if (pid != 0) {
64  // Parent process gets read end, closes write end.
65  endpoint = umbilical->TakeReadEnd();
66  umbilical->TakeWriteEnd().Close();
67 
68  int status = endpoint.TokenRead();
69  if (status != 0) { // Something went wrong while setting up child process.
70  endpoint.Close();
71  return -1;
72  }
73 
74  return pid;
75  }
76  // Child process gets write end, closes read end.
77  endpoint = umbilical->TakeWriteEnd();
78  umbilical->TakeReadEnd().Close();
79 
80 #if HAVE_DECL_SETSID
81  if (setsid() < 0) {
82  exit(1); // setsid failed.
83  }
84 #endif
85 
86  if (!nochdir) {
87  if (chdir("/") != 0) {
88  exit(1); // chdir failed.
89  }
90  }
91  if (!noclose) {
92  // Open /dev/null, and clone it into STDIN, STDOUT and STDERR to detach
93  // from terminal.
94  int fd = open("/dev/null", O_RDWR);
95  if (fd >= 0) {
96  bool err = dup2(fd, STDIN_FILENO) < 0 || dup2(fd, STDOUT_FILENO) < 0 || dup2(fd, STDERR_FILENO) < 0;
97  // Don't close if fd<=2 to try to handle the case where the program was invoked without any file descriptors open.
98  if (fd > 2) close(fd);
99  if (err) {
100  exit(1); // dup2 failed.
101  }
102  } else {
103  exit(1); // open /dev/null failed.
104  }
105  }
106  endpoint.TokenWrite(0); // Success
107  return 0;
108 }
109 
110 #endif
111 
112 static bool AppInit(NodeContext& node, int argc, char* argv[])
113 {
114  bool fRet = false;
115 
117 
118  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
119  ArgsManager& args = *Assert(node.args);
121  std::string error;
122  if (!args.ParseParameters(argc, argv, error)) {
123  return InitError(Untranslated(strprintf("Error parsing command line arguments: %s\n", error)));
124  }
125 
126  // Process help and version before taking care about datadir
127  if (HelpRequested(args) || args.IsArgSet("-version")) {
128  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
129 
130  if (args.IsArgSet("-version")) {
131  strUsage += FormatParagraph(LicenseInfo());
132  } else {
133  strUsage += "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n"
134  "\n";
135  strUsage += args.GetHelpMessage();
136  }
137 
138  tfm::format(std::cout, "%s", strUsage);
139  return true;
140  }
141 
142 #if HAVE_DECL_FORK
143  // Communication with parent after daemonizing. This is used for signalling in the following ways:
144  // - a boolean token is sent when the initialization process (all the Init* functions) have finished to indicate
145  // that the parent process can quit, and whether it was successful/unsuccessful.
146  // - an unexpected shutdown of the child process creates an unexpected end of stream at the parent
147  // end, which is interpreted as failure to start.
148  TokenPipeEnd daemon_ep;
149 #endif
150  std::any context{&node};
151  try
152  {
153  if (!CheckDataDirOption()) {
154  return InitError(Untranslated(strprintf("Specified data directory \"%s\" does not exist.\n", args.GetArg("-datadir", ""))));
155  }
156  if (!args.ReadConfigFiles(error, true)) {
157  return InitError(Untranslated(strprintf("Error reading configuration file: %s\n", error)));
158  }
159  // Check for chain settings (Params() calls are only valid after this clause)
160  try {
162  } catch (const std::exception& e) {
163  return InitError(Untranslated(strprintf("%s\n", e.what())));
164  }
165 
166  // Error out when loose non-argument tokens are encountered on command line
167  for (int i = 1; i < argc; i++) {
168  if (!IsSwitchChar(argv[i][0])) {
169  return InitError(Untranslated(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i])));
170  }
171  }
172 
173  if (!args.InitSettings(error)) {
175  return false;
176  }
177 
178  // -server defaults to true for bitcoind but not for the GUI so do this here
179  args.SoftSetBoolArg("-server", true);
180  // Set this early so that parameter interactions go to console
181  InitLogging(args);
183  if (!AppInitBasicSetup(args)) {
184  // InitError will have been called with detailed error, which ends up on console
185  return false;
186  }
188  // InitError will have been called with detailed error, which ends up on console
189  return false;
190  }
191 
192  node.kernel = std::make_unique<kernel::Context>();
193  if (!AppInitSanityChecks(*node.kernel))
194  {
195  // InitError will have been called with detailed error, which ends up on console
196  return false;
197  }
198 
199  if (args.GetBoolArg("-daemon", DEFAULT_DAEMON) || args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
200 #if HAVE_DECL_FORK
201  tfm::format(std::cout, PACKAGE_NAME " starting\n");
202 
203  // Daemonize
204  switch (fork_daemon(1, 0, daemon_ep)) { // don't chdir (1), do close FDs (0)
205  case 0: // Child: continue.
206  // If -daemonwait is not enabled, immediately send a success token the parent.
207  if (!args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
208  daemon_ep.TokenWrite(1);
209  daemon_ep.Close();
210  }
211  break;
212  case -1: // Error happened.
213  return InitError(Untranslated(strprintf("fork_daemon() failed: %s\n", SysErrorString(errno))));
214  default: { // Parent: wait and exit.
215  int token = daemon_ep.TokenRead();
216  if (token) { // Success
217  exit(EXIT_SUCCESS);
218  } else { // fRet = false or token read error (premature exit).
219  tfm::format(std::cerr, "Error during initialization - check debug.log for details\n");
220  exit(EXIT_FAILURE);
221  }
222  }
223  }
224 #else
225  return InitError(Untranslated("-daemon is not supported on this operating system\n"));
226 #endif // HAVE_DECL_FORK
227  }
228  // Lock data directory after daemonization
230  {
231  // If locking the data directory failed, exit immediately
232  return false;
233  }
235  }
236  catch (const std::exception& e) {
237  PrintExceptionContinue(&e, "AppInit()");
238  } catch (...) {
239  PrintExceptionContinue(nullptr, "AppInit()");
240  }
241 
242 #if HAVE_DECL_FORK
243  if (daemon_ep.IsOpen()) {
244  // Signal initialization status to parent, then close pipe.
245  daemon_ep.TokenWrite(fRet);
246  daemon_ep.Close();
247  }
248 #endif
250  if (fRet) {
251  WaitForShutdown();
252  }
253  Interrupt(node);
254  Shutdown(node);
255 
256  return fRet;
257 }
258 
260 {
261 #ifdef WIN32
262  util::WinCmdLineArgs winArgs;
263  std::tie(argc, argv) = winArgs.get();
264 #endif
265 
268  std::unique_ptr<interfaces::Init> init = interfaces::MakeNodeInit(node, argc, argv, exit_status);
269  if (!init) {
270  return exit_status;
271  }
272 
274 
275  // Connect bitcoind signal handlers
276  noui_connect();
277 
278  return (AppInit(node, argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE);
279 }
#define PACKAGE_NAME
return EXIT_SUCCESS
UrlDecodeFn *const URL_DECODE
Definition: bitcoind.cpp:37
static bool AppInit(NodeContext &node, int argc, char *argv[])
Definition: bitcoind.cpp:112
noui_connect()
Definition: noui.cpp:59
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoind.cpp:36
SetupEnvironment()
Definition: system.cpp:1374
int exit_status
Definition: bitcoind.cpp:267
MAIN_FUNCTION
Definition: bitcoind.cpp:260
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
#define Assert(val)
Identity function.
Definition: check.h:74
bool InitSettings(std::string &error)
Read and update settings file with saved settings.
Definition: system.cpp:505
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: system.cpp:300
std::string GetHelpMessage() const
Get the help string.
Definition: system.cpp:739
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:500
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:604
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: system.cpp:685
bool ReadConfigFiles(std::string &error, bool ignore_invalid_keys=false)
Definition: system.cpp:966
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: system.cpp:654
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
Definition: system.cpp:1058
One end of a token pipe.
Definition: tokenpipe.h:15
bool IsOpen()
Return whether endpoint is open.
Definition: tokenpipe.h:53
int TokenWrite(uint8_t token)
Write token to endpoint.
Definition: tokenpipe.cpp:40
void Close()
Explicit close function.
Definition: tokenpipe.cpp:78
int TokenRead()
Read token from endpoint.
Definition: tokenpipe.cpp:58
static std::optional< TokenPipe > Make()
Create a new pipe.
Definition: tokenpipe.cpp:84
std::string FormatFullVersion()
std::string LicenseInfo()
Returns licensing information (for -version)
void Interrupt(NodeContext &node)
Interrupt threads.
Definition: init.cpp:192
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:745
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1075
void SetupServerArgs(ArgsManager &argsman)
Register all arguments with the ArgsManager.
Definition: init.cpp:385
void Shutdown(NodeContext &node)
Definition: init.cpp:211
bool AppInitBasicSetup(const ArgsManager &args)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:775
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1087
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:656
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1093
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:1061
bool AppInitParameterInteraction(const ArgsManager &args, bool use_syscall_sandbox)
Initialization: parameter interaction.
Definition: init.cpp:820
static constexpr bool DEFAULT_DAEMON
Default value for -daemon option.
Definition: init.h:14
static constexpr bool DEFAULT_DAEMONWAIT
Default value for -daemonwait option.
Definition: init.h:16
bool InitError(const bilingual_str &str)
Show error message.
std::unique_ptr< Init > MakeNodeInit(node::NodeContext &node, int argc, char *argv[], int &exit_status)
Return implementation of Init interface for the node process.
Definition: init.h:25
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
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:65
WalletContext context
ArgsManager args
void WaitForShutdown()
Wait for StartShutdown to be called in any thread.
Definition: shutdown.cpp:94
NodeContext struct containing references to chain state and connection state.
Definition: context.h:43
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:15
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
bool IsSwitchChar(char c)
Definition: system.h:129
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
UrlDecodeFn urlDecode
Definition: url.h:11
std::string(const std::string &url_encoded) UrlDecodeFn
Definition: url.h:10
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.
bool HelpRequested(const ArgsManager &args)
Definition: system.cpp:808
bool CheckDataDirOption()
Definition: system.cpp:882
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: system.cpp:850