]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/core/shutdown.c
tree-wide: invoke rlimit_nofile_safe() before various exec{v,ve,l}() invocations
[thirdparty/systemd.git] / src / core / shutdown.c
index 1be0f8b603fbd5a6116aa90c7c0565de86a5f8e3..368a92dd38ed95b03df6868deff65e3e0a48b3bb 100644 (file)
@@ -1,21 +1,6 @@
 /* SPDX-License-Identifier: LGPL-2.1+ */
 /***
-  This file is part of systemd.
-
-  Copyright 2010 ProFUSION embedded systems
-
-  systemd is free software; you can redistribute it and/or modify it
-  under the terms of the GNU Lesser General Public License as published by
-  the Free Software Foundation; either version 2.1 of the License, or
-  (at your option) any later version.
-
-  systemd is distributed in the hope that it will be useful, but
-  WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-  Lesser General Public License for more details.
-
-  You should have received a copy of the GNU Lesser General Public License
-  along with systemd; If not, see <http://www.gnu.org/licenses/>.
+  Copyright © 2010 ProFUSION embedded systems
 ***/
 
 #include <errno.h>
@@ -42,6 +27,8 @@
 #include "missing.h"
 #include "parse-util.h"
 #include "process-util.h"
+#include "reboot-util.h"
+#include "rlimit-util.h"
 #include "signal-util.h"
 #include "string-util.h"
 #include "switch-root.h"
 #include "virt.h"
 #include "watchdog.h"
 
-#define FINALIZE_ATTEMPTS 50
-
 #define SYNC_PROGRESS_ATTEMPTS 3
 #define SYNC_TIMEOUT_USEC (10*USEC_PER_SEC)
 
 static char* arg_verb;
 static uint8_t arg_exit_code;
