]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
NEWS: Prepare NEWS file for next release
[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
ea430986
LP
22#include <dbus/dbus.h>
23
60918275
LP
24#include <stdio.h>
25#include <errno.h>
26#include <string.h>
16354eff 27#include <unistd.h>
4ade7963
LP
28#include <sys/types.h>
29#include <sys/stat.h>
f170852a 30#include <getopt.h>
97c4f35c 31#include <signal.h>
4fc935ca 32#include <sys/wait.h>
80876c20 33#include <fcntl.h>
f3b6a3ed 34#include <sys/prctl.h>
664f88a7 35#include <sys/mount.h>
60918275
LP
36
37#include "manager.h"
16354eff 38#include "log.h"
302e8c4c 39#include "load-fragment.h"
a16e1123 40#include "fdset.h"
514f4ef5 41#include "special.h"
487393e9 42#include "conf-parser.h"
398ef8ba 43#include "bus-errors.h"
ad780f19 44#include "missing.h"
e51bc1a2 45#include "label.h"
302e27c8 46#include "build.h"
06d4c99a 47#include "strv.h"
f6a6225e 48#include "def.h"
b52aae1d 49#include "virt.h"
e96d6be7 50#include "watchdog.h"
664f88a7 51#include "path-util.h"
41669317 52#include "switch-root.h"
ec8927ca 53#include "capability.h"
60918275 54
b6e66135
LP
55#include "mount-setup.h"
56#include "loopback-setup.h"
57#include "kmod-setup.h"
58#include "hostname-setup.h"
59#include "machine-id-setup.h"
60#include "locale-setup.h"
bbc98d32 61#include "hwclock.h"
b6e66135
LP
62#include "selinux-setup.h"
63#include "ima-setup.h"
64
f170852a
LP
65static enum {
66 ACTION_RUN,
e965d56d 67 ACTION_HELP,
e537352b 68 ACTION_TEST,
4288f619
LP
69 ACTION_DUMP_CONFIGURATION_ITEMS,
70 ACTION_DONE
fa0f4d8a 71} arg_action = ACTION_RUN;
f170852a 72
fa0f4d8a
LP
73static char *arg_default_unit = NULL;
74static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
75
76static bool arg_dump_core = true;
77static bool arg_crash_shell = false;
78static int arg_crash_chvt = -1;
79static bool arg_confirm_spawn = false;
9e58ff9c 80static bool arg_show_status = true;
bf4df7c3 81static bool arg_switched_root = false;
06d4c99a 82static char **arg_default_controllers = NULL;
0c85a4f3 83static char ***arg_join_controllers = NULL;
706343f4 84static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
0a494f1f 85static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
e96d6be7
LP
86static usec_t arg_runtime_watchdog = 0;
87static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
c93ff2e9 88static struct rlimit *arg_default_rlimit[RLIMIT_NLIMITS] = {};
ec8927ca 89static uint64_t arg_capability_bounding_set_drop = 0;
aa0f64ac 90static nsec_t arg_timer_slack_nsec = (nsec_t) -1;
4fc935ca 91
a16e1123 92static FILE* serialization = NULL;
80876c20 93
6f5e3f35
LP
94static void nop_handler(int sig) {
95}
96
93a46b0b 97_noreturn_ static void crash(int sig) {
97c4f35c 98
fa0f4d8a 99 if (!arg_dump_core)
582a507f 100 log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 101 else {
6f5e3f35 102 struct sigaction sa;
97c4f35c
LP
103 pid_t pid;
104
6f5e3f35
LP
105 /* We want to wait for the core process, hence let's enable SIGCHLD */
106 zero(sa);
107 sa.sa_handler = nop_handler;
108 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
109 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
110
97c4f35c 111 if ((pid = fork()) < 0)
582a507f 112 log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
97c4f35c
LP
113
114 else if (pid == 0) {
97c4f35c
LP
115 struct rlimit rl;
116
117 /* Enable default signal handler for core dump */
118 zero(sa);
119 sa.sa_handler = SIG_DFL;
120 assert_se(sigaction(sig, &sa, NULL) == 0);
121
122 /* Don't limit the core dump size */
123 zero(rl);
124 rl.rlim_cur = RLIM_INFINITY;
125 rl.rlim_max = RLIM_INFINITY;
126 setrlimit(RLIMIT_CORE, &rl);
127
128 /* Just to be sure... */
129 assert_se(chdir("/") == 0);
130
131 /* Raise the signal again */
132 raise(sig);
133
134 assert_not_reached("We shouldn't be here...");
135 _exit(1);
4fc935ca
LP
136
137 } else {
8e12a6ae
LP
138 siginfo_t status;
139 int r;
4fc935ca
LP
140
141 /* Order things nicely. */
8e12a6ae
LP
142 if ((r = wait_for_terminate(pid, &status)) < 0)
143 log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
144 else if (status.si_code != CLD_DUMPED)
582a507f 145 log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
4fc935ca 146 else
582a507f 147 log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
97c4f35c
LP
148 }
149 }
150
fa0f4d8a
LP
151 if (arg_crash_chvt)
152 chvt(arg_crash_chvt);
601f6a1e 153
fa0f4d8a 154 if (arg_crash_shell) {
6f5e3f35
LP
155 struct sigaction sa;
156 pid_t pid;
8c43883a 157
4fc935ca
LP
158 log_info("Executing crash shell in 10s...");
159 sleep(10);
160
6f5e3f35
LP
161 /* Let the kernel reap children for us */
162 zero(sa);
163 sa.sa_handler = SIG_IGN;
164 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
165 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
8c43883a 166
6f5e3f35
LP
167 if ((pid = fork()) < 0)
168 log_error("Failed to fork off crash shell: %s", strerror(errno));
169 else if (pid == 0) {
843d2643 170 int fd, r;
ea5652c2 171
af6da548 172 if ((fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1)) < 0)
ea5652c2 173 log_error("Failed to acquire terminal: %s", strerror(-fd));
5b2a0903 174 else if ((r = make_stdio(fd)) < 0)
843d2643 175 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
ea5652c2 176
6f5e3f35
LP
177 execl("/bin/sh", "/bin/sh", NULL);
178
179 log_error("execl() failed: %s", strerror(errno));
180 _exit(1);
181 }
c99b188e 182
f8e08a77 183 log_info("Successfully spawned crash shell as pid %lu.", (unsigned long) pid);
4fc935ca
LP
184 }
185
186 log_info("Freezing execution.");
97c4f35c
LP
187 freeze();
188}
189
190static void install_crash_handler(void) {
191 struct sigaction sa;
192
193 zero(sa);
194
195 sa.sa_handler = crash;
196 sa.sa_flags = SA_NODEFER;
197
1b91d3e8 198 sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
97c4f35c 199}
f170852a 200
843d2643
LP
201static int console_setup(bool do_reset) {
202 int tty_fd, r;
80876c20 203
843d2643
LP
204 /* If we are init, we connect stdin/stdout/stderr to /dev/null
205 * and make sure we don't have a controlling tty. */
80876c20 206
843d2643
LP
207 release_terminal();
208
209 if (!do_reset)
210 return 0;
80876c20 211
512947d4
MS
212 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
213 if (tty_fd < 0) {
843d2643
LP
214 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
215 return -tty_fd;
216 }
80876c20 217
512947d4
MS
218 /* We don't want to force text mode.
219 * plymouth may be showing pictures already from initrd. */
220 r = reset_terminal_fd(tty_fd, false);
221 if (r < 0)
843d2643
LP
222 log_error("Failed to reset /dev/console: %s", strerror(-r));
223
224 close_nointr_nofail(tty_fd);
80876c20
LP
225 return r;
226}
227
f170852a
LP
228static int set_default_unit(const char *u) {
229 char *c;
230
231 assert(u);
232
bf4df7c3
LP
233 c = strdup(u);
234 if (!c)
f170852a
LP
235 return -ENOMEM;
236
fa0f4d8a
LP
237 free(arg_default_unit);
238 arg_default_unit = c;
bf4df7c3 239
f170852a
LP
240 return 0;
241}
242
243static int parse_proc_cmdline_word(const char *word) {
244
245 static const char * const rlmap[] = {
ed370f5d 246 "emergency", SPECIAL_EMERGENCY_TARGET,
099663ff 247 "-b", SPECIAL_EMERGENCY_TARGET,
ed370f5d
LP
248 "single", SPECIAL_RESCUE_TARGET,
249 "-s", SPECIAL_RESCUE_TARGET,
250 "s", SPECIAL_RESCUE_TARGET,
251 "S", SPECIAL_RESCUE_TARGET,
252 "1", SPECIAL_RESCUE_TARGET,
253 "2", SPECIAL_RUNLEVEL2_TARGET,
254 "3", SPECIAL_RUNLEVEL3_TARGET,
255 "4", SPECIAL_RUNLEVEL4_TARGET,
256 "5", SPECIAL_RUNLEVEL5_TARGET,
f170852a
LP
257 };
258
5192bd19
LP
259 assert(word);
260
bf4df7c3
LP
261 if (startswith(word, "systemd.unit=")) {
262
263 if (!in_initrd())
264 return set_default_unit(word + 13);
265
266 } else if (startswith(word, "rd.systemd.unit=")) {
267
268 if (in_initrd())
269 return set_default_unit(word + 16);
f170852a 270
bf4df7c3 271 } else if (startswith(word, "systemd.log_target=")) {
f170852a
LP
272
273 if (log_set_target_from_string(word + 19) < 0)
274 log_warning("Failed to parse log target %s. Ignoring.", word + 19);
275
276 } else if (startswith(word, "systemd.log_level=")) {
277
278 if (log_set_max_level_from_string(word + 18) < 0)
279 log_warning("Failed to parse log level %s. Ignoring.", word + 18);
280
bbe63281
LP
281 } else if (startswith(word, "systemd.log_color=")) {
282
283 if (log_show_color_from_string(word + 18) < 0)
284 log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
285
286 } else if (startswith(word, "systemd.log_location=")) {
287
288 if (log_show_location_from_string(word + 21) < 0)
289 log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
290
4fc935ca
LP
291 } else if (startswith(word, "systemd.dump_core=")) {
292 int r;
293
294 if ((r = parse_boolean(word + 18)) < 0)
509b6efb 295 log_warning("Failed to parse dump core switch %s. Ignoring.", word + 18);
4fc935ca 296 else
fa0f4d8a 297 arg_dump_core = r;
4fc935ca
LP
298
299 } else if (startswith(word, "systemd.crash_shell=")) {
300 int r;
301
302 if ((r = parse_boolean(word + 20)) < 0)
509b6efb 303 log_warning("Failed to parse crash shell switch %s. Ignoring.", word + 20);
4fc935ca 304 else
fa0f4d8a 305 arg_crash_shell = r;
5e7ee61c
LP
306
307 } else if (startswith(word, "systemd.confirm_spawn=")) {
308 int r;
309
310 if ((r = parse_boolean(word + 22)) < 0)
509b6efb 311 log_warning("Failed to parse confirm spawn switch %s. Ignoring.", word + 22);
5e7ee61c 312 else
fa0f4d8a 313 arg_confirm_spawn = r;
5e7ee61c 314
601f6a1e
LP
315 } else if (startswith(word, "systemd.crash_chvt=")) {
316 int k;
317
318 if (safe_atoi(word + 19, &k) < 0)
509b6efb 319 log_warning("Failed to parse crash chvt switch %s. Ignoring.", word + 19);
601f6a1e 320 else
fa0f4d8a 321 arg_crash_chvt = k;
601f6a1e 322
9e58ff9c
LP
323 } else if (startswith(word, "systemd.show_status=")) {
324 int r;
325
326 if ((r = parse_boolean(word + 20)) < 0)
509b6efb 327 log_warning("Failed to parse show status switch %s. Ignoring.", word + 20);
6e98720f 328 else
9e58ff9c 329 arg_show_status = r;
0a494f1f
LP
330 } else if (startswith(word, "systemd.default_standard_output=")) {
331 int r;
332
333 if ((r = exec_output_from_string(word + 32)) < 0)
509b6efb 334 log_warning("Failed to parse default standard output switch %s. Ignoring.", word + 32);
0a494f1f
LP
335 else
336 arg_default_std_output = r;
337 } else if (startswith(word, "systemd.default_standard_error=")) {
338 int r;
339
340 if ((r = exec_output_from_string(word + 31)) < 0)
509b6efb 341 log_warning("Failed to parse default standard error switch %s. Ignoring.", word + 31);
0a494f1f
LP
342 else
343 arg_default_std_error = r;
9e7c5357
WD
344 } else if (startswith(word, "systemd.setenv=")) {
345 char *cenv, *eq;
346 int r;
347
348 cenv = strdup(word + 15);
349 if (!cenv)
350 return -ENOMEM;
351
352 eq = strchr(cenv, '=');
353 if (!eq) {
354 r = unsetenv(cenv);
355 if (r < 0)
356 log_warning("unsetenv failed %s. Ignoring.", strerror(errno));
357 } else {
358 *eq = 0;
359 r = setenv(cenv, eq + 1, 1);
360 if (r < 0)
361 log_warning("setenv failed %s. Ignoring.", strerror(errno));
362 }
363 free(cenv);
9e58ff9c 364
66a78c2b
LP
365 } else if (startswith(word, "systemd.") ||
366 (in_initrd() && startswith(word, "rd.systemd."))) {
4fc935ca
LP
367
368 log_warning("Unknown kernel switch %s. Ignoring.", word);
369
bbe63281
LP
370 log_info("Supported kernel switches:\n"
371 "systemd.unit=UNIT Default unit to start\n"
bf4df7c3 372 "rd.systemd.unit=UNIT Default unit to start when run in initrd\n"
bbe63281 373 "systemd.dump_core=0|1 Dump core on crash\n"
9e58ff9c 374 "systemd.crash_shell=0|1 Run shell on crash\n"
bbe63281 375 "systemd.crash_chvt=N Change to VT #N on crash\n"
9e58ff9c 376 "systemd.confirm_spawn=0|1 Confirm every process spawn\n"
6e98720f 377 "systemd.show_status=0|1 Show status updates on the console during bootup\n"
4cfa2c99 378 "systemd.log_target=console|kmsg|journal|journal-or-kmsg|syslog|syslog-or-kmsg|null\n"
6e98720f
LP
379 " Log target\n"
380 "systemd.log_level=LEVEL Log level\n"
381 "systemd.log_color=0|1 Highlight important log messages\n"
0a494f1f 382 "systemd.log_location=0|1 Include code location in log messages\n"
706343f4 383 "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
0a494f1f 384 " Set default log output for services\n"
706343f4 385 "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
c66e7bc7
LP
386 " Set default log error output for services\n"
387 "systemd.setenv=ASSIGNMENT Set an environment variable for all spawned processes\n");
4fc935ca 388
d081dffb 389 } else if (streq(word, "quiet"))
6e98720f 390 arg_show_status = false;
d081dffb 391 else if (!in_initrd()) {
f170852a
LP
392 unsigned i;
393
394 /* SysV compatibility */
f170852a
LP
395 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
396 if (streq(word, rlmap[i]))
397 return set_default_unit(rlmap[i+1]);
398 }
399
400 return 0;
401}
402
f975e971 403static int config_parse_level2(
487393e9
LP
404 const char *filename,
405 unsigned line,
406 const char *section,
407 const char *lvalue,
3731f1ea 408 int ltype,
487393e9
LP
409 const char *rvalue,
410 void *data,
411 void *userdata) {
412
413 assert(filename);
414 assert(lvalue);
415 assert(rvalue);
416
417 log_set_max_level_from_string(rvalue);
418 return 0;
419}
420
421static int config_parse_target(
422 const char *filename,
423 unsigned line,
424 const char *section,
425 const char *lvalue,
3731f1ea 426 int ltype,
487393e9
LP
427 const char *rvalue,
428 void *data,
429 void *userdata) {
430
431 assert(filename);
432 assert(lvalue);
433 assert(rvalue);
434
435 log_set_target_from_string(rvalue);
436 return 0;
437}
438
439static int config_parse_color(
440 const char *filename,
441 unsigned line,
442 const char *section,
443 const char *lvalue,
3731f1ea 444 int ltype,
487393e9
LP
445 const char *rvalue,
446 void *data,
447 void *userdata) {
448
449 assert(filename);
450 assert(lvalue);
451 assert(rvalue);
452
453 log_show_color_from_string(rvalue);
454 return 0;
455}
456
457static int config_parse_location(
458 const char *filename,
459 unsigned line,
460 const char *section,
461 const char *lvalue,
3731f1ea 462 int ltype,
487393e9
LP
463 const char *rvalue,
464 void *data,
465 void *userdata) {
466
467 assert(filename);
468 assert(lvalue);
469 assert(rvalue);
470
471 log_show_location_from_string(rvalue);
472 return 0;
473}
474
f975e971 475static int config_parse_cpu_affinity2(
487393e9
LP
476 const char *filename,
477 unsigned line,
478 const char *section,
479 const char *lvalue,
3731f1ea 480 int ltype,
487393e9
LP
481 const char *rvalue,
482 void *data,
483 void *userdata) {
484
485 char *w;
486 size_t l;
487 char *state;
488 cpu_set_t *c = NULL;
489 unsigned ncpus = 0;
490
491 assert(filename);
492 assert(lvalue);
493 assert(rvalue);
494
f60f22df 495 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
487393e9
LP
496 char *t;
497 int r;
498 unsigned cpu;
499
500 if (!(t = strndup(w, l)))
501 return -ENOMEM;
502
503 r = safe_atou(t, &cpu);
504 free(t);
505
506 if (!c)
507 if (!(c = cpu_set_malloc(&ncpus)))
508 return -ENOMEM;
509
510 if (r < 0 || cpu >= ncpus) {
511 log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
512 CPU_FREE(c);
513 return -EBADMSG;
514 }
515
516 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
517 }
518
519 if (c) {
520 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
521 log_warning("Failed to set CPU affinity: %m");
522
523 CPU_FREE(c);
524 }
525
526 return 0;
527}
528
0c85a4f3
LP
529static void strv_free_free(char ***l) {
530 char ***i;
531
532 if (!l)
533 return;
534
535 for (i = l; *i; i++)
536 strv_free(*i);
537
538 free(l);
539}
540
541static void free_join_controllers(void) {
542 if (!arg_join_controllers)
543 return;
544
545 strv_free_free(arg_join_controllers);
546 arg_join_controllers = NULL;
547}
548
549static int config_parse_join_controllers(
550 const char *filename,
551 unsigned line,
552 const char *section,
553 const char *lvalue,
554 int ltype,
555 const char *rvalue,
556 void *data,
557 void *userdata) {
558
559 unsigned n = 0;
560 char *state, *w;
561 size_t length;
562
563 assert(filename);
564 assert(lvalue);
565 assert(rvalue);
566
567 free_join_controllers();
568
569 FOREACH_WORD_QUOTED(w, length, rvalue, state) {
570 char *s, **l;
571
572 s = strndup(w, length);
573 if (!s)
574 return -ENOMEM;
575
576 l = strv_split(s, ",");
577 free(s);
578
579 strv_uniq(l);
580
581 if (strv_length(l) <= 1) {
582 strv_free(l);
583 continue;
584 }
585
586 if (!arg_join_controllers) {
587 arg_join_controllers = new(char**, 2);
588 if (!arg_join_controllers) {
589 strv_free(l);
590 return -ENOMEM;
591 }
592
593 arg_join_controllers[0] = l;
594 arg_join_controllers[1] = NULL;
595
596 n = 1;
597 } else {
598 char ***a;
599 char ***t;
600
601 t = new0(char**, n+2);
602 if (!t) {
603 strv_free(l);
604 return -ENOMEM;
605 }
606
607 n = 0;
608
609 for (a = arg_join_controllers; *a; a++) {
610
611 if (strv_overlap(*a, l)) {
612 char **c;
613
614 c = strv_merge(*a, l);
615 if (!c) {
616 strv_free(l);
617 strv_free_free(t);
618 return -ENOMEM;
619 }
620
621 strv_free(l);
622 l = c;
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 -ENOMEM;
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
644 return 0;
645}
646
487393e9
LP
647static int parse_config_file(void) {
648
f975e971
LP
649 const ConfigTableItem items[] = {
650 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
651 { "Manager", "LogTarget", config_parse_target, 0, NULL },
652 { "Manager", "LogColor", config_parse_color, 0, NULL },
653 { "Manager", "LogLocation", config_parse_location, 0, NULL },
654 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
655 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
656 { "Manager", "ShowStatus", config_parse_bool, 0, &arg_show_status },
f975e971
LP
657 { "Manager", "CrashChVT", config_parse_int, 0, &arg_crash_chvt },
658 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
f975e971
LP
659 { "Manager", "DefaultControllers", config_parse_strv, 0, &arg_default_controllers },
660 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
661 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
0c85a4f3 662 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
e96d6be7
LP
663 { "Manager", "RuntimeWatchdogSec", config_parse_usec, 0, &arg_runtime_watchdog },
664 { "Manager", "ShutdownWatchdogSec", config_parse_usec, 0, &arg_shutdown_watchdog },
ec8927ca 665 { "Manager", "CapabilityBoundingSet", config_parse_bounding_set, 0, &arg_capability_bounding_set_drop },
aa0f64ac 666 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
c93ff2e9
FC
667 { "Manager", "DefaultLimitCPU", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CPU]},
668 { "Manager", "DefaultLimitFSIZE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_FSIZE]},
669 { "Manager", "DefaultLimitDATA", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_DATA]},
670 { "Manager", "DefaultLimitSTACK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_STACK]},
671 { "Manager", "DefaultLimitCORE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_CORE]},
672 { "Manager", "DefaultLimitRSS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RSS]},
673 { "Manager", "DefaultLimitNOFILE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NOFILE]},
674 { "Manager", "DefaultLimitAS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_AS]},
675 { "Manager", "DefaultLimitNPROC", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NPROC]},
676 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MEMLOCK]},
677 { "Manager", "DefaultLimitLOCKS", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_LOCKS]},
678 { "Manager", "DefaultLimitSIGPENDING",config_parse_limit, 0, &arg_default_rlimit[RLIMIT_SIGPENDING]},
679 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_MSGQUEUE]},
680 { "Manager", "DefaultLimitNICE", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_NICE]},
681 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTPRIO]},
682 { "Manager", "DefaultLimitRTTIME", config_parse_limit, 0, &arg_default_rlimit[RLIMIT_RTTIME]},
f975e971 683 { NULL, NULL, NULL, 0, NULL }
487393e9
LP
684 };
685
686 FILE *f;
687 const char *fn;
688 int r;
689
af2d49f7 690 fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : USER_CONFIG_FILE;
f975e971
LP
691 f = fopen(fn, "re");
692 if (!f) {
487393e9
LP
693 if (errno == ENOENT)
694 return 0;
695
696 log_warning("Failed to open configuration file '%s': %m", fn);
697 return 0;
698 }
699
f975e971
LP
700 r = config_parse(fn, f, "Manager\0", config_item_table_lookup, (void*) items, false, NULL);
701 if (r < 0)
487393e9
LP
702 log_warning("Failed to parse configuration file: %s", strerror(-r));
703
704 fclose(f);
705
706 return 0;
707}
708
f170852a 709static int parse_proc_cmdline(void) {
52661efd 710 char *line, *w, *state;
f170852a 711 int r;
f170852a 712 size_t l;
f170852a 713
b770165a
LP
714 /* Don't read /proc/cmdline if we are in a container, since
715 * that is only relevant for the host system */
716 if (detect_container(NULL) > 0)
717 return 0;
718
f170852a 719 if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
e364ad06 720 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
f170852a
LP
721 return 0;
722 }
723
724 FOREACH_WORD_QUOTED(w, l, line, state) {
725 char *word;
726
727 if (!(word = strndup(w, l))) {
728 r = -ENOMEM;
729 goto finish;
730 }
731
732 r = parse_proc_cmdline_word(word);
733 free(word);
734
735 if (r < 0)
736 goto finish;
737 }
738
739 r = 0;
740
741finish:
742 free(line);
743 return r;
744}
745
746static int parse_argv(int argc, char *argv[]) {
747
748 enum {
749 ARG_LOG_LEVEL = 0x100,
750 ARG_LOG_TARGET,
bbe63281
LP
751 ARG_LOG_COLOR,
752 ARG_LOG_LOCATION,
2f198e2f 753 ARG_UNIT,
edb9aaa8 754 ARG_SYSTEM,
af2d49f7 755 ARG_USER,
e537352b 756 ARG_TEST,
80876c20 757 ARG_DUMP_CONFIGURATION_ITEMS,
9e58ff9c
LP
758 ARG_DUMP_CORE,
759 ARG_CRASH_SHELL,
a16e1123 760 ARG_CONFIRM_SPAWN,
9e58ff9c 761 ARG_SHOW_STATUS,
4288f619 762 ARG_DESERIALIZE,
2660882b 763 ARG_SWITCHED_ROOT,
0a494f1f
LP
764 ARG_INTROSPECT,
765 ARG_DEFAULT_STD_OUTPUT,
766 ARG_DEFAULT_STD_ERROR
f170852a
LP
767 };
768
769 static const struct option options[] = {
a16e1123
LP
770 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
771 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
772 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
773 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 774 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 775 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 776 { "user", no_argument, NULL, ARG_USER },
a16e1123
LP
777 { "test", no_argument, NULL, ARG_TEST },
778 { "help", no_argument, NULL, 'h' },
779 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
a5d87bf0
LP
780 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
781 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
782 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 783 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 784 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 785 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
4288f619 786 { "introspect", optional_argument, NULL, ARG_INTROSPECT },
0a494f1f
LP
787 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
788 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
a16e1123 789 { NULL, 0, NULL, 0 }
f170852a
LP
790 };
791
792 int c, r;
793
794 assert(argc >= 1);
795 assert(argv);
796
b770165a
LP
797 if (getpid() == 1)
798 opterr = 0;
799
099663ff 800 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
801
802 switch (c) {
803
804 case ARG_LOG_LEVEL:
805 if ((r = log_set_max_level_from_string(optarg)) < 0) {
806 log_error("Failed to parse log level %s.", optarg);
807 return r;
808 }
809
810 break;
811
812 case ARG_LOG_TARGET:
813
814 if ((r = log_set_target_from_string(optarg)) < 0) {
815 log_error("Failed to parse log target %s.", optarg);
816 return r;
817 }
818
819 break;
820
bbe63281
LP
821 case ARG_LOG_COLOR:
822
d0b170c8
LP
823 if (optarg) {
824 if ((r = log_show_color_from_string(optarg)) < 0) {
825 log_error("Failed to parse log color setting %s.", optarg);
826 return r;
827 }
828 } else
829 log_show_color(true);
bbe63281
LP
830
831 break;
832
833 case ARG_LOG_LOCATION:
834
d0b170c8
LP
835 if (optarg) {
836 if ((r = log_show_location_from_string(optarg)) < 0) {
837 log_error("Failed to parse log location setting %s.", optarg);
838 return r;
839 }
840 } else
841 log_show_location(true);
bbe63281
LP
842
843 break;
844
0a494f1f
LP
845 case ARG_DEFAULT_STD_OUTPUT:
846
847 if ((r = exec_output_from_string(optarg)) < 0) {
848 log_error("Failed to parse default standard output setting %s.", optarg);
849 return r;
850 } else
851 arg_default_std_output = r;
852 break;
853
854 case ARG_DEFAULT_STD_ERROR:
855
856 if ((r = exec_output_from_string(optarg)) < 0) {
857 log_error("Failed to parse default standard error output setting %s.", optarg);
858 return r;
859 } else
860 arg_default_std_error = r;
861 break;
862
2f198e2f 863 case ARG_UNIT:
f170852a
LP
864
865 if ((r = set_default_unit(optarg)) < 0) {
866 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
867 return r;
868 }
869
870 break;
871
edb9aaa8
LP
872 case ARG_SYSTEM:
873 arg_running_as = MANAGER_SYSTEM;
874 break;
a5dab5ce 875
af2d49f7
LP
876 case ARG_USER:
877 arg_running_as = MANAGER_USER;
a5dab5ce 878 break;
a5dab5ce 879
e965d56d 880 case ARG_TEST:
fa0f4d8a 881 arg_action = ACTION_TEST;
e965d56d
LP
882 break;
883
e537352b 884 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 885 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
886 break;
887
9e58ff9c 888 case ARG_DUMP_CORE:
a5d87bf0
LP
889 r = optarg ? parse_boolean(optarg) : 1;
890 if (r < 0) {
891 log_error("Failed to parse dump core boolean %s.", optarg);
892 return r;
893 }
894 arg_dump_core = r;
9e58ff9c
LP
895 break;
896
897 case ARG_CRASH_SHELL:
a5d87bf0
LP
898 r = optarg ? parse_boolean(optarg) : 1;
899 if (r < 0) {
900 log_error("Failed to parse crash shell boolean %s.", optarg);
901 return r;
902 }
903 arg_crash_shell = r;
9e58ff9c
LP
904 break;
905
80876c20 906 case ARG_CONFIRM_SPAWN:
a5d87bf0
LP
907 r = optarg ? parse_boolean(optarg) : 1;
908 if (r < 0) {
909 log_error("Failed to parse confirm spawn boolean %s.", optarg);
910 return r;
911 }
912 arg_confirm_spawn = r;
80876c20
LP
913 break;
914
9e58ff9c 915 case ARG_SHOW_STATUS:
a5d87bf0
LP
916 r = optarg ? parse_boolean(optarg) : 1;
917 if (r < 0) {
918 log_error("Failed to parse show status boolean %s.", optarg);
919 return r;
920 }
921 arg_show_status = r;
6e98720f 922 break;
a5d87bf0 923
a16e1123
LP
924 case ARG_DESERIALIZE: {
925 int fd;
926 FILE *f;
927
928 if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
929 log_error("Failed to parse deserialize option %s.", optarg);
930 return r;
931 }
932
933 if (!(f = fdopen(fd, "r"))) {
934 log_error("Failed to open serialization fd: %m");
935 return r;
936 }
937
938 if (serialization)
939 fclose(serialization);
940
941 serialization = f;
942
943 break;
944 }
945
2660882b 946 case ARG_SWITCHED_ROOT:
bf4df7c3 947 arg_switched_root = true;
d03bc1b8
HH
948 break;
949
4288f619
LP
950 case ARG_INTROSPECT: {
951 const char * const * i = NULL;
952
953 for (i = bus_interface_table; *i; i += 2)
954 if (!optarg || streq(i[0], optarg)) {
955 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
956 "<node>\n", stdout);
957 fputs(i[1], stdout);
958 fputs("</node>\n", stdout);
959
960 if (optarg)
961 break;
962 }
963
964 if (!i[0] && optarg)
965 log_error("Unknown interface %s.", optarg);
966
fa0f4d8a 967 arg_action = ACTION_DONE;
4288f619
LP
968 break;
969 }
970
f170852a 971 case 'h':
fa0f4d8a 972 arg_action = ACTION_HELP;
f170852a
LP
973 break;
974
1d2e23ab
LP
975 case 'D':
976 log_set_max_level(LOG_DEBUG);
977 break;
978
099663ff
LP
979 case 'b':
980 case 's':
981 case 'z':
982 /* Just to eat away the sysvinit kernel
983 * cmdline args without getopt() error
984 * messages that we'll parse in
985 * parse_proc_cmdline_word() or ignore. */
f170852a 986
099663ff 987 case '?':
f170852a 988 default:
099663ff
LP
989 if (getpid() != 1) {
990 log_error("Unknown option code %c", c);
991 return -EINVAL;
992 }
993
994 break;
f170852a
LP
995 }
996
d821e6d6
LP
997 if (optind < argc && getpid() != 1) {
998 /* Hmm, when we aren't run as init system
999 * let's complain about excess arguments */
1000
1001 log_error("Excess arguments.");
1002 return -EINVAL;
1003 }
1004
1005 if (detect_container(NULL) > 0) {
1006 char **a;
1007
1008 /* All /proc/cmdline arguments the kernel didn't
1009 * understand it passed to us. We're not really
1010 * interested in that usually since /proc/cmdline is
1011 * more interesting and complete. With one exception:
1012 * if we are run in a container /proc/cmdline is not
1013 * relevant for the container, hence we rely on argv[]
1014 * instead. */
1015
1016 for (a = argv; a < argv + argc; a++)
1017 if ((r = parse_proc_cmdline_word(*a)) < 0)
1018 return r;
51f0e189
LP
1019 }
1020
f170852a
LP
1021 return 0;
1022}
1023
1024static int help(void) {
1025
2e33c433 1026 printf("%s [OPTIONS...]\n\n"
af2d49f7 1027 "Starts up and maintains the system or user services.\n\n"
e537352b 1028 " -h --help Show this help\n"
e537352b 1029 " --test Determine startup sequence, dump it and exit\n"
80876c20 1030 " --dump-configuration-items Dump understood unit configuration items\n"
bbe63281 1031 " --introspect[=INTERFACE] Extract D-Bus interface data\n"
9e58ff9c 1032 " --unit=UNIT Set default unit\n"
edb9aaa8 1033 " --system Run a system instance, even if PID != 1\n"
af2d49f7 1034 " --user Run a user instance\n"
a5d87bf0
LP
1035 " --dump-core[=0|1] Dump core on crash\n"
1036 " --crash-shell[=0|1] Run shell on crash\n"
1037 " --confirm-spawn[=0|1] Ask for confirmation when spawning processes\n"
6e98720f 1038 " --show-status[=0|1] Show status updates on the console during bootup\n"
4cfa2c99 1039 " --log-target=TARGET Set log target (console, journal, syslog, kmsg, journal-or-kmsg, syslog-or-kmsg, null)\n"
9e58ff9c 1040 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
2218198b 1041 " --log-color[=0|1] Highlight important log messages\n"
0a494f1f
LP
1042 " --log-location[=0|1] Include code location in log messages\n"
1043 " --default-standard-output= Set default standard output for services\n"
1044 " --default-standard-error= Set default standard error output for services\n",
5b6319dc 1045 program_invocation_short_name);
f170852a
LP
1046
1047 return 0;
1048}
1049
a16e1123
LP
1050static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
1051 FILE *f = NULL;
1052 FDSet *fds = NULL;
1053 int r;
1054
1055 assert(m);
1056 assert(_f);
1057 assert(_fds);
1058
a7556052
LP
1059 /* Make sure nothing is really destructed when we shut down */
1060 m->n_reloading ++;
1061
d8d5ab98 1062 if ((r = manager_open_serialization(m, &f)) < 0) {
35b8ca3a 1063 log_error("Failed to create serialization file: %s", strerror(-r));
a16e1123
LP
1064 goto fail;
1065 }
1066
1067 if (!(fds = fdset_new())) {
1068 r = -ENOMEM;
1069 log_error("Failed to allocate fd set: %s", strerror(-r));
1070 goto fail;
1071 }
1072
1073 if ((r = manager_serialize(m, f, fds)) < 0) {
1074 log_error("Failed to serialize state: %s", strerror(-r));
1075 goto fail;
1076 }
1077
1078 if (fseeko(f, 0, SEEK_SET) < 0) {
1079 log_error("Failed to rewind serialization fd: %m");
1080 goto fail;
1081 }
1082
1083 if ((r = fd_cloexec(fileno(f), false)) < 0) {
1084 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
1085 goto fail;
1086 }
1087
1088 if ((r = fdset_cloexec(fds, false)) < 0) {
1089 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
1090 goto fail;
1091 }
1092
1093 *_f = f;
1094 *_fds = fds;
1095
1096 return 0;
1097
1098fail:
1099 fdset_free(fds);
1100
1101 if (f)
1102 fclose(f);
1103
1104 return r;
1105}
1106
e9ddabc2
LP
1107static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
1108 const char *e;
1109 unsigned long long a, b;
1110
1111 assert(t);
1112
966a5d37
LP
1113 e = getenv("RD_TIMESTAMP");
1114 if (!e)
e9ddabc2
LP
1115 return NULL;
1116
1117 if (sscanf(e, "%llu %llu", &a, &b) != 2)
1118 return NULL;
1119
1120 t->realtime = (usec_t) a;
1121 t->monotonic = (usec_t) b;
1122
1123 return t;
1124}
1125
6ee5bbf8
LP
1126static void test_mtab(void) {
1127 char *p;
1128
80758717
LP
1129 /* Check that /etc/mtab is a symlink */
1130
6ee5bbf8
LP
1131 if (readlink_malloc("/etc/mtab", &p) >= 0) {
1132 bool b;
1133
ed86ebc4 1134 b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
6ee5bbf8
LP
1135 free(p);
1136
1137 if (b)
1138 return;
1139 }
1140
80758717
LP
1141 log_warning("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
1142 "This is not supported anymore. "
1143 "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
1144}
1145
1146static void test_usr(void) {
80758717 1147
ed1c99fc 1148 /* Check that /usr is not a separate fs */
80758717 1149
871c44a7
LP
1150 if (dir_is_empty("/usr") <= 0)
1151 return;
1152
2376ce13 1153 log_warning("/usr appears to be on its own filesytem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1154 "Some things will probably break (sometimes even silently) in mysterious ways. "
1155 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1156}
1157
1158static void test_cgroups(void) {
1159
1160 if (access("/proc/cgroups", F_OK) >= 0)
1161 return;
1162
1163 log_warning("CONFIG_CGROUPS was not set when your kernel was compiled. "
1164 "Systems without control groups are not supported. "
1165 "We will now sleep for 10s, and then continue boot-up. "
1166 "Expect breakage and please do not file bugs. "
966a5d37
LP
1167 "Instead fix your kernel and enable CONFIG_CGROUPS. "
1168 "Consult http://0pointer.de/blog/projects/cgroups-vs-cgroups.html for more information.");
871c44a7
LP
1169
1170 sleep(10);
6ee5bbf8
LP
1171}
1172
60918275
LP
1173int main(int argc, char *argv[]) {
1174 Manager *m = NULL;
22f4096c 1175 int r, retval = EXIT_FAILURE;
9d76d730
LP
1176 usec_t before_startup, after_startup;
1177 char timespan[FORMAT_TIMESPAN_MAX];
a16e1123
LP
1178 FDSet *fds = NULL;
1179 bool reexecute = false;
b9080b03 1180 const char *shutdown_verb = NULL;
e9ddabc2 1181 dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
5d6b1584 1182 static char systemd[] = "systemd";
2660882b 1183 bool skip_setup = false;
0b3325e7
LP
1184 int j;
1185 bool loaded_policy = false;
e96d6be7 1186 bool arm_reboot_watchdog = false;
bf4df7c3 1187 bool queue_default_job = false;
41669317 1188 char *switch_root_dir = NULL, *switch_root_init = NULL;
27b14a22 1189
058dc6f3 1190#ifdef HAVE_SYSV_COMPAT
2cb1a60d 1191 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
35b8ca3a 1192 /* This is compatibility support for SysV, where
2cb1a60d
LP
1193 * calling init as a user is identical to telinit. */
1194
1195 errno = -ENOENT;
1196 execv(SYSTEMCTL_BINARY_PATH, argv);
1197 log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1198 return 1;
1199 }
058dc6f3 1200#endif
2cb1a60d 1201
0b3325e7
LP
1202 /* Determine if this is a reexecution or normal bootup. We do
1203 * the full command line parsing much later, so let's just
1204 * have a quick peek here. */
0b3325e7
LP
1205 for (j = 1; j < argc; j++)
1206 if (streq(argv[j], "--deserialize")) {
2660882b 1207 skip_setup = true;
7aaa27f2 1208 break;
0b3325e7
LP
1209 }
1210
2660882b
LP
1211 /* If we have switched root, do all the special setup
1212 * things */
d03bc1b8 1213 for (j = 1; j < argc; j++)
2660882b
LP
1214 if (streq(argv[j], "--switched-root")) {
1215 skip_setup = false;
d03bc1b8
HH
1216 break;
1217 }
1218
f3b6a3ed
LP
1219 /* If we get started via the /sbin/init symlink then we are
1220 called 'init'. After a subsequent reexecution we are then
1221 called 'systemd'. That is confusing, hence let's call us
1222 systemd right-away. */
f3b6a3ed
LP
1223 program_invocation_short_name = systemd;
1224 prctl(PR_SET_NAME, systemd);
5d6b1584 1225
9a0e6896
LP
1226 saved_argv = argv;
1227 saved_argc = argc;
f3b6a3ed 1228
2cc59dbf 1229 log_show_color(isatty(STDERR_FILENO) > 0);
bbe63281 1230 log_show_location(false);
7c706717 1231 log_set_max_level(LOG_INFO);
bbe63281 1232
843d2643 1233 if (getpid() == 1) {
c3ba6250
HH
1234 if (in_initrd()) {
1235 char *rd_timestamp = NULL;
1236
1237 dual_timestamp_get(&initrd_timestamp);
1238 asprintf(&rd_timestamp, "%llu %llu",
1239 (unsigned long long) initrd_timestamp.realtime,
1240 (unsigned long long) initrd_timestamp.monotonic);
1241 if (rd_timestamp) {
1242 setenv("RD_TIMESTAMP", rd_timestamp, 1);
1243 free(rd_timestamp);
1244 }
1245 }
1246
fa0f4d8a 1247 arg_running_as = MANAGER_SYSTEM;
a0a38448 1248 log_set_target(detect_container(NULL) > 0 ? LOG_TARGET_JOURNAL : LOG_TARGET_JOURNAL_OR_KMSG);
0ff4cdd9 1249
2660882b 1250 if (!skip_setup) {
0b3325e7
LP
1251 if (selinux_setup(&loaded_policy) < 0)
1252 goto finish;
81611586
RS
1253 if (ima_setup() < 0)
1254 goto finish;
1255 }
0b3325e7
LP
1256
1257 log_open();
c4dcdb9f 1258
e9a5ef7c 1259 if (label_init(NULL) < 0)
0ff4cdd9 1260 goto finish;
7948c4df 1261
2660882b 1262 if (!skip_setup)
0b3325e7
LP
1263 if (hwclock_is_localtime() > 0) {
1264 int min;
7948c4df 1265
0b3325e7
LP
1266 r = hwclock_apply_localtime_delta(&min);
1267 if (r < 0)
1268 log_error("Failed to apply local time delta, ignoring: %s", strerror(-r));
1269 else
1270 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1271 }
871e5809 1272
bbe63281 1273 } else {
af2d49f7 1274 arg_running_as = MANAGER_USER;
eeecf6e6 1275 log_set_target(LOG_TARGET_AUTO);
871e5809 1276 log_open();
bbe63281 1277 }
a5dab5ce 1278
0c85a4f3 1279 /* Initialize default unit */
f170852a
LP
1280 if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
1281 goto finish;
60918275 1282
0c85a4f3
LP
1283 /* By default, mount "cpu" and "cpuacct" together */
1284 arg_join_controllers = new(char**, 2);
1285 if (!arg_join_controllers)
1286 goto finish;
1287
1288 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
1289 arg_join_controllers[1] = NULL;
1290
1291 if (!arg_join_controllers[0])
1292 goto finish;
1293
f170852a
LP
1294 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1295 * /proc/$PID/fd is available. */
0c85a4f3
LP
1296 if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1297 r = mount_setup(loaded_policy);
1298 if (r < 0)
8efe3c01 1299 goto finish;
0c85a4f3 1300 }
4ade7963
LP
1301
1302 /* Reset all signal handlers. */
1303 assert_se(reset_all_signal_handlers() == 0);
1304
078e4539 1305 /* If we are init, we can block sigkill. Yay. */
9a34ec5f 1306 ignore_signals(SIGNALS_IGNORE, -1);
078e4539 1307
487393e9
LP
1308 if (parse_config_file() < 0)
1309 goto finish;
1310
fa0f4d8a 1311 if (arg_running_as == MANAGER_SYSTEM)
a5dab5ce
LP
1312 if (parse_proc_cmdline() < 0)
1313 goto finish;
f170852a
LP
1314
1315 log_parse_environment();
1316
1317 if (parse_argv(argc, argv) < 0)
1318 goto finish;
1319
b5c6cf87
LP
1320 if (arg_action == ACTION_TEST && geteuid() == 0) {
1321 log_error("Don't run test mode as root.");
1322 goto finish;
1323 }
1324
fe783b03
LP
1325 if (arg_running_as == MANAGER_SYSTEM &&
1326 arg_action == ACTION_RUN &&
1327 running_in_chroot() > 0) {
1328 log_error("Cannot be run in a chroot() environment.");
1329 goto finish;
1330 }
1331
fa0f4d8a 1332 if (arg_action == ACTION_HELP) {
f170852a
LP
1333 retval = help();
1334 goto finish;
fa0f4d8a 1335 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 1336 unit_dump_config_items(stdout);
22f4096c 1337 retval = EXIT_SUCCESS;
e537352b 1338 goto finish;
fa0f4d8a 1339 } else if (arg_action == ACTION_DONE) {
22f4096c 1340 retval = EXIT_SUCCESS;
4288f619 1341 goto finish;
f170852a
LP
1342 }
1343
fa0f4d8a 1344 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
f170852a 1345
871e5809
LP
1346 /* Close logging fds, in order not to confuse fdset below */
1347 log_close();
1348
a16e1123
LP
1349 /* Remember open file descriptors for later deserialization */
1350 if (serialization) {
966a5d37
LP
1351 r = fdset_new_fill(&fds);
1352 if (r < 0) {
a16e1123
LP
1353 log_error("Failed to allocate fd set: %s", strerror(-r));
1354 goto finish;
1355 }
1356
1357 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
1358 } else
1359 close_all_fds(NULL, 0);
1360
09082a94 1361 /* Set up PATH unless it is already set */
e537352b 1362 setenv("PATH",
2c6db6fb 1363#ifdef HAVE_SPLIT_USR
e537352b 1364 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
2c6db6fb
LP
1365#else
1366 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
1367#endif
fa0f4d8a 1368 arg_running_as == MANAGER_SYSTEM);
09082a94 1369
39439087 1370 if (arg_running_as == MANAGER_SYSTEM) {
71ecc858
LP
1371 /* Parse the data passed to us. We leave this
1372 * variables set, but the manager later on will not
1373 * pass them on to our children. */
2660882b 1374 if (!in_initrd())
c3ba6250 1375 parse_initrd_timestamp(&initrd_timestamp);
e9ddabc2
LP
1376
1377 /* Unset some environment variables passed in from the
1378 * kernel that don't really make sense for us. */
39439087
LP
1379 unsetenv("HOME");
1380 unsetenv("TERM");
b770165a 1381
9543ad16
LP
1382 /* When we are invoked by a shell, these might be set,
1383 * but make little sense to pass on */
1384 unsetenv("PWD");
1385 unsetenv("SHLVL");
1386 unsetenv("_");
1387
2660882b 1388 /* When we are invoked by a chroot-like tool such as
9f28b98e
LP
1389 * nspawn, these might be set, but make little sense
1390 * to pass on */
1391 unsetenv("USER");
1392 unsetenv("LOGNAME");
1393
b770165a
LP
1394 /* All other variables are left as is, so that clients
1395 * can still read them via /proc/1/environ */
39439087 1396 }
1104f3c1 1397
f170852a
LP
1398 /* Move out of the way, so that we won't block unmounts */
1399 assert_se(chdir("/") == 0);
1400
fa0f4d8a 1401 if (arg_running_as == MANAGER_SYSTEM) {
80876c20
LP
1402 /* Become a session leader if we aren't one yet. */
1403 setsid();
4ade7963 1404
80876c20
LP
1405 /* Disable the umask logic */
1406 umask(0);
1407 }
1408
843d2643
LP
1409 /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
1410 dbus_connection_set_change_sigpipe(FALSE);
1411
2146621b
LP
1412 /* Reset the console, but only if this is really init and we
1413 * are freshly booted */
fa0f4d8a 1414 if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
2660882b 1415 console_setup(getpid() == 1 && !skip_setup);
843d2643
LP
1416 make_null_stdio();
1417 }
4ade7963 1418
18149b9f 1419 /* Open the logging devices, if possible and necessary */
843d2643 1420 log_open();
4ade7963 1421
5373d602
LP
1422 /* Make sure we leave a core dump without panicing the
1423 * kernel. */
4fc935ca
LP
1424 if (getpid() == 1)
1425 install_crash_handler();
97c4f35c 1426
0c85a4f3
LP
1427 if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1428 r = mount_cgroup_controllers(arg_join_controllers);
1429 if (r < 0)
1430 goto finish;
1431 }
1432
c20f5ac7
LP
1433 if (arg_running_as == MANAGER_SYSTEM) {
1434 const char *virtualization = NULL;
1435
1436 log_info(PACKAGE_STRING " running in system mode. (" SYSTEMD_FEATURES "; " DISTRIBUTION ")");
1437
1438 detect_virtualization(&virtualization);
1439 if (virtualization)
1440 log_info("Detected virtualization '%s'.", virtualization);
1441
1442 } else
1443 log_debug(PACKAGE_STRING " running in user mode. (" SYSTEMD_FEATURES "; " DISTRIBUTION ")");
a5dab5ce 1444
2660882b 1445 if (arg_running_as == MANAGER_SYSTEM && !skip_setup) {
72bca11b
LP
1446 locale_setup();
1447
6faa1114 1448 if (arg_show_status || plymouth_running())
888c6216
LP
1449 status_welcome();
1450
888c6216
LP
1451 kmod_setup();
1452 hostname_setup();
d7ccca2e 1453 machine_id_setup();
888c6216 1454 loopback_setup();
490aed58 1455
6ee5bbf8 1456 test_mtab();
80758717 1457 test_usr();
871c44a7 1458 test_cgroups();
af5bc85d 1459 }
302e8c4c 1460
e96d6be7
LP
1461 if (arg_running_as == MANAGER_SYSTEM && arg_runtime_watchdog > 0)
1462 watchdog_set_timeout(&arg_runtime_watchdog);
1463
aa0f64ac
LP
1464 if (arg_timer_slack_nsec != (nsec_t) -1)
1465 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
1466 log_error("Failed to adjust timer slack: %m");
1467
ec8927ca
LP
1468 if (arg_capability_bounding_set_drop) {
1469 r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
1470 if (r < 0) {
1471 log_error("Failed to drop capability bounding set: %s", strerror(-r));
1472 goto finish;
1473 }
939b8f14
LP
1474 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
1475 if (r < 0) {
1476 log_error("Failed to drop capability bounding set of usermode helpers: %s", strerror(-r));
1477 goto finish;
1478 }
ec8927ca
LP
1479 }
1480
e96d6be7
LP
1481 r = manager_new(arg_running_as, &m);
1482 if (r < 0) {
8e274523 1483 log_error("Failed to allocate manager object: %s", strerror(-r));
60918275
LP
1484 goto finish;
1485 }
1486
9e58ff9c 1487 m->confirm_spawn = arg_confirm_spawn;
0a494f1f
LP
1488 m->default_std_output = arg_default_std_output;
1489 m->default_std_error = arg_default_std_error;
e96d6be7
LP
1490 m->runtime_watchdog = arg_runtime_watchdog;
1491 m->shutdown_watchdog = arg_shutdown_watchdog;
9e58ff9c 1492
c93ff2e9
FC
1493 manager_set_default_rlimits(m, arg_default_rlimit);
1494
e9ddabc2
LP
1495 if (dual_timestamp_is_set(&initrd_timestamp))
1496 m->initrd_timestamp = initrd_timestamp;
1497
06d4c99a
LP
1498 if (arg_default_controllers)
1499 manager_set_default_controllers(m, arg_default_controllers);
1500
27d340c7
LP
1501 manager_set_show_status(m, arg_show_status);
1502
bf4df7c3
LP
1503 /* Remember whether we should queue the default job */
1504 queue_default_job = !serialization || arg_switched_root;
1505
9d76d730
LP
1506 before_startup = now(CLOCK_MONOTONIC);
1507
e96d6be7
LP
1508 r = manager_startup(m, serialization, fds);
1509 if (r < 0)
6e2ef85b 1510 log_error("Failed to fully start up daemon: %s", strerror(-r));
a16e1123 1511
bf4df7c3
LP
1512 /* This will close all file descriptors that were opened, but
1513 * not claimed by any unit. */
a16e1123 1514 if (fds) {
a16e1123
LP
1515 fdset_free(fds);
1516 fds = NULL;
f50e0a01
LP
1517 }
1518
a16e1123
LP
1519 if (serialization) {
1520 fclose(serialization);
1521 serialization = NULL;
bf4df7c3
LP
1522 }
1523
1524 if (queue_default_job) {
398ef8ba 1525 DBusError error;
1c27d3f3 1526 Unit *target = NULL;
bacbccb7 1527 Job *default_unit_job;
398ef8ba
LP
1528
1529 dbus_error_init(&error);
1530
fa0f4d8a 1531 log_debug("Activating default unit: %s", arg_default_unit);
a16e1123 1532
e96d6be7
LP
1533 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
1534 if (r < 0) {
398ef8ba
LP
1535 log_error("Failed to load default target: %s", bus_error(&error, r));
1536 dbus_error_free(&error);
ac155bb8
MS
1537 } else if (target->load_state == UNIT_ERROR)
1538 log_error("Failed to load default target: %s", strerror(-target->load_error));
1539 else if (target->load_state == UNIT_MASKED)
6daf4f90 1540 log_error("Default target masked.");
27b14a22 1541
ac155bb8 1542 if (!target || target->load_state != UNIT_LOADED) {
a16e1123 1543 log_info("Trying to load rescue target...");
1c27d3f3 1544
e96d6be7
LP
1545 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1546 if (r < 0) {
398ef8ba
LP
1547 log_error("Failed to load rescue target: %s", bus_error(&error, r));
1548 dbus_error_free(&error);
a16e1123 1549 goto finish;
ac155bb8
MS
1550 } else if (target->load_state == UNIT_ERROR) {
1551 log_error("Failed to load rescue target: %s", strerror(-target->load_error));
1c27d3f3 1552 goto finish;
ac155bb8 1553 } else if (target->load_state == UNIT_MASKED) {
6daf4f90 1554 log_error("Rescue target masked.");
00dc5d76 1555 goto finish;
a16e1123
LP
1556 }
1557 }
37d88da7 1558
ac155bb8 1559 assert(target->load_state == UNIT_LOADED);
00dc5d76 1560
fa0f4d8a 1561 if (arg_action == ACTION_TEST) {
40d50879 1562 printf("-> By units:\n");
a16e1123
LP
1563 manager_dump_units(m, stdout, "\t");
1564 }
1565
bacbccb7
MS
1566 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, &default_unit_job);
1567 if (r < 0) {
398ef8ba
LP
1568 log_error("Failed to start default target: %s", bus_error(&error, r));
1569 dbus_error_free(&error);
37d88da7
LP
1570 goto finish;
1571 }
bacbccb7 1572 m->default_unit_job_id = default_unit_job->id;
60918275 1573
07672f49
LP
1574 after_startup = now(CLOCK_MONOTONIC);
1575 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1576 "Loaded units and determined initial transaction in %s.",
1577 format_timespan(timespan, sizeof(timespan), after_startup - before_startup));
1578
fa0f4d8a 1579 if (arg_action == ACTION_TEST) {
40d50879 1580 printf("-> By jobs:\n");
a16e1123 1581 manager_dump_jobs(m, stdout, "\t");
22f4096c 1582 retval = EXIT_SUCCESS;
a16e1123
LP
1583 goto finish;
1584 }
e965d56d 1585 }
d46de8a1 1586
a16e1123 1587 for (;;) {
e96d6be7
LP
1588 r = manager_loop(m);
1589 if (r < 0) {
a16e1123
LP
1590 log_error("Failed to run mainloop: %s", strerror(-r));
1591 goto finish;
1592 }
11dd41ce 1593
a16e1123 1594 switch (m->exit_code) {
e965d56d 1595
a16e1123 1596 case MANAGER_EXIT:
22f4096c 1597 retval = EXIT_SUCCESS;
a16e1123
LP
1598 log_debug("Exit.");
1599 goto finish;
e965d56d 1600
a16e1123 1601 case MANAGER_RELOAD:
e015090f 1602 log_info("Reloading.");
e96d6be7
LP
1603 r = manager_reload(m);
1604 if (r < 0)
a16e1123
LP
1605 log_error("Failed to reload: %s", strerror(-r));
1606 break;
cea8e32e 1607
a16e1123 1608 case MANAGER_REEXECUTE:
664f88a7 1609
a16e1123
LP
1610 if (prepare_reexecute(m, &serialization, &fds) < 0)
1611 goto finish;
60918275 1612
a16e1123 1613 reexecute = true;
e015090f 1614 log_notice("Reexecuting.");
a16e1123
LP
1615 goto finish;
1616
664f88a7
LP
1617 case MANAGER_SWITCH_ROOT:
1618 /* Steal the switch root parameters */
41669317 1619 switch_root_dir = m->switch_root;
664f88a7
LP
1620 switch_root_init = m->switch_root_init;
1621 m->switch_root = m->switch_root_init = NULL;
1622
1623 if (!switch_root_init)
1624 if (prepare_reexecute(m, &serialization, &fds) < 0)
1625 goto finish;
1626
1627 reexecute = true;
1628 log_notice("Switching root.");
1629 goto finish;
1630
b9080b03
FF
1631 case MANAGER_REBOOT:
1632 case MANAGER_POWEROFF:
1633 case MANAGER_HALT:
1634 case MANAGER_KEXEC: {
1635 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
1636 [MANAGER_REBOOT] = "reboot",
1637 [MANAGER_POWEROFF] = "poweroff",
1638 [MANAGER_HALT] = "halt",
1639 [MANAGER_KEXEC] = "kexec"
1640 };
1641
1642 assert_se(shutdown_verb = table[m->exit_code]);
e96d6be7 1643 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
b9080b03
FF
1644
1645 log_notice("Shutting down.");
1646 goto finish;
1647 }
1648
a16e1123
LP
1649 default:
1650 assert_not_reached("Unknown exit code.");
1651 }
1652 }
f170852a 1653
60918275
LP
1654finish:
1655 if (m)
1656 manager_free(m);
1657
c93ff2e9
FC
1658 for (j = 0; j < RLIMIT_NLIMITS; j++)
1659 free (arg_default_rlimit[j]);
1660
fa0f4d8a 1661 free(arg_default_unit);
06d4c99a 1662 strv_free(arg_default_controllers);
0c85a4f3 1663 free_join_controllers();
b9cd2ec1 1664
ea430986 1665 dbus_shutdown();
b2bb3dbe
LP
1666 label_finish();
1667
a16e1123 1668 if (reexecute) {
664f88a7 1669 const char **args;
e564a982 1670 unsigned i, args_size;
a16e1123 1671
664f88a7
LP
1672 /* Close and disarm the watchdog, so that the new
1673 * instance can reinitialize it, but doesn't get
1674 * rebooted while we do that */
1675 watchdog_close(true);
a16e1123 1676
41669317
LP
1677 if (switch_root_dir) {
1678 r = switch_root(switch_root_dir);
1679 if (r < 0)
1680 log_error("Failed to switch root, ignoring: %s", strerror(-r));
1681 }
a16e1123 1682
d03bc1b8 1683 args_size = MAX(6, argc+1);
e564a982 1684 args = newa(const char*, args_size);
a16e1123 1685
664f88a7
LP
1686 if (!switch_root_init) {
1687 char sfd[16];
a16e1123 1688
664f88a7
LP
1689 /* First try to spawn ourselves with the right
1690 * path, and with full serialization. We do
1691 * this only if the user didn't specify an
1692 * explicit init to spawn. */
edb9aaa8 1693
664f88a7
LP
1694 assert(serialization);
1695 assert(fds);
edb9aaa8 1696
664f88a7
LP
1697 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
1698 char_array_0(sfd);
edb9aaa8 1699
664f88a7
LP
1700 i = 0;
1701 args[i++] = SYSTEMD_BINARY_PATH;
41669317 1702 if (switch_root_dir)
2660882b 1703 args[i++] = "--switched-root";
664f88a7
LP
1704 args[i++] = arg_running_as == MANAGER_SYSTEM ? "--system" : "--user";
1705 args[i++] = "--deserialize";
1706 args[i++] = sfd;
1707 args[i++] = NULL;
edb9aaa8 1708
e564a982 1709 assert(i <= args_size);
664f88a7
LP
1710 execv(args[0], (char* const*) args);
1711 }
6e98720f 1712
664f88a7
LP
1713 /* Try the fallback, if there is any, without any
1714 * serialization. We pass the original argv[] and
1715 * envp[]. (Well, modulo the ordering changes due to
1716 * getopt() in argv[], and some cleanups in envp[],
1717 * but let's hope that doesn't matter.) */
a16e1123 1718
b8f83232 1719 if (serialization) {
664f88a7 1720 fclose(serialization);
b8f83232
LP
1721 serialization = NULL;
1722 }
a16e1123 1723
b8f83232 1724 if (fds) {
664f88a7 1725 fdset_free(fds);
b8f83232
LP
1726 fds = NULL;
1727 }
a16e1123 1728
b8f83232 1729 for (j = 1, i = 1; j < argc; j++)
664f88a7 1730 args[i++] = argv[j];
a16e1123 1731 args[i++] = NULL;
e564a982 1732 assert(i <= args_size);
b8f83232
LP
1733
1734 if (switch_root_init) {
1735 args[0] = switch_root_init;
1736 execv(args[0], (char* const*) args);
1737 log_warning("Failed to execute configured init, trying fallback: %m");
1738 }
1739
1740 args[0] = "/sbin/init";
a16e1123
LP
1741 execv(args[0], (char* const*) args);
1742
745e2fb7
KS
1743 if (errno == ENOENT) {
1744 log_warning("No /sbin/init, trying fallback");
b8f83232 1745
745e2fb7
KS
1746 args[0] = "/bin/sh";
1747 args[1] = NULL;
1748 execv(args[0], (char* const*) args);
1749 log_error("Failed to execute /bin/sh, giving up: %m");
1750 } else
1751 log_warning("Failed to execute /sbin/init, giving up: %m");
a16e1123
LP
1752 }
1753
1754 if (serialization)
1755 fclose(serialization);
1756
1757 if (fds)
1758 fdset_free(fds);
1759
b9080b03
FF
1760 if (shutdown_verb) {
1761 const char * command_line[] = {
1762 SYSTEMD_SHUTDOWN_BINARY_PATH,
1763 shutdown_verb,
1764 NULL
1765 };
d18f337c 1766 char **env_block;
b9080b03 1767
e96d6be7 1768 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0) {
d18f337c
LP
1769 char e[32];
1770
e96d6be7
LP
1771 /* If we reboot let's set the shutdown
1772 * watchdog and tell the shutdown binary to
1773 * repeatedly ping it */
1774 watchdog_set_timeout(&arg_shutdown_watchdog);
1775 watchdog_close(false);
1776
1777 /* Tell the binary how often to ping */
1778 snprintf(e, sizeof(e), "WATCHDOG_USEC=%llu", (unsigned long long) arg_shutdown_watchdog);
1779 char_array_0(e);
d18f337c
LP
1780
1781 env_block = strv_append(environ, e);
1782 } else {
1783 env_block = strv_copy(environ);
e96d6be7 1784 watchdog_close(true);
d18f337c 1785 }
e96d6be7 1786
d18f337c
LP
1787 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1788 free(env_block);
b9080b03
FF
1789 log_error("Failed to execute shutdown binary, freezing: %m");
1790 }
1791
c3b3c274
LP
1792 if (getpid() == 1)
1793 freeze();
1794
60918275
LP
1795 return retval;
1796}