]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/manager.c
core: rework logic to drop duplicate and non-existing items from search path
[thirdparty/systemd.git] / src / core / manager.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <dirent.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <linux/kd.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <sys/epoll.h>
27 #include <sys/inotify.h>
28 #include <sys/ioctl.h>
29 #include <sys/reboot.h>
30 #include <sys/timerfd.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33
34 #ifdef HAVE_AUDIT
35 #include <libaudit.h>
36 #endif
37
38 #include "sd-daemon.h"
39 #include "sd-messages.h"
40
41 #include "alloc-util.h"
42 #include "audit-fd.h"
43 #include "boot-timestamps.h"
44 #include "bus-common-errors.h"
45 #include "bus-error.h"
46 #include "bus-kernel.h"
47 #include "bus-util.h"
48 #include "dbus-job.h"
49 #include "dbus-manager.h"
50 #include "dbus-unit.h"
51 #include "dbus.h"
52 #include "env-util.h"
53 #include "escape.h"
54 #include "exit-status.h"
55 #include "fd-util.h"
56 #include "fileio.h"
57 #include "fs-util.h"
58 #include "hashmap.h"
59 #include "io-util.h"
60 #include "locale-setup.h"
61 #include "log.h"
62 #include "macro.h"
63 #include "manager.h"
64 #include "missing.h"
65 #include "mkdir.h"
66 #include "mkdir.h"
67 #include "parse-util.h"
68 #include "path-lookup.h"
69 #include "path-util.h"
70 #include "process-util.h"
71 #include "ratelimit.h"
72 #include "rm-rf.h"
73 #include "signal-util.h"
74 #include "special.h"
75 #include "stat-util.h"
76 #include "string-table.h"
77 #include "string-util.h"
78 #include "strv.h"
79 #include "terminal-util.h"
80 #include "time-util.h"
81 #include "transaction.h"
82 #include "umask-util.h"
83 #include "unit-name.h"
84 #include "util.h"
85 #include "virt.h"
86 #include "watchdog.h"
87
88 #define NOTIFY_RCVBUF_SIZE (8*1024*1024)
89
90 /* Initial delay and the interval for printing status messages about running jobs */
91 #define JOBS_IN_PROGRESS_WAIT_USEC (5*USEC_PER_SEC)
92 #define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
93 #define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
94
95 static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
96 static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
97 static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
98 static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
99 static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
100 static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
101 static int manager_run_generators(Manager *m);
102 static void manager_undo_generators(Manager *m);
103
104 static void manager_watch_jobs_in_progress(Manager *m) {
105 usec_t next;
106 int r;
107
108 assert(m);
109
110 if (m->jobs_in_progress_event_source)
111 return;
112
113 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC;
114 r = sd_event_add_time(
115 m->event,
116 &m->jobs_in_progress_event_source,
117 CLOCK_MONOTONIC,
118 next, 0,
119 manager_dispatch_jobs_in_progress, m);
120 if (r < 0)
121 return;
122
123 (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
124 }
125
126 #define CYLON_BUFFER_EXTRA (2*(sizeof(ANSI_RED)-1) + sizeof(ANSI_HIGHLIGHT_RED)-1 + 2*(sizeof(ANSI_NORMAL)-1))
127
128 static void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
129 char *p = buffer;
130
131 assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
132 assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */
133
134 if (pos > 1) {
135 if (pos > 2)
136 p = mempset(p, ' ', pos-2);
137 p = stpcpy(p, ANSI_RED);
138 *p++ = '*';
139 }
140
141 if (pos > 0 && pos <= width) {
142 p = stpcpy(p, ANSI_HIGHLIGHT_RED);
143 *p++ = '*';
144 }
145
146 p = stpcpy(p, ANSI_NORMAL);
147
148 if (pos < width) {
149 p = stpcpy(p, ANSI_RED);
150 *p++ = '*';
151 if (pos < width-1)
152 p = mempset(p, ' ', width-1-pos);
153 strcpy(p, ANSI_NORMAL);
154 }
155 }
156
157 void manager_flip_auto_status(Manager *m, bool enable) {
158 assert(m);
159
160 if (enable) {
161 if (m->show_status == SHOW_STATUS_AUTO)
162 manager_set_show_status(m, SHOW_STATUS_TEMPORARY);
163 } else {
164 if (m->show_status == SHOW_STATUS_TEMPORARY)
165 manager_set_show_status(m, SHOW_STATUS_AUTO);
166 }
167 }
168
169 static void manager_print_jobs_in_progress(Manager *m) {
170 _cleanup_free_ char *job_of_n = NULL;
171 Iterator i;
172 Job *j;
173 unsigned counter = 0, print_nr;
174 char cylon[6 + CYLON_BUFFER_EXTRA + 1];
175 unsigned cylon_pos;
176 char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit";
177 uint64_t x;
178
179 assert(m);
180 assert(m->n_running_jobs > 0);
181
182 manager_flip_auto_status(m, true);
183
184 print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
185
186 HASHMAP_FOREACH(j, m->jobs, i)
187 if (j->state == JOB_RUNNING && counter++ == print_nr)
188 break;
189
190 /* m->n_running_jobs must be consistent with the contents of m->jobs,
191 * so the above loop must have succeeded in finding j. */
192 assert(counter == print_nr + 1);
193 assert(j);
194
195 cylon_pos = m->jobs_in_progress_iteration % 14;
196 if (cylon_pos >= 8)
197 cylon_pos = 14 - cylon_pos;
198 draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
199
200 m->jobs_in_progress_iteration++;
201
202 if (m->n_running_jobs > 1) {
203 if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
204 job_of_n = NULL;
205 }
206
207 format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
208 if (job_get_timeout(j, &x) > 0)
209 format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC);
210
211 manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
212 "%sA %s job is running for %s (%s / %s)",
213 strempty(job_of_n),
214 job_type_to_string(j->type),
215 unit_description(j->unit),
216 time, limit);
217 }
218
219 static int have_ask_password(void) {
220 _cleanup_closedir_ DIR *dir;
221
222 dir = opendir("/run/systemd/ask-password");
223 if (!dir) {
224 if (errno == ENOENT)
225 return false;
226 else
227 return -errno;
228 }
229
230 for (;;) {
231 struct dirent *de;
232
233 errno = 0;
234 de = readdir(dir);
235 if (!de && errno > 0)
236 return -errno;
237 if (!de)
238 return false;
239
240 if (startswith(de->d_name, "ask."))
241 return true;
242 }
243 }
244
245 static int manager_dispatch_ask_password_fd(sd_event_source *source,
246 int fd, uint32_t revents, void *userdata) {
247 Manager *m = userdata;
248
249 assert(m);
250
251 flush_fd(fd);
252
253 m->have_ask_password = have_ask_password();
254 if (m->have_ask_password < 0)
255 /* Log error but continue. Negative have_ask_password
256 * is treated as unknown status. */
257 log_error_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password: %m");
258
259 return 0;
260 }
261
262 static void manager_close_ask_password(Manager *m) {
263 assert(m);
264
265 m->ask_password_event_source = sd_event_source_unref(m->ask_password_event_source);
266 m->ask_password_inotify_fd = safe_close(m->ask_password_inotify_fd);
267 m->have_ask_password = -EINVAL;
268 }
269
270 static int manager_check_ask_password(Manager *m) {
271 int r;
272
273 assert(m);
274
275 if (!m->ask_password_event_source) {
276 assert(m->ask_password_inotify_fd < 0);
277
278 mkdir_p_label("/run/systemd/ask-password", 0755);
279
280 m->ask_password_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
281 if (m->ask_password_inotify_fd < 0)
282 return log_error_errno(errno, "inotify_init1() failed: %m");
283
284 if (inotify_add_watch(m->ask_password_inotify_fd, "/run/systemd/ask-password", IN_CREATE|IN_DELETE|IN_MOVE) < 0) {
285 log_error_errno(errno, "Failed to add watch on /run/systemd/ask-password: %m");
286 manager_close_ask_password(m);
287 return -errno;
288 }
289
290 r = sd_event_add_io(m->event, &m->ask_password_event_source,
291 m->ask_password_inotify_fd, EPOLLIN,
292 manager_dispatch_ask_password_fd, m);
293 if (r < 0) {
294 log_error_errno(errno, "Failed to add event source for /run/systemd/ask-password: %m");
295 manager_close_ask_password(m);
296 return -errno;
297 }
298
299 (void) sd_event_source_set_description(m->ask_password_event_source, "manager-ask-password");
300
301 /* Queries might have been added meanwhile... */
302 manager_dispatch_ask_password_fd(m->ask_password_event_source,
303 m->ask_password_inotify_fd, EPOLLIN, m);
304 }
305
306 return m->have_ask_password;
307 }
308
309 static int manager_watch_idle_pipe(Manager *m) {
310 int r;
311
312 assert(m);
313
314 if (m->idle_pipe_event_source)
315 return 0;
316
317 if (m->idle_pipe[2] < 0)
318 return 0;
319
320 r = sd_event_add_io(m->event, &m->idle_pipe_event_source, m->idle_pipe[2], EPOLLIN, manager_dispatch_idle_pipe_fd, m);
321 if (r < 0)
322 return log_error_errno(r, "Failed to watch idle pipe: %m");
323
324 (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
325
326 return 0;
327 }
328
329 static void manager_close_idle_pipe(Manager *m) {
330 assert(m);
331
332 m->idle_pipe_event_source = sd_event_source_unref(m->idle_pipe_event_source);
333
334 safe_close_pair(m->idle_pipe);
335 safe_close_pair(m->idle_pipe + 2);
336 }
337
338 static int manager_setup_time_change(Manager *m) {
339 int r;
340
341 /* We only care for the cancellation event, hence we set the
342 * timeout to the latest possible value. */
343 struct itimerspec its = {
344 .it_value.tv_sec = TIME_T_MAX,
345 };
346
347 assert(m);
348 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
349
350 if (m->test_run)
351 return 0;
352
353 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
354 * CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
355
356 m->time_change_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
357 if (m->time_change_fd < 0)
358 return log_error_errno(errno, "Failed to create timerfd: %m");
359
360 if (timerfd_settime(m->time_change_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
361 log_debug_errno(errno, "Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
362 m->time_change_fd = safe_close(m->time_change_fd);
363 return 0;
364 }
365
366 r = sd_event_add_io(m->event, &m->time_change_event_source, m->time_change_fd, EPOLLIN, manager_dispatch_time_change_fd, m);
367 if (r < 0)
368 return log_error_errno(r, "Failed to create time change event source: %m");
369
370 (void) sd_event_source_set_description(m->time_change_event_source, "manager-time-change");
371
372 log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
373
374 return 0;
375 }
376
377 static int enable_special_signals(Manager *m) {
378 _cleanup_close_ int fd = -1;
379
380 assert(m);
381
382 if (m->test_run)
383 return 0;
384
385 /* Enable that we get SIGINT on control-alt-del. In containers
386 * this will fail with EPERM (older) or EINVAL (newer), so
387 * ignore that. */
388 if (reboot(RB_DISABLE_CAD) < 0 && errno != EPERM && errno != EINVAL)
389 log_warning_errno(errno, "Failed to enable ctrl-alt-del handling: %m");
390
391 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
392 if (fd < 0) {
393 /* Support systems without virtual console */
394 if (fd != -ENOENT)
395 log_warning_errno(errno, "Failed to open /dev/tty0: %m");
396 } else {
397 /* Enable that we get SIGWINCH on kbrequest */
398 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
399 log_warning_errno(errno, "Failed to enable kbrequest handling: %m");
400 }
401
402 return 0;
403 }
404
405 static int manager_setup_signals(Manager *m) {
406 struct sigaction sa = {
407 .sa_handler = SIG_DFL,
408 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
409 };
410 sigset_t mask;
411 int r;
412
413 assert(m);
414
415 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
416
417 /* We make liberal use of realtime signals here. On
418 * Linux/glibc we have 30 of them (with the exception of Linux
419 * on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
420 * (aka SIGRTMAX). */
421
422 assert_se(sigemptyset(&mask) == 0);
423 sigset_add_many(&mask,
424 SIGCHLD, /* Child died */
425 SIGTERM, /* Reexecute daemon */
426 SIGHUP, /* Reload configuration */
427 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
428 SIGUSR2, /* systemd: dump status */
429 SIGINT, /* Kernel sends us this on control-alt-del */
430 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
431 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
432
433 SIGRTMIN+0, /* systemd: start default.target */
434 SIGRTMIN+1, /* systemd: isolate rescue.target */
435 SIGRTMIN+2, /* systemd: isolate emergency.target */
436 SIGRTMIN+3, /* systemd: start halt.target */
437 SIGRTMIN+4, /* systemd: start poweroff.target */
438 SIGRTMIN+5, /* systemd: start reboot.target */
439 SIGRTMIN+6, /* systemd: start kexec.target */
440
441 /* ... space for more special targets ... */
442
443 SIGRTMIN+13, /* systemd: Immediate halt */
444 SIGRTMIN+14, /* systemd: Immediate poweroff */
445 SIGRTMIN+15, /* systemd: Immediate reboot */
446 SIGRTMIN+16, /* systemd: Immediate kexec */
447
448 /* ... space for more immediate system state changes ... */
449
450 SIGRTMIN+20, /* systemd: enable status messages */
451 SIGRTMIN+21, /* systemd: disable status messages */
452 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
453 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
454 SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
455
456 /* .. one free signal here ... */
457
458 #if !defined(__hppa64__) && !defined(__hppa__)
459 /* Apparently Linux on hppa has fewer RT
460 * signals (SIGRTMAX is SIGRTMIN+25 there),
461 * hence let's not try to make use of them
462 * here. Since these commands are accessible
463 * by different means and only really a safety
464 * net, the missing functionality on hppa
465 * shouldn't matter. */
466
467 SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
468 SIGRTMIN+27, /* systemd: set log target to console */
469 SIGRTMIN+28, /* systemd: set log target to kmsg */
470 SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg (obsolete) */
471
472 /* ... one free signal here SIGRTMIN+30 ... */
473 #endif
474 -1);
475 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
476
477 m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
478 if (m->signal_fd < 0)
479 return -errno;
480
481 r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
482 if (r < 0)
483 return r;
484
485 (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
486
487 /* Process signals a bit earlier than the rest of things, but
488 * later than notify_fd processing, so that the notify
489 * processing can still figure out to which process/service a
490 * message belongs, before we reap the process. */
491 r = sd_event_source_set_priority(m->signal_event_source, SD_EVENT_PRIORITY_NORMAL-5);
492 if (r < 0)
493 return r;
494
495 if (MANAGER_IS_SYSTEM(m))
496 return enable_special_signals(m);
497
498 return 0;
499 }
500
501 static void manager_clean_environment(Manager *m) {
502 assert(m);
503
504 /* Let's remove some environment variables that we
505 * need ourselves to communicate with our clients */
506 strv_env_unset_many(
507 m->environment,
508 "NOTIFY_SOCKET",
509 "MAINPID",
510 "MANAGERPID",
511 "LISTEN_PID",
512 "LISTEN_FDS",
513 "LISTEN_FDNAMES",
514 "WATCHDOG_PID",
515 "WATCHDOG_USEC",
516 NULL);
517 }
518
519 static int manager_default_environment(Manager *m) {
520 assert(m);
521
522 if (MANAGER_IS_SYSTEM(m)) {
523 /* The system manager always starts with a clean
524 * environment for its children. It does not import
525 * the kernel or the parents exported variables.
526 *
527 * The initial passed environ is untouched to keep
528 * /proc/self/environ valid; it is used for tagging
529 * the init process inside containers. */
530 m->environment = strv_new("PATH=" DEFAULT_PATH,
531 NULL);
532
533 /* Import locale variables LC_*= from configuration */
534 locale_setup(&m->environment);
535 } else {
536 /* The user manager passes its own environment
537 * along to its children. */
538 m->environment = strv_copy(environ);
539 }
540
541 if (!m->environment)
542 return -ENOMEM;
543
544 manager_clean_environment(m);
545 strv_sort(m->environment);
546
547 return 0;
548 }
549
550
551 int manager_new(UnitFileScope scope, bool test_run, Manager **_m) {
552 Manager *m;
553 int r;
554
555 assert(_m);
556 assert(IN_SET(scope, UNIT_FILE_SYSTEM, UNIT_FILE_USER));
557
558 m = new0(Manager, 1);
559 if (!m)
560 return -ENOMEM;
561
562 m->unit_file_scope = scope;
563 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
564 m->default_timer_accuracy_usec = USEC_PER_MINUTE;
565 m->default_tasks_accounting = true;
566 m->default_tasks_max = UINT64_C(512);
567
568 #ifdef ENABLE_EFI
569 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
570 boot_timestamps(&m->userspace_timestamp, &m->firmware_timestamp, &m->loader_timestamp);
571 #endif
572
573 /* Prepare log fields we can use for structured logging */
574 if (MANAGER_IS_SYSTEM(m)) {
575 m->unit_log_field = "UNIT=";
576 m->unit_log_format_string = "UNIT=%s";
577 } else {
578 m->unit_log_field = "USER_UNIT=";
579 m->unit_log_format_string = "USER_UNIT=%s";
580 }
581
582 m->idle_pipe[0] = m->idle_pipe[1] = m->idle_pipe[2] = m->idle_pipe[3] = -1;
583
584 m->pin_cgroupfs_fd = m->notify_fd = m->signal_fd = m->time_change_fd =
585 m->dev_autofs_fd = m->private_listen_fd = m->kdbus_fd = m->cgroup_inotify_fd = -1;
586
587 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
588
589 m->ask_password_inotify_fd = -1;
590 m->have_ask_password = -EINVAL; /* we don't know */
591 m->first_boot = -1;
592
593 m->test_run = test_run;
594
595 /* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
596 RATELIMIT_INIT(m->ctrl_alt_del_ratelimit, 2 * USEC_PER_SEC, 7);
597
598 r = manager_default_environment(m);
599 if (r < 0)
600 goto fail;
601
602 r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
603 if (r < 0)
604 goto fail;
605
606 r = hashmap_ensure_allocated(&m->jobs, NULL);
607 if (r < 0)
608 goto fail;
609
610 r = hashmap_ensure_allocated(&m->cgroup_unit, &string_hash_ops);
611 if (r < 0)
612 goto fail;
613
614 r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
615 if (r < 0)
616 goto fail;
617
618 r = sd_event_default(&m->event);
619 if (r < 0)
620 goto fail;
621
622 r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
623 if (r < 0)
624 goto fail;
625
626 r = sd_event_source_set_priority(m->run_queue_event_source, SD_EVENT_PRIORITY_IDLE);
627 if (r < 0)
628 goto fail;
629
630 r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
631 if (r < 0)
632 goto fail;
633
634 (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
635
636 r = manager_setup_signals(m);
637 if (r < 0)
638 goto fail;
639
640 r = manager_setup_cgroup(m);
641 if (r < 0)
642 goto fail;
643
644 r = manager_setup_time_change(m);
645 if (r < 0)
646 goto fail;
647
648 m->udev = udev_new();
649 if (!m->udev) {
650 r = -ENOMEM;
651 goto fail;
652 }
653
654 /* Note that we set up neither kdbus, nor the notify fd
655 * here. We do that after deserialization, since they might
656 * have gotten serialized across the reexec. */
657
658 m->taint_usr = dir_is_empty("/usr") > 0;
659
660 *_m = m;
661 return 0;
662
663 fail:
664 manager_free(m);
665 return r;
666 }
667
668 static int manager_setup_notify(Manager *m) {
669 int r;
670
671 if (m->test_run)
672 return 0;
673
674 if (m->notify_fd < 0) {
675 _cleanup_close_ int fd = -1;
676 union sockaddr_union sa = {
677 .sa.sa_family = AF_UNIX,
678 };
679 static const int one = 1;
680 const char *e;
681
682 /* First free all secondary fields */
683 m->notify_socket = mfree(m->notify_socket);
684 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
685
686 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
687 if (fd < 0)
688 return log_error_errno(errno, "Failed to allocate notification socket: %m");
689
690 fd_inc_rcvbuf(fd, NOTIFY_RCVBUF_SIZE);
691
692 e = manager_get_runtime_prefix(m);
693 if (!e) {
694 log_error("Failed to determine runtime prefix.");
695 return -EINVAL;
696 }
697
698 m->notify_socket = strappend(e, "/systemd/notify");
699 if (!m->notify_socket)
700 return log_oom();
701
702 (void) mkdir_parents_label(m->notify_socket, 0755);
703 (void) unlink(m->notify_socket);
704
705 strncpy(sa.un.sun_path, m->notify_socket, sizeof(sa.un.sun_path)-1);
706 r = bind(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path));
707 if (r < 0)
708 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
709
710 r = setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
711 if (r < 0)
712 return log_error_errno(errno, "SO_PASSCRED failed: %m");
713
714 m->notify_fd = fd;
715 fd = -1;
716
717 log_debug("Using notification socket %s", m->notify_socket);
718 }
719
720 if (!m->notify_event_source) {
721 r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
722 if (r < 0)
723 return log_error_errno(r, "Failed to allocate notify event source: %m");
724
725 /* Process signals a bit earlier than SIGCHLD, so that we can
726 * still identify to which service an exit message belongs */
727 r = sd_event_source_set_priority(m->notify_event_source, SD_EVENT_PRIORITY_NORMAL-7);
728 if (r < 0)
729 return log_error_errno(r, "Failed to set priority of notify event source: %m");
730
731 (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
732 }
733
734 return 0;
735 }
736
737 static int manager_setup_kdbus(Manager *m) {
738 _cleanup_free_ char *p = NULL;
739
740 assert(m);
741
742 if (m->test_run || m->kdbus_fd >= 0)
743 return 0;
744 if (!is_kdbus_available())
745 return -ESOCKTNOSUPPORT;
746
747 m->kdbus_fd = bus_kernel_create_bus(
748 MANAGER_IS_SYSTEM(m) ? "system" : "user",
749 MANAGER_IS_SYSTEM(m), &p);
750
751 if (m->kdbus_fd < 0)
752 return log_debug_errno(m->kdbus_fd, "Failed to set up kdbus: %m");
753
754 log_debug("Successfully set up kdbus on %s", p);
755
756 return 0;
757 }
758
759 static int manager_connect_bus(Manager *m, bool reexecuting) {
760 bool try_bus_connect;
761
762 assert(m);
763
764 if (m->test_run)
765 return 0;
766
767 try_bus_connect =
768 m->kdbus_fd >= 0 ||
769 reexecuting ||
770 (MANAGER_IS_USER(m) && getenv("DBUS_SESSION_BUS_ADDRESS"));
771
772 /* Try to connect to the buses, if possible. */
773 return bus_init(m, try_bus_connect);
774 }
775
776 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
777 Unit *u;
778 unsigned n = 0;
779
780 assert(m);
781
782 while ((u = m->cleanup_queue)) {
783 assert(u->in_cleanup_queue);
784
785 unit_free(u);
786 n++;
787 }
788
789 return n;
790 }
791
792 enum {
793 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
794 GC_OFFSET_UNSURE, /* No clue */
795 GC_OFFSET_GOOD, /* We still need this unit */
796 GC_OFFSET_BAD, /* We don't need this unit anymore */
797 _GC_OFFSET_MAX
798 };
799
800 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
801 Iterator i;
802 Unit *other;
803 bool is_bad;
804
805 assert(u);
806
807 if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
808 u->gc_marker == gc_marker + GC_OFFSET_BAD ||
809 u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
810 return;
811
812 if (u->in_cleanup_queue)
813 goto bad;
814
815 if (unit_check_gc(u))
816 goto good;
817
818 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
819
820 is_bad = true;
821
822 SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
823 unit_gc_sweep(other, gc_marker);
824
825 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
826 goto good;
827
828 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
829 is_bad = false;
830 }
831
832 if (is_bad)
833 goto bad;
834
835 /* We were unable to find anything out about this entry, so
836 * let's investigate it later */
837 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
838 unit_add_to_gc_queue(u);
839 return;
840
841 bad:
842 /* We definitely know that this one is not useful anymore, so
843 * let's mark it for deletion */
844 u->gc_marker = gc_marker + GC_OFFSET_BAD;
845 unit_add_to_cleanup_queue(u);
846 return;
847
848 good:
849 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
850 }
851
852 static unsigned manager_dispatch_gc_queue(Manager *m) {
853 Unit *u;
854 unsigned n = 0;
855 unsigned gc_marker;
856
857 assert(m);
858
859 /* log_debug("Running GC..."); */
860
861 m->gc_marker += _GC_OFFSET_MAX;
862 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
863 m->gc_marker = 1;
864
865 gc_marker = m->gc_marker;
866
867 while ((u = m->gc_queue)) {
868 assert(u->in_gc_queue);
869
870 unit_gc_sweep(u, gc_marker);
871
872 LIST_REMOVE(gc_queue, m->gc_queue, u);
873 u->in_gc_queue = false;
874
875 n++;
876
877 if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
878 u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
879 if (u->id)
880 log_unit_debug(u, "Collecting.");
881 u->gc_marker = gc_marker + GC_OFFSET_BAD;
882 unit_add_to_cleanup_queue(u);
883 }
884 }
885
886 m->n_in_gc_queue = 0;
887
888 return n;
889 }
890
891 static void manager_clear_jobs_and_units(Manager *m) {
892 Unit *u;
893
894 assert(m);
895
896 while ((u = hashmap_first(m->units)))
897 unit_free(u);
898
899 manager_dispatch_cleanup_queue(m);
900
901 assert(!m->load_queue);
902 assert(!m->run_queue);
903 assert(!m->dbus_unit_queue);
904 assert(!m->dbus_job_queue);
905 assert(!m->cleanup_queue);
906 assert(!m->gc_queue);
907
908 assert(hashmap_isempty(m->jobs));
909 assert(hashmap_isempty(m->units));
910
911 m->n_on_console = 0;
912 m->n_running_jobs = 0;
913 }
914
915 Manager* manager_free(Manager *m) {
916 UnitType c;
917 int i;
918
919 if (!m)
920 return NULL;
921
922 manager_clear_jobs_and_units(m);
923
924 for (c = 0; c < _UNIT_TYPE_MAX; c++)
925 if (unit_vtable[c]->shutdown)
926 unit_vtable[c]->shutdown(m);
927
928 /* If we reexecute ourselves, we keep the root cgroup
929 * around */
930 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
931
932 manager_undo_generators(m);
933
934 bus_done(m);
935
936 hashmap_free(m->units);
937 hashmap_free(m->jobs);
938 hashmap_free(m->watch_pids1);
939 hashmap_free(m->watch_pids2);
940 hashmap_free(m->watch_bus);
941
942 set_free(m->startup_units);
943 set_free(m->failed_units);
944
945 sd_event_source_unref(m->signal_event_source);
946 sd_event_source_unref(m->notify_event_source);
947 sd_event_source_unref(m->time_change_event_source);
948 sd_event_source_unref(m->jobs_in_progress_event_source);
949 sd_event_source_unref(m->run_queue_event_source);
950
951 safe_close(m->signal_fd);
952 safe_close(m->notify_fd);
953 safe_close(m->time_change_fd);
954 safe_close(m->kdbus_fd);
955
956 manager_close_ask_password(m);
957
958 manager_close_idle_pipe(m);
959
960 udev_unref(m->udev);
961 sd_event_unref(m->event);
962
963 free(m->notify_socket);
964
965 lookup_paths_free(&m->lookup_paths);
966 strv_free(m->environment);
967
968 hashmap_free(m->cgroup_unit);
969 set_free_free(m->unit_path_cache);
970
971 free(m->switch_root);
972 free(m->switch_root_init);
973
974 for (i = 0; i < _RLIMIT_MAX; i++)
975 m->rlimit[i] = mfree(m->rlimit[i]);
976
977 assert(hashmap_isempty(m->units_requiring_mounts_for));
978 hashmap_free(m->units_requiring_mounts_for);
979
980 free(m);
981 return NULL;
982 }
983
984 void manager_enumerate(Manager *m) {
985 UnitType c;
986
987 assert(m);
988
989 /* Let's ask every type to load all units from disk/kernel
990 * that it might know */
991 for (c = 0; c < _UNIT_TYPE_MAX; c++) {
992 if (!unit_type_supported(c)) {
993 log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
994 continue;
995 }
996
997 if (!unit_vtable[c]->enumerate)
998 continue;
999
1000 unit_vtable[c]->enumerate(m);
1001 }
1002
1003 manager_dispatch_load_queue(m);
1004 }
1005
1006 static void manager_coldplug(Manager *m) {
1007 Iterator i;
1008 Unit *u;
1009 char *k;
1010 int r;
1011
1012 assert(m);
1013
1014 /* Then, let's set up their initial state. */
1015 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1016
1017 /* ignore aliases */
1018 if (u->id != k)
1019 continue;
1020
1021 r = unit_coldplug(u);
1022 if (r < 0)
1023 log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
1024 }
1025 }
1026
1027 static void manager_build_unit_path_cache(Manager *m) {
1028 char **i;
1029 _cleanup_closedir_ DIR *d = NULL;
1030 int r;
1031
1032 assert(m);
1033
1034 set_free_free(m->unit_path_cache);
1035
1036 m->unit_path_cache = set_new(&string_hash_ops);
1037 if (!m->unit_path_cache) {
1038 log_error("Failed to allocate unit path cache.");
1039 return;
1040 }
1041
1042 /* This simply builds a list of files we know exist, so that
1043 * we don't always have to go to disk */
1044
1045 STRV_FOREACH(i, m->lookup_paths.search_path) {
1046 struct dirent *de;
1047
1048 d = opendir(*i);
1049 if (!d) {
1050 if (errno != ENOENT)
1051 log_error_errno(errno, "Failed to open directory %s: %m", *i);
1052 continue;
1053 }
1054
1055 while ((de = readdir(d))) {
1056 char *p;
1057
1058 if (hidden_file(de->d_name))
1059 continue;
1060
1061 p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
1062 if (!p) {
1063 r = -ENOMEM;
1064 goto fail;
1065 }
1066
1067 r = set_consume(m->unit_path_cache, p);
1068 if (r < 0)
1069 goto fail;
1070 }
1071
1072 d = safe_closedir(d);
1073 }
1074
1075 return;
1076
1077 fail:
1078 log_error_errno(r, "Failed to build unit path cache: %m");
1079
1080 set_free_free(m->unit_path_cache);
1081 m->unit_path_cache = NULL;
1082 }
1083
1084
1085 static void manager_distribute_fds(Manager *m, FDSet *fds) {
1086 Iterator i;
1087 Unit *u;
1088
1089 assert(m);
1090
1091 HASHMAP_FOREACH(u, m->units, i) {
1092
1093 if (fdset_size(fds) <= 0)
1094 break;
1095
1096 if (!UNIT_VTABLE(u)->distribute_fds)
1097 continue;
1098
1099 UNIT_VTABLE(u)->distribute_fds(u, fds);
1100 }
1101 }
1102
1103 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
1104 int r, q;
1105
1106 assert(m);
1107
1108 r = lookup_paths_init(&m->lookup_paths, m->unit_file_scope, NULL);
1109 if (r < 0)
1110 return r;
1111
1112 /* Make sure the transient directory always exists, so that it remains in the search path */
1113 r = mkdir_p_label(m->lookup_paths.transient, 0755);
1114 if (r < 0)
1115 return r;
1116
1117 dual_timestamp_get(&m->generators_start_timestamp);
1118 r = manager_run_generators(m);
1119 dual_timestamp_get(&m->generators_finish_timestamp);
1120 if (r < 0)
1121 return r;
1122
1123 lookup_paths_reduce(&m->lookup_paths);
1124 manager_build_unit_path_cache(m);
1125
1126 /* If we will deserialize make sure that during enumeration
1127 * this is already known, so we increase the counter here
1128 * already */
1129 if (serialization)
1130 m->n_reloading++;
1131
1132 /* First, enumerate what we can from all config files */
1133 dual_timestamp_get(&m->units_load_start_timestamp);
1134 manager_enumerate(m);
1135 dual_timestamp_get(&m->units_load_finish_timestamp);
1136
1137 /* Second, deserialize if there is something to deserialize */
1138 if (serialization)
1139 r = manager_deserialize(m, serialization, fds);
1140
1141 /* Any fds left? Find some unit which wants them. This is
1142 * useful to allow container managers to pass some file
1143 * descriptors to us pre-initialized. This enables
1144 * socket-based activation of entire containers. */
1145 manager_distribute_fds(m, fds);
1146
1147 /* We might have deserialized the notify fd, but if we didn't
1148 * then let's create the bus now */
1149 q = manager_setup_notify(m);
1150 if (q < 0 && r == 0)
1151 r = q;
1152
1153 /* We might have deserialized the kdbus control fd, but if we
1154 * didn't, then let's create the bus now. */
1155 manager_setup_kdbus(m);
1156 manager_connect_bus(m, !!serialization);
1157 bus_track_coldplug(m, &m->subscribed, &m->deserialized_subscribed);
1158
1159 /* Third, fire things up! */
1160 manager_coldplug(m);
1161
1162 if (serialization) {
1163 assert(m->n_reloading > 0);
1164 m->n_reloading--;
1165
1166 /* Let's wait for the UnitNew/JobNew messages being
1167 * sent, before we notify that the reload is
1168 * finished */
1169 m->send_reloading_done = true;
1170 }
1171
1172 return r;
1173 }
1174
1175 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, sd_bus_error *e, Job **_ret) {
1176 int r;
1177 Transaction *tr;
1178
1179 assert(m);
1180 assert(type < _JOB_TYPE_MAX);
1181 assert(unit);
1182 assert(mode < _JOB_MODE_MAX);
1183
1184 if (mode == JOB_ISOLATE && type != JOB_START)
1185 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
1186
1187 if (mode == JOB_ISOLATE && !unit->allow_isolate)
1188 return sd_bus_error_setf(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1189
1190 log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1191
1192 type = job_type_collapse(type, unit);
1193
1194 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1195 if (!tr)
1196 return -ENOMEM;
1197
1198 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, false,
1199 mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
1200 mode == JOB_IGNORE_DEPENDENCIES, e);
1201 if (r < 0)
1202 goto tr_abort;
1203
1204 if (mode == JOB_ISOLATE) {
1205 r = transaction_add_isolate_jobs(tr, m);
1206 if (r < 0)
1207 goto tr_abort;
1208 }
1209
1210 r = transaction_activate(tr, m, mode, e);
1211 if (r < 0)
1212 goto tr_abort;
1213
1214 log_unit_debug(unit,
1215 "Enqueued job %s/%s as %u", unit->id,
1216 job_type_to_string(type), (unsigned) tr->anchor_job->id);
1217
1218 if (_ret)
1219 *_ret = tr->anchor_job;
1220
1221 transaction_free(tr);
1222 return 0;
1223
1224 tr_abort:
1225 transaction_abort(tr);
1226 transaction_free(tr);
1227 return r;
1228 }
1229
1230 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, sd_bus_error *e, Job **ret) {
1231 Unit *unit;
1232 int r;
1233
1234 assert(m);
1235 assert(type < _JOB_TYPE_MAX);
1236 assert(name);
1237 assert(mode < _JOB_MODE_MAX);
1238
1239 r = manager_load_unit(m, name, NULL, NULL, &unit);
1240 if (r < 0)
1241 return r;
1242
1243 return manager_add_job(m, type, unit, mode, e, ret);
1244 }
1245
1246 int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Job **ret) {
1247 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1248 int r;
1249
1250 assert(m);
1251 assert(type < _JOB_TYPE_MAX);
1252 assert(name);
1253 assert(mode < _JOB_MODE_MAX);
1254
1255 r = manager_add_job_by_name(m, type, name, mode, &error, ret);
1256 if (r < 0)
1257 return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
1258
1259 return r;
1260 }
1261
1262 Job *manager_get_job(Manager *m, uint32_t id) {
1263 assert(m);
1264
1265 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1266 }
1267
1268 Unit *manager_get_unit(Manager *m, const char *name) {
1269 assert(m);
1270 assert(name);
1271
1272 return hashmap_get(m->units, name);
1273 }
1274
1275 unsigned manager_dispatch_load_queue(Manager *m) {
1276 Unit *u;
1277 unsigned n = 0;
1278
1279 assert(m);
1280
1281 /* Make sure we are not run recursively */
1282 if (m->dispatching_load_queue)
1283 return 0;
1284
1285 m->dispatching_load_queue = true;
1286
1287 /* Dispatches the load queue. Takes a unit from the queue and
1288 * tries to load its data until the queue is empty */
1289
1290 while ((u = m->load_queue)) {
1291 assert(u->in_load_queue);
1292
1293 unit_load(u);
1294 n++;
1295 }
1296
1297 m->dispatching_load_queue = false;
1298 return n;
1299 }
1300
1301 int manager_load_unit_prepare(
1302 Manager *m,
1303 const char *name,
1304 const char *path,
1305 sd_bus_error *e,
1306 Unit **_ret) {
1307
1308 Unit *ret;
1309 UnitType t;
1310 int r;
1311
1312 assert(m);
1313 assert(name || path);
1314
1315 /* This will prepare the unit for loading, but not actually
1316 * load anything from disk. */
1317
1318 if (path && !is_path(path))
1319 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
1320
1321 if (!name)
1322 name = basename(path);
1323
1324 t = unit_name_to_type(name);
1325
1326 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
1327 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
1328 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
1329
1330 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
1331 }
1332
1333 ret = manager_get_unit(m, name);
1334 if (ret) {
1335 *_ret = ret;
1336 return 1;
1337 }
1338
1339 ret = unit_new(m, unit_vtable[t]->object_size);
1340 if (!ret)
1341 return -ENOMEM;
1342
1343 if (path) {
1344 ret->fragment_path = strdup(path);
1345 if (!ret->fragment_path) {
1346 unit_free(ret);
1347 return -ENOMEM;
1348 }
1349 }
1350
1351 r = unit_add_name(ret, name);
1352 if (r < 0) {
1353 unit_free(ret);
1354 return r;
1355 }
1356
1357 unit_add_to_load_queue(ret);
1358 unit_add_to_dbus_queue(ret);
1359 unit_add_to_gc_queue(ret);
1360
1361 if (_ret)
1362 *_ret = ret;
1363
1364 return 0;
1365 }
1366
1367 int manager_load_unit(
1368 Manager *m,
1369 const char *name,
1370 const char *path,
1371 sd_bus_error *e,
1372 Unit **_ret) {
1373
1374 int r;
1375
1376 assert(m);
1377
1378 /* This will load the service information files, but not actually
1379 * start any services or anything. */
1380
1381 r = manager_load_unit_prepare(m, name, path, e, _ret);
1382 if (r != 0)
1383 return r;
1384
1385 manager_dispatch_load_queue(m);
1386
1387 if (_ret)
1388 *_ret = unit_follow_merge(*_ret);
1389
1390 return 0;
1391 }
1392
1393 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1394 Iterator i;
1395 Job *j;
1396
1397 assert(s);
1398 assert(f);
1399
1400 HASHMAP_FOREACH(j, s->jobs, i)
1401 job_dump(j, f, prefix);
1402 }
1403
1404 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1405 Iterator i;
1406 Unit *u;
1407 const char *t;
1408
1409 assert(s);
1410 assert(f);
1411
1412 HASHMAP_FOREACH_KEY(u, t, s->units, i)
1413 if (u->id == t)
1414 unit_dump(u, f, prefix);
1415 }
1416
1417 void manager_clear_jobs(Manager *m) {
1418 Job *j;
1419
1420 assert(m);
1421
1422 while ((j = hashmap_first(m->jobs)))
1423 /* No need to recurse. We're cancelling all jobs. */
1424 job_finish_and_invalidate(j, JOB_CANCELED, false);
1425 }
1426
1427 static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
1428 Manager *m = userdata;
1429 Job *j;
1430
1431 assert(source);
1432 assert(m);
1433
1434 while ((j = m->run_queue)) {
1435 assert(j->installed);
1436 assert(j->in_run_queue);
1437
1438 job_run_and_invalidate(j);
1439 }
1440
1441 if (m->n_running_jobs > 0)
1442 manager_watch_jobs_in_progress(m);
1443
1444 if (m->n_on_console > 0)
1445 manager_watch_idle_pipe(m);
1446
1447 return 1;
1448 }
1449
1450 static unsigned manager_dispatch_dbus_queue(Manager *m) {
1451 Job *j;
1452 Unit *u;
1453 unsigned n = 0;
1454
1455 assert(m);
1456
1457 if (m->dispatching_dbus_queue)
1458 return 0;
1459
1460 m->dispatching_dbus_queue = true;
1461
1462 while ((u = m->dbus_unit_queue)) {
1463 assert(u->in_dbus_queue);
1464
1465 bus_unit_send_change_signal(u);
1466 n++;
1467 }
1468
1469 while ((j = m->dbus_job_queue)) {
1470 assert(j->in_dbus_queue);
1471
1472 bus_job_send_change_signal(j);
1473 n++;
1474 }
1475
1476 m->dispatching_dbus_queue = false;
1477
1478 if (m->send_reloading_done) {
1479 m->send_reloading_done = false;
1480
1481 bus_manager_send_reloading(m, false);
1482 }
1483
1484 if (m->queued_message)
1485 bus_send_queued_message(m);
1486
1487 return n;
1488 }
1489
1490 static void manager_invoke_notify_message(Manager *m, Unit *u, pid_t pid, const char *buf, size_t n, FDSet *fds) {
1491 _cleanup_strv_free_ char **tags = NULL;
1492
1493 assert(m);
1494 assert(u);
1495 assert(buf);
1496 assert(n > 0);
1497
1498 tags = strv_split(buf, "\n\r");
1499 if (!tags) {
1500 log_oom();
1501 return;
1502 }
1503
1504 if (UNIT_VTABLE(u)->notify_message)
1505 UNIT_VTABLE(u)->notify_message(u, pid, tags, fds);
1506 else
1507 log_unit_debug(u, "Got notification message for unit. Ignoring.");
1508 }
1509
1510 static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1511 _cleanup_fdset_free_ FDSet *fds = NULL;
1512 Manager *m = userdata;
1513
1514 char buf[NOTIFY_BUFFER_MAX+1];
1515 struct iovec iovec = {
1516 .iov_base = buf,
1517 .iov_len = sizeof(buf)-1,
1518 };
1519 union {
1520 struct cmsghdr cmsghdr;
1521 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1522 CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];
1523 } control = {};
1524 struct msghdr msghdr = {
1525 .msg_iov = &iovec,
1526 .msg_iovlen = 1,
1527 .msg_control = &control,
1528 .msg_controllen = sizeof(control),
1529 };
1530
1531 struct cmsghdr *cmsg;
1532 struct ucred *ucred = NULL;
1533 bool found = false;
1534 Unit *u1, *u2, *u3;
1535 int r, *fd_array = NULL;
1536 unsigned n_fds = 0;
1537 ssize_t n;
1538
1539 assert(m);
1540 assert(m->notify_fd == fd);
1541
1542 if (revents != EPOLLIN) {
1543 log_warning("Got unexpected poll event for notify fd.");
1544 return 0;
1545 }
1546
1547 n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC);
1548 if (n < 0) {
1549 if (errno == EAGAIN || errno == EINTR)
1550 return 0;
1551
1552 return -errno;
1553 }
1554
1555 CMSG_FOREACH(cmsg, &msghdr) {
1556 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1557
1558 fd_array = (int*) CMSG_DATA(cmsg);
1559 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
1560
1561 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1562 cmsg->cmsg_type == SCM_CREDENTIALS &&
1563 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
1564
1565 ucred = (struct ucred*) CMSG_DATA(cmsg);
1566 }
1567 }
1568
1569 if (n_fds > 0) {
1570 assert(fd_array);
1571
1572 r = fdset_new_array(&fds, fd_array, n_fds);
1573 if (r < 0) {
1574 close_many(fd_array, n_fds);
1575 return log_oom();
1576 }
1577 }
1578
1579 if (!ucred || ucred->pid <= 0) {
1580 log_warning("Received notify message without valid credentials. Ignoring.");
1581 return 0;
1582 }
1583
1584 if ((size_t) n >= sizeof(buf)) {
1585 log_warning("Received notify message exceeded maximum size. Ignoring.");
1586 return 0;
1587 }
1588
1589 buf[n] = 0;
1590
1591 /* Notify every unit that might be interested, but try
1592 * to avoid notifying the same one multiple times. */
1593 u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);
1594 if (u1) {
1595 manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds);
1596 found = true;
1597 }
1598
1599 u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));
1600 if (u2 && u2 != u1) {
1601 manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds);
1602 found = true;
1603 }
1604
1605 u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));
1606 if (u3 && u3 != u2 && u3 != u1) {
1607 manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds);
1608 found = true;
1609 }
1610
1611 if (!found)
1612 log_warning("Cannot find unit for notify message of PID "PID_FMT".", ucred->pid);
1613
1614 if (fdset_size(fds) > 0)
1615 log_warning("Got auxiliary fds with notification message, closing all.");
1616
1617 return 0;
1618 }
1619
1620 static void invoke_sigchld_event(Manager *m, Unit *u, const siginfo_t *si) {
1621 assert(m);
1622 assert(u);
1623 assert(si);
1624
1625 log_unit_debug(u, "Child "PID_FMT" belongs to %s", si->si_pid, u->id);
1626
1627 unit_unwatch_pid(u, si->si_pid);
1628
1629 if (UNIT_VTABLE(u)->sigchld_event)
1630 UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
1631 }
1632
1633 static int manager_dispatch_sigchld(Manager *m) {
1634 assert(m);
1635
1636 for (;;) {
1637 siginfo_t si = {};
1638
1639 /* First we call waitd() for a PID and do not reap the
1640 * zombie. That way we can still access /proc/$PID for
1641 * it while it is a zombie. */
1642 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
1643
1644 if (errno == ECHILD)
1645 break;
1646
1647 if (errno == EINTR)
1648 continue;
1649
1650 return -errno;
1651 }
1652
1653 if (si.si_pid <= 0)
1654 break;
1655
1656 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1657 _cleanup_free_ char *name = NULL;
1658 Unit *u1, *u2, *u3;
1659
1660 get_process_comm(si.si_pid, &name);
1661
1662 log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
1663 si.si_pid, strna(name),
1664 sigchld_code_to_string(si.si_code),
1665 si.si_status,
1666 strna(si.si_code == CLD_EXITED
1667 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1668 : signal_to_string(si.si_status)));
1669
1670 /* And now figure out the unit this belongs
1671 * to, it might be multiple... */
1672 u1 = manager_get_unit_by_pid_cgroup(m, si.si_pid);
1673 if (u1)
1674 invoke_sigchld_event(m, u1, &si);
1675 u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(si.si_pid));
1676 if (u2 && u2 != u1)
1677 invoke_sigchld_event(m, u2, &si);
1678 u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(si.si_pid));
1679 if (u3 && u3 != u2 && u3 != u1)
1680 invoke_sigchld_event(m, u3, &si);
1681 }
1682
1683 /* And now, we actually reap the zombie. */
1684 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1685 if (errno == EINTR)
1686 continue;
1687
1688 return -errno;
1689 }
1690 }
1691
1692 return 0;
1693 }
1694
1695 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1696 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1697 int r;
1698
1699 log_debug("Activating special unit %s", name);
1700
1701 r = manager_add_job_by_name(m, JOB_START, name, mode, &error, NULL);
1702 if (r < 0)
1703 log_error("Failed to enqueue %s job: %s", name, bus_error_message(&error, r));
1704
1705 return r;
1706 }
1707
1708 static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1709 Manager *m = userdata;
1710 ssize_t n;
1711 struct signalfd_siginfo sfsi;
1712 bool sigchld = false;
1713 int r;
1714
1715 assert(m);
1716 assert(m->signal_fd == fd);
1717
1718 if (revents != EPOLLIN) {
1719 log_warning("Got unexpected events from signal file descriptor.");
1720 return 0;
1721 }
1722
1723 for (;;) {
1724 n = read(m->signal_fd, &sfsi, sizeof(sfsi));
1725 if (n != sizeof(sfsi)) {
1726
1727 if (n >= 0)
1728 return -EIO;
1729
1730 if (errno == EINTR || errno == EAGAIN)
1731 break;
1732
1733 return -errno;
1734 }
1735
1736 log_received_signal(sfsi.ssi_signo == SIGCHLD ||
1737 (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
1738 ? LOG_DEBUG : LOG_INFO,
1739 &sfsi);
1740
1741 switch (sfsi.ssi_signo) {
1742
1743 case SIGCHLD:
1744 sigchld = true;
1745 break;
1746
1747 case SIGTERM:
1748 if (MANAGER_IS_SYSTEM(m)) {
1749 /* This is for compatibility with the
1750 * original sysvinit */
1751 m->exit_code = MANAGER_REEXECUTE;
1752 break;
1753 }
1754
1755 /* Fall through */
1756
1757 case SIGINT:
1758 if (MANAGER_IS_SYSTEM(m)) {
1759
1760 /* If the user presses C-A-D more than
1761 * 7 times within 2s, we reboot
1762 * immediately. */
1763
1764 if (ratelimit_test(&m->ctrl_alt_del_ratelimit))
1765 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
1766 else {
1767 log_notice("Ctrl-Alt-Del was pressed more than 7 times within 2s, rebooting immediately.");
1768 status_printf(NULL, true, false, "Ctrl-Alt-Del was pressed more than 7 times within 2s, rebooting immediately.");
1769 m->exit_code = MANAGER_REBOOT;
1770 }
1771
1772 break;
1773 }
1774
1775 /* Run the exit target if there is one, if not, just exit. */
1776 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
1777 m->exit_code = MANAGER_EXIT;
1778 return 0;
1779 }
1780
1781 break;
1782
1783 case SIGWINCH:
1784 if (MANAGER_IS_SYSTEM(m))
1785 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1786
1787 /* This is a nop on non-init */
1788 break;
1789
1790 case SIGPWR:
1791 if (MANAGER_IS_SYSTEM(m))
1792 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1793
1794 /* This is a nop on non-init */
1795 break;
1796
1797 case SIGUSR1: {
1798 Unit *u;
1799
1800 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1801
1802 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1803 log_info("Trying to reconnect to bus...");
1804 bus_init(m, true);
1805 }
1806
1807 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1808 log_info("Loading D-Bus service...");
1809 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1810 }
1811
1812 break;
1813 }
1814
1815 case SIGUSR2: {
1816 _cleanup_free_ char *dump = NULL;
1817 _cleanup_fclose_ FILE *f = NULL;
1818 size_t size;
1819
1820 f = open_memstream(&dump, &size);
1821 if (!f) {
1822 log_warning_errno(errno, "Failed to allocate memory stream: %m");
1823 break;
1824 }
1825
1826 manager_dump_units(m, f, "\t");
1827 manager_dump_jobs(m, f, "\t");
1828
1829 r = fflush_and_check(f);
1830 if (r < 0) {
1831 log_warning_errno(r, "Failed to write status stream: %m");
1832 break;
1833 }
1834
1835 log_dump(LOG_INFO, dump);
1836 break;
1837 }
1838
1839 case SIGHUP:
1840 m->exit_code = MANAGER_RELOAD;
1841 break;
1842
1843 default: {
1844
1845 /* Starting SIGRTMIN+0 */
1846 static const char * const target_table[] = {
1847 [0] = SPECIAL_DEFAULT_TARGET,
1848 [1] = SPECIAL_RESCUE_TARGET,
1849 [2] = SPECIAL_EMERGENCY_TARGET,
1850 [3] = SPECIAL_HALT_TARGET,
1851 [4] = SPECIAL_POWEROFF_TARGET,
1852 [5] = SPECIAL_REBOOT_TARGET,
1853 [6] = SPECIAL_KEXEC_TARGET
1854 };
1855
1856 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
1857 static const ManagerExitCode code_table[] = {
1858 [0] = MANAGER_HALT,
1859 [1] = MANAGER_POWEROFF,
1860 [2] = MANAGER_REBOOT,
1861 [3] = MANAGER_KEXEC
1862 };
1863
1864 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1865 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
1866 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
1867 manager_start_target(m, target_table[idx],
1868 (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
1869 break;
1870 }
1871
1872 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
1873 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
1874 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
1875 break;
1876 }
1877
1878 switch (sfsi.ssi_signo - SIGRTMIN) {
1879
1880 case 20:
1881 manager_set_show_status(m, SHOW_STATUS_YES);
1882 break;
1883
1884 case 21:
1885 manager_set_show_status(m, SHOW_STATUS_NO);
1886 break;
1887
1888 case 22:
1889 log_set_max_level(LOG_DEBUG);
1890 log_info("Setting log level to debug.");
1891 break;
1892
1893 case 23:
1894 log_set_max_level(LOG_INFO);
1895 log_info("Setting log level to info.");
1896 break;
1897
1898 case 24:
1899 if (MANAGER_IS_USER(m)) {
1900 m->exit_code = MANAGER_EXIT;
1901 return 0;
1902 }
1903
1904 /* This is a nop on init */
1905 break;
1906
1907 case 26:
1908 case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
1909 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1910 log_notice("Setting log target to journal-or-kmsg.");
1911 break;
1912
1913 case 27:
1914 log_set_target(LOG_TARGET_CONSOLE);
1915 log_notice("Setting log target to console.");
1916 break;
1917
1918 case 28:
1919 log_set_target(LOG_TARGET_KMSG);
1920 log_notice("Setting log target to kmsg.");
1921 break;
1922
1923 default:
1924 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
1925 }
1926 }
1927 }
1928 }
1929
1930 if (sigchld)
1931 manager_dispatch_sigchld(m);
1932
1933 return 0;
1934 }
1935
1936 static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1937 Manager *m = userdata;
1938 Iterator i;
1939 Unit *u;
1940
1941 assert(m);
1942 assert(m->time_change_fd == fd);
1943
1944 log_struct(LOG_INFO,
1945 LOG_MESSAGE_ID(SD_MESSAGE_TIME_CHANGE),
1946 LOG_MESSAGE("Time has been changed"),
1947 NULL);
1948
1949 /* Restart the watch */
1950 m->time_change_event_source = sd_event_source_unref(m->time_change_event_source);
1951 m->time_change_fd = safe_close(m->time_change_fd);
1952
1953 manager_setup_time_change(m);
1954
1955 HASHMAP_FOREACH(u, m->units, i)
1956 if (UNIT_VTABLE(u)->time_change)
1957 UNIT_VTABLE(u)->time_change(u);
1958
1959 return 0;
1960 }
1961
1962 static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1963 Manager *m = userdata;
1964
1965 assert(m);
1966 assert(m->idle_pipe[2] == fd);
1967
1968 m->no_console_output = m->n_on_console > 0;
1969
1970 manager_close_idle_pipe(m);
1971
1972 return 0;
1973 }
1974
1975 static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
1976 Manager *m = userdata;
1977 int r;
1978 uint64_t next;
1979
1980 assert(m);
1981 assert(source);
1982
1983 manager_print_jobs_in_progress(m);
1984
1985 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_PERIOD_USEC;
1986 r = sd_event_source_set_time(source, next);
1987 if (r < 0)
1988 return r;
1989
1990 return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
1991 }
1992
1993 int manager_loop(Manager *m) {
1994 int r;
1995
1996 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
1997
1998 assert(m);
1999 m->exit_code = MANAGER_OK;
2000
2001 /* Release the path cache */
2002 m->unit_path_cache = set_free_free(m->unit_path_cache);
2003
2004 manager_check_finished(m);
2005
2006 /* There might still be some zombies hanging around from
2007 * before we were exec()'ed. Let's reap them. */
2008 r = manager_dispatch_sigchld(m);
2009 if (r < 0)
2010 return r;
2011
2012 while (m->exit_code == MANAGER_OK) {
2013 usec_t wait_usec;
2014
2015 if (m->runtime_watchdog > 0 && m->runtime_watchdog != USEC_INFINITY && MANAGER_IS_SYSTEM(m))
2016 watchdog_ping();
2017
2018 if (!ratelimit_test(&rl)) {
2019 /* Yay, something is going seriously wrong, pause a little */
2020 log_warning("Looping too fast. Throttling execution a little.");
2021 sleep(1);
2022 }
2023
2024 if (manager_dispatch_load_queue(m) > 0)
2025 continue;
2026
2027 if (manager_dispatch_gc_queue(m) > 0)
2028 continue;
2029
2030 if (manager_dispatch_cleanup_queue(m) > 0)
2031 continue;
2032
2033 if (manager_dispatch_cgroup_queue(m) > 0)
2034 continue;
2035
2036 if (manager_dispatch_dbus_queue(m) > 0)
2037 continue;
2038
2039 /* Sleep for half the watchdog time */
2040 if (m->runtime_watchdog > 0 && m->runtime_watchdog != USEC_INFINITY && MANAGER_IS_SYSTEM(m)) {
2041 wait_usec = m->runtime_watchdog / 2;
2042 if (wait_usec <= 0)
2043 wait_usec = 1;
2044 } else
2045 wait_usec = USEC_INFINITY;
2046
2047 r = sd_event_run(m->event, wait_usec);
2048 if (r < 0)
2049 return log_error_errno(r, "Failed to run event loop: %m");
2050 }
2051
2052 return m->exit_code;
2053 }
2054
2055 int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
2056 _cleanup_free_ char *n = NULL;
2057 Unit *u;
2058 int r;
2059
2060 assert(m);
2061 assert(s);
2062 assert(_u);
2063
2064 r = unit_name_from_dbus_path(s, &n);
2065 if (r < 0)
2066 return r;
2067
2068 r = manager_load_unit(m, n, NULL, e, &u);
2069 if (r < 0)
2070 return r;
2071
2072 *_u = u;
2073
2074 return 0;
2075 }
2076
2077 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2078 const char *p;
2079 unsigned id;
2080 Job *j;
2081 int r;
2082
2083 assert(m);
2084 assert(s);
2085 assert(_j);
2086
2087 p = startswith(s, "/org/freedesktop/systemd1/job/");
2088 if (!p)
2089 return -EINVAL;
2090
2091 r = safe_atou(p, &id);
2092 if (r < 0)
2093 return r;
2094
2095 j = manager_get_job(m, id);
2096 if (!j)
2097 return -ENOENT;
2098
2099 *_j = j;
2100
2101 return 0;
2102 }
2103
2104 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2105
2106 #ifdef HAVE_AUDIT
2107 _cleanup_free_ char *p = NULL;
2108 const char *msg;
2109 int audit_fd, r;
2110
2111 if (!MANAGER_IS_SYSTEM(m))
2112 return;
2113
2114 audit_fd = get_audit_fd();
2115 if (audit_fd < 0)
2116 return;
2117
2118 /* Don't generate audit events if the service was already
2119 * started and we're just deserializing */
2120 if (MANAGER_IS_RELOADING(m))
2121 return;
2122
2123 if (u->type != UNIT_SERVICE)
2124 return;
2125
2126 r = unit_name_to_prefix_and_instance(u->id, &p);
2127 if (r < 0) {
2128 log_error_errno(r, "Failed to extract prefix and instance of unit name: %m");
2129 return;
2130 }
2131
2132 msg = strjoina("unit=", p);
2133 if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
2134 if (errno == EPERM)
2135 /* We aren't allowed to send audit messages?
2136 * Then let's not retry again. */
2137 close_audit_fd();
2138 else
2139 log_warning_errno(errno, "Failed to send audit message: %m");
2140 }
2141 #endif
2142
2143 }
2144
2145 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2146 union sockaddr_union sa = PLYMOUTH_SOCKET;
2147
2148 int n = 0;
2149 _cleanup_free_ char *message = NULL;
2150 _cleanup_close_ int fd = -1;
2151
2152 /* Don't generate plymouth events if the service was already
2153 * started and we're just deserializing */
2154 if (MANAGER_IS_RELOADING(m))
2155 return;
2156
2157 if (!MANAGER_IS_SYSTEM(m))
2158 return;
2159
2160 if (detect_container() > 0)
2161 return;
2162
2163 if (u->type != UNIT_SERVICE &&
2164 u->type != UNIT_MOUNT &&
2165 u->type != UNIT_SWAP)
2166 return;
2167
2168 /* We set SOCK_NONBLOCK here so that we rather drop the
2169 * message then wait for plymouth */
2170 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2171 if (fd < 0) {
2172 log_error_errno(errno, "socket() failed: %m");
2173 return;
2174 }
2175
2176 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
2177
2178 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
2179 log_error_errno(errno, "connect() failed: %m");
2180 return;
2181 }
2182
2183 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
2184 log_oom();
2185 return;
2186 }
2187
2188 errno = 0;
2189 if (write(fd, message, n + 1) != n + 1)
2190 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
2191 log_error_errno(errno, "Failed to write Plymouth message: %m");
2192 }
2193
2194 int manager_open_serialization(Manager *m, FILE **_f) {
2195 const char *path;
2196 int fd = -1;
2197 FILE *f;
2198
2199 assert(_f);
2200
2201 path = MANAGER_IS_SYSTEM(m) ? "/run/systemd" : "/tmp";
2202 fd = open_tmpfile(path, O_RDWR|O_CLOEXEC);
2203 if (fd < 0)
2204 return -errno;
2205
2206 log_debug("Serializing state to %s", path);
2207
2208 f = fdopen(fd, "w+");
2209 if (!f) {
2210 safe_close(fd);
2211 return -errno;
2212 }
2213
2214 *_f = f;
2215
2216 return 0;
2217 }
2218
2219 int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root) {
2220 Iterator i;
2221 Unit *u;
2222 const char *t;
2223 char **e;
2224 int r;
2225
2226 assert(m);
2227 assert(f);
2228 assert(fds);
2229
2230 m->n_reloading++;
2231
2232 fprintf(f, "current-job-id=%"PRIu32"\n", m->current_job_id);
2233 fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
2234 fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
2235 fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
2236
2237 dual_timestamp_serialize(f, "firmware-timestamp", &m->firmware_timestamp);
2238 dual_timestamp_serialize(f, "loader-timestamp", &m->loader_timestamp);
2239 dual_timestamp_serialize(f, "kernel-timestamp", &m->kernel_timestamp);
2240 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2241
2242 if (!in_initrd()) {
2243 dual_timestamp_serialize(f, "userspace-timestamp", &m->userspace_timestamp);
2244 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2245 dual_timestamp_serialize(f, "security-start-timestamp", &m->security_start_timestamp);
2246 dual_timestamp_serialize(f, "security-finish-timestamp", &m->security_finish_timestamp);
2247 dual_timestamp_serialize(f, "generators-start-timestamp", &m->generators_start_timestamp);
2248 dual_timestamp_serialize(f, "generators-finish-timestamp", &m->generators_finish_timestamp);
2249 dual_timestamp_serialize(f, "units-load-start-timestamp", &m->units_load_start_timestamp);
2250 dual_timestamp_serialize(f, "units-load-finish-timestamp", &m->units_load_finish_timestamp);
2251 }
2252
2253 if (!switching_root) {
2254 STRV_FOREACH(e, m->environment) {
2255 _cleanup_free_ char *ce;
2256
2257 ce = cescape(*e);
2258 if (!ce)
2259 return -ENOMEM;
2260
2261 fprintf(f, "env=%s\n", *e);
2262 }
2263 }
2264
2265 if (m->notify_fd >= 0) {
2266 int copy;
2267
2268 copy = fdset_put_dup(fds, m->notify_fd);
2269 if (copy < 0)
2270 return copy;
2271
2272 fprintf(f, "notify-fd=%i\n", copy);
2273 fprintf(f, "notify-socket=%s\n", m->notify_socket);
2274 }
2275
2276 if (m->kdbus_fd >= 0) {
2277 int copy;
2278
2279 copy = fdset_put_dup(fds, m->kdbus_fd);
2280 if (copy < 0)
2281 return copy;
2282
2283 fprintf(f, "kdbus-fd=%i\n", copy);
2284 }
2285
2286 bus_track_serialize(m->subscribed, f);
2287
2288 fputc('\n', f);
2289
2290 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2291 if (u->id != t)
2292 continue;
2293
2294 /* Start marker */
2295 fputs(u->id, f);
2296 fputc('\n', f);
2297
2298 r = unit_serialize(u, f, fds, !switching_root);
2299 if (r < 0) {
2300 m->n_reloading--;
2301 return r;
2302 }
2303 }
2304
2305 assert(m->n_reloading > 0);
2306 m->n_reloading--;
2307
2308 if (ferror(f))
2309 return -EIO;
2310
2311 r = bus_fdset_add_all(m, fds);
2312 if (r < 0)
2313 return r;
2314
2315 return 0;
2316 }
2317
2318 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2319 int r = 0;
2320
2321 assert(m);
2322 assert(f);
2323
2324 log_debug("Deserializing state...");
2325
2326 m->n_reloading++;
2327
2328 for (;;) {
2329 char line[LINE_MAX], *l;
2330
2331 if (!fgets(line, sizeof(line), f)) {
2332 if (feof(f))
2333 r = 0;
2334 else
2335 r = -errno;
2336
2337 goto finish;
2338 }
2339
2340 char_array_0(line);
2341 l = strstrip(line);
2342
2343 if (l[0] == 0)
2344 break;
2345
2346 if (startswith(l, "current-job-id=")) {
2347 uint32_t id;
2348
2349 if (safe_atou32(l+15, &id) < 0)
2350 log_debug("Failed to parse current job id value %s", l+15);
2351 else
2352 m->current_job_id = MAX(m->current_job_id, id);
2353
2354 } else if (startswith(l, "n-installed-jobs=")) {
2355 uint32_t n;
2356
2357 if (safe_atou32(l+17, &n) < 0)
2358 log_debug("Failed to parse installed jobs counter %s", l+17);
2359 else
2360 m->n_installed_jobs += n;
2361
2362 } else if (startswith(l, "n-failed-jobs=")) {
2363 uint32_t n;
2364
2365 if (safe_atou32(l+14, &n) < 0)
2366 log_debug("Failed to parse failed jobs counter %s", l+14);
2367 else
2368 m->n_failed_jobs += n;
2369
2370 } else if (startswith(l, "taint-usr=")) {
2371 int b;
2372
2373 b = parse_boolean(l+10);
2374 if (b < 0)
2375 log_debug("Failed to parse taint /usr flag %s", l+10);
2376 else
2377 m->taint_usr = m->taint_usr || b;
2378
2379 } else if (startswith(l, "firmware-timestamp="))
2380 dual_timestamp_deserialize(l+19, &m->firmware_timestamp);
2381 else if (startswith(l, "loader-timestamp="))
2382 dual_timestamp_deserialize(l+17, &m->loader_timestamp);
2383 else if (startswith(l, "kernel-timestamp="))
2384 dual_timestamp_deserialize(l+17, &m->kernel_timestamp);
2385 else if (startswith(l, "initrd-timestamp="))
2386 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2387 else if (startswith(l, "userspace-timestamp="))
2388 dual_timestamp_deserialize(l+20, &m->userspace_timestamp);
2389 else if (startswith(l, "finish-timestamp="))
2390 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2391 else if (startswith(l, "security-start-timestamp="))
2392 dual_timestamp_deserialize(l+25, &m->security_start_timestamp);
2393 else if (startswith(l, "security-finish-timestamp="))
2394 dual_timestamp_deserialize(l+26, &m->security_finish_timestamp);
2395 else if (startswith(l, "generators-start-timestamp="))
2396 dual_timestamp_deserialize(l+27, &m->generators_start_timestamp);
2397 else if (startswith(l, "generators-finish-timestamp="))
2398 dual_timestamp_deserialize(l+28, &m->generators_finish_timestamp);
2399 else if (startswith(l, "units-load-start-timestamp="))
2400 dual_timestamp_deserialize(l+27, &m->units_load_start_timestamp);
2401 else if (startswith(l, "units-load-finish-timestamp="))
2402 dual_timestamp_deserialize(l+28, &m->units_load_finish_timestamp);
2403 else if (startswith(l, "env=")) {
2404 _cleanup_free_ char *uce = NULL;
2405 char **e;
2406
2407 r = cunescape(l + 4, UNESCAPE_RELAX, &uce);
2408 if (r < 0)
2409 goto finish;
2410
2411 e = strv_env_set(m->environment, uce);
2412 if (!e) {
2413 r = -ENOMEM;
2414 goto finish;
2415 }
2416
2417 strv_free(m->environment);
2418 m->environment = e;
2419
2420 } else if (startswith(l, "notify-fd=")) {
2421 int fd;
2422
2423 if (safe_atoi(l + 10, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2424 log_debug("Failed to parse notify fd: %s", l + 10);
2425 else {
2426 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
2427 safe_close(m->notify_fd);
2428 m->notify_fd = fdset_remove(fds, fd);
2429 }
2430
2431 } else if (startswith(l, "notify-socket=")) {
2432 char *n;
2433
2434 n = strdup(l+14);
2435 if (!n) {
2436 r = -ENOMEM;
2437 goto finish;
2438 }
2439
2440 free(m->notify_socket);
2441 m->notify_socket = n;
2442
2443 } else if (startswith(l, "kdbus-fd=")) {
2444 int fd;
2445
2446 if (safe_atoi(l + 9, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
2447 log_debug("Failed to parse kdbus fd: %s", l + 9);
2448 else {
2449 safe_close(m->kdbus_fd);
2450 m->kdbus_fd = fdset_remove(fds, fd);
2451 }
2452
2453 } else {
2454 int k;
2455
2456 k = bus_track_deserialize_item(&m->deserialized_subscribed, l);
2457 if (k < 0)
2458 log_debug_errno(k, "Failed to deserialize bus tracker object: %m");
2459 else if (k == 0)
2460 log_debug("Unknown serialization item '%s'", l);
2461 }
2462 }
2463
2464 for (;;) {
2465 Unit *u;
2466 char name[UNIT_NAME_MAX+2];
2467
2468 /* Start marker */
2469 if (!fgets(name, sizeof(name), f)) {
2470 if (feof(f))
2471 r = 0;
2472 else
2473 r = -errno;
2474
2475 goto finish;
2476 }
2477
2478 char_array_0(name);
2479
2480 r = manager_load_unit(m, strstrip(name), NULL, NULL, &u);
2481 if (r < 0)
2482 goto finish;
2483
2484 r = unit_deserialize(u, f, fds);
2485 if (r < 0)
2486 goto finish;
2487 }
2488
2489 finish:
2490 if (ferror(f))
2491 r = -EIO;
2492
2493 assert(m->n_reloading > 0);
2494 m->n_reloading--;
2495
2496 return r;
2497 }
2498
2499 int manager_reload(Manager *m) {
2500 int r, q;
2501 _cleanup_fclose_ FILE *f = NULL;
2502 _cleanup_fdset_free_ FDSet *fds = NULL;
2503
2504 assert(m);
2505
2506 r = manager_open_serialization(m, &f);
2507 if (r < 0)
2508 return r;
2509
2510 m->n_reloading++;
2511 bus_manager_send_reloading(m, true);
2512
2513 fds = fdset_new();
2514 if (!fds) {
2515 m->n_reloading--;
2516 return -ENOMEM;
2517 }
2518
2519 r = manager_serialize(m, f, fds, false);
2520 if (r < 0) {
2521 m->n_reloading--;
2522 return r;
2523 }
2524
2525 if (fseeko(f, 0, SEEK_SET) < 0) {
2526 m->n_reloading--;
2527 return -errno;
2528 }
2529
2530 /* From here on there is no way back. */
2531 manager_clear_jobs_and_units(m);
2532 manager_undo_generators(m);
2533 lookup_paths_free(&m->lookup_paths);
2534
2535 q = lookup_paths_init(&m->lookup_paths, m->unit_file_scope, NULL);
2536 if (q < 0 && r >= 0)
2537 r = q;
2538
2539 /* Find new unit paths */
2540 q = manager_run_generators(m);
2541 if (q < 0 && r >= 0)
2542 r = q;
2543
2544 lookup_paths_reduce(&m->lookup_paths);
2545 manager_build_unit_path_cache(m);
2546
2547 /* First, enumerate what we can from all config files */
2548 manager_enumerate(m);
2549
2550 /* Second, deserialize our stored data */
2551 q = manager_deserialize(m, f, fds);
2552 if (q < 0 && r >= 0)
2553 r = q;
2554
2555 fclose(f);
2556 f = NULL;
2557
2558 /* Re-register notify_fd as event source */
2559 q = manager_setup_notify(m);
2560 if (q < 0 && r >= 0)
2561 r = q;
2562
2563 /* Third, fire things up! */
2564 manager_coldplug(m);
2565
2566 /* Sync current state of bus names with our set of listening units */
2567 if (m->api_bus)
2568 manager_sync_bus_names(m, m->api_bus);
2569
2570 assert(m->n_reloading > 0);
2571 m->n_reloading--;
2572
2573 m->send_reloading_done = true;
2574
2575 return r;
2576 }
2577
2578 void manager_reset_failed(Manager *m) {
2579 Unit *u;
2580 Iterator i;
2581
2582 assert(m);
2583
2584 HASHMAP_FOREACH(u, m->units, i)
2585 unit_reset_failed(u);
2586 }
2587
2588 bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
2589 Unit *u;
2590
2591 assert(m);
2592 assert(name);
2593
2594 /* Returns true if the unit is inactive or going down */
2595 u = manager_get_unit(m, name);
2596 if (!u)
2597 return true;
2598
2599 return unit_inactive_or_pending(u);
2600 }
2601
2602 static void manager_notify_finished(Manager *m) {
2603 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2604 usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
2605
2606 if (m->test_run)
2607 return;
2608
2609 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
2610
2611 /* Note that m->kernel_usec.monotonic is always at 0,
2612 * and m->firmware_usec.monotonic and
2613 * m->loader_usec.monotonic should be considered
2614 * negative values. */
2615
2616 firmware_usec = m->firmware_timestamp.monotonic - m->loader_timestamp.monotonic;
2617 loader_usec = m->loader_timestamp.monotonic - m->kernel_timestamp.monotonic;
2618 userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
2619 total_usec = m->firmware_timestamp.monotonic + m->finish_timestamp.monotonic;
2620
2621 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
2622
2623 kernel_usec = m->initrd_timestamp.monotonic - m->kernel_timestamp.monotonic;
2624 initrd_usec = m->userspace_timestamp.monotonic - m->initrd_timestamp.monotonic;
2625
2626 log_struct(LOG_INFO,
2627 LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
2628 "KERNEL_USEC="USEC_FMT, kernel_usec,
2629 "INITRD_USEC="USEC_FMT, initrd_usec,
2630 "USERSPACE_USEC="USEC_FMT, userspace_usec,
2631 LOG_MESSAGE("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2632 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
2633 format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC),
2634 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
2635 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
2636 NULL);
2637 } else {
2638 kernel_usec = m->userspace_timestamp.monotonic - m->kernel_timestamp.monotonic;
2639 initrd_usec = 0;
2640
2641 log_struct(LOG_INFO,
2642 LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
2643 "KERNEL_USEC="USEC_FMT, kernel_usec,
2644 "USERSPACE_USEC="USEC_FMT, userspace_usec,
2645 LOG_MESSAGE("Startup finished in %s (kernel) + %s (userspace) = %s.",
2646 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
2647 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
2648 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
2649 NULL);
2650 }
2651 } else {
2652 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
2653 total_usec = userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
2654
2655 log_struct(LOG_INFO,
2656 LOG_MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
2657 "USERSPACE_USEC="USEC_FMT, userspace_usec,
2658 LOG_MESSAGE("Startup finished in %s.",
2659 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
2660 NULL);
2661 }
2662
2663 bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
2664
2665 sd_notifyf(false,
2666 "READY=1\n"
2667 "STATUS=Startup finished in %s.",
2668 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC));
2669 }
2670
2671 void manager_check_finished(Manager *m) {
2672 assert(m);
2673
2674 if (MANAGER_IS_RELOADING(m))
2675 return;
2676
2677 /* Verify that we are actually running currently. Initially
2678 * the exit code is set to invalid, and during operation it is
2679 * then set to MANAGER_OK */
2680 if (m->exit_code != MANAGER_OK)
2681 return;
2682
2683 if (hashmap_size(m->jobs) > 0) {
2684 if (m->jobs_in_progress_event_source)
2685 /* Ignore any failure, this is only for feedback */
2686 (void) sd_event_source_set_time(m->jobs_in_progress_event_source, now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC);
2687
2688 return;
2689 }
2690
2691 manager_flip_auto_status(m, false);
2692
2693 /* Notify Type=idle units that we are done now */
2694 manager_close_idle_pipe(m);
2695
2696 /* Turn off confirm spawn now */
2697 m->confirm_spawn = false;
2698
2699 /* No need to update ask password status when we're going non-interactive */
2700 manager_close_ask_password(m);
2701
2702 /* This is no longer the first boot */
2703 manager_set_first_boot(m, false);
2704
2705 if (dual_timestamp_is_set(&m->finish_timestamp))
2706 return;
2707
2708 dual_timestamp_get(&m->finish_timestamp);
2709
2710 manager_notify_finished(m);
2711
2712 manager_invalidate_startup_units(m);
2713 }
2714
2715 static int manager_run_generators(Manager *m) {
2716 _cleanup_strv_free_ char **paths = NULL;
2717 const char *argv[5];
2718 char **path;
2719 int r;
2720
2721 assert(m);
2722
2723 if (m->test_run)
2724 return 0;
2725
2726 paths = generator_paths(m->unit_file_scope);
2727 if (!paths)
2728 return log_oom();
2729
2730 /* Optimize by skipping the whole process by not creating output directories
2731 * if no generators are found. */
2732 STRV_FOREACH(path, paths) {
2733 if (access(*path, F_OK) >= 0)
2734 goto found;
2735 if (errno != ENOENT)
2736 log_warning_errno(errno, "Failed to open generator directory %s: %m", *path);
2737 }
2738
2739 return 0;
2740
2741 found:
2742 r = lookup_paths_mkdir_generator(&m->lookup_paths);
2743 if (r < 0)
2744 goto finish;
2745
2746 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2747 argv[1] = m->lookup_paths.generator;
2748 argv[2] = m->lookup_paths.generator_early;
2749 argv[3] = m->lookup_paths.generator_late;
2750 argv[4] = NULL;
2751
2752 RUN_WITH_UMASK(0022)
2753 execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC, (char**) argv);
2754
2755 finish:
2756 lookup_paths_trim_generator(&m->lookup_paths);
2757 return r;
2758 }
2759
2760 static void manager_undo_generators(Manager *m) {
2761 assert(m);
2762
2763 if (m->lookup_paths.generator)
2764 (void) rm_rf(m->lookup_paths.generator, REMOVE_ROOT);
2765 if (m->lookup_paths.generator_early)
2766 (void) rm_rf(m->lookup_paths.generator_early, REMOVE_ROOT);
2767 if (m->lookup_paths.generator_late)
2768 (void) rm_rf(m->lookup_paths.generator_late, REMOVE_ROOT);
2769 }
2770
2771 int manager_environment_add(Manager *m, char **minus, char **plus) {
2772 char **a = NULL, **b = NULL, **l;
2773 assert(m);
2774
2775 l = m->environment;
2776
2777 if (!strv_isempty(minus)) {
2778 a = strv_env_delete(l, 1, minus);
2779 if (!a)
2780 return -ENOMEM;
2781
2782 l = a;
2783 }
2784
2785 if (!strv_isempty(plus)) {
2786 b = strv_env_merge(2, l, plus);
2787 if (!b) {
2788 strv_free(a);
2789 return -ENOMEM;
2790 }
2791
2792 l = b;
2793 }
2794
2795 if (m->environment != l)
2796 strv_free(m->environment);
2797 if (a != l)
2798 strv_free(a);
2799 if (b != l)
2800 strv_free(b);
2801
2802 m->environment = l;
2803 manager_clean_environment(m);
2804 strv_sort(m->environment);
2805
2806 return 0;
2807 }
2808
2809 int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
2810 int i;
2811
2812 assert(m);
2813
2814 for (i = 0; i < _RLIMIT_MAX; i++) {
2815 m->rlimit[i] = mfree(m->rlimit[i]);
2816
2817 if (!default_rlimit[i])
2818 continue;
2819
2820 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
2821 if (!m->rlimit[i])
2822 return -ENOMEM;
2823 }
2824
2825 return 0;
2826 }
2827
2828 void manager_recheck_journal(Manager *m) {
2829 Unit *u;
2830
2831 assert(m);
2832
2833 if (!MANAGER_IS_SYSTEM(m))
2834 return;
2835
2836 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
2837 if (u && SOCKET(u)->state != SOCKET_RUNNING) {
2838 log_close_journal();
2839 return;
2840 }
2841
2842 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
2843 if (u && SERVICE(u)->state != SERVICE_RUNNING) {
2844 log_close_journal();
2845 return;
2846 }
2847
2848 /* Hmm, OK, so the socket is fully up and the service is up
2849 * too, then let's make use of the thing. */
2850 log_open();
2851 }
2852
2853 void manager_set_show_status(Manager *m, ShowStatus mode) {
2854 assert(m);
2855 assert(IN_SET(mode, SHOW_STATUS_AUTO, SHOW_STATUS_NO, SHOW_STATUS_YES, SHOW_STATUS_TEMPORARY));
2856
2857 if (!MANAGER_IS_SYSTEM(m))
2858 return;
2859
2860 if (m->show_status != mode)
2861 log_debug("%s showing of status.",
2862 mode == SHOW_STATUS_NO ? "Disabling" : "Enabling");
2863 m->show_status = mode;
2864
2865 if (mode > 0)
2866 (void) touch("/run/systemd/show-status");
2867 else
2868 (void) unlink("/run/systemd/show-status");
2869 }
2870
2871 static bool manager_get_show_status(Manager *m, StatusType type) {
2872 assert(m);
2873
2874 if (!MANAGER_IS_SYSTEM(m))
2875 return false;
2876
2877 if (m->no_console_output)
2878 return false;
2879
2880 if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
2881 return false;
2882
2883 /* If we cannot find out the status properly, just proceed. */
2884 if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
2885 return false;
2886
2887 if (m->show_status > 0)
2888 return true;
2889
2890 return false;
2891 }
2892
2893 void manager_set_first_boot(Manager *m, bool b) {
2894 assert(m);
2895
2896 if (!MANAGER_IS_SYSTEM(m))
2897 return;
2898
2899 if (m->first_boot != (int) b) {
2900 if (b)
2901 (void) touch("/run/systemd/first-boot");
2902 else
2903 (void) unlink("/run/systemd/first-boot");
2904 }
2905
2906 m->first_boot = b;
2907 }
2908
2909 void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
2910 va_list ap;
2911
2912 /* If m is NULL, assume we're after shutdown and let the messages through. */
2913
2914 if (m && !manager_get_show_status(m, type))
2915 return;
2916
2917 /* XXX We should totally drop the check for ephemeral here
2918 * and thus effectively make 'Type=idle' pointless. */
2919 if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
2920 return;
2921
2922 va_start(ap, format);
2923 status_vprintf(status, true, type == STATUS_TYPE_EPHEMERAL, format, ap);
2924 va_end(ap);
2925 }
2926
2927 Set *manager_get_units_requiring_mounts_for(Manager *m, const char *path) {
2928 char p[strlen(path)+1];
2929
2930 assert(m);
2931 assert(path);
2932
2933 strcpy(p, path);
2934 path_kill_slashes(p);
2935
2936 return hashmap_get(m->units_requiring_mounts_for, streq(p, "/") ? "" : p);
2937 }
2938
2939 const char *manager_get_runtime_prefix(Manager *m) {
2940 assert(m);
2941
2942 return MANAGER_IS_SYSTEM(m) ?
2943 "/run" :
2944 getenv("XDG_RUNTIME_DIR");
2945 }
2946
2947 int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
2948 unsigned size;
2949 int r;
2950
2951 assert(m);
2952 assert(u->manager == m);
2953
2954 size = set_size(m->failed_units);
2955
2956 if (failed) {
2957 r = set_ensure_allocated(&m->failed_units, NULL);
2958 if (r < 0)
2959 return log_oom();
2960
2961 if (set_put(m->failed_units, u) < 0)
2962 return log_oom();
2963 } else
2964 (void) set_remove(m->failed_units, u);
2965
2966 if (set_size(m->failed_units) != size)
2967 bus_manager_send_change_signal(m);
2968
2969 return 0;
2970 }
2971
2972 ManagerState manager_state(Manager *m) {
2973 Unit *u;
2974
2975 assert(m);
2976
2977 /* Did we ever finish booting? If not then we are still starting up */
2978 if (!dual_timestamp_is_set(&m->finish_timestamp)) {
2979
2980 u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
2981 if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
2982 return MANAGER_INITIALIZING;
2983
2984 return MANAGER_STARTING;
2985 }
2986
2987 /* Is the special shutdown target queued? If so, we are in shutdown state */
2988 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2989 if (u && u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_RELOAD_OR_START))
2990 return MANAGER_STOPPING;
2991
2992 /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
2993 u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
2994 if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
2995 (u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_RELOAD_OR_START))))
2996 return MANAGER_MAINTENANCE;
2997
2998 u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
2999 if (u && (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)) ||
3000 (u->job && IN_SET(u->job->type, JOB_START, JOB_RESTART, JOB_RELOAD_OR_START))))
3001 return MANAGER_MAINTENANCE;
3002
3003 /* Are there any failed units? If so, we are in degraded mode */
3004 if (set_size(m->failed_units) > 0)
3005 return MANAGER_DEGRADED;
3006
3007 return MANAGER_RUNNING;
3008 }
3009
3010 static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
3011 [MANAGER_INITIALIZING] = "initializing",
3012 [MANAGER_STARTING] = "starting",
3013 [MANAGER_RUNNING] = "running",
3014 [MANAGER_DEGRADED] = "degraded",
3015 [MANAGER_MAINTENANCE] = "maintenance",
3016 [MANAGER_STOPPING] = "stopping",
3017 };
3018
3019 DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);