]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/main.c
Systemd is causing mislabeled devices to be created and then attempting to read them.
[thirdparty/systemd.git] / src / main.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
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
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
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
16 General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <dbus/dbus.h>
23
24 #include <stdio.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <getopt.h>
31 #include <signal.h>
32 #include <sys/wait.h>
33 #include <fcntl.h>
34
35 #include "manager.h"
36 #include "log.h"
37 #include "mount-setup.h"
38 #include "hostname-setup.h"
39 #include "loopback-setup.h"
40 #include "kmod-setup.h"
41 #include "modprobe-setup.h"
42 #include "load-fragment.h"
43 #include "fdset.h"
44 #include "special.h"
45 #include "conf-parser.h"
46 #include "bus-errors.h"
47 #include "missing.h"
48
49 static enum {
50 ACTION_RUN,
51 ACTION_HELP,
52 ACTION_TEST,
53 ACTION_DUMP_CONFIGURATION_ITEMS,
54 ACTION_DONE
55 } arg_action = ACTION_RUN;
56
57 static char *arg_default_unit = NULL;
58 static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
59
60 static bool arg_dump_core = true;
61 static bool arg_crash_shell = false;
62 static int arg_crash_chvt = -1;
63 static bool arg_confirm_spawn = false;
64 static bool arg_nomodules = false;
65 static bool arg_show_status = true;
66
67 static FILE* serialization = NULL;
68
69 _noreturn_ static void freeze(void) {
70 for (;;)
71 pause();
72 }
73
74 static void nop_handler(int sig) {
75 }
76
77 _noreturn_ static void crash(int sig) {
78
79 if (!arg_dump_core)
80 log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
81 else {
82 struct sigaction sa;
83 pid_t pid;
84
85 /* We want to wait for the core process, hence let's enable SIGCHLD */
86 zero(sa);
87 sa.sa_handler = nop_handler;
88 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
89 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
90
91 if ((pid = fork()) < 0)
92 log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
93
94 else if (pid == 0) {
95 struct rlimit rl;
96
97 /* Enable default signal handler for core dump */
98 zero(sa);
99 sa.sa_handler = SIG_DFL;
100 assert_se(sigaction(sig, &sa, NULL) == 0);
101
102 /* Don't limit the core dump size */
103 zero(rl);
104 rl.rlim_cur = RLIM_INFINITY;
105 rl.rlim_max = RLIM_INFINITY;
106 setrlimit(RLIMIT_CORE, &rl);
107
108 /* Just to be sure... */
109 assert_se(chdir("/") == 0);
110
111 /* Raise the signal again */
112 raise(sig);
113
114 assert_not_reached("We shouldn't be here...");
115 _exit(1);
116
117 } else {
118 int status, r;
119
120 /* Order things nicely. */
121 if ((r = waitpid(pid, &status, 0)) < 0)
122 log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(errno));
123 else if (!WCOREDUMP(status))
124 log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
125 else
126 log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
127 }
128 }
129
130 if (arg_crash_chvt)
131 chvt(arg_crash_chvt);
132
133 if (arg_crash_shell) {
134 struct sigaction sa;
135 pid_t pid;
136
137 log_info("Executing crash shell in 10s...");
138 sleep(10);
139
140 /* Let the kernel reap children for us */
141 zero(sa);
142 sa.sa_handler = SIG_IGN;
143 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
144 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
145
146 if ((pid = fork()) < 0)
147 log_error("Failed to fork off crash shell: %s", strerror(errno));
148 else if (pid == 0) {
149 int fd, r;
150
151 if ((fd = acquire_terminal("/dev/console", false, true, true)) < 0)
152 log_error("Failed to acquire terminal: %s", strerror(-fd));
153 else if ((r = make_stdio(fd)) < 0)
154 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
155
156 execl("/bin/sh", "/bin/sh", NULL);
157
158 log_error("execl() failed: %s", strerror(errno));
159 _exit(1);
160 }
161
162 log_info("Successfully spawned crash shall as pid %lu.", (unsigned long) pid);
163 }
164
165 log_info("Freezing execution.");
166 freeze();
167 }
168
169 static void install_crash_handler(void) {
170 struct sigaction sa;
171
172 zero(sa);
173
174 sa.sa_handler = crash;
175 sa.sa_flags = SA_NODEFER;
176
177 sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
178 }
179
180 static int make_null_stdio(void) {
181 int null_fd, r;
182
183 if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0) {
184 log_error("Failed to open /dev/null: %m");
185 return -errno;
186 }
187
188 if ((r = make_stdio(null_fd)) < 0)
189 log_warning("Failed to dup2() device: %s", strerror(-r));
190
191 return r;
192 }
193
194 static int console_setup(bool do_reset) {
195 int tty_fd, r;
196
197 /* If we are init, we connect stdin/stdout/stderr to /dev/null
198 * and make sure we don't have a controlling tty. */
199
200 release_terminal();
201
202 if (!do_reset)
203 return 0;
204
205 if ((tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0) {
206 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
207 return -tty_fd;
208 }
209
210 if ((r = reset_terminal(tty_fd)) < 0)
211 log_error("Failed to reset /dev/console: %s", strerror(-r));
212
213 close_nointr_nofail(tty_fd);
214 return r;
215 }
216
217 static int set_default_unit(const char *u) {
218 char *c;
219
220 assert(u);
221
222 if (!(c = strdup(u)))
223 return -ENOMEM;
224
225 free(arg_default_unit);
226 arg_default_unit = c;
227 return 0;
228 }
229
230 static int parse_proc_cmdline_word(const char *word) {
231
232 static const char * const rlmap[] = {
233 "single", SPECIAL_RESCUE_TARGET,
234 "-s", SPECIAL_RESCUE_TARGET,
235 "s", SPECIAL_RESCUE_TARGET,
236 "S", SPECIAL_RESCUE_TARGET,
237 "1", SPECIAL_RESCUE_TARGET,
238 "2", SPECIAL_RUNLEVEL2_TARGET,
239 "3", SPECIAL_RUNLEVEL3_TARGET,
240 "4", SPECIAL_RUNLEVEL4_TARGET,
241 "5", SPECIAL_RUNLEVEL5_TARGET
242 };
243 bool ignore_quiet = false;
244
245 if (startswith(word, "systemd.unit="))
246 return set_default_unit(word + 13);
247
248 else if (startswith(word, "systemd.log_target=")) {
249
250 if (log_set_target_from_string(word + 19) < 0)
251 log_warning("Failed to parse log target %s. Ignoring.", word + 19);
252
253 } else if (startswith(word, "systemd.log_level=")) {
254
255 if (log_set_max_level_from_string(word + 18) < 0)
256 log_warning("Failed to parse log level %s. Ignoring.", word + 18);
257
258 } else if (startswith(word, "systemd.log_color=")) {
259
260 if (log_show_color_from_string(word + 18) < 0)
261 log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
262
263 } else if (startswith(word, "systemd.log_location=")) {
264
265 if (log_show_location_from_string(word + 21) < 0)
266 log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
267
268 } else if (startswith(word, "systemd.dump_core=")) {
269 int r;
270
271 if ((r = parse_boolean(word + 18)) < 0)
272 log_warning("Failed to parse dump core switch %s, Ignoring.", word + 18);
273 else
274 arg_dump_core = r;
275
276 } else if (startswith(word, "systemd.crash_shell=")) {
277 int r;
278
279 if ((r = parse_boolean(word + 20)) < 0)
280 log_warning("Failed to parse crash shell switch %s, Ignoring.", word + 20);
281 else
282 arg_crash_shell = r;
283
284 } else if (startswith(word, "systemd.confirm_spawn=")) {
285 int r;
286
287 if ((r = parse_boolean(word + 22)) < 0)
288 log_warning("Failed to parse confirm spawn switch %s, Ignoring.", word + 22);
289 else
290 arg_confirm_spawn = r;
291
292 } else if (startswith(word, "systemd.crash_chvt=")) {
293 int k;
294
295 if (safe_atoi(word + 19, &k) < 0)
296 log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
297 else
298 arg_crash_chvt = k;
299
300 } else if (startswith(word, "systemd.show_status=")) {
301 int r;
302
303 if ((r = parse_boolean(word + 20)) < 0)
304 log_warning("Failed to parse show status switch %s, Ignoring.", word + 20);
305 else {
306 arg_show_status = r;
307 ignore_quiet = true;
308 }
309
310 } else if (startswith(word, "systemd.")) {
311
312 log_warning("Unknown kernel switch %s. Ignoring.", word);
313
314 log_info("Supported kernel switches:\n"
315 "systemd.unit=UNIT Default unit to start\n"
316 "systemd.log_target=console|kmsg|syslog| Log target\n"
317 " syslog-org-kmsg|null\n"
318 "systemd.log_level=LEVEL Log level\n"
319 "systemd.log_color=0|1 Highlight important log messages\n"
320 "systemd.log_location=0|1 Include code location in log messages\n"
321 "systemd.dump_core=0|1 Dump core on crash\n"
322 "systemd.crash_shell=0|1 Run shell on crash\n"
323 "systemd.crash_chvt=N Change to VT #N on crash\n"
324 "systemd.confirm_spawn=0|1 Confirm every process spawn\n"
325 "systemd.show_status=0|1 Show status updates on the console during bootup\n");
326
327 } else if (streq(word, "nomodules"))
328 arg_nomodules = true;
329 else if (streq(word, "quiet")) {
330 if (!ignore_quiet)
331 arg_show_status = false;
332 } else {
333 unsigned i;
334
335 /* SysV compatibility */
336 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
337 if (streq(word, rlmap[i]))
338 return set_default_unit(rlmap[i+1]);
339 }
340
341 return 0;
342 }
343
344 static int config_parse_level(
345 const char *filename,
346 unsigned line,
347 const char *section,
348 const char *lvalue,
349 const char *rvalue,
350 void *data,
351 void *userdata) {
352
353 assert(filename);
354 assert(lvalue);
355 assert(rvalue);
356
357 log_set_max_level_from_string(rvalue);
358 return 0;
359 }
360
361 static int config_parse_target(
362 const char *filename,
363 unsigned line,
364 const char *section,
365 const char *lvalue,
366 const char *rvalue,
367 void *data,
368 void *userdata) {
369
370 assert(filename);
371 assert(lvalue);
372 assert(rvalue);
373
374 log_set_target_from_string(rvalue);
375 return 0;
376 }
377
378 static int config_parse_color(
379 const char *filename,
380 unsigned line,
381 const char *section,
382 const char *lvalue,
383 const char *rvalue,
384 void *data,
385 void *userdata) {
386
387 assert(filename);
388 assert(lvalue);
389 assert(rvalue);
390
391 log_show_color_from_string(rvalue);
392 return 0;
393 }
394
395 static int config_parse_location(
396 const char *filename,
397 unsigned line,
398 const char *section,
399 const char *lvalue,
400 const char *rvalue,
401 void *data,
402 void *userdata) {
403
404 assert(filename);
405 assert(lvalue);
406 assert(rvalue);
407
408 log_show_location_from_string(rvalue);
409 return 0;
410 }
411
412 static int config_parse_cpu_affinity(
413 const char *filename,
414 unsigned line,
415 const char *section,
416 const char *lvalue,
417 const char *rvalue,
418 void *data,
419 void *userdata) {
420
421 char *w;
422 size_t l;
423 char *state;
424 cpu_set_t *c = NULL;
425 unsigned ncpus = 0;
426
427 assert(filename);
428 assert(lvalue);
429 assert(rvalue);
430
431 FOREACH_WORD_QUOTED(w, l, rvalue, state) {
432 char *t;
433 int r;
434 unsigned cpu;
435
436 if (!(t = strndup(w, l)))
437 return -ENOMEM;
438
439 r = safe_atou(t, &cpu);
440 free(t);
441
442 if (!c)
443 if (!(c = cpu_set_malloc(&ncpus)))
444 return -ENOMEM;
445
446 if (r < 0 || cpu >= ncpus) {
447 log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
448 CPU_FREE(c);
449 return -EBADMSG;
450 }
451
452 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
453 }
454
455 if (c) {
456 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
457 log_warning("Failed to set CPU affinity: %m");
458
459 CPU_FREE(c);
460 }
461
462 return 0;
463 }
464
465 static int parse_config_file(void) {
466
467 const ConfigItem items[] = {
468 { "LogLevel", config_parse_level, NULL, "Manager" },
469 { "LogTarget", config_parse_target, NULL, "Manager" },
470 { "LogColor", config_parse_color, NULL, "Manager" },
471 { "LogLocation", config_parse_location, NULL, "Manager" },
472 { "DumpCore", config_parse_bool, &arg_dump_core, "Manager" },
473 { "CrashShell", config_parse_bool, &arg_crash_shell, "Manager" },
474 { "ShowStatus", config_parse_bool, &arg_show_status, "Manager" },
475 { "CrashChVT", config_parse_int, &arg_crash_chvt, "Manager" },
476 { "CPUAffinity", config_parse_cpu_affinity, NULL, "Manager" },
477 { NULL, NULL, NULL, NULL }
478 };
479
480 static const char * const sections[] = {
481 "Manager",
482 NULL
483 };
484
485 FILE *f;
486 const char *fn;
487 int r;
488
489 fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : SESSION_CONFIG_FILE;
490
491 if (!(f = fopen(fn, "re"))) {
492 if (errno == ENOENT)
493 return 0;
494
495 log_warning("Failed to open configuration file '%s': %m", fn);
496 return 0;
497 }
498
499 if ((r = config_parse(fn, f, sections, items, false, NULL)) < 0)
500 log_warning("Failed to parse configuration file: %s", strerror(-r));
501
502 fclose(f);
503
504 return 0;
505 }
506
507 static int parse_proc_cmdline(void) {
508 char *line;
509 int r;
510 char *w;
511 size_t l;
512 char *state;
513
514 if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
515 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(errno));
516 return 0;
517 }
518
519 FOREACH_WORD_QUOTED(w, l, line, state) {
520 char *word;
521
522 if (!(word = strndup(w, l))) {
523 r = -ENOMEM;
524 goto finish;
525 }
526
527 r = parse_proc_cmdline_word(word);
528 free(word);
529
530 if (r < 0)
531 goto finish;
532 }
533
534 r = 0;
535
536 finish:
537 free(line);
538 return r;
539 }
540
541 static int parse_argv(int argc, char *argv[]) {
542
543 enum {
544 ARG_LOG_LEVEL = 0x100,
545 ARG_LOG_TARGET,
546 ARG_LOG_COLOR,
547 ARG_LOG_LOCATION,
548 ARG_UNIT,
549 ARG_SYSTEM,
550 ARG_SESSION,
551 ARG_TEST,
552 ARG_DUMP_CONFIGURATION_ITEMS,
553 ARG_DUMP_CORE,
554 ARG_CRASH_SHELL,
555 ARG_CONFIRM_SPAWN,
556 ARG_SHOW_STATUS,
557 ARG_DESERIALIZE,
558 ARG_INTROSPECT
559 };
560
561 static const struct option options[] = {
562 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
563 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
564 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
565 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
566 { "unit", required_argument, NULL, ARG_UNIT },
567 { "system", no_argument, NULL, ARG_SYSTEM },
568 { "session", no_argument, NULL, ARG_SESSION },
569 { "test", no_argument, NULL, ARG_TEST },
570 { "help", no_argument, NULL, 'h' },
571 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
572 { "dump-core", no_argument, NULL, ARG_DUMP_CORE },
573 { "crash-shell", no_argument, NULL, ARG_CRASH_SHELL },
574 { "confirm-spawn", no_argument, NULL, ARG_CONFIRM_SPAWN },
575 { "show-status", no_argument, NULL, ARG_SHOW_STATUS },
576 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
577 { "introspect", optional_argument, NULL, ARG_INTROSPECT },
578 { NULL, 0, NULL, 0 }
579 };
580
581 int c, r;
582
583 assert(argc >= 1);
584 assert(argv);
585
586 while ((c = getopt_long(argc, argv, "hD", options, NULL)) >= 0)
587
588 switch (c) {
589
590 case ARG_LOG_LEVEL:
591 if ((r = log_set_max_level_from_string(optarg)) < 0) {
592 log_error("Failed to parse log level %s.", optarg);
593 return r;
594 }
595
596 break;
597
598 case ARG_LOG_TARGET:
599
600 if ((r = log_set_target_from_string(optarg)) < 0) {
601 log_error("Failed to parse log target %s.", optarg);
602 return r;
603 }
604
605 break;
606
607 case ARG_LOG_COLOR:
608
609 if (optarg) {
610 if ((r = log_show_color_from_string(optarg)) < 0) {
611 log_error("Failed to parse log color setting %s.", optarg);
612 return r;
613 }
614 } else
615 log_show_color(true);
616
617 break;
618
619 case ARG_LOG_LOCATION:
620
621 if (optarg) {
622 if ((r = log_show_location_from_string(optarg)) < 0) {
623 log_error("Failed to parse log location setting %s.", optarg);
624 return r;
625 }
626 } else
627 log_show_location(true);
628
629 break;
630
631 case ARG_UNIT:
632
633 if ((r = set_default_unit(optarg)) < 0) {
634 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
635 return r;
636 }
637
638 break;
639
640 case ARG_SYSTEM:
641 arg_running_as = MANAGER_SYSTEM;
642 break;
643
644 case ARG_SESSION:
645 arg_running_as = MANAGER_SESSION;
646 break;
647
648 case ARG_TEST:
649 arg_action = ACTION_TEST;
650 break;
651
652 case ARG_DUMP_CONFIGURATION_ITEMS:
653 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
654 break;
655
656 case ARG_DUMP_CORE:
657 arg_dump_core = true;
658 break;
659
660 case ARG_CRASH_SHELL:
661 arg_crash_shell = true;
662 break;
663
664 case ARG_CONFIRM_SPAWN:
665 arg_confirm_spawn = true;
666 break;
667
668 case ARG_SHOW_STATUS:
669 arg_show_status = true;
670 break;
671
672 case ARG_DESERIALIZE: {
673 int fd;
674 FILE *f;
675
676 if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
677 log_error("Failed to parse deserialize option %s.", optarg);
678 return r;
679 }
680
681 if (!(f = fdopen(fd, "r"))) {
682 log_error("Failed to open serialization fd: %m");
683 return r;
684 }
685
686 if (serialization)
687 fclose(serialization);
688
689 serialization = f;
690
691 break;
692 }
693
694 case ARG_INTROSPECT: {
695 const char * const * i = NULL;
696
697 for (i = bus_interface_table; *i; i += 2)
698 if (!optarg || streq(i[0], optarg)) {
699 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
700 "<node>\n", stdout);
701 fputs(i[1], stdout);
702 fputs("</node>\n", stdout);
703
704 if (optarg)
705 break;
706 }
707
708 if (!i[0] && optarg)
709 log_error("Unknown interface %s.", optarg);
710
711 arg_action = ACTION_DONE;
712 break;
713 }
714
715 case 'h':
716 arg_action = ACTION_HELP;
717 break;
718
719 case 'D':
720 log_set_max_level(LOG_DEBUG);
721 break;
722
723 case '?':
724 return -EINVAL;
725
726 default:
727 log_error("Unknown option code %c", c);
728 return -EINVAL;
729 }
730
731 /* PID 1 will get the kernel arguments as parameters, which we
732 * ignore and unconditionally read from
733 * /proc/cmdline. However, we need to ignore those arguments
734 * here. */
735 if (arg_running_as != MANAGER_SYSTEM && optind < argc) {
736 log_error("Excess arguments.");
737 return -EINVAL;
738 }
739
740 return 0;
741 }
742
743 static int help(void) {
744
745 printf("%s [OPTIONS...]\n\n"
746 "Starts up and maintains the system or a session.\n\n"
747 " -h --help Show this help\n"
748 " --test Determine startup sequence, dump it and exit\n"
749 " --dump-configuration-items Dump understood unit configuration items\n"
750 " --introspect[=INTERFACE] Extract D-Bus interface data\n"
751 " --unit=UNIT Set default unit\n"
752 " --system Run a system instance, even if PID != 1\n"
753 " --session Run a session instance\n"
754 " --dump-core Dump core on crash\n"
755 " --crash-shell Run shell on crash\n"
756 " --confirm-spawn Ask for confirmation when spawning processes\n"
757 " --show-status Show status updates on the console during bootup\n"
758 " --log-target=TARGET Set log target (console, syslog, kmsg, syslog-or-kmsg, null)\n"
759 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
760 " --log-color[=0|1] Highlight important log messages\n"
761 " --log-location[=0|1] Include code location in log messages\n",
762 program_invocation_short_name);
763
764 return 0;
765 }
766
767 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
768 FILE *f = NULL;
769 FDSet *fds = NULL;
770 int r;
771
772 assert(m);
773 assert(_f);
774 assert(_fds);
775
776 if ((r = manager_open_serialization(m, &f)) < 0) {
777 log_error("Failed to create serialization faile: %s", strerror(-r));
778 goto fail;
779 }
780
781 if (!(fds = fdset_new())) {
782 r = -ENOMEM;
783 log_error("Failed to allocate fd set: %s", strerror(-r));
784 goto fail;
785 }
786
787 if ((r = manager_serialize(m, f, fds)) < 0) {
788 log_error("Failed to serialize state: %s", strerror(-r));
789 goto fail;
790 }
791
792 if (fseeko(f, 0, SEEK_SET) < 0) {
793 log_error("Failed to rewind serialization fd: %m");
794 goto fail;
795 }
796
797 if ((r = fd_cloexec(fileno(f), false)) < 0) {
798 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
799 goto fail;
800 }
801
802 if ((r = fdset_cloexec(fds, false)) < 0) {
803 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
804 goto fail;
805 }
806
807 *_f = f;
808 *_fds = fds;
809
810 return 0;
811
812 fail:
813 fdset_free(fds);
814
815 if (f)
816 fclose(f);
817
818 return r;
819 }
820
821 int main(int argc, char *argv[]) {
822 Manager *m = NULL;
823 Unit *target = NULL;
824 Job *job = NULL;
825 int r, retval = 1;
826 FDSet *fds = NULL;
827 bool reexecute = false;
828
829 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
830 /* This is compatbility support for SysV, where
831 * calling init as a user is identical to telinit. */
832
833 errno = -ENOENT;
834 execv(SYSTEMCTL_BINARY_PATH, argv);
835 log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
836 return 1;
837 }
838
839 if (label_init() < 0)
840 goto finish;
841
842 log_show_color(isatty(STDERR_FILENO) > 0);
843 log_show_location(false);
844 log_set_max_level(LOG_INFO);
845
846 if (getpid() == 1) {
847 arg_running_as = MANAGER_SYSTEM;
848 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
849 } else {
850 arg_running_as = MANAGER_SESSION;
851 log_set_target(LOG_TARGET_CONSOLE);
852 }
853
854 if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
855 goto finish;
856
857 /* Mount /proc, /sys and friends, so that /proc/cmdline and
858 * /proc/$PID/fd is available. */
859 if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS"))
860 if (mount_setup() < 0)
861 goto finish;
862
863 /* Reset all signal handlers. */
864 assert_se(reset_all_signal_handlers() == 0);
865
866 /* If we are init, we can block sigkill. Yay. */
867 ignore_signals(SIGNALS_IGNORE, -1);
868
869 if (parse_config_file() < 0)
870 goto finish;
871
872 if (arg_running_as == MANAGER_SYSTEM)
873 if (parse_proc_cmdline() < 0)
874 goto finish;
875
876 log_parse_environment();
877
878 if (parse_argv(argc, argv) < 0)
879 goto finish;
880
881 if (arg_action == ACTION_HELP) {
882 retval = help();
883 goto finish;
884 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
885 unit_dump_config_items(stdout);
886 retval = 0;
887 goto finish;
888 } else if (arg_action == ACTION_DONE) {
889 retval = 0;
890 goto finish;
891 }
892
893 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
894
895 /* Remember open file descriptors for later deserialization */
896 if (serialization) {
897 if ((r = fdset_new_fill(&fds)) < 0) {
898 log_error("Failed to allocate fd set: %s", strerror(-r));
899 goto finish;
900 }
901
902 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
903 } else
904 close_all_fds(NULL, 0);
905
906 /* Set up PATH unless it is already set */
907 setenv("PATH",
908 "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
909 arg_running_as == MANAGER_SYSTEM);
910
911 /* Move out of the way, so that we won't block unmounts */
912 assert_se(chdir("/") == 0);
913
914 if (arg_running_as == MANAGER_SYSTEM) {
915 /* Become a session leader if we aren't one yet. */
916 setsid();
917
918 /* Disable the umask logic */
919 umask(0);
920 }
921
922 /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
923 dbus_connection_set_change_sigpipe(FALSE);
924
925 /* Reset the console, but only if this is really init and we
926 * are freshly booted */
927 if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
928 console_setup(getpid() == 1 && !serialization);
929 make_null_stdio();
930 }
931
932 /* Open the logging devices, if possible and necessary */
933 log_open();
934
935 /* Make sure we leave a core dump without panicing the
936 * kernel. */
937 if (getpid() == 1)
938 install_crash_handler();
939
940 log_info(PACKAGE_STRING " running in %s mode.", manager_running_as_to_string(arg_running_as));
941
942 if (arg_running_as == MANAGER_SYSTEM) {
943
944 /* Disable nscd, to avoid deadlocks when systemd uses
945 * NSS and the nscd socket is maintained by us. */
946 /* if (nss_disable_nscd) { */
947 /* log_debug("Disabling nscd"); */
948 /* nss_disable_nscd(); */
949 /* } else */
950 /* log_debug("Hmm, can't disable nscd."); */
951
952 if (!serialization) {
953 if (arg_show_status)
954 status_welcome();
955 modprobe_setup(arg_nomodules);
956 kmod_setup();
957 hostname_setup();
958 loopback_setup();
959 }
960 }
961
962 if ((r = manager_new(arg_running_as, &m)) < 0) {
963 log_error("Failed to allocate manager object: %s", strerror(-r));
964 goto finish;
965 }
966
967 m->confirm_spawn = arg_confirm_spawn;
968 m->show_status = arg_show_status;
969
970 if ((r = manager_startup(m, serialization, fds)) < 0)
971 log_error("Failed to fully start up daemon: %s", strerror(-r));
972
973 if (fds) {
974 /* This will close all file descriptors that were opened, but
975 * not claimed by any unit. */
976
977 fdset_free(fds);
978 fds = NULL;
979 }
980
981 if (serialization) {
982 fclose(serialization);
983 serialization = NULL;
984 } else {
985 DBusError error;
986
987 dbus_error_init(&error);
988
989 log_debug("Activating default unit: %s", arg_default_unit);
990
991 if ((r = manager_load_unit(m, arg_default_unit, NULL, &error, &target)) < 0) {
992 log_error("Failed to load default target: %s", bus_error(&error, r));
993 dbus_error_free(&error);
994
995 log_info("Trying to load rescue target...");
996 if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target)) < 0) {
997 log_error("Failed to load rescue target: %s", bus_error(&error, r));
998 dbus_error_free(&error);
999 goto finish;
1000 }
1001 }
1002
1003 if (arg_action == ACTION_TEST) {
1004 printf("-> By units:\n");
1005 manager_dump_units(m, stdout, "\t");
1006 }
1007
1008 if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, &job)) < 0) {
1009 log_error("Failed to start default target: %s", bus_error(&error, r));
1010 dbus_error_free(&error);
1011 goto finish;
1012 }
1013
1014 if (arg_action == ACTION_TEST) {
1015 printf("-> By jobs:\n");
1016 manager_dump_jobs(m, stdout, "\t");
1017 retval = 0;
1018 goto finish;
1019 }
1020 }
1021
1022 for (;;) {
1023 if ((r = manager_loop(m)) < 0) {
1024 log_error("Failed to run mainloop: %s", strerror(-r));
1025 goto finish;
1026 }
1027
1028 switch (m->exit_code) {
1029
1030 case MANAGER_EXIT:
1031 retval = 0;
1032 log_debug("Exit.");
1033 goto finish;
1034
1035 case MANAGER_RELOAD:
1036 log_info("Reloading.");
1037 if ((r = manager_reload(m)) < 0)
1038 log_error("Failed to reload: %s", strerror(-r));
1039 break;
1040
1041 case MANAGER_REEXECUTE:
1042 if (prepare_reexecute(m, &serialization, &fds) < 0)
1043 goto finish;
1044
1045 reexecute = true;
1046 log_notice("Reexecuting.");
1047 goto finish;
1048
1049 default:
1050 assert_not_reached("Unknown exit code.");
1051 }
1052 }
1053
1054 finish:
1055 if (m)
1056 manager_free(m);
1057
1058 free(arg_default_unit);
1059
1060 dbus_shutdown();
1061
1062 if (reexecute) {
1063 const char *args[14];
1064 unsigned i = 0;
1065 char sfd[16];
1066
1067 assert(serialization);
1068 assert(fds);
1069
1070 args[i++] = SYSTEMD_BINARY_PATH;
1071
1072 args[i++] = "--log-level";
1073 args[i++] = log_level_to_string(log_get_max_level());
1074
1075 args[i++] = "--log-target";
1076 args[i++] = log_target_to_string(log_get_target());
1077
1078 if (arg_running_as == MANAGER_SYSTEM)
1079 args[i++] = "--system";
1080 else
1081 args[i++] = "--session";
1082
1083 if (arg_dump_core)
1084 args[i++] = "--dump-core";
1085
1086 if (arg_crash_shell)
1087 args[i++] = "--crash-shell";
1088
1089 if (arg_confirm_spawn)
1090 args[i++] = "--confirm-spawn";
1091
1092 if (arg_show_status)
1093 args[i++] = "--show-status";
1094
1095 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
1096 char_array_0(sfd);
1097
1098 args[i++] = "--deserialize";
1099 args[i++] = sfd;
1100
1101 args[i++] = NULL;
1102
1103 assert(i <= ELEMENTSOF(args));
1104
1105 execv(args[0], (char* const*) args);
1106
1107 log_error("Failed to reexecute: %m");
1108 }
1109
1110 if (serialization)
1111 fclose(serialization);
1112
1113 if (fds)
1114 fdset_free(fds);
1115
1116 if (getpid() == 1)
1117 freeze();
1118
1119 label_finish();
1120
1121 return retval;
1122 }