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