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