chiark / gitweb /
main: don't force text mode in console_setup()
[elogind.git] / src / main.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 #include <sys/prctl.h>
35
36 #include "manager.h"
37 #include "log.h"
38 #include "mount-setup.h"
39 #include "hostname-setup.h"
40 #include "loopback-setup.h"
41 #include "kmod-setup.h"
42 #include "locale-setup.h"
43 #include "selinux-setup.h"
44 #include "machine-id-setup.h"
45 #include "load-fragment.h"
46 #include "fdset.h"
47 #include "special.h"
48 #include "conf-parser.h"
49 #include "bus-errors.h"
50 #include "missing.h"
51 #include "label.h"
52 #include "build.h"
53 #include "strv.h"
54 #include "def.h"
55 #include "virt.h"
56
57 static enum {
58         ACTION_RUN,
59         ACTION_HELP,
60         ACTION_TEST,
61         ACTION_DUMP_CONFIGURATION_ITEMS,
62         ACTION_DONE
63 } arg_action = ACTION_RUN;
64
65 static char *arg_default_unit = NULL;
66 static ManagerRunningAs arg_running_as = _MANAGER_RUNNING_AS_INVALID;
67
68 static bool arg_dump_core = true;
69 static bool arg_crash_shell = false;
70 static int arg_crash_chvt = -1;
71 static bool arg_confirm_spawn = false;
72 static bool arg_show_status = true;
73 #ifdef HAVE_SYSV_COMPAT
74 static bool arg_sysv_console = true;
75 #endif
76 static bool arg_mount_auto = true;
77 static bool arg_swap_auto = true;
78 static char **arg_default_controllers = NULL;
79 static char ***arg_join_controllers = NULL;
80 static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
81 static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
82
83 static FILE* serialization = NULL;
84
85 static void nop_handler(int sig) {
86 }
87
88 _noreturn_ static void crash(int sig) {
89
90         if (!arg_dump_core)
91                 log_error("Caught <%s>, not dumping core.", signal_to_string(sig));
92         else {
93                 struct sigaction sa;
94                 pid_t pid;
95
96                 /* We want to wait for the core process, hence let's enable SIGCHLD */
97                 zero(sa);
98                 sa.sa_handler = nop_handler;
99                 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
100                 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
101
102                 if ((pid = fork()) < 0)
103                         log_error("Caught <%s>, cannot fork for core dump: %s", signal_to_string(sig), strerror(errno));
104
105                 else if (pid == 0) {
106                         struct rlimit rl;
107
108                         /* Enable default signal handler for core dump */
109                         zero(sa);
110                         sa.sa_handler = SIG_DFL;
111                         assert_se(sigaction(sig, &sa, NULL) == 0);
112
113                         /* Don't limit the core dump size */
114                         zero(rl);
115                         rl.rlim_cur = RLIM_INFINITY;
116                         rl.rlim_max = RLIM_INFINITY;
117                         setrlimit(RLIMIT_CORE, &rl);
118
119                         /* Just to be sure... */
120                         assert_se(chdir("/") == 0);
121
122                         /* Raise the signal again */
123                         raise(sig);
124
125                         assert_not_reached("We shouldn't be here...");
126                         _exit(1);
127
128                 } else {
129                         siginfo_t status;
130                         int r;
131
132                         /* Order things nicely. */
133                         if ((r = wait_for_terminate(pid, &status)) < 0)
134                                 log_error("Caught <%s>, waitpid() failed: %s", signal_to_string(sig), strerror(-r));
135                         else if (status.si_code != CLD_DUMPED)
136                                 log_error("Caught <%s>, core dump failed.", signal_to_string(sig));
137                         else
138                                 log_error("Caught <%s>, dumped core as pid %lu.", signal_to_string(sig), (unsigned long) pid);
139                 }
140         }
141
142         if (arg_crash_chvt)
143                 chvt(arg_crash_chvt);
144
145         if (arg_crash_shell) {
146                 struct sigaction sa;
147                 pid_t pid;
148
149                 log_info("Executing crash shell in 10s...");
150                 sleep(10);
151
152                 /* Let the kernel reap children for us */
153                 zero(sa);
154                 sa.sa_handler = SIG_IGN;
155                 sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART;
156                 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
157
158                 if ((pid = fork()) < 0)
159                         log_error("Failed to fork off crash shell: %s", strerror(errno));
160                 else if (pid == 0) {
161                         int fd, r;
162
163                         if ((fd = acquire_terminal("/dev/console", false, true, true)) < 0)
164                                 log_error("Failed to acquire terminal: %s", strerror(-fd));
165                         else if ((r = make_stdio(fd)) < 0)
166                                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
167
168                         execl("/bin/sh", "/bin/sh", NULL);
169
170                         log_error("execl() failed: %s", strerror(errno));
171                         _exit(1);
172                 }
173
174                 log_info("Successfully spawned crash shell as pid %lu.", (unsigned long) pid);
175         }
176
177         log_info("Freezing execution.");
178         freeze();
179 }
180
181 static void install_crash_handler(void) {
182         struct sigaction sa;
183
184         zero(sa);
185
186         sa.sa_handler = crash;
187         sa.sa_flags = SA_NODEFER;
188
189         sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
190 }
191
192 static int console_setup(bool do_reset) {
193         int tty_fd, r;
194
195         /* If we are init, we connect stdin/stdout/stderr to /dev/null
196          * and make sure we don't have a controlling tty. */
197
198         release_terminal();
199
200         if (!do_reset)
201                 return 0;
202
203         tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
204         if (tty_fd < 0) {
205                 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
206                 return -tty_fd;
207         }
208
209         /* We don't want to force text mode.
210          * plymouth may be showing pictures already from initrd. */
211         r = reset_terminal_fd(tty_fd, false);
212         if (r < 0)
213                 log_error("Failed to reset /dev/console: %s", strerror(-r));
214
215         close_nointr_nofail(tty_fd);
216         return r;
217 }
218
219 static int set_default_unit(const char *u) {
220         char *c;
221
222         assert(u);
223
224         if (!(c = strdup(u)))
225                 return -ENOMEM;
226
227         free(arg_default_unit);
228         arg_default_unit = c;
229         return 0;
230 }
231
232 static int parse_proc_cmdline_word(const char *word) {
233
234         static const char * const rlmap[] = {
235                 "emergency", SPECIAL_EMERGENCY_TARGET,
236                 "-b",        SPECIAL_EMERGENCY_TARGET,
237                 "single",    SPECIAL_RESCUE_TARGET,
238                 "-s",        SPECIAL_RESCUE_TARGET,
239                 "s",         SPECIAL_RESCUE_TARGET,
240                 "S",         SPECIAL_RESCUE_TARGET,
241                 "1",         SPECIAL_RESCUE_TARGET,
242                 "2",         SPECIAL_RUNLEVEL2_TARGET,
243                 "3",         SPECIAL_RUNLEVEL3_TARGET,
244                 "4",         SPECIAL_RUNLEVEL4_TARGET,
245                 "5",         SPECIAL_RUNLEVEL5_TARGET,
246         };
247
248         assert(word);
249
250         if (startswith(word, "systemd.unit="))
251                 return set_default_unit(word + 13);
252
253         else if (startswith(word, "systemd.log_target=")) {
254
255                 if (log_set_target_from_string(word + 19) < 0)
256                         log_warning("Failed to parse log target %s. Ignoring.", word + 19);
257
258         } else if (startswith(word, "systemd.log_level=")) {
259
260                 if (log_set_max_level_from_string(word + 18) < 0)
261                         log_warning("Failed to parse log level %s. Ignoring.", word + 18);
262
263         } else if (startswith(word, "systemd.log_color=")) {
264
265                 if (log_show_color_from_string(word + 18) < 0)
266                         log_warning("Failed to parse log color setting %s. Ignoring.", word + 18);
267
268         } else if (startswith(word, "systemd.log_location=")) {
269
270                 if (log_show_location_from_string(word + 21) < 0)
271                         log_warning("Failed to parse log location setting %s. Ignoring.", word + 21);
272
273         } else if (startswith(word, "systemd.dump_core=")) {
274                 int r;
275
276                 if ((r = parse_boolean(word + 18)) < 0)
277                         log_warning("Failed to parse dump core switch %s. Ignoring.", word + 18);
278                 else
279                         arg_dump_core = r;
280
281         } else if (startswith(word, "systemd.crash_shell=")) {
282                 int r;
283
284                 if ((r = parse_boolean(word + 20)) < 0)
285                         log_warning("Failed to parse crash shell switch %s. Ignoring.", word + 20);
286                 else
287                         arg_crash_shell = r;
288
289         } else if (startswith(word, "systemd.confirm_spawn=")) {
290                 int r;
291
292                 if ((r = parse_boolean(word + 22)) < 0)
293                         log_warning("Failed to parse confirm spawn switch %s. Ignoring.", word + 22);
294                 else
295                         arg_confirm_spawn = r;
296
297         } else if (startswith(word, "systemd.crash_chvt=")) {
298                 int k;
299
300                 if (safe_atoi(word + 19, &k) < 0)
301                         log_warning("Failed to parse crash chvt switch %s. Ignoring.", word + 19);
302                 else
303                         arg_crash_chvt = k;
304
305         } else if (startswith(word, "systemd.show_status=")) {
306                 int r;
307
308                 if ((r = parse_boolean(word + 20)) < 0)
309                         log_warning("Failed to parse show status switch %s. Ignoring.", word + 20);
310                 else
311                         arg_show_status = r;
312         } else if (startswith(word, "systemd.default_standard_output=")) {
313                 int r;
314
315                 if ((r = exec_output_from_string(word + 32)) < 0)
316                         log_warning("Failed to parse default standard output switch %s. Ignoring.", word + 32);
317                 else
318                         arg_default_std_output = r;
319         } else if (startswith(word, "systemd.default_standard_error=")) {
320                 int r;
321
322                 if ((r = exec_output_from_string(word + 31)) < 0)
323                         log_warning("Failed to parse default standard error switch %s. Ignoring.", word + 31);
324                 else
325                         arg_default_std_error = r;
326 #ifdef HAVE_SYSV_COMPAT
327         } else if (startswith(word, "systemd.sysv_console=")) {
328                 int r;
329
330                 if ((r = parse_boolean(word + 21)) < 0)
331                         log_warning("Failed to parse SysV console switch %s. Ignoring.", word + 20);
332                 else
333                         arg_sysv_console = r;
334 #endif
335
336         } else if (startswith(word, "systemd.")) {
337
338                 log_warning("Unknown kernel switch %s. Ignoring.", word);
339
340                 log_info("Supported kernel switches:\n"
341                          "systemd.unit=UNIT                        Default unit to start\n"
342                          "systemd.dump_core=0|1                    Dump core on crash\n"
343                          "systemd.crash_shell=0|1                  Run shell on crash\n"
344                          "systemd.crash_chvt=N                     Change to VT #N on crash\n"
345                          "systemd.confirm_spawn=0|1                Confirm every process spawn\n"
346                          "systemd.show_status=0|1                  Show status updates on the console during bootup\n"
347 #ifdef HAVE_SYSV_COMPAT
348                          "systemd.sysv_console=0|1                 Connect output of SysV scripts to console\n"
349 #endif
350                          "systemd.log_target=console|kmsg|journal|journal-or-kmsg|syslog|syslog-or-kmsg|null\n"
351                          "                                         Log target\n"
352                          "systemd.log_level=LEVEL                  Log level\n"
353                          "systemd.log_color=0|1                    Highlight important log messages\n"
354                          "systemd.log_location=0|1                 Include code location in log messages\n"
355                          "systemd.default_standard_output=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
356                          "                                         Set default log output for services\n"
357                          "systemd.default_standard_error=null|tty|syslog|syslog+console|kmsg|kmsg+console|journal|journal+console\n"
358                          "                                         Set default log error output for services\n");
359
360         } else if (streq(word, "quiet")) {
361                 arg_show_status = false;
362 #ifdef HAVE_SYSV_COMPAT
363                 arg_sysv_console = false;
364 #endif
365         } else {
366                 unsigned i;
367
368                 /* SysV compatibility */
369                 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
370                         if (streq(word, rlmap[i]))
371                                 return set_default_unit(rlmap[i+1]);
372         }
373
374         return 0;
375 }
376
377 static int config_parse_level2(
378                 const char *filename,
379                 unsigned line,
380                 const char *section,
381                 const char *lvalue,
382                 int ltype,
383                 const char *rvalue,
384                 void *data,
385                 void *userdata) {
386
387         assert(filename);
388         assert(lvalue);
389         assert(rvalue);
390
391         log_set_max_level_from_string(rvalue);
392         return 0;
393 }
394
395 static int config_parse_target(
396                 const char *filename,
397                 unsigned line,
398                 const char *section,
399                 const char *lvalue,
400                 int ltype,
401                 const char *rvalue,
402                 void *data,
403                 void *userdata) {
404
405         assert(filename);
406         assert(lvalue);
407         assert(rvalue);
408
409         log_set_target_from_string(rvalue);
410         return 0;
411 }
412
413 static int config_parse_color(
414                 const char *filename,
415                 unsigned line,
416                 const char *section,
417                 const char *lvalue,
418                 int ltype,
419                 const char *rvalue,
420                 void *data,
421                 void *userdata) {
422
423         assert(filename);
424         assert(lvalue);
425         assert(rvalue);
426
427         log_show_color_from_string(rvalue);
428         return 0;
429 }
430
431 static int config_parse_location(
432                 const char *filename,
433                 unsigned line,
434                 const char *section,
435                 const char *lvalue,
436                 int ltype,
437                 const char *rvalue,
438                 void *data,
439                 void *userdata) {
440
441         assert(filename);
442         assert(lvalue);
443         assert(rvalue);
444
445         log_show_location_from_string(rvalue);
446         return 0;
447 }
448
449 static int config_parse_cpu_affinity2(
450                 const char *filename,
451                 unsigned line,
452                 const char *section,
453                 const char *lvalue,
454                 int ltype,
455                 const char *rvalue,
456                 void *data,
457                 void *userdata) {
458
459         char *w;
460         size_t l;
461         char *state;
462         cpu_set_t *c = NULL;
463         unsigned ncpus = 0;
464
465         assert(filename);
466         assert(lvalue);
467         assert(rvalue);
468
469         FOREACH_WORD_QUOTED(w, l, rvalue, state) {
470                 char *t;
471                 int r;
472                 unsigned cpu;
473
474                 if (!(t = strndup(w, l)))
475                         return -ENOMEM;
476
477                 r = safe_atou(t, &cpu);
478                 free(t);
479
480                 if (!c)
481                         if (!(c = cpu_set_malloc(&ncpus)))
482                                 return -ENOMEM;
483
484                 if (r < 0 || cpu >= ncpus) {
485                         log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
486                         CPU_FREE(c);
487                         return -EBADMSG;
488                 }
489
490                 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
491         }
492
493         if (c) {
494                 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
495                         log_warning("Failed to set CPU affinity: %m");
496
497                 CPU_FREE(c);
498         }
499
500         return 0;
501 }
502
503 static void strv_free_free(char ***l) {
504         char ***i;
505
506         if (!l)
507                 return;
508
509         for (i = l; *i; i++)
510                 strv_free(*i);
511
512         free(l);
513 }
514
515 static void free_join_controllers(void) {
516         if (!arg_join_controllers)
517                 return;
518
519         strv_free_free(arg_join_controllers);
520         arg_join_controllers = NULL;
521 }
522
523 static int config_parse_join_controllers(
524                 const char *filename,
525                 unsigned line,
526                 const char *section,
527                 const char *lvalue,
528                 int ltype,
529                 const char *rvalue,
530                 void *data,
531                 void *userdata) {
532
533         unsigned n = 0;
534         char *state, *w;
535         size_t length;
536
537         assert(filename);
538         assert(lvalue);
539         assert(rvalue);
540
541         free_join_controllers();
542
543         FOREACH_WORD_QUOTED(w, length, rvalue, state) {
544                 char *s, **l;
545
546                 s = strndup(w, length);
547                 if (!s)
548                         return -ENOMEM;
549
550                 l = strv_split(s, ",");
551                 free(s);
552
553                 strv_uniq(l);
554
555                 if (strv_length(l) <= 1) {
556                         strv_free(l);
557                         continue;
558                 }
559
560                 if (!arg_join_controllers) {
561                         arg_join_controllers = new(char**, 2);
562                         if (!arg_join_controllers) {
563                                 strv_free(l);
564                                 return -ENOMEM;
565                         }
566
567                         arg_join_controllers[0] = l;
568                         arg_join_controllers[1] = NULL;
569
570                         n = 1;
571                 } else {
572                         char ***a;
573                         char ***t;
574
575                         t = new0(char**, n+2);
576                         if (!t) {
577                                 strv_free(l);
578                                 return -ENOMEM;
579                         }
580
581                         n = 0;
582
583                         for (a = arg_join_controllers; *a; a++) {
584
585                                 if (strv_overlap(*a, l)) {
586                                         char **c;
587
588                                         c = strv_merge(*a, l);
589                                         if (!c) {
590                                                 strv_free(l);
591                                                 strv_free_free(t);
592                                                 return -ENOMEM;
593                                         }
594
595                                         strv_free(l);
596                                         l = c;
597                                 } else {
598                                         char **c;
599
600                                         c = strv_copy(*a);
601                                         if (!c) {
602                                                 strv_free(l);
603                                                 strv_free_free(t);
604                                                 return -ENOMEM;
605                                         }
606
607                                         t[n++] = c;
608                                 }
609                         }
610
611                         t[n++] = strv_uniq(l);
612
613                         strv_free_free(arg_join_controllers);
614                         arg_join_controllers = t;
615                 }
616         }
617
618         return 0;
619 }
620
621 static int parse_config_file(void) {
622
623         const ConfigTableItem items[] = {
624                 { "Manager", "LogLevel",              config_parse_level2,       0, NULL                     },
625                 { "Manager", "LogTarget",             config_parse_target,       0, NULL                     },
626                 { "Manager", "LogColor",              config_parse_color,        0, NULL                     },
627                 { "Manager", "LogLocation",           config_parse_location,     0, NULL                     },
628                 { "Manager", "DumpCore",              config_parse_bool,         0, &arg_dump_core           },
629                 { "Manager", "CrashShell",            config_parse_bool,         0, &arg_crash_shell         },
630                 { "Manager", "ShowStatus",            config_parse_bool,         0, &arg_show_status         },
631 #ifdef HAVE_SYSV_COMPAT
632                 { "Manager", "SysVConsole",           config_parse_bool,         0, &arg_sysv_console        },
633 #endif
634                 { "Manager", "CrashChVT",             config_parse_int,          0, &arg_crash_chvt          },
635                 { "Manager", "CPUAffinity",           config_parse_cpu_affinity2, 0, NULL                    },
636                 { "Manager", "MountAuto",             config_parse_bool,         0, &arg_mount_auto          },
637                 { "Manager", "SwapAuto",              config_parse_bool,         0, &arg_swap_auto           },
638                 { "Manager", "DefaultControllers",    config_parse_strv,         0, &arg_default_controllers },
639                 { "Manager", "DefaultStandardOutput", config_parse_output,       0, &arg_default_std_output  },
640                 { "Manager", "DefaultStandardError",  config_parse_output,       0, &arg_default_std_error   },
641                 { "Manager", "JoinControllers",       config_parse_join_controllers, 0, &arg_join_controllers },
642                 { NULL, NULL, NULL, 0, NULL }
643         };
644
645         FILE *f;
646         const char *fn;
647         int r;
648
649         fn = arg_running_as == MANAGER_SYSTEM ? SYSTEM_CONFIG_FILE : USER_CONFIG_FILE;
650         f = fopen(fn, "re");
651         if (!f) {
652                 if (errno == ENOENT)
653                         return 0;
654
655                 log_warning("Failed to open configuration file '%s': %m", fn);
656                 return 0;
657         }
658
659         r = config_parse(fn, f, "Manager\0", config_item_table_lookup, (void*) items, false, NULL);
660         if (r < 0)
661                 log_warning("Failed to parse configuration file: %s", strerror(-r));
662
663         fclose(f);
664
665         return 0;
666 }
667
668 static int parse_proc_cmdline(void) {
669         char *line, *w, *state;
670         int r;
671         size_t l;
672
673         /* Don't read /proc/cmdline if we are in a container, since
674          * that is only relevant for the host system */
675         if (detect_container(NULL) > 0)
676                 return 0;
677
678         if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
679                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(-r));
680                 return 0;
681         }
682
683         FOREACH_WORD_QUOTED(w, l, line, state) {
684                 char *word;
685
686                 if (!(word = strndup(w, l))) {
687                         r = -ENOMEM;
688                         goto finish;
689                 }
690
691                 r = parse_proc_cmdline_word(word);
692                 free(word);
693
694                 if (r < 0)
695                         goto finish;
696         }
697
698         r = 0;
699
700 finish:
701         free(line);
702         return r;
703 }
704
705 static int parse_argv(int argc, char *argv[]) {
706
707         enum {
708                 ARG_LOG_LEVEL = 0x100,
709                 ARG_LOG_TARGET,
710                 ARG_LOG_COLOR,
711                 ARG_LOG_LOCATION,
712                 ARG_UNIT,
713                 ARG_SYSTEM,
714                 ARG_USER,
715                 ARG_TEST,
716                 ARG_DUMP_CONFIGURATION_ITEMS,
717                 ARG_DUMP_CORE,
718                 ARG_CRASH_SHELL,
719                 ARG_CONFIRM_SPAWN,
720                 ARG_SHOW_STATUS,
721                 ARG_SYSV_CONSOLE,
722                 ARG_DESERIALIZE,
723                 ARG_INTROSPECT,
724                 ARG_DEFAULT_STD_OUTPUT,
725                 ARG_DEFAULT_STD_ERROR
726         };
727
728         static const struct option options[] = {
729                 { "log-level",                required_argument, NULL, ARG_LOG_LEVEL                },
730                 { "log-target",               required_argument, NULL, ARG_LOG_TARGET               },
731                 { "log-color",                optional_argument, NULL, ARG_LOG_COLOR                },
732                 { "log-location",             optional_argument, NULL, ARG_LOG_LOCATION             },
733                 { "unit",                     required_argument, NULL, ARG_UNIT                     },
734                 { "system",                   no_argument,       NULL, ARG_SYSTEM                   },
735                 { "user",                     no_argument,       NULL, ARG_USER                     },
736                 { "test",                     no_argument,       NULL, ARG_TEST                     },
737                 { "help",                     no_argument,       NULL, 'h'                          },
738                 { "dump-configuration-items", no_argument,       NULL, ARG_DUMP_CONFIGURATION_ITEMS },
739                 { "dump-core",                no_argument,       NULL, ARG_DUMP_CORE                },
740                 { "crash-shell",              no_argument,       NULL, ARG_CRASH_SHELL              },
741                 { "confirm-spawn",            no_argument,       NULL, ARG_CONFIRM_SPAWN            },
742                 { "show-status",              optional_argument, NULL, ARG_SHOW_STATUS              },
743 #ifdef HAVE_SYSV_COMPAT
744                 { "sysv-console",             optional_argument, NULL, ARG_SYSV_CONSOLE             },
745 #endif
746                 { "deserialize",              required_argument, NULL, ARG_DESERIALIZE              },
747                 { "introspect",               optional_argument, NULL, ARG_INTROSPECT               },
748                 { "default-standard-output",  required_argument, NULL, ARG_DEFAULT_STD_OUTPUT,      },
749                 { "default-standard-error",   required_argument, NULL, ARG_DEFAULT_STD_ERROR,       },
750                 { NULL,                       0,                 NULL, 0                            }
751         };
752
753         int c, r;
754
755         assert(argc >= 1);
756         assert(argv);
757
758         if (getpid() == 1)
759                 opterr = 0;
760
761         while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
762
763                 switch (c) {
764
765                 case ARG_LOG_LEVEL:
766                         if ((r = log_set_max_level_from_string(optarg)) < 0) {
767                                 log_error("Failed to parse log level %s.", optarg);
768                                 return r;
769                         }
770
771                         break;
772
773                 case ARG_LOG_TARGET:
774
775                         if ((r = log_set_target_from_string(optarg)) < 0) {
776                                 log_error("Failed to parse log target %s.", optarg);
777                                 return r;
778                         }
779
780                         break;
781
782                 case ARG_LOG_COLOR:
783
784                         if (optarg) {
785                                 if ((r = log_show_color_from_string(optarg)) < 0) {
786                                         log_error("Failed to parse log color setting %s.", optarg);
787                                         return r;
788                                 }
789                         } else
790                                 log_show_color(true);
791
792                         break;
793
794                 case ARG_LOG_LOCATION:
795
796                         if (optarg) {
797                                 if ((r = log_show_location_from_string(optarg)) < 0) {
798                                         log_error("Failed to parse log location setting %s.", optarg);
799                                         return r;
800                                 }
801                         } else
802                                 log_show_location(true);
803
804                         break;
805
806                 case ARG_DEFAULT_STD_OUTPUT:
807
808                         if ((r = exec_output_from_string(optarg)) < 0) {
809                                 log_error("Failed to parse default standard output setting %s.", optarg);
810                                 return r;
811                         } else
812                                 arg_default_std_output = r;
813                         break;
814
815                 case ARG_DEFAULT_STD_ERROR:
816
817                         if ((r = exec_output_from_string(optarg)) < 0) {
818                                 log_error("Failed to parse default standard error output setting %s.", optarg);
819                                 return r;
820                         } else
821                                 arg_default_std_error = r;
822                         break;
823
824                 case ARG_UNIT:
825
826                         if ((r = set_default_unit(optarg)) < 0) {
827                                 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
828                                 return r;
829                         }
830
831                         break;
832
833                 case ARG_SYSTEM:
834                         arg_running_as = MANAGER_SYSTEM;
835                         break;
836
837                 case ARG_USER:
838                         arg_running_as = MANAGER_USER;
839                         break;
840
841                 case ARG_TEST:
842                         arg_action = ACTION_TEST;
843                         break;
844
845                 case ARG_DUMP_CONFIGURATION_ITEMS:
846                         arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
847                         break;
848
849                 case ARG_DUMP_CORE:
850                         arg_dump_core = true;
851                         break;
852
853                 case ARG_CRASH_SHELL:
854                         arg_crash_shell = true;
855                         break;
856
857                 case ARG_CONFIRM_SPAWN:
858                         arg_confirm_spawn = true;
859                         break;
860
861                 case ARG_SHOW_STATUS:
862
863                         if (optarg) {
864                                 if ((r = parse_boolean(optarg)) < 0) {
865                                         log_error("Failed to show status boolean %s.", optarg);
866                                         return r;
867                                 }
868                                 arg_show_status = r;
869                         } else
870                                 arg_show_status = true;
871                         break;
872 #ifdef HAVE_SYSV_COMPAT
873                 case ARG_SYSV_CONSOLE:
874
875                         if (optarg) {
876                                 if ((r = parse_boolean(optarg)) < 0) {
877                                         log_error("Failed to SysV console boolean %s.", optarg);
878                                         return r;
879                                 }
880                                 arg_sysv_console = r;
881                         } else
882                                 arg_sysv_console = true;
883                         break;
884 #endif
885
886                 case ARG_DESERIALIZE: {
887                         int fd;
888                         FILE *f;
889
890                         if ((r = safe_atoi(optarg, &fd)) < 0 || fd < 0) {
891                                 log_error("Failed to parse deserialize option %s.", optarg);
892                                 return r;
893                         }
894
895                         if (!(f = fdopen(fd, "r"))) {
896                                 log_error("Failed to open serialization fd: %m");
897                                 return r;
898                         }
899
900                         if (serialization)
901                                 fclose(serialization);
902
903                         serialization = f;
904
905                         break;
906                 }
907
908                 case ARG_INTROSPECT: {
909                         const char * const * i = NULL;
910
911                         for (i = bus_interface_table; *i; i += 2)
912                                 if (!optarg || streq(i[0], optarg)) {
913                                         fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
914                                               "<node>\n", stdout);
915                                         fputs(i[1], stdout);
916                                         fputs("</node>\n", stdout);
917
918                                         if (optarg)
919                                                 break;
920                                 }
921
922                         if (!i[0] && optarg)
923                                 log_error("Unknown interface %s.", optarg);
924
925                         arg_action = ACTION_DONE;
926                         break;
927                 }
928
929                 case 'h':
930                         arg_action = ACTION_HELP;
931                         break;
932
933                 case 'D':
934                         log_set_max_level(LOG_DEBUG);
935                         break;
936
937                 case 'b':
938                 case 's':
939                 case 'z':
940                         /* Just to eat away the sysvinit kernel
941                          * cmdline args without getopt() error
942                          * messages that we'll parse in
943                          * parse_proc_cmdline_word() or ignore. */
944
945                 case '?':
946                 default:
947                         if (getpid() != 1) {
948                                 log_error("Unknown option code %c", c);
949                                 return -EINVAL;
950                         }
951
952                         break;
953                 }
954
955         if (optind < argc && getpid() != 1) {
956                 /* Hmm, when we aren't run as init system
957                  * let's complain about excess arguments */
958
959                 log_error("Excess arguments.");
960                 return -EINVAL;
961         }
962
963         if (detect_container(NULL) > 0) {
964                 char **a;
965
966                 /* All /proc/cmdline arguments the kernel didn't
967                  * understand it passed to us. We're not really
968                  * interested in that usually since /proc/cmdline is
969                  * more interesting and complete. With one exception:
970                  * if we are run in a container /proc/cmdline is not
971                  * relevant for the container, hence we rely on argv[]
972                  * instead. */
973
974                 for (a = argv; a < argv + argc; a++)
975                         if ((r = parse_proc_cmdline_word(*a)) < 0)
976                                 return r;
977         }
978
979         return 0;
980 }
981
982 static int help(void) {
983
984         printf("%s [OPTIONS...]\n\n"
985                "Starts up and maintains the system or user services.\n\n"
986                "  -h --help                      Show this help\n"
987                "     --test                      Determine startup sequence, dump it and exit\n"
988                "     --dump-configuration-items  Dump understood unit configuration items\n"
989                "     --introspect[=INTERFACE]    Extract D-Bus interface data\n"
990                "     --unit=UNIT                 Set default unit\n"
991                "     --system                    Run a system instance, even if PID != 1\n"
992                "     --user                      Run a user instance\n"
993                "     --dump-core                 Dump core on crash\n"
994                "     --crash-shell               Run shell on crash\n"
995                "     --confirm-spawn             Ask for confirmation when spawning processes\n"
996                "     --show-status[=0|1]         Show status updates on the console during bootup\n"
997 #ifdef HAVE_SYSV_COMPAT
998                "     --sysv-console[=0|1]        Connect output of SysV scripts to console\n"
999 #endif
1000                "     --log-target=TARGET         Set log target (console, journal, syslog, kmsg, journal-or-kmsg, syslog-or-kmsg, null)\n"
1001                "     --log-level=LEVEL           Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
1002                "     --log-color[=0|1]           Highlight important log messages\n"
1003                "     --log-location[=0|1]        Include code location in log messages\n"
1004                "     --default-standard-output=  Set default standard output for services\n"
1005                "     --default-standard-error=   Set default standard error output for services\n",
1006                program_invocation_short_name);
1007
1008         return 0;
1009 }
1010
1011 static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds) {
1012         FILE *f = NULL;
1013         FDSet *fds = NULL;
1014         int r;
1015
1016         assert(m);
1017         assert(_f);
1018         assert(_fds);
1019
1020         /* Make sure nothing is really destructed when we shut down */
1021         m->n_reloading ++;
1022
1023         if ((r = manager_open_serialization(m, &f)) < 0) {
1024                 log_error("Failed to create serialization file: %s", strerror(-r));
1025                 goto fail;
1026         }
1027
1028         if (!(fds = fdset_new())) {
1029                 r = -ENOMEM;
1030                 log_error("Failed to allocate fd set: %s", strerror(-r));
1031                 goto fail;
1032         }
1033
1034         if ((r = manager_serialize(m, f, fds)) < 0) {
1035                 log_error("Failed to serialize state: %s", strerror(-r));
1036                 goto fail;
1037         }
1038
1039         if (fseeko(f, 0, SEEK_SET) < 0) {
1040                 log_error("Failed to rewind serialization fd: %m");
1041                 goto fail;
1042         }
1043
1044         if ((r = fd_cloexec(fileno(f), false)) < 0) {
1045                 log_error("Failed to disable O_CLOEXEC for serialization: %s", strerror(-r));
1046                 goto fail;
1047         }
1048
1049         if ((r = fdset_cloexec(fds, false)) < 0) {
1050                 log_error("Failed to disable O_CLOEXEC for serialization fds: %s", strerror(-r));
1051                 goto fail;
1052         }
1053
1054         *_f = f;
1055         *_fds = fds;
1056
1057         return 0;
1058
1059 fail:
1060         fdset_free(fds);
1061
1062         if (f)
1063                 fclose(f);
1064
1065         return r;
1066 }
1067
1068 static struct dual_timestamp* parse_initrd_timestamp(struct dual_timestamp *t) {
1069         const char *e;
1070         unsigned long long a, b;
1071
1072         assert(t);
1073
1074         if (!(e = getenv("RD_TIMESTAMP")))
1075                 return NULL;
1076
1077         if (sscanf(e, "%llu %llu", &a, &b) != 2)
1078                 return NULL;
1079
1080         t->realtime = (usec_t) a;
1081         t->monotonic = (usec_t) b;
1082
1083         return t;
1084 }
1085
1086 static void test_mtab(void) {
1087         char *p;
1088
1089         /* Check that /etc/mtab is a symlink */
1090
1091         if (readlink_malloc("/etc/mtab", &p) >= 0) {
1092                 bool b;
1093
1094                 b = streq(p, "/proc/self/mounts") || streq(p, "/proc/mounts");
1095                 free(p);
1096
1097                 if (b)
1098                         return;
1099         }
1100
1101         log_warning("/etc/mtab is not a symlink or not pointing to /proc/self/mounts. "
1102                     "This is not supported anymore. "
1103                     "Please make sure to replace this file by a symlink to avoid incorrect or misleading mount(8) output.");
1104 }
1105
1106 static void test_usr(void) {
1107
1108         /* Check that /usr is not a separate fs */
1109
1110         if (dir_is_empty("/usr") <= 0)
1111                 return;
1112
1113         log_warning("/usr appears to be on its own filesytem and is not already mounted. This is not a supported setup. "
1114                     "Some things will probably break (sometimes even silently) in mysterious ways. "
1115                     "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1116 }
1117
1118 static void test_cgroups(void) {
1119
1120         if (access("/proc/cgroups", F_OK) >= 0)
1121                 return;
1122
1123         log_warning("CONFIG_CGROUPS was not set when your kernel was compiled. "
1124                     "Systems without control groups are not supported. "
1125                     "We will now sleep for 10s, and then continue boot-up. "
1126                     "Expect breakage and please do not file bugs. "
1127                     "Instead fix your kernel and enable CONFIG_CGROUPS." );
1128
1129         sleep(10);
1130 }
1131
1132 int main(int argc, char *argv[]) {
1133         Manager *m = NULL;
1134         int r, retval = EXIT_FAILURE;
1135         usec_t before_startup, after_startup;
1136         char timespan[FORMAT_TIMESPAN_MAX];
1137         FDSet *fds = NULL;
1138         bool reexecute = false;
1139         const char *shutdown_verb = NULL;
1140         dual_timestamp initrd_timestamp = { 0ULL, 0ULL };
1141         char systemd[] = "systemd";
1142         bool is_reexec = false;
1143         int j;
1144         bool loaded_policy = false;
1145
1146 #ifdef HAVE_SYSV_COMPAT
1147         if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
1148                 /* This is compatibility support for SysV, where
1149                  * calling init as a user is identical to telinit. */
1150
1151                 errno = -ENOENT;
1152                 execv(SYSTEMCTL_BINARY_PATH, argv);
1153                 log_error("Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
1154                 return 1;
1155         }
1156 #endif
1157
1158         /* Determine if this is a reexecution or normal bootup. We do
1159          * the full command line parsing much later, so let's just
1160          * have a quick peek here. */
1161
1162         for (j = 1; j < argc; j++)
1163                 if (streq(argv[j], "--deserialize")) {
1164                         is_reexec = true;
1165                         break;
1166                 }
1167
1168         /* If we get started via the /sbin/init symlink then we are
1169            called 'init'. After a subsequent reexecution we are then
1170            called 'systemd'. That is confusing, hence let's call us
1171            systemd right-away. */
1172
1173         program_invocation_short_name = systemd;
1174         prctl(PR_SET_NAME, systemd);
1175         saved_argv = argv;
1176         saved_argc = argc;
1177
1178         log_show_color(isatty(STDERR_FILENO) > 0);
1179         log_show_location(false);
1180         log_set_max_level(LOG_INFO);
1181
1182         if (getpid() == 1) {
1183                 arg_running_as = MANAGER_SYSTEM;
1184                 log_set_target(detect_container(NULL) > 0 ? LOG_TARGET_CONSOLE : LOG_TARGET_JOURNAL_OR_KMSG);
1185
1186                 if (!is_reexec)
1187                         if (selinux_setup(&loaded_policy) < 0)
1188                                 goto finish;
1189
1190                 log_open();
1191
1192                 if (label_init() < 0)
1193                         goto finish;
1194
1195                 if (!is_reexec)
1196                         if (hwclock_is_localtime() > 0) {
1197                                 int min;
1198
1199                                 r = hwclock_apply_localtime_delta(&min);
1200                                 if (r < 0)
1201                                         log_error("Failed to apply local time delta, ignoring: %s", strerror(-r));
1202                                 else
1203                                         log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1204                         }
1205
1206         } else {
1207                 arg_running_as = MANAGER_USER;
1208                 log_set_target(LOG_TARGET_AUTO);
1209                 log_open();
1210         }
1211
1212         /* Initialize default unit */
1213         if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
1214                 goto finish;
1215
1216         /* By default, mount "cpu" and "cpuacct" together */
1217         arg_join_controllers = new(char**, 2);
1218         if (!arg_join_controllers)
1219                 goto finish;
1220
1221         arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
1222         arg_join_controllers[1] = NULL;
1223
1224         if (!arg_join_controllers[0])
1225                 goto finish;
1226
1227         /* Mount /proc, /sys and friends, so that /proc/cmdline and
1228          * /proc/$PID/fd is available. */
1229         if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1230                 r = mount_setup(loaded_policy);
1231                 if (r < 0)
1232                         goto finish;
1233         }
1234
1235         /* Reset all signal handlers. */
1236         assert_se(reset_all_signal_handlers() == 0);
1237
1238         /* If we are init, we can block sigkill. Yay. */
1239         ignore_signals(SIGNALS_IGNORE, -1);
1240
1241         if (parse_config_file() < 0)
1242                 goto finish;
1243
1244         if (arg_running_as == MANAGER_SYSTEM)
1245                 if (parse_proc_cmdline() < 0)
1246                         goto finish;
1247
1248         log_parse_environment();
1249
1250         if (parse_argv(argc, argv) < 0)
1251                 goto finish;
1252
1253         if (arg_action == ACTION_TEST && geteuid() == 0) {
1254                 log_error("Don't run test mode as root.");
1255                 goto finish;
1256         }
1257
1258         if (arg_running_as == MANAGER_SYSTEM &&
1259             arg_action == ACTION_RUN &&
1260             running_in_chroot() > 0) {
1261                 log_error("Cannot be run in a chroot() environment.");
1262                 goto finish;
1263         }
1264
1265         if (arg_action == ACTION_HELP) {
1266                 retval = help();
1267                 goto finish;
1268         } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
1269                 unit_dump_config_items(stdout);
1270                 retval = EXIT_SUCCESS;
1271                 goto finish;
1272         } else if (arg_action == ACTION_DONE) {
1273                 retval = EXIT_SUCCESS;
1274                 goto finish;
1275         }
1276
1277         assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
1278
1279         /* Close logging fds, in order not to confuse fdset below */
1280         log_close();
1281
1282         /* Remember open file descriptors for later deserialization */
1283         if (serialization) {
1284                 if ((r = fdset_new_fill(&fds)) < 0) {
1285                         log_error("Failed to allocate fd set: %s", strerror(-r));
1286                         goto finish;
1287                 }
1288
1289                 assert_se(fdset_remove(fds, fileno(serialization)) >= 0);
1290         } else
1291                 close_all_fds(NULL, 0);
1292
1293         /* Set up PATH unless it is already set */
1294         setenv("PATH",
1295                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1296                arg_running_as == MANAGER_SYSTEM);
1297
1298         if (arg_running_as == MANAGER_SYSTEM) {
1299                 /* Parse the data passed to us by the initrd and unset it */
1300                 parse_initrd_timestamp(&initrd_timestamp);
1301                 filter_environ("RD_");
1302
1303                 /* Unset some environment variables passed in from the
1304                  * kernel that don't really make sense for us. */
1305                 unsetenv("HOME");
1306                 unsetenv("TERM");
1307
1308                 /* All other variables are left as is, so that clients
1309                  * can still read them via /proc/1/environ */
1310         }
1311
1312         /* Move out of the way, so that we won't block unmounts */
1313         assert_se(chdir("/")  == 0);
1314
1315         if (arg_running_as == MANAGER_SYSTEM) {
1316                 /* Become a session leader if we aren't one yet. */
1317                 setsid();
1318
1319                 /* Disable the umask logic */
1320                 umask(0);
1321         }
1322
1323         /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
1324         dbus_connection_set_change_sigpipe(FALSE);
1325
1326         /* Reset the console, but only if this is really init and we
1327          * are freshly booted */
1328         if (arg_running_as == MANAGER_SYSTEM && arg_action == ACTION_RUN) {
1329                 console_setup(getpid() == 1 && !is_reexec);
1330                 make_null_stdio();
1331         }
1332
1333         /* Open the logging devices, if possible and necessary */
1334         log_open();
1335
1336         /* Make sure we leave a core dump without panicing the
1337          * kernel. */
1338         if (getpid() == 1)
1339                 install_crash_handler();
1340
1341         if (geteuid() == 0 && !getenv("SYSTEMD_SKIP_API_MOUNTS")) {
1342                 r = mount_cgroup_controllers(arg_join_controllers);
1343                 if (r < 0)
1344                         goto finish;
1345         }
1346
1347         log_full(arg_running_as == MANAGER_SYSTEM ? LOG_INFO : LOG_DEBUG,
1348                  PACKAGE_STRING " running in %s mode. (" SYSTEMD_FEATURES "; " DISTRIBUTION ")", manager_running_as_to_string(arg_running_as));
1349
1350         if (arg_running_as == MANAGER_SYSTEM && !is_reexec) {
1351                 locale_setup();
1352
1353                 if (arg_show_status || plymouth_running())
1354                         status_welcome();
1355
1356                 kmod_setup();
1357                 hostname_setup();
1358                 machine_id_setup();
1359                 loopback_setup();
1360
1361                 test_mtab();
1362                 test_usr();
1363                 test_cgroups();
1364         }
1365
1366         if ((r = manager_new(arg_running_as, &m)) < 0) {
1367                 log_error("Failed to allocate manager object: %s", strerror(-r));
1368                 goto finish;
1369         }
1370
1371         m->confirm_spawn = arg_confirm_spawn;
1372 #ifdef HAVE_SYSV_COMPAT
1373         m->sysv_console = arg_sysv_console;
1374 #endif
1375         m->mount_auto = arg_mount_auto;
1376         m->swap_auto = arg_swap_auto;
1377         m->default_std_output = arg_default_std_output;
1378         m->default_std_error = arg_default_std_error;
1379
1380         if (dual_timestamp_is_set(&initrd_timestamp))
1381                 m->initrd_timestamp = initrd_timestamp;
1382
1383         if (arg_default_controllers)
1384                 manager_set_default_controllers(m, arg_default_controllers);
1385
1386         manager_set_show_status(m, arg_show_status);
1387
1388         before_startup = now(CLOCK_MONOTONIC);
1389
1390         if ((r = manager_startup(m, serialization, fds)) < 0)
1391                 log_error("Failed to fully start up daemon: %s", strerror(-r));
1392
1393         if (fds) {
1394                 /* This will close all file descriptors that were opened, but
1395                  * not claimed by any unit. */
1396
1397                 fdset_free(fds);
1398                 fds = NULL;
1399         }
1400
1401         if (serialization) {
1402                 fclose(serialization);
1403                 serialization = NULL;
1404         } else {
1405                 DBusError error;
1406                 Unit *target = NULL;
1407
1408                 dbus_error_init(&error);
1409
1410                 log_debug("Activating default unit: %s", arg_default_unit);
1411
1412                 if ((r = manager_load_unit(m, arg_default_unit, NULL, &error, &target)) < 0) {
1413                         log_error("Failed to load default target: %s", bus_error(&error, r));
1414                         dbus_error_free(&error);
1415                 } else if (target->load_state == UNIT_ERROR)
1416                         log_error("Failed to load default target: %s", strerror(-target->load_error));
1417                 else if (target->load_state == UNIT_MASKED)
1418                         log_error("Default target masked.");
1419
1420                 if (!target || target->load_state != UNIT_LOADED) {
1421                         log_info("Trying to load rescue target...");
1422
1423                         if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target)) < 0) {
1424                                 log_error("Failed to load rescue target: %s", bus_error(&error, r));
1425                                 dbus_error_free(&error);
1426                                 goto finish;
1427                         } else if (target->load_state == UNIT_ERROR) {
1428                                 log_error("Failed to load rescue target: %s", strerror(-target->load_error));
1429                                 goto finish;
1430                         } else if (target->load_state == UNIT_MASKED) {
1431                                 log_error("Rescue target masked.");
1432                                 goto finish;
1433                         }
1434                 }
1435
1436                 assert(target->load_state == UNIT_LOADED);
1437
1438                 if (arg_action == ACTION_TEST) {
1439                         printf("-> By units:\n");
1440                         manager_dump_units(m, stdout, "\t");
1441                 }
1442
1443                 if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &error, NULL)) < 0) {
1444                         log_error("Failed to start default target: %s", bus_error(&error, r));
1445                         dbus_error_free(&error);
1446                         goto finish;
1447                 }
1448
1449                 after_startup = now(CLOCK_MONOTONIC);
1450                 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1451                          "Loaded units and determined initial transaction in %s.",
1452                           format_timespan(timespan, sizeof(timespan), after_startup - before_startup));
1453
1454                 if (arg_action == ACTION_TEST) {
1455                         printf("-> By jobs:\n");
1456                         manager_dump_jobs(m, stdout, "\t");
1457                         retval = EXIT_SUCCESS;
1458                         goto finish;
1459                 }
1460         }
1461
1462         for (;;) {
1463                 if ((r = manager_loop(m)) < 0) {
1464                         log_error("Failed to run mainloop: %s", strerror(-r));
1465                         goto finish;
1466                 }
1467
1468                 switch (m->exit_code) {
1469
1470                 case MANAGER_EXIT:
1471                         retval = EXIT_SUCCESS;
1472                         log_debug("Exit.");
1473                         goto finish;
1474
1475                 case MANAGER_RELOAD:
1476                         log_info("Reloading.");
1477                         if ((r = manager_reload(m)) < 0)
1478                                 log_error("Failed to reload: %s", strerror(-r));
1479                         break;
1480
1481                 case MANAGER_REEXECUTE:
1482                         if (prepare_reexecute(m, &serialization, &fds) < 0)
1483                                 goto finish;
1484
1485                         reexecute = true;
1486                         log_notice("Reexecuting.");
1487                         goto finish;
1488
1489                 case MANAGER_REBOOT:
1490                 case MANAGER_POWEROFF:
1491                 case MANAGER_HALT:
1492                 case MANAGER_KEXEC: {
1493                         static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
1494                                 [MANAGER_REBOOT] = "reboot",
1495                                 [MANAGER_POWEROFF] = "poweroff",
1496                                 [MANAGER_HALT] = "halt",
1497                                 [MANAGER_KEXEC] = "kexec"
1498                         };
1499
1500                         assert_se(shutdown_verb = table[m->exit_code]);
1501
1502                         log_notice("Shutting down.");
1503                         goto finish;
1504                 }
1505
1506                 default:
1507                         assert_not_reached("Unknown exit code.");
1508                 }
1509         }
1510
1511 finish:
1512         if (m)
1513                 manager_free(m);
1514
1515         free(arg_default_unit);
1516         strv_free(arg_default_controllers);
1517         free_join_controllers();
1518
1519         dbus_shutdown();
1520
1521         label_finish();
1522
1523         if (reexecute) {
1524                 const char *args[15];
1525                 unsigned i = 0;
1526                 char sfd[16];
1527
1528                 assert(serialization);
1529                 assert(fds);
1530
1531                 args[i++] = SYSTEMD_BINARY_PATH;
1532
1533                 args[i++] = "--log-level";
1534                 args[i++] = log_level_to_string(log_get_max_level());
1535
1536                 args[i++] = "--log-target";
1537                 args[i++] = log_target_to_string(log_get_target());
1538
1539                 if (arg_running_as == MANAGER_SYSTEM)
1540                         args[i++] = "--system";
1541                 else
1542                         args[i++] = "--user";
1543
1544                 if (arg_dump_core)
1545                         args[i++] = "--dump-core";
1546
1547                 if (arg_crash_shell)
1548                         args[i++] = "--crash-shell";
1549
1550                 if (arg_confirm_spawn)
1551                         args[i++] = "--confirm-spawn";
1552
1553                 if (arg_show_status)
1554                         args[i++] = "--show-status=1";
1555                 else
1556                         args[i++] = "--show-status=0";
1557
1558 #ifdef HAVE_SYSV_COMPAT
1559                 if (arg_sysv_console)
1560                         args[i++] = "--sysv-console=1";
1561                 else
1562                         args[i++] = "--sysv-console=0";
1563 #endif
1564
1565                 snprintf(sfd, sizeof(sfd), "%i", fileno(serialization));
1566                 char_array_0(sfd);
1567
1568                 args[i++] = "--deserialize";
1569                 args[i++] = sfd;
1570
1571                 args[i++] = NULL;
1572
1573                 assert(i <= ELEMENTSOF(args));
1574
1575                 execv(args[0], (char* const*) args);
1576
1577                 log_error("Failed to reexecute: %m");
1578         }
1579
1580         if (serialization)
1581                 fclose(serialization);
1582
1583         if (fds)
1584                 fdset_free(fds);
1585
1586         if (shutdown_verb) {
1587                 const char * command_line[] = {
1588                         SYSTEMD_SHUTDOWN_BINARY_PATH,
1589                         shutdown_verb,
1590                         NULL
1591                 };
1592
1593                 execv(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line);
1594                 log_error("Failed to execute shutdown binary, freezing: %m");
1595         }
1596
1597         if (getpid() == 1)
1598                 freeze();
1599
1600         return retval;
1601 }