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