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