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