chiark / gitweb /
main: add kernel option to enable confirm_spawn
[elogind.git] / main.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 "load-fragment.h"
40
41 static enum {
42         ACTION_RUN,
43         ACTION_HELP,
44         ACTION_TEST,
45         ACTION_DUMP_CONFIGURATION_ITEMS
46 } action = ACTION_RUN;
47
48 static char *default_unit = NULL;
49 static ManagerRunningAs running_as = _MANAGER_RUNNING_AS_INVALID;
50
51 static bool dump_core = true;
52 static bool crash_shell = false;
53 static int crash_chvt = -1;
54
55 static bool confirm_spawn = false;
56
57 _noreturn static void freeze(void) {
58         for (;;)
59                 pause();
60 }
61
62 _noreturn static void crash(int sig) {
63
64         if (!dump_core)
65                 log_error("Caught <%s>, not dumping core.", strsignal(sig));
66         else {
67                 pid_t pid;
68
69                 if ((pid = fork()) < 0)
70                         log_error("Caught <%s>, cannot fork for core dump: %s", strsignal(sig), strerror(errno));
71
72                 else if (pid == 0) {
73                         struct sigaction sa;
74                         struct rlimit rl;
75
76                         /* Enable default signal handler for core dump */
77                         zero(sa);
78                         sa.sa_handler = SIG_DFL;
79                         assert_se(sigaction(sig, &sa, NULL) == 0);
80
81                         /* Don't limit the core dump size */
82                         zero(rl);
83                         rl.rlim_cur = RLIM_INFINITY;
84                         rl.rlim_max = RLIM_INFINITY;
85                         setrlimit(RLIMIT_CORE, &rl);
86
87                         /* Just to be sure... */
88                         assert_se(chdir("/") == 0);
89
90                         /* Raise the signal again */
91                         raise(sig);
92
93                         assert_not_reached("We shouldn't be here...");
94                         _exit(1);
95
96                 } else {
97                         int status, r;
98
99                         /* Order things nicely. */
100                         if ((r = waitpid(pid, &status, 0)) < 0)
101                                 log_error("Caught <%s>, waitpid() failed: %s", strsignal(sig), strerror(errno));
102                         else if (!WCOREDUMP(status))
103                                 log_error("Caught <%s>, core dump failed.", strsignal(sig));
104                         else
105                                 log_error("Caught <%s>, dumped core as pid %llu.", strsignal(sig), (unsigned long long) pid);
106                 }
107         }
108
109         if (crash_chvt)
110                 chvt(crash_chvt);
111
112         if (crash_shell) {
113                 sigset_t mask;
114
115                 log_info("Executing crash shell in 10s...");
116                 sleep(10);
117
118                 /* Make sure the signal is not delivered inside the
119                  * exec() */
120                 assert_se(sigemptyset(&mask) == 0);
121                 assert_se(sigaddset(&mask, sig) == 0);
122                 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
123
124                 ignore_signal(sig);
125
126                 execl("/bin/sh", "/bin/sh", NULL);
127                 log_error("execl() failed: %s", strerror(errno));
128         }
129
130         log_info("Freezing execution.");
131         freeze();
132 }
133
134 static void install_crash_handler(void) {
135         struct sigaction sa;
136
137         zero(sa);
138
139         sa.sa_handler = crash;
140         sa.sa_flags = SA_NODEFER;
141
142         assert_se(sigaction(SIGSEGV, &sa, NULL) == 0);
143         assert_se(sigaction(SIGILL, &sa, NULL) == 0);
144         assert_se(sigaction(SIGFPE, &sa, NULL) == 0);
145         assert_se(sigaction(SIGBUS, &sa, NULL) == 0);
146         assert_se(sigaction(SIGQUIT, &sa, NULL) == 0);
147         assert_se(sigaction(SIGABRT, &sa, NULL) == 0);
148 }
149
150 static int console_setup(void) {
151         int tty_fd = -1, null_fd = -1, r = 0;
152
153         /* If we are init, we connect stdout/stderr to /dev/console
154          * and stdin to /dev/null and make sure we don't have a
155          * controlling tty. */
156
157         release_terminal();
158
159         if ((tty_fd = open_terminal("/dev/console", O_WRONLY)) < 0) {
160                 log_error("Failed to open /dev/console: %s", strerror(-tty_fd));
161                 r = -tty_fd;
162                 goto finish;
163         }
164
165         if ((null_fd = open("/dev/null", O_RDONLY)) < 0) {
166                 log_error("Failed to open /dev/null: %m");
167                 r = -errno;
168                 goto finish;
169         }
170
171         assert(tty_fd >= 3);
172         assert(null_fd >= 3);
173
174         if (reset_terminal(tty_fd) < 0)
175                 log_error("Failed to reset /dev/console: %m");
176
177         if (dup2(tty_fd, STDOUT_FILENO) < 0 ||
178             dup2(tty_fd, STDERR_FILENO) < 0 ||
179             dup2(null_fd, STDIN_FILENO) < 0) {
180                 log_error("Failed to dup2() device: %m");
181                 r = -errno;
182                 goto finish;
183         }
184
185         r = 0;
186
187 finish:
188         if (tty_fd >= 0)
189                 close_nointr(tty_fd);
190
191         if (null_fd >= 0)
192                 close_nointr(null_fd);
193
194         return r;
195 }
196
197 static int set_default_unit(const char *u) {
198         char *c;
199
200         assert(u);
201
202         if (!(c = strdup(u)))
203                 return -ENOMEM;
204
205         free(default_unit);
206         default_unit = c;
207         return 0;
208 }
209
210 static int parse_proc_cmdline_word(const char *word) {
211
212         static const char * const rlmap[] = {
213                 "single", SPECIAL_RUNLEVEL1_TARGET,
214                 "-s",     SPECIAL_RUNLEVEL1_TARGET,
215                 "s",      SPECIAL_RUNLEVEL1_TARGET,
216                 "S",      SPECIAL_RUNLEVEL1_TARGET,
217                 "1",      SPECIAL_RUNLEVEL1_TARGET,
218                 "2",      SPECIAL_RUNLEVEL2_TARGET,
219                 "3",      SPECIAL_RUNLEVEL3_TARGET,
220                 "4",      SPECIAL_RUNLEVEL4_TARGET,
221                 "5",      SPECIAL_RUNLEVEL5_TARGET
222         };
223
224         if (startswith(word, "systemd.default="))
225                 return set_default_unit(word + 16);
226
227         else if (startswith(word, "systemd.log_target=")) {
228
229                 if (log_set_target_from_string(word + 19) < 0)
230                         log_warning("Failed to parse log target %s. Ignoring.", word + 19);
231
232         } else if (startswith(word, "systemd.log_level=")) {
233
234                 if (log_set_max_level_from_string(word + 18) < 0)
235                         log_warning("Failed to parse log level %s. Ignoring.", word + 18);
236
237         } else if (startswith(word, "systemd.dump_core=")) {
238                 int r;
239
240                 if ((r = parse_boolean(word + 18)) < 0)
241                         log_warning("Failed to parse dump core switch %s, Ignoring.", word + 18);
242                 else
243                         dump_core = r;
244
245         } else if (startswith(word, "systemd.crash_shell=")) {
246                 int r;
247
248                 if ((r = parse_boolean(word + 20)) < 0)
249                         log_warning("Failed to parse crash shell switch %s, Ignoring.", word + 20);
250                 else
251                         crash_shell = r;
252
253
254         } else if (startswith(word, "systemd.confirm_spawn=")) {
255                 int r;
256
257                 if ((r = parse_boolean(word + 22)) < 0)
258                         log_warning("Failed to parse confirm spawn switch %s, Ignoring.", word + 22);
259                 else
260                         confirm_spawn = r;
261
262         } else if (startswith(word, "systemd.crash_chvt=")) {
263                 int k;
264
265                 if (safe_atoi(word + 19, &k) < 0)
266                         log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
267                 else
268                         crash_chvt = k;
269
270         } else if (startswith(word, "systemd.")) {
271
272                 log_warning("Unknown kernel switch %s. Ignoring.", word);
273
274                 log_info("Supported kernel switches:");
275                 log_info("systemd.default=UNIT                     Default unit to start");
276                 log_info("systemd.log_target=console|kmsg|syslog   Log target");
277                 log_info("systemd.log_level=LEVEL                  Log level");
278                 log_info("systemd.dump_core=0|1                    Dump core on crash");
279                 log_info("systemd.crash_shell=0|1                  On crash run shell");
280                 log_info("systemd.crash_chvt=N                     Change to VT #N on crash");
281                 log_info("systemd.confirm_spawn=0|1                Confirm every process spawn");
282
283         } else {
284                 unsigned i;
285
286                 /* SysV compatibility */
287                 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
288                         if (streq(word, rlmap[i]))
289                                 return set_default_unit(rlmap[i+1]);
290         }
291
292         return 0;
293 }
294
295 static int parse_proc_cmdline(void) {
296         char *line;
297         int r;
298         char *w;
299         size_t l;
300         char *state;
301
302         if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
303                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(errno));
304                 return 0;
305         }
306
307         FOREACH_WORD_QUOTED(w, l, line, state) {
308                 char *word;
309
310                 if (!(word = strndup(w, l))) {
311                         r = -ENOMEM;
312                         goto finish;
313                 }
314
315                 r = parse_proc_cmdline_word(word);
316                 free(word);
317
318                 if (r < 0)
319                         goto finish;
320         }
321
322         r = 0;
323
324 finish:
325         free(line);
326         return r;
327 }
328
329 static int parse_argv(int argc, char *argv[]) {
330
331         enum {
332                 ARG_LOG_LEVEL = 0x100,
333                 ARG_LOG_TARGET,
334                 ARG_DEFAULT,
335                 ARG_RUNNING_AS,
336                 ARG_TEST,
337                 ARG_DUMP_CONFIGURATION_ITEMS,
338                 ARG_CONFIRM_SPAWN
339         };
340
341         static const struct option options[] = {
342                 { "log-level",  required_argument, NULL, ARG_LOG_LEVEL },
343                 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
344                 { "default",    required_argument, NULL, ARG_DEFAULT },
345                 { "running-as", required_argument, NULL, ARG_RUNNING_AS },
346                 { "test",       no_argument,       NULL, ARG_TEST },
347                 { "help",       no_argument,       NULL, 'h' },
348                 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
349                 { "confirm-spawn", no_argument,    NULL, ARG_CONFIRM_SPAWN },
350                 { NULL,         0,                 NULL, 0 }
351         };
352
353         int c, r;
354
355         assert(argc >= 1);
356         assert(argv);
357
358         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
359
360                 switch (c) {
361
362                 case ARG_LOG_LEVEL:
363                         if ((r = log_set_max_level_from_string(optarg)) < 0) {
364                                 log_error("Failed to parse log level %s.", optarg);
365                                 return r;
366                         }
367
368                         break;
369
370                 case ARG_LOG_TARGET:
371
372                         if ((r = log_set_target_from_string(optarg)) < 0) {
373                                 log_error("Failed to parse log target %s.", optarg);
374                                 return r;
375                         }
376
377                         break;
378
379                 case ARG_DEFAULT:
380
381                         if ((r = set_default_unit(optarg)) < 0) {
382                                 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
383                                 return r;
384                         }
385
386                         break;
387
388                 case ARG_RUNNING_AS: {
389                         ManagerRunningAs as;
390
391                         if ((as = manager_running_as_from_string(optarg)) < 0) {
392                                 log_error("Failed to parse running as value %s", optarg);
393                                 return -EINVAL;
394                         }
395
396                         running_as = as;
397                         break;
398                 }
399
400                 case ARG_TEST:
401                         action = ACTION_TEST;
402                         break;
403
404                 case ARG_DUMP_CONFIGURATION_ITEMS:
405                         action = ACTION_DUMP_CONFIGURATION_ITEMS;
406                         break;
407
408                 case ARG_CONFIRM_SPAWN:
409                         confirm_spawn = true;
410                         break;
411
412                 case 'h':
413                         action = ACTION_HELP;
414                         break;
415
416                 case '?':
417                         return -EINVAL;
418
419                 default:
420                         log_error("Unknown option code %c", c);
421                         return -EINVAL;
422                 }
423
424         return 0;
425 }
426
427 static int help(void) {
428
429         printf("%s [options]\n\n"
430                "  -h --help                      Show this help\n"
431                "     --default=UNIT              Set default unit\n"
432                "     --log-level=LEVEL           Set log level\n"
433                "     --log-target=TARGET         Set log target (console, syslog, kmsg)\n"
434                "     --running-as=AS             Set running as (init, system, session)\n"
435                "     --test                      Determine startup sequence, dump it and exit\n"
436                "     --dump-configuration-items  Dump understood unit configuration items\n"
437                "     --confirm-spawn             Ask for confirmation when spawning processes\n",
438                __progname);
439
440         return 0;
441 }
442
443 int main(int argc, char *argv[]) {
444         Manager *m = NULL;
445         Unit *target = NULL;
446         Job *job = NULL;
447         int r, retval = 1;
448
449         if (getpid() == 1)
450                 running_as = MANAGER_INIT;
451         else if (getuid() == 0)
452                 running_as = MANAGER_SYSTEM;
453         else
454                 running_as = MANAGER_SESSION;
455
456         if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
457                 goto finish;
458
459         /* Mount /proc, /sys and friends, so that /proc/cmdline and
460          * /proc/$PID/fd is available. */
461         if (mount_setup() < 0)
462                 goto finish;
463
464         /* Reset all signal handlers. */
465         assert_se(reset_all_signal_handlers() == 0);
466
467         /* If we are init, we can block sigkill. Yay. */
468         ignore_signal(SIGKILL);
469         ignore_signal(SIGPIPE);
470
471         /* Close all open files */
472         assert_se(close_all_fds(NULL, 0) == 0);
473
474         if (running_as != MANAGER_SESSION)
475                 if (parse_proc_cmdline() < 0)
476                         goto finish;
477
478         log_parse_environment();
479
480         if (parse_argv(argc, argv) < 0)
481                 goto finish;
482
483         if (action == ACTION_HELP) {
484                 retval = help();
485                 goto finish;
486         } else if (action == ACTION_DUMP_CONFIGURATION_ITEMS) {
487                 unit_dump_config_items(stdout);
488                 retval = 0;
489                 goto finish;
490         }
491
492         assert_se(action == ACTION_RUN || action == ACTION_TEST);
493
494         /* Set up PATH unless it is already set */
495         setenv("PATH",
496                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
497                running_as == MANAGER_INIT);
498
499         /* Move out of the way, so that we won't block unmounts */
500         assert_se(chdir("/")  == 0);
501
502         if (running_as != MANAGER_SESSION) {
503                 /* Become a session leader if we aren't one yet. */
504                 setsid();
505
506                 /* Disable the umask logic */
507                 umask(0);
508         }
509
510         if (running_as == MANAGER_INIT)
511                 console_setup();
512
513         /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
514         dbus_connection_set_change_sigpipe(FALSE);
515
516         /* Open the logging devices, if possible and necessary */
517         log_open_syslog();
518         log_open_kmsg();
519
520         /* Make sure we leave a core dump without panicing the
521          * kernel. */
522         if (getpid() == 1)
523                 install_crash_handler();
524
525         log_debug("systemd running in %s mode.", manager_running_as_to_string(running_as));
526
527         if (running_as == MANAGER_INIT)
528                 hostname_setup();
529
530         if ((r = manager_new(running_as, confirm_spawn, &m)) < 0) {
531                 log_error("Failed to allocate manager object: %s", strerror(-r));
532                 goto finish;
533         }
534
535         if ((r = manager_coldplug(m)) < 0) {
536                 log_error("Failed to retrieve coldplug information: %s", strerror(-r));
537                 goto finish;
538         }
539
540         log_debug("Activating default unit: %s", default_unit);
541
542         if ((r = manager_load_unit(m, default_unit, &target)) < 0) {
543                 log_error("Failed to load default target: %s", strerror(-r));
544
545                 log_info("Trying to load rescue target...");
546                 if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, &target)) < 0) {
547                         log_error("Failed to load rescue target: %s", strerror(-r));
548                         goto finish;
549                 }
550         }
551
552         if (action == ACTION_TEST) {
553                 printf("→ By units:\n");
554                 manager_dump_units(m, stdout, "\t");
555         }
556
557         if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &job)) < 0) {
558                 log_error("Failed to start default target: %s", strerror(-r));
559                 goto finish;
560         }
561
562         if (action == ACTION_TEST) {
563                 printf("→ By jobs:\n");
564                 manager_dump_jobs(m, stdout, "\t");
565
566                 if (getpid() == 1)
567                         pause();
568
569                 retval = 0;
570                 goto finish;
571         }
572
573         if ((r = manager_loop(m)) < 0) {
574                 log_error("Failed to run mainloop: %s", strerror(-r));
575                 goto finish;
576         }
577
578         retval = 0;
579
580         log_debug("Exit.");
581
582 finish:
583         if (m)
584                 manager_free(m);
585
586         free(default_unit);
587
588         dbus_shutdown();
589
590         if (getpid() == 1)
591                 freeze();
592
593         return retval;
594 }