]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/main.c
build-sys: use #if Y instead of #ifdef Y everywhere
[thirdparty/systemd.git] / src / core / main.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <getopt.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <sys/mount.h>
27 #include <sys/prctl.h>
28 #include <sys/reboot.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #if HAVE_SECCOMP
32 #include <seccomp.h>
33 #endif
34 #if HAVE_VALGRIND_VALGRIND_H
35 #include <valgrind/valgrind.h>
36 #endif
37
38 #include "sd-bus.h"
39 #include "sd-daemon.h"
40
41 #include "alloc-util.h"
42 #include "architecture.h"
43 #include "build.h"
44 #include "bus-error.h"
45 #include "bus-util.h"
46 #include "capability-util.h"
47 #include "clock-util.h"
48 #include "conf-parser.h"
49 #include "cpu-set-util.h"
50 #include "dbus-manager.h"
51 #include "def.h"
52 #include "emergency-action.h"
53 #include "env-util.h"
54 #include "fd-util.h"
55 #include "fdset.h"
56 #include "fileio.h"
57 #include "format-util.h"
58 #include "fs-util.h"
59 #include "hostname-setup.h"
60 #include "ima-setup.h"
61 #include "killall.h"
62 #include "kmod-setup.h"
63 #include "load-fragment.h"
64 #include "log.h"
65 #include "loopback-setup.h"
66 #include "machine-id-setup.h"
67 #include "manager.h"
68 #include "missing.h"
69 #include "mount-setup.h"
70 #include "pager.h"
71 #include "parse-util.h"
72 #include "path-util.h"
73 #include "proc-cmdline.h"
74 #include "process-util.h"
75 #include "raw-clone.h"
76 #include "rlimit-util.h"
77 #if HAVE_SECCOMP
78 #include "seccomp-util.h"
79 #endif
80 #include "selinux-setup.h"
81 #include "selinux-util.h"
82 #include "signal-util.h"
83 #include "smack-setup.h"
84 #include "special.h"
85 #include "stat-util.h"
86 #include "stdio-util.h"
87 #include "strv.h"
88 #include "switch-root.h"
89 #include "terminal-util.h"
90 #include "umask-util.h"
91 #include "user-util.h"
92 #include "virt.h"
93 #include "watchdog.h"
94
95 static enum {
96 ACTION_RUN,
97 ACTION_HELP,
98 ACTION_VERSION,
99 ACTION_TEST,
100 ACTION_DUMP_CONFIGURATION_ITEMS
101 } arg_action = ACTION_RUN;
102 static char *arg_default_unit = NULL;
103 static bool arg_system = false;
104 static bool arg_dump_core = true;
105 static int arg_crash_chvt = -1;
106 static bool arg_crash_shell = false;
107 static bool arg_crash_reboot = false;
108 static char *arg_confirm_spawn = NULL;
109 static ShowStatus arg_show_status = _SHOW_STATUS_UNSET;
110 static bool arg_switched_root = false;
111 static bool arg_no_pager = false;
112 static char ***arg_join_controllers = NULL;
113 static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
114 static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
115 static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
116 static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
117 static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
118 static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
119 static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
120 static usec_t arg_runtime_watchdog = 0;
121 static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
122 static char **arg_default_environment = NULL;
123 static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
124 static uint64_t arg_capability_bounding_set = CAP_ALL;
125 static nsec_t arg_timer_slack_nsec = NSEC_INFINITY;
126 static usec_t arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
127 static Set* arg_syscall_archs = NULL;
128 static FILE* arg_serialization = NULL;
129 static bool arg_default_cpu_accounting = false;
130 static bool arg_default_io_accounting = false;
131 static bool arg_default_ip_accounting = false;
132 static bool arg_default_blockio_accounting = false;
133 static bool arg_default_memory_accounting = false;
134 static bool arg_default_tasks_accounting = true;
135 static uint64_t arg_default_tasks_max = UINT64_MAX;
136 static sd_id128_t arg_machine_id = {};
137 static EmergencyAction arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
138
139 noreturn static void freeze_or_reboot(void) {
140
141 if (arg_crash_reboot) {
142 log_notice("Rebooting in 10s...");
143 (void) sleep(10);
144
145 log_notice("Rebooting now...");
146 (void) reboot(RB_AUTOBOOT);
147 log_emergency_errno(errno, "Failed to reboot: %m");
148 }
149
150 log_emergency("Freezing execution.");
151 freeze();
152 }
153
154 noreturn static void crash(int sig) {
155 struct sigaction sa;
156 pid_t pid;
157
158 if (getpid_cached() != 1)
159 /* Pass this on immediately, if this is not PID 1 */
160 (void) raise(sig);
161 else if (!arg_dump_core)
162 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
163 else {
164 sa = (struct sigaction) {
165 .sa_handler = nop_signal_handler,
166 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
167 };
168
169 /* We want to wait for the core process, hence let's enable SIGCHLD */
170 (void) sigaction(SIGCHLD, &sa, NULL);
171
172 pid = raw_clone(SIGCHLD);
173 if (pid < 0)
174 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
175 else if (pid == 0) {
176 /* Enable default signal handler for core dump */
177
178 sa = (struct sigaction) {
179 .sa_handler = SIG_DFL,
180 };
181 (void) sigaction(sig, &sa, NULL);
182
183 /* Don't limit the coredump size */
184 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
185
186 /* Just to be sure... */
187 (void) chdir("/");
188
189 /* Raise the signal again */
190 pid = raw_getpid();
191 (void) kill(pid, sig); /* raise() would kill the parent */
192
193 assert_not_reached("We shouldn't be here...");
194 _exit(EXIT_FAILURE);
195 } else {
196 siginfo_t status;
197 int r;
198
199 /* Order things nicely. */
200 r = wait_for_terminate(pid, &status);
201 if (r < 0)
202 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
203 else if (status.si_code != CLD_DUMPED)
204 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
205 signal_to_string(sig),
206 pid, sigchld_code_to_string(status.si_code),
207 status.si_status,
208 strna(status.si_code == CLD_EXITED
209 ? exit_status_to_string(status.si_status, EXIT_STATUS_MINIMAL)
210 : signal_to_string(status.si_status)));
211 else
212 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
213 }
214 }
215
216 if (arg_crash_chvt >= 0)
217 (void) chvt(arg_crash_chvt);
218
219 sa = (struct sigaction) {
220 .sa_handler = SIG_IGN,
221 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
222 };
223
224 /* Let the kernel reap children for us */
225 (void) sigaction(SIGCHLD, &sa, NULL);
226
227 if (arg_crash_shell) {
228 log_notice("Executing crash shell in 10s...");
229 (void) sleep(10);
230
231 pid = raw_clone(SIGCHLD);
232 if (pid < 0)
233 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
234 else if (pid == 0) {
235 (void) setsid();
236 (void) make_console_stdio();
237 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
238
239 log_emergency_errno(errno, "execle() failed: %m");
240 _exit(EXIT_FAILURE);
241 } else {
242 log_info("Spawned crash shell as PID "PID_FMT".", pid);
243 (void) wait_for_terminate(pid, NULL);
244 }
245 }
246
247 freeze_or_reboot();
248 }
249
250 static void install_crash_handler(void) {
251 static const struct sigaction sa = {
252 .sa_handler = crash,
253 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
254 };
255 int r;
256
257 /* We ignore the return value here, since, we don't mind if we
258 * cannot set up a crash handler */
259 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
260 if (r < 0)
261 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
262 }
263
264 static int console_setup(void) {
265 _cleanup_close_ int tty_fd = -1;
266 int r;
267
268 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
269 if (tty_fd < 0)
270 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
271
272 /* We don't want to force text mode. plymouth may be showing
273 * pictures already from initrd. */
274 r = reset_terminal_fd(tty_fd, false);
275 if (r < 0)
276 return log_error_errno(r, "Failed to reset /dev/console: %m");
277
278 return 0;
279 }
280
281 static int parse_crash_chvt(const char *value) {
282 int b;
283
284 if (safe_atoi(value, &arg_crash_chvt) >= 0)
285 return 0;
286
287 b = parse_boolean(value);
288 if (b < 0)
289 return b;
290
291 if (b > 0)
292 arg_crash_chvt = 0; /* switch to where kmsg goes */
293 else
294 arg_crash_chvt = -1; /* turn off switching */
295
296 return 0;
297 }
298
299 static int parse_confirm_spawn(const char *value, char **console) {
300 char *s;
301 int r;
302
303 r = value ? parse_boolean(value) : 1;
304 if (r == 0) {
305 *console = NULL;
306 return 0;
307 }
308
309 if (r > 0) /* on with default tty */
310 s = strdup("/dev/console");
311 else if (is_path(value)) /* on with fully qualified path */
312 s = strdup(value);
313 else /* on with only a tty file name, not a fully qualified path */
314 s = strjoin("/dev/", value);
315 if (!s)
316 return -ENOMEM;
317 *console = s;
318 return 0;
319 }
320
321 static int set_machine_id(const char *m) {
322 sd_id128_t t;
323 assert(m);
324
325 if (sd_id128_from_string(m, &t) < 0)
326 return -EINVAL;
327
328 if (sd_id128_is_null(t))
329 return -EINVAL;
330
331 arg_machine_id = t;
332 return 0;
333 }
334
335 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
336
337 int r;
338
339 assert(key);
340
341 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
342
343 if (proc_cmdline_value_missing(key, value))
344 return 0;
345
346 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
347 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
348 else if (in_initrd() == !!startswith(key, "rd.")) {
349 if (free_and_strdup(&arg_default_unit, value) < 0)
350 return log_oom();
351 }
352
353 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
354
355 r = value ? parse_boolean(value) : true;
356 if (r < 0)
357 log_warning("Failed to parse dump core switch %s. Ignoring.", value);
358 else
359 arg_dump_core = r;
360
361 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
362
363 if (!value)
364 arg_crash_chvt = 0; /* turn on */
365 else if (parse_crash_chvt(value) < 0)
366 log_warning("Failed to parse crash chvt switch %s. Ignoring.", value);
367
368 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
369
370 r = value ? parse_boolean(value) : true;
371 if (r < 0)
372 log_warning("Failed to parse crash shell switch %s. Ignoring.", value);
373 else
374 arg_crash_shell = r;
375
376 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
377
378 r = value ? parse_boolean(value) : true;
379 if (r < 0)
380 log_warning("Failed to parse crash reboot switch %s. Ignoring.", value);
381 else
382 arg_crash_reboot = r;
383
384 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
385 char *s;
386
387 r = parse_confirm_spawn(value, &s);
388 if (r < 0)
389 log_warning_errno(r, "Failed to parse confirm_spawn switch %s. Ignoring.", value);
390 else {
391 free(arg_confirm_spawn);
392 arg_confirm_spawn = s;
393 }
394
395 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
396
397 if (value) {
398 r = parse_show_status(value, &arg_show_status);
399 if (r < 0)
400 log_warning("Failed to parse show status switch %s. Ignoring.", value);
401 } else
402 arg_show_status = SHOW_STATUS_YES;
403
404 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
405
406 if (proc_cmdline_value_missing(key, value))
407 return 0;
408
409 r = exec_output_from_string(value);
410 if (r < 0)
411 log_warning("Failed to parse default standard output switch %s. Ignoring.", value);
412 else
413 arg_default_std_output = r;
414
415 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
416
417 if (proc_cmdline_value_missing(key, value))
418 return 0;
419
420 r = exec_output_from_string(value);
421 if (r < 0)
422 log_warning("Failed to parse default standard error switch %s. Ignoring.", value);
423 else
424 arg_default_std_error = r;
425
426 } else if (streq(key, "systemd.setenv")) {
427
428 if (proc_cmdline_value_missing(key, value))
429 return 0;
430
431 if (env_assignment_is_valid(value)) {
432 char **env;
433
434 env = strv_env_set(arg_default_environment, value);
435 if (!env)
436 return log_oom();
437
438 arg_default_environment = env;
439 } else
440 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
441
442 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
443
444 if (proc_cmdline_value_missing(key, value))
445 return 0;
446
447 r = set_machine_id(value);
448 if (r < 0)
449 log_warning("MachineID '%s' is not valid. Ignoring.", value);
450
451 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
452
453 if (proc_cmdline_value_missing(key, value))
454 return 0;
455
456 r = parse_sec(value, &arg_default_timeout_start_usec);
457 if (r < 0)
458 log_warning_errno(r, "Failed to parse default start timeout: %s, ignoring.", value);
459
460 if (arg_default_timeout_start_usec <= 0)
461 arg_default_timeout_start_usec = USEC_INFINITY;
462
463 } else if (streq(key, "quiet") && !value) {
464
465 if (arg_show_status == _SHOW_STATUS_UNSET)
466 arg_show_status = SHOW_STATUS_AUTO;
467
468 } else if (streq(key, "debug") && !value) {
469
470 /* Note that log_parse_environment() handles 'debug'
471 * too, and sets the log level to LOG_DEBUG. */
472
473 if (detect_container() > 0)
474 log_set_target(LOG_TARGET_CONSOLE);
475
476 } else if (!value) {
477 const char *target;
478
479 /* SysV compatibility */
480 target = runlevel_to_target(key);
481 if (target)
482 return free_and_strdup(&arg_default_unit, target);
483 }
484
485 return 0;
486 }
487
488 #define DEFINE_SETTER(name, func, descr) \
489 static int name(const char *unit, \
490 const char *filename, \
491 unsigned line, \
492 const char *section, \
493 unsigned section_line, \
494 const char *lvalue, \
495 int ltype, \
496 const char *rvalue, \
497 void *data, \
498 void *userdata) { \
499 \
500 int r; \
501 \
502 assert(filename); \
503 assert(lvalue); \
504 assert(rvalue); \
505 \
506 r = func(rvalue); \
507 if (r < 0) \
508 log_syntax(unit, LOG_ERR, filename, line, r, \
509 "Invalid " descr "'%s': %m", \
510 rvalue); \
511 \
512 return 0; \
513 }
514
515 DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
516 DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
517 DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
518 DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
519
520 static int config_parse_cpu_affinity2(
521 const char *unit,
522 const char *filename,
523 unsigned line,
524 const char *section,
525 unsigned section_line,
526 const char *lvalue,
527 int ltype,
528 const char *rvalue,
529 void *data,
530 void *userdata) {
531
532 _cleanup_cpu_free_ cpu_set_t *c = NULL;
533 int ncpus;
534
535 ncpus = parse_cpu_set_and_warn(rvalue, &c, unit, filename, line, lvalue);
536 if (ncpus < 0)
537 return ncpus;
538
539 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
540 log_warning_errno(errno, "Failed to set CPU affinity: %m");
541
542 return 0;
543 }
544
545 static int config_parse_show_status(
546 const char* unit,
547 const char *filename,
548 unsigned line,
549 const char *section,
550 unsigned section_line,
551 const char *lvalue,
552 int ltype,
553 const char *rvalue,
554 void *data,
555 void *userdata) {
556
557 int k;
558 ShowStatus *b = data;
559
560 assert(filename);
561 assert(lvalue);
562 assert(rvalue);
563 assert(data);
564
565 k = parse_show_status(rvalue, b);
566 if (k < 0) {
567 log_syntax(unit, LOG_ERR, filename, line, k, "Failed to parse show status setting, ignoring: %s", rvalue);
568 return 0;
569 }
570
571 return 0;
572 }
573
574 static int config_parse_crash_chvt(
575 const char* unit,
576 const char *filename,
577 unsigned line,
578 const char *section,
579 unsigned section_line,
580 const char *lvalue,
581 int ltype,
582 const char *rvalue,
583 void *data,
584 void *userdata) {
585
586 int r;
587
588 assert(filename);
589 assert(lvalue);
590 assert(rvalue);
591
592 r = parse_crash_chvt(rvalue);
593 if (r < 0) {
594 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue);
595 return 0;
596 }
597
598 return 0;
599 }
600
601 static int config_parse_join_controllers(const char *unit,
602 const char *filename,
603 unsigned line,
604 const char *section,
605 unsigned section_line,
606 const char *lvalue,
607 int ltype,
608 const char *rvalue,
609 void *data,
610 void *userdata) {
611
612 const char *whole_rvalue = rvalue;
613 unsigned n = 0;
614
615 assert(filename);
616 assert(lvalue);
617 assert(rvalue);
618
619 arg_join_controllers = strv_free_free(arg_join_controllers);
620
621 for (;;) {
622 _cleanup_free_ char *word = NULL;
623 char **l;
624 int r;
625
626 r = extract_first_word(&rvalue, &word, NULL, EXTRACT_QUOTES);
627 if (r < 0) {
628 log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, whole_rvalue);
629 return r;
630 }
631 if (r == 0)
632 break;
633
634 l = strv_split(word, ",");
635 if (!l)
636 return log_oom();
637 strv_uniq(l);
638
639 if (strv_length(l) <= 1) {
640 strv_free(l);
641 continue;
642 }
643
644 if (!arg_join_controllers) {
645 arg_join_controllers = new(char**, 2);
646 if (!arg_join_controllers) {
647 strv_free(l);
648 return log_oom();
649 }
650
651 arg_join_controllers[0] = l;
652 arg_join_controllers[1] = NULL;
653
654 n = 1;
655 } else {
656 char ***a;
657 char ***t;
658
659 t = new0(char**, n+2);
660 if (!t) {
661 strv_free(l);
662 return log_oom();
663 }
664
665 n = 0;
666
667 for (a = arg_join_controllers; *a; a++) {
668
669 if (strv_overlap(*a, l)) {
670 if (strv_extend_strv(&l, *a, false) < 0) {
671 strv_free(l);
672 strv_free_free(t);
673 return log_oom();
674 }
675
676 } else {
677 char **c;
678
679 c = strv_copy(*a);
680 if (!c) {
681 strv_free(l);
682 strv_free_free(t);
683 return log_oom();
684 }
685
686 t[n++] = c;
687 }
688 }
689
690 t[n++] = strv_uniq(l);
691
692 strv_free_free(arg_join_controllers);
693 arg_join_controllers = t;
694 }
695 }
696 if (!isempty(rvalue))
697 log_syntax(unit, LOG_ERR, filename, line, 0, "Trailing garbage, ignoring.");
698
699 return 0;
700 }
701
702 static int parse_config_file(void) {
703
704 const ConfigTableItem items[] = {
705 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
706 { "Manager", "LogTarget", config_parse_target, 0, NULL },
707 { "Manager", "LogColor", config_parse_color, 0, NULL },
708 { "Manager", "LogLocation", config_parse_location, 0, NULL },
709 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
710 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, NULL },
711 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, NULL },
712 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
713 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
714 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
715 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
716 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
717 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
718 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
719 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
720 #if HAVE_SECCOMP
721 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
722 #endif
723 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
724 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
725 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
726 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
727 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
728 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
729 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
730 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
731 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec, 0, &arg_default_start_limit_interval },
732 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
733 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
734 { "Manager", "DefaultLimitCPU", config_parse_limit, RLIMIT_CPU, arg_default_rlimit },
735 { "Manager", "DefaultLimitFSIZE", config_parse_limit, RLIMIT_FSIZE, arg_default_rlimit },
736 { "Manager", "DefaultLimitDATA", config_parse_limit, RLIMIT_DATA, arg_default_rlimit },
737 { "Manager", "DefaultLimitSTACK", config_parse_limit, RLIMIT_STACK, arg_default_rlimit },
738 { "Manager", "DefaultLimitCORE", config_parse_limit, RLIMIT_CORE, arg_default_rlimit },
739 { "Manager", "DefaultLimitRSS", config_parse_limit, RLIMIT_RSS, arg_default_rlimit },
740 { "Manager", "DefaultLimitNOFILE", config_parse_limit, RLIMIT_NOFILE, arg_default_rlimit },
741 { "Manager", "DefaultLimitAS", config_parse_limit, RLIMIT_AS, arg_default_rlimit },
742 { "Manager", "DefaultLimitNPROC", config_parse_limit, RLIMIT_NPROC, arg_default_rlimit },
743 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, RLIMIT_MEMLOCK, arg_default_rlimit },
744 { "Manager", "DefaultLimitLOCKS", config_parse_limit, RLIMIT_LOCKS, arg_default_rlimit },
745 { "Manager", "DefaultLimitSIGPENDING", config_parse_limit, RLIMIT_SIGPENDING, arg_default_rlimit },
746 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, RLIMIT_MSGQUEUE, arg_default_rlimit },
747 { "Manager", "DefaultLimitNICE", config_parse_limit, RLIMIT_NICE, arg_default_rlimit },
748 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, RLIMIT_RTPRIO, arg_default_rlimit },
749 { "Manager", "DefaultLimitRTTIME", config_parse_limit, RLIMIT_RTTIME, arg_default_rlimit },
750 { "Manager", "DefaultCPUAccounting", config_parse_bool, 0, &arg_default_cpu_accounting },
751 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
752 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
753 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
754 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
755 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
756 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
757 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
758 {}
759 };
760
761 const char *fn, *conf_dirs_nulstr;
762
763 fn = arg_system ?
764 PKGSYSCONFDIR "/system.conf" :
765 PKGSYSCONFDIR "/user.conf";
766
767 conf_dirs_nulstr = arg_system ?
768 CONF_PATHS_NULSTR("systemd/system.conf.d") :
769 CONF_PATHS_NULSTR("systemd/user.conf.d");
770
771 config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, false, NULL);
772
773 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
774 * like everywhere else. */
775 if (arg_default_timeout_start_usec <= 0)
776 arg_default_timeout_start_usec = USEC_INFINITY;
777 if (arg_default_timeout_stop_usec <= 0)
778 arg_default_timeout_stop_usec = USEC_INFINITY;
779
780 return 0;
781 }
782
783 static void manager_set_defaults(Manager *m) {
784
785 assert(m);
786
787 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
788 m->default_std_output = arg_default_std_output;
789 m->default_std_error = arg_default_std_error;
790 m->default_timeout_start_usec = arg_default_timeout_start_usec;
791 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
792 m->default_restart_usec = arg_default_restart_usec;
793 m->default_start_limit_interval = arg_default_start_limit_interval;
794 m->default_start_limit_burst = arg_default_start_limit_burst;
795 m->default_cpu_accounting = arg_default_cpu_accounting;
796 m->default_io_accounting = arg_default_io_accounting;
797 m->default_ip_accounting = arg_default_ip_accounting;
798 m->default_blockio_accounting = arg_default_blockio_accounting;
799 m->default_memory_accounting = arg_default_memory_accounting;
800 m->default_tasks_accounting = arg_default_tasks_accounting;
801 m->default_tasks_max = arg_default_tasks_max;
802
803 manager_set_default_rlimits(m, arg_default_rlimit);
804 manager_environment_add(m, NULL, arg_default_environment);
805 }
806
807 static int parse_argv(int argc, char *argv[]) {
808
809 enum {
810 ARG_LOG_LEVEL = 0x100,
811 ARG_LOG_TARGET,
812 ARG_LOG_COLOR,
813 ARG_LOG_LOCATION,
814 ARG_UNIT,
815 ARG_SYSTEM,
816 ARG_USER,
817 ARG_TEST,
818 ARG_NO_PAGER,
819 ARG_VERSION,
820 ARG_DUMP_CONFIGURATION_ITEMS,
821 ARG_DUMP_CORE,
822 ARG_CRASH_CHVT,
823 ARG_CRASH_SHELL,
824 ARG_CRASH_REBOOT,
825 ARG_CONFIRM_SPAWN,
826 ARG_SHOW_STATUS,
827 ARG_DESERIALIZE,
828 ARG_SWITCHED_ROOT,
829 ARG_DEFAULT_STD_OUTPUT,
830 ARG_DEFAULT_STD_ERROR,
831 ARG_MACHINE_ID
832 };
833
834 static const struct option options[] = {
835 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
836 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
837 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
838 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
839 { "unit", required_argument, NULL, ARG_UNIT },
840 { "system", no_argument, NULL, ARG_SYSTEM },
841 { "user", no_argument, NULL, ARG_USER },
842 { "test", no_argument, NULL, ARG_TEST },
843 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
844 { "help", no_argument, NULL, 'h' },
845 { "version", no_argument, NULL, ARG_VERSION },
846 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
847 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
848 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
849 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
850 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
851 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
852 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
853 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
854 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
855 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
856 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
857 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
858 {}
859 };
860
861 int c, r;
862
863 assert(argc >= 1);
864 assert(argv);
865
866 if (getpid_cached() == 1)
867 opterr = 0;
868
869 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
870
871 switch (c) {
872
873 case ARG_LOG_LEVEL:
874 r = log_set_max_level_from_string(optarg);
875 if (r < 0) {
876 log_error("Failed to parse log level %s.", optarg);
877 return r;
878 }
879
880 break;
881
882 case ARG_LOG_TARGET:
883 r = log_set_target_from_string(optarg);
884 if (r < 0) {
885 log_error("Failed to parse log target %s.", optarg);
886 return r;
887 }
888
889 break;
890
891 case ARG_LOG_COLOR:
892
893 if (optarg) {
894 r = log_show_color_from_string(optarg);
895 if (r < 0) {
896 log_error("Failed to parse log color setting %s.", optarg);
897 return r;
898 }
899 } else
900 log_show_color(true);
901
902 break;
903
904 case ARG_LOG_LOCATION:
905 if (optarg) {
906 r = log_show_location_from_string(optarg);
907 if (r < 0) {
908 log_error("Failed to parse log location setting %s.", optarg);
909 return r;
910 }
911 } else
912 log_show_location(true);
913
914 break;
915
916 case ARG_DEFAULT_STD_OUTPUT:
917 r = exec_output_from_string(optarg);
918 if (r < 0) {
919 log_error("Failed to parse default standard output setting %s.", optarg);
920 return r;
921 } else
922 arg_default_std_output = r;
923 break;
924
925 case ARG_DEFAULT_STD_ERROR:
926 r = exec_output_from_string(optarg);
927 if (r < 0) {
928 log_error("Failed to parse default standard error output setting %s.", optarg);
929 return r;
930 } else
931 arg_default_std_error = r;
932 break;
933
934 case ARG_UNIT:
935 r = free_and_strdup(&arg_default_unit, optarg);
936 if (r < 0)
937 return log_error_errno(r, "Failed to set default unit %s: %m", optarg);
938
939 break;
940
941 case ARG_SYSTEM:
942 arg_system = true;
943 break;
944
945 case ARG_USER:
946 arg_system = false;
947 break;
948
949 case ARG_TEST:
950 arg_action = ACTION_TEST;
951 break;
952
953 case ARG_NO_PAGER:
954 arg_no_pager = true;
955 break;
956
957 case ARG_VERSION:
958 arg_action = ACTION_VERSION;
959 break;
960
961 case ARG_DUMP_CONFIGURATION_ITEMS:
962 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
963 break;
964
965 case ARG_DUMP_CORE:
966 if (!optarg)
967 arg_dump_core = true;
968 else {
969 r = parse_boolean(optarg);
970 if (r < 0)
971 return log_error_errno(r, "Failed to parse dump core boolean: %s", optarg);
972 arg_dump_core = r;
973 }
974 break;
975
976 case ARG_CRASH_CHVT:
977 r = parse_crash_chvt(optarg);
978 if (r < 0)
979 return log_error_errno(r, "Failed to parse crash virtual terminal index: %s", optarg);
980 break;
981
982 case ARG_CRASH_SHELL:
983 if (!optarg)
984 arg_crash_shell = true;
985 else {
986 r = parse_boolean(optarg);
987 if (r < 0)
988 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
989 arg_crash_shell = r;
990 }
991 break;
992
993 case ARG_CRASH_REBOOT:
994 if (!optarg)
995 arg_crash_reboot = true;
996 else {
997 r = parse_boolean(optarg);
998 if (r < 0)
999 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
1000 arg_crash_reboot = r;
1001 }
1002 break;
1003
1004 case ARG_CONFIRM_SPAWN:
1005 arg_confirm_spawn = mfree(arg_confirm_spawn);
1006
1007 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
1008 if (r < 0)
1009 return log_error_errno(r, "Failed to parse confirm spawn option: %m");
1010 break;
1011
1012 case ARG_SHOW_STATUS:
1013 if (optarg) {
1014 r = parse_show_status(optarg, &arg_show_status);
1015 if (r < 0) {
1016 log_error("Failed to parse show status boolean %s.", optarg);
1017 return r;
1018 }
1019 } else
1020 arg_show_status = SHOW_STATUS_YES;
1021 break;
1022
1023 case ARG_DESERIALIZE: {
1024 int fd;
1025 FILE *f;
1026
1027 r = safe_atoi(optarg, &fd);
1028 if (r < 0 || fd < 0) {
1029 log_error("Failed to parse deserialize option %s.", optarg);
1030 return -EINVAL;
1031 }
1032
1033 (void) fd_cloexec(fd, true);
1034
1035 f = fdopen(fd, "r");
1036 if (!f)
1037 return log_error_errno(errno, "Failed to open serialization fd: %m");
1038
1039 safe_fclose(arg_serialization);
1040 arg_serialization = f;
1041
1042 break;
1043 }
1044
1045 case ARG_SWITCHED_ROOT:
1046 arg_switched_root = true;
1047 break;
1048
1049 case ARG_MACHINE_ID:
1050 r = set_machine_id(optarg);
1051 if (r < 0)
1052 return log_error_errno(r, "MachineID '%s' is not valid.", optarg);
1053 break;
1054
1055 case 'h':
1056 arg_action = ACTION_HELP;
1057 break;
1058
1059 case 'D':
1060 log_set_max_level(LOG_DEBUG);
1061 break;
1062
1063 case 'b':
1064 case 's':
1065 case 'z':
1066 /* Just to eat away the sysvinit kernel
1067 * cmdline args without getopt() error
1068 * messages that we'll parse in
1069 * parse_proc_cmdline_word() or ignore. */
1070
1071 case '?':
1072 if (getpid_cached() != 1)
1073 return -EINVAL;
1074 else
1075 return 0;
1076
1077 default:
1078 assert_not_reached("Unhandled option code.");
1079 }
1080
1081 if (optind < argc && getpid_cached() != 1) {
1082 /* Hmm, when we aren't run as init system
1083 * let's complain about excess arguments */
1084
1085 log_error("Excess arguments.");
1086 return -EINVAL;
1087 }
1088
1089 return 0;
1090 }
1091
1092 static int help(void) {
1093
1094 printf("%s [OPTIONS...]\n\n"
1095 "Starts up and maintains the system or user services.\n\n"
1096 " -h --help Show this help\n"
1097 " --version Show version\n"
1098 " --test Determine startup sequence, dump it and exit\n"
1099 " --no-pager Do not pipe output into a pager\n"
1100 " --dump-configuration-items Dump understood unit configuration items\n"
1101 " --unit=UNIT Set default unit\n"
1102 " --system Run a system instance, even if PID != 1\n"
1103 " --user Run a user instance\n"
1104 " --dump-core[=BOOL] Dump core on crash\n"
1105 " --crash-vt=NR Change to specified VT on crash\n"
1106 " --crash-reboot[=BOOL] Reboot on crash\n"
1107 " --crash-shell[=BOOL] Run shell on crash\n"
1108 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1109 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1110 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1111 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1112 " --log-color[=BOOL] Highlight important log messages\n"
1113 " --log-location[=BOOL] Include code location in log messages\n"
1114 " --default-standard-output= Set default standard output for services\n"
1115 " --default-standard-error= Set default standard error output for services\n",
1116 program_invocation_short_name);
1117
1118 return 0;
1119 }
1120
1121 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
1122 _cleanup_fdset_free_ FDSet *fds = NULL;
1123 _cleanup_fclose_ FILE *f = NULL;
1124 int r;
1125
1126 assert(m);
1127 assert(_f);
1128 assert(_fds);
1129
1130 r = manager_open_serialization(m, &f);
1131 if (r < 0)
1132 return log_error_errno(r, "Failed to create serialization file: %m");
1133
1134 /* Make sure nothing is really destructed when we shut down */
1135 m->n_reloading++;
1136 bus_manager_send_reloading(m, true);
1137
1138 fds = fdset_new();
1139 if (!fds)
1140 return log_oom();
1141
1142 r = manager_serialize(m, f, fds, switching_root);
1143 if (r < 0)
1144 return log_error_errno(r, "Failed to serialize state: %m");
1145
1146 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1147 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
1148
1149 r = fd_cloexec(fileno(f), false);
1150 if (r < 0)
1151 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
1152
1153 r = fdset_cloexec(fds, false);
1154 if (r < 0)
1155 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
1156
1157 *_f = f;
1158 *_fds = fds;
1159
1160 f = NULL;
1161 fds = NULL;
1162
1163 return 0;
1164 }
1165
1166 static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
1167 struct rlimit nl;
1168 int r;
1169 int min_max;
1170 _cleanup_free_ char *nr_open = NULL;
1171
1172 assert(saved_rlimit);
1173
1174 /* Save the original RLIMIT_NOFILE so that we can reset it
1175 * later when transitioning from the initrd to the main
1176 * systemd or suchlike. */
1177 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
1178 return log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
1179
1180 /* Make sure forked processes get the default kernel setting */
1181 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1182 struct rlimit *rl;
1183
1184 rl = newdup(struct rlimit, saved_rlimit, 1);
1185 if (!rl)
1186 return log_oom();
1187
1188 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1189 }
1190
1191 /* Get current RLIMIT_NOFILE maximum compiled into the kernel. */
1192 r = read_one_line_file("/proc/sys/fs/nr_open", &nr_open);
1193 if (r == 0)
1194 r = safe_atoi(nr_open, &min_max);
1195 /* If we fail, fallback to the hard-coded kernel limit of 1024 * 1024. */
1196 if (r < 0)
1197 min_max = 1024 * 1024;
1198
1199 /* Bump up the resource limit for ourselves substantially */
1200 nl.rlim_cur = nl.rlim_max = min_max;
1201 r = setrlimit_closest(RLIMIT_NOFILE, &nl);
1202 if (r < 0)
1203 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1204
1205 return 0;
1206 }
1207
1208 static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
1209 int r;
1210
1211 assert(saved_rlimit);
1212 assert(getuid() == 0);
1213
1214 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even though we have CAP_IPC_LOCK which
1215 * should normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's
1216 * bump the value high enough for the root user. */
1217
1218 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit) < 0)
1219 return log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1220
1221 r = setrlimit_closest(RLIMIT_MEMLOCK, &RLIMIT_MAKE_CONST(1024ULL*1024ULL*16ULL));
1222 if (r < 0)
1223 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1224
1225 return 0;
1226 }
1227
1228 static void test_usr(void) {
1229
1230 /* Check that /usr is not a separate fs */
1231
1232 if (dir_is_empty("/usr") <= 0)
1233 return;
1234
1235 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1236 "Some things will probably break (sometimes even silently) in mysterious ways. "
1237 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1238 }
1239
1240 static int initialize_join_controllers(void) {
1241 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1242 * + "net_prio". We'd like to add "cpuset" to the mix, but
1243 * "cpuset" doesn't really work for groups with no initialized
1244 * attributes. */
1245
1246 arg_join_controllers = new(char**, 3);
1247 if (!arg_join_controllers)
1248 return -ENOMEM;
1249
1250 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
1251 if (!arg_join_controllers[0])
1252 goto oom;
1253
1254 arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
1255 if (!arg_join_controllers[1])
1256 goto oom;
1257
1258 arg_join_controllers[2] = NULL;
1259 return 0;
1260
1261 oom:
1262 arg_join_controllers = strv_free_free(arg_join_controllers);
1263 return -ENOMEM;
1264 }
1265
1266 static int enforce_syscall_archs(Set *archs) {
1267 #if HAVE_SECCOMP
1268 int r;
1269
1270 if (!is_seccomp_available())
1271 return 0;
1272
1273 r = seccomp_restrict_archs(arg_syscall_archs);
1274 if (r < 0)
1275 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
1276 #endif
1277 return 0;
1278 }
1279
1280 static int status_welcome(void) {
1281 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1282 int r;
1283
1284 r = parse_env_file("/etc/os-release", NEWLINE,
1285 "PRETTY_NAME", &pretty_name,
1286 "ANSI_COLOR", &ansi_color,
1287 NULL);
1288 if (r == -ENOENT)
1289 r = parse_env_file("/usr/lib/os-release", NEWLINE,
1290 "PRETTY_NAME", &pretty_name,
1291 "ANSI_COLOR", &ansi_color,
1292 NULL);
1293
1294 if (r < 0 && r != -ENOENT)
1295 log_warning_errno(r, "Failed to read os-release file: %m");
1296
1297 if (log_get_show_color())
1298 return status_printf(NULL, false, false,
1299 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1300 isempty(ansi_color) ? "1" : ansi_color,
1301 isempty(pretty_name) ? "Linux" : pretty_name);
1302 else
1303 return status_printf(NULL, false, false,
1304 "\nWelcome to %s!\n",
1305 isempty(pretty_name) ? "Linux" : pretty_name);
1306 }
1307
1308 static int write_container_id(void) {
1309 const char *c;
1310 int r;
1311
1312 c = getenv("container");
1313 if (isempty(c))
1314 return 0;
1315
1316 RUN_WITH_UMASK(0022)
1317 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
1318 if (r < 0)
1319 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
1320
1321 return 1;
1322 }
1323
1324 static int bump_unix_max_dgram_qlen(void) {
1325 _cleanup_free_ char *qlen = NULL;
1326 unsigned long v;
1327 int r;
1328
1329 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1330 * default of 16 is simply too low. We set the value really
1331 * really early during boot, so that it is actually applied to
1332 * all our sockets, including the $NOTIFY_SOCKET one. */
1333
1334 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1335 if (r < 0)
1336 return log_warning_errno(r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1337
1338 r = safe_atolu(qlen, &v);
1339 if (r < 0)
1340 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1341
1342 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1343 return 0;
1344
1345 qlen = mfree(qlen);
1346 if (asprintf(&qlen, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN) < 0)
1347 return log_oom();
1348
1349 r = write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen, 0);
1350 if (r < 0)
1351 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1352 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1353
1354 return 1;
1355 }
1356
1357 static int fixup_environment(void) {
1358 _cleanup_free_ char *term = NULL;
1359 int r;
1360
1361 /* We expect the environment to be set correctly
1362 * if run inside a container. */
1363 if (detect_container() > 0)
1364 return 0;
1365
1366 /* When started as PID1, the kernel uses /dev/console
1367 * for our stdios and uses TERM=linux whatever the
1368 * backend device used by the console. We try to make
1369 * a better guess here since some consoles might not
1370 * have support for color mode for example.
1371 *
1372 * However if TERM was configured through the kernel
1373 * command line then leave it alone. */
1374
1375 r = proc_cmdline_get_key("TERM", 0, &term);
1376 if (r < 0)
1377 return r;
1378 if (r == 0) {
1379 term = strdup(default_term_for_tty("/dev/console"));
1380 if (!term)
1381 return -ENOMEM;
1382 }
1383
1384 if (setenv("TERM", term, 1) < 0)
1385 return -errno;
1386
1387 return 0;
1388 }
1389
1390 int main(int argc, char *argv[]) {
1391 Manager *m = NULL;
1392 int r, retval = EXIT_FAILURE;
1393 usec_t before_startup, after_startup;
1394 char timespan[FORMAT_TIMESPAN_MAX];
1395 FDSet *fds = NULL;
1396 bool reexecute = false;
1397 const char *shutdown_verb = NULL;
1398 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL;
1399 dual_timestamp userspace_timestamp = DUAL_TIMESTAMP_NULL;
1400 dual_timestamp kernel_timestamp = DUAL_TIMESTAMP_NULL;
1401 dual_timestamp security_start_timestamp = DUAL_TIMESTAMP_NULL;
1402 dual_timestamp security_finish_timestamp = DUAL_TIMESTAMP_NULL;
1403 static char systemd[] = "systemd";
1404 bool skip_setup = false;
1405 unsigned j;
1406 bool loaded_policy = false;
1407 bool arm_reboot_watchdog = false;
1408 bool queue_default_job = false;
1409 bool empty_etc = false;
1410 char *switch_root_dir = NULL, *switch_root_init = NULL;
1411 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0), saved_rlimit_memlock = RLIMIT_MAKE_CONST((rlim_t) -1);
1412 const char *error_message = NULL;
1413
1414 #if HAVE_SYSV_COMPAT
1415 if (getpid_cached() != 1 && strstr(program_invocation_short_name, "init")) {
1416 /* This is compatibility support for SysV, where
1417 * calling init as a user is identical to telinit. */
1418
1419 execv(SYSTEMCTL_BINARY_PATH, argv);
1420 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1421 return 1;
1422 }
1423 #endif
1424
1425 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
1426 dual_timestamp_get(&userspace_timestamp);
1427
1428 /* Determine if this is a reexecution or normal bootup. We do
1429 * the full command line parsing much later, so let's just
1430 * have a quick peek here. */
1431 if (strv_find(argv+1, "--deserialize"))
1432 skip_setup = true;
1433
1434 /* If we have switched root, do all the special setup
1435 * things */
1436 if (strv_find(argv+1, "--switched-root"))
1437 skip_setup = false;
1438
1439 /* If we get started via the /sbin/init symlink then we are
1440 called 'init'. After a subsequent reexecution we are then
1441 called 'systemd'. That is confusing, hence let's call us
1442 systemd right-away. */
1443 program_invocation_short_name = systemd;
1444 (void) prctl(PR_SET_NAME, systemd);
1445
1446 saved_argv = argv;
1447 saved_argc = argc;
1448
1449 log_set_upgrade_syslog_to_journal(true);
1450
1451 if (getpid_cached() == 1) {
1452 /* Disable the umask logic */
1453 umask(0);
1454
1455 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
1456 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
1457 * child process right before execve()'ing the actual binary, at a point in time where socket
1458 * activation stderr/stdout area already set up. */
1459 log_set_always_reopen_console(true);
1460 }
1461
1462 if (getpid_cached() == 1 && detect_container() <= 0) {
1463
1464 /* Running outside of a container as PID 1 */
1465 arg_system = true;
1466 log_set_target(LOG_TARGET_KMSG);
1467 log_open();
1468
1469 if (in_initrd())
1470 initrd_timestamp = userspace_timestamp;
1471
1472 if (!skip_setup) {
1473 r = mount_setup_early();
1474 if (r < 0) {
1475 error_message = "Failed to mount early API filesystems";
1476 goto finish;
1477 }
1478
1479 dual_timestamp_get(&security_start_timestamp);
1480 if (mac_selinux_setup(&loaded_policy) < 0) {
1481 error_message = "Failed to load SELinux policy";
1482 goto finish;
1483 } else if (mac_smack_setup(&loaded_policy) < 0) {
1484 error_message = "Failed to load SMACK policy";
1485 goto finish;
1486 } else if (ima_setup() < 0) {
1487 error_message = "Failed to load IMA policy";
1488 goto finish;
1489 }
1490 dual_timestamp_get(&security_finish_timestamp);
1491 }
1492
1493 if (mac_selinux_init() < 0) {
1494 error_message = "Failed to initialize SELinux policy";
1495 goto finish;
1496 }
1497
1498 if (!skip_setup) {
1499 if (clock_is_localtime(NULL) > 0) {
1500 int min;
1501
1502 /*
1503 * The very first call of settimeofday() also does a time warp in the kernel.
1504 *
1505 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on
1506 * external tools to take care of maintaining the RTC and do all adjustments.
1507 * This matches the behavior of Windows, which leaves the RTC alone if the
1508 * registry tells that the RTC runs in UTC.
1509 */
1510 r = clock_set_timezone(&min);
1511 if (r < 0)
1512 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1513 else
1514 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1515 } else if (!in_initrd()) {
1516 /*
1517 * Do a dummy very first call to seal the kernel's time warp magic.
1518 *
1519 * Do not call this from inside the initrd. The initrd might not
1520 * carry /etc/adjtime with LOCAL, but the real system could be set up
1521 * that way. In such case, we need to delay the time-warp or the sealing
1522 * until we reach the real system.
1523 *
1524 * Do no set the kernel's timezone. The concept of local time cannot
1525 * be supported reliably, the time will jump or be incorrect at every daylight
1526 * saving time change. All kernel local time concepts will be treated
1527 * as UTC that way.
1528 */
1529 (void) clock_reset_timewarp();
1530 }
1531
1532 r = clock_apply_epoch();
1533 if (r < 0)
1534 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1535 else if (r > 0)
1536 log_info("System time before build time, advancing clock.");
1537 }
1538
1539 /* Set the default for later on, but don't actually
1540 * open the logs like this for now. Note that if we
1541 * are transitioning from the initrd there might still
1542 * be journal fd open, and we shouldn't attempt
1543 * opening that before we parsed /proc/cmdline which
1544 * might redirect output elsewhere. */
1545 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1546
1547 } else if (getpid_cached() == 1) {
1548 /* Running inside a container, as PID 1 */
1549 arg_system = true;
1550 log_set_target(LOG_TARGET_CONSOLE);
1551 log_close_console(); /* force reopen of /dev/console */
1552 log_open();
1553
1554 /* For later on, see above... */
1555 log_set_target(LOG_TARGET_JOURNAL);
1556
1557 /* clear the kernel timestamp,
1558 * because we are in a container */
1559 kernel_timestamp = DUAL_TIMESTAMP_NULL;
1560 } else {
1561 /* Running as user instance */
1562 arg_system = false;
1563 log_set_target(LOG_TARGET_AUTO);
1564 log_open();
1565
1566 /* clear the kernel timestamp,
1567 * because we are not PID 1 */
1568 kernel_timestamp = DUAL_TIMESTAMP_NULL;
1569 }
1570
1571 if (getpid_cached() == 1) {
1572 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1573 * will process core dumps for system services by default. */
1574 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1575 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1576
1577 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1578 * until the systemd-coredump tool is enabled via sysctl. */
1579 if (!skip_setup)
1580 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1581 }
1582
1583 if (arg_system) {
1584 if (fixup_environment() < 0) {
1585 error_message = "Failed to fix up PID1 environment";
1586 goto finish;
1587 }
1588
1589 /* Try to figure out if we can use colors with the console. No
1590 * need to do that for user instances since they never log
1591 * into the console. */
1592 log_show_color(colors_enabled());
1593 r = make_null_stdio();
1594 if (r < 0)
1595 log_warning_errno(r, "Failed to redirect standard streams to /dev/null: %m");
1596 }
1597
1598 r = initialize_join_controllers();
1599 if (r < 0) {
1600 error_message = "Failed to initialize cgroup controllers";
1601 goto finish;
1602 }
1603
1604 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1605 * /proc/$PID/fd is available. */
1606 if (getpid_cached() == 1) {
1607
1608 /* Load the kernel modules early. */
1609 if (!skip_setup)
1610 kmod_setup();
1611
1612 r = mount_setup(loaded_policy);
1613 if (r < 0) {
1614 error_message = "Failed to mount API filesystems";
1615 goto finish;
1616 }
1617 }
1618
1619 /* Reset all signal handlers. */
1620 (void) reset_all_signal_handlers();
1621 (void) ignore_signals(SIGNALS_IGNORE, -1);
1622
1623 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
1624
1625 if (parse_config_file() < 0) {
1626 error_message = "Failed to parse config file";
1627 goto finish;
1628 }
1629
1630 if (arg_system) {
1631 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
1632 if (r < 0)
1633 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
1634 }
1635
1636 /* Note that this also parses bits from the kernel command
1637 * line, including "debug". */
1638 log_parse_environment();
1639
1640 if (parse_argv(argc, argv) < 0) {
1641 error_message = "Failed to parse commandline arguments";
1642 goto finish;
1643 }
1644
1645 /* Initialize default unit */
1646 if (!arg_default_unit) {
1647 arg_default_unit = strdup(SPECIAL_DEFAULT_TARGET);
1648 if (!arg_default_unit) {
1649 r = log_oom();
1650 error_message = "Failed to set default unit";
1651 goto finish;
1652 }
1653 }
1654
1655 if (arg_action == ACTION_TEST &&
1656 geteuid() == 0) {
1657 log_error("Don't run test mode as root.");
1658 goto finish;
1659 }
1660
1661 if (!arg_system &&
1662 arg_action == ACTION_RUN &&
1663 sd_booted() <= 0) {
1664 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1665 goto finish;
1666 }
1667
1668 if (arg_system &&
1669 arg_action == ACTION_RUN &&
1670 running_in_chroot() > 0) {
1671 log_error("Cannot be run in a chroot() environment.");
1672 goto finish;
1673 }
1674
1675 if (arg_action == ACTION_TEST || arg_action == ACTION_HELP) {
1676 pager_open(arg_no_pager, false);
1677 skip_setup = true;
1678 }
1679
1680 if (arg_action == ACTION_HELP) {
1681 retval = help();
1682 goto finish;
1683 } else if (arg_action == ACTION_VERSION) {
1684 retval = version();
1685 goto finish;
1686 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
1687 pager_open(arg_no_pager, false);
1688 unit_dump_config_items(stdout);
1689 retval = EXIT_SUCCESS;
1690 goto finish;
1691 }
1692
1693 if (!arg_system &&
1694 !getenv("XDG_RUNTIME_DIR")) {
1695 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1696 goto finish;
1697 }
1698
1699 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
1700
1701 /* Close logging fds, in order not to confuse fdset below */
1702 log_close();
1703
1704 /* Remember open file descriptors for later deserialization */
1705 if (arg_action == ACTION_RUN) {
1706 r = fdset_new_fill(&fds);
1707 if (r < 0) {
1708 log_emergency_errno(r, "Failed to allocate fd set: %m");
1709 error_message = "Failed to allocate fd set";
1710 goto finish;
1711 } else
1712 fdset_cloexec(fds, true);
1713
1714 if (arg_serialization)
1715 assert_se(fdset_remove(fds, fileno(arg_serialization)) >= 0);
1716
1717 if (arg_system)
1718 /* Become a session leader if we aren't one yet. */
1719 setsid();
1720 }
1721
1722 /* Move out of the way, so that we won't block unmounts */
1723 assert_se(chdir("/") == 0);
1724
1725 /* Reset the console, but only if this is really init and we
1726 * are freshly booted */
1727 if (arg_system && arg_action == ACTION_RUN) {
1728
1729 /* If we are init, we connect stdin/stdout/stderr to
1730 * /dev/null and make sure we don't have a controlling
1731 * tty. */
1732 release_terminal();
1733
1734 if (getpid_cached() == 1 && !skip_setup)
1735 console_setup();
1736 }
1737
1738 /* Open the logging devices, if possible and necessary */
1739 log_open();
1740
1741 if (arg_show_status == _SHOW_STATUS_UNSET)
1742 arg_show_status = SHOW_STATUS_YES;
1743
1744 /* Make sure we leave a core dump without panicing the
1745 * kernel. */
1746 if (getpid_cached() == 1) {
1747 install_crash_handler();
1748
1749 r = mount_cgroup_controllers(arg_join_controllers);
1750 if (r < 0)
1751 goto finish;
1752 }
1753
1754 if (arg_system) {
1755 int v;
1756
1757 log_info(PACKAGE_STRING " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1758 arg_action == ACTION_TEST ? "test " : "" );
1759
1760 v = detect_virtualization();
1761 if (v > 0)
1762 log_info("Detected virtualization %s.", virtualization_to_string(v));
1763
1764 write_container_id();
1765
1766 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1767
1768 if (in_initrd())
1769 log_info("Running in initial RAM disk.");
1770
1771 /* Let's check whether /etc is already populated. We
1772 * don't actually really check for that, but use
1773 * /etc/machine-id as flag file. This allows container
1774 * managers and installers to provision a couple of
1775 * files already. If the container manager wants to
1776 * provision the machine ID itself it should pass
1777 * $container_uuid to PID 1. */
1778
1779 empty_etc = access("/etc/machine-id", F_OK) < 0;
1780 if (empty_etc)
1781 log_info("Running with unpopulated /etc.");
1782 } else {
1783 _cleanup_free_ char *t;
1784
1785 t = uid_to_name(getuid());
1786 log_debug(PACKAGE_STRING " running in %suser mode for user "UID_FMT"/%s. (" SYSTEMD_FEATURES ")",
1787 arg_action == ACTION_TEST ? " test" : "", getuid(), t);
1788 }
1789
1790 if (arg_action == ACTION_RUN) {
1791 if (arg_system && !skip_setup) {
1792 if (arg_show_status > 0)
1793 status_welcome();
1794
1795 hostname_setup();
1796 machine_id_setup(NULL, arg_machine_id, NULL);
1797 loopback_setup();
1798 bump_unix_max_dgram_qlen();
1799
1800 test_usr();
1801 }
1802
1803 if (arg_system && arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
1804 watchdog_set_timeout(&arg_runtime_watchdog);
1805
1806 if (arg_timer_slack_nsec != NSEC_INFINITY)
1807 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
1808 log_error_errno(errno, "Failed to adjust timer slack: %m");
1809
1810 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
1811 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
1812 if (r < 0) {
1813 log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
1814 error_message = "Failed to drop capability bounding set of usermode helpers";
1815 goto finish;
1816 }
1817 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
1818 if (r < 0) {
1819 log_emergency_errno(r, "Failed to drop capability bounding set: %m");
1820 error_message = "Failed to drop capability bounding set";
1821 goto finish;
1822 }
1823 }
1824
1825 if (arg_syscall_archs) {
1826 r = enforce_syscall_archs(arg_syscall_archs);
1827 if (r < 0) {
1828 error_message = "Failed to set syscall architectures";
1829 goto finish;
1830 }
1831 }
1832
1833 if (!arg_system)
1834 /* Become reaper of our children */
1835 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
1836 log_warning_errno(errno, "Failed to make us a subreaper: %m");
1837
1838 if (arg_system) {
1839 /* Bump up RLIMIT_NOFILE for systemd itself */
1840 (void) bump_rlimit_nofile(&saved_rlimit_nofile);
1841 (void) bump_rlimit_memlock(&saved_rlimit_memlock);
1842 }
1843 }
1844
1845 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
1846 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
1847 &m);
1848 if (r < 0) {
1849 log_emergency_errno(r, "Failed to allocate manager object: %m");
1850 error_message = "Failed to allocate manager object";
1851 goto finish;
1852 }
1853
1854 m->confirm_spawn = arg_confirm_spawn;
1855 m->runtime_watchdog = arg_runtime_watchdog;
1856 m->shutdown_watchdog = arg_shutdown_watchdog;
1857 m->userspace_timestamp = userspace_timestamp;
1858 m->kernel_timestamp = kernel_timestamp;
1859 m->initrd_timestamp = initrd_timestamp;
1860 m->security_start_timestamp = security_start_timestamp;
1861 m->security_finish_timestamp = security_finish_timestamp;
1862 m->cad_burst_action = arg_cad_burst_action;
1863
1864 manager_set_defaults(m);
1865 manager_set_show_status(m, arg_show_status);
1866 manager_set_first_boot(m, empty_etc);
1867
1868 /* Remember whether we should queue the default job */
1869 queue_default_job = !arg_serialization || arg_switched_root;
1870
1871 before_startup = now(CLOCK_MONOTONIC);
1872
1873 r = manager_startup(m, arg_serialization, fds);
1874 if (r < 0) {
1875 log_error_errno(r, "Failed to fully start up daemon: %m");
1876 goto finish;
1877 }
1878
1879 /* This will close all file descriptors that were opened, but
1880 * not claimed by any unit. */
1881 fds = fdset_free(fds);
1882
1883 arg_serialization = safe_fclose(arg_serialization);
1884
1885 if (queue_default_job) {
1886 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1887 Unit *target = NULL;
1888 Job *default_unit_job;
1889
1890 log_debug("Activating default unit: %s", arg_default_unit);
1891
1892 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
1893 if (r < 0)
1894 log_error("Failed to load default target: %s", bus_error_message(&error, r));
1895 else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND)
1896 log_error_errno(target->load_error, "Failed to load default target: %m");
1897 else if (target->load_state == UNIT_MASKED)
1898 log_error("Default target masked.");
1899
1900 if (!target || target->load_state != UNIT_LOADED) {
1901 log_info("Trying to load rescue target...");
1902
1903 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1904 if (r < 0) {
1905 log_emergency("Failed to load rescue target: %s", bus_error_message(&error, r));
1906 error_message = "Failed to load rescue target";
1907 goto finish;
1908 } else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND) {
1909 log_emergency_errno(target->load_error, "Failed to load rescue target: %m");
1910 error_message = "Failed to load rescue target";
1911 goto finish;
1912 } else if (target->load_state == UNIT_MASKED) {
1913 log_emergency("Rescue target masked.");
1914 error_message = "Rescue target masked";
1915 goto finish;
1916 }
1917 }
1918
1919 assert(target->load_state == UNIT_LOADED);
1920
1921 if (arg_action == ACTION_TEST) {
1922 printf("-> By units:\n");
1923 manager_dump_units(m, stdout, "\t");
1924 }
1925
1926 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, &error, &default_unit_job);
1927 if (r == -EPERM) {
1928 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
1929
1930 sd_bus_error_free(&error);
1931
1932 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, &error, &default_unit_job);
1933 if (r < 0) {
1934 log_emergency("Failed to start default target: %s", bus_error_message(&error, r));
1935 error_message = "Failed to start default target";
1936 goto finish;
1937 }
1938 } else if (r < 0) {
1939 log_emergency("Failed to isolate default target: %s", bus_error_message(&error, r));
1940 error_message = "Failed to isolate default target";
1941 goto finish;
1942 }
1943
1944 m->default_unit_job_id = default_unit_job->id;
1945
1946 after_startup = now(CLOCK_MONOTONIC);
1947 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1948 "Loaded units and determined initial transaction in %s.",
1949 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
1950
1951 if (arg_action == ACTION_TEST) {
1952 printf("-> By jobs:\n");
1953 manager_dump_jobs(m, stdout, "\t");
1954 retval = EXIT_SUCCESS;
1955 goto finish;
1956 }
1957 }
1958
1959 for (;;) {
1960 r = manager_loop(m);
1961 if (r < 0) {
1962 log_emergency_errno(r, "Failed to run main loop: %m");
1963 error_message = "Failed to run main loop";
1964 goto finish;
1965 }
1966
1967 switch (m->exit_code) {
1968
1969 case MANAGER_RELOAD:
1970 log_info("Reloading.");
1971
1972 r = parse_config_file();
1973 if (r < 0)
1974 log_error("Failed to parse config file.");
1975
1976 manager_set_defaults(m);
1977
1978 r = manager_reload(m);
1979 if (r < 0)
1980 log_error_errno(r, "Failed to reload: %m");
1981 break;
1982
1983 case MANAGER_REEXECUTE:
1984
1985 if (prepare_reexecute(m, &arg_serialization, &fds, false) < 0) {
1986 error_message = "Failed to prepare for reexecution";
1987 goto finish;
1988 }
1989
1990 reexecute = true;
1991 log_notice("Reexecuting.");
1992 goto finish;
1993
1994 case MANAGER_SWITCH_ROOT:
1995 /* Steal the switch root parameters */
1996 switch_root_dir = m->switch_root;
1997 switch_root_init = m->switch_root_init;
1998 m->switch_root = m->switch_root_init = NULL;
1999
2000 if (!switch_root_init)
2001 if (prepare_reexecute(m, &arg_serialization, &fds, true) < 0) {
2002 error_message = "Failed to prepare for reexecution";
2003 goto finish;
2004 }
2005
2006 reexecute = true;
2007 log_notice("Switching root.");
2008 goto finish;
2009
2010 case MANAGER_EXIT:
2011 retval = m->return_value;
2012
2013 if (MANAGER_IS_USER(m)) {
2014 log_debug("Exit.");
2015 goto finish;
2016 }
2017
2018 /* fallthrough */
2019 case MANAGER_REBOOT:
2020 case MANAGER_POWEROFF:
2021 case MANAGER_HALT:
2022 case MANAGER_KEXEC: {
2023 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
2024 [MANAGER_EXIT] = "exit",
2025 [MANAGER_REBOOT] = "reboot",
2026 [MANAGER_POWEROFF] = "poweroff",
2027 [MANAGER_HALT] = "halt",
2028 [MANAGER_KEXEC] = "kexec"
2029 };
2030
2031 assert_se(shutdown_verb = table[m->exit_code]);
2032 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
2033
2034 log_notice("Shutting down.");
2035 goto finish;
2036 }
2037
2038 default:
2039 assert_not_reached("Unknown exit code.");
2040 }
2041 }
2042
2043 finish:
2044 pager_close();
2045
2046 if (m)
2047 arg_shutdown_watchdog = m->shutdown_watchdog;
2048
2049 m = manager_free(m);
2050
2051 for (j = 0; j < ELEMENTSOF(arg_default_rlimit); j++)
2052 arg_default_rlimit[j] = mfree(arg_default_rlimit[j]);
2053
2054 arg_default_unit = mfree(arg_default_unit);
2055 arg_confirm_spawn = mfree(arg_confirm_spawn);
2056 arg_join_controllers = strv_free_free(arg_join_controllers);
2057 arg_default_environment = strv_free(arg_default_environment);
2058 arg_syscall_archs = set_free(arg_syscall_archs);
2059
2060 mac_selinux_finish();
2061
2062 if (reexecute) {
2063 const char **args;
2064 unsigned i, args_size;
2065
2066 /* Close and disarm the watchdog, so that the new
2067 * instance can reinitialize it, but doesn't get
2068 * rebooted while we do that */
2069 watchdog_close(true);
2070
2071 /* Reset the RLIMIT_NOFILE to the kernel default, so
2072 * that the new systemd can pass the kernel default to
2073 * its child processes */
2074 if (saved_rlimit_nofile.rlim_cur > 0)
2075 (void) setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
2076 if (saved_rlimit_memlock.rlim_cur != (rlim_t) -1)
2077 (void) setrlimit(RLIMIT_MEMLOCK, &saved_rlimit_memlock);
2078
2079 if (switch_root_dir) {
2080 /* Kill all remaining processes from the
2081 * initrd, but don't wait for them, so that we
2082 * can handle the SIGCHLD for them after
2083 * deserializing. */
2084 broadcast_signal(SIGTERM, false, true);
2085
2086 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2087 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
2088 if (r < 0)
2089 log_error_errno(r, "Failed to switch root, trying to continue: %m");
2090 }
2091
2092 args_size = MAX(6, argc+1);
2093 args = newa(const char*, args_size);
2094
2095 if (!switch_root_init) {
2096 char sfd[DECIMAL_STR_MAX(int) + 1];
2097
2098 /* First try to spawn ourselves with the right
2099 * path, and with full serialization. We do
2100 * this only if the user didn't specify an
2101 * explicit init to spawn. */
2102
2103 assert(arg_serialization);
2104 assert(fds);
2105
2106 xsprintf(sfd, "%i", fileno(arg_serialization));
2107
2108 i = 0;
2109 args[i++] = SYSTEMD_BINARY_PATH;
2110 if (switch_root_dir)
2111 args[i++] = "--switched-root";
2112 args[i++] = arg_system ? "--system" : "--user";
2113 args[i++] = "--deserialize";
2114 args[i++] = sfd;
2115 args[i++] = NULL;
2116
2117 assert(i <= args_size);
2118
2119 /*
2120 * We want valgrind to print its memory usage summary before reexecution.
2121 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2122 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2123 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2124 */
2125 valgrind_summary_hack();
2126
2127 (void) execv(args[0], (char* const*) args);
2128 }
2129
2130 /* Try the fallback, if there is any, without any
2131 * serialization. We pass the original argv[] and
2132 * envp[]. (Well, modulo the ordering changes due to
2133 * getopt() in argv[], and some cleanups in envp[],
2134 * but let's hope that doesn't matter.) */
2135
2136 arg_serialization = safe_fclose(arg_serialization);
2137 fds = fdset_free(fds);
2138
2139 /* Reopen the console */
2140 (void) make_console_stdio();
2141
2142 for (j = 1, i = 1; j < (unsigned) argc; j++)
2143 args[i++] = argv[j];
2144 args[i++] = NULL;
2145 assert(i <= args_size);
2146
2147 /* Reenable any blocked signals, especially important
2148 * if we switch from initial ramdisk to init=... */
2149 (void) reset_all_signal_handlers();
2150 (void) reset_signal_mask();
2151
2152 if (switch_root_init) {
2153 args[0] = switch_root_init;
2154 (void) execv(args[0], (char* const*) args);
2155 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
2156 }
2157
2158 args[0] = "/sbin/init";
2159 (void) execv(args[0], (char* const*) args);
2160
2161 if (errno == ENOENT) {
2162 log_warning("No /sbin/init, trying fallback");
2163
2164 args[0] = "/bin/sh";
2165 args[1] = NULL;
2166 (void) execv(args[0], (char* const*) args);
2167 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
2168 } else
2169 log_warning_errno(errno, "Failed to execute /sbin/init, giving up: %m");
2170 }
2171
2172 arg_serialization = safe_fclose(arg_serialization);
2173 fds = fdset_free(fds);
2174
2175 #if HAVE_VALGRIND_VALGRIND_H
2176 /* If we are PID 1 and running under valgrind, then let's exit
2177 * here explicitly. valgrind will only generate nice output on
2178 * exit(), not on exec(), hence let's do the former not the
2179 * latter here. */
2180 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND)
2181 return 0;
2182 #endif
2183
2184 if (shutdown_verb) {
2185 char log_level[DECIMAL_STR_MAX(int) + 1];
2186 char exit_code[DECIMAL_STR_MAX(uint8_t) + 1];
2187 const char* command_line[11] = {
2188 SYSTEMD_SHUTDOWN_BINARY_PATH,
2189 shutdown_verb,
2190 "--log-level", log_level,
2191 "--log-target",
2192 };
2193 unsigned pos = 5;
2194 _cleanup_strv_free_ char **env_block = NULL;
2195
2196 assert(command_line[pos] == NULL);
2197 env_block = strv_copy(environ);
2198
2199 xsprintf(log_level, "%d", log_get_max_level());
2200
2201 switch (log_get_target()) {
2202
2203 case LOG_TARGET_KMSG:
2204 case LOG_TARGET_JOURNAL_OR_KMSG:
2205 case LOG_TARGET_SYSLOG_OR_KMSG:
2206 command_line[pos++] = "kmsg";
2207 break;
2208
2209 case LOG_TARGET_NULL:
2210 command_line[pos++] = "null";
2211 break;
2212
2213 case LOG_TARGET_CONSOLE:
2214 default:
2215 command_line[pos++] = "console";
2216 break;
2217 };
2218
2219 if (log_get_show_color())
2220 command_line[pos++] = "--log-color";
2221
2222 if (log_get_show_location())
2223 command_line[pos++] = "--log-location";
2224
2225 if (streq(shutdown_verb, "exit")) {
2226 command_line[pos++] = "--exit-code";
2227 command_line[pos++] = exit_code;
2228 xsprintf(exit_code, "%d", retval);
2229 }
2230
2231 assert(pos < ELEMENTSOF(command_line));
2232
2233 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0 && arg_shutdown_watchdog != USEC_INFINITY) {
2234 char *e;
2235
2236 /* If we reboot let's set the shutdown
2237 * watchdog and tell the shutdown binary to
2238 * repeatedly ping it */
2239 r = watchdog_set_timeout(&arg_shutdown_watchdog);
2240 watchdog_close(r < 0);
2241
2242 /* Tell the binary how often to ping, ignore failure */
2243 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
2244 (void) strv_push(&env_block, e);
2245 } else
2246 watchdog_close(true);
2247
2248 /* Avoid the creation of new processes forked by the
2249 * kernel; at this point, we will not listen to the
2250 * signals anyway */
2251 if (detect_container() <= 0)
2252 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
2253
2254 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
2255 log_error_errno(errno, "Failed to execute shutdown binary, %s: %m",
2256 getpid_cached() == 1 ? "freezing" : "quitting");
2257 }
2258
2259 if (getpid_cached() == 1) {
2260 if (error_message)
2261 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
2262 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
2263 "%s, freezing.", error_message);
2264 freeze_or_reboot();
2265 }
2266
2267 return retval;
2268 }