chiark / gitweb /
execute: minor cleanups
[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         } else if (startswith(word, "systemd.crash_chvt=")) {
254                 int k;
255
256                 if (safe_atoi(word + 19, &k) < 0)
257                         log_warning("Failed to parse crash chvt switch %s, Ignoring.", word + 19);
258                 else
259                         crash_chvt = k;
260
261         } else if (startswith(word, "systemd.")) {
262
263                 log_warning("Unknown kernel switch %s. Ignoring.", word);
264
265                 log_info("Supported kernel switches:");
266                 log_info("systemd.default=UNIT                     Default unit to start");
267                 log_info("systemd.log_target=console|kmsg|syslog   Log target");
268                 log_info("systemd.log_level=LEVEL                  Log level");
269                 log_info("systemd.dump_core=0|1                    Dump core on crash");
270                 log_info("systemd.crash_shell=0|1                  On crash run shell");
271                 log_info("systemd.crash_chvt=N                     Change to VT #N on crash");
272
273         } else {
274                 unsigned i;
275
276                 /* SysV compatibility */
277                 for (i = 0; i < ELEMENTSOF(rlmap); i += 2)
278                         if (streq(word, rlmap[i]))
279                                 return set_default_unit(rlmap[i+1]);
280         }
281
282         return 0;
283 }
284
285 static int parse_proc_cmdline(void) {
286         char *line;
287         int r;
288         char *w;
289         size_t l;
290         char *state;
291
292         if ((r = read_one_line_file("/proc/cmdline", &line)) < 0) {
293                 log_warning("Failed to read /proc/cmdline, ignoring: %s", strerror(errno));
294                 return 0;
295         }
296
297         FOREACH_WORD_QUOTED(w, l, line, state) {
298                 char *word;
299
300                 if (!(word = strndup(w, l))) {
301                         r = -ENOMEM;
302                         goto finish;
303                 }
304
305                 r = parse_proc_cmdline_word(word);
306                 free(word);
307
308                 if (r < 0)
309                         goto finish;
310         }
311
312         r = 0;
313
314 finish:
315         free(line);
316         return r;
317 }
318
319 static int parse_argv(int argc, char *argv[]) {
320
321         enum {
322                 ARG_LOG_LEVEL = 0x100,
323                 ARG_LOG_TARGET,
324                 ARG_DEFAULT,
325                 ARG_RUNNING_AS,
326                 ARG_TEST,
327                 ARG_DUMP_CONFIGURATION_ITEMS,
328                 ARG_CONFIRM_SPAWN
329         };
330
331         static const struct option options[] = {
332                 { "log-level",  required_argument, NULL, ARG_LOG_LEVEL },
333                 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
334                 { "default",    required_argument, NULL, ARG_DEFAULT },
335                 { "running-as", required_argument, NULL, ARG_RUNNING_AS },
336                 { "test",       no_argument,       NULL, ARG_TEST },
337                 { "help",       no_argument,       NULL, 'h' },
338                 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
339                 { "confirm-spawn", no_argument,    NULL, ARG_CONFIRM_SPAWN },
340                 { NULL,         0,                 NULL, 0 }
341         };
342
343         int c, r;
344
345         assert(argc >= 1);
346         assert(argv);
347
348         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
349
350                 switch (c) {
351
352                 case ARG_LOG_LEVEL:
353                         if ((r = log_set_max_level_from_string(optarg)) < 0) {
354                                 log_error("Failed to parse log level %s.", optarg);
355                                 return r;
356                         }
357
358                         break;
359
360                 case ARG_LOG_TARGET:
361
362                         if ((r = log_set_target_from_string(optarg)) < 0) {
363                                 log_error("Failed to parse log target %s.", optarg);
364                                 return r;
365                         }
366
367                         break;
368
369                 case ARG_DEFAULT:
370
371                         if ((r = set_default_unit(optarg)) < 0) {
372                                 log_error("Failed to set default unit %s: %s", optarg, strerror(-r));
373                                 return r;
374                         }
375
376                         break;
377
378                 case ARG_RUNNING_AS: {
379                         ManagerRunningAs as;
380
381                         if ((as = manager_running_as_from_string(optarg)) < 0) {
382                                 log_error("Failed to parse running as value %s", optarg);
383                                 return -EINVAL;
384                         }
385
386                         running_as = as;
387                         break;
388                 }
389
390                 case ARG_TEST:
391                         action = ACTION_TEST;
392                         break;
393
394                 case ARG_DUMP_CONFIGURATION_ITEMS:
395                         action = ACTION_DUMP_CONFIGURATION_ITEMS;
396                         break;
397
398                 case ARG_CONFIRM_SPAWN:
399                         confirm_spawn = true;
400                         break;
401
402                 case 'h':
403                         action = ACTION_HELP;
404                         break;
405
406                 case '?':
407                         return -EINVAL;
408
409                 default:
410                         log_error("Unknown option code %c", c);
411                         return -EINVAL;
412                 }
413
414         return 0;
415 }
416
417 static int help(void) {
418
419         printf("%s [options]\n\n"
420                "  -h --help                      Show this help\n"
421                "     --default=UNIT              Set default unit\n"
422                "     --log-level=LEVEL           Set log level\n"
423                "     --log-target=TARGET         Set log target (console, syslog, kmsg)\n"
424                "     --running-as=AS             Set running as (init, system, session)\n"
425                "     --test                      Determine startup sequence, dump it and exit\n"
426                "     --dump-configuration-items  Dump understood unit configuration items\n"
427                "     --confirm-spawn             Ask for confirmation when spawning processes\n",
428                __progname);
429
430         return 0;
431 }
432
433 int main(int argc, char *argv[]) {
434         Manager *m = NULL;
435         Unit *target = NULL;
436         Job *job = NULL;
437         int r, retval = 1;
438
439         if (getpid() == 1)
440                 running_as = MANAGER_INIT;
441         else if (getuid() == 0)
442                 running_as = MANAGER_SYSTEM;
443         else
444                 running_as = MANAGER_SESSION;
445
446         if (set_default_unit(SPECIAL_DEFAULT_TARGET) < 0)
447                 goto finish;
448
449         /* Mount /proc, /sys and friends, so that /proc/cmdline and
450          * /proc/$PID/fd is available. */
451         if (mount_setup() < 0)
452                 goto finish;
453
454         /* Reset all signal handlers. */
455         assert_se(reset_all_signal_handlers() == 0);
456
457         /* If we are init, we can block sigkill. Yay. */
458         ignore_signal(SIGKILL);
459         ignore_signal(SIGPIPE);
460
461         /* Close all open files */
462         assert_se(close_all_fds(NULL, 0) == 0);
463
464         if (running_as != MANAGER_SESSION)
465                 if (parse_proc_cmdline() < 0)
466                         goto finish;
467
468         log_parse_environment();
469
470         if (parse_argv(argc, argv) < 0)
471                 goto finish;
472
473         if (action == ACTION_HELP) {
474                 retval = help();
475                 goto finish;
476         } else if (action == ACTION_DUMP_CONFIGURATION_ITEMS) {
477                 unit_dump_config_items(stdout);
478                 retval = 0;
479                 goto finish;
480         }
481
482         assert_se(action == ACTION_RUN || action == ACTION_TEST);
483
484         /* Set up PATH unless it is already set */
485         setenv("PATH",
486                "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
487                running_as == MANAGER_INIT);
488
489         /* Move out of the way, so that we won't block unmounts */
490         assert_se(chdir("/")  == 0);
491
492         if (running_as != MANAGER_SESSION) {
493                 /* Become a session leader if we aren't one yet. */
494                 setsid();
495
496                 /* Disable the umask logic */
497                 umask(0);
498         }
499
500         if (running_as == MANAGER_INIT)
501                 console_setup();
502
503         /* Make sure D-Bus doesn't fiddle with the SIGPIPE handlers */
504         dbus_connection_set_change_sigpipe(FALSE);
505
506         /* Open the logging devices, if possible and necessary */
507         log_open_syslog();
508         log_open_kmsg();
509
510         /* Make sure we leave a core dump without panicing the
511          * kernel. */
512         if (getpid() == 1)
513                 install_crash_handler();
514
515         log_debug("systemd running in %s mode.", manager_running_as_to_string(running_as));
516
517         if (running_as == MANAGER_INIT)
518                 hostname_setup();
519
520         if ((r = manager_new(running_as, confirm_spawn, &m)) < 0) {
521                 log_error("Failed to allocate manager object: %s", strerror(-r));
522                 goto finish;
523         }
524
525         if ((r = manager_coldplug(m)) < 0) {
526                 log_error("Failed to retrieve coldplug information: %s", strerror(-r));
527                 goto finish;
528         }
529
530         log_debug("Activating default unit: %s", default_unit);
531
532         if ((r = manager_load_unit(m, default_unit, &target)) < 0) {
533                 log_error("Failed to load default target: %s", strerror(-r));
534
535                 log_info("Trying to load rescue target...");
536                 if ((r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, &target)) < 0) {
537                         log_error("Failed to load rescue target: %s", strerror(-r));
538                         goto finish;
539                 }
540         }
541
542         if (action == ACTION_TEST) {
543                 printf("→ By units:\n");
544                 manager_dump_units(m, stdout, "\t");
545         }
546
547         if ((r = manager_add_job(m, JOB_START, target, JOB_REPLACE, false, &job)) < 0) {
548                 log_error("Failed to start default target: %s", strerror(-r));
549                 goto finish;
550         }
551
552         if (action == ACTION_TEST) {
553                 printf("→ By jobs:\n");
554                 manager_dump_jobs(m, stdout, "\t");
555
556                 if (getpid() == 1)
557                         pause();
558
559                 retval = 0;
560                 goto finish;
561         }
562
563         if ((r = manager_loop(m)) < 0) {
564                 log_error("Failed to run mainloop: %s", strerror(-r));
565                 goto finish;
566         }
567
568         retval = 0;
569
570         log_debug("Exit.");
571
572 finish:
573         if (m)
574                 manager_free(m);
575
576         free(default_unit);
577
578         dbus_shutdown();
579
580         if (getpid() == 1)
581                 freeze();
582
583         return retval;
584 }