]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/manager.c
manager: split out send_ready and basic.target checking into functions of their own
[thirdparty/systemd.git] / src / core / manager.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 15 Lesser General Public License for more details.
a7334b09 16
5430f7f2 17 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19***/
20
60918275 21#include <errno.h>
400f1a33
LP
22#include <fcntl.h>
23#include <linux/kd.h>
9152c765 24#include <signal.h>
713f6f90 25#include <stdio_ext.h>
400f1a33 26#include <string.h>
e46b13c8 27#include <sys/epoll.h>
400f1a33 28#include <sys/inotify.h>
e1414003 29#include <sys/ioctl.h>
400f1a33 30#include <sys/reboot.h>
8742514c 31#include <sys/timerfd.h>
400f1a33
LP
32#include <sys/wait.h>
33#include <unistd.h>
830f6caa 34
349cc4a5 35#if HAVE_AUDIT
4927fcae 36#include <libaudit.h>
830f6caa 37#endif
60918275 38
718db961 39#include "sd-daemon.h"
718db961 40#include "sd-messages.h"
3536f49e 41#include "sd-path.h"
81527be1 42
b5efdb8a 43#include "alloc-util.h"
400f1a33
LP
44#include "audit-fd.h"
45#include "boot-timestamps.h"
46#include "bus-common-errors.h"
47#include "bus-error.h"
48#include "bus-kernel.h"
49#include "bus-util.h"
00d9ef85 50#include "clean-ipc.h"
af6b0ecc 51#include "clock-util.h"
400f1a33
LP
52#include "dbus-job.h"
53#include "dbus-manager.h"
54#include "dbus-unit.h"
55#include "dbus.h"
d063a527 56#include "dirent-util.h"
400f1a33 57#include "env-util.h"
4f5dd394 58#include "escape.h"
89711996 59#include "exec-util.h"
d3070fbd 60#include "execute.h"
400f1a33 61#include "exit-status.h"
3ffd4af2 62#include "fd-util.h"
0d39fa9c 63#include "fileio.h"
f4f15635 64#include "fs-util.h"
60918275 65#include "hashmap.h"
c004493c 66#include "io-util.h"
d3070fbd 67#include "label.h"
400f1a33 68#include "locale-setup.h"
16354eff 69#include "log.h"
400f1a33 70#include "macro.h"
3ffd4af2 71#include "manager.h"
400f1a33 72#include "missing.h"
49e942b2 73#include "mkdir.h"
6bedfcbb 74#include "parse-util.h"
400f1a33
LP
75#include "path-lookup.h"
76#include "path-util.h"
77#include "process-util.h"
ea430986 78#include "ratelimit.h"
c6878637 79#include "rm-rf.h"
400f1a33 80#include "signal-util.h"
514f4ef5 81#include "special.h"
8fcde012 82#include "stat-util.h"
8b43440b 83#include "string-table.h"
07630cea 84#include "string-util.h"
400f1a33
LP
85#include "strv.h"
86#include "terminal-util.h"
87#include "time-util.h"
88#include "transaction.h"
affb60b1 89#include "umask-util.h"
400f1a33 90#include "unit-name.h"
00d9ef85 91#include "user-util.h"
400f1a33 92#include "util.h"
5dc4c17f 93#include "virt.h"
e96d6be7 94#include "watchdog.h"
60918275 95
a47806fa 96#define NOTIFY_RCVBUF_SIZE (8*1024*1024)
d8fdc620 97#define CGROUPS_AGENT_RCVBUF_SIZE (8*1024*1024)
a47806fa 98
03b717a3 99/* Initial delay and the interval for printing status messages about running jobs */
fd08a840
ZJS
100#define JOBS_IN_PROGRESS_WAIT_USEC (5*USEC_PER_SEC)
101#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
03b717a3
MS
102#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
103
718db961 104static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
d8fdc620 105static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
718db961
LP
106static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
107static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
108static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
00d9ef85 109static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
718db961 110static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
752b5905 111static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
64691d20 112static int manager_run_environment_generators(Manager *m);
e801700e 113static int manager_run_generators(Manager *m);
718db961 114
2ae56591 115static void manager_watch_jobs_in_progress(Manager *m) {
e5723c89 116 usec_t next;
cfa9677b 117 int r;
e5723c89 118
718db961 119 assert(m);
03b717a3 120
42bf1ae1
FB
121 /* We do not want to show the cylon animation if the user
122 * needs to confirm service executions otherwise confirmation
123 * messages will be screwed by the cylon animation. */
b0eb2944 124 if (!manager_is_confirm_spawn_disabled(m))
42bf1ae1
FB
125 return;
126
718db961 127 if (m->jobs_in_progress_event_source)
2ae56591 128 return;
03b717a3 129
e5723c89 130 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC;
cfa9677b 131 r = sd_event_add_time(
6a0f1f6d
LP
132 m->event,
133 &m->jobs_in_progress_event_source,
134 CLOCK_MONOTONIC,
135 next, 0,
136 manager_dispatch_jobs_in_progress, m);
cfa9677b
MM
137 if (r < 0)
138 return;
7dfbe2e3
TG
139
140 (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
03b717a3
MS
141}
142
fbd0b64f 143#define CYLON_BUFFER_EXTRA (2*STRLEN(ANSI_RED) + STRLEN(ANSI_HIGHLIGHT_RED) + 2*STRLEN(ANSI_NORMAL))
03b717a3 144
03b717a3
MS
145static void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
146 char *p = buffer;
147
148 assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
149 assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */
150
151 if (pos > 1) {
6282c859
MS
152 if (pos > 2)
153 p = mempset(p, ' ', pos-2);
64c3610b
FB
154 if (log_get_show_color())
155 p = stpcpy(p, ANSI_RED);
03b717a3
MS
156 *p++ = '*';
157 }
158
159 if (pos > 0 && pos <= width) {
64c3610b
FB
160 if (log_get_show_color())
161 p = stpcpy(p, ANSI_HIGHLIGHT_RED);
03b717a3
MS
162 *p++ = '*';
163 }
164
64c3610b
FB
165 if (log_get_show_color())
166 p = stpcpy(p, ANSI_NORMAL);
03b717a3
MS
167
168 if (pos < width) {
64c3610b
FB
169 if (log_get_show_color())
170 p = stpcpy(p, ANSI_RED);
03b717a3 171 *p++ = '*';
6282c859
MS
172 if (pos < width-1)
173 p = mempset(p, ' ', width-1-pos);
64c3610b
FB
174 if (log_get_show_color())
175 strcpy(p, ANSI_NORMAL);
03b717a3 176 }
03b717a3
MS
177}
178
cb8ccb22 179void manager_flip_auto_status(Manager *m, bool enable) {
f755e3b7
LP
180 assert(m);
181
cb8ccb22
ZJS
182 if (enable) {
183 if (m->show_status == SHOW_STATUS_AUTO)
184 manager_set_show_status(m, SHOW_STATUS_TEMPORARY);
185 } else {
186 if (m->show_status == SHOW_STATUS_TEMPORARY)
187 manager_set_show_status(m, SHOW_STATUS_AUTO);
188 }
189}
190
03b717a3 191static void manager_print_jobs_in_progress(Manager *m) {
718db961 192 _cleanup_free_ char *job_of_n = NULL;
03b717a3
MS
193 Iterator i;
194 Job *j;
03b717a3
MS
195 unsigned counter = 0, print_nr;
196 char cylon[6 + CYLON_BUFFER_EXTRA + 1];
197 unsigned cylon_pos;
8bb310c3
ZJS
198 char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit";
199 uint64_t x;
03b717a3 200
718db961 201 assert(m);
9c3349e2 202 assert(m->n_running_jobs > 0);
718db961 203
cb8ccb22 204 manager_flip_auto_status(m, true);
d450b6f2 205
03b717a3
MS
206 print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
207
208 HASHMAP_FOREACH(j, m->jobs, i)
209 if (j->state == JOB_RUNNING && counter++ == print_nr)
210 break;
211
e970a72e
MS
212 /* m->n_running_jobs must be consistent with the contents of m->jobs,
213 * so the above loop must have succeeded in finding j. */
214 assert(counter == print_nr + 1);
51d122af 215 assert(j);
5a82a91a 216
03b717a3
MS
217 cylon_pos = m->jobs_in_progress_iteration % 14;
218 if (cylon_pos >= 8)
219 cylon_pos = 14 - cylon_pos;
220 draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
221
8bb310c3
ZJS
222 m->jobs_in_progress_iteration++;
223
d6483ba7
ZJS
224 if (m->n_running_jobs > 1) {
225 if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
226 job_of_n = NULL;
227 }
03b717a3 228
8bb310c3
ZJS
229 format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
230 if (job_get_timeout(j, &x) > 0)
231 format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC);
232
127d5fd1 233 manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
8bb310c3
ZJS
234 "%sA %s job is running for %s (%s / %s)",
235 strempty(job_of_n),
236 job_type_to_string(j->type),
237 unit_description(j->unit),
238 time, limit);
03b717a3
MS
239}
240
e46b13c8
ZJS
241static int have_ask_password(void) {
242 _cleanup_closedir_ DIR *dir;
8fb3f009 243 struct dirent *de;
e46b13c8
ZJS
244
245 dir = opendir("/run/systemd/ask-password");
246 if (!dir) {
247 if (errno == ENOENT)
248 return false;
249 else
250 return -errno;
251 }
252
8fb3f009 253 FOREACH_DIRENT_ALL(de, dir, return -errno) {
e46b13c8
ZJS
254 if (startswith(de->d_name, "ask."))
255 return true;
256 }
8fb3f009 257 return false;
e46b13c8
ZJS
258}
259
260static int manager_dispatch_ask_password_fd(sd_event_source *source,
261 int fd, uint32_t revents, void *userdata) {
262 Manager *m = userdata;
263
264 assert(m);
265
665dfe93 266 (void) flush_fd(fd);
e46b13c8
ZJS
267
268 m->have_ask_password = have_ask_password();
269 if (m->have_ask_password < 0)
270 /* Log error but continue. Negative have_ask_password
271 * is treated as unknown status. */
c33b3297 272 log_error_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password: %m");
e46b13c8
ZJS
273
274 return 0;
275}
276
277static void manager_close_ask_password(Manager *m) {
278 assert(m);
279
e46b13c8 280 m->ask_password_event_source = sd_event_source_unref(m->ask_password_event_source);
90990e28 281 m->ask_password_inotify_fd = safe_close(m->ask_password_inotify_fd);
e46b13c8
ZJS
282 m->have_ask_password = -EINVAL;
283}
284
285static int manager_check_ask_password(Manager *m) {
286 int r;
287
288 assert(m);
289
290 if (!m->ask_password_event_source) {
291 assert(m->ask_password_inotify_fd < 0);
292
293 mkdir_p_label("/run/systemd/ask-password", 0755);
294
295 m->ask_password_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
4a62c710
MS
296 if (m->ask_password_inotify_fd < 0)
297 return log_error_errno(errno, "inotify_init1() failed: %m");
e46b13c8
ZJS
298
299 if (inotify_add_watch(m->ask_password_inotify_fd, "/run/systemd/ask-password", IN_CREATE|IN_DELETE|IN_MOVE) < 0) {
56f64d95 300 log_error_errno(errno, "Failed to add watch on /run/systemd/ask-password: %m");
e46b13c8
ZJS
301 manager_close_ask_password(m);
302 return -errno;
303 }
304
305 r = sd_event_add_io(m->event, &m->ask_password_event_source,
306 m->ask_password_inotify_fd, EPOLLIN,
307 manager_dispatch_ask_password_fd, m);
308 if (r < 0) {
56f64d95 309 log_error_errno(errno, "Failed to add event source for /run/systemd/ask-password: %m");
e46b13c8
ZJS
310 manager_close_ask_password(m);
311 return -errno;
312 }
313
7dfbe2e3
TG
314 (void) sd_event_source_set_description(m->ask_password_event_source, "manager-ask-password");
315
e46b13c8
ZJS
316 /* Queries might have been added meanwhile... */
317 manager_dispatch_ask_password_fd(m->ask_password_event_source,
318 m->ask_password_inotify_fd, EPOLLIN, m);
319 }
320
321 return m->have_ask_password;
322}
323
31a7eb86 324static int manager_watch_idle_pipe(Manager *m) {
31a7eb86
ZJS
325 int r;
326
718db961
LP
327 assert(m);
328
329 if (m->idle_pipe_event_source)
31a7eb86
ZJS
330 return 0;
331
332 if (m->idle_pipe[2] < 0)
333 return 0;
334
151b9b96 335 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
336 if (r < 0)
337 return log_error_errno(r, "Failed to watch idle pipe: %m");
31a7eb86 338
7dfbe2e3
TG
339 (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
340
31a7eb86 341 return 0;
31a7eb86
ZJS
342}
343
718db961
LP
344static void manager_close_idle_pipe(Manager *m) {
345 assert(m);
31a7eb86 346
cd72bd8a
LP
347 m->idle_pipe_event_source = sd_event_source_unref(m->idle_pipe_event_source);
348
3d94f76c
LP
349 safe_close_pair(m->idle_pipe);
350 safe_close_pair(m->idle_pipe + 2);
31a7eb86
ZJS
351}
352
8742514c 353static int manager_setup_time_change(Manager *m) {
718db961 354 int r;
b92bea5d
ZJS
355
356 /* We only care for the cancellation event, hence we set the
357 * timeout to the latest possible value. */
358 struct itimerspec its = {
359 .it_value.tv_sec = TIME_T_MAX,
360 };
8742514c 361
718db961
LP
362 assert(m);
363 assert_cc(sizeof(time_t) == sizeof(TIME_T_MAX));
8742514c 364
e0a3da1f 365 if (m->test_run_flags)
0d8c31ff
ZJS
366 return 0;
367
8742514c
LP
368 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
369 * CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
370
718db961 371 m->time_change_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
4a62c710
MS
372 if (m->time_change_fd < 0)
373 return log_error_errno(errno, "Failed to create timerfd: %m");
8742514c 374
718db961 375 if (timerfd_settime(m->time_change_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
56f64d95 376 log_debug_errno(errno, "Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
03e334a1 377 m->time_change_fd = safe_close(m->time_change_fd);
8742514c
LP
378 return 0;
379 }
380
151b9b96 381 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
382 if (r < 0)
383 return log_error_errno(r, "Failed to create time change event source: %m");
8742514c 384
7dfbe2e3
TG
385 (void) sd_event_source_set_description(m->time_change_event_source, "manager-time-change");
386
8742514c
LP
387 log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
388
389 return 0;
390}
391
80876c20 392static int enable_special_signals(Manager *m) {
718db961 393 _cleanup_close_ int fd = -1;
80876c20
LP
394
395 assert(m);
396
e0a3da1f 397 if (m->test_run_flags)
37453b3a
EV
398 return 0;
399
a41b539e 400 /* Enable that we get SIGINT on control-alt-del. In containers
c9999773
LP
401 * this will fail with EPERM (older) or EINVAL (newer), so
402 * ignore that. */
4c701096 403 if (reboot(RB_DISABLE_CAD) < 0 && !IN_SET(errno, EPERM, EINVAL))
56f64d95 404 log_warning_errno(errno, "Failed to enable ctrl-alt-del handling: %m");
80876c20 405
a41b539e
LP
406 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
407 if (fd < 0) {
408 /* Support systems without virtual console */
409 if (fd != -ENOENT)
56f64d95 410 log_warning_errno(errno, "Failed to open /dev/tty0: %m");
a41b539e 411 } else {
80876c20
LP
412 /* Enable that we get SIGWINCH on kbrequest */
413 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
56f64d95 414 log_warning_errno(errno, "Failed to enable kbrequest handling: %m");
80876c20
LP
415 }
416
417 return 0;
418}
419
ce578209 420static int manager_setup_signals(Manager *m) {
b92bea5d
ZJS
421 struct sigaction sa = {
422 .sa_handler = SIG_DFL,
423 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
424 };
718db961
LP
425 sigset_t mask;
426 int r;
60918275 427
ce578209
LP
428 assert(m);
429
57c0c30e
LP
430 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
431
4dffec14
LP
432 /* We make liberal use of realtime signals here. On
433 * Linux/glibc we have 30 of them (with the exception of Linux
434 * on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
435 * (aka SIGRTMAX). */
7d793605 436
4dffec14 437 assert_se(sigemptyset(&mask) == 0);
7d793605
LP
438 sigset_add_many(&mask,
439 SIGCHLD, /* Child died */
440 SIGTERM, /* Reexecute daemon */
441 SIGHUP, /* Reload configuration */
442 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
443 SIGUSR2, /* systemd: dump status */
444 SIGINT, /* Kernel sends us this on control-alt-del */
445 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
446 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
4dffec14 447
7d793605 448 SIGRTMIN+0, /* systemd: start default.target */
0003d1ab 449 SIGRTMIN+1, /* systemd: isolate rescue.target */
7d793605
LP
450 SIGRTMIN+2, /* systemd: isolate emergency.target */
451 SIGRTMIN+3, /* systemd: start halt.target */
452 SIGRTMIN+4, /* systemd: start poweroff.target */
453 SIGRTMIN+5, /* systemd: start reboot.target */
0003d1ab 454 SIGRTMIN+6, /* systemd: start kexec.target */
4dffec14
LP
455
456 /* ... space for more special targets ... */
457
0003d1ab
LP
458 SIGRTMIN+13, /* systemd: Immediate halt */
459 SIGRTMIN+14, /* systemd: Immediate poweroff */
460 SIGRTMIN+15, /* systemd: Immediate reboot */
461 SIGRTMIN+16, /* systemd: Immediate kexec */
4dffec14
LP
462
463 /* ... space for more immediate system state changes ... */
464
0658666b
LP
465 SIGRTMIN+20, /* systemd: enable status messages */
466 SIGRTMIN+21, /* systemd: disable status messages */
253ee27a
LP
467 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
468 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
600b704e 469 SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
4dffec14
LP
470
471 /* .. one free signal here ... */
472
473#if !defined(__hppa64__) && !defined(__hppa__)
474 /* Apparently Linux on hppa has fewer RT
475 * signals (SIGRTMAX is SIGRTMIN+25 there),
476 * hence let's not try to make use of them
477 * here. Since these commands are accessible
478 * by different means and only really a safety
479 * net, the missing functionality on hppa
480 * shouldn't matter. */
481
4cfa2c99 482 SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
253ee27a
LP
483 SIGRTMIN+27, /* systemd: set log target to console */
484 SIGRTMIN+28, /* systemd: set log target to kmsg */
ee33e53a 485 SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg (obsolete) */
4dffec14
LP
486
487 /* ... one free signal here SIGRTMIN+30 ... */
488#endif
7d793605 489 -1);
ce578209
LP
490 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
491
718db961
LP
492 m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
493 if (m->signal_fd < 0)
ce578209
LP
494 return -errno;
495
151b9b96 496 r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
718db961
LP
497 if (r < 0)
498 return r;
ce578209 499
7dfbe2e3
TG
500 (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
501
d8fdc620
LP
502 /* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
503 * notify processing can still figure out to which process/service a message belongs, before we reap the
504 * process. Also, process this before handling cgroup notifications, so that we always collect child exit
505 * status information before detecting that there's no process in a cgroup. */
506 r = sd_event_source_set_priority(m->signal_event_source, SD_EVENT_PRIORITY_NORMAL-6);
29083707
LP
507 if (r < 0)
508 return r;
509
463d0d15 510 if (MANAGER_IS_SYSTEM(m))
80876c20 511 return enable_special_signals(m);
e1414003 512
ce578209
LP
513 return 0;
514}
515
47cf8ff2 516static void manager_sanitize_environment(Manager *m) {
f069efb4
LP
517 assert(m);
518
47cf8ff2 519 /* Let's remove some environment variables that we need ourselves to communicate with our clients */
f069efb4
LP
520 strv_env_unset_many(
521 m->environment,
47cf8ff2
LP
522 "EXIT_CODE",
523 "EXIT_STATUS",
524 "INVOCATION_ID",
525 "JOURNAL_STREAM",
526 "LISTEN_FDNAMES",
527 "LISTEN_FDS",
528 "LISTEN_PID",
f069efb4
LP
529 "MAINPID",
530 "MANAGERPID",
47cf8ff2
LP
531 "NOTIFY_SOCKET",
532 "REMOTE_ADDR",
533 "REMOTE_PORT",
534 "SERVICE_RESULT",
f069efb4
LP
535 "WATCHDOG_PID",
536 "WATCHDOG_USEC",
537 NULL);
47cf8ff2
LP
538
539 /* Let's order the environment alphabetically, just to make it pretty */
540 strv_sort(m->environment);
f069efb4
LP
541}
542
e21fea24 543static int manager_default_environment(Manager *m) {
71ecc858
LP
544 assert(m);
545
463d0d15 546 if (MANAGER_IS_SYSTEM(m)) {
e21fea24
KS
547 /* The system manager always starts with a clean
548 * environment for its children. It does not import
71cb7d30 549 * the kernel's or the parents' exported variables.
e21fea24 550 *
71cb7d30 551 * The initial passed environment is untouched to keep
e21fea24
KS
552 * /proc/self/environ valid; it is used for tagging
553 * the init process inside containers. */
43638332
ZJS
554 m->environment = strv_new("PATH=" DEFAULT_PATH,
555 NULL);
e21fea24
KS
556
557 /* Import locale variables LC_*= from configuration */
558 locale_setup(&m->environment);
71cb7d30 559 } else
e21fea24
KS
560 /* The user manager passes its own environment
561 * along to its children. */
562 m->environment = strv_copy(environ);
43d03a83 563
e21fea24
KS
564 if (!m->environment)
565 return -ENOMEM;
8b55b8c4 566
47cf8ff2 567 manager_sanitize_environment(m);
9d5a3757 568
e21fea24 569 return 0;
71ecc858
LP
570}
571
3536f49e
YW
572static int manager_setup_prefix(Manager *m) {
573 struct table_entry {
574 uint64_t type;
575 const char *suffix;
576 };
577
72fd1768 578 static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
579 [EXEC_DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME, NULL },
580 [EXEC_DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
581 [EXEC_DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE, NULL },
582 [EXEC_DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS, NULL },
583 [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
584 };
585
72fd1768 586 static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
3536f49e
YW
587 [EXEC_DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME, NULL },
588 [EXEC_DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION, NULL },
c6218495
LP
589 [EXEC_DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE, NULL },
590 [EXEC_DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
591 [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL },
3536f49e
YW
592 };
593
594 const struct table_entry *p;
595 ExecDirectoryType i;
596 int r;
597
598 assert(m);
599
600 if (MANAGER_IS_SYSTEM(m))
601 p = paths_system;
602 else
603 p = paths_user;
604
72fd1768 605 for (i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
3536f49e
YW
606 r = sd_path_home(p[i].type, p[i].suffix, &m->prefix[i]);
607 if (r < 0)
608 return r;
609 }
610
611 return 0;
612}
613
279d81dd
LP
614static int manager_setup_run_queue(Manager *m) {
615 int r;
616
617 assert(m);
618 assert(!m->run_queue_event_source);
619
620 r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
621 if (r < 0)
622 return r;
623
624 r = sd_event_source_set_priority(m->run_queue_event_source, SD_EVENT_PRIORITY_IDLE);
625 if (r < 0)
626 return r;
627
628 r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
629 if (r < 0)
630 return r;
631
632 (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
633
634 return 0;
635}
636
e0a3da1f 637int manager_new(UnitFileScope scope, unsigned test_run_flags, Manager **_m) {
ce578209 638 Manager *m;
e3dd987c 639 int r;
8e274523
LP
640
641 assert(_m);
463d0d15 642 assert(IN_SET(scope, UNIT_FILE_SYSTEM, UNIT_FILE_USER));
ce578209 643
915b3753
LP
644 m = new0(Manager, 1);
645 if (!m)
8e274523 646 return -ENOMEM;
60918275 647
463d0d15 648 m->unit_file_scope = scope;
a16e1123 649 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
bd8f585b 650 m->default_timer_accuracy_usec = USEC_PER_MINUTE;
9ded9cd1 651 m->default_tasks_accounting = true;
79baeeb9 652 m->default_tasks_max = UINT64_MAX;
bd389aa7
LP
653 m->default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
654 m->default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
655 m->default_restart_usec = DEFAULT_RESTART_USEC;
80876c20 656
349cc4a5 657#if ENABLE_EFI
463d0d15 658 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
9f9f0342
LP
659 boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
660 m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
661 m->timestamps + MANAGER_TIMESTAMP_LOADER);
463d0d15
LP
662#endif
663
f2341e0a 664 /* Prepare log fields we can use for structured logging */
463d0d15
LP
665 if (MANAGER_IS_SYSTEM(m)) {
666 m->unit_log_field = "UNIT=";
667 m->unit_log_format_string = "UNIT=%s";
4b58153d
LP
668
669 m->invocation_log_field = "INVOCATION_ID=";
f1c50bec 670 m->invocation_log_format_string = "INVOCATION_ID=%s";
463d0d15
LP
671 } else {
672 m->unit_log_field = "USER_UNIT=";
673 m->unit_log_format_string = "USER_UNIT=%s";
4b58153d
LP
674
675 m->invocation_log_field = "USER_INVOCATION_ID=";
f1c50bec 676 m->invocation_log_format_string = "USER_INVOCATION_ID=%s";
463d0d15 677 }
f2341e0a 678
718db961 679 m->idle_pipe[0] = m->idle_pipe[1] = m->idle_pipe[2] = m->idle_pipe[3] = -1;
8742514c 680
d8fdc620 681 m->pin_cgroupfs_fd = m->notify_fd = m->cgroups_agent_fd = m->signal_fd = m->time_change_fd =
232f6754 682 m->dev_autofs_fd = m->private_listen_fd = m->cgroup_inotify_fd =
d8fdc620 683 m->ask_password_inotify_fd = -1;
d379d442 684
00d9ef85
LP
685 m->user_lookup_fds[0] = m->user_lookup_fds[1] = -1;
686
ea430986 687 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
9152c765 688
e46b13c8 689 m->have_ask_password = -EINVAL; /* we don't know */
ae2a2c53 690 m->first_boot = -1;
e46b13c8 691
e0a3da1f 692 m->test_run_flags = test_run_flags;
0d8c31ff 693
2e5c94b9
LP
694 /* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
695 RATELIMIT_INIT(m->ctrl_alt_del_ratelimit, 2 * USEC_PER_SEC, 7);
696
e21fea24
KS
697 r = manager_default_environment(m);
698 if (r < 0)
1137a57c
LP
699 goto fail;
700
d5099efc 701 r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
718db961 702 if (r < 0)
60918275
LP
703 goto fail;
704
d5099efc 705 r = hashmap_ensure_allocated(&m->jobs, NULL);
718db961 706 if (r < 0)
60918275
LP
707 goto fail;
708
d5099efc 709 r = hashmap_ensure_allocated(&m->cgroup_unit, &string_hash_ops);
718db961 710 if (r < 0)
9152c765
LP
711 goto fail;
712
d5099efc 713 r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
718db961 714 if (r < 0)
05e343b7
LP
715 goto fail;
716
718db961
LP
717 r = sd_event_default(&m->event);
718 if (r < 0)
8742514c
LP
719 goto fail;
720
279d81dd 721 r = manager_setup_run_queue(m);
752b5905
LP
722 if (r < 0)
723 goto fail;
724
8742514c
LP
725 r = manager_setup_signals(m);
726 if (r < 0)
9152c765
LP
727 goto fail;
728
8742514c
LP
729 r = manager_setup_cgroup(m);
730 if (r < 0)
8e274523
LP
731 goto fail;
732
8742514c
LP
733 r = manager_setup_time_change(m);
734 if (r < 0)
8c47c732
LP
735 goto fail;
736
9670d583
LP
737 m->udev = udev_new();
738 if (!m->udev) {
739 r = -ENOMEM;
740 goto fail;
741 }
742
e27fe688
LP
743 r = manager_setup_prefix(m);
744 if (r < 0)
745 goto fail;
746
5eb397cf 747 if (MANAGER_IS_SYSTEM(m) && test_run_flags == 0) {
d3070fbd
LP
748 r = mkdir_label("/run/systemd/units", 0755);
749 if (r < 0 && r != -EEXIST)
750 goto fail;
751 }
752
e27fe688
LP
753 m->taint_usr =
754 !in_initrd() &&
755 dir_is_empty("/usr") > 0;
756
232f6754
ZJS
757 /* Note that we do not set up the notify fd here. We do that after deserialization,
758 * since they might have gotten serialized across the reexec. */
3536f49e 759
8e274523
LP
760 *_m = m;
761 return 0;
60918275
LP
762
763fail:
764 manager_free(m);
8e274523 765 return r;
60918275
LP
766}
767
d86f9d52 768static int manager_setup_notify(Manager *m) {
7181dbdb 769 int r;
d86f9d52 770
e0a3da1f 771 if (m->test_run_flags)
0d8c31ff
ZJS
772 return 0;
773
d86f9d52
LP
774 if (m->notify_fd < 0) {
775 _cleanup_close_ int fd = -1;
920b52e4 776 union sockaddr_union sa = {
7181dbdb
LP
777 .sa.sa_family = AF_UNIX,
778 };
55836941 779 static const int one = 1;
d86f9d52
LP
780
781 /* First free all secondary fields */
a1e58e8e 782 m->notify_socket = mfree(m->notify_socket);
d86f9d52
LP
783 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
784
785 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
4a62c710
MS
786 if (fd < 0)
787 return log_error_errno(errno, "Failed to allocate notification socket: %m");
d86f9d52 788
a47806fa
LP
789 fd_inc_rcvbuf(fd, NOTIFY_RCVBUF_SIZE);
790
3536f49e 791 m->notify_socket = strappend(m->prefix[EXEC_DIRECTORY_RUNTIME], "/systemd/notify");
498e87d6
LP
792 if (!m->notify_socket)
793 return log_oom();
794
795 (void) mkdir_parents_label(m->notify_socket, 0755);
f0e62e89 796 (void) unlink(m->notify_socket);
7181dbdb
LP
797
798 strncpy(sa.un.sun_path, m->notify_socket, sizeof(sa.un.sun_path)-1);
fc2fffe7 799 r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
4a62c710
MS
800 if (r < 0)
801 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
d86f9d52
LP
802
803 r = setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one));
4a62c710
MS
804 if (r < 0)
805 return log_error_errno(errno, "SO_PASSCRED failed: %m");
d86f9d52 806
d86f9d52
LP
807 m->notify_fd = fd;
808 fd = -1;
809
810 log_debug("Using notification socket %s", m->notify_socket);
811 }
812
813 if (!m->notify_event_source) {
151b9b96 814 r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
895b3a7b
MS
815 if (r < 0)
816 return log_error_errno(r, "Failed to allocate notify event source: %m");
d86f9d52 817
d8fdc620
LP
818 /* Process notification messages a bit earlier than SIGCHLD, so that we can still identify to which
819 * service an exit message belongs. */
df006034 820 r = sd_event_source_set_priority(m->notify_event_source, SD_EVENT_PRIORITY_NORMAL-7);
23bbb0de
MS
821 if (r < 0)
822 return log_error_errno(r, "Failed to set priority of notify event source: %m");
7dfbe2e3
TG
823
824 (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
d86f9d52
LP
825 }
826
827 return 0;
828}
829
d8fdc620
LP
830static int manager_setup_cgroups_agent(Manager *m) {
831
832 static const union sockaddr_union sa = {
833 .un.sun_family = AF_UNIX,
834 .un.sun_path = "/run/systemd/cgroups-agent",
835 };
836 int r;
837
838 /* This creates a listening socket we receive cgroups agent messages on. We do not use D-Bus for delivering
839 * these messages from the cgroups agent binary to PID 1, as the cgroups agent binary is very short-living, and
840 * each instance of it needs a new D-Bus connection. Since D-Bus connections are SOCK_STREAM/AF_UNIX, on
841 * overloaded systems the backlog of the D-Bus socket becomes relevant, as not more than the configured number
842 * of D-Bus connections may be queued until the kernel will start dropping further incoming connections,
843 * possibly resulting in lost cgroups agent messages. To avoid this, we'll use a private SOCK_DGRAM/AF_UNIX
844 * socket, where no backlog is relevant as communication may take place without an actual connect() cycle, and
845 * we thus won't lose messages.
846 *
847 * Note that PID 1 will forward the agent message to system bus, so that the user systemd instance may listen
848 * to it. The system instance hence listens on this special socket, but the user instances listen on the system
849 * bus for these messages. */
850
e0a3da1f 851 if (m->test_run_flags)
d8fdc620
LP
852 return 0;
853
854 if (!MANAGER_IS_SYSTEM(m))
855 return 0;
856
c22800e4 857 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
b4cccbc1
LP
858 if (r < 0)
859 return log_error_errno(r, "Failed to determine whether unified cgroups hierarchy is used: %m");
860 if (r > 0) /* We don't need this anymore on the unified hierarchy */
d8fdc620
LP
861 return 0;
862
863 if (m->cgroups_agent_fd < 0) {
864 _cleanup_close_ int fd = -1;
865
866 /* First free all secondary fields */
867 m->cgroups_agent_event_source = sd_event_source_unref(m->cgroups_agent_event_source);
868
869 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
870 if (fd < 0)
871 return log_error_errno(errno, "Failed to allocate cgroups agent socket: %m");
872
873 fd_inc_rcvbuf(fd, CGROUPS_AGENT_RCVBUF_SIZE);
874
875 (void) unlink(sa.un.sun_path);
876
877 /* Only allow root to connect to this socket */
878 RUN_WITH_UMASK(0077)
fc2fffe7 879 r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
d8fdc620
LP
880 if (r < 0)
881 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
882
883 m->cgroups_agent_fd = fd;
884 fd = -1;
885 }
886
887 if (!m->cgroups_agent_event_source) {
888 r = sd_event_add_io(m->event, &m->cgroups_agent_event_source, m->cgroups_agent_fd, EPOLLIN, manager_dispatch_cgroups_agent_fd, m);
889 if (r < 0)
890 return log_error_errno(r, "Failed to allocate cgroups agent event source: %m");
891
892 /* Process cgroups notifications early, but after having processed service notification messages or
893 * SIGCHLD signals, so that a cgroup running empty is always just the last safety net of notification,
894 * and we collected the metadata the notification and SIGCHLD stuff offers first. Also see handling of
895 * cgroup inotify for the unified cgroup stuff. */
09e24654 896 r = sd_event_source_set_priority(m->cgroups_agent_event_source, SD_EVENT_PRIORITY_NORMAL-4);
d8fdc620
LP
897 if (r < 0)
898 return log_error_errno(r, "Failed to set priority of cgroups agent event source: %m");
899
900 (void) sd_event_source_set_description(m->cgroups_agent_event_source, "manager-cgroups-agent");
901 }
902
903 return 0;
904}
905
00d9ef85
LP
906static int manager_setup_user_lookup_fd(Manager *m) {
907 int r;
908
909 assert(m);
910
911 /* Set up the socket pair used for passing UID/GID resolution results from forked off processes to PID
912 * 1. Background: we can't do name lookups (NSS) from PID 1, since it might involve IPC and thus activation,
913 * and we might hence deadlock on ourselves. Hence we do all user/group lookups asynchronously from the forked
914 * off processes right before executing the binaries to start. In order to be able to clean up any IPC objects
915 * created by a unit (see RemoveIPC=) we need to know in PID 1 the used UID/GID of the executed processes,
916 * hence we establish this communication channel so that forked off processes can pass their UID/GID
917 * information back to PID 1. The forked off processes send their resolved UID/GID to PID 1 in a simple
918 * datagram, along with their unit name, so that we can share one communication socket pair among all units for
919 * this purpose.
920 *
921 * You might wonder why we need a communication channel for this that is independent of the usual notification
922 * socket scheme (i.e. $NOTIFY_SOCKET). The primary difference is about trust: data sent via the $NOTIFY_SOCKET
923 * channel is only accepted if it originates from the right unit and if reception was enabled for it. The user
924 * lookup socket OTOH is only accessible by PID 1 and its children until they exec(), and always available.
925 *
926 * Note that this function is called under two circumstances: when we first initialize (in which case we
927 * allocate both the socket pair and the event source to listen on it), and when we deserialize after a reload
928 * (in which case the socket pair already exists but we still need to allocate the event source for it). */
929
930 if (m->user_lookup_fds[0] < 0) {
931
932 /* Free all secondary fields */
933 safe_close_pair(m->user_lookup_fds);
934 m->user_lookup_event_source = sd_event_source_unref(m->user_lookup_event_source);
935
936 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
937 return log_error_errno(errno, "Failed to allocate user lookup socket: %m");
938
939 (void) fd_inc_rcvbuf(m->user_lookup_fds[0], NOTIFY_RCVBUF_SIZE);
940 }
941
942 if (!m->user_lookup_event_source) {
943 r = sd_event_add_io(m->event, &m->user_lookup_event_source, m->user_lookup_fds[0], EPOLLIN, manager_dispatch_user_lookup_fd, m);
944 if (r < 0)
945 return log_error_errno(errno, "Failed to allocate user lookup event source: %m");
946
947 /* Process even earlier than the notify event source, so that we always know first about valid UID/GID
948 * resolutions */
949 r = sd_event_source_set_priority(m->user_lookup_event_source, SD_EVENT_PRIORITY_NORMAL-8);
950 if (r < 0)
951 return log_error_errno(errno, "Failed to set priority ot user lookup event source: %m");
952
953 (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
954 }
955
956 return 0;
957}
958
d86f9d52
LP
959static int manager_connect_bus(Manager *m, bool reexecuting) {
960 bool try_bus_connect;
5463fa0a 961 Unit *u = NULL;
d86f9d52
LP
962
963 assert(m);
964
e0a3da1f 965 if (m->test_run_flags)
0d8c31ff
ZJS
966 return 0;
967
5463fa0a
MS
968 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
969
d86f9d52 970 try_bus_connect =
41dfa61d 971 (u && SERVICE(u)->deserialized_state == SERVICE_RUNNING) &&
5463fa0a
MS
972 (reexecuting ||
973 (MANAGER_IS_USER(m) && getenv("DBUS_SESSION_BUS_ADDRESS")));
d86f9d52 974
ff9b60f3 975 /* Try to connect to the buses, if possible. */
d86f9d52
LP
976 return bus_init(m, try_bus_connect);
977}
978
23a177ef 979static unsigned manager_dispatch_cleanup_queue(Manager *m) {
595ed347 980 Unit *u;
23a177ef
LP
981 unsigned n = 0;
982
983 assert(m);
984
595ed347
MS
985 while ((u = m->cleanup_queue)) {
986 assert(u->in_cleanup_queue);
23a177ef 987
595ed347 988 unit_free(u);
23a177ef
LP
989 n++;
990 }
991
992 return n;
993}
994
eced69b3 995enum {
35b8ca3a 996 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
eced69b3
LP
997 GC_OFFSET_UNSURE, /* No clue */
998 GC_OFFSET_GOOD, /* We still need this unit */
999 GC_OFFSET_BAD, /* We don't need this unit anymore */
1000 _GC_OFFSET_MAX
1001};
1002
00d9ef85 1003static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
4892084f 1004 Unit *other;
eef85c4a
LP
1005 Iterator i;
1006 void *v;
4892084f
LN
1007
1008 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
1009
1010 /* Recursively mark referenced units as GOOD as well */
eef85c4a 1011 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REFERENCES], i)
4892084f
LN
1012 if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
1013 unit_gc_mark_good(other, gc_marker);
1014}
1015
eced69b3 1016static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
701cc384 1017 Unit *other;
eced69b3 1018 bool is_bad;
eef85c4a
LP
1019 Iterator i;
1020 void *v;
701cc384
LP
1021
1022 assert(u);
1023
4c701096
YW
1024 if (IN_SET(u->gc_marker - gc_marker,
1025 GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
701cc384
LP
1026 return;
1027
ac155bb8 1028 if (u->in_cleanup_queue)
701cc384
LP
1029 goto bad;
1030
1031 if (unit_check_gc(u))
1032 goto good;
1033
ac155bb8 1034 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
eced69b3
LP
1035
1036 is_bad = true;
1037
eef85c4a 1038 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REFERENCED_BY], i) {
701cc384
LP
1039 unit_gc_sweep(other, gc_marker);
1040
ac155bb8 1041 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
701cc384 1042 goto good;
eced69b3 1043
ac155bb8 1044 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
eced69b3 1045 is_bad = false;
701cc384
LP
1046 }
1047
eced69b3
LP
1048 if (is_bad)
1049 goto bad;
1050
1051 /* We were unable to find anything out about this entry, so
1052 * let's investigate it later */
ac155bb8 1053 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
eced69b3
LP
1054 unit_add_to_gc_queue(u);
1055 return;
1056
701cc384 1057bad:
eced69b3
LP
1058 /* We definitely know that this one is not useful anymore, so
1059 * let's mark it for deletion */
ac155bb8 1060 u->gc_marker = gc_marker + GC_OFFSET_BAD;
eced69b3 1061 unit_add_to_cleanup_queue(u);
701cc384
LP
1062 return;
1063
1064good:
4892084f 1065 unit_gc_mark_good(u, gc_marker);
701cc384
LP
1066}
1067
c5a97ed1
LP
1068static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
1069 unsigned n = 0, gc_marker;
595ed347 1070 Unit *u;
701cc384
LP
1071
1072 assert(m);
1073
cf1265e1 1074 /* log_debug("Running GC..."); */
701cc384 1075
eced69b3
LP
1076 m->gc_marker += _GC_OFFSET_MAX;
1077 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
c9c0cadb 1078 m->gc_marker = 1;
701cc384 1079
eced69b3
LP
1080 gc_marker = m->gc_marker;
1081
c5a97ed1 1082 while ((u = m->gc_unit_queue)) {
595ed347 1083 assert(u->in_gc_queue);
701cc384 1084
595ed347 1085 unit_gc_sweep(u, gc_marker);
eced69b3 1086
c5a97ed1 1087 LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
595ed347 1088 u->in_gc_queue = false;
701cc384
LP
1089
1090 n++;
1091
4c701096
YW
1092 if (IN_SET(u->gc_marker - gc_marker,
1093 GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
cc3bc3e6 1094 if (u->id)
f2341e0a 1095 log_unit_debug(u, "Collecting.");
595ed347
MS
1096 u->gc_marker = gc_marker + GC_OFFSET_BAD;
1097 unit_add_to_cleanup_queue(u);
701cc384
LP
1098 }
1099 }
1100
701cc384
LP
1101 return n;
1102}
1103
c5a97ed1
LP
1104static unsigned manager_dispatch_gc_job_queue(Manager *m) {
1105 unsigned n = 0;
1106 Job *j;
1107
1108 assert(m);
1109
1110 while ((j = m->gc_job_queue)) {
1111 assert(j->in_gc_queue);
1112
1113 LIST_REMOVE(gc_queue, m->gc_job_queue, j);
1114 j->in_gc_queue = false;
1115
1116 n++;
1117
1118 if (job_check_gc(j))
1119 continue;
1120
1121 log_unit_debug(j->unit, "Collecting job.");
1122 (void) job_finish_and_invalidate(j, JOB_COLLECTED, false, false);
1123 }
1124
1125 return n;
1126}
1127
a16e1123 1128static void manager_clear_jobs_and_units(Manager *m) {
a16e1123 1129 Unit *u;
60918275
LP
1130
1131 assert(m);
1132
87f0e418
LP
1133 while ((u = hashmap_first(m->units)))
1134 unit_free(u);
964e0949
LP
1135
1136 manager_dispatch_cleanup_queue(m);
1137
1138 assert(!m->load_queue);
1139 assert(!m->run_queue);
1140 assert(!m->dbus_unit_queue);
1141 assert(!m->dbus_job_queue);
1142 assert(!m->cleanup_queue);
c5a97ed1
LP
1143 assert(!m->gc_unit_queue);
1144 assert(!m->gc_job_queue);
964e0949 1145
964e0949
LP
1146 assert(hashmap_isempty(m->jobs));
1147 assert(hashmap_isempty(m->units));
9e9e2b72
MS
1148
1149 m->n_on_console = 0;
1150 m->n_running_jobs = 0;
a16e1123
LP
1151}
1152
06d8d842 1153Manager* manager_free(Manager *m) {
a16e1123 1154 UnitType c;
c93ff2e9 1155 int i;
35aba85a 1156 ExecDirectoryType dt;
87f0e418 1157
06d8d842
ZJS
1158 if (!m)
1159 return NULL;
a16e1123
LP
1160
1161 manager_clear_jobs_and_units(m);
23a177ef 1162
7824bbeb
LP
1163 for (c = 0; c < _UNIT_TYPE_MAX; c++)
1164 if (unit_vtable[c]->shutdown)
1165 unit_vtable[c]->shutdown(m);
1166
a1f31f47 1167 /* If we reexecute ourselves, we keep the root cgroup around */
c6c18be3 1168 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
8e274523 1169
07a78643 1170 lookup_paths_flush_generator(&m->lookup_paths);
5a1e9937 1171
5e8d1c9a 1172 bus_done(m);
ea430986 1173
29206d46
LP
1174 dynamic_user_vacuum(m, false);
1175 hashmap_free(m->dynamic_users);
1176
87f0e418 1177 hashmap_free(m->units);
4b58153d 1178 hashmap_free(m->units_by_invocation_id);
60918275 1179 hashmap_free(m->jobs);
5ba6985b
LP
1180 hashmap_free(m->watch_pids1);
1181 hashmap_free(m->watch_pids2);
05e343b7 1182 hashmap_free(m->watch_bus);
9152c765 1183
95ae05c0 1184 set_free(m->startup_units);
f755e3b7
LP
1185 set_free(m->failed_units);
1186
718db961
LP
1187 sd_event_source_unref(m->signal_event_source);
1188 sd_event_source_unref(m->notify_event_source);
d8fdc620 1189 sd_event_source_unref(m->cgroups_agent_event_source);
718db961
LP
1190 sd_event_source_unref(m->time_change_event_source);
1191 sd_event_source_unref(m->jobs_in_progress_event_source);
752b5905 1192 sd_event_source_unref(m->run_queue_event_source);
00d9ef85 1193 sd_event_source_unref(m->user_lookup_event_source);
718db961 1194
03e334a1
LP
1195 safe_close(m->signal_fd);
1196 safe_close(m->notify_fd);
d8fdc620 1197 safe_close(m->cgroups_agent_fd);
03e334a1 1198 safe_close(m->time_change_fd);
00d9ef85 1199 safe_close_pair(m->user_lookup_fds);
718db961 1200
e46b13c8
ZJS
1201 manager_close_ask_password(m);
1202
718db961
LP
1203 manager_close_idle_pipe(m);
1204
9670d583 1205 udev_unref(m->udev);
718db961 1206 sd_event_unref(m->event);
60918275 1207
c952c6ec
LP
1208 free(m->notify_socket);
1209
84e3543e 1210 lookup_paths_free(&m->lookup_paths);
1137a57c 1211 strv_free(m->environment);
036643a2 1212
4ad49000 1213 hashmap_free(m->cgroup_unit);
c6c18be3 1214 set_free_free(m->unit_path_cache);
33be102a 1215
664f88a7
LP
1216 free(m->switch_root);
1217 free(m->switch_root_init);
1218
517d56b1 1219 for (i = 0; i < _RLIMIT_MAX; i++)
d9814c76 1220 m->rlimit[i] = mfree(m->rlimit[i]);
c93ff2e9 1221
a57f7e2c
LP
1222 assert(hashmap_isempty(m->units_requiring_mounts_for));
1223 hashmap_free(m->units_requiring_mounts_for);
1224
00d9ef85
LP
1225 hashmap_free(m->uid_refs);
1226 hashmap_free(m->gid_refs);
1227
72fd1768 1228 for (dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
35aba85a
YW
1229 m->prefix[dt] = mfree(m->prefix[dt]);
1230
6b430fdb 1231 return mfree(m);
60918275
LP
1232}
1233
ba64af90 1234void manager_enumerate(Manager *m) {
f50e0a01 1235 UnitType c;
f50e0a01
LP
1236
1237 assert(m);
1238
a16e1123
LP
1239 /* Let's ask every type to load all units from disk/kernel
1240 * that it might know */
0faacd47 1241 for (c = 0; c < _UNIT_TYPE_MAX; c++) {
1c2e9646 1242 if (!unit_type_supported(c)) {
03afec3c 1243 log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
0faacd47 1244 continue;
a57f7e2c 1245 }
f50e0a01 1246
0faacd47
LP
1247 if (!unit_vtable[c]->enumerate)
1248 continue;
1249
ba64af90 1250 unit_vtable[c]->enumerate(m);
0faacd47
LP
1251 }
1252
f50e0a01 1253 manager_dispatch_load_queue(m);
a16e1123
LP
1254}
1255
007c6337 1256static void manager_coldplug(Manager *m) {
a16e1123
LP
1257 Iterator i;
1258 Unit *u;
1259 char *k;
007c6337 1260 int r;
a16e1123
LP
1261
1262 assert(m);
f50e0a01
LP
1263
1264 /* Then, let's set up their initial state. */
1265 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1266
1267 /* ignore aliases */
ac155bb8 1268 if (u->id != k)
f50e0a01
LP
1269 continue;
1270
007c6337
LP
1271 r = unit_coldplug(u);
1272 if (r < 0)
1273 log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
f50e0a01 1274 }
a16e1123
LP
1275}
1276
fe51822e
LP
1277static void manager_build_unit_path_cache(Manager *m) {
1278 char **i;
fe51822e
LP
1279 int r;
1280
1281 assert(m);
1282
1283 set_free_free(m->unit_path_cache);
1284
d5099efc 1285 m->unit_path_cache = set_new(&string_hash_ops);
874310b7 1286 if (!m->unit_path_cache) {
d063a527
LP
1287 r = -ENOMEM;
1288 goto fail;
fe51822e
LP
1289 }
1290
1291 /* This simply builds a list of files we know exist, so that
1292 * we don't always have to go to disk */
1293
a3c4eb07 1294 STRV_FOREACH(i, m->lookup_paths.search_path) {
d063a527 1295 _cleanup_closedir_ DIR *d = NULL;
fe51822e
LP
1296 struct dirent *de;
1297
bd0af849
ZJS
1298 d = opendir(*i);
1299 if (!d) {
874310b7 1300 if (errno != ENOENT)
d063a527 1301 log_warning_errno(errno, "Failed to open directory %s, ignoring: %m", *i);
fe51822e
LP
1302 continue;
1303 }
1304
d063a527 1305 FOREACH_DIRENT(de, d, r = -errno; goto fail) {
fe51822e
LP
1306 char *p;
1307
605405c6 1308 p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name);
44d91056 1309 if (!p) {
fe51822e
LP
1310 r = -ENOMEM;
1311 goto fail;
1312 }
1313
ef42202a
ZJS
1314 r = set_consume(m->unit_path_cache, p);
1315 if (r < 0)
fe51822e 1316 goto fail;
fe51822e 1317 }
fe51822e
LP
1318 }
1319
1320 return;
1321
1322fail:
d063a527
LP
1323 log_warning_errno(r, "Failed to build unit path cache, proceeding without: %m");
1324 m->unit_path_cache = set_free_free(m->unit_path_cache);
fe51822e
LP
1325}
1326
9ff1a6f1 1327static void manager_distribute_fds(Manager *m, FDSet *fds) {
9588bc32 1328 Iterator i;
9ff1a6f1 1329 Unit *u;
9588bc32
LP
1330
1331 assert(m);
1332
1333 HASHMAP_FOREACH(u, m->units, i) {
1334
1335 if (fdset_size(fds) <= 0)
1336 break;
1337
9ff1a6f1
LP
1338 if (!UNIT_VTABLE(u)->distribute_fds)
1339 continue;
9588bc32 1340
9ff1a6f1
LP
1341 UNIT_VTABLE(u)->distribute_fds(u, fds);
1342 }
9588bc32
LP
1343}
1344
a16e1123 1345int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
17f01ace 1346 int r;
a16e1123
LP
1347
1348 assert(m);
1349
a1f31f47
ZJS
1350 /* If we are running in test mode, we still want to run the generators,
1351 * but we should not touch the real generator directories. */
1352 r = lookup_paths_init(&m->lookup_paths, m->unit_file_scope,
e0a3da1f 1353 m->test_run_flags ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
a1f31f47 1354 NULL);
e801700e
ZJS
1355 if (r < 0)
1356 return r;
5a1e9937 1357
64691d20
ZJS
1358 r = manager_run_environment_generators(m);
1359 if (r < 0)
1360 return r;
1361
9f9f0342 1362 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_GENERATORS_START);
a3c4eb07 1363 r = manager_run_generators(m);
9f9f0342 1364 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_GENERATORS_FINISH);
07719a21
LP
1365 if (r < 0)
1366 return r;
1367
fd130612 1368 /* If this is the first boot, and we are in the host system, then preset everything */
81fe6cde 1369 if (m->first_boot > 0 &&
fd130612 1370 MANAGER_IS_SYSTEM(m) &&
e0a3da1f 1371 !m->test_run_flags) {
81fe6cde 1372
17f01ace
ZJS
1373 r = unit_file_preset_all(UNIT_FILE_SYSTEM, 0, NULL, UNIT_FILE_PRESET_ENABLE_ONLY, NULL, 0);
1374 if (r < 0)
1375 log_full_errno(r == -EEXIST ? LOG_NOTICE : LOG_WARNING, r,
1376 "Failed to populate /etc with preset unit settings, ignoring: %m");
28dd66ec
LB
1377 else
1378 log_info("Populated /etc with preset unit settings.");
1379 }
1380
a1453343 1381 lookup_paths_reduce(&m->lookup_paths);
fe51822e
LP
1382 manager_build_unit_path_cache(m);
1383
9f611ad8
LP
1384 /* If we will deserialize make sure that during enumeration
1385 * this is already known, so we increase the counter here
1386 * already */
1387 if (serialization)
313cefa1 1388 m->n_reloading++;
9f611ad8 1389
a16e1123 1390 /* First, enumerate what we can from all config files */
9f9f0342 1391 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD_START);
ba64af90 1392 manager_enumerate(m);
9f9f0342 1393 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD_FINISH);
a16e1123
LP
1394
1395 /* Second, deserialize if there is something to deserialize */
07429866 1396 if (serialization) {
1cd974ed 1397 r = manager_deserialize(m, serialization, fds);
07429866 1398 if (r < 0)
17f01ace 1399 return log_error_errno(r, "Deserialization failed: %m");
07429866 1400 }
a16e1123 1401
01e10de3
LP
1402 /* Any fds left? Find some unit which wants them. This is
1403 * useful to allow container managers to pass some file
1404 * descriptors to us pre-initialized. This enables
1405 * socket-based activation of entire containers. */
9ff1a6f1 1406 manager_distribute_fds(m, fds);
01e10de3 1407
d86f9d52
LP
1408 /* We might have deserialized the notify fd, but if we didn't
1409 * then let's create the bus now */
17f01ace
ZJS
1410 r = manager_setup_notify(m);
1411 if (r < 0)
1412 /* No sense to continue without notifications, our children would fail anyway. */
1413 return r;
d86f9d52 1414
17f01ace
ZJS
1415 r = manager_setup_cgroups_agent(m);
1416 if (r < 0)
1417 /* Likewise, no sense to continue without empty cgroup notifications. */
1418 return r;
d8fdc620 1419
17f01ace
ZJS
1420 r = manager_setup_user_lookup_fd(m);
1421 if (r < 0)
1422 /* This shouldn't fail, except if things are really broken. */
1423 return r;
00d9ef85 1424
232f6754 1425 /* Let's connect to the bus now. */
05a98afd
LP
1426 (void) manager_connect_bus(m, !!serialization);
1427
1428 (void) bus_track_coldplug(m, &m->subscribed, false, m->deserialized_subscribed);
1429 m->deserialized_subscribed = strv_free(m->deserialized_subscribed);
e3dd987c 1430
a16e1123 1431 /* Third, fire things up! */
007c6337 1432 manager_coldplug(m);
a16e1123 1433
29206d46
LP
1434 /* Release any dynamic users no longer referenced */
1435 dynamic_user_vacuum(m, true);
1436
00d9ef85
LP
1437 /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
1438 manager_vacuum_uid_refs(m);
1439 manager_vacuum_gid_refs(m);
1440
9f611ad8 1441 if (serialization) {
a7556052 1442 assert(m->n_reloading > 0);
313cefa1 1443 m->n_reloading--;
71445ae7
LP
1444
1445 /* Let's wait for the UnitNew/JobNew messages being
1446 * sent, before we notify that the reload is
1447 * finished */
1448 m->send_reloading_done = true;
9f611ad8
LP
1449 }
1450
17f01ace 1451 return 0;
f50e0a01
LP
1452}
1453
4bd29fe5 1454int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, sd_bus_error *e, Job **_ret) {
e5b5ae50 1455 int r;
7527cb52 1456 Transaction *tr;
e5b5ae50
LP
1457
1458 assert(m);
1459 assert(type < _JOB_TYPE_MAX);
87f0e418 1460 assert(unit);
e5b5ae50 1461 assert(mode < _JOB_MODE_MAX);
60918275 1462
7358dc02
ZJS
1463 if (mode == JOB_ISOLATE && type != JOB_START)
1464 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
c497c7a9 1465
7358dc02
ZJS
1466 if (mode == JOB_ISOLATE && !unit->allow_isolate)
1467 return sd_bus_error_setf(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
2528a7a6 1468
f2341e0a 1469 log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
9f04bd52 1470
c6497ccb 1471 type = job_type_collapse(type, unit);
e0209d83 1472
23ade460 1473 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
7527cb52
MS
1474 if (!tr)
1475 return -ENOMEM;
11dd41ce 1476
4bd29fe5 1477 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, false,
3742095b 1478 IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS),
b94fbd30 1479 mode == JOB_IGNORE_DEPENDENCIES, e);
7527cb52
MS
1480 if (r < 0)
1481 goto tr_abort;
c497c7a9 1482
7527cb52
MS
1483 if (mode == JOB_ISOLATE) {
1484 r = transaction_add_isolate_jobs(tr, m);
1485 if (r < 0)
1486 goto tr_abort;
1487 }
1488
1489 r = transaction_activate(tr, m, mode, e);
1490 if (r < 0)
1491 goto tr_abort;
e5b5ae50 1492
f2341e0a 1493 log_unit_debug(unit,
66870f90
ZJS
1494 "Enqueued job %s/%s as %u", unit->id,
1495 job_type_to_string(type), (unsigned) tr->anchor_job->id);
f50e0a01 1496
e5b5ae50 1497 if (_ret)
b94fbd30 1498 *_ret = tr->anchor_job;
60918275 1499
7527cb52 1500 transaction_free(tr);
e5b5ae50 1501 return 0;
7527cb52
MS
1502
1503tr_abort:
1504 transaction_abort(tr);
1505 transaction_free(tr);
1506 return r;
e5b5ae50 1507}
60918275 1508
53f18416 1509int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, sd_bus_error *e, Job **ret) {
4440b27d 1510 Unit *unit = NULL; /* just to appease gcc, initialization is not really necessary */
28247076
LP
1511 int r;
1512
1513 assert(m);
1514 assert(type < _JOB_TYPE_MAX);
1515 assert(name);
1516 assert(mode < _JOB_MODE_MAX);
1517
c3090674
LP
1518 r = manager_load_unit(m, name, NULL, NULL, &unit);
1519 if (r < 0)
28247076 1520 return r;
4440b27d 1521 assert(unit);
28247076 1522
53f18416
LP
1523 return manager_add_job(m, type, unit, mode, e, ret);
1524}
1525
1526int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Job **ret) {
4afd3348 1527 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
53f18416
LP
1528 int r;
1529
1530 assert(m);
1531 assert(type < _JOB_TYPE_MAX);
1532 assert(name);
1533 assert(mode < _JOB_MODE_MAX);
1534
1535 r = manager_add_job_by_name(m, type, name, mode, &error, ret);
1536 if (r < 0)
1537 return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
1538
1539 return r;
28247076
LP
1540}
1541
15d167f8
JW
1542int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
1543 int r;
1544 Transaction *tr;
1545
1546 assert(m);
1547 assert(unit);
1548 assert(mode < _JOB_MODE_MAX);
1549 assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
1550
1551 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1552 if (!tr)
1553 return -ENOMEM;
1554
1555 /* We need an anchor job */
1556 r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, false, false, true, true, e);
1557 if (r < 0)
1558 goto tr_abort;
1559
1560 /* Failure in adding individual dependencies is ignored, so this always succeeds. */
1561 transaction_add_propagate_reload_jobs(tr, unit, tr->anchor_job, mode == JOB_IGNORE_DEPENDENCIES, e);
1562
1563 r = transaction_activate(tr, m, mode, e);
1564 if (r < 0)
1565 goto tr_abort;
1566
1567 transaction_free(tr);
1568 return 0;
1569
1570tr_abort:
1571 transaction_abort(tr);
1572 transaction_free(tr);
1573 return r;
1574}
1575
60918275
LP
1576Job *manager_get_job(Manager *m, uint32_t id) {
1577 assert(m);
1578
1579 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1580}
1581
87f0e418 1582Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
1583 assert(m);
1584 assert(name);
1585
87f0e418 1586 return hashmap_get(m->units, name);
60918275
LP
1587}
1588
c1e1601e 1589unsigned manager_dispatch_load_queue(Manager *m) {
595ed347 1590 Unit *u;
c1e1601e 1591 unsigned n = 0;
60918275
LP
1592
1593 assert(m);
1594
223dabab
LP
1595 /* Make sure we are not run recursively */
1596 if (m->dispatching_load_queue)
c1e1601e 1597 return 0;
223dabab
LP
1598
1599 m->dispatching_load_queue = true;
1600
87f0e418 1601 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
1602 * tries to load its data until the queue is empty */
1603
595ed347
MS
1604 while ((u = m->load_queue)) {
1605 assert(u->in_load_queue);
034c6ed7 1606
595ed347 1607 unit_load(u);
c1e1601e 1608 n++;
60918275
LP
1609 }
1610
223dabab 1611 m->dispatching_load_queue = false;
c1e1601e 1612 return n;
60918275
LP
1613}
1614
c2756a68
LP
1615int manager_load_unit_prepare(
1616 Manager *m,
1617 const char *name,
1618 const char *path,
718db961 1619 sd_bus_error *e,
c2756a68
LP
1620 Unit **_ret) {
1621
87f0e418 1622 Unit *ret;
7d17cfbc 1623 UnitType t;
60918275
LP
1624 int r;
1625
1626 assert(m);
9e2f7c11 1627 assert(name || path);
7a6a095a 1628 assert(_ret);
60918275 1629
db06e3b6
LP
1630 /* This will prepare the unit for loading, but not actually
1631 * load anything from disk. */
0301abf4 1632
718db961
LP
1633 if (path && !is_path(path))
1634 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
9e2f7c11
LP
1635
1636 if (!name)
2b6bf07d 1637 name = basename(path);
9e2f7c11 1638
7d17cfbc
MS
1639 t = unit_name_to_type(name);
1640
5d512d54
LN
1641 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
1642 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
1643 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
1644
718db961 1645 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
5d512d54 1646 }
60918275 1647
7d17cfbc
MS
1648 ret = manager_get_unit(m, name);
1649 if (ret) {
034c6ed7 1650 *_ret = ret;
413d6313 1651 return 1;
034c6ed7 1652 }
60918275 1653
7d17cfbc
MS
1654 ret = unit_new(m, unit_vtable[t]->object_size);
1655 if (!ret)
60918275
LP
1656 return -ENOMEM;
1657
7d17cfbc 1658 if (path) {
ac155bb8
MS
1659 ret->fragment_path = strdup(path);
1660 if (!ret->fragment_path) {
0301abf4
LP
1661 unit_free(ret);
1662 return -ENOMEM;
1663 }
7d17cfbc 1664 }
0301abf4 1665
1058cbf2
ZJS
1666 r = unit_add_name(ret, name);
1667 if (r < 0) {
87f0e418 1668 unit_free(ret);
1ffba6fe 1669 return r;
60918275
LP
1670 }
1671
87f0e418 1672 unit_add_to_load_queue(ret);
c1e1601e 1673 unit_add_to_dbus_queue(ret);
949061f0 1674 unit_add_to_gc_queue(ret);
c1e1601e 1675
7a6a095a 1676 *_ret = ret;
db06e3b6
LP
1677
1678 return 0;
1679}
1680
c2756a68
LP
1681int manager_load_unit(
1682 Manager *m,
1683 const char *name,
1684 const char *path,
718db961 1685 sd_bus_error *e,
c2756a68
LP
1686 Unit **_ret) {
1687
db06e3b6
LP
1688 int r;
1689
1690 assert(m);
7a6a095a 1691 assert(_ret);
db06e3b6
LP
1692
1693 /* This will load the service information files, but not actually
1694 * start any services or anything. */
1695
c3090674
LP
1696 r = manager_load_unit_prepare(m, name, path, e, _ret);
1697 if (r != 0)
db06e3b6
LP
1698 return r;
1699
f50e0a01 1700 manager_dispatch_load_queue(m);
60918275 1701
7a6a095a 1702 *_ret = unit_follow_merge(*_ret);
9e2f7c11 1703
60918275
LP
1704 return 0;
1705}
a66d02c3 1706
cea8e32e 1707void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1708 Iterator i;
a66d02c3
LP
1709 Job *j;
1710
1711 assert(s);
1712 assert(f);
1713
034c6ed7 1714 HASHMAP_FOREACH(j, s->jobs, i)
cea8e32e 1715 job_dump(j, f, prefix);
a66d02c3
LP
1716}
1717
87f0e418 1718void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
034c6ed7 1719 Iterator i;
87f0e418 1720 Unit *u;
11dd41ce 1721 const char *t;
a66d02c3
LP
1722
1723 assert(s);
1724 assert(f);
1725
87f0e418 1726 HASHMAP_FOREACH_KEY(u, t, s->units, i)
ac155bb8 1727 if (u->id == t)
87f0e418 1728 unit_dump(u, f, prefix);
a66d02c3 1729}
7fad411c 1730
ad75b9e7
LP
1731void manager_dump(Manager *m, FILE *f, const char *prefix) {
1732 ManagerTimestamp q;
1733
1734 assert(m);
1735 assert(f);
1736
1737 for (q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) {
1738 char buf[FORMAT_TIMESTAMP_MAX];
1739
1740 if (dual_timestamp_is_set(m->timestamps + q))
1741 fprintf(f, "%sTimestamp %s: %s\n",
1742 strempty(prefix),
1743 manager_timestamp_to_string(q),
1744 format_timestamp(buf, sizeof(buf), m->timestamps[q].realtime));
1745 }
1746
1747 manager_dump_units(m, f, prefix);
1748 manager_dump_jobs(m, f, prefix);
1749}
1750
713f6f90
LP
1751int manager_get_dump_string(Manager *m, char **ret) {
1752 _cleanup_free_ char *dump = NULL;
1753 _cleanup_fclose_ FILE *f = NULL;
1754 size_t size;
1755 int r;
1756
1757 assert(m);
1758 assert(ret);
1759
1760 f = open_memstream(&dump, &size);
1761 if (!f)
1762 return -errno;
1763
0d536673 1764 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
713f6f90
LP
1765
1766 manager_dump(m, f, NULL);
1767
1768 r = fflush_and_check(f);
1769 if (r < 0)
1770 return r;
1771
1772 f = safe_fclose(f);
1773
1774 *ret = dump;
1775 dump = NULL;
1776
1777 return 0;
1778}
1779
7fad411c
LP
1780void manager_clear_jobs(Manager *m) {
1781 Job *j;
1782
1783 assert(m);
1784
7fad411c 1785 while ((j = hashmap_first(m->jobs)))
5273510e 1786 /* No need to recurse. We're cancelling all jobs. */
833f92ad 1787 job_finish_and_invalidate(j, JOB_CANCELED, false, false);
7fad411c 1788}
83c60c9f 1789
752b5905
LP
1790static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
1791 Manager *m = userdata;
83c60c9f 1792 Job *j;
034c6ed7 1793
752b5905
LP
1794 assert(source);
1795 assert(m);
9152c765 1796
034c6ed7 1797 while ((j = m->run_queue)) {
ac1135be 1798 assert(j->installed);
034c6ed7
LP
1799 assert(j->in_run_queue);
1800
1801 job_run_and_invalidate(j);
9152c765 1802 }
034c6ed7 1803
a0b64226 1804 if (m->n_running_jobs > 0)
03b717a3
MS
1805 manager_watch_jobs_in_progress(m);
1806
31a7eb86
ZJS
1807 if (m->n_on_console > 0)
1808 manager_watch_idle_pipe(m);
1809
752b5905 1810 return 1;
c1e1601e
LP
1811}
1812
9588bc32 1813static unsigned manager_dispatch_dbus_queue(Manager *m) {
c1e1601e 1814 Job *j;
595ed347 1815 Unit *u;
c1e1601e
LP
1816 unsigned n = 0;
1817
1818 assert(m);
1819
1820 if (m->dispatching_dbus_queue)
1821 return 0;
1822
1823 m->dispatching_dbus_queue = true;
1824
595ed347
MS
1825 while ((u = m->dbus_unit_queue)) {
1826 assert(u->in_dbus_queue);
c1e1601e 1827
595ed347 1828 bus_unit_send_change_signal(u);
c1e1601e
LP
1829 n++;
1830 }
1831
1832 while ((j = m->dbus_job_queue)) {
1833 assert(j->in_dbus_queue);
1834
1835 bus_job_send_change_signal(j);
1836 n++;
1837 }
1838
1839 m->dispatching_dbus_queue = false;
71445ae7
LP
1840
1841 if (m->send_reloading_done) {
1842 m->send_reloading_done = false;
1843
718db961 1844 bus_manager_send_reloading(m, false);
71445ae7
LP
1845 }
1846
718db961
LP
1847 if (m->queued_message)
1848 bus_send_queued_message(m);
1849
c1e1601e 1850 return n;
9152c765
LP
1851}
1852
d8fdc620
LP
1853static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1854 Manager *m = userdata;
1855 char buf[PATH_MAX+1];
1856 ssize_t n;
1857
1858 n = recv(fd, buf, sizeof(buf), 0);
1859 if (n < 0)
1860 return log_error_errno(errno, "Failed to read cgroups agent message: %m");
1861 if (n == 0) {
1862 log_error("Got zero-length cgroups agent message, ignoring.");
1863 return 0;
1864 }
1865 if ((size_t) n >= sizeof(buf)) {
1866 log_error("Got overly long cgroups agent message, ignoring.");
1867 return 0;
1868 }
1869
1870 if (memchr(buf, 0, n)) {
1871 log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
1872 return 0;
1873 }
1874 buf[n] = 0;
1875
1876 manager_notify_cgroup_empty(m, buf);
d5f15326 1877 (void) bus_forward_agent_released(m, buf);
d8fdc620
LP
1878
1879 return 0;
1880}
1881
db256aab
LP
1882static void manager_invoke_notify_message(
1883 Manager *m,
1884 Unit *u,
1885 const struct ucred *ucred,
1886 const char *buf,
1887 FDSet *fds) {
1888
5ba6985b
LP
1889 _cleanup_strv_free_ char **tags = NULL;
1890
1891 assert(m);
1892 assert(u);
db256aab 1893 assert(ucred);
5ba6985b 1894 assert(buf);
5ba6985b 1895
007e4b54 1896 tags = strv_split(buf, NEWLINE);
5ba6985b
LP
1897 if (!tags) {
1898 log_oom();
1899 return;
1900 }
1901
5ba6985b 1902 if (UNIT_VTABLE(u)->notify_message)
db256aab 1903 UNIT_VTABLE(u)->notify_message(u, ucred, tags, fds);
f1d34068 1904 else if (DEBUG_LOGGING) {
a86b7675
ZJS
1905 _cleanup_free_ char *x = NULL, *y = NULL;
1906
da5fb861 1907 x = ellipsize(buf, 20, 90);
a86b7675 1908 if (x)
da5fb861
LP
1909 y = cescape(x);
1910
a86b7675
ZJS
1911 log_unit_debug(u, "Got notification message \"%s\", ignoring.", strnull(y));
1912 }
5ba6985b
LP
1913}
1914
718db961 1915static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3d0b8a55 1916
b215b0ed 1917 _cleanup_fdset_free_ FDSet *fds = NULL;
718db961 1918 Manager *m = userdata;
b215b0ed
DH
1919 char buf[NOTIFY_BUFFER_MAX+1];
1920 struct iovec iovec = {
1921 .iov_base = buf,
1922 .iov_len = sizeof(buf)-1,
1923 };
1924 union {
1925 struct cmsghdr cmsghdr;
1926 uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) +
1927 CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)];
1928 } control = {};
1929 struct msghdr msghdr = {
1930 .msg_iov = &iovec,
1931 .msg_iovlen = 1,
1932 .msg_control = &control,
1933 .msg_controllen = sizeof(control),
1934 };
1935
1936 struct cmsghdr *cmsg;
1937 struct ucred *ucred = NULL;
b215b0ed
DH
1938 Unit *u1, *u2, *u3;
1939 int r, *fd_array = NULL;
1940 unsigned n_fds = 0;
8c47c732
LP
1941 ssize_t n;
1942
1943 assert(m);
718db961
LP
1944 assert(m->notify_fd == fd);
1945
1946 if (revents != EPOLLIN) {
1947 log_warning("Got unexpected poll event for notify fd.");
1948 return 0;
1949 }
8c47c732 1950
045a3d59 1951 n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
b215b0ed 1952 if (n < 0) {
c55ae51e
LP
1953 if (IN_SET(errno, EAGAIN, EINTR))
1954 return 0; /* Spurious wakeup, try again */
8c47c732 1955
c55ae51e
LP
1956 /* If this is any other, real error, then let's stop processing this socket. This of course means we
1957 * won't take notification messages anymore, but that's still better than busy looping around this:
1958 * being woken up over and over again but being unable to actually read the message off the socket. */
1959 return log_error_errno(errno, "Failed to receive notification message: %m");
b215b0ed 1960 }
a354329f 1961
b215b0ed
DH
1962 CMSG_FOREACH(cmsg, &msghdr) {
1963 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
a354329f 1964
b215b0ed
DH
1965 fd_array = (int*) CMSG_DATA(cmsg);
1966 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
a354329f 1967
b215b0ed
DH
1968 } else if (cmsg->cmsg_level == SOL_SOCKET &&
1969 cmsg->cmsg_type == SCM_CREDENTIALS &&
1970 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
a354329f 1971
b215b0ed 1972 ucred = (struct ucred*) CMSG_DATA(cmsg);
a354329f 1973 }
b215b0ed 1974 }
a354329f 1975
b215b0ed
DH
1976 if (n_fds > 0) {
1977 assert(fd_array);
a354329f 1978
b215b0ed
DH
1979 r = fdset_new_array(&fds, fd_array, n_fds);
1980 if (r < 0) {
1981 close_many(fd_array, n_fds);
9987750e
FB
1982 log_oom();
1983 return 0;
a354329f 1984 }
b215b0ed 1985 }
8c47c732 1986
15e23e8c 1987 if (!ucred || !pid_is_valid(ucred->pid)) {
b215b0ed
DH
1988 log_warning("Received notify message without valid credentials. Ignoring.");
1989 return 0;
1990 }
8c47c732 1991
045a3d59 1992 if ((size_t) n >= sizeof(buf) || (msghdr.msg_flags & MSG_TRUNC)) {
b215b0ed
DH
1993 log_warning("Received notify message exceeded maximum size. Ignoring.");
1994 return 0;
1995 }
8c47c732 1996
875ca88d
LP
1997 /* As extra safety check, let's make sure the string we get doesn't contain embedded NUL bytes. We permit one
1998 * trailing NUL byte in the message, but don't expect it. */
1999 if (n > 1 && memchr(buf, 0, n-1)) {
2000 log_warning("Received notify message with embedded NUL bytes. Ignoring.");
2001 return 0;
2002 }
2003
2004 /* Make sure it's NUL-terminated. */
b215b0ed 2005 buf[n] = 0;
8c47c732 2006
b215b0ed
DH
2007 /* Notify every unit that might be interested, but try
2008 * to avoid notifying the same one multiple times. */
2009 u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);
c4bee3c4 2010 if (u1)
db256aab 2011 manager_invoke_notify_message(m, u1, ucred, buf, fds);
5ba6985b 2012
b215b0ed 2013 u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid));
c4bee3c4 2014 if (u2 && u2 != u1)
db256aab 2015 manager_invoke_notify_message(m, u2, ucred, buf, fds);
5ba6985b 2016
b215b0ed 2017 u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid));
c4bee3c4 2018 if (u3 && u3 != u2 && u3 != u1)
db256aab 2019 manager_invoke_notify_message(m, u3, ucred, buf, fds);
8c47c732 2020
c4bee3c4 2021 if (!u1 && !u2 && !u3)
b215b0ed 2022 log_warning("Cannot find unit for notify message of PID "PID_FMT".", ucred->pid);
a354329f 2023
b215b0ed 2024 if (fdset_size(fds) > 0)
5fd2c135 2025 log_warning("Got extra auxiliary fds with notification message, closing them.");
8c47c732
LP
2026
2027 return 0;
2028}
2029
96d66d89 2030static void invoke_sigchld_event(Manager *m, Unit *u, const siginfo_t *si) {
36f20ae3
KW
2031 uint64_t iteration;
2032
5ba6985b
LP
2033 assert(m);
2034 assert(u);
2035 assert(si);
2036
36f20ae3
KW
2037 sd_event_get_iteration(m->event, &iteration);
2038
f2341e0a 2039 log_unit_debug(u, "Child "PID_FMT" belongs to %s", si->si_pid, u->id);
5ba6985b
LP
2040
2041 unit_unwatch_pid(u, si->si_pid);
e57051f5 2042
36f20ae3 2043 if (UNIT_VTABLE(u)->sigchld_event) {
ccc2c98e
LN
2044 if (set_size(u->pids) <= 1 ||
2045 iteration != u->sigchldgen ||
2046 unit_main_pid(u) == si->si_pid ||
2047 unit_control_pid(u) == si->si_pid) {
36f20ae3
KW
2048 UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
2049 u->sigchldgen = iteration;
2050 } else
1e706c8d 2051 log_debug("%s already issued a sigchld this iteration %" PRIu64 ", skipping. Pids still being watched %d", u->id, iteration, set_size(u->pids));
36f20ae3 2052 }
5ba6985b
LP
2053}
2054
034c6ed7 2055static int manager_dispatch_sigchld(Manager *m) {
9152c765
LP
2056 assert(m);
2057
2058 for (;;) {
b92bea5d 2059 siginfo_t si = {};
9152c765 2060
4112df16
LP
2061 /* First we call waitd() for a PID and do not reap the
2062 * zombie. That way we can still access /proc/$PID for
2063 * it while it is a zombie. */
2064 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
acbb0225
LP
2065
2066 if (errno == ECHILD)
2067 break;
2068
4112df16
LP
2069 if (errno == EINTR)
2070 continue;
2071
9152c765 2072 return -errno;
acbb0225 2073 }
9152c765 2074
4112df16 2075 if (si.si_pid <= 0)
9152c765
LP
2076 break;
2077
3742095b 2078 if (IN_SET(si.si_code, CLD_EXITED, CLD_KILLED, CLD_DUMPED)) {
7fd1b19b 2079 _cleanup_free_ char *name = NULL;
70af4d17 2080 Unit *u1, *u2, *u3;
4112df16 2081
87d2c1ff 2082 get_process_comm(si.si_pid, &name);
4112df16 2083
5ba6985b
LP
2084 log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
2085 si.si_pid, strna(name),
2086 sigchld_code_to_string(si.si_code),
2087 si.si_status,
2088 strna(si.si_code == CLD_EXITED
2089 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2090 : signal_to_string(si.si_status)));
2091
2092 /* And now figure out the unit this belongs
2093 * to, it might be multiple... */
b3ac818b 2094 u1 = manager_get_unit_by_pid_cgroup(m, si.si_pid);
70af4d17
LP
2095 if (u1)
2096 invoke_sigchld_event(m, u1, &si);
fea72cc0 2097 u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(si.si_pid));
70af4d17
LP
2098 if (u2 && u2 != u1)
2099 invoke_sigchld_event(m, u2, &si);
fea72cc0 2100 u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(si.si_pid));
70af4d17
LP
2101 if (u3 && u3 != u2 && u3 != u1)
2102 invoke_sigchld_event(m, u3, &si);
5ba6985b 2103 }
8c47c732 2104
4112df16
LP
2105 /* And now, we actually reap the zombie. */
2106 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
2107 if (errno == EINTR)
2108 continue;
2109
2110 return -errno;
2111 }
9152c765
LP
2112 }
2113
2114 return 0;
2115}
2116
c75fbada 2117static void manager_start_target(Manager *m, const char *name, JobMode mode) {
4afd3348 2118 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
28247076 2119 int r;
398ef8ba 2120
f2341e0a 2121 log_debug("Activating special unit %s", name);
1e001f52 2122
4bd29fe5 2123 r = manager_add_job_by_name(m, JOB_START, name, mode, &error, NULL);
bd0af849 2124 if (r < 0)
f2341e0a 2125 log_error("Failed to enqueue %s job: %s", name, bus_error_message(&error, r));
28247076
LP
2126}
2127
24dd31c1
LN
2128static void manager_handle_ctrl_alt_del(Manager *m) {
2129 /* If the user presses C-A-D more than
2130 * 7 times within 2s, we reboot/shutdown immediately,
2131 * unless it was disabled in system.conf */
2132
ae8c7939 2133 if (ratelimit_test(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
24dd31c1 2134 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
ae8c7939
LN
2135 else
2136 emergency_action(m, m->cad_burst_action, NULL,
2137 "Ctrl-Alt-Del was pressed more than 7 times within 2s");
24dd31c1
LN
2138}
2139
718db961
LP
2140static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2141 Manager *m = userdata;
9152c765
LP
2142 ssize_t n;
2143 struct signalfd_siginfo sfsi;
2144 bool sigchld = false;
dacd6cee 2145 int r;
9152c765
LP
2146
2147 assert(m);
718db961
LP
2148 assert(m->signal_fd == fd);
2149
2150 if (revents != EPOLLIN) {
2151 log_warning("Got unexpected events from signal file descriptor.");
2152 return 0;
2153 }
9152c765
LP
2154
2155 for (;;) {
718db961 2156 n = read(m->signal_fd, &sfsi, sizeof(sfsi));
57cb4adf 2157 if (n != sizeof(sfsi)) {
8f4d6401
ZJS
2158 if (n >= 0) {
2159 log_warning("Truncated read from signal fd (%zu bytes)!", n);
2160 return 0;
2161 }
9152c765 2162
8f4d6401 2163 if (IN_SET(errno, EINTR, EAGAIN))
acbb0225 2164 break;
9152c765 2165
8f4d6401
ZJS
2166 /* We return an error here, which will kill this handler,
2167 * to avoid a busy loop on read error. */
2168 return log_error_errno(errno, "Reading from signal fd failed: %m");
9152c765
LP
2169 }
2170
4daf54a8 2171 log_received_signal(sfsi.ssi_signo == SIGCHLD ||
463d0d15 2172 (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
4daf54a8
ZJS
2173 ? LOG_DEBUG : LOG_INFO,
2174 &sfsi);
1e001f52 2175
b9cd2ec1
LP
2176 switch (sfsi.ssi_signo) {
2177
4112df16 2178 case SIGCHLD:
9152c765 2179 sigchld = true;
b9cd2ec1
LP
2180 break;
2181
6632c602 2182 case SIGTERM:
463d0d15 2183 if (MANAGER_IS_SYSTEM(m)) {
db06e3b6
LP
2184 /* This is for compatibility with the
2185 * original sysvinit */
ae57dad3
LP
2186 r = verify_run_space_and_log("Refusing to reexecute");
2187 if (r >= 0)
2188 m->exit_code = MANAGER_REEXECUTE;
a1b256b0
LP
2189 break;
2190 }
84e9af1e 2191
4831981d 2192 _fallthrough_;
e11dc4a2 2193 case SIGINT:
c75fbada 2194 if (MANAGER_IS_SYSTEM(m))
24dd31c1 2195 manager_handle_ctrl_alt_del(m);
c75fbada 2196 else
d60cb656
AJ
2197 manager_start_target(m, SPECIAL_EXIT_TARGET,
2198 JOB_REPLACE_IRREVERSIBLY);
a1b256b0 2199 break;
84e9af1e 2200
28247076 2201 case SIGWINCH:
463d0d15 2202 if (MANAGER_IS_SYSTEM(m))
7d793605 2203 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
84e9af1e 2204
28247076
LP
2205 /* This is a nop on non-init */
2206 break;
84e9af1e 2207
28247076 2208 case SIGPWR:
463d0d15 2209 if (MANAGER_IS_SYSTEM(m))
7d793605 2210 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
84e9af1e 2211
28247076 2212 /* This is a nop on non-init */
84e9af1e 2213 break;
6632c602 2214
1005d14f 2215 case SIGUSR1: {
57ee42ce
LP
2216 Unit *u;
2217
2218 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2219
2220 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2221 log_info("Trying to reconnect to bus...");
3996fbe2 2222 bus_init(m, true);
57ee42ce
LP
2223 }
2224
2225 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2226 log_info("Loading D-Bus service...");
7d793605 2227 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
57ee42ce
LP
2228 }
2229
2230 break;
2231 }
2232
2149e37c 2233 case SIGUSR2: {
718db961 2234 _cleanup_free_ char *dump = NULL;
2149e37c 2235
713f6f90 2236 r = manager_get_dump_string(m, &dump);
dacd6cee 2237 if (r < 0) {
713f6f90 2238 log_warning_errno(errno, "Failed to acquire manager dump: %m");
b2cdc666
DM
2239 break;
2240 }
2241
2149e37c 2242 log_dump(LOG_INFO, dump);
1005d14f 2243 break;
2149e37c 2244 }
1005d14f 2245
a16e1123 2246 case SIGHUP:
ae57dad3
LP
2247 r = verify_run_space_and_log("Refusing to reload");
2248 if (r >= 0)
2249 m->exit_code = MANAGER_RELOAD;
a16e1123
LP
2250 break;
2251
7d793605 2252 default: {
253ee27a 2253
0003d1ab 2254 /* Starting SIGRTMIN+0 */
d60cb656
AJ
2255 static const struct {
2256 const char *target;
2257 JobMode mode;
2258 } target_table[] = {
2259 [0] = { SPECIAL_DEFAULT_TARGET, JOB_ISOLATE },
2260 [1] = { SPECIAL_RESCUE_TARGET, JOB_ISOLATE },
2261 [2] = { SPECIAL_EMERGENCY_TARGET, JOB_ISOLATE },
2262 [3] = { SPECIAL_HALT_TARGET, JOB_REPLACE_IRREVERSIBLY },
2263 [4] = { SPECIAL_POWEROFF_TARGET, JOB_REPLACE_IRREVERSIBLY },
2264 [5] = { SPECIAL_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
2265 [6] = { SPECIAL_KEXEC_TARGET, JOB_REPLACE_IRREVERSIBLY }
0003d1ab
LP
2266 };
2267
2268 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2269 static const ManagerExitCode code_table[] = {
2270 [0] = MANAGER_HALT,
2271 [1] = MANAGER_POWEROFF,
2272 [2] = MANAGER_REBOOT,
2273 [3] = MANAGER_KEXEC
7d793605
LP
2274 };
2275
2276 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
0003d1ab 2277 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
764e9b5f 2278 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
d60cb656
AJ
2279 manager_start_target(m, target_table[idx].target,
2280 target_table[idx].mode);
7d793605
LP
2281 break;
2282 }
2283
0003d1ab
LP
2284 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2285 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2286 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2287 break;
2288 }
2289
0658666b
LP
2290 switch (sfsi.ssi_signo - SIGRTMIN) {
2291
2292 case 20:
d450b6f2 2293 manager_set_show_status(m, SHOW_STATUS_YES);
0658666b
LP
2294 break;
2295
2296 case 21:
d450b6f2 2297 manager_set_show_status(m, SHOW_STATUS_NO);
0658666b
LP
2298 break;
2299
253ee27a
LP
2300 case 22:
2301 log_set_max_level(LOG_DEBUG);
4cee3a78 2302 log_info("Setting log level to debug.");
253ee27a
LP
2303 break;
2304
2305 case 23:
2306 log_set_max_level(LOG_INFO);
4cee3a78 2307 log_info("Setting log level to info.");
253ee27a
LP
2308 break;
2309
600b704e 2310 case 24:
463d0d15 2311 if (MANAGER_IS_USER(m)) {
600b704e
LP
2312 m->exit_code = MANAGER_EXIT;
2313 return 0;
2314 }
2315
2316 /* This is a nop on init */
2317 break;
2318
4cfa2c99 2319 case 26:
c1dc6153 2320 case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
4cfa2c99
LP
2321 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2322 log_notice("Setting log target to journal-or-kmsg.");
2323 break;
2324
253ee27a
LP
2325 case 27:
2326 log_set_target(LOG_TARGET_CONSOLE);
2327 log_notice("Setting log target to console.");
2328 break;
2329
2330 case 28:
2331 log_set_target(LOG_TARGET_KMSG);
2332 log_notice("Setting log target to kmsg.");
2333 break;
2334
0658666b 2335 default:
4e240ab0 2336 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
0658666b 2337 }
b9cd2ec1 2338 }
7d793605 2339 }
9152c765
LP
2340 }
2341
2342 if (sigchld)
7b77ed8c 2343 manager_dispatch_sigchld(m);
034c6ed7
LP
2344
2345 return 0;
2346}
2347
718db961
LP
2348static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2349 Manager *m = userdata;
2350 Iterator i;
2351 Unit *u;
034c6ed7
LP
2352
2353 assert(m);
718db961 2354 assert(m->time_change_fd == fd);
034c6ed7 2355
a80c1575 2356 log_struct(LOG_DEBUG,
2b044526 2357 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
e2cc6eca 2358 LOG_MESSAGE("Time has been changed"),
718db961 2359 NULL);
034c6ed7 2360
718db961
LP
2361 /* Restart the watch */
2362 m->time_change_event_source = sd_event_source_unref(m->time_change_event_source);
03e334a1 2363 m->time_change_fd = safe_close(m->time_change_fd);
ef734fd6 2364
718db961 2365 manager_setup_time_change(m);
4e434314 2366
718db961
LP
2367 HASHMAP_FOREACH(u, m->units, i)
2368 if (UNIT_VTABLE(u)->time_change)
2369 UNIT_VTABLE(u)->time_change(u);
ea430986 2370
718db961
LP
2371 return 0;
2372}
ea430986 2373
718db961
LP
2374static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2375 Manager *m = userdata;
8742514c 2376
718db961
LP
2377 assert(m);
2378 assert(m->idle_pipe[2] == fd);
8742514c 2379
718db961 2380 m->no_console_output = m->n_on_console > 0;
03b717a3 2381
718db961 2382 manager_close_idle_pipe(m);
03b717a3 2383
718db961
LP
2384 return 0;
2385}
31a7eb86 2386
718db961
LP
2387static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
2388 Manager *m = userdata;
fd08a840
ZJS
2389 int r;
2390 uint64_t next;
31a7eb86 2391
718db961 2392 assert(m);
fd08a840 2393 assert(source);
9152c765 2394
718db961 2395 manager_print_jobs_in_progress(m);
fd08a840
ZJS
2396
2397 next = now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_PERIOD_USEC;
2398 r = sd_event_source_set_time(source, next);
2399 if (r < 0)
2400 return r;
2401
2402 return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
9152c765
LP
2403}
2404
2405int manager_loop(Manager *m) {
2406 int r;
9152c765 2407
fac9f8df 2408 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
ea430986 2409
9152c765 2410 assert(m);
f755e3b7 2411 m->exit_code = MANAGER_OK;
9152c765 2412
fe51822e 2413 /* Release the path cache */
97044145 2414 m->unit_path_cache = set_free_free(m->unit_path_cache);
fe51822e 2415
b0c918b9
LP
2416 manager_check_finished(m);
2417
a4312405 2418 /* There might still be some zombies hanging around from
f3669545 2419 * before we were exec()'ed. Let's reap them. */
e96d6be7
LP
2420 r = manager_dispatch_sigchld(m);
2421 if (r < 0)
a4312405
LP
2422 return r;
2423
f755e3b7 2424 while (m->exit_code == MANAGER_OK) {
718db961 2425 usec_t wait_usec;
9152c765 2426
463d0d15 2427 if (m->runtime_watchdog > 0 && m->runtime_watchdog != USEC_INFINITY && MANAGER_IS_SYSTEM(m))
e96d6be7
LP
2428 watchdog_ping();
2429
ea430986
LP
2430 if (!ratelimit_test(&rl)) {
2431 /* Yay, something is going seriously wrong, pause a little */
2432 log_warning("Looping too fast. Throttling execution a little.");
2433 sleep(1);
2434 }
2435
37a8e683 2436 if (manager_dispatch_load_queue(m) > 0)
23a177ef
LP
2437 continue;
2438
c5a97ed1
LP
2439 if (manager_dispatch_gc_job_queue(m) > 0)
2440 continue;
2441
2442 if (manager_dispatch_gc_unit_queue(m) > 0)
701cc384
LP
2443 continue;
2444
cf1265e1 2445 if (manager_dispatch_cleanup_queue(m) > 0)
c1e1601e 2446 continue;
034c6ed7 2447
91a6073e 2448 if (manager_dispatch_cgroup_realize_queue(m) > 0)
c1e1601e
LP
2449 continue;
2450
c1e1601e 2451 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 2452 continue;
ea430986 2453
c757a65b 2454 /* Sleep for half the watchdog time */
463d0d15 2455 if (m->runtime_watchdog > 0 && m->runtime_watchdog != USEC_INFINITY && MANAGER_IS_SYSTEM(m)) {
718db961
LP
2456 wait_usec = m->runtime_watchdog / 2;
2457 if (wait_usec <= 0)
2458 wait_usec = 1;
c757a65b 2459 } else
3a43da28 2460 wait_usec = USEC_INFINITY;
9152c765 2461
718db961 2462 r = sd_event_run(m->event, wait_usec);
23bbb0de
MS
2463 if (r < 0)
2464 return log_error_errno(r, "Failed to run event loop: %m");
a16e1123 2465 }
957ca890 2466
a16e1123 2467 return m->exit_code;
83c60c9f 2468}
ea430986 2469
718db961 2470int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
ede3a796 2471 _cleanup_free_ char *n = NULL;
4b58153d 2472 sd_id128_t invocation_id;
ea430986 2473 Unit *u;
80fbf05e 2474 int r;
ea430986
LP
2475
2476 assert(m);
2477 assert(s);
2478 assert(_u);
2479
ede3a796
LP
2480 r = unit_name_from_dbus_path(s, &n);
2481 if (r < 0)
2482 return r;
ea430986 2483
4b58153d
LP
2484 /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128bit ID then we use it
2485 * as invocation ID. */
2486 r = sd_id128_from_string(n, &invocation_id);
2487 if (r >= 0) {
2488 u = hashmap_get(m->units_by_invocation_id, &invocation_id);
2489 if (u) {
2490 *_u = u;
2491 return 0;
2492 }
2493
2494 return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID, "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.", SD_ID128_FORMAT_VAL(invocation_id));
2495 }
2496
00c83b43
LP
2497 /* If this didn't work, we check if this is a unit name */
2498 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
2499 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is neither a valid invocation ID nor unit name.", n);
2500
80fbf05e 2501 r = manager_load_unit(m, n, NULL, e, &u);
80fbf05e
MS
2502 if (r < 0)
2503 return r;
ea430986
LP
2504
2505 *_u = u;
ea430986
LP
2506 return 0;
2507}
86fbf370
LP
2508
2509int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
718db961 2510 const char *p;
86fbf370 2511 unsigned id;
718db961 2512 Job *j;
86fbf370
LP
2513 int r;
2514
2515 assert(m);
2516 assert(s);
2517 assert(_j);
2518
718db961
LP
2519 p = startswith(s, "/org/freedesktop/systemd1/job/");
2520 if (!p)
86fbf370
LP
2521 return -EINVAL;
2522
718db961 2523 r = safe_atou(p, &id);
8742514c 2524 if (r < 0)
86fbf370
LP
2525 return r;
2526
8742514c
LP
2527 j = manager_get_job(m, id);
2528 if (!j)
86fbf370
LP
2529 return -ENOENT;
2530
2531 *_j = j;
2532
2533 return 0;
2534}
dfcd764e 2535
4927fcae 2536void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
e537352b 2537
349cc4a5 2538#if HAVE_AUDIT
2ba11090 2539 _cleanup_free_ char *p = NULL;
0aa281df 2540 const char *msg;
7410616c 2541 int audit_fd, r;
e537352b 2542
463d0d15 2543 if (!MANAGER_IS_SYSTEM(m))
a1a078ee
LP
2544 return;
2545
c1165f82
LP
2546 audit_fd = get_audit_fd();
2547 if (audit_fd < 0)
e537352b
LP
2548 return;
2549
bbd3a7ba
LP
2550 /* Don't generate audit events if the service was already
2551 * started and we're just deserializing */
2c289ea8 2552 if (MANAGER_IS_RELOADING(m))
bbd3a7ba
LP
2553 return;
2554
ac155bb8 2555 if (u->type != UNIT_SERVICE)
f1dd0c3f
LP
2556 return;
2557
7410616c
LP
2558 r = unit_name_to_prefix_and_instance(u->id, &p);
2559 if (r < 0) {
2560 log_error_errno(r, "Failed to extract prefix and instance of unit name: %m");
e537352b
LP
2561 return;
2562 }
2563
63c372cb 2564 msg = strjoina("unit=", p);
0aa281df
LP
2565 if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
2566 if (errno == EPERM)
391ade86 2567 /* We aren't allowed to send audit messages?
44785992 2568 * Then let's not retry again. */
c1165f82 2569 close_audit_fd();
0aa281df 2570 else
56f64d95 2571 log_warning_errno(errno, "Failed to send audit message: %m");
391ade86 2572 }
4927fcae 2573#endif
e537352b 2574
e537352b
LP
2575}
2576
e983b760 2577void manager_send_unit_plymouth(Manager *m, Unit *u) {
fc2fffe7 2578 static const union sockaddr_union sa = PLYMOUTH_SOCKET;
2ba11090
ZJS
2579 _cleanup_free_ char *message = NULL;
2580 _cleanup_close_ int fd = -1;
fc2fffe7 2581 int n = 0;
e983b760
LP
2582
2583 /* Don't generate plymouth events if the service was already
2584 * started and we're just deserializing */
2c289ea8 2585 if (MANAGER_IS_RELOADING(m))
e983b760
LP
2586 return;
2587
463d0d15 2588 if (!MANAGER_IS_SYSTEM(m))
e983b760
LP
2589 return;
2590
75f86906 2591 if (detect_container() > 0)
3772995a
LP
2592 return;
2593
ec2ce0c5 2594 if (!IN_SET(u->type, UNIT_SERVICE, UNIT_MOUNT, UNIT_SWAP))
e983b760
LP
2595 return;
2596
2597 /* We set SOCK_NONBLOCK here so that we rather drop the
2598 * message then wait for plymouth */
e62d8c39
ZJS
2599 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2600 if (fd < 0) {
56f64d95 2601 log_error_errno(errno, "socket() failed: %m");
e983b760
LP
2602 return;
2603 }
2604
fc2fffe7 2605 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
e983b760 2606
2ba11090 2607 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
56f64d95 2608 log_error_errno(errno, "connect() failed: %m");
2ba11090 2609 return;
e983b760
LP
2610 }
2611
ac155bb8 2612 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
0d0f0c50 2613 log_oom();
2ba11090 2614 return;
e983b760
LP
2615 }
2616
2617 errno = 0;
2ba11090
ZJS
2618 if (write(fd, message, n + 1) != n + 1)
2619 if (!IN_SET(errno, EPIPE, EAGAIN, ENOENT, ECONNREFUSED, ECONNRESET, ECONNABORTED))
56f64d95 2620 log_error_errno(errno, "Failed to write Plymouth message: %m");
e983b760
LP
2621}
2622
d8d5ab98 2623int manager_open_serialization(Manager *m, FILE **_f) {
504afd7c 2624 int fd;
a16e1123
LP
2625 FILE *f;
2626
2627 assert(_f);
2628
504afd7c
ZJS
2629 fd = open_serialization_fd("systemd-state");
2630 if (fd < 0)
2631 return fd;
a16e1123 2632
01e10de3 2633 f = fdopen(fd, "w+");
d86f9d52 2634 if (!f) {
03e334a1 2635 safe_close(fd);
a16e1123 2636 return -errno;
d86f9d52 2637 }
a16e1123
LP
2638
2639 *_f = f;
a16e1123
LP
2640 return 0;
2641}
2642
b3680f49 2643int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root) {
9f9f0342
LP
2644 ManagerTimestamp q;
2645 const char *t;
a16e1123
LP
2646 Iterator i;
2647 Unit *u;
a16e1123
LP
2648 int r;
2649
2650 assert(m);
2651 assert(f);
2652 assert(fds);
2653
313cefa1 2654 m->n_reloading++;
38c52d46 2655
1fa2f38f 2656 fprintf(f, "current-job-id=%"PRIu32"\n", m->current_job_id);
33c5fae9
LP
2657 fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
2658 fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
0c2826c6
ZJS
2659 fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
2660 fprintf(f, "ready-sent=%s\n", yes_no(m->ready_sent));
d8eb10d6 2661 fprintf(f, "taint-logged=%s\n", yes_no(m->taint_logged));
2a12e32e 2662 fprintf(f, "service-watchdogs=%s\n", yes_no(m->service_watchdogs));
01d67b43 2663
9f9f0342
LP
2664 for (q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) {
2665 /* The userspace and finish timestamps only apply to the host system, hence only serialize them there */
2666 if (in_initrd() && IN_SET(q, MANAGER_TIMESTAMP_USERSPACE, MANAGER_TIMESTAMP_FINISH))
2667 continue;
f38ed060 2668
9f9f0342
LP
2669 t = manager_timestamp_to_string(q);
2670 {
fbd0b64f 2671 char field[strlen(t) + STRLEN("-timestamp") + 1];
9f9f0342
LP
2672 strcpy(stpcpy(field, t), "-timestamp");
2673 dual_timestamp_serialize(f, field, m->timestamps + q);
2674 }
f38ed060 2675 }
47a483a1 2676
fe902fa4
ZJS
2677 if (!switching_root)
2678 (void) serialize_environment(f, m->environment);
4a9fd066 2679
d86f9d52
LP
2680 if (m->notify_fd >= 0) {
2681 int copy;
2682
2683 copy = fdset_put_dup(fds, m->notify_fd);
2684 if (copy < 0)
2685 return copy;
2686
2687 fprintf(f, "notify-fd=%i\n", copy);
2688 fprintf(f, "notify-socket=%s\n", m->notify_socket);
2689 }
2690
d8fdc620
LP
2691 if (m->cgroups_agent_fd >= 0) {
2692 int copy;
2693
2694 copy = fdset_put_dup(fds, m->cgroups_agent_fd);
2695 if (copy < 0)
2696 return copy;
2697
2698 fprintf(f, "cgroups-agent-fd=%i\n", copy);
2699 }
2700
00d9ef85
LP
2701 if (m->user_lookup_fds[0] >= 0) {
2702 int copy0, copy1;
2703
2704 copy0 = fdset_put_dup(fds, m->user_lookup_fds[0]);
2705 if (copy0 < 0)
2706 return copy0;
2707
2708 copy1 = fdset_put_dup(fds, m->user_lookup_fds[1]);
2709 if (copy1 < 0)
2710 return copy1;
2711
2712 fprintf(f, "user-lookup=%i %i\n", copy0, copy1);
2713 }
2714
05a98afd 2715 bus_track_serialize(m->subscribed, f, "subscribed");
6fa48533 2716
29206d46
LP
2717 r = dynamic_user_serialize(m, f, fds);
2718 if (r < 0)
2719 return r;
2720
00d9ef85
LP
2721 manager_serialize_uid_refs(m, f);
2722 manager_serialize_gid_refs(m, f);
2723
0d536673 2724 (void) fputc('\n', f);
f2382a94 2725
a16e1123 2726 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
ac155bb8 2727 if (u->id != t)
a16e1123
LP
2728 continue;
2729
a16e1123 2730 /* Start marker */
0d536673
LP
2731 fputs(u->id, f);
2732 fputc('\n', f);
a16e1123 2733
6fa48533
LP
2734 r = unit_serialize(u, f, fds, !switching_root);
2735 if (r < 0) {
313cefa1 2736 m->n_reloading--;
a16e1123 2737 return r;
38c52d46 2738 }
a16e1123
LP
2739 }
2740
a7556052 2741 assert(m->n_reloading > 0);
313cefa1 2742 m->n_reloading--;
38c52d46 2743
a16e1123
LP
2744 if (ferror(f))
2745 return -EIO;
2746
b23de6af
LP
2747 r = bus_fdset_add_all(m, fds);
2748 if (r < 0)
2749 return r;
2750
a16e1123
LP
2751 return 0;
2752}
2753
2754int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2755 int r = 0;
2756
2757 assert(m);
2758 assert(f);
2759
2760 log_debug("Deserializing state...");
2761
313cefa1 2762 m->n_reloading++;
82c64bf5 2763
10f8e83c 2764 for (;;) {
d233c99a
ZJS
2765 char line[LINE_MAX];
2766 const char *val, *l;
10f8e83c
LP
2767
2768 if (!fgets(line, sizeof(line), f)) {
2769 if (feof(f))
2770 r = 0;
2771 else
2772 r = -errno;
2773
2774 goto finish;
2775 }
2776
2777 char_array_0(line);
2778 l = strstrip(line);
2779
2780 if (l[0] == 0)
2781 break;
2782
fb4650aa 2783 if ((val = startswith(l, "current-job-id="))) {
01d67b43
LP
2784 uint32_t id;
2785
fb4650aa 2786 if (safe_atou32(val, &id) < 0)
62c460c6 2787 log_notice("Failed to parse current job id value %s", val);
01d67b43
LP
2788 else
2789 m->current_job_id = MAX(m->current_job_id, id);
718db961 2790
fb4650aa 2791 } else if ((val = startswith(l, "n-installed-jobs="))) {
33c5fae9
LP
2792 uint32_t n;
2793
fb4650aa 2794 if (safe_atou32(val, &n) < 0)
62c460c6 2795 log_notice("Failed to parse installed jobs counter %s", val);
33c5fae9
LP
2796 else
2797 m->n_installed_jobs += n;
718db961 2798
fb4650aa 2799 } else if ((val = startswith(l, "n-failed-jobs="))) {
33c5fae9
LP
2800 uint32_t n;
2801
fb4650aa 2802 if (safe_atou32(val, &n) < 0)
62c460c6 2803 log_notice("Failed to parse failed jobs counter %s", val);
33c5fae9
LP
2804 else
2805 m->n_failed_jobs += n;
718db961 2806
fb4650aa 2807 } else if ((val = startswith(l, "taint-usr="))) {
01d67b43
LP
2808 int b;
2809
fb4650aa 2810 b = parse_boolean(val);
e3dd987c 2811 if (b < 0)
62c460c6 2812 log_notice("Failed to parse taint /usr flag %s", val);
01d67b43
LP
2813 else
2814 m->taint_usr = m->taint_usr || b;
718db961 2815
0c2826c6
ZJS
2816 } else if ((val = startswith(l, "ready-sent="))) {
2817 int b;
2818
2819 b = parse_boolean(val);
2820 if (b < 0)
2821 log_notice("Failed to parse ready-sent flag %s", val);
2822 else
2823 m->ready_sent = m->ready_sent || b;
2824
d8eb10d6
ZJS
2825 } else if ((val = startswith(l, "taint-logged="))) {
2826 int b;
2827
2828 b = parse_boolean(val);
2829 if (b < 0)
2830 log_notice("Failed to parse taint-logged flag %s", val);
2831 else
2832 m->taint_logged = m->taint_logged || b;
2833
2a12e32e
JK
2834 } else if ((val = startswith(l, "service-watchdogs="))) {
2835 int b;
2836
2837 b = parse_boolean(val);
2838 if (b < 0)
2839 log_notice("Failed to parse service-watchdogs flag %s", val);
2840 else
2841 m->service_watchdogs = b;
2842
9f9f0342 2843 } else if (startswith(l, "env=")) {
fe902fa4 2844 r = deserialize_environment(&m->environment, l);
d233c99a
ZJS
2845 if (r == -ENOMEM)
2846 goto finish;
527b7a42 2847 if (r < 0)
d233c99a 2848 log_notice_errno(r, "Failed to parse environment entry: \"%s\": %m", l);
e3dd987c 2849
fb4650aa 2850 } else if ((val = startswith(l, "notify-fd="))) {
d86f9d52
LP
2851 int fd;
2852
fb4650aa 2853 if (safe_atoi(val, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
62c460c6 2854 log_notice("Failed to parse notify fd: \"%s\"", val);
d86f9d52 2855 else {
03e334a1
LP
2856 m->notify_event_source = sd_event_source_unref(m->notify_event_source);
2857 safe_close(m->notify_fd);
d86f9d52
LP
2858 m->notify_fd = fdset_remove(fds, fd);
2859 }
2860
fb4650aa 2861 } else if ((val = startswith(l, "notify-socket="))) {
d86f9d52
LP
2862 char *n;
2863
fb4650aa 2864 n = strdup(val);
d86f9d52
LP
2865 if (!n) {
2866 r = -ENOMEM;
2867 goto finish;
2868 }
2869
2870 free(m->notify_socket);
2871 m->notify_socket = n;
2872
fb4650aa 2873 } else if ((val = startswith(l, "cgroups-agent-fd="))) {
d8fdc620
LP
2874 int fd;
2875
fb4650aa 2876 if (safe_atoi(val, &fd) < 0 || fd < 0 || !fdset_contains(fds, fd))
62c460c6 2877 log_notice("Failed to parse cgroups agent fd: %s", val);
d8fdc620
LP
2878 else {
2879 m->cgroups_agent_event_source = sd_event_source_unref(m->cgroups_agent_event_source);
2880 safe_close(m->cgroups_agent_fd);
2881 m->cgroups_agent_fd = fdset_remove(fds, fd);
2882 }
2883
fb4650aa 2884 } else if ((val = startswith(l, "user-lookup="))) {
00d9ef85
LP
2885 int fd0, fd1;
2886
fb4650aa 2887 if (sscanf(val, "%i %i", &fd0, &fd1) != 2 || fd0 < 0 || fd1 < 0 || fd0 == fd1 || !fdset_contains(fds, fd0) || !fdset_contains(fds, fd1))
62c460c6 2888 log_notice("Failed to parse user lookup fd: %s", val);
00d9ef85
LP
2889 else {
2890 m->user_lookup_event_source = sd_event_source_unref(m->user_lookup_event_source);
2891 safe_close_pair(m->user_lookup_fds);
2892 m->user_lookup_fds[0] = fdset_remove(fds, fd0);
2893 m->user_lookup_fds[1] = fdset_remove(fds, fd1);
2894 }
2895
fb4650aa
ZJS
2896 } else if ((val = startswith(l, "dynamic-user=")))
2897 dynamic_user_deserialize_one(m, val, fds);
2898 else if ((val = startswith(l, "destroy-ipc-uid=")))
2899 manager_deserialize_uid_refs_one(m, val);
2900 else if ((val = startswith(l, "destroy-ipc-gid=")))
2901 manager_deserialize_gid_refs_one(m, val);
2902 else if ((val = startswith(l, "subscribed="))) {
05a98afd 2903
fb4650aa 2904 if (strv_extend(&m->deserialized_subscribed, val) < 0)
05a98afd 2905 log_oom();
9f9f0342
LP
2906 } else {
2907 ManagerTimestamp q;
2908
2909 for (q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) {
2910 val = startswith(l, manager_timestamp_to_string(q));
2911 if (!val)
2912 continue;
05a98afd 2913
9f9f0342
LP
2914 val = startswith(val, "-timestamp=");
2915 if (val)
2916 break;
2917 }
05a98afd 2918
9f9f0342
LP
2919 if (q < _MANAGER_TIMESTAMP_MAX) /* found it */
2920 dual_timestamp_deserialize(val, m->timestamps + q);
2921 else if (!startswith(l, "kdbus-fd=")) /* ignore kdbus */
2922 log_notice("Unknown serialization item '%s'", l);
2923 }
10f8e83c
LP
2924 }
2925
a16e1123
LP
2926 for (;;) {
2927 Unit *u;
2928 char name[UNIT_NAME_MAX+2];
07429866 2929 const char* unit_name;
a16e1123
LP
2930
2931 /* Start marker */
2932 if (!fgets(name, sizeof(name), f)) {
2933 if (feof(f))
10f8e83c
LP
2934 r = 0;
2935 else
2936 r = -errno;
a16e1123 2937
82c64bf5 2938 goto finish;
a16e1123
LP
2939 }
2940
2941 char_array_0(name);
07429866 2942 unit_name = strstrip(name);
a16e1123 2943
07429866
ZJS
2944 r = manager_load_unit(m, unit_name, NULL, NULL, &u);
2945 if (r < 0) {
2946 log_notice_errno(r, "Failed to load unit \"%s\", skipping deserialization: %m", unit_name);
2947 if (r == -ENOMEM)
2948 goto finish;
2949 unit_deserialize_skip(f);
2950 continue;
2951 }
a16e1123 2952
01e10de3 2953 r = unit_deserialize(u, f, fds);
07429866
ZJS
2954 if (r < 0) {
2955 log_notice_errno(r, "Failed to deserialize unit \"%s\": %m", unit_name);
2956 if (r == -ENOMEM)
2957 goto finish;
2958 }
a16e1123
LP
2959 }
2960
10f8e83c 2961finish:
145b1f79 2962 if (ferror(f))
82c64bf5 2963 r = -EIO;
a16e1123 2964
a7556052 2965 assert(m->n_reloading > 0);
313cefa1 2966 m->n_reloading--;
82c64bf5
LP
2967
2968 return r;
a16e1123
LP
2969}
2970
2971int manager_reload(Manager *m) {
2972 int r, q;
51d122af
ZJS
2973 _cleanup_fclose_ FILE *f = NULL;
2974 _cleanup_fdset_free_ FDSet *fds = NULL;
a16e1123
LP
2975
2976 assert(m);
2977
07719a21
LP
2978 r = manager_open_serialization(m, &f);
2979 if (r < 0)
a16e1123
LP
2980 return r;
2981
313cefa1 2982 m->n_reloading++;
718db961 2983 bus_manager_send_reloading(m, true);
38c52d46 2984
07719a21
LP
2985 fds = fdset_new();
2986 if (!fds) {
313cefa1 2987 m->n_reloading--;
51d122af 2988 return -ENOMEM;
a16e1123
LP
2989 }
2990
b3680f49 2991 r = manager_serialize(m, f, fds, false);
07719a21 2992 if (r < 0) {
313cefa1 2993 m->n_reloading--;
51d122af 2994 return r;
38c52d46 2995 }
a16e1123
LP
2996
2997 if (fseeko(f, 0, SEEK_SET) < 0) {
313cefa1 2998 m->n_reloading--;
51d122af 2999 return -errno;
a16e1123
LP
3000 }
3001
3002 /* From here on there is no way back. */
3003 manager_clear_jobs_and_units(m);
07a78643 3004 lookup_paths_flush_generator(&m->lookup_paths);
84e3543e 3005 lookup_paths_free(&m->lookup_paths);
29206d46 3006 dynamic_user_vacuum(m, false);
00d9ef85
LP
3007 m->uid_refs = hashmap_free(m->uid_refs);
3008 m->gid_refs = hashmap_free(m->gid_refs);
2ded0c04 3009
4943d143 3010 q = lookup_paths_init(&m->lookup_paths, m->unit_file_scope, 0, NULL);
e801700e
ZJS
3011 if (q < 0 && r >= 0)
3012 r = q;
5a1e9937 3013
64691d20
ZJS
3014 q = manager_run_environment_generators(m);
3015 if (q < 0 && r >= 0)
3016 r = q;
3017
a3c4eb07
LP
3018 /* Find new unit paths */
3019 q = manager_run_generators(m);
e801700e 3020 if (q < 0 && r >= 0)
07719a21
LP
3021 r = q;
3022
a1453343 3023 lookup_paths_reduce(&m->lookup_paths);
5a1e9937
LP
3024 manager_build_unit_path_cache(m);
3025
a16e1123 3026 /* First, enumerate what we can from all config files */
ba64af90 3027 manager_enumerate(m);
a16e1123
LP
3028
3029 /* Second, deserialize our stored data */
07719a21 3030 q = manager_deserialize(m, f, fds);
07429866
ZJS
3031 if (q < 0) {
3032 log_error_errno(q, "Deserialization failed: %m");
3033
3034 if (r >= 0)
3035 r = q;
3036 }
a16e1123
LP
3037
3038 fclose(f);
3039 f = NULL;
3040
a2cc4a6c
ZJS
3041 /* Re-register notify_fd as event source */
3042 q = manager_setup_notify(m);
e801700e 3043 if (q < 0 && r >= 0)
a2cc4a6c
ZJS
3044 r = q;
3045
d8fdc620
LP
3046 q = manager_setup_cgroups_agent(m);
3047 if (q < 0 && r >= 0)
3048 r = q;
3049
00d9ef85
LP
3050 q = manager_setup_user_lookup_fd(m);
3051 if (q < 0 && r >= 0)
3052 r = q;
3053
a16e1123 3054 /* Third, fire things up! */
007c6337 3055 manager_coldplug(m);
a16e1123 3056
29206d46
LP
3057 /* Release any dynamic users no longer referenced */
3058 dynamic_user_vacuum(m, true);
3059
00d9ef85
LP
3060 /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
3061 manager_vacuum_uid_refs(m);
3062 manager_vacuum_gid_refs(m);
3063
8936a5e3
DM
3064 /* Sync current state of bus names with our set of listening units */
3065 if (m->api_bus)
3066 manager_sync_bus_names(m, m->api_bus);
3067
a7556052
LP
3068 assert(m->n_reloading > 0);
3069 m->n_reloading--;
9f611ad8 3070
71445ae7
LP
3071 m->send_reloading_done = true;
3072
a16e1123
LP
3073 return r;
3074}
3075
fdf20a31 3076void manager_reset_failed(Manager *m) {
5632e374
LP
3077 Unit *u;
3078 Iterator i;
3079
3080 assert(m);
3081
3082 HASHMAP_FOREACH(u, m->units, i)
fdf20a31 3083 unit_reset_failed(u);
5632e374
LP
3084}
3085
31afa0a4 3086bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
8f6df3fa
LP
3087 Unit *u;
3088
3089 assert(m);
3090 assert(name);
3091
3092 /* Returns true if the unit is inactive or going down */
bd0af849
ZJS
3093 u = manager_get_unit(m, name);
3094 if (!u)
8f6df3fa
LP
3095 return true;
3096
31afa0a4 3097 return unit_inactive_or_pending(u);
8f6df3fa
LP
3098}
3099
d8eb10d6
ZJS
3100static void log_taint_string(Manager *m) {
3101 _cleanup_free_ char *taint = NULL;
3102
3103 assert(m);
3104
3105 if (MANAGER_IS_USER(m) || m->taint_logged)
3106 return;
3107
3108 m->taint_logged = true; /* only check for taint once */
3109
3110 taint = manager_taint_string(m);
3111 if (isempty(taint))
3112 return;
3113
3114 log_struct(LOG_NOTICE,
3115 LOG_MESSAGE("System is tainted: %s", taint),
3116 "TAINT=%s", taint,
3117 "MESSAGE_ID=" SD_MESSAGE_TAINTED_STR,
3118 NULL);
3119}
3120
56dacdbc 3121static void manager_notify_finished(Manager *m) {
7ceba241 3122 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
915b3753 3123 usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
b0c918b9 3124
e0a3da1f 3125 if (m->test_run_flags)
b0c918b9
LP
3126 return;
3127
463d0d15 3128 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
e03ae661 3129
9f9f0342
LP
3130 /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3131 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
915b3753
LP
3132 * negative values. */
3133
9f9f0342
LP
3134 firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
3135 loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
3136 userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
3137 total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
18fa6b27 3138
9f9f0342 3139 if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
18fa6b27 3140
9f9f0342
LP
3141 /* The initrd case on bare-metal*/
3142 kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
3143 initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
18fa6b27 3144
e12919e8 3145 log_struct(LOG_INFO,
2b044526 3146 "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
e12919e8
LP
3147 "KERNEL_USEC="USEC_FMT, kernel_usec,
3148 "INITRD_USEC="USEC_FMT, initrd_usec,
3149 "USERSPACE_USEC="USEC_FMT, userspace_usec,
e2cc6eca
LP
3150 LOG_MESSAGE("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
3151 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
3152 format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC),
3153 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
3154 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
e12919e8 3155 NULL);
18fa6b27 3156 } else {
9f9f0342
LP
3157 /* The initrd-less case on bare-metal*/
3158
3159 kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
18fa6b27
LP
3160 initrd_usec = 0;
3161
81270860 3162 log_struct(LOG_INFO,
2b044526 3163 "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
e12919e8 3164 "KERNEL_USEC="USEC_FMT, kernel_usec,
ccd06097 3165 "USERSPACE_USEC="USEC_FMT, userspace_usec,
e2cc6eca
LP
3166 LOG_MESSAGE("Startup finished in %s (kernel) + %s (userspace) = %s.",
3167 format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC),
3168 format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC),
3169 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
81270860 3170 NULL);
e12919e8
LP
3171 }
3172 } else {
4adf314b 3173 /* The container and --user case */
e12919e8 3174 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
9f9f0342 3175 total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
e12919e8
LP
3176
3177 log_struct(LOG_INFO,
2b044526 3178 "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR,
e12919e8 3179 "USERSPACE_USEC="USEC_FMT, userspace_usec,
e2cc6eca
LP
3180 LOG_MESSAGE("Startup finished in %s.",
3181 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)),
e12919e8 3182 NULL);
18fa6b27 3183 }
b0c918b9 3184
718db961 3185 bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
530345e7
LP
3186
3187 sd_notifyf(false,
0c2826c6
ZJS
3188 m->ready_sent ? "STATUS=Startup finished in %s."
3189 : "READY=1\n"
3190 "STATUS=Startup finished in %s.",
2fa4092c 3191 format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC));
0c2826c6 3192 m->ready_sent = true;
d8eb10d6
ZJS
3193
3194 log_taint_string(m);
b0c918b9
LP
3195}
3196
4adf314b
LP
3197static void manager_send_ready(Manager *m) {
3198 assert(m);
3199
3200 /* We send READY=1 on reaching basic.target only when running in --user mode. */
3201 if (!MANAGER_IS_USER(m) || m->ready_sent)
3202 return;
3203
3204 m->ready_sent = true;
3205
3206 sd_notifyf(false,
3207 "READY=1\n"
3208 "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
3209}
3210
3211static void manager_check_basic_target(Manager *m) {
3212 Unit *u;
3213
3214 assert(m);
3215
3216 /* Small shortcut */
3217 if (m->ready_sent && m->taint_logged)
3218 return;
3219
3220 u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
3221 if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
3222 return;
3223
3224 /* For user managers, send out READY=1 as soon as we reach basic.target */
3225 manager_send_ready(m);
3226
3227 /* Log the taint string as soon as we reach basic.target */
3228 log_taint_string(m);
3229}
3230
56dacdbc 3231void manager_check_finished(Manager *m) {
56dacdbc
ZJS
3232 assert(m);
3233
2c289ea8 3234 if (MANAGER_IS_RELOADING(m))
aad1976f
LP
3235 return;
3236
9771b62d
LP
3237 /* Verify that we are actually running currently. Initially
3238 * the exit code is set to invalid, and during operation it is
3239 * then set to MANAGER_OK */
3240 if (m->exit_code != MANAGER_OK)
3241 return;
3242
4adf314b 3243 manager_check_basic_target(m);
0c2826c6 3244
56dacdbc 3245 if (hashmap_size(m->jobs) > 0) {
56dacdbc 3246 if (m->jobs_in_progress_event_source)
2ae56591 3247 /* Ignore any failure, this is only for feedback */
e7ab4d1a 3248 (void) sd_event_source_set_time(m->jobs_in_progress_event_source, now(CLOCK_MONOTONIC) + JOBS_IN_PROGRESS_WAIT_USEC);
56dacdbc
ZJS
3249
3250 return;
3251 }
3252
3253 manager_flip_auto_status(m, false);
3254
3255 /* Notify Type=idle units that we are done now */
56dacdbc
ZJS
3256 manager_close_idle_pipe(m);
3257
3258 /* Turn off confirm spawn now */
7d5ceb64 3259 m->confirm_spawn = NULL;
56dacdbc
ZJS
3260
3261 /* No need to update ask password status when we're going non-interactive */
3262 manager_close_ask_password(m);
3263
3264 /* This is no longer the first boot */
3265 manager_set_first_boot(m, false);
3266
49d5666c 3267 if (MANAGER_IS_FINISHED(m))
56dacdbc
ZJS
3268 return;
3269
9f9f0342 3270 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_FINISH);
56dacdbc
ZJS
3271
3272 manager_notify_finished(m);
3273
e7ab4d1a 3274 manager_invalidate_startup_units(m);
56dacdbc
ZJS
3275}
3276
64691d20
ZJS
3277static bool generator_path_any(const char* const* paths) {
3278 char **path;
3279 bool found = false;
3280
3281 /* Optimize by skipping the whole process by not creating output directories
3282 * if no generators are found. */
3283 STRV_FOREACH(path, (char**) paths)
3284 if (access(*path, F_OK) == 0)
3285 found = true;
3286 else if (errno != ENOENT)
3287 log_warning_errno(errno, "Failed to open generator directory %s: %m", *path);
3288
3289 return found;
3290}
3291
3292static const char* system_env_generator_binary_paths[] = {
3293 "/run/systemd/system-environment-generators",
3294 "/etc/systemd/system-environment-generators",
3295 "/usr/local/lib/systemd/system-environment-generators",
3296 SYSTEM_ENV_GENERATOR_PATH,
3297 NULL
3298};
3299
3300static const char* user_env_generator_binary_paths[] = {
3301 "/run/systemd/user-environment-generators",
3302 "/etc/systemd/user-environment-generators",
3303 "/usr/local/lib/systemd/user-environment-generators",
3304 USER_ENV_GENERATOR_PATH,
3305 NULL
3306};
3307
3308static int manager_run_environment_generators(Manager *m) {
3309 char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
3310 const char **paths;
3311 void* args[] = {&tmp, &tmp, &m->environment};
3312
e0a3da1f
ZJS
3313 if (m->test_run_flags && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
3314 return 0;
3315
64691d20
ZJS
3316 paths = MANAGER_IS_SYSTEM(m) ? system_env_generator_binary_paths : user_env_generator_binary_paths;
3317
3318 if (!generator_path_any(paths))
3319 return 0;
3320
3321 return execute_directories(paths, DEFAULT_TIMEOUT_USEC, gather_environment, args, NULL);
3322}
3323
e801700e 3324static int manager_run_generators(Manager *m) {
f42348ac 3325 _cleanup_strv_free_ char **paths = NULL;
07719a21 3326 const char *argv[5];
07719a21 3327 int r;
5a1e9937
LP
3328
3329 assert(m);
3330
e0a3da1f
ZJS
3331 if (m->test_run_flags && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
3332 return 0;
3333
9183df70 3334 paths = generator_binary_paths(m->unit_file_scope);
e801700e
ZJS
3335 if (!paths)
3336 return log_oom();
5a1e9937 3337
64691d20
ZJS
3338 if (!generator_path_any((const char* const*) paths))
3339 return 0;
5a1e9937 3340
cd64fd56 3341 r = lookup_paths_mkdir_generator(&m->lookup_paths);
07719a21
LP
3342 if (r < 0)
3343 goto finish;
5a1e9937 3344
83cc030f 3345 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
a3c4eb07
LP
3346 argv[1] = m->lookup_paths.generator;
3347 argv[2] = m->lookup_paths.generator_early;
3348 argv[3] = m->lookup_paths.generator_late;
07719a21 3349 argv[4] = NULL;
5a1e9937 3350
718db961 3351 RUN_WITH_UMASK(0022)
c6e47247
ZJS
3352 execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC,
3353 NULL, NULL, (char**) argv);
5a1e9937 3354
718db961 3355finish:
cd64fd56 3356 lookup_paths_trim_generator(&m->lookup_paths);
e801700e 3357 return r;
5a1e9937
LP
3358}
3359
718db961
LP
3360int manager_environment_add(Manager *m, char **minus, char **plus) {
3361 char **a = NULL, **b = NULL, **l;
97d0e5f8 3362 assert(m);
bcd8e6d1 3363
718db961 3364 l = m->environment;
bcd8e6d1 3365
718db961
LP
3366 if (!strv_isempty(minus)) {
3367 a = strv_env_delete(l, 1, minus);
3368 if (!a)
3369 return -ENOMEM;
3370
3371 l = a;
3372 }
3373
3374 if (!strv_isempty(plus)) {
3375 b = strv_env_merge(2, l, plus);
aa9f8a30
AH
3376 if (!b) {
3377 strv_free(a);
718db961 3378 return -ENOMEM;
aa9f8a30 3379 }
bcd8e6d1 3380
718db961
LP
3381 l = b;
3382 }
3383
3384 if (m->environment != l)
3385 strv_free(m->environment);
3386 if (a != l)
3387 strv_free(a);
3388 if (b != l)
3389 strv_free(b);
3390
f069efb4 3391 m->environment = l;
47cf8ff2 3392 manager_sanitize_environment(m);
f069efb4 3393
97d0e5f8
UTL
3394 return 0;
3395}
3396
c93ff2e9
FC
3397int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
3398 int i;
3399
3400 assert(m);
3401
517d56b1 3402 for (i = 0; i < _RLIMIT_MAX; i++) {
d9814c76
EV
3403 m->rlimit[i] = mfree(m->rlimit[i]);
3404
07719a21
LP
3405 if (!default_rlimit[i])
3406 continue;
c93ff2e9 3407
07719a21
LP
3408 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
3409 if (!m->rlimit[i])
3ce40911 3410 return log_oom();
c93ff2e9
FC
3411 }
3412
3413 return 0;
3414}
3415
4cfa2c99 3416void manager_recheck_journal(Manager *m) {
f1dd0c3f
LP
3417 Unit *u;
3418
3419 assert(m);
3420
463d0d15 3421 if (!MANAGER_IS_SYSTEM(m))
f1dd0c3f
LP
3422 return;
3423
731a676c
LP
3424 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
3425 if (u && SOCKET(u)->state != SOCKET_RUNNING) {
4cfa2c99 3426 log_close_journal();
731a676c 3427 return;
f1dd0c3f
LP
3428 }
3429
731a676c
LP
3430 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
3431 if (u && SERVICE(u)->state != SERVICE_RUNNING) {
4cfa2c99 3432 log_close_journal();
731a676c
LP
3433 return;
3434 }
f1dd0c3f 3435
731a676c
LP
3436 /* Hmm, OK, so the socket is fully up and the service is up
3437 * too, then let's make use of the thing. */
f1dd0c3f
LP
3438 log_open();
3439}
3440
d450b6f2 3441void manager_set_show_status(Manager *m, ShowStatus mode) {
27d340c7 3442 assert(m);
d450b6f2 3443 assert(IN_SET(mode, SHOW_STATUS_AUTO, SHOW_STATUS_NO, SHOW_STATUS_YES, SHOW_STATUS_TEMPORARY));
27d340c7 3444
463d0d15 3445 if (!MANAGER_IS_SYSTEM(m))
27d340c7
LP
3446 return;
3447
76b6f3f6
ZJS
3448 if (m->show_status != mode)
3449 log_debug("%s showing of status.",
3450 mode == SHOW_STATUS_NO ? "Disabling" : "Enabling");
d450b6f2 3451 m->show_status = mode;
27d340c7 3452
d450b6f2 3453 if (mode > 0)
ac5b0c13 3454 (void) touch("/run/systemd/show-status");
27d340c7 3455 else
ac5b0c13 3456 (void) unlink("/run/systemd/show-status");
27d340c7
LP
3457}
3458
127d5fd1 3459static bool manager_get_show_status(Manager *m, StatusType type) {
27d340c7
LP
3460 assert(m);
3461
463d0d15 3462 if (!MANAGER_IS_SYSTEM(m))
27d340c7
LP
3463 return false;
3464
31a7eb86
ZJS
3465 if (m->no_console_output)
3466 return false;
3467
d81afec1 3468 if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
08510627
LP
3469 return false;
3470
e46b13c8 3471 /* If we cannot find out the status properly, just proceed. */
ebc5788e 3472 if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
e46b13c8
ZJS
3473 return false;
3474
d450b6f2 3475 if (m->show_status > 0)
27d340c7
LP
3476 return true;
3477
031886ed 3478 return false;
27d340c7 3479}
68b29a9f 3480
7d5ceb64
FB
3481const char *manager_get_confirm_spawn(Manager *m) {
3482 static int last_errno = 0;
3483 const char *vc = m->confirm_spawn;
3484 struct stat st;
3485 int r;
3486
3487 /* Here's the deal: we want to test the validity of the console but don't want
3488 * PID1 to go through the whole console process which might block. But we also
3489 * want to warn the user only once if something is wrong with the console so we
3490 * cannot do the sanity checks after spawning our children. So here we simply do
3491 * really basic tests to hopefully trap common errors.
3492 *
3493 * If the console suddenly disappear at the time our children will really it
3494 * then they will simply fail to acquire it and a positive answer will be
3495 * assumed. New children will fallback to /dev/console though.
3496 *
3497 * Note: TTYs are devices that can come and go any time, and frequently aren't
3498 * available yet during early boot (consider a USB rs232 dongle...). If for any
3499 * reason the configured console is not ready, we fallback to the default
3500 * console. */
3501
3502 if (!vc || path_equal(vc, "/dev/console"))
3503 return vc;
3504
3505 r = stat(vc, &st);
3506 if (r < 0)
3507 goto fail;
3508
3509 if (!S_ISCHR(st.st_mode)) {
3510 errno = ENOTTY;
3511 goto fail;
3512 }
3513
3514 last_errno = 0;
3515 return vc;
3516fail:
3517 if (last_errno != errno) {
3518 last_errno = errno;
3519 log_warning_errno(errno, "Failed to open %s: %m, using default console", vc);
3520 }
3521 return "/dev/console";
3522}
3523
e2680723
LP
3524void manager_set_first_boot(Manager *m, bool b) {
3525 assert(m);
3526
463d0d15 3527 if (!MANAGER_IS_SYSTEM(m))
e2680723
LP
3528 return;
3529
ae2a2c53
LP
3530 if (m->first_boot != (int) b) {
3531 if (b)
3532 (void) touch("/run/systemd/first-boot");
3533 else
3534 (void) unlink("/run/systemd/first-boot");
3535 }
e2680723 3536
ae2a2c53 3537 m->first_boot = b;
e2680723
LP
3538}
3539
b0eb2944
FB
3540void manager_disable_confirm_spawn(void) {
3541 (void) touch("/run/systemd/confirm_spawn_disabled");
3542}
3543
3544bool manager_is_confirm_spawn_disabled(Manager *m) {
3545 if (!m->confirm_spawn)
3546 return true;
3547
3548 return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
3549}
3550
127d5fd1 3551void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
25cee550
MS
3552 va_list ap;
3553
cb6531be
ZJS
3554 /* If m is NULL, assume we're after shutdown and let the messages through. */
3555
3556 if (m && !manager_get_show_status(m, type))
25cee550
MS
3557 return;
3558
03b717a3
MS
3559 /* XXX We should totally drop the check for ephemeral here
3560 * and thus effectively make 'Type=idle' pointless. */
cb6531be 3561 if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
03b717a3
MS
3562 return;
3563
25cee550 3564 va_start(ap, format);
127d5fd1 3565 status_vprintf(status, true, type == STATUS_TYPE_EPHEMERAL, format, ap);
25cee550
MS
3566 va_end(ap);
3567}
3568
a57f7e2c
LP
3569Set *manager_get_units_requiring_mounts_for(Manager *m, const char *path) {
3570 char p[strlen(path)+1];
3571
3572 assert(m);
3573 assert(path);
3574
3575 strcpy(p, path);
3576 path_kill_slashes(p);
3577
3578 return hashmap_get(m->units_requiring_mounts_for, streq(p, "/") ? "" : p);
3579}
e66cf1a3 3580
19bbdd98 3581void manager_set_exec_params(Manager *m, ExecParameters *p) {
f755e3b7 3582 assert(m);
3536f49e
YW
3583 assert(p);
3584
3585 p->environment = m->environment;
3586 p->confirm_spawn = manager_get_confirm_spawn(m);
3587 p->cgroup_supported = m->cgroup_supported;
3588 p->prefix = m->prefix;
e66cf1a3 3589
8679efde 3590 SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(m));
e66cf1a3 3591}
f755e3b7 3592
5269eb6b 3593int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
03455c28 3594 unsigned size;
5269eb6b 3595 int r;
03455c28
LDM
3596
3597 assert(m);
3598 assert(u->manager == m);
3599
3600 size = set_size(m->failed_units);
3601
9fff8981 3602 if (failed) {
5269eb6b
LP
3603 r = set_ensure_allocated(&m->failed_units, NULL);
3604 if (r < 0)
3605 return log_oom();
3606
9fff8981 3607 if (set_put(m->failed_units, u) < 0)
5269eb6b 3608 return log_oom();
9fff8981 3609 } else
5269eb6b 3610 (void) set_remove(m->failed_units, u);
03455c28
LDM
3611
3612 if (set_size(m->failed_units) != size)
3613 bus_manager_send_change_signal(m);
5269eb6b
LP
3614
3615 return 0;
03455c28
LDM
3616}
3617
f755e3b7
LP
3618ManagerState manager_state(Manager *m) {
3619 Unit *u;
3620
3621 assert(m);
3622
3623 /* Did we ever finish booting? If not then we are still starting up */
49d5666c 3624 if (!MANAGER_IS_FINISHED(m)) {
d81afec1
LP
3625
3626 u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
3627 if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
3628 return MANAGER_INITIALIZING;
3629
f755e3b7 3630 return MANAGER_STARTING;
d81afec1 3631 }
f755e3b7 3632
e68537f0 3633 /* Is the special shutdown target active or queued? If so, we are in shutdown state */
f755e3b7 3634 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
706424c2 3635 if (u && unit_active_or_pending(u))
f755e3b7
LP
3636 return MANAGER_STOPPING;
3637
45a7b16b
LP
3638 if (MANAGER_IS_SYSTEM(m)) {
3639 /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
3640 u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
3641 if (u && unit_active_or_pending(u))
3642 return MANAGER_MAINTENANCE;
f755e3b7 3643
45a7b16b
LP
3644 u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
3645 if (u && unit_active_or_pending(u))
3646 return MANAGER_MAINTENANCE;
3647 }
f755e3b7
LP
3648
3649 /* Are there any failed units? If so, we are in degraded mode */
3650 if (set_size(m->failed_units) > 0)
3651 return MANAGER_DEGRADED;
3652
3653 return MANAGER_RUNNING;
3654}
3655
00d9ef85
LP
3656#define DESTROY_IPC_FLAG (UINT32_C(1) << 31)
3657
3658static void manager_unref_uid_internal(
3659 Manager *m,
3660 Hashmap **uid_refs,
3661 uid_t uid,
3662 bool destroy_now,
3663 int (*_clean_ipc)(uid_t uid)) {
3664
3665 uint32_t c, n;
3666
3667 assert(m);
3668 assert(uid_refs);
3669 assert(uid_is_valid(uid));
3670 assert(_clean_ipc);
3671
3672 /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the assumption
3673 * that uid_t and gid_t are actually defined the same way, with the same validity rules.
3674 *
3675 * We store a hashmap where the UID/GID is they key and the value is a 32bit reference counter, whose highest
3676 * bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last reference to the UID/GID
3677 * is dropped. The flag is set to on, once at least one reference from a unit where RemoveIPC= is set is added
3678 * on a UID/GID. It is reset when the UID's/GID's reference counter drops to 0 again. */
3679
3680 assert_cc(sizeof(uid_t) == sizeof(gid_t));
3681 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
3682
3683 if (uid == 0) /* We don't keep track of root, and will never destroy it */
3684 return;
3685
3686 c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
3687
3688 n = c & ~DESTROY_IPC_FLAG;
3689 assert(n > 0);
3690 n--;
3691
3692 if (destroy_now && n == 0) {
3693 hashmap_remove(*uid_refs, UID_TO_PTR(uid));
3694
3695 if (c & DESTROY_IPC_FLAG) {
3696 log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
3697 _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
3698 uid);
3699 (void) _clean_ipc(uid);
3700 }
3701 } else {
3702 c = n | (c & DESTROY_IPC_FLAG);
3703 assert_se(hashmap_update(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
3704 }
3705}
3706
3707void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
3708 manager_unref_uid_internal(m, &m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
3709}
3710
3711void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
3712 manager_unref_uid_internal(m, &m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
3713}
3714
3715static int manager_ref_uid_internal(
3716 Manager *m,
3717 Hashmap **uid_refs,
3718 uid_t uid,
3719 bool clean_ipc) {
3720
3721 uint32_t c, n;
3722 int r;
3723
3724 assert(m);
3725 assert(uid_refs);
3726 assert(uid_is_valid(uid));
3727
3728 /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the assumption
3729 * that uid_t and gid_t are actually defined the same way, with the same validity rules. */
3730
3731 assert_cc(sizeof(uid_t) == sizeof(gid_t));
3732 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
3733
3734 if (uid == 0) /* We don't keep track of root, and will never destroy it */
3735 return 0;
3736
3737 r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
3738 if (r < 0)
3739 return r;
3740
3741 c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
3742
3743 n = c & ~DESTROY_IPC_FLAG;
3744 n++;
3745
3746 if (n & DESTROY_IPC_FLAG) /* check for overflow */
3747 return -EOVERFLOW;
3748
3749 c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
3750
3751 return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
3752}
3753
3754int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
3755 return manager_ref_uid_internal(m, &m->uid_refs, uid, clean_ipc);
3756}
3757
3758int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
3759 return manager_ref_uid_internal(m, &m->gid_refs, (uid_t) gid, clean_ipc);
3760}
3761
3762static void manager_vacuum_uid_refs_internal(
3763 Manager *m,
3764 Hashmap **uid_refs,
3765 int (*_clean_ipc)(uid_t uid)) {
3766
3767 Iterator i;
3768 void *p, *k;
3769
3770 assert(m);
3771 assert(uid_refs);
3772 assert(_clean_ipc);
3773
3774 HASHMAP_FOREACH_KEY(p, k, *uid_refs, i) {
3775 uint32_t c, n;
3776 uid_t uid;
3777
3778 uid = PTR_TO_UID(k);
3779 c = PTR_TO_UINT32(p);
3780
3781 n = c & ~DESTROY_IPC_FLAG;
3782 if (n > 0)
3783 continue;
3784
3785 if (c & DESTROY_IPC_FLAG) {
3786 log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
3787 _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
3788 uid);
3789 (void) _clean_ipc(uid);
3790 }
3791
3792 assert_se(hashmap_remove(*uid_refs, k) == p);
3793 }
3794}
3795
3796void manager_vacuum_uid_refs(Manager *m) {
3797 manager_vacuum_uid_refs_internal(m, &m->uid_refs, clean_ipc_by_uid);
3798}
3799
3800void manager_vacuum_gid_refs(Manager *m) {
3801 manager_vacuum_uid_refs_internal(m, &m->gid_refs, clean_ipc_by_gid);
3802}
3803
3804static void manager_serialize_uid_refs_internal(
3805 Manager *m,
3806 FILE *f,
3807 Hashmap **uid_refs,
3808 const char *field_name) {
3809
3810 Iterator i;
3811 void *p, *k;
3812
3813 assert(m);
3814 assert(f);
3815 assert(uid_refs);
3816 assert(field_name);
3817
3818 /* Serialize the UID reference table. Or actually, just the IPC destruction flag of it, as the actual counter
3819 * of it is better rebuild after a reload/reexec. */
3820
3821 HASHMAP_FOREACH_KEY(p, k, *uid_refs, i) {
3822 uint32_t c;
3823 uid_t uid;
3824
3825 uid = PTR_TO_UID(k);
3826 c = PTR_TO_UINT32(p);
3827
3828 if (!(c & DESTROY_IPC_FLAG))
3829 continue;
3830
3831 fprintf(f, "%s=" UID_FMT "\n", field_name, uid);
3832 }
3833}
3834
3835void manager_serialize_uid_refs(Manager *m, FILE *f) {
3836 manager_serialize_uid_refs_internal(m, f, &m->uid_refs, "destroy-ipc-uid");
3837}
3838
3839void manager_serialize_gid_refs(Manager *m, FILE *f) {
3840 manager_serialize_uid_refs_internal(m, f, &m->gid_refs, "destroy-ipc-gid");
3841}
3842
3843static void manager_deserialize_uid_refs_one_internal(
3844 Manager *m,
3845 Hashmap** uid_refs,
3846 const char *value) {
3847
3848 uid_t uid;
3849 uint32_t c;
3850 int r;
3851
3852 assert(m);
3853 assert(uid_refs);
3854 assert(value);
3855
3856 r = parse_uid(value, &uid);
3857 if (r < 0 || uid == 0) {
3858 log_debug("Unable to parse UID reference serialization");
3859 return;
3860 }
3861
3862 r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
3863 if (r < 0) {
3864 log_oom();
3865 return;
3866 }
3867
3868 c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
3869 if (c & DESTROY_IPC_FLAG)
3870 return;
3871
3872 c |= DESTROY_IPC_FLAG;
3873
3874 r = hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
3875 if (r < 0) {
3876 log_debug("Failed to add UID reference entry");
3877 return;
3878 }
3879}
3880
3881void manager_deserialize_uid_refs_one(Manager *m, const char *value) {
3882 manager_deserialize_uid_refs_one_internal(m, &m->uid_refs, value);
3883}
3884
3885void manager_deserialize_gid_refs_one(Manager *m, const char *value) {
3886 manager_deserialize_uid_refs_one_internal(m, &m->gid_refs, value);
3887}
3888
3889int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3890 struct buffer {
3891 uid_t uid;
3892 gid_t gid;
3893 char unit_name[UNIT_NAME_MAX+1];
3894 } _packed_ buffer;
3895
3896 Manager *m = userdata;
3897 ssize_t l;
3898 size_t n;
3899 Unit *u;
3900
3901 assert_se(source);
3902 assert_se(m);
3903
3904 /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the resulting UID/GID
3905 * in a datagram. We parse the datagram here and pass it off to the unit, so that it can add a reference to the
3906 * UID/GID so that it can destroy the UID/GID's IPC objects when the reference counter drops to 0. */
3907
3908 l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
3909 if (l < 0) {
4c701096 3910 if (IN_SET(errno, EINTR, EAGAIN))
00d9ef85
LP
3911 return 0;
3912
3913 return log_error_errno(errno, "Failed to read from user lookup fd: %m");
3914 }
3915
3916 if ((size_t) l <= offsetof(struct buffer, unit_name)) {
3917 log_warning("Received too short user lookup message, ignoring.");
3918 return 0;
3919 }
3920
3921 if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
3922 log_warning("Received too long user lookup message, ignoring.");
3923 return 0;
3924 }
3925
3926 if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
3927 log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
3928 return 0;
3929 }
3930
3931 n = (size_t) l - offsetof(struct buffer, unit_name);
3932 if (memchr(buffer.unit_name, 0, n)) {
3933 log_warning("Received lookup message with embedded NUL character, ignoring.");
3934 return 0;
3935 }
3936
3937 buffer.unit_name[n] = 0;
3938 u = manager_get_unit(m, buffer.unit_name);
3939 if (!u) {
3940 log_debug("Got user lookup message but unit doesn't exist, ignoring.");
3941 return 0;
3942 }
3943
3944 log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
3945
3946 unit_notify_user_lookup(u, buffer.uid, buffer.gid);
3947 return 0;
3948}
3949
af6b0ecc 3950char *manager_taint_string(Manager *m) {
90d7464d 3951 _cleanup_free_ char *destination = NULL, *overflowuid = NULL, *overflowgid = NULL;
af6b0ecc
LP
3952 char *buf, *e;
3953 int r;
3954
198ce932
ZJS
3955 /* Returns a "taint string", e.g. "local-hwclock:var-run-bad".
3956 * Only things that are detected at runtime should be tagged
3957 * here. For stuff that is set during compilation, emit a warning
3958 * in the configuration phase. */
3959
af6b0ecc
LP
3960 assert(m);
3961
3962 buf = new(char, sizeof("split-usr:"
3963 "cgroups-missing:"
3964 "local-hwclock:"
3965 "var-run-bad:"
90d7464d
LP
3966 "overflowuid-not-65534:"
3967 "overflowgid-not-65534:"));
af6b0ecc
LP
3968 if (!buf)
3969 return NULL;
3970
3971 e = buf;
0fd402b0 3972 buf[0] = 0;
af6b0ecc
LP
3973
3974 if (m->taint_usr)
3975 e = stpcpy(e, "split-usr:");
3976
3977 if (access("/proc/cgroups", F_OK) < 0)
3978 e = stpcpy(e, "cgroups-missing:");
3979
3980 if (clock_is_localtime(NULL) > 0)
3981 e = stpcpy(e, "local-hwclock:");
3982
3983 r = readlink_malloc("/var/run", &destination);
3984 if (r < 0 || !PATH_IN_SET(destination, "../run", "/run"))
3985 e = stpcpy(e, "var-run-bad:");
3986
90d7464d
LP
3987 r = read_one_line_file("/proc/sys/kernel/overflowuid", &overflowuid);
3988 if (r >= 0 && !streq(overflowuid, "65534"))
3989 e = stpcpy(e, "overflowuid-not-65534:");
3990
3991 r = read_one_line_file("/proc/sys/kernel/overflowgid", &overflowgid);
3992 if (r >= 0 && !streq(overflowgid, "65534"))
3993 e = stpcpy(e, "overflowgid-not-65534:");
3994
af6b0ecc
LP
3995 /* remove the last ':' */
3996 if (e != buf)
3997 e[-1] = 0;
3998
3999 return buf;
4000}
4001
f755e3b7 4002static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
d81afec1 4003 [MANAGER_INITIALIZING] = "initializing",
f755e3b7
LP
4004 [MANAGER_STARTING] = "starting",
4005 [MANAGER_RUNNING] = "running",
4006 [MANAGER_DEGRADED] = "degraded",
4007 [MANAGER_MAINTENANCE] = "maintenance",
4008 [MANAGER_STOPPING] = "stopping",
4009};
4010
4011DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
9f9f0342
LP
4012
4013static const char *const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
4014 [MANAGER_TIMESTAMP_FIRMWARE] = "firmware",
4015 [MANAGER_TIMESTAMP_LOADER] = "loader",
4016 [MANAGER_TIMESTAMP_KERNEL] = "kernel",
4017 [MANAGER_TIMESTAMP_INITRD] = "initrd",
4018 [MANAGER_TIMESTAMP_USERSPACE] = "userspace",
4019 [MANAGER_TIMESTAMP_FINISH] = "finish",
4020 [MANAGER_TIMESTAMP_SECURITY_START] = "security-start",
4021 [MANAGER_TIMESTAMP_SECURITY_FINISH] = "security-finish",
4022 [MANAGER_TIMESTAMP_GENERATORS_START] = "generators-start",
4023 [MANAGER_TIMESTAMP_GENERATORS_FINISH] = "generators-finish",
4024 [MANAGER_TIMESTAMP_UNITS_LOAD_START] = "units-load-start",
4025 [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH] = "units-load-finish",
4026};
4027
4028DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);