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 "modprobe-setup.h"
42 #include "load-fragment.h"
45 #include "conf-parser.h"
51 ACTION_DUMP_CONFIGURATION_ITEMS,
53 } arg_action = ACTION_RUN;
55 static char *arg_default_unit = NULL;
56 static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
58 static bool arg_dump_core = true;
59 static bool arg_crash_shell = false;
60 static int arg_crash_chvt = -1;
61 static bool arg_confirm_spawn = false;
62 static bool arg_nomodules = false;
63 static bool arg_show_status = true;
65 static FILE* serialization = NULL;
67 _noreturn_ static void freeze(void) {
72 static void nop_handler(int sig) {
75 _noreturn_ static void crash(int sig) {
78 log_error("Caught <%s>, not dumping core.", strsignal(sig));
83 /* We want to wait for the core process, hence let's enable SIGCHLD */
85 sa.sa_handler = nop_handler;
86 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
87 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
89 if ((pid = fork()) < 0)
90 log_error("Caught <%s>, cannot fork for core dump: %s", strsignal(sig), strerror(errno));
95 /* Enable default signal handler for core dump */
97 sa.sa_handler = SIG_DFL;
98 assert_se(sigaction(sig, &sa, NULL) == 0);
100 /* Don't limit the core dump size */
102 rl.rlim_cur = RLIM_INFINITY;
103 rl.rlim_max = RLIM_INFINITY;
104 setrlimit(RLIMIT_CORE, &rl);
106 /* Just to be sure... */
107 assert_se(chdir("/") == 0);
109 /* Raise the signal again */
112 assert_not_reached("We shouldn't be here...");
118 /* Order things nicely. */
119 if ((r = waitpid(pid, &status, 0)) < 0)
120 log_error("Caught <%s>, waitpid() failed: %s", strsignal(sig), strerror(errno));
121 else if (!WCOREDUMP(status))
122 log_error("Caught <%s>, core dump failed.", strsignal(sig));
124 log_error("Caught <%s>, dumped core as pid %lu.", strsignal(sig), (unsigned long) pid);
129 chvt(arg_crash_chvt);
131 if (arg_crash_shell) {
135 log_info("Executing crash shell in 10s...");
138 /* Let the kernel reap children for us */
140 sa.sa_handler = SIG_IGN;
141 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
142 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
144 if ((pid = fork()) < 0)
145 log_error("Failed to fork off crash shell: %s", strerror(errno));
149 if ((fd = acquire_terminal("/dev/console", false, true, true)) < 0)
150 log_error("Failed to acquire terminal: %s", strerror(-fd));
151 else if ((r = make_stdio(fd)) < 0)
152 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
154 execl("/bin/sh", "/bin/sh", NULL);
156 log_error("execl() failed: %s", strerror(errno));
160 log_info("Successfully spawned crash shall as pid %lu.", (unsigned long) pid);
163 log_info("Freezing execution.");
167 static void install_crash_handler(void) {
172 sa.sa_handler = crash;
173 sa.sa_flags = SA_NODEFER;
175 sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
178 static int make_null_stdio(void) {
181 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0) {
182 log_error("Failed to open /dev/null: %m");
186 if ((r = make_stdio(null_fd)) < 0)
187 log_warning("Failed to dup2() device: %s", strerror(-r));
192 static int console_setup(bool do_reset) {
195 /* If we are init, we connect stdin/stdout/stderr to /dev/null
196 * and make sure we don't have a controlling tty. */
203 if ((tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
204 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
208 if ((r = reset_terminal(tty_fd)) < 0)
209 log_error("Failed to reset /dev/console: %s", strerror(-r));
211 close_nointr_nofail(tty_fd);
215 static int set_default_unit(const char *u) {
220 if (!(c = strdup(u)))
223 free(arg_default_unit);
224 arg_default_unit = c;
228 static int parse_proc_cmdline_word(const char *word) {
230 static const char * const rlmap[] = {
231 "single", SPECIAL_RESCUE_TARGET,
232 "-s", SPECIAL_RESCUE_TARGET,
233 "s", SPECIAL_RESCUE_TARGET,
234 "S", SPECIAL_RESCUE_TARGET,
235 "1", SPECIAL_RESCUE_TARGET,
236 "2", SPECIAL_RUNLEVEL2_TARGET,
237 "3", SPECIAL_RUNLEVEL3_TARGET,
238 "4", SPECIAL_RUNLEVEL4_TARGET,
239 "5", SPECIAL_RUNLEVEL5_TARGET
241 bool ignore_quiet = false;
243 if (startswith(word, "systemd.unit="))
244 return set_default_unit(word + 13);
246 else if (startswith(word, "systemd.log_target=")) {
248 if (log_set_target_from_string(word + 19) < 0)
249 log_warning("Failed to parse log target %s. Ignoring.", word + 19);
251 } else if (startswith(word, "systemd.log_level=")) {
253 if (log_set_max_level_from_string(word + 18) < 0)
254 log_warning("Failed to parse log level %s. Ignoring.", word + 18);
256 } else if (startswith(word, "systemd.log_color=")) {
258 if (log_show_color_from_string(word + 18) < 0)
259 log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
261 } else if (startswith(word, "systemd.log_location=")) {
263 if (log_show_location_from_string(word + 21) < 0)
264 log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
266 } else if (startswith(word, "systemd.dump_core=")) {
269 if ((r = parse_boolean(word + 18)) < 0)
270 log_warning("Failed to parse dump core switch %s, Ignoring.", word + 18);
274 } else if (startswith(word, "systemd.crash_shell=")) {
277 if ((r = parse_boolean(word + 20)) < 0)
278 log_warning("Failed to parse crash shell switch %s, Ignoring.", word + 20);
282 } else if (startswith(word, "systemd.confirm_spawn=")) {
285 if ((r = parse_boolean(word + 22)) < 0)
286 log_warning("Failed to parse confirm spawn switch %s, Ignoring.", word + 22);
288 arg_confirm_spawn = r;
290 } else if (startswith(word, "systemd.crash_chvt=")) {
293 if (safe_atoi(word + 19, &k) < 0)
294 log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
298 } else if (startswith(word, "systemd.show_status=")) {
301 if ((r = parse_boolean(word + 20)) < 0)
302 log_warning("Failed to parse show status switch %s, Ignoring.", word + 20);
308 } else if (startswith(word, "systemd.")) {
310 log_warning("Unknown kernel switch %s. Ignoring.", word);
312 log_info("Supported kernel switches:\n"
313 "systemd.unit=UNIT Default unit to start\n"
314 "systemd.log_target=console|kmsg|syslog| Log target\n"
315 " syslog-org-kmsg|null\n"
316 "systemd.log_level=LEVEL Log level\n"
317 "systemd.log_color=0|1 Highlight important log messages\n"
318 "systemd.log_location=0|1 Include code location in log messages\n"
319 "systemd.dump_core=0|1 Dump core on crash\n"
320 "systemd.crash_shell=0|1 Run shell on crash\n"
321 "systemd.crash_chvt=N Change to VT #N on crash\n"
322 "systemd.confirm_spawn=0|1 Confirm every process spawn\n"
323 "systemd.show_status=0|1 Show status updates on the console during bootup\n");
325 } else if (streq(word, "nomodules"))
326 arg_nomodules = true;
327 else if (streq(word, "quiet")) {
329 arg_show_status = false;
333 /* SysV compatibility */
334 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
335 if (streq(word, rlmap[i]))
336 return set_default_unit(rlmap[i+1]);
342 static int config_parse_level(
343 const char *filename,
355 log_set_max_level_from_string(rvalue);
359 static int config_parse_target(
360 const char *filename,
372 log_set_target_from_string(rvalue);
376 static int config_parse_color(
377 const char *filename,
389 log_show_color_from_string(rvalue);
393 static int config_parse_location(
394 const char *filename,
406 log_show_location_from_string(rvalue);
410 static int config_parse_cpu_affinity(
411 const char *filename,
429 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
434 if (!(t = strndup(w, l)))
437 r = safe_atou(t, &cpu);
441 if (!(c = cpu_set_malloc(&ncpus)))
444 if (r < 0 || cpu >= ncpus) {
445 log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
450 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
454 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
455 log_warning("Failed to set CPU affinity: %m");
463 static int parse_config_file(void) {
465 const ConfigItem items[] = {
466 { "LogLevel", config_parse_level, NULL, "Manager" },
467 { "LogTarget", config_parse_target, NULL, "Manager" },
468 { "LogColor", config_parse_color, NULL, "Manager" },
469 { "LogLocation", config_parse_location, NULL, "Manager" },
470 { "DumpCore", config_parse_bool, &arg_dump_core, "Manager" },
471 { "CrashShell", config_parse_bool, &arg_crash_shell, "Manager" },
472 { "ShowStatus", config_parse_bool, &arg_show_status, "Manager" },
473 { "CrashChVT", config_parse_int, &arg_crash_chvt, "Manager" },
474 { "CPUAffinity", config_parse_cpu_affinity, NULL, "Manager" },
475 { NULL, NULL, NULL, NULL }
478 static const char * const sections[] = {
487 fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : SESSION_CONFIG_FILE;
489 if (!(f = fopen(fn, "re"))) {
493 log_warning("Failed to open configuration file '%s': %m", fn);
497 if ((r = config_parse(fn, f, sections, items, false, NULL)) < 0)
498 log_warning("Failed to parse configuration file: %s", strerror(-r));
505 static int parse_proc_cmdline(void) {
512 if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
513 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(errno));
517 FOREACH_WORD_QUOTED(w, l, line, state) {
520 if (!(word = strndup(w, l))) {
525 r = parse_proc_cmdline_word(word);
539 static int parse_argv(int argc, char *argv[]) {
542 ARG_LOG_LEVEL = 0x100,
549 ARG_DUMP_CONFIGURATION_ITEMS,
558 static const struct option options[] = {
559 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
560 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
561 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
562 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
563 { "unit", required_argument, NULL, ARG_UNIT },
564 { "running-as", required_argument, NULL, ARG_RUNNING_AS },
565 { "test", no_argument, NULL, ARG_TEST },
566 { "help", no_argument, NULL, 'h' },
567 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
568 { "dump-core", no_argument, NULL, ARG_DUMP_CORE },
569 { "crash-shell", no_argument, NULL, ARG_CRASH_SHELL },
570 { "confirm-spawn", no_argument, NULL, ARG_CONFIRM_SPAWN },
571 { "show-status", no_argument, NULL, ARG_SHOW_STATUS },
572 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
573 { "introspect", optional_argument, NULL, ARG_INTROSPECT },
582 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
587 if ((r = log_set_max_level_from_string(optarg)) < 0) {
588 log_error("Failed to parse log level %s.", optarg);
596 if ((r = log_set_target_from_string(optarg)) < 0) {
597 log_error("Failed to parse log target %s.", optarg);
606 if ((r = log_show_color_from_string(optarg)) < 0) {
607 log_error("Failed to parse log color setting %s.", optarg);
611 log_show_color(true);
615 case ARG_LOG_LOCATION:
618 if ((r = log_show_location_from_string(optarg)) < 0) {
619 log_error("Failed to parse log location setting %s.", optarg);
623 log_show_location(true);
629 if ((r = set_default_unit(optarg)) < 0) {
630 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
636 case ARG_RUNNING_AS: {
639 if ((as = manager_running_as_from_string(optarg)) < 0) {
640 log_error("Failed to parse running as value %s", optarg);
649 arg_action = ACTION_TEST;
652 case ARG_DUMP_CONFIGURATION_ITEMS:
653 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
657 arg_dump_core = true;
660 case ARG_CRASH_SHELL:
661 arg_crash_shell = true;
664 case ARG_CONFIRM_SPAWN:
665 arg_confirm_spawn = true;
668 case ARG_SHOW_STATUS:
669 arg_show_status = true;
672 case ARG_DESERIALIZE: {
676 if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
677 log_error("Failed to parse deserialize option %s.", optarg);
681 if (!(f = fdopen(fd, "r"))) {
682 log_error("Failed to open serialization fd: %m");
687 fclose(serialization);
694 case ARG_INTROSPECT: {
695 const char * const * i = NULL;
697 for (i = bus_interface_table; *i; i += 2)
698 if (!optarg || streq(i[0], optarg)) {
699 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
702 fputs("</node>\n", stdout);
709 log_error("Unknown interface %s.", optarg);
711 arg_action = ACTION_DONE;
716 arg_action = ACTION_HELP;
723 log_error("Unknown option code %c", c);
727 /* PID 1 will get the kernel arguments as parameters, which we
728 * ignore and unconditionally read from
729 * /proc/cmdline. However, we need to ignore those arguments
731 if (arg_running_as != MANAGER_SYSTEM && optind < argc) {
732 log_error("Excess arguments.");
739 static int help(void) {
741 printf("%s [OPTIONS...]\n\n"
742 "Starts up and maintains the system or a session.\n\n"
743 " -h --help Show this help\n"
744 " --test Determine startup sequence, dump it and exit\n"
745 " --dump-configuration-items Dump understood unit configuration items\n"
746 " --introspect[=INTERFACE] Extract D-Bus interface data\n"
747 " --unit=UNIT Set default unit\n"
748 " --running-as=AS Set running as (system, session)\n"
749 " --dump-core Dump core on crash\n"
750 " --crash-shell Run shell on crash\n"
751 " --confirm-spawn Ask for confirmation when spawning processes\n"
752 " --show-status Show status updates on the console during bootup\n"
753 " --log-target=TARGET Set log target (console, syslog, kmsg, syslog-or-kmsg, null)\n"
754 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
755 " --log-color[=0|1] Highlight important log messages\n"
756 " --log-location[=0|1] Include code location in log messages\n",
757 program_invocation_short_name);
762 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
771 if ((r = manager_open_serialization(&f)) < 0) {
772 log_error("Failed to create serialization faile: %s", strerror(-r));
776 if (!(fds = fdset_new())) {
778 log_error("Failed to allocate fd set: %s", strerror(-r));
782 if ((r = manager_serialize(m, f, fds)) < 0) {
783 log_error("Failed to serialize state: %s", strerror(-r));
787 if (fseeko(f, 0, SEEK_SET) < 0) {
788 log_error("Failed to rewind serialization fd: %m");
792 if ((r = fd_cloexec(fileno(f), false)) < 0) {
793 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
797 if ((r = fdset_cloexec(fds, false)) < 0) {
798 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
816 int main(int argc, char *argv[]) {
822 bool reexecute = false;
824 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
825 /* This is compatbility support for SysV, where
826 * calling init as a user is identical to telinit. */
829 execv(SYSTEMCTL_BINARY_PATH, argv);
830 log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
834 log_show_color(true);
835 log_show_location(false);
836 log_set_max_level(LOG_INFO);
839 arg_running_as = MANAGER_SYSTEM;
840 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
842 arg_running_as = MANAGER_SESSION;
843 log_set_target(LOG_TARGET_CONSOLE);
846 if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
849 /* Mount /proc, /sys and friends, so that /proc/cmdline and
850 * /proc/$PID/fd is available. */
852 if (mount_setup() < 0)
855 /* Reset all signal handlers. */
856 assert_se(reset_all_signal_handlers() == 0);
858 /* If we are init, we can block sigkill. Yay. */
859 ignore_signals(SIGNALS_IGNORE, -1);
861 if (parse_config_file() < 0)
864 if (arg_running_as == MANAGER_SYSTEM)
865 if (parse_proc_cmdline() < 0)
868 log_parse_environment();
870 if (parse_argv(argc, argv) < 0)
873 if (arg_action == ACTION_HELP) {
876 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
877 unit_dump_config_items(stdout);
880 } else if (arg_action == ACTION_DONE) {
885 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
887 /* Remember open file descriptors for later deserialization */
889 if ((r = fdset_new_fill(&fds)) < 0) {
890 log_error("Failed to allocate fd set: %s", strerror(-r));
894 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
896 close_all_fds(NULL, 0);
898 /* Set up PATH unless it is already set */
900 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
901 arg_running_as == MANAGER_SYSTEM);
903 /* Move out of the way, so that we won't block unmounts */
904 assert_se(chdir("/") == 0);
906 if (arg_running_as == MANAGER_SYSTEM) {
907 /* Become a session leader if we aren't one yet. */
910 /* Disable the umask logic */
914 /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
915 dbus_connection_set_change_sigpipe(FALSE);
917 /* Reset the console, but only if this is really init and we
918 * are freshly booted */
919 if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
920 console_setup(getpid() == 1 && !serialization);
924 /* Open the logging devices, if possible and necessary */
927 /* Make sure we leave a core dump without panicing the
930 install_crash_handler();
932 log_info(PACKAGE_STRING " running in %s mode.", manager_running_as_to_string(arg_running_as));
934 if (arg_running_as == MANAGER_SYSTEM && !serialization) {
937 modprobe_setup(arg_nomodules);
943 if ((r = manager_new(arg_running_as, &m)) < 0) {
944 log_error("Failed to allocate manager object: %s", strerror(-r));
948 m->confirm_spawn = arg_confirm_spawn;
949 m->show_status = arg_show_status;
951 if ((r = manager_startup(m, serialization, fds)) < 0)
952 log_error("Failed to fully start up daemon: %s", strerror(-r));
955 /* This will close all file descriptors that were opened, but
956 * not claimed by any unit. */
963 fclose(serialization);
964 serialization = NULL;
966 log_debug("Activating default unit: %s", arg_default_unit);
968 if ((r = manager_load_unit(m, arg_default_unit, NULL, &target)) < 0) {
969 log_error("Failed to load default target: %s", strerror(-r));
971 log_info("Trying to load rescue target...");
972 if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &target)) < 0) {
973 log_error("Failed to load rescue target: %s", strerror(-r));
978 if (arg_action == ACTION_TEST) {
979 printf("-> By units:\n");
980 manager_dump_units(m, stdout, "\t");
983 if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &job)) < 0) {
984 log_error("Failed to start default target: %s", strerror(-r));
988 if (arg_action == ACTION_TEST) {
989 printf("-> By jobs:\n");
990 manager_dump_jobs(m, stdout, "\t");
997 if ((r = manager_loop(m)) < 0) {
998 log_error("Failed to run mainloop: %s", strerror(-r));
1002 switch (m->exit_code) {
1009 case MANAGER_RELOAD:
1010 log_info("Reloading.");
1011 if ((r = manager_reload(m)) < 0)
1012 log_error("Failed to reload: %s", strerror(-r));
1015 case MANAGER_REEXECUTE:
1016 if (prepare_reexecute(m, &serialization, &fds) < 0)
1020 log_notice("Reexecuting.");
1024 assert_not_reached("Unknown exit code.");
1032 free(arg_default_unit);
1037 const char *args[11];
1041 assert(serialization);
1044 args[i++] = SYSTEMD_BINARY_PATH;
1046 args[i++] = "--log-level";
1047 args[i++] = log_level_to_string(log_get_max_level());
1049 args[i++] = "--log-target";
1050 args[i++] = log_target_to_string(log_get_target());
1052 args[i++] = "--running-as";
1053 args[i++] = manager_running_as_to_string(arg_running_as);
1055 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
1058 args[i++] = "--deserialize";
1061 if (arg_confirm_spawn)
1062 args[i++] = "--confirm-spawn";
1066 assert(i <= ELEMENTSOF(args));
1068 execv(args[0], (char* const*) args);
1070 log_error("Failed to reexecute: %m");
1074 fclose(serialization);