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