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