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