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