1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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>
34 #include <sys/prctl.h>
35 #include <sys/mount.h>
39 #include "load-fragment.h"
42 #include "conf-parser.h"
43 #include "bus-errors.h"
51 #include "path-util.h"
52 #include "switch-root.h"
53 #include "capability.h"
55 #include "mount-setup.h"
56 #include "loopback-setup.h"
57 #include "kmod-setup.h"
58 #include "hostname-setup.h"
59 #include "machine-id-setup.h"
60 #include "locale-setup.h"
62 #include "selinux-setup.h"
63 #include "ima-setup.h"
69 ACTION_DUMP_CONFIGURATION_ITEMS,
71 } arg_action = ACTION_RUN;
73 static char *arg_default_unit = NULL;
74 static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
76 static bool arg_dump_core = true;
77 static bool arg_crash_shell = false;
78 static int arg_crash_chvt = -1;
79 static bool arg_confirm_spawn = false;
80 static bool arg_show_status = true;
81 static bool arg_switched_root = false;
82 static char **arg_default_controllers = NULL;
83 static char ***arg_join_controllers = NULL;
84 static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
85 static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
86 static usec_t arg_runtime_watchdog = 0;
87 static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
88 static struct rlimit *arg_default_rlimit[RLIMIT_NLIMITS] = {};
89 static uint64_t arg_capability_bounding_set_drop = 0;
90 static nsec_t arg_timer_slack_nsec = (nsec_t) -1;
92 static FILE* serialization = NULL;
94 static void nop_handler(int sig) {
97 _noreturn_ static void crash(int sig) {
100 log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
105 /* We want to wait for the core process, hence let's enable SIGCHLD */
107 sa.sa_handler = nop_handler;
108 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
109 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
111 if ((pid = fork()) < 0)
112 log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
117 /* Enable default signal handler for core dump */
119 sa.sa_handler = SIG_DFL;
120 assert_se(sigaction(sig, &sa, NULL) == 0);
122 /* Don't limit the core dump size */
124 rl.rlim_cur = RLIM_INFINITY;
125 rl.rlim_max = RLIM_INFINITY;
126 setrlimit(RLIMIT_CORE, &rl);
128 /* Just to be sure... */
129 assert_se(chdir("/") == 0);
131 /* Raise the signal again */
134 assert_not_reached("We shouldn't be here...");
141 /* Order things nicely. */
142 if ((r = wait_for_terminate(pid, &status)) < 0)
143 log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
144 else if (status.si_code != CLD_DUMPED)
145 log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
147 log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
152 chvt(arg_crash_chvt);
154 if (arg_crash_shell) {
158 log_info("Executing crash shell in 10s...");
161 /* Let the kernel reap children for us */
163 sa.sa_handler = SIG_IGN;
164 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
165 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
167 if ((pid = fork()) < 0)
168 log_error("Failed to fork off crash shell: %s", strerror(errno));
172 if ((fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1)) < 0)
173 log_error("Failed to acquire terminal: %s", strerror(-fd));
174 else if ((r = make_stdio(fd)) < 0)
175 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
177 execl("/bin/sh", "/bin/sh", NULL);
179 log_error("execl() failed: %s", strerror(errno));
183 log_info("Successfully spawned crash shell as pid %lu.", (unsigned long) pid);
186 log_info("Freezing execution.");
190 static void install_crash_handler(void) {
195 sa.sa_handler = crash;
196 sa.sa_flags = SA_NODEFER;
198 sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
201 static int console_setup(bool do_reset) {
204 /* If we are init, we connect stdin/stdout/stderr to /dev/null
205 * and make sure we don't have a controlling tty. */
212 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
214 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
218 /* We don't want to force text mode.
219 * plymouth may be showing pictures already from initrd. */
220 r = reset_terminal_fd(tty_fd, false);
222 log_error("Failed to reset /dev/console: %s", strerror(-r));
224 close_nointr_nofail(tty_fd);
228 static int set_default_unit(const char *u) {
237 free(arg_default_unit);
238 arg_default_unit = c;
243 static int parse_proc_cmdline_word(const char *word) {
245 static const char * const rlmap[] = {
246 "emergency", SPECIAL_EMERGENCY_TARGET,
247 "-b", SPECIAL_EMERGENCY_TARGET,
248 "single", SPECIAL_RESCUE_TARGET,
249 "-s", SPECIAL_RESCUE_TARGET,
250 "s", SPECIAL_RESCUE_TARGET,
251 "S", SPECIAL_RESCUE_TARGET,
252 "1", SPECIAL_RESCUE_TARGET,
253 "2", SPECIAL_RUNLEVEL2_TARGET,
254 "3", SPECIAL_RUNLEVEL3_TARGET,
255 "4", SPECIAL_RUNLEVEL4_TARGET,
256 "5", SPECIAL_RUNLEVEL5_TARGET,
261 if (startswith(word, "systemd.unit=")) {
264 return set_default_unit(word + 13);
266 } else if (startswith(word, "rd.systemd.unit=")) {
269 return set_default_unit(word + 16);
271 } else if (startswith(word, "systemd.log_target=")) {
273 if (log_set_target_from_string(word + 19) < 0)
274 log_warning("Failed to parse log target %s. Ignoring.", word + 19);
276 } else if (startswith(word, "systemd.log_level=")) {
278 if (log_set_max_level_from_string(word + 18) < 0)
279 log_warning("Failed to parse log level %s. Ignoring.", word + 18);
281 } else if (startswith(word, "systemd.log_color=")) {
283 if (log_show_color_from_string(word + 18) < 0)
284 log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
286 } else if (startswith(word, "systemd.log_location=")) {
288 if (log_show_location_from_string(word + 21) < 0)
289 log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
291 } else if (startswith(word, "systemd.dump_core=")) {
294 if ((r = parse_boolean(word + 18)) < 0)
295 log_warning("Failed to parse dump core switch %s. Ignoring.", word + 18);
299 } else if (startswith(word, "systemd.crash_shell=")) {
302 if ((r = parse_boolean(word + 20)) < 0)
303 log_warning("Failed to parse crash shell switch %s. Ignoring.", word + 20);
307 } else if (startswith(word, "systemd.confirm_spawn=")) {
310 if ((r = parse_boolean(word + 22)) < 0)
311 log_warning("Failed to parse confirm spawn switch %s. Ignoring.", word + 22);
313 arg_confirm_spawn = r;
315 } else if (startswith(word, "systemd.crash_chvt=")) {
318 if (safe_atoi(word + 19, &k) < 0)
319 log_warning("Failed to parse crash chvt switch %s. Ignoring.", word + 19);
323 } else if (startswith(word, "systemd.show_status=")) {
326 if ((r = parse_boolean(word + 20)) < 0)
327 log_warning("Failed to parse show status switch %s. Ignoring.", word + 20);
330 } else if (startswith(word, "systemd.default_standard_output=")) {
333 if ((r = exec_output_from_string(word + 32)) < 0)
334 log_warning("Failed to parse default standard output switch %s. Ignoring.", word + 32);
336 arg_default_std_output = r;
337 } else if (startswith(word, "systemd.default_standard_error=")) {
340 if ((r = exec_output_from_string(word + 31)) < 0)
341 log_warning("Failed to parse default standard error switch %s. Ignoring.", word + 31);
343 arg_default_std_error = r;
344 } else if (startswith(word, "systemd.setenv=")) {
348 cenv = strdup(word + 15);
352 eq = strchr(cenv, '=');
356 log_warning("unsetenv failed %s. Ignoring.", strerror(errno));
359 r = setenv(cenv, eq + 1, 1);
361 log_warning("setenv failed %s. Ignoring.", strerror(errno));
365 } else if (startswith(word, "systemd.") ||
366 (in_initrd() && startswith(word, "rd.systemd."))) {
368 log_warning("Unknown kernel switch %s. Ignoring.", word);
370 log_info("Supported kernel switches:\n"
371 "systemd.unit=UNIT Default unit to start\n"
372 "rd.systemd.unit=UNIT Default unit to start when run in initrd\n"
373 "systemd.dump_core=0|1 Dump core on crash\n"
374 "systemd.crash_shell=0|1 Run shell on crash\n"
375 "systemd.crash_chvt=N Change to VT #N on crash\n"
376 "systemd.confirm_spawn=0|1 Confirm every process spawn\n"
377 "systemd.show_status=0|1 Show status updates on the console during bootup\n"
378 "systemd.log_target=console|kmsg|journal|journal-or-kmsg|syslog|syslog-or-kmsg|null\n"
380 "systemd.log_level=LEVEL Log level\n"
381 "systemd.log_color=0|1 Highlight important log messages\n"
382 "systemd.log_location=0|1 Include code location in log messages\n"
383 "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
384 " Set default log output for services\n"
385 "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
386 " Set default log error output for services\n"
387 "systemd.setenv=ASSIGNMENT Set an environment variable for all spawned processes\n");
389 } else if (streq(word, "quiet"))
390 arg_show_status = false;
391 else if (!in_initrd()) {
394 /* SysV compatibility */
395 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
396 if (streq(word, rlmap[i]))
397 return set_default_unit(rlmap[i+1]);
403 static int config_parse_level2(
404 const char *filename,
417 log_set_max_level_from_string(rvalue);
421 static int config_parse_target(
422 const char *filename,
435 log_set_target_from_string(rvalue);
439 static int config_parse_color(
440 const char *filename,
453 log_show_color_from_string(rvalue);
457 static int config_parse_location(
458 const char *filename,
471 log_show_location_from_string(rvalue);
475 static int config_parse_cpu_affinity2(
476 const char *filename,
495 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
500 if (!(t = strndup(w, l)))
503 r = safe_atou(t, &cpu);
507 if (!(c = cpu_set_malloc(&ncpus)))
510 if (r < 0 || cpu >= ncpus) {
511 log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
516 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
520 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
521 log_warning("Failed to set CPU affinity: %m");
529 static void strv_free_free(char ***l) {
541 static void free_join_controllers(void) {
542 if (!arg_join_controllers)
545 strv_free_free(arg_join_controllers);
546 arg_join_controllers = NULL;
549 static int config_parse_join_controllers(
550 const char *filename,
567 free_join_controllers();
569 FOREACH_WORD_QUOTED(w, length, rvalue, state) {
572 s = strndup(w, length);
576 l = strv_split(s, ",");
581 if (strv_length(l) <= 1) {
586 if (!arg_join_controllers) {
587 arg_join_controllers = new(char**, 2);
588 if (!arg_join_controllers) {
593 arg_join_controllers[0] = l;
594 arg_join_controllers[1] = NULL;
601 t = new0(char**, n+2);
609 for (a = arg_join_controllers; *a; a++) {
611 if (strv_overlap(*a, l)) {
614 c = strv_merge(*a, l);
637 t[n++] = strv_uniq(l);
639 strv_free_free(arg_join_controllers);
640 arg_join_controllers = t;
647 static int parse_config_file(void) {
649 const ConfigTableItem items[] = {
650 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
651 { "Manager", "LogTarget", config_parse_target, 0, NULL },
652 { "Manager", "LogColor", config_parse_color, 0, NULL },
653 { "Manager", "LogLocation", config_parse_location, 0, NULL },
654 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
655 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
656 { "Manager", "ShowStatus", config_parse_bool, 0, &arg_show_status },
657 { "Manager", "CrashChVT", config_parse_int, 0, &arg_crash_chvt },
658 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
659 { "Manager", "DefaultControllers", config_parse_strv, 0, &arg_default_controllers },
660 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
661 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
662 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
663 { "Manager", "RuntimeWatchdogSec", config_parse_usec, 0, &arg_runtime_watchdog },
664 { "Manager", "ShutdownWatchdogSec", config_parse_usec, 0, &arg_shutdown_watchdog },
665 { "Manager", "CapabilityBoundingSet", config_parse_bounding_set, 0, &arg_capability_bounding_set_drop },
666 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
667 { "Manager", "DefaultLimitCPU", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CPU]},
668 { "Manager", "DefaultLimitFSIZE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_FSIZE]},
669 { "Manager", "DefaultLimitDATA", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_DATA]},
670 { "Manager", "DefaultLimitSTACK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_STACK]},
671 { "Manager", "DefaultLimitCORE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CORE]},
672 { "Manager", "DefaultLimitRSS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RSS]},
673 { "Manager", "DefaultLimitNOFILE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NOFILE]},
674 { "Manager", "DefaultLimitAS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_AS]},
675 { "Manager", "DefaultLimitNPROC", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NPROC]},
676 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MEMLOCK]},
677 { "Manager", "DefaultLimitLOCKS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_LOCKS]},
678 { "Manager", "DefaultLimitSIGPENDING",config_parse_limit, 0, &arg_default_rlimit[RLIMIT_SIGPENDING]},
679 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MSGQUEUE]},
680 { "Manager", "DefaultLimitNICE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NICE]},
681 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTPRIO]},
682 { "Manager", "DefaultLimitRTTIME", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTTIME]},
683 { NULL, NULL, NULL, 0, NULL }
690 fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : USER_CONFIG_FILE;
696 log_warning("Failed to open configuration file '%s': %m", fn);
700 r = config_parse(fn, f, "Manager\0", config_item_table_lookup, (void*) items, false, NULL);
702 log_warning("Failed to parse configuration file: %s", strerror(-r));
709 static int parse_proc_cmdline(void) {
710 char *line, *w, *state;
714 /* Don't read /proc/cmdline if we are in a container, since
715 * that is only relevant for the host system */
716 if (detect_container(NULL) > 0)
719 if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
720 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
724 FOREACH_WORD_QUOTED(w, l, line, state) {
727 if (!(word = strndup(w, l))) {
732 r = parse_proc_cmdline_word(word);
746 static int parse_argv(int argc, char *argv[]) {
749 ARG_LOG_LEVEL = 0x100,
757 ARG_DUMP_CONFIGURATION_ITEMS,
765 ARG_DEFAULT_STD_OUTPUT,
766 ARG_DEFAULT_STD_ERROR
769 static const struct option options[] = {
770 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
771 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
772 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
773 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
774 { "unit", required_argument, NULL, ARG_UNIT },
775 { "system", no_argument, NULL, ARG_SYSTEM },
776 { "user", no_argument, NULL, ARG_USER },
777 { "test", no_argument, NULL, ARG_TEST },
778 { "help", no_argument, NULL, 'h' },
779 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
780 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
781 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
782 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
783 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
784 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
785 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
786 { "introspect", optional_argument, NULL, ARG_INTROSPECT },
787 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
788 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
800 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
805 if ((r = log_set_max_level_from_string(optarg)) < 0) {
806 log_error("Failed to parse log level %s.", optarg);
814 if ((r = log_set_target_from_string(optarg)) < 0) {
815 log_error("Failed to parse log target %s.", optarg);
824 if ((r = log_show_color_from_string(optarg)) < 0) {
825 log_error("Failed to parse log color setting %s.", optarg);
829 log_show_color(true);
833 case ARG_LOG_LOCATION:
836 if ((r = log_show_location_from_string(optarg)) < 0) {
837 log_error("Failed to parse log location setting %s.", optarg);
841 log_show_location(true);
845 case ARG_DEFAULT_STD_OUTPUT:
847 if ((r = exec_output_from_string(optarg)) < 0) {
848 log_error("Failed to parse default standard output setting %s.", optarg);
851 arg_default_std_output = r;
854 case ARG_DEFAULT_STD_ERROR:
856 if ((r = exec_output_from_string(optarg)) < 0) {
857 log_error("Failed to parse default standard error output setting %s.", optarg);
860 arg_default_std_error = r;
865 if ((r = set_default_unit(optarg)) < 0) {
866 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
873 arg_running_as = MANAGER_SYSTEM;
877 arg_running_as = MANAGER_USER;
881 arg_action = ACTION_TEST;
884 case ARG_DUMP_CONFIGURATION_ITEMS:
885 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
889 r = optarg ? parse_boolean(optarg) : 1;
891 log_error("Failed to parse dump core boolean %s.", optarg);
897 case ARG_CRASH_SHELL:
898 r = optarg ? parse_boolean(optarg) : 1;
900 log_error("Failed to parse crash shell boolean %s.", optarg);
906 case ARG_CONFIRM_SPAWN:
907 r = optarg ? parse_boolean(optarg) : 1;
909 log_error("Failed to parse confirm spawn boolean %s.", optarg);
912 arg_confirm_spawn = r;
915 case ARG_SHOW_STATUS:
916 r = optarg ? parse_boolean(optarg) : 1;
918 log_error("Failed to parse show status boolean %s.", optarg);
924 case ARG_DESERIALIZE: {
928 if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
929 log_error("Failed to parse deserialize option %s.", optarg);
933 if (!(f = fdopen(fd, "r"))) {
934 log_error("Failed to open serialization fd: %m");
939 fclose(serialization);
946 case ARG_SWITCHED_ROOT:
947 arg_switched_root = true;
950 case ARG_INTROSPECT: {
951 const char * const * i = NULL;
953 for (i = bus_interface_table; *i; i += 2)
954 if (!optarg || streq(i[0], optarg)) {
955 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
958 fputs("</node>\n", stdout);
965 log_error("Unknown interface %s.", optarg);
967 arg_action = ACTION_DONE;
972 arg_action = ACTION_HELP;
976 log_set_max_level(LOG_DEBUG);
982 /* Just to eat away the sysvinit kernel
983 * cmdline args without getopt() error
984 * messages that we'll parse in
985 * parse_proc_cmdline_word() or ignore. */
990 log_error("Unknown option code %c", c);
997 if (optind < argc && getpid() != 1) {
998 /* Hmm, when we aren't run as init system
999 * let's complain about excess arguments */
1001 log_error("Excess arguments.");
1005 if (detect_container(NULL) > 0) {
1008 /* All /proc/cmdline arguments the kernel didn't
1009 * understand it passed to us. We're not really
1010 * interested in that usually since /proc/cmdline is
1011 * more interesting and complete. With one exception:
1012 * if we are run in a container /proc/cmdline is not
1013 * relevant for the container, hence we rely on argv[]
1016 for (a = argv; a < argv + argc; a++)
1017 if ((r = parse_proc_cmdline_word(*a)) < 0)
1024 static int help(void) {
1026 printf("%s [OPTIONS...]\n\n"
1027 "Starts up and maintains the system or user services.\n\n"
1028 " -h --help Show this help\n"
1029 " --test Determine startup sequence, dump it and exit\n"
1030 " --dump-configuration-items Dump understood unit configuration items\n"
1031 " --introspect[=INTERFACE] Extract D-Bus interface data\n"
1032 " --unit=UNIT Set default unit\n"
1033 " --system Run a system instance, even if PID != 1\n"
1034 " --user Run a user instance\n"
1035 " --dump-core[=0|1] Dump core on crash\n"
1036 " --crash-shell[=0|1] Run shell on crash\n"
1037 " --confirm-spawn[=0|1] Ask for confirmation when spawning processes\n"
1038 " --show-status[=0|1] Show status updates on the console during bootup\n"
1039 " --log-target=TARGET Set log target (console, journal, syslog, kmsg, journal-or-kmsg, syslog-or-kmsg, null)\n"
1040 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1041 " --log-color[=0|1] Highlight important log messages\n"
1042 " --log-location[=0|1] Include code location in log messages\n"
1043 " --default-standard-output= Set default standard output for services\n"
1044 " --default-standard-error= Set default standard error output for services\n",
1045 program_invocation_short_name);
1050 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
1059 /* Make sure nothing is really destructed when we shut down */
1062 if ((r = manager_open_serialization(m, &f)) < 0) {
1063 log_error("Failed to create serialization file: %s", strerror(-r));
1067 if (!(fds = fdset_new())) {
1069 log_error("Failed to allocate fd set: %s", strerror(-r));
1073 if ((r = manager_serialize(m, f, fds)) < 0) {
1074 log_error("Failed to serialize state: %s", strerror(-r));
1078 if (fseeko(f, 0, SEEK_SET) < 0) {
1079 log_error("Failed to rewind serialization fd: %m");
1083 if ((r = fd_cloexec(fileno(f), false)) < 0) {
1084 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
1088 if ((r = fdset_cloexec(fds, false)) < 0) {
1089 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
1107 static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
1109 unsigned long long a, b;
1113 e = getenv("RD_TIMESTAMP");
1117 if (sscanf(e, "%llu %llu", &a, &b) != 2)
1120 t->realtime = (usec_t) a;
1121 t->monotonic = (usec_t) b;
1126 static void test_mtab(void) {
1129 /* Check that /etc/mtab is a symlink */
1131 if (readlink_malloc("/etc/mtab", &p) >= 0) {
1134 b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
1141 log_warning("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
1142 "This is not supported anymore. "
1143 "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
1146 static void test_usr(void) {
1148 /* Check that /usr is not a separate fs */
1150 if (dir_is_empty("/usr") <= 0)
1153 log_warning("/usr appears to be on its own filesytem and is not already mounted. This is not a supported setup. "
1154 "Some things will probably break (sometimes even silently) in mysterious ways. "
1155 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1158 static void test_cgroups(void) {
1160 if (access("/proc/cgroups", F_OK) >= 0)
1163 log_warning("CONFIG_CGROUPS was not set when your kernel was compiled. "
1164 "Systems without control groups are not supported. "
1165 "We will now sleep for 10s, and then continue boot-up. "
1166 "Expect breakage and please do not file bugs. "
1167 "Instead fix your kernel and enable CONFIG_CGROUPS. "
1168 "Consult http://0pointer.de/blog/projects/cgroups-vs-cgroups.html for more information.");
1173 int main(int argc, char *argv[]) {
1175 int r, retval = EXIT_FAILURE;
1176 usec_t before_startup, after_startup;
1177 char timespan[FORMAT_TIMESPAN_MAX];
1179 bool reexecute = false;
1180 const char *shutdown_verb = NULL;
1181 dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
1182 static char systemd[] = "systemd";
1183 bool skip_setup = false;
1185 bool loaded_policy = false;
1186 bool arm_reboot_watchdog = false;
1187 bool queue_default_job = false;
1188 char *switch_root_dir = NULL, *switch_root_init = NULL;
1190 #ifdef HAVE_SYSV_COMPAT
1191 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
1192 /* This is compatibility support for SysV, where
1193 * calling init as a user is identical to telinit. */
1196 execv(SYSTEMCTL_BINARY_PATH, argv);
1197 log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1202 /* Determine if this is a reexecution or normal bootup. We do
1203 * the full command line parsing much later, so let's just
1204 * have a quick peek here. */
1205 for (j = 1; j < argc; j++)
1206 if (streq(argv[j], "--deserialize")) {
1211 /* If we have switched root, do all the special setup
1213 for (j = 1; j < argc; j++)
1214 if (streq(argv[j], "--switched-root")) {
1219 /* If we get started via the /sbin/init symlink then we are
1220 called 'init'. After a subsequent reexecution we are then
1221 called 'systemd'. That is confusing, hence let's call us
1222 systemd right-away. */
1223 program_invocation_short_name = systemd;
1224 prctl(PR_SET_NAME, systemd);
1229 log_show_color(isatty(STDERR_FILENO) > 0);
1230 log_show_location(false);
1231 log_set_max_level(LOG_INFO);
1233 if (getpid() == 1) {
1235 char *rd_timestamp = NULL;
1237 dual_timestamp_get(&initrd_timestamp);
1238 asprintf(&rd_timestamp, "%llu %llu",
1239 (unsigned long long) initrd_timestamp.realtime,
1240 (unsigned long long) initrd_timestamp.monotonic);
1242 setenv("RD_TIMESTAMP", rd_timestamp, 1);
1247 arg_running_as = MANAGER_SYSTEM;
1248 log_set_target(detect_container(NULL) > 0 ? LOG_TARGET_JOURNAL : LOG_TARGET_JOURNAL_OR_KMSG);
1251 if (selinux_setup(&loaded_policy) < 0)
1253 if (ima_setup() < 0)
1259 if (label_init(NULL) < 0)
1263 if (hwclock_is_localtime() > 0) {
1266 r = hwclock_apply_localtime_delta(&min);
1268 log_error("Failed to apply local time delta, ignoring: %s", strerror(-r));
1270 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1274 arg_running_as = MANAGER_USER;
1275 log_set_target(LOG_TARGET_AUTO);
1279 /* Initialize default unit */
1280 if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
1283 /* By default, mount "cpu" and "cpuacct" together */
1284 arg_join_controllers = new(char**, 2);
1285 if (!arg_join_controllers)
1288 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
1289 arg_join_controllers[1] = NULL;
1291 if (!arg_join_controllers[0])
1294 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1295 * /proc/$PID/fd is available. */
1296 if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1297 r = mount_setup(loaded_policy);
1302 /* Reset all signal handlers. */
1303 assert_se(reset_all_signal_handlers() == 0);
1305 /* If we are init, we can block sigkill. Yay. */
1306 ignore_signals(SIGNALS_IGNORE, -1);
1308 if (parse_config_file() < 0)
1311 if (arg_running_as == MANAGER_SYSTEM)
1312 if (parse_proc_cmdline() < 0)
1315 log_parse_environment();
1317 if (parse_argv(argc, argv) < 0)
1320 if (arg_action == ACTION_TEST && geteuid() == 0) {
1321 log_error("Don't run test mode as root.");
1325 if (arg_running_as == MANAGER_SYSTEM &&
1326 arg_action == ACTION_RUN &&
1327 running_in_chroot() > 0) {
1328 log_error("Cannot be run in a chroot() environment.");
1332 if (arg_action == ACTION_HELP) {
1335 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
1336 unit_dump_config_items(stdout);
1337 retval = EXIT_SUCCESS;
1339 } else if (arg_action == ACTION_DONE) {
1340 retval = EXIT_SUCCESS;
1344 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
1346 /* Close logging fds, in order not to confuse fdset below */
1349 /* Remember open file descriptors for later deserialization */
1350 if (serialization) {
1351 r = fdset_new_fill(&fds);
1353 log_error("Failed to allocate fd set: %s", strerror(-r));
1357 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
1359 close_all_fds(NULL, 0);
1361 /* Set up PATH unless it is already set */
1363 #ifdef HAVE_SPLIT_USR
1364 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1366 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
1368 arg_running_as == MANAGER_SYSTEM);
1370 if (arg_running_as == MANAGER_SYSTEM) {
1371 /* Parse the data passed to us. We leave this
1372 * variables set, but the manager later on will not
1373 * pass them on to our children. */
1375 parse_initrd_timestamp(&initrd_timestamp);
1377 /* Unset some environment variables passed in from the
1378 * kernel that don't really make sense for us. */
1382 /* When we are invoked by a shell, these might be set,
1383 * but make little sense to pass on */
1388 /* When we are invoked by a chroot-like tool such as
1389 * nspawn, these might be set, but make little sense
1392 unsetenv("LOGNAME");
1394 /* All other variables are left as is, so that clients
1395 * can still read them via /proc/1/environ */
1398 /* Move out of the way, so that we won't block unmounts */
1399 assert_se(chdir("/") == 0);
1401 if (arg_running_as == MANAGER_SYSTEM) {
1402 /* Become a session leader if we aren't one yet. */
1405 /* Disable the umask logic */
1409 /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
1410 dbus_connection_set_change_sigpipe(FALSE);
1412 /* Reset the console, but only if this is really init and we
1413 * are freshly booted */
1414 if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
1415 console_setup(getpid() == 1 && !skip_setup);
1419 /* Open the logging devices, if possible and necessary */
1422 /* Make sure we leave a core dump without panicing the
1425 install_crash_handler();
1427 if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1428 r = mount_cgroup_controllers(arg_join_controllers);
1433 if (arg_running_as == MANAGER_SYSTEM) {
1434 const char *virtualization = NULL;
1436 log_info(PACKAGE_STRING " running in system mode. (" SYSTEMD_FEATURES "; " DISTRIBUTION ")");
1438 detect_virtualization(&virtualization);
1440 log_info("Detected virtualization '%s'.", virtualization);
1443 log_debug(PACKAGE_STRING " running in user mode. (" SYSTEMD_FEATURES "; " DISTRIBUTION ")");
1445 if (arg_running_as == MANAGER_SYSTEM && !skip_setup) {
1448 if (arg_show_status || plymouth_running())
1461 if (arg_running_as == MANAGER_SYSTEM && arg_runtime_watchdog > 0)
1462 watchdog_set_timeout(&arg_runtime_watchdog);
1464 if (arg_timer_slack_nsec != (nsec_t) -1)
1465 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
1466 log_error("Failed to adjust timer slack: %m");
1468 if (arg_capability_bounding_set_drop) {
1469 r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
1471 log_error("Failed to drop capability bounding set: %s", strerror(-r));
1474 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
1476 log_error("Failed to drop capability bounding set of usermode helpers: %s", strerror(-r));
1481 r = manager_new(arg_running_as, &m);
1483 log_error("Failed to allocate manager object: %s", strerror(-r));
1487 m->confirm_spawn = arg_confirm_spawn;
1488 m->default_std_output = arg_default_std_output;
1489 m->default_std_error = arg_default_std_error;
1490 m->runtime_watchdog = arg_runtime_watchdog;
1491 m->shutdown_watchdog = arg_shutdown_watchdog;
1493 manager_set_default_rlimits(m, arg_default_rlimit);
1495 if (dual_timestamp_is_set(&initrd_timestamp))
1496 m->initrd_timestamp = initrd_timestamp;
1498 if (arg_default_controllers)
1499 manager_set_default_controllers(m, arg_default_controllers);
1501 manager_set_show_status(m, arg_show_status);
1503 /* Remember whether we should queue the default job */
1504 queue_default_job = !serialization || arg_switched_root;
1506 before_startup = now(CLOCK_MONOTONIC);
1508 r = manager_startup(m, serialization, fds);
1510 log_error("Failed to fully start up daemon: %s", strerror(-r));
1512 /* This will close all file descriptors that were opened, but
1513 * not claimed by any unit. */
1519 if (serialization) {
1520 fclose(serialization);
1521 serialization = NULL;
1524 if (queue_default_job) {
1526 Unit *target = NULL;
1527 Job *default_unit_job;
1529 dbus_error_init(&error);
1531 log_debug("Activating default unit: %s", arg_default_unit);
1533 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
1535 log_error("Failed to load default target: %s", bus_error(&error, r));
1536 dbus_error_free(&error);
1537 } else if (target->load_state == UNIT_ERROR)
1538 log_error("Failed to load default target: %s", strerror(-target->load_error));
1539 else if (target->load_state == UNIT_MASKED)
1540 log_error("Default target masked.");
1542 if (!target || target->load_state != UNIT_LOADED) {
1543 log_info("Trying to load rescue target...");
1545 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1547 log_error("Failed to load rescue target: %s", bus_error(&error, r));
1548 dbus_error_free(&error);
1550 } else if (target->load_state == UNIT_ERROR) {
1551 log_error("Failed to load rescue target: %s", strerror(-target->load_error));
1553 } else if (target->load_state == UNIT_MASKED) {
1554 log_error("Rescue target masked.");
1559 assert(target->load_state == UNIT_LOADED);
1561 if (arg_action == ACTION_TEST) {
1562 printf("-> By units:\n");
1563 manager_dump_units(m, stdout, "\t");
1566 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, &default_unit_job);
1568 log_error("Failed to start default target: %s", bus_error(&error, r));
1569 dbus_error_free(&error);
1572 m->default_unit_job_id = default_unit_job->id;
1574 after_startup = now(CLOCK_MONOTONIC);
1575 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1576 "Loaded units and determined initial transaction in %s.",
1577 format_timespan(timespan, sizeof(timespan), after_startup - before_startup));
1579 if (arg_action == ACTION_TEST) {
1580 printf("-> By jobs:\n");
1581 manager_dump_jobs(m, stdout, "\t");
1582 retval = EXIT_SUCCESS;
1588 r = manager_loop(m);
1590 log_error("Failed to run mainloop: %s", strerror(-r));
1594 switch (m->exit_code) {
1597 retval = EXIT_SUCCESS;
1601 case MANAGER_RELOAD:
1602 log_info("Reloading.");
1603 r = manager_reload(m);
1605 log_error("Failed to reload: %s", strerror(-r));
1608 case MANAGER_REEXECUTE:
1610 if (prepare_reexecute(m, &serialization, &fds) < 0)
1614 log_notice("Reexecuting.");
1617 case MANAGER_SWITCH_ROOT:
1618 /* Steal the switch root parameters */
1619 switch_root_dir = m->switch_root;
1620 switch_root_init = m->switch_root_init;
1621 m->switch_root = m->switch_root_init = NULL;
1623 if (!switch_root_init)
1624 if (prepare_reexecute(m, &serialization, &fds) < 0)
1628 log_notice("Switching root.");
1631 case MANAGER_REBOOT:
1632 case MANAGER_POWEROFF:
1634 case MANAGER_KEXEC: {
1635 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
1636 [MANAGER_REBOOT] = "reboot",
1637 [MANAGER_POWEROFF] = "poweroff",
1638 [MANAGER_HALT] = "halt",
1639 [MANAGER_KEXEC] = "kexec"
1642 assert_se(shutdown_verb = table[m->exit_code]);
1643 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
1645 log_notice("Shutting down.");
1650 assert_not_reached("Unknown exit code.");
1658 for (j = 0; j < RLIMIT_NLIMITS; j++)
1659 free (arg_default_rlimit[j]);
1661 free(arg_default_unit);
1662 strv_free(arg_default_controllers);
1663 free_join_controllers();
1670 unsigned i, args_size;
1672 /* Close and disarm the watchdog, so that the new
1673 * instance can reinitialize it, but doesn't get
1674 * rebooted while we do that */
1675 watchdog_close(true);
1677 if (switch_root_dir) {
1678 r = switch_root(switch_root_dir);
1680 log_error("Failed to switch root, ignoring: %s", strerror(-r));
1683 args_size = MAX(6, argc+1);
1684 args = newa(const char*, args_size);
1686 if (!switch_root_init) {
1689 /* First try to spawn ourselves with the right
1690 * path, and with full serialization. We do
1691 * this only if the user didn't specify an
1692 * explicit init to spawn. */
1694 assert(serialization);
1697 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
1701 args[i++] = SYSTEMD_BINARY_PATH;
1702 if (switch_root_dir)
1703 args[i++] = "--switched-root";
1704 args[i++] = arg_running_as == MANAGER_SYSTEM ? "--system" : "--user";
1705 args[i++] = "--deserialize";
1709 assert(i <= args_size);
1710 execv(args[0], (char* const*) args);
1713 /* Try the fallback, if there is any, without any
1714 * serialization. We pass the original argv[] and
1715 * envp[]. (Well, modulo the ordering changes due to
1716 * getopt() in argv[], and some cleanups in envp[],
1717 * but let's hope that doesn't matter.) */
1719 if (serialization) {
1720 fclose(serialization);
1721 serialization = NULL;
1729 for (j = 1, i = 1; j < argc; j++)
1730 args[i++] = argv[j];
1732 assert(i <= args_size);
1734 if (switch_root_init) {
1735 args[0] = switch_root_init;
1736 execv(args[0], (char* const*) args);
1737 log_warning("Failed to execute configured init, trying fallback: %m");
1740 args[0] = "/sbin/init";
1741 execv(args[0], (char* const*) args);
1743 if (errno == ENOENT) {
1744 log_warning("No /sbin/init, trying fallback");
1746 args[0] = "/bin/sh";
1748 execv(args[0], (char* const*) args);
1749 log_error("Failed to execute /bin/sh, giving up: %m");
1751 log_warning("Failed to execute /sbin/init, giving up: %m");
1755 fclose(serialization);
1760 if (shutdown_verb) {
1761 const char * command_line[] = {
1762 SYSTEMD_SHUTDOWN_BINARY_PATH,
1768 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0) {
1771 /* If we reboot let's set the shutdown
1772 * watchdog and tell the shutdown binary to
1773 * repeatedly ping it */
1774 watchdog_set_timeout(&arg_shutdown_watchdog);
1775 watchdog_close(false);
1777 /* Tell the binary how often to ping */
1778 snprintf(e, sizeof(e), "WATCHDOG_USEC=%llu", (unsigned long long) arg_shutdown_watchdog);
1781 env_block = strv_append(environ, e);
1783 env_block = strv_copy(environ);
1784 watchdog_close(true);
1787 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1789 log_error("Failed to execute shutdown binary, freezing: %m");