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