LCOV - code coverage report
Current view: top level - src - bitcoind.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 0.0 % 111 0
Test Date: 2024-11-04 04:45:35 Functions: 0.0 % 5 0
Branches: 0.0 % 241 0

             Branch data     Line data    Source code
       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                 :             : #include <bitcoin-build-config.h> // IWYU pragma: keep
       7                 :             : 
       8                 :             : #include <chainparams.h>
       9                 :             : #include <clientversion.h>
      10                 :             : #include <common/args.h>
      11                 :             : #include <common/init.h>
      12                 :             : #include <common/system.h>
      13                 :             : #include <compat/compat.h>
      14                 :             : #include <init.h>
      15                 :             : #include <interfaces/chain.h>
      16                 :             : #include <interfaces/init.h>
      17                 :             : #include <kernel/context.h>
      18                 :             : #include <node/context.h>
      19                 :             : #include <node/interface_ui.h>
      20                 :             : #include <node/warnings.h>
      21                 :             : #include <noui.h>
      22                 :             : #include <util/check.h>
      23                 :             : #include <util/exception.h>
      24                 :             : #include <util/signalinterrupt.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;
      38                 :             : 
      39                 :             : #if HAVE_DECL_FORK
      40                 :             : 
      41                 :             : /** Custom implementation of daemon(). This implements the same order of operations as glibc.
      42                 :             :  * Opens a pipe to the child process to be able to wait for an event to occur.
      43                 :             :  *
      44                 :             :  * @returns 0 if successful, and in child process.
      45                 :             :  *          >0 if successful, and in parent process.
      46                 :             :  *          -1 in case of error (in parent process).
      47                 :             :  *
      48                 :             :  *          In case of success, endpoint will be one end of a pipe from the child to parent process,
      49                 :             :  *          which can be used with TokenWrite (in the child) or TokenRead (in the parent).
      50                 :             :  */
      51                 :           0 : int fork_daemon(bool nochdir, bool noclose, TokenPipeEnd& endpoint)
      52                 :             : {
      53                 :             :     // communication pipe with child process
      54                 :           0 :     std::optional<TokenPipe> umbilical = TokenPipe::Make();
      55         [ #  # ]:           0 :     if (!umbilical) {
      56                 :             :         return -1; // pipe or pipe2 failed.
      57                 :             :     }
      58                 :             : 
      59                 :           0 :     int pid = fork();
      60         [ #  # ]:           0 :     if (pid < 0) {
      61                 :             :         return -1; // fork failed.
      62                 :             :     }
      63         [ #  # ]:           0 :     if (pid != 0) {
      64                 :             :         // Parent process gets read end, closes write end.
      65         [ #  # ]:           0 :         endpoint = umbilical->TakeReadEnd();
      66   [ #  #  #  # ]:           0 :         umbilical->TakeWriteEnd().Close();
      67                 :             : 
      68         [ #  # ]:           0 :         int status = endpoint.TokenRead();
      69         [ #  # ]:           0 :         if (status != 0) { // Something went wrong while setting up child process.
      70         [ #  # ]:           0 :             endpoint.Close();
      71                 :             :             return -1;
      72                 :             :         }
      73                 :             : 
      74                 :             :         return pid;
      75                 :             :     }
      76                 :             :     // Child process gets write end, closes read end.
      77         [ #  # ]:           0 :     endpoint = umbilical->TakeWriteEnd();
      78   [ #  #  #  # ]:           0 :     umbilical->TakeReadEnd().Close();
      79                 :             : 
      80                 :             : #if HAVE_DECL_SETSID
      81         [ #  # ]:           0 :     if (setsid() < 0) {
      82                 :           0 :         exit(1); // setsid failed.
      83                 :             :     }
      84                 :             : #endif
      85                 :             : 
      86         [ #  # ]:           0 :     if (!nochdir) {
      87         [ #  # ]:           0 :         if (chdir("/") != 0) {
      88                 :           0 :             exit(1); // chdir failed.
      89                 :             :         }
      90                 :             :     }
      91         [ #  # ]:           0 :     if (!noclose) {
      92                 :             :         // Open /dev/null, and clone it into STDIN, STDOUT and STDERR to detach
      93                 :             :         // from terminal.
      94         [ #  # ]:           0 :         int fd = open("/dev/null", O_RDWR);
      95         [ #  # ]:           0 :         if (fd >= 0) {
      96   [ #  #  #  #  :           0 :             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   [ #  #  #  # ]:           0 :             if (fd > 2) close(fd);
      99         [ #  # ]:           0 :             if (err) {
     100                 :           0 :                 exit(1); // dup2 failed.
     101                 :             :             }
     102                 :             :         } else {
     103                 :           0 :             exit(1); // open /dev/null failed.
     104                 :             :         }
     105                 :             :     }
     106         [ #  # ]:           0 :     endpoint.TokenWrite(0); // Success
     107                 :             :     return 0;
     108                 :           0 : }
     109                 :             : 
     110                 :             : #endif
     111                 :             : 
     112                 :           0 : static bool ParseArgs(NodeContext& node, int argc, char* argv[])
     113                 :             : {
     114                 :           0 :     ArgsManager& args{*Assert(node.args)};
     115                 :             :     // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
     116                 :           0 :     SetupServerArgs(args, node.init->canListenIpc());
     117         [ #  # ]:           0 :     std::string error;
     118   [ #  #  #  # ]:           0 :     if (!args.ParseParameters(argc, argv, error)) {
     119   [ #  #  #  #  :           0 :         return InitError(Untranslated(strprintf("Error parsing command line arguments: %s", error)));
                   #  # ]
     120                 :             :     }
     121                 :             : 
     122   [ #  #  #  # ]:           0 :     if (auto error = common::InitConfig(args)) {
     123         [ #  # ]:           0 :         return InitError(error->message, error->details);
     124                 :           0 :     }
     125                 :             : 
     126                 :             :     // Error out when loose non-argument tokens are encountered on command line
     127         [ #  # ]:           0 :     for (int i = 1; i < argc; i++) {
     128         [ #  # ]:           0 :         if (!IsSwitchChar(argv[i][0])) {
     129   [ #  #  #  #  :           0 :             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                 :           0 : }
     134                 :             : 
     135                 :           0 : static bool ProcessInitCommands(ArgsManager& args)
     136                 :             : {
     137                 :             :     // Process help and version before taking care about datadir
     138   [ #  #  #  #  :           0 :     if (HelpRequested(args) || args.IsArgSet("-version")) {
             #  #  #  # ]
     139         [ #  # ]:           0 :         std::string strUsage = CLIENT_NAME " version " + FormatFullVersion() + "\n";
     140                 :             : 
     141   [ #  #  #  #  :           0 :         if (args.IsArgSet("-version")) {
                   #  # ]
     142   [ #  #  #  # ]:           0 :             strUsage += FormatParagraph(LicenseInfo());
     143                 :             :         } else {
     144         [ #  # ]:           0 :             strUsage += "\nUsage:  bitcoind [options]                     Start " CLIENT_NAME "\n"
     145                 :           0 :                 "\n";
     146         [ #  # ]:           0 :             strUsage += args.GetHelpMessage();
     147                 :             :         }
     148                 :             : 
     149         [ #  # ]:           0 :         tfm::format(std::cout, "%s", strUsage);
     150                 :           0 :         return true;
     151                 :           0 :     }
     152                 :             : 
     153                 :             :     return false;
     154                 :             : }
     155                 :             : 
     156                 :           0 : static bool AppInit(NodeContext& node)
     157                 :             : {
     158                 :           0 :     bool fRet = false;
     159                 :           0 :     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                 :           0 :     TokenPipeEnd daemon_ep;
     168                 :             : #endif
     169         [ #  # ]:           0 :     std::any context{&node};
     170                 :           0 :     try
     171                 :             :     {
     172                 :             :         // -server defaults to true for bitcoind but not for the GUI so do this here
     173   [ #  #  #  # ]:           0 :         args.SoftSetBoolArg("-server", true);
     174                 :             :         // Set this early so that parameter interactions go to console
     175         [ #  # ]:           0 :         InitLogging(args);
     176         [ #  # ]:           0 :         InitParameterInteraction(args);
     177   [ #  #  #  # ]:           0 :         if (!AppInitBasicSetup(args, node.exit_status)) {
     178                 :             :             // InitError will have been called with detailed error, which ends up on console
     179                 :             :             return false;
     180                 :             :         }
     181   [ #  #  #  # ]:           0 :         if (!AppInitParameterInteraction(args)) {
     182                 :             :             // InitError will have been called with detailed error, which ends up on console
     183                 :             :             return false;
     184                 :             :         }
     185                 :             : 
     186         [ #  # ]:           0 :         node.warnings = std::make_unique<node::Warnings>();
     187                 :             : 
     188         [ #  # ]:           0 :         node.kernel = std::make_unique<kernel::Context>();
     189         [ #  # ]:           0 :         node.ecc_context = std::make_unique<ECC_Context>();
     190   [ #  #  #  # ]:           0 :         if (!AppInitSanityChecks(*node.kernel))
     191                 :             :         {
     192                 :             :             // InitError will have been called with detailed error, which ends up on console
     193                 :             :             return false;
     194                 :             :         }
     195                 :             : 
     196   [ #  #  #  #  :           0 :         if (args.GetBoolArg("-daemon", DEFAULT_DAEMON) || args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
          #  #  #  #  #  
          #  #  #  #  #  
                   #  # ]
     197                 :             : #if HAVE_DECL_FORK
     198         [ #  # ]:           0 :             tfm::format(std::cout, CLIENT_NAME " starting\n");
     199                 :             : 
     200                 :             :             // Daemonize
     201   [ #  #  #  #  :           0 :             switch (fork_daemon(1, 0, daemon_ep)) { // don't chdir (1), do close FDs (0)
                      # ]
     202                 :           0 :             case 0: // Child: continue.
     203                 :             :                 // If -daemonwait is not enabled, immediately send a success token the parent.
     204   [ #  #  #  #  :           0 :                 if (!args.GetBoolArg("-daemonwait", DEFAULT_DAEMONWAIT)) {
                   #  # ]
     205         [ #  # ]:           0 :                     daemon_ep.TokenWrite(1);
     206         [ #  # ]:           0 :                     daemon_ep.Close();
     207                 :             :                 }
     208                 :             :                 break;
     209                 :           0 :             case -1: // Error happened.
     210   [ #  #  #  #  :           0 :                 return InitError(Untranslated(strprintf("fork_daemon() failed: %s", SysErrorString(errno))));
             #  #  #  # ]
     211                 :           0 :             default: { // Parent: wait and exit.
     212         [ #  # ]:           0 :                 int token = daemon_ep.TokenRead();
     213         [ #  # ]:           0 :                 if (token) { // Success
     214                 :           0 :                     exit(EXIT_SUCCESS);
     215                 :             :                 } else { // fRet = false or token read error (premature exit).
     216         [ #  # ]:           0 :                     tfm::format(std::cerr, "Error during initialization - check debug.log for details\n");
     217                 :           0 :                     exit(EXIT_FAILURE);
     218                 :             :                 }
     219                 :             :             }
     220                 :             :             }
     221                 :             : #else
     222                 :             :             return InitError(Untranslated("-daemon is not supported on this operating system"));
     223                 :             : #endif // HAVE_DECL_FORK
     224                 :             :         }
     225                 :             :         // Lock data directory after daemonization
     226   [ #  #  #  # ]:           0 :         if (!AppInitLockDataDirectory())
     227                 :             :         {
     228                 :             :             // If locking the data directory failed, exit immediately
     229                 :             :             return false;
     230                 :             :         }
     231   [ #  #  #  #  :           0 :         fRet = AppInitInterfaces(node) && AppInitMain(node);
             #  #  #  # ]
     232                 :             :     }
     233         [ -  - ]:           0 :     catch (const std::exception& e) {
     234         [ -  - ]:           0 :         PrintExceptionContinue(&e, "AppInit()");
     235                 :           0 :     } catch (...) {
     236         [ -  - ]:           0 :         PrintExceptionContinue(nullptr, "AppInit()");
     237         [ -  - ]:           0 :     }
     238                 :             : 
     239                 :             : #if HAVE_DECL_FORK
     240         [ #  # ]:           0 :     if (daemon_ep.IsOpen()) {
     241                 :             :         // Signal initialization status to parent, then close pipe.
     242         [ #  # ]:           0 :         daemon_ep.TokenWrite(fRet);
     243         [ #  # ]:           0 :         daemon_ep.Close();
     244                 :             :     }
     245                 :             : #endif
     246                 :             :     return fRet;
     247                 :           0 : }
     248                 :             : 
     249                 :           0 : MAIN_FUNCTION
     250                 :             : {
     251                 :             : #ifdef WIN32
     252                 :             :     common::WinCmdLineArgs winArgs;
     253                 :             :     std::tie(argc, argv) = winArgs.get();
     254                 :             : #endif
     255                 :             : 
     256                 :           0 :     NodeContext node;
     257                 :           0 :     int exit_status;
     258         [ #  # ]:           0 :     std::unique_ptr<interfaces::Init> init = interfaces::MakeNodeInit(node, argc, argv, exit_status);
     259         [ #  # ]:           0 :     if (!init) {
     260                 :           0 :         return exit_status;
     261                 :             :     }
     262                 :             : 
     263         [ #  # ]:           0 :     SetupEnvironment();
     264                 :             : 
     265                 :             :     // Connect bitcoind signal handlers
     266         [ #  # ]:           0 :     noui_connect();
     267                 :             : 
     268   [ #  #  #  # ]:           0 :     util::ThreadSetInternalName("init");
     269                 :             : 
     270                 :             :     // Interpret command line arguments
     271         [ #  # ]:           0 :     ArgsManager& args = *Assert(node.args);
     272   [ #  #  #  # ]:           0 :     if (!ParseArgs(node, argc, argv)) return EXIT_FAILURE;
     273                 :             :     // Process early info return commands such as -help or -version
     274   [ #  #  #  # ]:           0 :     if (ProcessInitCommands(args)) return EXIT_SUCCESS;
     275                 :             : 
     276                 :             :     // Start application
     277   [ #  #  #  #  :           0 :     if (!AppInit(node) || !Assert(node.shutdown_signal)->wait()) {
          #  #  #  #  #  
                      # ]
     278                 :           0 :         node.exit_status = EXIT_FAILURE;
     279                 :             :     }
     280         [ #  # ]:           0 :     Interrupt(node);
     281         [ #  # ]:           0 :     Shutdown(node);
     282                 :             : 
     283                 :           0 :     return node.exit_status;
     284                 :           0 : }
        

Generated by: LCOV version 2.0-1