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