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