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