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