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