Bitcoin Core  27.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-2022 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 <common/args.h>
13 #include <common/init.h>
14 #include <common/system.h>
15 #include <common/url.h>
16 #include <compat/compat.h>
17 #include <init.h>
18 #include <interfaces/chain.h>
19 #include <interfaces/init.h>
20 #include <node/context.h>
21 #include <node/interface_ui.h>
22 #include <noui.h>
23 #include <util/check.h>
24 #include <util/exception.h>
25 #include <util/strencodings.h>
26 #include <util/syserror.h>
27 #include <util/threadnames.h>
28 #include <util/tokenpipe.h>
29 #include <util/translation.h>
30 
31 #include <any>
32 #include <functional>
33 #include <optional>
34 
35 using node::NodeContext;
36 
37 const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
39 
40 #if HAVE_DECL_FORK
41 
52 int fork_daemon(bool nochdir, bool noclose, TokenPipeEnd& endpoint)
53 {
54  // communication pipe with child process
55  std::optional<TokenPipe> umbilical = TokenPipe::Make();
56  if (!umbilical) {
57  return -1; // pipe or pipe2 failed.
58  }
59 
60  int pid = fork();
61  if (pid < 0) {
62  return -1; // fork failed.
63  }
64  if (pid != 0) {
65  // Parent process gets read end, closes write end.
66  endpoint = umbilical->TakeReadEnd();
67  umbilical->TakeWriteEnd().Close();
68 
69  int status = endpoint.TokenRead();
70  if (status != 0) { // Something went wrong while setting up child process.
71  endpoint.Close();
72  return -1;
73  }
74 
75  return pid;
76  }
77  // Child process gets write end, closes read end.
78  endpoint = umbilical->TakeWriteEnd();
79  umbilical->TakeReadEnd().Close();
80 
81 #if HAVE_DECL_SETSID
82  if (setsid() < 0) {
83  exit(1); // setsid failed.
84  }
85 #endif
86 
87  if (!nochdir) {
88  if (chdir("/") != 0) {
89  exit(1); // chdir failed.
90  }
91  }
92  if (!noclose) {
93  // Open /dev/null, and clone it into STDIN, STDOUT and STDERR to detach
94  // from terminal.
95  int fd = open("/dev/null", O_RDWR);
96  if (fd >= 0) {
97  bool err = dup2(fd, STDIN_FILENO) < 0 || dup2(fd, STDOUT_FILENO) < 0 || dup2(fd, STDERR_FILENO) < 0;
98  // Don't close if fd<=2 to try to handle the case where the program was invoked without any file descriptors open.
99  if (fd > 2) close(fd);
100  if (err) {
101  exit(1); // dup2 failed.
102  }
103  } else {
104  exit(1); // open /dev/null failed.
105  }
106  }
107  endpoint.TokenWrite(0); // Success
108  return 0;
109 }
110 
111 #endif
112 
113 static bool ParseArgs(ArgsManager& args, int argc, char* argv[])
114 {
115  // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
117  std::string error;
118  if (!args.ParseParameters(argc, argv, error)) {
119  return InitError(Untranslated(strprintf("Error parsing command line arguments: %s", error)));
120  }
121 
122  if (auto error = common::InitConfig(args)) {
123  return InitError(error->message, error->details);
124  }
125 
126  // Error out when loose non-argument tokens are encountered on command line
127  for (int i = 1; i < argc; i++) {
128  if (!IsSwitchChar(argv[i][0])) {
129  return InitError(Untranslated(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.", argv[i])));
130  }
131  }
132  return true;
133 }
134 
136 {
137  // Process help and version before taking care about datadir
138  if (HelpRequested(args) || args.IsArgSet("-version")) {
139  std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n";
140 
141  if (args.IsArgSet("-version")) {
142  strUsage += FormatParagraph(LicenseInfo());
143  } else {
144  strUsage += "\nUsage: bitcoind [options] Start " PACKAGE_NAME "\n"
145  "\n";
146  strUsage += args.GetHelpMessage();
147  }
148 
149  tfm::format(std::cout, "%s", strUsage);
150  return true;
151  }
152 
153  return false;
154 }
155 
156 static bool AppInit(NodeContext& node)
157 {
158  bool fRet = false;
159  ArgsManager& args = *Assert(node.args);
160 
161 #if HAVE_DECL_FORK
162  // Communication with parent after daemonizing. This is used for signalling in the following ways:
163  // - a boolean token is sent when the initialization process (all the Init* functions) have finished to indicate
164  // that the parent process can quit, and whether it was successful/unsuccessful.
165  // - an unexpected shutdown of the child process creates an unexpected end of stream at the parent
166  // end, which is interpreted as failure to start.
167  TokenPipeEnd daemon_ep;
168 #endif
169  std::any context{&node};
170  try
171  {
172  // -server defaults to true for bitcoind but not for the GUI so do this here
173  args.SoftSetBoolArg("-server", true);
174  // Set this early so that parameter interactions go to console
175  InitLogging(args);
177  if (!AppInitBasicSetup(args, node.exit_status)) {
178  // InitError will have been called with detailed error, which ends up on console
179  return false;
180  }
182  // InitError will have been called with detailed error, which ends up on console
183  return false;
184  }
185 
186  node.kernel = std::make_unique<kernel::Context>();
187  if (!AppInitSanityChecks(*node.kernel))
188  {
189  // InitError will have been called with detailed error, which ends up on console
190  return false;
191  }
192 
193  if (args.GetBoolArg("-daemon", DEFAULT_DAEMON) || args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
194 #if HAVE_DECL_FORK
195  tfm::format(std::cout, PACKAGE_NAME " starting\n");
196 
197  // Daemonize
198  switch (fork_daemon(1, 0, daemon_ep)) { // don't chdir (1), do close FDs (0)
199  case 0: // Child: continue.
200  // If -daemonwait is not enabled, immediately send a success token the parent.
201  if (!args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
202  daemon_ep.TokenWrite(1);
203  daemon_ep.Close();
204  }
205  break;
206  case -1: // Error happened.
207  return InitError(Untranslated(strprintf("fork_daemon() failed: %s", SysErrorString(errno))));
208  default: { // Parent: wait and exit.
209  int token = daemon_ep.TokenRead();
210  if (token) { // Success
211  exit(EXIT_SUCCESS);
212  } else { // fRet = false or token read error (premature exit).
213  tfm::format(std::cerr, "Error during initialization - check debug.log for details\n");
214  exit(EXIT_FAILURE);
215  }
216  }
217  }
218 #else
219  return InitError(Untranslated("-daemon is not supported on this operating system"));
220 #endif // HAVE_DECL_FORK
221  }
222  // Lock data directory after daemonization
224  {
225  // If locking the data directory failed, exit immediately
226  return false;
227  }
229  }
230  catch (const std::exception& e) {
231  PrintExceptionContinue(&e, "AppInit()");
232  } catch (...) {
233  PrintExceptionContinue(nullptr, "AppInit()");
234  }
235 
236 #if HAVE_DECL_FORK
237  if (daemon_ep.IsOpen()) {
238  // Signal initialization status to parent, then close pipe.
239  daemon_ep.TokenWrite(fRet);
240  daemon_ep.Close();
241  }
242 #endif
243  return fRet;
244 }
245 
247 {
248 #ifdef WIN32
249  common::WinCmdLineArgs winArgs;
250  std::tie(argc, argv) = winArgs.get();
251 #endif
252 
255  std::unique_ptr<interfaces::Init> init = interfaces::MakeNodeInit(node, argc, argv, exit_status);
256  if (!init) {
257  return exit_status;
258  }
259 
261 
262  // Connect bitcoind signal handlers
263  noui_connect();
264 
266 
267  // Interpret command line arguments
269  if (!ParseArgs(args, argc, argv)) return EXIT_FAILURE;
270  // Process early info return commands such as -help or -version
272 
273  // Start application
274  if (!AppInit(node) || !Assert(node.shutdown)->wait()) {
275  node.exit_status = EXIT_FAILURE;
276  }
279 
280  return node.exit_status;
281 }
bool HelpRequested(const ArgsManager &args)
Definition: args.cpp:659
bool IsSwitchChar(char c)
Definition: args.h:43
#define PACKAGE_NAME
return EXIT_SUCCESS
UrlDecodeFn *const URL_DECODE
Definition: bitcoind.cpp:38
int exit_status
Definition: bitcoind.cpp:254
static bool ParseArgs(ArgsManager &args, int argc, char *argv[])
Definition: bitcoind.cpp:113
noui_connect()
Definition: noui.cpp:60
ArgsManager & args
Definition: bitcoind.cpp:268
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
Definition: bitcoind.cpp:37
SetupEnvironment()
Definition: system.cpp:59
static bool AppInit(NodeContext &node)
Definition: bitcoind.cpp:156
Interrupt(node)
Shutdown(node)
static bool ProcessInitCommands(ArgsManager &args)
Definition: bitcoind.cpp:135
MAIN_FUNCTION
Definition: bitcoind.cpp:247
#define Assert(val)
Identity function.
Definition: check.h:77
bool ParseParameters(int argc, const char *const argv[], std::string &error)
Definition: args.cpp:177
std::string GetHelpMessage() const
Get the help string.
Definition: args.cpp:590
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:369
bool SoftSetBoolArg(const std::string &strArg, bool fValue)
Set a boolean argument if it doesn't already have a value.
Definition: args.cpp:536
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
Definition: args.cpp:505
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 PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
Definition: exception.cpp:36
void InitLogging(const ArgsManager &args)
Initialize global loggers.
Definition: init.cpp:815
bool AppInitLockDataDirectory()
Lock bitcoin core data directory.
Definition: init.cpp:1099
void SetupServerArgs(ArgsManager &argsman)
Register all arguments with the ArgsManager.
Definition: init.cpp:438
bool AppInitBasicSetup(const ArgsManager &args, std::atomic< int > &exit_status)
Initialize bitcoin core: Basic context setup.
Definition: init.cpp:845
bool AppInitParameterInteraction(const ArgsManager &args)
Initialization: parameter interaction.
Definition: init.cpp:882
bool AppInitInterfaces(NodeContext &node)
Initialize node and wallet interface pointers.
Definition: init.cpp:1111
void InitParameterInteraction(ArgsManager &args)
Parameter interaction: change current parameters depending on various rules.
Definition: init.cpp:723
bool AppInitMain(NodeContext &node, interfaces::BlockAndHeaderTipInfo *tip_info)
Bitcoin core main initialization.
Definition: init.cpp:1117
bool AppInitSanityChecks(const kernel::Context &kernel)
Initialization sanity checks.
Definition: init.cpp:1084
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::optional< ConfigError > InitConfig(ArgsManager &args, SettingsAbortFn settings_abort_fn)
Definition: init.cpp:18
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:1060
void ThreadSetInternalName(std::string &&)
Set the internal (in-memory) name of the current thread only.
Definition: threadnames.cpp:65
NodeContext struct containing references to chain state and connection state.
Definition: context.h:49
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:21
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
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.