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