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