+static usec_t arg_timeout = DEFAULT_TIMEOUT_USEC;
 
 static int parse_argv(int argc, char *argv[]) {
         enum {
@@ -66,6 +52,7 @@ static int parse_argv(int argc, char *argv[]) {
                 ARG_LOG_COLOR,
                 ARG_LOG_LOCATION,
                 ARG_EXIT_CODE,
+                ARG_TIMEOUT,
         };
 
         static const struct option options[] = {
@@ -74,6 +61,7 @@ static int parse_argv(int argc, char *argv[]) {
                 { "log-color",     optional_argument, NULL, ARG_LOG_COLOR    },
                 { "log-location",  optional_argument, NULL, ARG_LOG_LOCATION },
                 { "exit-code",     required_argument, NULL, ARG_EXIT_CODE    },
+                { "timeout",       required_argument, NULL, ARG_TIMEOUT      },
                 {}
         };
 
@@ -90,14 +78,14 @@ static int parse_argv(int argc, char *argv[]) {
                 case ARG_LOG_LEVEL:
                         r = log_set_max_level_from_string(optarg);
                         if (r < 0)
-                                log_error("Failed to parse log level %s, ignoring.", optarg);
+                                log_error_errno(r, "Failed to parse log level %s, ignoring: %m", optarg);
 
                         break;
 
                 case ARG_LOG_TARGET:
                         r = log_set_target_from_string(optarg);
                         if (r < 0)
-                                log_error("Failed to parse log target %s, ignoring", optarg);
+                                log_error_errno(r, "Failed to parse log target %s, ignoring: %m", optarg);
 
                         break;
 
@@ -106,7 +94,7 @@ static int parse_argv(int argc, char *argv[]) {
                         if (optarg) {
                                 r = log_show_color_from_string(optarg);
                                 if (r < 0)
-                                        log_error("Failed to parse log color setting %s, ignoring", optarg);
+                                        log_error_errno(r, "Failed to parse log color setting %s, ignoring: %m", optarg);
                         } else
                                 log_show_color(true);
 
@@ -116,7 +104,7 @@ static int parse_argv(int argc, char *argv[]) {
                         if (optarg) {
                                 r = log_show_location_from_string(optarg);
                                 if (r < 0)
-                                        log_error("Failed to parse log location setting %s, ignoring", optarg);
+                                        log_error_errno(r, "Failed to parse log location setting %s, ignoring: %m", optarg);
                         } else
                                 log_show_location(true);
 
@@ -125,7 +113,14 @@ static int parse_argv(int argc, char *argv[]) {
                 case ARG_EXIT_CODE:
                         r = safe_atou8(optarg, &arg_exit_code);
                         if (r < 0)
-                                log_error("Failed to parse exit code %s, ignoring", optarg);
+                                log_error_errno(r, "Failed to parse exit code %s, ignoring: %m", optarg);
+
+                        break;
+
+                case ARG_TIMEOUT:
+                        r = parse_sec(optarg, &arg_timeout);
+                        if (r < 0)
+                                log_error_errno(r, "Failed to parse shutdown timeout %s, ignoring: %m", optarg);
 
                         break;
 
@@ -143,10 +138,9 @@ static int parse_argv(int argc, char *argv[]) {
                         assert_not_reached("Unhandled option code.");
                 }
 
-        if (!arg_verb) {
-                log_error("Verb argument missing.");
-                return -EINVAL;
-        }
+        if (!arg_verb)
+                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
+                                       "Verb argument missing.");
 
         return 0;
 }
@@ -177,16 +171,23 @@ static int switch_root_initramfs(void) {
  */
 static bool sync_making_progress(unsigned long long *prev_dirty) {
         _cleanup_fclose_ FILE *f = NULL;
-        char line[LINE_MAX];
-        bool r = false;
         unsigned long long val = 0;
+        bool r = false;
 
         f = fopen("/proc/meminfo", "re");
         if (!f)
                 return log_warning_errno(errno, "Failed to open /proc/meminfo: %m");
 
-        FOREACH_LINE(line, f, log_warning_errno(errno, "Failed to parse /proc/meminfo: %m")) {
+        for (;;) {
+                _cleanup_free_ char *line = NULL;
                 unsigned long long ull = 0;
+                int q;
+
+                q = read_line(f, LONG_LINE_MAX, &line);
+                if (q < 0)
+                        return log_warning_errno(q, "Failed to parse /proc/meminfo: %m");
+                if (q == 0)
+                        break;
 
                 if (!first_word(line, "NFS_Unstable:") && !first_word(line, "Writeback:") && !first_word(line, "Dirty:"))
                         continue;
@@ -258,23 +259,25 @@ static void sync_with_progress(void) {
 
 int main(int argc, char *argv[]) {
         bool need_umount, need_swapoff, need_loop_detach, need_dm_detach;
-        bool in_container, use_watchdog = false;
+        bool in_container, use_watchdog = false, can_initrd;
         _cleanup_free_ char *cgroup = NULL;
         char *arguments[3];
-        unsigned retries;
-        int cmd, r;
+        int cmd, r, umount_log_level = LOG_INFO;
         static const char* const dirs[] = {SYSTEM_SHUTDOWN_PATH, NULL};
         char *watchdog_device;
 
+        /* The log target defaults to console, but the original systemd process will pass its log target in through a
+         * command line argument, which will override this default. Also, ensure we'll never log to the journal or
+         * syslog, as these logging daemons are either already dead or will die very soon. */
+
+        log_set_target(LOG_TARGET_CONSOLE);
+        log_set_prohibit_ipc(true);
         log_parse_environment();
+
         r = parse_argv(argc, argv);
         if (r < 0)
                 goto error;
 
-        /* journald will die if not gone yet. The log target defaults
-         * to console, but may have been changed by command line options. */
-
-        log_close_console(); /* force reopen of /dev/console */
         log_open();
 
         umask(0022);
@@ -296,15 +299,15 @@ int main(int argc, char *argv[]) {
         else if (streq(arg_verb, "exit"))
                 cmd = 0; /* ignored, just checking that arg_verb is valid */
         else {
-                r = -EINVAL;
                 log_error("Unknown action '%s'.", arg_verb);
+                r = -EINVAL;
                 goto error;
         }
 
         (void) cg_get_root_path(&cgroup);
         in_container = detect_container() > 0;
 
-        use_watchdog = !!getenv("WATCHDOG_USEC");
+        use_watchdog = getenv("WATCHDOG_USEC");
         watchdog_device = getenv("WATCHDOG_DEVICE");
         if (watchdog_device) {
                 r = watchdog_set_device(watchdog_device);
@@ -314,7 +317,7 @@ int main(int argc, char *argv[]) {
         }
 
         /* Lock us into memory */
-        mlockall(MCL_CURRENT|MCL_FUTURE);
+        (void) mlockall(MCL_CURRENT|MCL_FUTURE);
 
         /* Synchronize everything that is not written to disk yet at this point already. This is a good idea so that
          * slow IO is processed here already and the final process killing spree is not impacted by processes
@@ -323,19 +326,22 @@ int main(int argc, char *argv[]) {
         if (!in_container)
                 sync_with_progress();
 
+        disable_coredumps();
+
         log_info("Sending SIGTERM to remaining processes...");
-        broadcast_signal(SIGTERM, true, true);
+        broadcast_signal(SIGTERM, true, true, arg_timeout);
 
         log_info("Sending SIGKILL to remaining processes...");
-        broadcast_signal(SIGKILL, true, false);
+        broadcast_signal(SIGKILL, true, false, arg_timeout);
 
         need_umount = !in_container;
         need_swapoff = !in_container;
         need_loop_detach = !in_container;
         need_dm_detach = !in_container;
+        can_initrd = !in_container && !in_initrd() && access("/run/initramfs/shutdown", X_OK) == 0;
 
         /* Unmount all mountpoints, swaps, and loopback devices */
-        for (retries = 0; retries < FINALIZE_ATTEMPTS; retries++) {
+        for (;;) {
                 bool changed = false;
 
                 if (use_watchdog)
@@ -350,7 +356,7 @@ int main(int argc, char *argv[]) {
 
                 if (need_umount) {
                         log_info("Unmounting file systems.");
-                        r = umount_all(&changed);
+                        r = umount_all(&changed, umount_log_level);
                         if (r == 0) {
                                 need_umount = false;
                                 log_info("All filesystems unmounted.");
@@ -374,7 +380,7 @@ int main(int argc, char *argv[]) {
 
                 if (need_loop_detach) {
                         log_info("Detaching loop devices.");
-                        r = loopback_detach_all(&changed);
+                        r = loopback_detach_all(&changed, umount_log_level);
                         if (r == 0) {
                                 need_loop_detach = false;
                                 log_info("All loop devices detached.");
@@ -386,7 +392,7 @@ int main(int argc, char *argv[]) {
 
                 if (need_dm_detach) {
                         log_info("Detaching DM devices.");
-                        r = dm_detach_all(&changed);
+                        r = dm_detach_all(&changed, umount_log_level);
                         if (r == 0) {
                                 need_dm_detach = false;
                                 log_info("All DM devices detached.");
@@ -397,10 +403,19 @@ int main(int argc, char *argv[]) {
                 }
 
                 if (!need_umount && !need_swapoff && !need_loop_detach && !need_dm_detach) {
-                        if (retries > 0)
-                                log_info("All filesystems, swaps, loop devices, DM devices detached.");
+                        log_info("All filesystems, swaps, loop devices and DM devices detached.");
                         /* Yay, done */
-                        goto initrd_jump;
+                        break;
+                }
+
+                if (!changed && umount_log_level == LOG_INFO && !can_initrd) {
+                        /* There are things we cannot get rid of. Loop one more time
+                         * with LOG_ERR to inform the user. Note that we don't need
+                         * to do this if there is a initrd to switch to, because that
+                         * one is likely to get rid of the remounting mounts. If not,
+                         * it will log about them. */
+                        umount_log_level = LOG_ERR;
+                        continue;
                 }
 
                 /* If in this iteration we didn't manage to
@@ -411,31 +426,27 @@ int main(int argc, char *argv[]) {
                                  need_swapoff ? " swap devices," : "",
                                  need_loop_detach ? " loop devices," : "",
                                  need_dm_detach ? " DM devices," : "");
-                        goto initrd_jump;
+                        break;
                 }
 
-                log_debug("After %u retries, couldn't finalize remaining %s%s%s%s trying again.",
-                          retries + 1,
+                log_debug("Couldn't finalize remaining %s%s%s%s trying again.",
                           need_umount ? " file systems," : "",
                           need_swapoff ? " swap devices," : "",
                           need_loop_detach ? " loop devices," : "",
                           need_dm_detach ? " DM devices," : "");
         }
 
-        log_error("Too many iterations, giving up.");
-
- initrd_jump:
-
         /* We're done with the watchdog. */
         watchdog_free_device();
 
         arguments[0] = NULL;
         arguments[1] = arg_verb;
         arguments[2] = NULL;
-        execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments);
+        execute_directories(dirs, DEFAULT_TIMEOUT_USEC, NULL, NULL, arguments, NULL);
+
+        (void) rlimit_nofile_safe();
 
-        if (!in_container && !in_initrd() &&
-            access("/run/initramfs/shutdown", X_OK) == 0) {
+        if (can_initrd) {
                 r = switch_root_initramfs();
                 if (r >= 0) {
                         argv[0] = (char*) "/shutdown";
@@ -469,12 +480,9 @@ int main(int argc, char *argv[]) {
 
         if (streq(arg_verb, "exit")) {
                 if (in_container)
-                        exit(arg_exit_code);
-                else {
-                        /* We cannot exit() on the host, fallback on another
-                         * method. */
-                        cmd = RB_POWER_OFF;
-                }
+                        return arg_exit_code;
+
+                cmd = RB_POWER_OFF; /* We cannot exit() on the host, fallback on another method. */
         }
 
         switch (cmd) {
@@ -483,13 +491,10 @@ int main(int argc, char *argv[]) {
 
                 if (!in_container) {
                         /* We cheat and exec kexec to avoid doing all its work */
-                        pid_t pid;
-
                         log_info("Rebooting with kexec.");
 
-                        r = safe_fork("(sd-kexec)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_LOG, &pid);
+                        r = safe_fork("(sd-kexec)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_LOG|FORK_WAIT, NULL);
                         if (r == 0) {
-
                                 const char * const args[] = {
                                         KEXEC, "-e", NULL
                                 };
@@ -500,27 +505,14 @@ int main(int argc, char *argv[]) {
                                 _exit(EXIT_FAILURE);
                         }
 
-                        (void) wait_for_terminate_and_check("kexec", pid, WAIT_LOG);
+                        /* If we are still running, then the kexec can't have worked, let's fall through */
                 }
 
                 cmd = RB_AUTOBOOT;
                 _fallthrough_;
-        case RB_AUTOBOOT:
-
-                if (!in_container) {
-                        _cleanup_free_ char *param = NULL;
-
-                        r = read_one_line_file("/run/systemd/reboot-param", &param);
-                        if (r < 0 && r != -ENOENT)
-                                log_warning_errno(r, "Failed to read reboot parameter file: %m");
-
-                        if (!isempty(param)) {
-                                log_info("Rebooting with argument '%s'.", param);
-                                syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, param);
-                                log_warning_errno(errno, "Failed to reboot with parameter, retrying without: %m");
-                        }
-                }
 
+        case RB_AUTOBOOT:
+                (void) reboot_with_parameter(REBOOT_LOG);
                 log_info("Rebooting.");
                 break;
 
@@ -536,13 +528,13 @@ int main(int argc, char *argv[]) {
                 assert_not_reached("Unknown magic");
         }
 
-        reboot(cmd);
+        (void) reboot(cmd);
         if (errno == EPERM && in_container) {
                 /* If we are in a container, and we lacked
                  * CAP_SYS_BOOT just exit, this will kill our
                  * container for good. */
                 log_info("Exiting container.");
-                exit(EXIT_SUCCESS);
+                return EXIT_SUCCESS;
         }
 
         r = log_error_errno(errno, "Failed to invoke reboot(): %m");