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