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