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