1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <dbus/dbus.h>
28 #include <sys/types.h>
37 #include "mount-setup.h"
38 #include "hostname-setup.h"
39 #include "loopback-setup.h"
40 #include "kmod-setup.h"
41 #include "load-fragment.h"
48 ACTION_DUMP_CONFIGURATION_ITEMS
49 } action = ACTION_RUN;
51 static char *default_unit = NULL;
52 static ManagerRunningAs running_as = _MANAGER_RUNNING_AS_INVALID;
54 static bool dump_core = true;
55 static bool crash_shell = false;
56 static int crash_chvt = -1;
57 static bool confirm_spawn = false;
58 static FILE* serialization = NULL;
60 _noreturn static void freeze(void) {
65 static void nop_handler(int sig) {
68 _noreturn static void crash(int sig) {
71 log_error("Caught <%s>, not dumping core.", strsignal(sig));
76 /* We want to wait for the core process, hence let's enable SIGCHLD */
78 sa.sa_handler = nop_handler;
79 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
80 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
82 if ((pid = fork()) < 0)
83 log_error("Caught <%s>, cannot fork for core dump: %s", strsignal(sig), strerror(errno));
88 /* Enable default signal handler for core dump */
90 sa.sa_handler = SIG_DFL;
91 assert_se(sigaction(sig, &sa, NULL) == 0);
93 /* Don't limit the core dump size */
95 rl.rlim_cur = RLIM_INFINITY;
96 rl.rlim_max = RLIM_INFINITY;
97 setrlimit(RLIMIT_CORE, &rl);
99 /* Just to be sure... */
100 assert_se(chdir("/") == 0);
102 /* Raise the signal again */
105 assert_not_reached("We shouldn't be here...");
111 /* Order things nicely. */
112 if ((r = waitpid(pid, &status, 0)) < 0)
113 log_error("Caught <%s>, waitpid() failed: %s", strsignal(sig), strerror(errno));
114 else if (!WCOREDUMP(status))
115 log_error("Caught <%s>, core dump failed.", strsignal(sig));
117 log_error("Caught <%s>, dumped core as pid %llu.", strsignal(sig), (unsigned long long) pid);
128 log_info("Executing crash shell in 10s...");
131 /* Let the kernel reap children for us */
133 sa.sa_handler = SIG_IGN;
134 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
135 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
137 if ((pid = fork()) < 0)
138 log_error("Failed to fork off crash shell: %s", strerror(errno));
142 if ((fd = acquire_terminal("/dev/console", false, true, true)) < 0)
143 log_error("Failed to acquire terminal: %s", strerror(-fd));
144 else if ((r = make_stdio(fd)) < 0)
145 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
147 execl("/bin/sh", "/bin/sh", NULL);
149 log_error("execl() failed: %s", strerror(errno));
153 log_info("Successfully spawned crash shall as pid %llu.", (unsigned long long) pid);
156 log_info("Freezing execution.");
160 static void install_crash_handler(void) {
165 sa.sa_handler = crash;
166 sa.sa_flags = SA_NODEFER;
168 assert_se(sigaction(SIGSEGV, &sa, NULL) == 0);
169 assert_se(sigaction(SIGILL, &sa, NULL) == 0);
170 assert_se(sigaction(SIGFPE, &sa, NULL) == 0);
171 assert_se(sigaction(SIGBUS, &sa, NULL) == 0);
172 assert_se(sigaction(SIGQUIT, &sa, NULL) == 0);
173 assert_se(sigaction(SIGABRT, &sa, NULL) == 0);
176 static int make_null_stdio(void) {
179 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0) {
180 log_error("Failed to open /dev/null: %m");
184 if ((r = make_stdio(null_fd)) < 0)
185 log_warning("Failed to dup2() device: %s", strerror(-r));
190 static int console_setup(bool do_reset) {
193 /* If we are init, we connect stdin/stdout/stderr to /dev/null
194 * and make sure we don't have a controlling tty. */
201 if ((tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
202 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
206 if ((r = reset_terminal(tty_fd)) < 0)
207 log_error("Failed to reset /dev/console: %s", strerror(-r));
209 close_nointr_nofail(tty_fd);
213 static int set_default_unit(const char *u) {
218 if (!(c = strdup(u)))
226 static int parse_proc_cmdline_word(const char *word) {
228 static const char * const rlmap[] = {
229 "single", SPECIAL_RUNLEVEL1_TARGET,
230 "-s", SPECIAL_RUNLEVEL1_TARGET,
231 "s", SPECIAL_RUNLEVEL1_TARGET,
232 "S", SPECIAL_RUNLEVEL1_TARGET,
233 "1", SPECIAL_RUNLEVEL1_TARGET,
234 "2", SPECIAL_RUNLEVEL2_TARGET,
235 "3", SPECIAL_RUNLEVEL3_TARGET,
236 "4", SPECIAL_RUNLEVEL4_TARGET,
237 "5", SPECIAL_RUNLEVEL5_TARGET
240 if (startswith(word, "systemd.default="))
241 return set_default_unit(word + 16);
243 else if (startswith(word, "systemd.log_target=")) {
245 if (log_set_target_from_string(word + 19) < 0)
246 log_warning("Failed to parse log target %s. Ignoring.", word + 19);
248 } else if (startswith(word, "systemd.log_level=")) {
250 if (log_set_max_level_from_string(word + 18) < 0)
251 log_warning("Failed to parse log level %s. Ignoring.", word + 18);
253 } else if (startswith(word, "systemd.dump_core=")) {
256 if ((r = parse_boolean(word + 18)) < 0)
257 log_warning("Failed to parse dump core switch %s, Ignoring.", word + 18);
261 } else if (startswith(word, "systemd.crash_shell=")) {
264 if ((r = parse_boolean(word + 20)) < 0)
265 log_warning("Failed to parse crash shell switch %s, Ignoring.", word + 20);
270 } else if (startswith(word, "systemd.confirm_spawn=")) {
273 if ((r = parse_boolean(word + 22)) < 0)
274 log_warning("Failed to parse confirm spawn switch %s, Ignoring.", word + 22);
278 } else if (startswith(word, "systemd.crash_chvt=")) {
281 if (safe_atoi(word + 19, &k) < 0)
282 log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
286 } else if (startswith(word, "systemd.")) {
288 log_warning("Unknown kernel switch %s. Ignoring.", word);
290 log_info("Supported kernel switches:");
291 log_info("systemd.default=UNIT Default unit to start");
292 log_info("systemd.log_target=console|kmsg|syslog Log target");
293 log_info("systemd.log_level=LEVEL Log level");
294 log_info("systemd.dump_core=0|1 Dump core on crash");
295 log_info("systemd.crash_shell=0|1 On crash run shell");
296 log_info("systemd.crash_chvt=N Change to VT #N on crash");
297 log_info("systemd.confirm_spawn=0|1 Confirm every process spawn");
302 /* SysV compatibility */
303 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
304 if (streq(word, rlmap[i]))
305 return set_default_unit(rlmap[i+1]);
311 static int parse_proc_cmdline(void) {
318 if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
319 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(errno));
323 FOREACH_WORD_QUOTED(w, l, line, state) {
326 if (!(word = strndup(w, l))) {
331 r = parse_proc_cmdline_word(word);
345 static int parse_argv(int argc, char *argv[]) {
348 ARG_LOG_LEVEL = 0x100,
353 ARG_DUMP_CONFIGURATION_ITEMS,
358 static const struct option options[] = {
359 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
360 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
361 { "default", required_argument, NULL, ARG_DEFAULT },
362 { "running-as", required_argument, NULL, ARG_RUNNING_AS },
363 { "test", no_argument, NULL, ARG_TEST },
364 { "help", no_argument, NULL, 'h' },
365 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
366 { "confirm-spawn", no_argument, NULL, ARG_CONFIRM_SPAWN },
367 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
376 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
381 if ((r = log_set_max_level_from_string(optarg)) < 0) {
382 log_error("Failed to parse log level %s.", optarg);
390 if ((r = log_set_target_from_string(optarg)) < 0) {
391 log_error("Failed to parse log target %s.", optarg);
399 if ((r = set_default_unit(optarg)) < 0) {
400 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
406 case ARG_RUNNING_AS: {
409 if ((as = manager_running_as_from_string(optarg)) < 0) {
410 log_error("Failed to parse running as value %s", optarg);
419 action = ACTION_TEST;
422 case ARG_DUMP_CONFIGURATION_ITEMS:
423 action = ACTION_DUMP_CONFIGURATION_ITEMS;
426 case ARG_CONFIRM_SPAWN:
427 confirm_spawn = true;
430 case ARG_DESERIALIZE: {
434 if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
435 log_error("Failed to parse deserialize option %s.", optarg);
439 if (!(f = fdopen(fd, "r"))) {
440 log_error("Failed to open serialization fd: %m");
445 fclose(serialization);
453 action = ACTION_HELP;
460 log_error("Unknown option code %c", c);
464 /* PID 1 will get the kernel arguments as parameters, which we
465 * ignore and unconditionally read from
466 * /proc/cmdline. However, we need to ignore those arguments
468 if (running_as != MANAGER_INIT && optind < argc) {
469 log_error("Excess arguments.");
476 static int help(void) {
478 printf("%s [options]\n\n"
479 " -h --help Show this help\n"
480 " --default=UNIT Set default unit\n"
481 " --log-level=LEVEL Set log level\n"
482 " --log-target=TARGET Set log target (console, syslog, kmsg, syslog-or-kmsg)\n"
483 " --running-as=AS Set running as (init, system, session)\n"
484 " --test Determine startup sequence, dump it and exit\n"
485 " --dump-configuration-items Dump understood unit configuration items\n"
486 " --confirm-spawn Ask for confirmation when spawning processes\n",
492 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
501 if ((r = manager_open_serialization(&f)) < 0) {
502 log_error("Failed to create serialization faile: %s", strerror(-r));
506 if (!(fds = fdset_new())) {
508 log_error("Failed to allocate fd set: %s", strerror(-r));
512 if ((r = manager_serialize(m, f, fds)) < 0) {
513 log_error("Failed to serialize state: %s", strerror(-r));
517 if (fseeko(f, 0, SEEK_SET) < 0) {
518 log_error("Failed to rewind serialization fd: %m");
522 if ((r = fd_cloexec(fileno(f), false)) < 0) {
523 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
527 if ((r = fdset_cloexec(fds, false)) < 0) {
528 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
546 int main(int argc, char *argv[]) {
552 bool reexecute = false;
555 running_as = MANAGER_INIT;
556 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
558 running_as = MANAGER_SESSION;
560 if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
563 /* Mount /proc, /sys and friends, so that /proc/cmdline and
564 * /proc/$PID/fd is available. */
565 if (mount_setup() < 0)
568 /* Reset all signal handlers. */
569 assert_se(reset_all_signal_handlers() == 0);
571 /* If we are init, we can block sigkill. Yay. */
572 ignore_signal(SIGKILL);
573 ignore_signal(SIGPIPE);
575 if (running_as != MANAGER_SESSION)
576 if (parse_proc_cmdline() < 0)
579 log_parse_environment();
581 if (parse_argv(argc, argv) < 0)
584 if (action == ACTION_HELP) {
587 } else if (action == ACTION_DUMP_CONFIGURATION_ITEMS) {
588 unit_dump_config_items(stdout);
593 assert_se(action == ACTION_RUN || action == ACTION_TEST);
595 /* Remember open file descriptors for later deserialization */
597 if ((r = fdset_new_fill(&fds)) < 0) {
598 log_error("Failed to allocate fd set: %s", strerror(-r));
602 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
604 close_all_fds(NULL, 0);
606 /* Set up PATH unless it is already set */
608 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
609 running_as == MANAGER_INIT);
611 /* Move out of the way, so that we won't block unmounts */
612 assert_se(chdir("/") == 0);
614 if (running_as != MANAGER_SESSION) {
615 /* Become a session leader if we aren't one yet. */
618 /* Disable the umask logic */
622 /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
623 dbus_connection_set_change_sigpipe(FALSE);
625 /* Reset the console, but only if this is really init and we
626 * are freshly booted */
627 if (running_as != MANAGER_SESSION && action == ACTION_RUN) {
628 console_setup(getpid() == 1 && !serialization);
632 /* Open the logging devices, if possible and necessary */
635 /* Make sure we leave a core dump without panicing the
638 install_crash_handler();
640 log_debug("systemd running in %s mode.", manager_running_as_to_string(running_as));
642 if (running_as == MANAGER_INIT) {
648 if ((r = manager_new(running_as, confirm_spawn, &m)) < 0) {
649 log_error("Failed to allocate manager object: %s", strerror(-r));
653 if ((r = manager_startup(m, serialization, fds)) < 0)
654 log_error("Failed to fully start up daemon: %s", strerror(-r));
657 /* This will close all file descriptors that were opened, but
658 * not claimed by any unit. */
665 fclose(serialization);
666 serialization = NULL;
668 log_debug("Activating default unit: %s", default_unit);
670 if ((r = manager_load_unit(m, default_unit, NULL, &target)) < 0) {
671 log_error("Failed to load default target: %s", strerror(-r));
673 log_info("Trying to load rescue target...");
674 if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &target)) < 0) {
675 log_error("Failed to load rescue target: %s", strerror(-r));
680 if (action == ACTION_TEST) {
681 printf("-> By units:\n");
682 manager_dump_units(m, stdout, "\t");
685 if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &job)) < 0) {
686 log_error("Failed to start default target: %s", strerror(-r));
690 if (action == ACTION_TEST) {
691 printf("-> By jobs:\n");
692 manager_dump_jobs(m, stdout, "\t");
699 if ((r = manager_loop(m)) < 0) {
700 log_error("Failed to run mainloop: %s", strerror(-r));
704 switch (m->exit_code) {
712 if ((r = manager_reload(m)) < 0)
713 log_error("Failed to reload: %s", strerror(-r));
716 case MANAGER_REEXECUTE:
717 if (prepare_reexecute(m, &serialization, &fds) < 0)
721 log_debug("Reexecuting.");
725 assert_not_reached("Unknown exit code.");
738 const char *args[11];
742 assert(serialization);
745 args[i++] = SYSTEMD_BINARY_PATH;
747 args[i++] = "--log-level";
748 args[i++] = log_level_to_string(log_get_max_level());
750 args[i++] = "--log-target";
751 args[i++] = log_target_to_string(log_get_target());
753 args[i++] = "--running-as";
754 args[i++] = manager_running_as_to_string(running_as);
756 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
759 args[i++] = "--deserialize";
763 args[i++] = "--confirm-spawn";
767 assert(i <= ELEMENTSOF(args));
769 execv(args[0], (char* const*) args);
771 log_error("Failed to reexecute: %m");
775 fclose(serialization);