]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/main.c
core: add new API for enqueing a job with returning the transaction data
[thirdparty/systemd.git] / src / core / main.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <sys/mount.h>
10 #include <sys/prctl.h>
11 #include <sys/reboot.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14 #if HAVE_SECCOMP
15 #include <seccomp.h>
16 #endif
17 #if HAVE_VALGRIND_VALGRIND_H
18 #include <valgrind/valgrind.h>
19 #endif
20
21 #include "sd-bus.h"
22 #include "sd-daemon.h"
23 #include "sd-messages.h"
24
25 #include "alloc-util.h"
26 #include "architecture.h"
27 #include "build.h"
28 #include "bus-error.h"
29 #include "bus-util.h"
30 #include "capability-util.h"
31 #include "cgroup-util.h"
32 #include "clock-util.h"
33 #include "conf-parser.h"
34 #include "cpu-set-util.h"
35 #include "dbus.h"
36 #include "dbus-manager.h"
37 #include "def.h"
38 #include "emergency-action.h"
39 #include "env-util.h"
40 #include "exit-status.h"
41 #include "fd-util.h"
42 #include "fdset.h"
43 #include "fileio.h"
44 #include "format-util.h"
45 #include "fs-util.h"
46 #include "hostname-setup.h"
47 #include "ima-setup.h"
48 #include "killall.h"
49 #include "kmod-setup.h"
50 #include "limits-util.h"
51 #include "load-fragment.h"
52 #include "log.h"
53 #include "loopback-setup.h"
54 #include "machine-id-setup.h"
55 #include "manager.h"
56 #include "missing.h"
57 #include "mount-setup.h"
58 #include "os-util.h"
59 #include "pager.h"
60 #include "parse-util.h"
61 #include "path-util.h"
62 #include "pretty-print.h"
63 #include "proc-cmdline.h"
64 #include "process-util.h"
65 #include "raw-clone.h"
66 #include "rlimit-util.h"
67 #if HAVE_SECCOMP
68 #include "seccomp-util.h"
69 #endif
70 #include "selinux-setup.h"
71 #include "selinux-util.h"
72 #include "signal-util.h"
73 #include "smack-setup.h"
74 #include "special.h"
75 #include "stat-util.h"
76 #include "stdio-util.h"
77 #include "strv.h"
78 #include "switch-root.h"
79 #include "sysctl-util.h"
80 #include "terminal-util.h"
81 #include "umask-util.h"
82 #include "user-util.h"
83 #include "util.h"
84 #include "virt.h"
85 #include "watchdog.h"
86
87 #if HAS_FEATURE_ADDRESS_SANITIZER
88 #include <sanitizer/lsan_interface.h>
89 #endif
90
91 static enum {
92 ACTION_RUN,
93 ACTION_HELP,
94 ACTION_VERSION,
95 ACTION_TEST,
96 ACTION_DUMP_CONFIGURATION_ITEMS,
97 ACTION_DUMP_BUS_PROPERTIES,
98 } arg_action = ACTION_RUN;
99 static char *arg_default_unit = NULL;
100 static bool arg_system = false;
101 static bool arg_dump_core = true;
102 static int arg_crash_chvt = -1;
103 static bool arg_crash_shell = false;
104 static bool arg_crash_reboot = false;
105 static char *arg_confirm_spawn = NULL;
106 static ShowStatus arg_show_status = _SHOW_STATUS_INVALID;
107 static bool arg_switched_root = false;
108 static PagerFlags arg_pager_flags = 0;
109 static bool arg_service_watchdogs = true;
110 static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
111 static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
112 static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
113 static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
114 static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
115 static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
116 static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
117 static usec_t arg_runtime_watchdog = 0;
118 static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
119 static char *arg_early_core_pattern = NULL;
120 static char *arg_watchdog_device = NULL;
121 static char **arg_default_environment = NULL;
122 static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
123 static uint64_t arg_capability_bounding_set = CAP_ALL;
124 static bool arg_no_new_privs = false;
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 int arg_default_cpu_accounting = -1;
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 = MEMORY_ACCOUNTING_DEFAULT;
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_exit_or_reboot(void) {
140
141 /* If we are running in a container, let's prefer exiting, after all we can propagate an exit code to
142 * the container manager, and thus inform it that something went wrong. */
143 if (detect_container() > 0) {
144 log_emergency("Exiting PID 1...");
145 _exit(EXIT_EXCEPTION);
146 }
147
148 if (arg_crash_reboot) {
149 log_notice("Rebooting in 10s...");
150 (void) sleep(10);
151
152 log_notice("Rebooting now...");
153 (void) reboot(RB_AUTOBOOT);
154 log_emergency_errno(errno, "Failed to reboot: %m");
155 }
156
157 log_emergency("Freezing execution.");
158 freeze();
159 }
160
161 _noreturn_ static void crash(int sig) {
162 struct sigaction sa;
163 pid_t pid;
164
165 if (getpid_cached() != 1)
166 /* Pass this on immediately, if this is not PID 1 */
167 (void) raise(sig);
168 else if (!arg_dump_core)
169 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
170 else {
171 sa = (struct sigaction) {
172 .sa_handler = nop_signal_handler,
173 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
174 };
175
176 /* We want to wait for the core process, hence let's enable SIGCHLD */
177 (void) sigaction(SIGCHLD, &sa, NULL);
178
179 pid = raw_clone(SIGCHLD);
180 if (pid < 0)
181 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
182 else if (pid == 0) {
183 /* Enable default signal handler for core dump */
184
185 sa = (struct sigaction) {
186 .sa_handler = SIG_DFL,
187 };
188 (void) sigaction(sig, &sa, NULL);
189
190 /* Don't limit the coredump size */
191 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
192
193 /* Just to be sure... */
194 (void) chdir("/");
195
196 /* Raise the signal again */
197 pid = raw_getpid();
198 (void) kill(pid, sig); /* raise() would kill the parent */
199
200 assert_not_reached("We shouldn't be here...");
201 _exit(EXIT_EXCEPTION);
202 } else {
203 siginfo_t status;
204 int r;
205
206 /* Order things nicely. */
207 r = wait_for_terminate(pid, &status);
208 if (r < 0)
209 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
210 else if (status.si_code != CLD_DUMPED)
211 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
212 signal_to_string(sig),
213 pid, sigchld_code_to_string(status.si_code),
214 status.si_status,
215 strna(status.si_code == CLD_EXITED
216 ? exit_status_to_string(status.si_status, EXIT_STATUS_MINIMAL)
217 : signal_to_string(status.si_status)));
218 else
219 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
220 }
221 }
222
223 if (arg_crash_chvt >= 0)
224 (void) chvt(arg_crash_chvt);
225
226 sa = (struct sigaction) {
227 .sa_handler = SIG_IGN,
228 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
229 };
230
231 /* Let the kernel reap children for us */
232 (void) sigaction(SIGCHLD, &sa, NULL);
233
234 if (arg_crash_shell) {
235 log_notice("Executing crash shell in 10s...");
236 (void) sleep(10);
237
238 pid = raw_clone(SIGCHLD);
239 if (pid < 0)
240 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
241 else if (pid == 0) {
242 (void) setsid();
243 (void) make_console_stdio();
244 (void) rlimit_nofile_safe();
245 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
246
247 log_emergency_errno(errno, "execle() failed: %m");
248 _exit(EXIT_EXCEPTION);
249 } else {
250 log_info("Spawned crash shell as PID "PID_FMT".", pid);
251 (void) wait_for_terminate(pid, NULL);
252 }
253 }
254
255 freeze_or_exit_or_reboot();
256 }
257
258 static void install_crash_handler(void) {
259 static const struct sigaction sa = {
260 .sa_handler = crash,
261 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
262 };
263 int r;
264
265 /* We ignore the return value here, since, we don't mind if we
266 * cannot set up a crash handler */
267 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
268 if (r < 0)
269 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
270 }
271
272 static int console_setup(void) {
273 _cleanup_close_ int tty_fd = -1;
274 int r;
275
276 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
277 if (tty_fd < 0)
278 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
279
280 /* We don't want to force text mode. plymouth may be showing
281 * pictures already from initrd. */
282 r = reset_terminal_fd(tty_fd, false);
283 if (r < 0)
284 return log_error_errno(r, "Failed to reset /dev/console: %m");
285
286 return 0;
287 }
288
289 static int parse_crash_chvt(const char *value) {
290 int b;
291
292 if (safe_atoi(value, &arg_crash_chvt) >= 0)
293 return 0;
294
295 b = parse_boolean(value);
296 if (b < 0)
297 return b;
298
299 if (b > 0)
300 arg_crash_chvt = 0; /* switch to where kmsg goes */
301 else
302 arg_crash_chvt = -1; /* turn off switching */
303
304 return 0;
305 }
306
307 static int parse_confirm_spawn(const char *value, char **console) {
308 char *s;
309 int r;
310
311 r = value ? parse_boolean(value) : 1;
312 if (r == 0) {
313 *console = NULL;
314 return 0;
315 }
316
317 if (r > 0) /* on with default tty */
318 s = strdup("/dev/console");
319 else if (is_path(value)) /* on with fully qualified path */
320 s = strdup(value);
321 else /* on with only a tty file name, not a fully qualified path */
322 s = strjoin("/dev/", value);
323 if (!s)
324 return -ENOMEM;
325
326 *console = s;
327 return 0;
328 }
329
330 static int set_machine_id(const char *m) {
331 sd_id128_t t;
332 assert(m);
333
334 if (sd_id128_from_string(m, &t) < 0)
335 return -EINVAL;
336
337 if (sd_id128_is_null(t))
338 return -EINVAL;
339
340 arg_machine_id = t;
341 return 0;
342 }
343
344 static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
345
346 int r;
347
348 assert(key);
349
350 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
351
352 if (proc_cmdline_value_missing(key, value))
353 return 0;
354
355 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
356 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
357 else if (in_initrd() == !!startswith(key, "rd.")) {
358 if (free_and_strdup(&arg_default_unit, value) < 0)
359 return log_oom();
360 }
361
362 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
363
364 r = value ? parse_boolean(value) : true;
365 if (r < 0)
366 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
367 else
368 arg_dump_core = r;
369
370 } else if (proc_cmdline_key_streq(key, "systemd.early_core_pattern")) {
371
372 if (proc_cmdline_value_missing(key, value))
373 return 0;
374
375 if (path_is_absolute(value))
376 (void) parse_path_argument_and_warn(value, false, &arg_early_core_pattern);
377 else
378 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
379
380 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
381
382 if (!value)
383 arg_crash_chvt = 0; /* turn on */
384 else {
385 r = parse_crash_chvt(value);
386 if (r < 0)
387 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
388 }
389
390 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
391
392 r = value ? parse_boolean(value) : true;
393 if (r < 0)
394 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
395 else
396 arg_crash_shell = r;
397
398 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
399
400 r = value ? parse_boolean(value) : true;
401 if (r < 0)
402 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
403 else
404 arg_crash_reboot = r;
405
406 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
407 char *s;
408
409 r = parse_confirm_spawn(value, &s);
410 if (r < 0)
411 log_warning_errno(r, "Failed to parse confirm_spawn switch %s, ignoring: %m", value);
412 else
413 free_and_replace(arg_confirm_spawn, s);
414
415 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
416
417 r = value ? parse_boolean(value) : true;
418 if (r < 0)
419 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
420 else
421 arg_service_watchdogs = r;
422
423 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
424
425 if (value) {
426 r = parse_show_status(value, &arg_show_status);
427 if (r < 0)
428 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
429 } else
430 arg_show_status = SHOW_STATUS_YES;
431
432 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
433
434 if (proc_cmdline_value_missing(key, value))
435 return 0;
436
437 r = exec_output_from_string(value);
438 if (r < 0)
439 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
440 else
441 arg_default_std_output = r;
442
443 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
444
445 if (proc_cmdline_value_missing(key, value))
446 return 0;
447
448 r = exec_output_from_string(value);
449 if (r < 0)
450 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
451 else
452 arg_default_std_error = r;
453
454 } else if (streq(key, "systemd.setenv")) {
455
456 if (proc_cmdline_value_missing(key, value))
457 return 0;
458
459 if (env_assignment_is_valid(value)) {
460 char **env;
461
462 env = strv_env_set(arg_default_environment, value);
463 if (!env)
464 return log_oom();
465
466 arg_default_environment = env;
467 } else
468 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
469
470 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
471
472 if (proc_cmdline_value_missing(key, value))
473 return 0;
474
475 r = set_machine_id(value);
476 if (r < 0)
477 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
478
479 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
480
481 if (proc_cmdline_value_missing(key, value))
482 return 0;
483
484 r = parse_sec(value, &arg_default_timeout_start_usec);
485 if (r < 0)
486 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
487
488 if (arg_default_timeout_start_usec <= 0)
489 arg_default_timeout_start_usec = USEC_INFINITY;
490
491 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
492
493 if (proc_cmdline_value_missing(key, value))
494 return 0;
495
496 (void) parse_path_argument_and_warn(value, false, &arg_watchdog_device);
497
498 } else if (streq(key, "quiet") && !value) {
499
500 if (arg_show_status == _SHOW_STATUS_INVALID)
501 arg_show_status = SHOW_STATUS_AUTO;
502
503 } else if (streq(key, "debug") && !value) {
504
505 /* Note that log_parse_environment() handles 'debug'
506 * too, and sets the log level to LOG_DEBUG. */
507
508 if (detect_container() > 0)
509 log_set_target(LOG_TARGET_CONSOLE);
510
511 } else if (!value) {
512 const char *target;
513
514 /* SysV compatibility */
515 target = runlevel_to_target(key);
516 if (target)
517 return free_and_strdup(&arg_default_unit, target);
518 }
519
520 return 0;
521 }
522
523 #define DEFINE_SETTER(name, func, descr) \
524 static int name(const char *unit, \
525 const char *filename, \
526 unsigned line, \
527 const char *section, \
528 unsigned section_line, \
529 const char *lvalue, \
530 int ltype, \
531 const char *rvalue, \
532 void *data, \
533 void *userdata) { \
534 \
535 int r; \
536 \
537 assert(filename); \
538 assert(lvalue); \
539 assert(rvalue); \
540 \
541 r = func(rvalue); \
542 if (r < 0) \
543 log_syntax(unit, LOG_ERR, filename, line, r, \
544 "Invalid " descr "'%s': %m", \
545 rvalue); \
546 \
547 return 0; \
548 }
549
550 DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
551 DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
552 DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" );
553 DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
554
555 static int config_parse_cpu_affinity2(
556 const char *unit,
557 const char *filename,
558 unsigned line,
559 const char *section,
560 unsigned section_line,
561 const char *lvalue,
562 int ltype,
563 const char *rvalue,
564 void *data,
565 void *userdata) {
566
567 _cleanup_cpu_free_ cpu_set_t *c = NULL;
568 int ncpus;
569
570 ncpus = parse_cpu_set_and_warn(rvalue, &c, unit, filename, line, lvalue);
571 if (ncpus < 0)
572 return ncpus;
573
574 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
575 log_warning_errno(errno, "Failed to set CPU affinity: %m");
576
577 return 0;
578 }
579
580 static int config_parse_show_status(
581 const char* unit,
582 const char *filename,
583 unsigned line,
584 const char *section,
585 unsigned section_line,
586 const char *lvalue,
587 int ltype,
588 const char *rvalue,
589 void *data,
590 void *userdata) {
591
592 int k;
593 ShowStatus *b = data;
594
595 assert(filename);
596 assert(lvalue);
597 assert(rvalue);
598 assert(data);
599
600 k = parse_show_status(rvalue, b);
601 if (k < 0) {
602 log_syntax(unit, LOG_ERR, filename, line, k, "Failed to parse show status setting, ignoring: %s", rvalue);
603 return 0;
604 }
605
606 return 0;
607 }
608
609 static int config_parse_output_restricted(
610 const char* unit,
611 const char *filename,
612 unsigned line,
613 const char *section,
614 unsigned section_line,
615 const char *lvalue,
616 int ltype,
617 const char *rvalue,
618 void *data,
619 void *userdata) {
620
621 ExecOutput t, *eo = data;
622
623 assert(filename);
624 assert(lvalue);
625 assert(rvalue);
626 assert(data);
627
628 t = exec_output_from_string(rvalue);
629 if (t < 0) {
630 log_syntax(unit, LOG_ERR, filename, line, 0, "Failed to parse output type, ignoring: %s", rvalue);
631 return 0;
632 }
633
634 if (IN_SET(t, EXEC_OUTPUT_SOCKET, EXEC_OUTPUT_NAMED_FD, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND)) {
635 log_syntax(unit, LOG_ERR, filename, line, 0, "Standard output types socket, fd:, file:, append: are not supported as defaults, ignoring: %s", rvalue);
636 return 0;
637 }
638
639 *eo = t;
640 return 0;
641 }
642
643 static int config_parse_crash_chvt(
644 const char* unit,
645 const char *filename,
646 unsigned line,
647 const char *section,
648 unsigned section_line,
649 const char *lvalue,
650 int ltype,
651 const char *rvalue,
652 void *data,
653 void *userdata) {
654
655 int r;
656
657 assert(filename);
658 assert(lvalue);
659 assert(rvalue);
660
661 r = parse_crash_chvt(rvalue);
662 if (r < 0) {
663 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue);
664 return 0;
665 }
666
667 return 0;
668 }
669
670 static int parse_config_file(void) {
671
672 const ConfigTableItem items[] = {
673 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
674 { "Manager", "LogTarget", config_parse_target, 0, NULL },
675 { "Manager", "LogColor", config_parse_color, 0, NULL },
676 { "Manager", "LogLocation", config_parse_location, 0, NULL },
677 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
678 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, NULL },
679 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, NULL },
680 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
681 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
682 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
683 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
684 { "Manager", "JoinControllers", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
685 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
686 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
687 { "Manager", "WatchdogDevice", config_parse_path, 0, &arg_watchdog_device },
688 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
689 { "Manager", "NoNewPrivileges", config_parse_bool, 0, &arg_no_new_privs },
690 #if HAVE_SECCOMP
691 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
692 #endif
693 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
694 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
695 { "Manager", "DefaultStandardOutput", config_parse_output_restricted,0, &arg_default_std_output },
696 { "Manager", "DefaultStandardError", config_parse_output_restricted,0, &arg_default_std_error },
697 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
698 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
699 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
700 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
701 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec, 0, &arg_default_start_limit_interval },
702 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
703 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
704 { "Manager", "DefaultLimitCPU", config_parse_rlimit, RLIMIT_CPU, arg_default_rlimit },
705 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit, RLIMIT_FSIZE, arg_default_rlimit },
706 { "Manager", "DefaultLimitDATA", config_parse_rlimit, RLIMIT_DATA, arg_default_rlimit },
707 { "Manager", "DefaultLimitSTACK", config_parse_rlimit, RLIMIT_STACK, arg_default_rlimit },
708 { "Manager", "DefaultLimitCORE", config_parse_rlimit, RLIMIT_CORE, arg_default_rlimit },
709 { "Manager", "DefaultLimitRSS", config_parse_rlimit, RLIMIT_RSS, arg_default_rlimit },
710 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit, RLIMIT_NOFILE, arg_default_rlimit },
711 { "Manager", "DefaultLimitAS", config_parse_rlimit, RLIMIT_AS, arg_default_rlimit },
712 { "Manager", "DefaultLimitNPROC", config_parse_rlimit, RLIMIT_NPROC, arg_default_rlimit },
713 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit, RLIMIT_MEMLOCK, arg_default_rlimit },
714 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit, RLIMIT_LOCKS, arg_default_rlimit },
715 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit, RLIMIT_SIGPENDING, arg_default_rlimit },
716 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit, RLIMIT_MSGQUEUE, arg_default_rlimit },
717 { "Manager", "DefaultLimitNICE", config_parse_rlimit, RLIMIT_NICE, arg_default_rlimit },
718 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit, RLIMIT_RTPRIO, arg_default_rlimit },
719 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit, RLIMIT_RTTIME, arg_default_rlimit },
720 { "Manager", "DefaultCPUAccounting", config_parse_tristate, 0, &arg_default_cpu_accounting },
721 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
722 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
723 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
724 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
725 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
726 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
727 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
728 {}
729 };
730
731 const char *fn, *conf_dirs_nulstr;
732
733 fn = arg_system ?
734 PKGSYSCONFDIR "/system.conf" :
735 PKGSYSCONFDIR "/user.conf";
736
737 conf_dirs_nulstr = arg_system ?
738 CONF_PATHS_NULSTR("systemd/system.conf.d") :
739 CONF_PATHS_NULSTR("systemd/user.conf.d");
740
741 (void) config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, CONFIG_PARSE_WARN, NULL);
742
743 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
744 * like everywhere else. */
745 if (arg_default_timeout_start_usec <= 0)
746 arg_default_timeout_start_usec = USEC_INFINITY;
747 if (arg_default_timeout_stop_usec <= 0)
748 arg_default_timeout_stop_usec = USEC_INFINITY;
749
750 return 0;
751 }
752
753 static void set_manager_defaults(Manager *m) {
754
755 assert(m);
756
757 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
758 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
759 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
760
761 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
762 m->default_std_output = arg_default_std_output;
763 m->default_std_error = arg_default_std_error;
764 m->default_timeout_start_usec = arg_default_timeout_start_usec;
765 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
766 m->default_restart_usec = arg_default_restart_usec;
767 m->default_start_limit_interval = arg_default_start_limit_interval;
768 m->default_start_limit_burst = arg_default_start_limit_burst;
769
770 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
771 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
772 if (arg_default_cpu_accounting >= 0)
773 m->default_cpu_accounting = arg_default_cpu_accounting;
774 else
775 m->default_cpu_accounting = cpu_accounting_is_cheap();
776
777 m->default_io_accounting = arg_default_io_accounting;
778 m->default_ip_accounting = arg_default_ip_accounting;
779 m->default_blockio_accounting = arg_default_blockio_accounting;
780 m->default_memory_accounting = arg_default_memory_accounting;
781 m->default_tasks_accounting = arg_default_tasks_accounting;
782 m->default_tasks_max = arg_default_tasks_max;
783
784 (void) manager_set_default_rlimits(m, arg_default_rlimit);
785
786 (void) manager_default_environment(m);
787 (void) manager_transient_environment_add(m, arg_default_environment);
788 }
789
790 static void set_manager_settings(Manager *m) {
791
792 assert(m);
793
794 /* Propagates the various manager settings into the manager object, i.e. properties that effect the manager
795 * itself (as opposed to just being inherited into newly allocated units, see set_manager_defaults() above). */
796
797 m->confirm_spawn = arg_confirm_spawn;
798 m->service_watchdogs = arg_service_watchdogs;
799 m->runtime_watchdog = arg_runtime_watchdog;
800 m->shutdown_watchdog = arg_shutdown_watchdog;
801 m->cad_burst_action = arg_cad_burst_action;
802
803 manager_set_show_status(m, arg_show_status);
804 }
805
806 static int parse_argv(int argc, char *argv[]) {
807 enum {
808 ARG_LOG_LEVEL = 0x100,
809 ARG_LOG_TARGET,
810 ARG_LOG_COLOR,
811 ARG_LOG_LOCATION,
812 ARG_UNIT,
813 ARG_SYSTEM,
814 ARG_USER,
815 ARG_TEST,
816 ARG_NO_PAGER,
817 ARG_VERSION,
818 ARG_DUMP_CONFIGURATION_ITEMS,
819 ARG_DUMP_BUS_PROPERTIES,
820 ARG_DUMP_CORE,
821 ARG_CRASH_CHVT,
822 ARG_CRASH_SHELL,
823 ARG_CRASH_REBOOT,
824 ARG_CONFIRM_SPAWN,
825 ARG_SHOW_STATUS,
826 ARG_DESERIALIZE,
827 ARG_SWITCHED_ROOT,
828 ARG_DEFAULT_STD_OUTPUT,
829 ARG_DEFAULT_STD_ERROR,
830 ARG_MACHINE_ID,
831 ARG_SERVICE_WATCHDOGS,
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-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
848 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
849 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
850 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
851 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
852 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
853 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
854 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
855 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
856 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
857 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
858 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
859 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
860 {}
861 };
862
863 int c, r;
864
865 assert(argc >= 1);
866 assert(argv);
867
868 if (getpid_cached() == 1)
869 opterr = 0;
870
871 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
872
873 switch (c) {
874
875 case ARG_LOG_LEVEL:
876 r = log_set_max_level_from_string(optarg);
877 if (r < 0)
878 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
879
880 break;
881
882 case ARG_LOG_TARGET:
883 r = log_set_target_from_string(optarg);
884 if (r < 0)
885 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
886
887 break;
888
889 case ARG_LOG_COLOR:
890
891 if (optarg) {
892 r = log_show_color_from_string(optarg);
893 if (r < 0)
894 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
895 optarg);
896 } else
897 log_show_color(true);
898
899 break;
900
901 case ARG_LOG_LOCATION:
902 if (optarg) {
903 r = log_show_location_from_string(optarg);
904 if (r < 0)
905 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
906 optarg);
907 } else
908 log_show_location(true);
909
910 break;
911
912 case ARG_DEFAULT_STD_OUTPUT:
913 r = exec_output_from_string(optarg);
914 if (r < 0)
915 return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
916 optarg);
917 arg_default_std_output = r;
918 break;
919
920 case ARG_DEFAULT_STD_ERROR:
921 r = exec_output_from_string(optarg);
922 if (r < 0)
923 return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
924 optarg);
925 arg_default_std_error = r;
926 break;
927
928 case ARG_UNIT:
929 r = free_and_strdup(&arg_default_unit, optarg);
930 if (r < 0)
931 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
932
933 break;
934
935 case ARG_SYSTEM:
936 arg_system = true;
937 break;
938
939 case ARG_USER:
940 arg_system = false;
941 break;
942
943 case ARG_TEST:
944 arg_action = ACTION_TEST;
945 break;
946
947 case ARG_NO_PAGER:
948 arg_pager_flags |= PAGER_DISABLE;
949 break;
950
951 case ARG_VERSION:
952 arg_action = ACTION_VERSION;
953 break;
954
955 case ARG_DUMP_CONFIGURATION_ITEMS:
956 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
957 break;
958
959 case ARG_DUMP_BUS_PROPERTIES:
960 arg_action = ACTION_DUMP_BUS_PROPERTIES;
961 break;
962
963 case ARG_DUMP_CORE:
964 if (!optarg)
965 arg_dump_core = true;
966 else {
967 r = parse_boolean(optarg);
968 if (r < 0)
969 return log_error_errno(r, "Failed to parse dump core boolean: \"%s\": %m",
970 optarg);
971 arg_dump_core = r;
972 }
973 break;
974
975 case ARG_CRASH_CHVT:
976 r = parse_crash_chvt(optarg);
977 if (r < 0)
978 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
979 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\": %m",
989 optarg);
990 arg_crash_shell = r;
991 }
992 break;
993
994 case ARG_CRASH_REBOOT:
995 if (!optarg)
996 arg_crash_reboot = true;
997 else {
998 r = parse_boolean(optarg);
999 if (r < 0)
1000 return log_error_errno(r, "Failed to parse crash shell boolean: \"%s\": %m",
1001 optarg);
1002 arg_crash_reboot = r;
1003 }
1004 break;
1005
1006 case ARG_CONFIRM_SPAWN:
1007 arg_confirm_spawn = mfree(arg_confirm_spawn);
1008
1009 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
1010 if (r < 0)
1011 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
1012 optarg);
1013 break;
1014
1015 case ARG_SERVICE_WATCHDOGS:
1016 r = parse_boolean(optarg);
1017 if (r < 0)
1018 return log_error_errno(r, "Failed to parse service watchdogs boolean: \"%s\": %m",
1019 optarg);
1020 arg_service_watchdogs = r;
1021 break;
1022
1023 case ARG_SHOW_STATUS:
1024 if (optarg) {
1025 r = parse_show_status(optarg, &arg_show_status);
1026 if (r < 0)
1027 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
1028 optarg);
1029 } else
1030 arg_show_status = SHOW_STATUS_YES;
1031 break;
1032
1033 case ARG_DESERIALIZE: {
1034 int fd;
1035 FILE *f;
1036
1037 r = safe_atoi(optarg, &fd);
1038 if (r < 0)
1039 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
1040 if (fd < 0)
1041 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1042 "Invalid deserialize fd: %d",
1043 fd);
1044
1045 (void) fd_cloexec(fd, true);
1046
1047 f = fdopen(fd, "r");
1048 if (!f)
1049 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
1050
1051 safe_fclose(arg_serialization);
1052 arg_serialization = f;
1053
1054 break;
1055 }
1056
1057 case ARG_SWITCHED_ROOT:
1058 arg_switched_root = true;
1059 break;
1060
1061 case ARG_MACHINE_ID:
1062 r = set_machine_id(optarg);
1063 if (r < 0)
1064 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
1065 break;
1066
1067 case 'h':
1068 arg_action = ACTION_HELP;
1069 break;
1070
1071 case 'D':
1072 log_set_max_level(LOG_DEBUG);
1073 break;
1074
1075 case 'b':
1076 case 's':
1077 case 'z':
1078 /* Just to eat away the sysvinit kernel
1079 * cmdline args without getopt() error
1080 * messages that we'll parse in
1081 * parse_proc_cmdline_word() or ignore. */
1082
1083 case '?':
1084 if (getpid_cached() != 1)
1085 return -EINVAL;
1086 else
1087 return 0;
1088
1089 default:
1090 assert_not_reached("Unhandled option code.");
1091 }
1092
1093 if (optind < argc && getpid_cached() != 1) {
1094 /* Hmm, when we aren't run as init system
1095 * let's complain about excess arguments */
1096
1097 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1098 "Excess arguments.");
1099 }
1100
1101 return 0;
1102 }
1103
1104 static int help(void) {
1105 _cleanup_free_ char *link = NULL;
1106 int r;
1107
1108 r = terminal_urlify_man("systemd", "1", &link);
1109 if (r < 0)
1110 return log_oom();
1111
1112 printf("%s [OPTIONS...]\n\n"
1113 "Starts up and maintains the system or user services.\n\n"
1114 " -h --help Show this help\n"
1115 " --version Show version\n"
1116 " --test Determine startup sequence, dump it and exit\n"
1117 " --no-pager Do not pipe output into a pager\n"
1118 " --dump-configuration-items Dump understood unit configuration items\n"
1119 " --dump-bus-properties Dump exposed bus properties\n"
1120 " --unit=UNIT Set default unit\n"
1121 " --system Run a system instance, even if PID != 1\n"
1122 " --user Run a user instance\n"
1123 " --dump-core[=BOOL] Dump core on crash\n"
1124 " --crash-vt=NR Change to specified VT on crash\n"
1125 " --crash-reboot[=BOOL] Reboot on crash\n"
1126 " --crash-shell[=BOOL] Run shell on crash\n"
1127 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1128 " --show-status[=BOOL] Show status updates on the console during bootup\n"
1129 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
1130 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1131 " --log-color[=BOOL] Highlight important log messages\n"
1132 " --log-location[=BOOL] Include code location in log messages\n"
1133 " --default-standard-output= Set default standard output for services\n"
1134 " --default-standard-error= Set default standard error output for services\n"
1135 "\nSee the %s for details.\n"
1136 , program_invocation_short_name
1137 , link
1138 );
1139
1140 return 0;
1141 }
1142
1143 static int prepare_reexecute(
1144 Manager *m,
1145 FILE **ret_f,
1146 FDSet **ret_fds,
1147 bool switching_root) {
1148
1149 _cleanup_fdset_free_ FDSet *fds = NULL;
1150 _cleanup_fclose_ FILE *f = NULL;
1151 int r;
1152
1153 assert(m);
1154 assert(ret_f);
1155 assert(ret_fds);
1156
1157 r = manager_open_serialization(m, &f);
1158 if (r < 0)
1159 return log_error_errno(r, "Failed to create serialization file: %m");
1160
1161 /* Make sure nothing is really destructed when we shut down */
1162 m->n_reloading++;
1163 bus_manager_send_reloading(m, true);
1164
1165 fds = fdset_new();
1166 if (!fds)
1167 return log_oom();
1168
1169 r = manager_serialize(m, f, fds, switching_root);
1170 if (r < 0)
1171 return r;
1172
1173 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1174 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
1175
1176 r = fd_cloexec(fileno(f), false);
1177 if (r < 0)
1178 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
1179
1180 r = fdset_cloexec(fds, false);
1181 if (r < 0)
1182 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
1183
1184 *ret_f = TAKE_PTR(f);
1185 *ret_fds = TAKE_PTR(fds);
1186
1187 return 0;
1188 }
1189
1190 static void bump_file_max_and_nr_open(void) {
1191
1192 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large numbers of file
1193 * descriptors are no longer a performance problem and their memory is properly tracked by memcg, thus counting
1194 * them and limiting them in another two layers of limits is unnecessary and just complicates things. This
1195 * function hence turns off 2 of the 4 levels of limits on file descriptors, and makes RLIMIT_NOLIMIT (soft +
1196 * hard) the only ones that really matter. */
1197
1198 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1199 _cleanup_free_ char *t = NULL;
1200 int r;
1201 #endif
1202
1203 #if BUMP_PROC_SYS_FS_FILE_MAX
1204 /* I so wanted to use STRINGIFY(ULONG_MAX) here, but alas we can't as glibc/gcc define that as
1205 * "(0x7fffffffffffffffL * 2UL + 1UL)". Seriously. 😢 */
1206 if (asprintf(&t, "%lu\n", ULONG_MAX) < 0) {
1207 log_oom();
1208 return;
1209 }
1210
1211 r = sysctl_write("fs/file-max", t);
1212 if (r < 0)
1213 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.file-max, ignoring: %m");
1214 #endif
1215
1216 #if BUMP_PROC_SYS_FS_FILE_MAX && BUMP_PROC_SYS_FS_NR_OPEN
1217 t = mfree(t);
1218 #endif
1219
1220 #if BUMP_PROC_SYS_FS_NR_OPEN
1221 int v = INT_MAX;
1222
1223 /* Arg! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know what they
1224 * are. The expression by which the maximum is determined is dependent on the architecture, and is something we
1225 * don't really want to copy to userspace, as it is dependent on implementation details of the kernel. Since
1226 * the kernel doesn't expose the maximum value to us, we can only try and hope. Hence, let's start with
1227 * INT_MAX, and then keep halving the value until we find one that works. Ugly? Yes, absolutely, but kernel
1228 * APIs are kernel APIs, so what do can we do... 🤯 */
1229
1230 for (;;) {
1231 int k;
1232
1233 v &= ~(__SIZEOF_POINTER__ - 1); /* Round down to next multiple of the pointer size */
1234 if (v < 1024) {
1235 log_warning("Can't bump fs.nr_open, value too small.");
1236 break;
1237 }
1238
1239 k = read_nr_open();
1240 if (k < 0) {
1241 log_error_errno(k, "Failed to read fs.nr_open: %m");
1242 break;
1243 }
1244 if (k >= v) { /* Already larger */
1245 log_debug("Skipping bump, value is already larger.");
1246 break;
1247 }
1248
1249 if (asprintf(&t, "%i\n", v) < 0) {
1250 log_oom();
1251 return;
1252 }
1253
1254 r = sysctl_write("fs/nr_open", t);
1255 t = mfree(t);
1256 if (r == -EINVAL) {
1257 log_debug("Couldn't write fs.nr_open as %i, halving it.", v);
1258 v /= 2;
1259 continue;
1260 }
1261 if (r < 0) {
1262 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.nr_open, ignoring: %m");
1263 break;
1264 }
1265
1266 log_debug("Successfully bumped fs.nr_open to %i", v);
1267 break;
1268 }
1269 #endif
1270 }
1271
1272 static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
1273 struct rlimit new_rlimit;
1274 int r, nr;
1275
1276 assert(saved_rlimit);
1277
1278 /* Save the original RLIMIT_NOFILE so that we can reset it later when transitioning from the initrd to the main
1279 * systemd or suchlike. */
1280 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
1281 return log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
1282
1283 /* Get the underlying absolute limit the kernel enforces */
1284 nr = read_nr_open();
1285
1286 /* Make sure forked processes get limits based on the original kernel setting */
1287 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1288 struct rlimit *rl;
1289
1290 rl = newdup(struct rlimit, saved_rlimit, 1);
1291 if (!rl)
1292 return log_oom();
1293
1294 /* Bump the hard limit for system services to a substantially higher value. The default hard limit
1295 * current kernels set is pretty low (4K), mostly for historical reasons. According to kernel
1296 * developers, the fd handling in recent kernels has been optimized substantially enough, so that we
1297 * can bump the limit now, without paying too high a price in memory or performance. Note however that
1298 * we only bump the hard limit, not the soft limit. That's because select() works the way it works, and
1299 * chokes on fds >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
1300 * unexpecting programs that they get fds higher than what they can process using select(). By only
1301 * bumping the hard limit but leaving the low limit as it is we avoid this pitfall: programs that are
1302 * written by folks aware of the select() problem in mind (and thus use poll()/epoll instead of
1303 * select(), the way everybody should) can explicitly opt into high fds by bumping their soft limit
1304 * beyond 1024, to the hard limit we pass. */
1305 if (arg_system)
1306 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
1307
1308 /* If for some reason we were invoked with a soft limit above 1024 (which should never
1309 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
1310 * instance), then lower what we pass on to not confuse our children */
1311 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
1312
1313 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1314 }
1315
1316 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1317 new_rlimit = (struct rlimit) {
1318 .rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
1319 .rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
1320 };
1321
1322 /* Shortcut if nothing changes. */
1323 if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
1324 saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
1325 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1326 return 0;
1327 }
1328
1329 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1330 * both hard and soft. */
1331 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
1332 if (r < 0)
1333 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1334
1335 return 0;
1336 }
1337
1338 static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
1339 struct rlimit new_rlimit;
1340 int r;
1341
1342 assert(saved_rlimit);
1343
1344 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK which should
1345 * normally disable such checks. We need them to implement IPAccessAllow= and IPAccessDeny=, hence let's bump
1346 * the value high enough for our user. */
1347
1348 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit) < 0)
1349 return log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
1350
1351 /* Pass the original value down to invoked processes */
1352 if (!arg_default_rlimit[RLIMIT_MEMLOCK]) {
1353 struct rlimit *rl;
1354
1355 rl = newdup(struct rlimit, saved_rlimit, 1);
1356 if (!rl)
1357 return log_oom();
1358
1359 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
1360 }
1361
1362 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1363 * must be unsigned, hence this is a given, but let's make this clear here. */
1364 assert_cc(RLIM_INFINITY > 0);
1365
1366 new_rlimit = (struct rlimit) {
1367 .rlim_cur = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur),
1368 .rlim_max = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max),
1369 };
1370
1371 if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
1372 saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
1373 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1374 return 0;
1375 }
1376
1377 r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
1378 if (r < 0)
1379 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1380
1381 return 0;
1382 }
1383
1384 static void test_usr(void) {
1385
1386 /* Check that /usr is either on the same file system as / or mounted already. */
1387
1388 if (dir_is_empty("/usr") <= 0)
1389 return;
1390
1391 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1392 "Some things will probably break (sometimes even silently) in mysterious ways. "
1393 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1394 }
1395
1396 static int enforce_syscall_archs(Set *archs) {
1397 #if HAVE_SECCOMP
1398 int r;
1399
1400 if (!is_seccomp_available())
1401 return 0;
1402
1403 r = seccomp_restrict_archs(arg_syscall_archs);
1404 if (r < 0)
1405 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
1406 #endif
1407 return 0;
1408 }
1409
1410 static int status_welcome(void) {
1411 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1412 int r;
1413
1414 if (IN_SET(arg_show_status, SHOW_STATUS_NO, SHOW_STATUS_AUTO))
1415 return 0;
1416
1417 r = parse_os_release(NULL,
1418 "PRETTY_NAME", &pretty_name,
1419 "ANSI_COLOR", &ansi_color,
1420 NULL);
1421 if (r < 0)
1422 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1423 "Failed to read os-release file, ignoring: %m");
1424
1425 if (log_get_show_color())
1426 return status_printf(NULL, 0,
1427 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1428 isempty(ansi_color) ? "1" : ansi_color,
1429 isempty(pretty_name) ? "Linux" : pretty_name);
1430 else
1431 return status_printf(NULL, 0,
1432 "\nWelcome to %s!\n",
1433 isempty(pretty_name) ? "Linux" : pretty_name);
1434 }
1435
1436 static int write_container_id(void) {
1437 const char *c;
1438 int r;
1439
1440 c = getenv("container");
1441 if (isempty(c))
1442 return 0;
1443
1444 RUN_WITH_UMASK(0022)
1445 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
1446 if (r < 0)
1447 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
1448
1449 return 1;
1450 }
1451
1452 static int bump_unix_max_dgram_qlen(void) {
1453 _cleanup_free_ char *qlen = NULL;
1454 unsigned long v;
1455 int r;
1456
1457 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set the value
1458 * really really early during boot, so that it is actually applied to all our sockets, including the
1459 * $NOTIFY_SOCKET one. */
1460
1461 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1462 if (r < 0)
1463 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1464
1465 r = safe_atolu(qlen, &v);
1466 if (r < 0)
1467 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
1468
1469 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1470 return 0;
1471
1472 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER, "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
1473 if (r < 0)
1474 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1475 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1476
1477 return 1;
1478 }
1479
1480 static int fixup_environment(void) {
1481 _cleanup_free_ char *term = NULL;
1482 const char *t;
1483 int r;
1484
1485 /* Only fix up the environment when we are started as PID 1 */
1486 if (getpid_cached() != 1)
1487 return 0;
1488
1489 /* We expect the environment to be set correctly if run inside a container. */
1490 if (detect_container() > 0)
1491 return 0;
1492
1493 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the backend
1494 * device used by the console. We try to make a better guess here since some consoles might not have support
1495 * for color mode for example.
1496 *
1497 * However if TERM was configured through the kernel command line then leave it alone. */
1498 r = proc_cmdline_get_key("TERM", 0, &term);
1499 if (r < 0)
1500 return r;
1501
1502 t = term ?: default_term_for_tty("/dev/console");
1503
1504 if (setenv("TERM", t, 1) < 0)
1505 return -errno;
1506
1507 return 0;
1508 }
1509
1510 static void redirect_telinit(int argc, char *argv[]) {
1511
1512 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1513
1514 #if HAVE_SYSV_COMPAT
1515 if (getpid_cached() == 1)
1516 return;
1517
1518 if (!strstr(program_invocation_short_name, "init"))
1519 return;
1520
1521 execv(SYSTEMCTL_BINARY_PATH, argv);
1522 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1523 exit(EXIT_FAILURE);
1524 #endif
1525 }
1526
1527 static int become_shutdown(
1528 const char *shutdown_verb,
1529 int retval) {
1530
1531 char log_level[DECIMAL_STR_MAX(int) + 1],
1532 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1533 timeout[DECIMAL_STR_MAX(usec_t) + 1];
1534
1535 const char* command_line[13] = {
1536 SYSTEMD_SHUTDOWN_BINARY_PATH,
1537 shutdown_verb,
1538 "--timeout", timeout,
1539 "--log-level", log_level,
1540 "--log-target",
1541 };
1542
1543 _cleanup_strv_free_ char **env_block = NULL;
1544 size_t pos = 7;
1545 int r;
1546
1547 assert(shutdown_verb);
1548 assert(!command_line[pos]);
1549 env_block = strv_copy(environ);
1550
1551 xsprintf(log_level, "%d", log_get_max_level());
1552 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
1553
1554 switch (log_get_target()) {
1555
1556 case LOG_TARGET_KMSG:
1557 case LOG_TARGET_JOURNAL_OR_KMSG:
1558 case LOG_TARGET_SYSLOG_OR_KMSG:
1559 command_line[pos++] = "kmsg";
1560 break;
1561
1562 case LOG_TARGET_NULL:
1563 command_line[pos++] = "null";
1564 break;
1565
1566 case LOG_TARGET_CONSOLE:
1567 default:
1568 command_line[pos++] = "console";
1569 break;
1570 };
1571
1572 if (log_get_show_color())
1573 command_line[pos++] = "--log-color";
1574
1575 if (log_get_show_location())
1576 command_line[pos++] = "--log-location";
1577
1578 if (streq(shutdown_verb, "exit")) {
1579 command_line[pos++] = "--exit-code";
1580 command_line[pos++] = exit_code;
1581 xsprintf(exit_code, "%d", retval);
1582 }
1583
1584 assert(pos < ELEMENTSOF(command_line));
1585
1586 if (streq(shutdown_verb, "reboot") &&
1587 arg_shutdown_watchdog > 0 &&
1588 arg_shutdown_watchdog != USEC_INFINITY) {
1589
1590 char *e;
1591
1592 /* If we reboot let's set the shutdown
1593 * watchdog and tell the shutdown binary to
1594 * repeatedly ping it */
1595 r = watchdog_set_timeout(&arg_shutdown_watchdog);
1596 watchdog_close(r < 0);
1597
1598 /* Tell the binary how often to ping, ignore failure */
1599 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
1600 (void) strv_consume(&env_block, e);
1601
1602 if (arg_watchdog_device &&
1603 asprintf(&e, "WATCHDOG_DEVICE=%s", arg_watchdog_device) > 0)
1604 (void) strv_consume(&env_block, e);
1605 } else
1606 watchdog_close(true);
1607
1608 /* Avoid the creation of new processes forked by the
1609 * kernel; at this point, we will not listen to the
1610 * signals anyway */
1611 if (detect_container() <= 0)
1612 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1613
1614 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1615 return -errno;
1616 }
1617
1618 static void initialize_clock(void) {
1619 int r;
1620
1621 if (clock_is_localtime(NULL) > 0) {
1622 int min;
1623
1624 /*
1625 * The very first call of settimeofday() also does a time warp in the kernel.
1626 *
1627 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1628 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1629 * the RTC alone if the registry tells that the RTC runs in UTC.
1630 */
1631 r = clock_set_timezone(&min);
1632 if (r < 0)
1633 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1634 else
1635 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1636
1637 } else if (!in_initrd()) {
1638 /*
1639 * Do a dummy very first call to seal the kernel's time warp magic.
1640 *
1641 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1642 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1643 * until we reach the real system.
1644 *
1645 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1646 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1647 * be treated as UTC that way.
1648 */
1649 (void) clock_reset_timewarp();
1650 }
1651
1652 r = clock_apply_epoch();
1653 if (r < 0)
1654 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1655 else if (r > 0)
1656 log_info("System time before build time, advancing clock.");
1657 }
1658
1659 static void initialize_coredump(bool skip_setup) {
1660 #if ENABLE_COREDUMP
1661 if (getpid_cached() != 1)
1662 return;
1663
1664 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1665 * will process core dumps for system services by default. */
1666 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1667 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1668
1669 /* But at the same time, turn off the core_pattern logic by default, so that no
1670 * coredumps are stored until the systemd-coredump tool is enabled via
1671 * sysctl. However it can be changed via the kernel command line later so core
1672 * dumps can still be generated during early startup and in initramfs. */
1673 if (!skip_setup)
1674 disable_coredumps();
1675 #endif
1676 }
1677
1678 static void initialize_core_pattern(bool skip_setup) {
1679 int r;
1680
1681 if (skip_setup || !arg_early_core_pattern)
1682 return;
1683
1684 if (getpid_cached() != 1)
1685 return;
1686
1687 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
1688 if (r < 0)
1689 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m", arg_early_core_pattern);
1690 }
1691
1692 static void do_reexecute(
1693 int argc,
1694 char *argv[],
1695 const struct rlimit *saved_rlimit_nofile,
1696 const struct rlimit *saved_rlimit_memlock,
1697 FDSet *fds,
1698 const char *switch_root_dir,
1699 const char *switch_root_init,
1700 const char **ret_error_message) {
1701
1702 unsigned i, j, args_size;
1703 const char **args;
1704 int r;
1705
1706 assert(saved_rlimit_nofile);
1707 assert(saved_rlimit_memlock);
1708 assert(ret_error_message);
1709
1710 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get rebooted while
1711 * we do that */
1712 watchdog_close(true);
1713
1714 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1715 * the kernel default to its child processes */
1716 if (saved_rlimit_nofile->rlim_cur != 0)
1717 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
1718 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
1719 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1720
1721 if (switch_root_dir) {
1722 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1723 * SIGCHLD for them after deserializing. */
1724 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
1725
1726 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1727 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
1728 if (r < 0)
1729 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1730 }
1731
1732 args_size = MAX(6, argc+1);
1733 args = newa(const char*, args_size);
1734
1735 if (!switch_root_init) {
1736 char sfd[DECIMAL_STR_MAX(int) + 1];
1737
1738 /* First try to spawn ourselves with the right path, and with full serialization. We do this only if
1739 * the user didn't specify an explicit init to spawn. */
1740
1741 assert(arg_serialization);
1742 assert(fds);
1743
1744 xsprintf(sfd, "%i", fileno(arg_serialization));
1745
1746 i = 0;
1747 args[i++] = SYSTEMD_BINARY_PATH;
1748 if (switch_root_dir)
1749 args[i++] = "--switched-root";
1750 args[i++] = arg_system ? "--system" : "--user";
1751 args[i++] = "--deserialize";
1752 args[i++] = sfd;
1753 args[i++] = NULL;
1754
1755 assert(i <= args_size);
1756
1757 /*
1758 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do this is on
1759 * its own on exec(), but it will do it on exit(). Hence, to ensure we get a summary here, fork() off
1760 * a child, let it exit() cleanly, so that it prints the summary, and wait() for it in the parent,
1761 * before proceeding into the exec().
1762 */
1763 valgrind_summary_hack();
1764
1765 (void) execv(args[0], (char* const*) args);
1766 log_debug_errno(errno, "Failed to execute our own binary, trying fallback: %m");
1767 }
1768
1769 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and envp[]. (Well,
1770 * modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[], but let's hope that
1771 * doesn't matter.) */
1772
1773 arg_serialization = safe_fclose(arg_serialization);
1774 fds = fdset_free(fds);
1775
1776 /* Reopen the console */
1777 (void) make_console_stdio();
1778
1779 for (j = 1, i = 1; j < (unsigned) argc; j++)
1780 args[i++] = argv[j];
1781 args[i++] = NULL;
1782 assert(i <= args_size);
1783
1784 /* Reenable any blocked signals, especially important if we switch from initial ramdisk to init=... */
1785 (void) reset_all_signal_handlers();
1786 (void) reset_signal_mask();
1787 (void) rlimit_nofile_safe();
1788
1789 if (switch_root_init) {
1790 args[0] = switch_root_init;
1791 (void) execv(args[0], (char* const*) args);
1792 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
1793 }
1794
1795 args[0] = "/sbin/init";
1796 (void) execv(args[0], (char* const*) args);
1797 r = -errno;
1798
1799 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1800 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1801 "Failed to execute /sbin/init");
1802
1803 if (r == -ENOENT) {
1804 log_warning("No /sbin/init, trying fallback");
1805
1806 args[0] = "/bin/sh";
1807 args[1] = NULL;
1808 (void) execv(args[0], (char* const*) args);
1809 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1810 } else
1811 log_warning_errno(r, "Failed to execute /sbin/init, giving up: %m");
1812
1813 *ret_error_message = "Failed to execute fallback shell";
1814 }
1815
1816 static int invoke_main_loop(
1817 Manager *m,
1818 bool *ret_reexecute,
1819 int *ret_retval, /* Return parameters relevant for shutting down */
1820 const char **ret_shutdown_verb, /* … */
1821 FDSet **ret_fds, /* Return parameters for reexecuting */
1822 char **ret_switch_root_dir, /* … */
1823 char **ret_switch_root_init, /* … */
1824 const char **ret_error_message) {
1825
1826 int r;
1827
1828 assert(m);
1829 assert(ret_reexecute);
1830 assert(ret_retval);
1831 assert(ret_shutdown_verb);
1832 assert(ret_fds);
1833 assert(ret_switch_root_dir);
1834 assert(ret_switch_root_init);
1835 assert(ret_error_message);
1836
1837 for (;;) {
1838 r = manager_loop(m);
1839 if (r < 0) {
1840 *ret_error_message = "Failed to run main loop";
1841 return log_emergency_errno(r, "Failed to run main loop: %m");
1842 }
1843
1844 switch ((ManagerObjective) r) {
1845
1846 case MANAGER_RELOAD: {
1847 LogTarget saved_log_target;
1848 int saved_log_level;
1849
1850 log_info("Reloading.");
1851
1852 /* First, save any overridden log level/target, then parse the configuration file, which might
1853 * change the log level to new settings. */
1854
1855 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
1856 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
1857
1858 r = parse_config_file();
1859 if (r < 0)
1860 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
1861
1862 set_manager_defaults(m);
1863
1864 if (saved_log_level >= 0)
1865 manager_override_log_level(m, saved_log_level);
1866 if (saved_log_target >= 0)
1867 manager_override_log_target(m, saved_log_target);
1868
1869 r = manager_reload(m);
1870 if (r < 0)
1871 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1872 m->objective = MANAGER_OK;
1873
1874 break;
1875 }
1876
1877 case MANAGER_REEXECUTE:
1878
1879 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1880 if (r < 0) {
1881 *ret_error_message = "Failed to prepare for reexecution";
1882 return r;
1883 }
1884
1885 log_notice("Reexecuting.");
1886
1887 *ret_reexecute = true;
1888 *ret_retval = EXIT_SUCCESS;
1889 *ret_shutdown_verb = NULL;
1890 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1891
1892 return 0;
1893
1894 case MANAGER_SWITCH_ROOT:
1895 if (!m->switch_root_init) {
1896 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1897 if (r < 0) {
1898 *ret_error_message = "Failed to prepare for reexecution";
1899 return r;
1900 }
1901 } else
1902 *ret_fds = NULL;
1903
1904 log_notice("Switching root.");
1905
1906 *ret_reexecute = true;
1907 *ret_retval = EXIT_SUCCESS;
1908 *ret_shutdown_verb = NULL;
1909
1910 /* Steal the switch root parameters */
1911 *ret_switch_root_dir = m->switch_root;
1912 *ret_switch_root_init = m->switch_root_init;
1913 m->switch_root = m->switch_root_init = NULL;
1914
1915 return 0;
1916
1917 case MANAGER_EXIT:
1918
1919 if (MANAGER_IS_USER(m)) {
1920 log_debug("Exit.");
1921
1922 *ret_reexecute = false;
1923 *ret_retval = m->return_value;
1924 *ret_shutdown_verb = NULL;
1925 *ret_fds = NULL;
1926 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1927
1928 return 0;
1929 }
1930
1931 _fallthrough_;
1932 case MANAGER_REBOOT:
1933 case MANAGER_POWEROFF:
1934 case MANAGER_HALT:
1935 case MANAGER_KEXEC: {
1936 static const char * const table[_MANAGER_OBJECTIVE_MAX] = {
1937 [MANAGER_EXIT] = "exit",
1938 [MANAGER_REBOOT] = "reboot",
1939 [MANAGER_POWEROFF] = "poweroff",
1940 [MANAGER_HALT] = "halt",
1941 [MANAGER_KEXEC] = "kexec",
1942 };
1943
1944 log_notice("Shutting down.");
1945
1946 *ret_reexecute = false;
1947 *ret_retval = m->return_value;
1948 assert_se(*ret_shutdown_verb = table[m->objective]);
1949 *ret_fds = NULL;
1950 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1951
1952 return 0;
1953 }
1954
1955 default:
1956 assert_not_reached("Unknown or unexpected manager objective.");
1957 }
1958 }
1959 }
1960
1961 static void log_execution_mode(bool *ret_first_boot) {
1962 assert(ret_first_boot);
1963
1964 if (arg_system) {
1965 int v;
1966
1967 log_info("systemd " GIT_VERSION " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1968 arg_action == ACTION_TEST ? "test " : "" );
1969
1970 v = detect_virtualization();
1971 if (v > 0)
1972 log_info("Detected virtualization %s.", virtualization_to_string(v));
1973
1974 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1975
1976 if (in_initrd()) {
1977 *ret_first_boot = false;
1978 log_info("Running in initial RAM disk.");
1979 } else {
1980 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1981 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1982 * doesn't it's unpopulated. This allows container managers and installers to provision a
1983 * couple of files already. If the container manager wants to provision the machine ID itself
1984 * it should pass $container_uuid to PID 1. */
1985
1986 *ret_first_boot = access("/etc/machine-id", F_OK) < 0;
1987 if (*ret_first_boot)
1988 log_info("Running with unpopulated /etc.");
1989 }
1990 } else {
1991 if (DEBUG_LOGGING) {
1992 _cleanup_free_ char *t;
1993
1994 t = uid_to_name(getuid());
1995 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (" SYSTEMD_FEATURES ")",
1996 arg_action == ACTION_TEST ? " test" : "", getuid(), strna(t));
1997 }
1998
1999 *ret_first_boot = false;
2000 }
2001 }
2002
2003 static int initialize_runtime(
2004 bool skip_setup,
2005 struct rlimit *saved_rlimit_nofile,
2006 struct rlimit *saved_rlimit_memlock,
2007 const char **ret_error_message) {
2008
2009 int r;
2010
2011 assert(ret_error_message);
2012
2013 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2014 *
2015 * - Some only apply to --system instances
2016 * - Some only apply to --user instances
2017 * - Some only apply when we first start up, but not when we reexecute
2018 */
2019
2020 if (arg_action != ACTION_RUN)
2021 return 0;
2022
2023 if (arg_system) {
2024 /* Make sure we leave a core dump without panicing the kernel. */
2025 install_crash_handler();
2026
2027 if (!skip_setup) {
2028 r = mount_cgroup_controllers();
2029 if (r < 0) {
2030 *ret_error_message = "Failed to mount cgroup hierarchies";
2031 return r;
2032 }
2033
2034 status_welcome();
2035 hostname_setup();
2036 machine_id_setup(NULL, arg_machine_id, NULL);
2037 loopback_setup();
2038 bump_unix_max_dgram_qlen();
2039 bump_file_max_and_nr_open();
2040 test_usr();
2041 write_container_id();
2042 }
2043
2044 if (arg_watchdog_device) {
2045 r = watchdog_set_device(arg_watchdog_device);
2046 if (r < 0)
2047 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
2048 }
2049
2050 if (arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
2051 watchdog_set_timeout(&arg_runtime_watchdog);
2052 }
2053
2054 if (arg_timer_slack_nsec != NSEC_INFINITY)
2055 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
2056 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
2057
2058 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
2059 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
2060 if (r < 0) {
2061 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
2062 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
2063 }
2064
2065 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
2066 if (r < 0) {
2067 *ret_error_message = "Failed to drop capability bounding set";
2068 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
2069 }
2070 }
2071
2072 if (arg_system && arg_no_new_privs) {
2073 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
2074 *ret_error_message = "Failed to disable new privileges";
2075 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
2076 }
2077 }
2078
2079 if (arg_syscall_archs) {
2080 r = enforce_syscall_archs(arg_syscall_archs);
2081 if (r < 0) {
2082 *ret_error_message = "Failed to set syscall architectures";
2083 return r;
2084 }
2085 }
2086
2087 if (!arg_system)
2088 /* Become reaper of our children */
2089 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
2090 log_warning_errno(errno, "Failed to make us a subreaper: %m");
2091
2092 /* Bump up RLIMIT_NOFILE for systemd itself */
2093 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2094 (void) bump_rlimit_memlock(saved_rlimit_memlock);
2095
2096 return 0;
2097 }
2098
2099 static int do_queue_default_job(
2100 Manager *m,
2101 const char **ret_error_message) {
2102
2103 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2104 Job *default_unit_job;
2105 Unit *target = NULL;
2106 int r;
2107
2108 log_debug("Activating default unit: %s", arg_default_unit);
2109
2110 r = manager_load_startable_unit_or_warn(m, arg_default_unit, NULL, &target);
2111 if (r < 0) {
2112 log_info("Falling back to rescue target: " SPECIAL_RESCUE_TARGET);
2113
2114 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
2115 if (r < 0) {
2116 *ret_error_message = r == -ERFKILL ? "Rescue target masked"
2117 : "Failed to load rescue target";
2118 return r;
2119 }
2120 }
2121
2122 assert(target->load_state == UNIT_LOADED);
2123
2124 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &default_unit_job);
2125 if (r == -EPERM) {
2126 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2127
2128 sd_bus_error_free(&error);
2129
2130 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &default_unit_job);
2131 if (r < 0) {
2132 *ret_error_message = "Failed to start default target";
2133 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2134 }
2135
2136 } else if (r < 0) {
2137 *ret_error_message = "Failed to isolate default target";
2138 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
2139 }
2140
2141 m->default_unit_job_id = default_unit_job->id;
2142
2143 return 0;
2144 }
2145
2146 static void free_arguments(void) {
2147
2148 /* Frees all arg_* variables, with the exception of arg_serialization */
2149 rlimit_free_all(arg_default_rlimit);
2150
2151 arg_default_unit = mfree(arg_default_unit);
2152 arg_confirm_spawn = mfree(arg_confirm_spawn);
2153 arg_default_environment = strv_free(arg_default_environment);
2154 arg_syscall_archs = set_free(arg_syscall_archs);
2155 }
2156
2157 static int load_configuration(int argc, char **argv, const char **ret_error_message) {
2158 int r;
2159
2160 assert(ret_error_message);
2161
2162 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
2163
2164 r = parse_config_file();
2165 if (r < 0) {
2166 *ret_error_message = "Failed to parse config file";
2167 return r;
2168 }
2169
2170 if (arg_system) {
2171 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2172 if (r < 0)
2173 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2174 }
2175
2176 /* Note that this also parses bits from the kernel command line, including "debug". */
2177 log_parse_environment();
2178
2179 r = parse_argv(argc, argv);
2180 if (r < 0) {
2181 *ret_error_message = "Failed to parse commandline arguments";
2182 return r;
2183 }
2184
2185 /* Initialize default unit */
2186 if (!arg_default_unit) {
2187 arg_default_unit = strdup(SPECIAL_DEFAULT_TARGET);
2188 if (!arg_default_unit) {
2189 *ret_error_message = "Failed to set default unit";
2190 return log_oom();
2191 }
2192 }
2193
2194 /* Initialize the show status setting if it hasn't been set explicitly yet */
2195 if (arg_show_status == _SHOW_STATUS_INVALID)
2196 arg_show_status = SHOW_STATUS_YES;
2197
2198 return 0;
2199 }
2200
2201 static int safety_checks(void) {
2202
2203 if (getpid_cached() == 1 &&
2204 arg_action != ACTION_RUN)
2205 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2206 "Unsupported execution mode while PID 1.");
2207
2208 if (getpid_cached() == 1 &&
2209 !arg_system)
2210 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2211 "Can't run --user mode as PID 1.");
2212
2213 if (arg_action == ACTION_RUN &&
2214 arg_system &&
2215 getpid_cached() != 1)
2216 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2217 "Can't run system mode unless PID 1.");
2218
2219 if (arg_action == ACTION_TEST &&
2220 geteuid() == 0)
2221 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2222 "Don't run test mode as root.");
2223
2224 if (!arg_system &&
2225 arg_action == ACTION_RUN &&
2226 sd_booted() <= 0)
2227 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2228 "Trying to run as user instance, but the system has not been booted with systemd.");
2229
2230 if (!arg_system &&
2231 arg_action == ACTION_RUN &&
2232 !getenv("XDG_RUNTIME_DIR"))
2233 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2234 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2235
2236 if (arg_system &&
2237 arg_action == ACTION_RUN &&
2238 running_in_chroot() > 0)
2239 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2240 "Cannot be run in a chroot() environment.");
2241
2242 return 0;
2243 }
2244
2245 static int initialize_security(
2246 bool *loaded_policy,
2247 dual_timestamp *security_start_timestamp,
2248 dual_timestamp *security_finish_timestamp,
2249 const char **ret_error_message) {
2250
2251 int r;
2252
2253 assert(loaded_policy);
2254 assert(security_start_timestamp);
2255 assert(security_finish_timestamp);
2256 assert(ret_error_message);
2257
2258 dual_timestamp_get(security_start_timestamp);
2259
2260 r = mac_selinux_setup(loaded_policy);
2261 if (r < 0) {
2262 *ret_error_message = "Failed to load SELinux policy";
2263 return r;
2264 }
2265
2266 r = mac_smack_setup(loaded_policy);
2267 if (r < 0) {
2268 *ret_error_message = "Failed to load SMACK policy";
2269 return r;
2270 }
2271
2272 r = ima_setup();
2273 if (r < 0) {
2274 *ret_error_message = "Failed to load IMA policy";
2275 return r;
2276 }
2277
2278 dual_timestamp_get(security_finish_timestamp);
2279 return 0;
2280 }
2281
2282 static void test_summary(Manager *m) {
2283 assert(m);
2284
2285 printf("-> By units:\n");
2286 manager_dump_units(m, stdout, "\t");
2287
2288 printf("-> By jobs:\n");
2289 manager_dump_jobs(m, stdout, "\t");
2290 }
2291
2292 static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2293 int r;
2294
2295 assert(ret_fds);
2296 assert(ret_error_message);
2297
2298 r = fdset_new_fill(ret_fds);
2299 if (r < 0) {
2300 *ret_error_message = "Failed to allocate fd set";
2301 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2302 }
2303
2304 fdset_cloexec(*ret_fds, true);
2305
2306 if (arg_serialization)
2307 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2308
2309 return 0;
2310 }
2311
2312 static void setup_console_terminal(bool skip_setup) {
2313
2314 if (!arg_system)
2315 return;
2316
2317 /* Become a session leader if we aren't one yet. */
2318 (void) setsid();
2319
2320 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2321 * tty. */
2322 (void) release_terminal();
2323
2324 /* Reset the console, but only if this is really init and we are freshly booted */
2325 if (getpid_cached() == 1 && !skip_setup)
2326 (void) console_setup();
2327 }
2328
2329 static bool early_skip_setup_check(int argc, char *argv[]) {
2330 bool found_deserialize = false;
2331 int i;
2332
2333 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2334 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2335 * anyway, even if in that case we also do deserialization. */
2336
2337 for (i = 1; i < argc; i++) {
2338 if (streq(argv[i], "--switched-root"))
2339 return false; /* If we switched root, don't skip the setup. */
2340 else if (streq(argv[i], "--deserialize"))
2341 found_deserialize = true;
2342 }
2343
2344 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2345 }
2346
2347 int main(int argc, char *argv[]) {
2348
2349 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL, userspace_timestamp = DUAL_TIMESTAMP_NULL, kernel_timestamp = DUAL_TIMESTAMP_NULL,
2350 security_start_timestamp = DUAL_TIMESTAMP_NULL, security_finish_timestamp = DUAL_TIMESTAMP_NULL;
2351 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2352 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2353 * in. Note we use different values
2354 * for the two that indicate whether
2355 * these fields are initialized! */
2356 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false, reexecute = false;
2357 char *switch_root_dir = NULL, *switch_root_init = NULL;
2358 usec_t before_startup, after_startup;
2359 static char systemd[] = "systemd";
2360 char timespan[FORMAT_TIMESPAN_MAX];
2361 const char *shutdown_verb = NULL, *error_message = NULL;
2362 int r, retval = EXIT_FAILURE;
2363 Manager *m = NULL;
2364 FDSet *fds = NULL;
2365
2366 /* SysV compatibility: redirect init → telinit */
2367 redirect_telinit(argc, argv);
2368
2369 /* Take timestamps early on */
2370 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2371 dual_timestamp_get(&userspace_timestamp);
2372
2373 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2374 * reexecuting */
2375 skip_setup = early_skip_setup_check(argc, argv);
2376
2377 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2378 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
2379 program_invocation_short_name = systemd;
2380 (void) prctl(PR_SET_NAME, systemd);
2381
2382 /* Save the original command line */
2383 save_argc_argv(argc, argv);
2384
2385 /* Make sure that if the user says "syslog" we actually log to the journal. */
2386 log_set_upgrade_syslog_to_journal(true);
2387
2388 if (getpid_cached() == 1) {
2389 /* When we run as PID 1 force system mode */
2390 arg_system = true;
2391
2392 /* Disable the umask logic */
2393 umask(0);
2394
2395 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2396 * activated yet (even though the log socket for it exists). */
2397 log_set_prohibit_ipc(true);
2398
2399 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2400 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2401 * child process right before execve()'ing the actual binary, at a point in time where socket
2402 * activation stderr/stdout area already set up. */
2403 log_set_always_reopen_console(true);
2404
2405 if (detect_container() <= 0) {
2406
2407 /* Running outside of a container as PID 1 */
2408 log_set_target(LOG_TARGET_KMSG);
2409 log_open();
2410
2411 if (in_initrd())
2412 initrd_timestamp = userspace_timestamp;
2413
2414 if (!skip_setup) {
2415 r = mount_setup_early();
2416 if (r < 0) {
2417 error_message = "Failed to mount early API filesystems";
2418 goto finish;
2419 }
2420
2421 r = initialize_security(
2422 &loaded_policy,
2423 &security_start_timestamp,
2424 &security_finish_timestamp,
2425 &error_message);
2426 if (r < 0)
2427 goto finish;
2428 }
2429
2430 if (mac_selinux_init() < 0) {
2431 error_message = "Failed to initialize SELinux policy";
2432 goto finish;
2433 }
2434
2435 if (!skip_setup)
2436 initialize_clock();
2437
2438 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2439 * if we are transitioning from the initrd there might still be journal fd open, and we
2440 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2441 * elsewhere. */
2442 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2443
2444 } else {
2445 /* Running inside a container, as PID 1 */
2446 log_set_target(LOG_TARGET_CONSOLE);
2447 log_open();
2448
2449 /* For later on, see above... */
2450 log_set_target(LOG_TARGET_JOURNAL);
2451
2452 /* clear the kernel timestamp,
2453 * because we are in a container */
2454 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2455 }
2456
2457 initialize_coredump(skip_setup);
2458
2459 r = fixup_environment();
2460 if (r < 0) {
2461 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2462 error_message = "Failed to fix up PID1 environment";
2463 goto finish;
2464 }
2465
2466 } else {
2467 /* Running as user instance */
2468 arg_system = false;
2469 log_set_target(LOG_TARGET_AUTO);
2470 log_open();
2471
2472 /* clear the kernel timestamp,
2473 * because we are not PID 1 */
2474 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2475 }
2476
2477 if (arg_system) {
2478 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2479 * they never log into the console. */
2480 log_show_color(colors_enabled());
2481
2482 r = make_null_stdio();
2483 if (r < 0)
2484 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
2485 }
2486
2487 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2488 * /proc/$PID/fd is available. */
2489 if (getpid_cached() == 1) {
2490
2491 /* Load the kernel modules early. */
2492 if (!skip_setup)
2493 kmod_setup();
2494
2495 r = mount_setup(loaded_policy);
2496 if (r < 0) {
2497 error_message = "Failed to mount API filesystems";
2498 goto finish;
2499 }
2500 }
2501
2502 /* Reset all signal handlers. */
2503 (void) reset_all_signal_handlers();
2504 (void) ignore_signals(SIGNALS_IGNORE, -1);
2505
2506 r = load_configuration(argc, argv, &error_message);
2507 if (r < 0)
2508 goto finish;
2509
2510 r = safety_checks();
2511 if (r < 0)
2512 goto finish;
2513
2514 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES))
2515 (void) pager_open(arg_pager_flags);
2516
2517 if (arg_action != ACTION_RUN)
2518 skip_setup = true;
2519
2520 if (arg_action == ACTION_HELP) {
2521 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
2522 goto finish;
2523 } else if (arg_action == ACTION_VERSION) {
2524 retval = version();
2525 goto finish;
2526 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
2527 unit_dump_config_items(stdout);
2528 retval = EXIT_SUCCESS;
2529 goto finish;
2530 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2531 dump_bus_properties(stdout);
2532 retval = EXIT_SUCCESS;
2533 goto finish;
2534 }
2535
2536 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
2537
2538 /* Move out of the way, so that we won't block unmounts */
2539 assert_se(chdir("/") == 0);
2540
2541 if (arg_action == ACTION_RUN) {
2542
2543 /* A core pattern might have been specified via the cmdline. */
2544 initialize_core_pattern(skip_setup);
2545
2546 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
2547 log_close();
2548
2549 /* Remember open file descriptors for later deserialization */
2550 r = collect_fds(&fds, &error_message);
2551 if (r < 0)
2552 goto finish;
2553
2554 /* Give up any control of the console, but make sure its initialized. */
2555 setup_console_terminal(skip_setup);
2556
2557 /* Open the logging devices, if possible and necessary */
2558 log_open();
2559 }
2560
2561 log_execution_mode(&first_boot);
2562
2563 r = initialize_runtime(skip_setup,
2564 &saved_rlimit_nofile,
2565 &saved_rlimit_memlock,
2566 &error_message);
2567 if (r < 0)
2568 goto finish;
2569
2570 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2571 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2572 &m);
2573 if (r < 0) {
2574 log_emergency_errno(r, "Failed to allocate manager object: %m");
2575 error_message = "Failed to allocate manager object";
2576 goto finish;
2577 }
2578
2579 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2580 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2581 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
2582 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2583 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
2584
2585 set_manager_defaults(m);
2586 set_manager_settings(m);
2587 manager_set_first_boot(m, first_boot);
2588
2589 /* Remember whether we should queue the default job */
2590 queue_default_job = !arg_serialization || arg_switched_root;
2591
2592 before_startup = now(CLOCK_MONOTONIC);
2593
2594 r = manager_startup(m, arg_serialization, fds);
2595 if (r < 0) {
2596 error_message = "Failed to start up manager";
2597 goto finish;
2598 }
2599
2600 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2601 fds = fdset_free(fds);
2602 arg_serialization = safe_fclose(arg_serialization);
2603
2604 if (queue_default_job) {
2605 r = do_queue_default_job(m, &error_message);
2606 if (r < 0)
2607 goto finish;
2608 }
2609
2610 after_startup = now(CLOCK_MONOTONIC);
2611
2612 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2613 "Loaded units and determined initial transaction in %s.",
2614 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
2615
2616 if (arg_action == ACTION_TEST) {
2617 test_summary(m);
2618 retval = EXIT_SUCCESS;
2619 goto finish;
2620 }
2621
2622 (void) invoke_main_loop(m,
2623 &reexecute,
2624 &retval,
2625 &shutdown_verb,
2626 &fds,
2627 &switch_root_dir,
2628 &switch_root_init,
2629 &error_message);
2630
2631 finish:
2632 pager_close();
2633
2634 if (m) {
2635 arg_shutdown_watchdog = m->shutdown_watchdog;
2636 m = manager_free(m);
2637 }
2638
2639 free_arguments();
2640 mac_selinux_finish();
2641
2642 if (reexecute)
2643 do_reexecute(argc, argv,
2644 &saved_rlimit_nofile,
2645 &saved_rlimit_memlock,
2646 fds,
2647 switch_root_dir,
2648 switch_root_init,
2649 &error_message); /* This only returns if reexecution failed */
2650
2651 arg_serialization = safe_fclose(arg_serialization);
2652 fds = fdset_free(fds);
2653
2654 #if HAVE_VALGRIND_VALGRIND_H
2655 /* If we are PID 1 and running under valgrind, then let's exit
2656 * here explicitly. valgrind will only generate nice output on
2657 * exit(), not on exec(), hence let's do the former not the
2658 * latter here. */
2659 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
2660 /* Cleanup watchdog_device strings for valgrind. We need them
2661 * in become_shutdown() so normally we cannot free them yet. */
2662 watchdog_free_device();
2663 arg_watchdog_device = mfree(arg_watchdog_device);
2664 return retval;
2665 }
2666 #endif
2667
2668 #if HAS_FEATURE_ADDRESS_SANITIZER
2669 __lsan_do_leak_check();
2670 #endif
2671
2672 if (shutdown_verb) {
2673 r = become_shutdown(shutdown_verb, retval);
2674 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
2675 error_message = "Failed to execute shutdown binary";
2676 }
2677
2678 watchdog_free_device();
2679 arg_watchdog_device = mfree(arg_watchdog_device);
2680
2681 if (getpid_cached() == 1) {
2682 if (error_message)
2683 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
2684 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
2685 "%s.", error_message);
2686 freeze_or_exit_or_reboot();
2687 }
2688
2689 return retval;
2690 }