]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/manager.c
Merge pull request #24021 from poettering/man-rlimit-comments
[thirdparty/systemd.git] / src / core / manager.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
60918275 3#include <errno.h>
400f1a33
LP
4#include <fcntl.h>
5#include <linux/kd.h>
e46b13c8 6#include <sys/epoll.h>
400f1a33 7#include <sys/inotify.h>
e1414003 8#include <sys/ioctl.h>
400f1a33 9#include <sys/reboot.h>
8742514c 10#include <sys/timerfd.h>
40efaaed 11#include <sys/utsname.h>
400f1a33
LP
12#include <sys/wait.h>
13#include <unistd.h>
830f6caa 14
349cc4a5 15#if HAVE_AUDIT
4927fcae 16#include <libaudit.h>
830f6caa 17#endif
60918275 18
718db961 19#include "sd-daemon.h"
718db961 20#include "sd-messages.h"
3536f49e 21#include "sd-path.h"
81527be1 22
57b7a260 23#include "all-units.h"
d68c645b 24#include "alloc-util.h"
400f1a33
LP
25#include "audit-fd.h"
26#include "boot-timestamps.h"
27#include "bus-common-errors.h"
28#include "bus-error.h"
29#include "bus-kernel.h"
30#include "bus-util.h"
00d9ef85 31#include "clean-ipc.h"
af6b0ecc 32#include "clock-util.h"
19d22d43 33#include "core-varlink.h"
786d19fd 34#include "creds-util.h"
400f1a33
LP
35#include "dbus-job.h"
36#include "dbus-manager.h"
37#include "dbus-unit.h"
38#include "dbus.h"
0e7f5ad9 39#include "def.h"
d063a527 40#include "dirent-util.h"
400f1a33 41#include "env-util.h"
4f5dd394 42#include "escape.h"
ec75e8e0 43#include "event-util.h"
89711996 44#include "exec-util.h"
d3070fbd 45#include "execute.h"
400f1a33 46#include "exit-status.h"
3ffd4af2 47#include "fd-util.h"
0d39fa9c 48#include "fileio.h"
385093b7 49#include "generator-setup.h"
60918275 50#include "hashmap.h"
9e5fd717 51#include "inotify-util.h"
5cfa33e0 52#include "install.h"
19d22d43 53#include "io-util.h"
d3070fbd 54#include "label.h"
d904afc7 55#include "load-fragment.h"
786d19fd 56#include "locale-setup.h"
16354eff 57#include "log.h"
400f1a33 58#include "macro.h"
3ffd4af2 59#include "manager.h"
2a341bb9 60#include "manager-dump.h"
a01ba4b2 61#include "manager-serialize.h"
0a970718 62#include "memory-util.h"
35cd0ba5 63#include "mkdir-label.h"
4bd03515 64#include "os-util.h"
6bedfcbb 65#include "parse-util.h"
400f1a33
LP
66#include "path-lookup.h"
67#include "path-util.h"
68#include "process-util.h"
ea430986 69#include "ratelimit.h"
31ce987c 70#include "rlimit-util.h"
c6878637 71#include "rm-rf.h"
45ae2f72 72#include "selinux-util.h"
400f1a33 73#include "signal-util.h"
57b7a260 74#include "socket-util.h"
514f4ef5 75#include "special.h"
8fcde012 76#include "stat-util.h"
8b43440b 77#include "string-table.h"
07630cea 78#include "string-util.h"
400f1a33 79#include "strv.h"
dd1db3c2 80#include "strxcpyx.h"
6123dfaa 81#include "sysctl-util.h"
a6ecbf83 82#include "syslog-util.h"
400f1a33
LP
83#include "terminal-util.h"
84#include "time-util.h"
85#include "transaction.h"
63e8df04 86#include "uid-range.h"
affb60b1 87#include "umask-util.h"
400f1a33 88#include "unit-name.h"
00d9ef85 89#include "user-util.h"
5dc4c17f 90#include "virt.h"
e96d6be7 91#include "watchdog.h"
60918275 92
a47806fa 93#define NOTIFY_RCVBUF_SIZE (8*1024*1024)
d8fdc620 94#define CGROUPS_AGENT_RCVBUF_SIZE (8*1024*1024)
a47806fa 95
03b717a3 96/* Initial delay and the interval for printing status messages about running jobs */
1b4154a8
ZJS
97#define JOBS_IN_PROGRESS_WAIT_USEC (2*USEC_PER_SEC)
98#define JOBS_IN_PROGRESS_QUIET_WAIT_USEC (25*USEC_PER_SEC)
fd08a840 99#define JOBS_IN_PROGRESS_PERIOD_USEC (USEC_PER_SEC / 3)
03b717a3
MS
100#define JOBS_IN_PROGRESS_PERIOD_DIVISOR 3
101
5238e957 102/* If there are more than 1K bus messages queue across our API and direct buses, then let's not add more on top until
e0a08581
LP
103 * the queue gets more empty. */
104#define MANAGER_BUS_BUSY_THRESHOLD 1024LU
105
106/* How many units and jobs to process of the bus queue before returning to the event loop. */
107#define MANAGER_BUS_MESSAGE_BUDGET 100U
108
718db961 109static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
d8fdc620 110static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
718db961
LP
111static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
112static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
113static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
00d9ef85 114static int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata);
718db961 115static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata);
752b5905 116static int manager_dispatch_run_queue(sd_event_source *source, void *userdata);
575b300b 117static int manager_dispatch_sigchld(sd_event_source *source, void *userdata);
bbf5fd8e 118static int manager_dispatch_timezone_change(sd_event_source *source, const struct inotify_event *event, void *userdata);
64691d20 119static int manager_run_environment_generators(Manager *m);
e801700e 120static int manager_run_generators(Manager *m);
06a4eb07 121static void manager_vacuum(Manager *m);
718db961 122
1b4154a8 123static usec_t manager_watch_jobs_next_time(Manager *m) {
3889fc6f
ZJS
124 usec_t timeout;
125
126 if (MANAGER_IS_USER(m))
127 /* Let the user manager without a timeout show status quickly, so the system manager can make
128 * use of it, if it wants to. */
129 timeout = JOBS_IN_PROGRESS_WAIT_USEC * 2 / 3;
130 else if (show_status_on(m->show_status))
131 /* When status is on, just use the usual timeout. */
132 timeout = JOBS_IN_PROGRESS_WAIT_USEC;
133 else
134 timeout = JOBS_IN_PROGRESS_QUIET_WAIT_USEC;
135
136 return usec_add(now(CLOCK_MONOTONIC), timeout);
1b4154a8
ZJS
137}
138
2ae56591 139static void manager_watch_jobs_in_progress(Manager *m) {
e5723c89 140 usec_t next;
cfa9677b 141 int r;
e5723c89 142
718db961 143 assert(m);
03b717a3 144
42bf1ae1
FB
145 /* We do not want to show the cylon animation if the user
146 * needs to confirm service executions otherwise confirmation
147 * messages will be screwed by the cylon animation. */
b0eb2944 148 if (!manager_is_confirm_spawn_disabled(m))
42bf1ae1
FB
149 return;
150
718db961 151 if (m->jobs_in_progress_event_source)
2ae56591 152 return;
03b717a3 153
1b4154a8 154 next = manager_watch_jobs_next_time(m);
cfa9677b 155 r = sd_event_add_time(
6a0f1f6d
LP
156 m->event,
157 &m->jobs_in_progress_event_source,
158 CLOCK_MONOTONIC,
159 next, 0,
160 manager_dispatch_jobs_in_progress, m);
cfa9677b
MM
161 if (r < 0)
162 return;
7dfbe2e3
TG
163
164 (void) sd_event_source_set_description(m->jobs_in_progress_event_source, "manager-jobs-in-progress");
03b717a3
MS
165}
166
fbd0b64f 167#define CYLON_BUFFER_EXTRA (2*STRLEN(ANSI_RED) + STRLEN(ANSI_HIGHLIGHT_RED) + 2*STRLEN(ANSI_NORMAL))
03b717a3 168
03b717a3
MS
169static void draw_cylon(char buffer[], size_t buflen, unsigned width, unsigned pos) {
170 char *p = buffer;
171
172 assert(buflen >= CYLON_BUFFER_EXTRA + width + 1);
173 assert(pos <= width+1); /* 0 or width+1 mean that the center light is behind the corner */
174
175 if (pos > 1) {
6282c859
MS
176 if (pos > 2)
177 p = mempset(p, ' ', pos-2);
64c3610b
FB
178 if (log_get_show_color())
179 p = stpcpy(p, ANSI_RED);
03b717a3
MS
180 *p++ = '*';
181 }
182
183 if (pos > 0 && pos <= width) {
64c3610b
FB
184 if (log_get_show_color())
185 p = stpcpy(p, ANSI_HIGHLIGHT_RED);
03b717a3
MS
186 *p++ = '*';
187 }
188
64c3610b
FB
189 if (log_get_show_color())
190 p = stpcpy(p, ANSI_NORMAL);
03b717a3
MS
191
192 if (pos < width) {
64c3610b
FB
193 if (log_get_show_color())
194 p = stpcpy(p, ANSI_RED);
03b717a3 195 *p++ = '*';
6282c859
MS
196 if (pos < width-1)
197 p = mempset(p, ' ', width-1-pos);
64c3610b
FB
198 if (log_get_show_color())
199 strcpy(p, ANSI_NORMAL);
03b717a3 200 }
03b717a3
MS
201}
202
1addc46c 203static void manager_flip_auto_status(Manager *m, bool enable, const char *reason) {
f755e3b7
LP
204 assert(m);
205
cb8ccb22
ZJS
206 if (enable) {
207 if (m->show_status == SHOW_STATUS_AUTO)
7365a296 208 manager_set_show_status(m, SHOW_STATUS_TEMPORARY, reason);
cb8ccb22
ZJS
209 } else {
210 if (m->show_status == SHOW_STATUS_TEMPORARY)
7365a296 211 manager_set_show_status(m, SHOW_STATUS_AUTO, reason);
cb8ccb22
ZJS
212 }
213}
214
03b717a3 215static void manager_print_jobs_in_progress(Manager *m) {
03b717a3 216 Job *j;
03b717a3
MS
217 unsigned counter = 0, print_nr;
218 char cylon[6 + CYLON_BUFFER_EXTRA + 1];
219 unsigned cylon_pos;
4c989f89 220 uint64_t timeout = 0;
03b717a3 221
718db961 222 assert(m);
9c3349e2 223 assert(m->n_running_jobs > 0);
718db961 224
7365a296 225 manager_flip_auto_status(m, true, "delay");
d450b6f2 226
03b717a3
MS
227 print_nr = (m->jobs_in_progress_iteration / JOBS_IN_PROGRESS_PERIOD_DIVISOR) % m->n_running_jobs;
228
90e74a66 229 HASHMAP_FOREACH(j, m->jobs)
03b717a3
MS
230 if (j->state == JOB_RUNNING && counter++ == print_nr)
231 break;
232
e970a72e
MS
233 /* m->n_running_jobs must be consistent with the contents of m->jobs,
234 * so the above loop must have succeeded in finding j. */
235 assert(counter == print_nr + 1);
51d122af 236 assert(j);
5a82a91a 237
03b717a3
MS
238 cylon_pos = m->jobs_in_progress_iteration % 14;
239 if (cylon_pos >= 8)
240 cylon_pos = 14 - cylon_pos;
241 draw_cylon(cylon, sizeof(cylon), 6, cylon_pos);
242
8bb310c3
ZJS
243 m->jobs_in_progress_iteration++;
244
3889fc6f 245 char job_of_n[STRLEN("( of ) ") + DECIMAL_STR_MAX(unsigned)*2] = "";
5291f26d 246 if (m->n_running_jobs > 1)
3889fc6f 247 xsprintf(job_of_n, "(%u of %u) ", counter, m->n_running_jobs);
03b717a3 248
4c989f89 249 (void) job_get_timeout(j, &timeout);
8bb310c3 250
04d232d8
ZJS
251 /* We want to use enough information for the user to identify previous lines talking about the same
252 * unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting
3889fc6f 253 * foo.service - Description' were used, 'foo.service' is enough here. On the other hand, if we used
04d232d8
ZJS
254 * 'Starting Description' before, then we shall also use 'Description' here. So we pass NULL as the
255 * second argument to unit_status_string(). */
256 const char *ident = unit_status_string(j->unit, NULL);
257
3889fc6f 258 const char *time = FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC);
4c989f89 259 const char *limit = timeout > 0 ? FORMAT_TIMESPAN(timeout - j->begin_usec, 1*USEC_PER_SEC) : "no limit";
3889fc6f
ZJS
260
261 if (m->status_unit_format == STATUS_UNIT_FORMAT_DESCRIPTION)
262 /* When using 'Description', we effectively don't have enough space to show the nested status
263 * without ellipsization, so let's not even try. */
264 manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
265 "%sA %s job is running for %s (%s / %s)",
266 job_of_n,
267 job_type_to_string(j->type),
268 ident,
269 time, limit);
270 else {
271 const char *status_text = unit_status_text(j->unit);
272
273 manager_status_printf(m, STATUS_TYPE_EPHEMERAL, cylon,
274 "%sJob %s/%s running (%s / %s)%s%s",
275 job_of_n,
276 ident,
277 job_type_to_string(j->type),
278 time, limit,
279 status_text ? ": " : "",
280 strempty(status_text));
281 }
282
283 sd_notifyf(false,
284 "STATUS=%sUser job %s/%s running (%s / %s)...",
285 job_of_n,
286 ident,
287 job_type_to_string(j->type),
288 time, limit);
289 m->status_ready = false;
03b717a3
MS
290}
291
e46b13c8 292static int have_ask_password(void) {
c2b2df60 293 _cleanup_closedir_ DIR *dir = NULL;
e46b13c8
ZJS
294
295 dir = opendir("/run/systemd/ask-password");
296 if (!dir) {
297 if (errno == ENOENT)
298 return false;
299 else
300 return -errno;
301 }
302
c7f0d9e5 303 FOREACH_DIRENT_ALL(de, dir, return -errno)
e46b13c8
ZJS
304 if (startswith(de->d_name, "ask."))
305 return true;
8fb3f009 306 return false;
e46b13c8
ZJS
307}
308
309static int manager_dispatch_ask_password_fd(sd_event_source *source,
310 int fd, uint32_t revents, void *userdata) {
311 Manager *m = userdata;
312
313 assert(m);
314
665dfe93 315 (void) flush_fd(fd);
e46b13c8
ZJS
316
317 m->have_ask_password = have_ask_password();
318 if (m->have_ask_password < 0)
319 /* Log error but continue. Negative have_ask_password
320 * is treated as unknown status. */
c33b3297 321 log_error_errno(m->have_ask_password, "Failed to list /run/systemd/ask-password: %m");
e46b13c8
ZJS
322
323 return 0;
324}
325
326static void manager_close_ask_password(Manager *m) {
327 assert(m);
328
5dcadb4c 329 m->ask_password_event_source = sd_event_source_disable_unref(m->ask_password_event_source);
90990e28 330 m->ask_password_inotify_fd = safe_close(m->ask_password_inotify_fd);
e46b13c8
ZJS
331 m->have_ask_password = -EINVAL;
332}
333
334static int manager_check_ask_password(Manager *m) {
335 int r;
336
337 assert(m);
338
339 if (!m->ask_password_event_source) {
340 assert(m->ask_password_inotify_fd < 0);
341
17e4b070 342 (void) mkdir_p_label("/run/systemd/ask-password", 0755);
e46b13c8
ZJS
343
344 m->ask_password_inotify_fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
4a62c710 345 if (m->ask_password_inotify_fd < 0)
330b8fb3 346 return log_error_errno(errno, "Failed to create inotify object: %m");
e46b13c8 347
27c3112d
FB
348 r = inotify_add_watch_and_warn(m->ask_password_inotify_fd,
349 "/run/systemd/ask-password",
350 IN_CREATE|IN_DELETE|IN_MOVE);
351 if (r < 0) {
e46b13c8 352 manager_close_ask_password(m);
27c3112d 353 return r;
e46b13c8
ZJS
354 }
355
356 r = sd_event_add_io(m->event, &m->ask_password_event_source,
357 m->ask_password_inotify_fd, EPOLLIN,
358 manager_dispatch_ask_password_fd, m);
359 if (r < 0) {
df3d3bdf 360 log_error_errno(r, "Failed to add event source for /run/systemd/ask-password: %m");
e46b13c8 361 manager_close_ask_password(m);
df3d3bdf 362 return r;
e46b13c8
ZJS
363 }
364
7dfbe2e3
TG
365 (void) sd_event_source_set_description(m->ask_password_event_source, "manager-ask-password");
366
e46b13c8
ZJS
367 /* Queries might have been added meanwhile... */
368 manager_dispatch_ask_password_fd(m->ask_password_event_source,
369 m->ask_password_inotify_fd, EPOLLIN, m);
370 }
371
372 return m->have_ask_password;
373}
374
31a7eb86 375static int manager_watch_idle_pipe(Manager *m) {
31a7eb86
ZJS
376 int r;
377
718db961
LP
378 assert(m);
379
380 if (m->idle_pipe_event_source)
31a7eb86
ZJS
381 return 0;
382
383 if (m->idle_pipe[2] < 0)
384 return 0;
385
151b9b96 386 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
387 if (r < 0)
388 return log_error_errno(r, "Failed to watch idle pipe: %m");
31a7eb86 389
7dfbe2e3
TG
390 (void) sd_event_source_set_description(m->idle_pipe_event_source, "manager-idle-pipe");
391
31a7eb86 392 return 0;
31a7eb86
ZJS
393}
394
718db961
LP
395static void manager_close_idle_pipe(Manager *m) {
396 assert(m);
31a7eb86 397
5dcadb4c 398 m->idle_pipe_event_source = sd_event_source_disable_unref(m->idle_pipe_event_source);
cd72bd8a 399
3d94f76c
LP
400 safe_close_pair(m->idle_pipe);
401 safe_close_pair(m->idle_pipe + 2);
31a7eb86
ZJS
402}
403
8742514c 404static int manager_setup_time_change(Manager *m) {
718db961 405 int r;
b92bea5d 406
718db961 407 assert(m);
8742514c 408
638cece4 409 if (MANAGER_IS_TEST_RUN(m))
0d8c31ff
ZJS
410 return 0;
411
5dcadb4c 412 m->time_change_event_source = sd_event_source_disable_unref(m->time_change_event_source);
7feedd18 413
ec75e8e0 414 r = event_add_time_change(m->event, &m->time_change_event_source, manager_dispatch_time_change_fd, m);
23bbb0de
MS
415 if (r < 0)
416 return log_error_errno(r, "Failed to create time change event source: %m");
8742514c 417
a5cc7e5a
LP
418 /* Schedule this slightly earlier than the .timer event sources */
419 r = sd_event_source_set_priority(m->time_change_event_source, SD_EVENT_PRIORITY_NORMAL-1);
420 if (r < 0)
421 return log_error_errno(r, "Failed to set priority of time change event sources: %m");
422
8742514c
LP
423 log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
424
425 return 0;
426}
427
bbf5fd8e
LP
428static int manager_read_timezone_stat(Manager *m) {
429 struct stat st;
430 bool changed;
431
432 assert(m);
433
434 /* Read the current stat() data of /etc/localtime so that we detect changes */
435 if (lstat("/etc/localtime", &st) < 0) {
436 log_debug_errno(errno, "Failed to stat /etc/localtime, ignoring: %m");
437 changed = m->etc_localtime_accessible;
438 m->etc_localtime_accessible = false;
439 } else {
440 usec_t k;
441
442 k = timespec_load(&st.st_mtim);
443 changed = !m->etc_localtime_accessible || k != m->etc_localtime_mtime;
444
445 m->etc_localtime_mtime = k;
446 m->etc_localtime_accessible = true;
447 }
448
449 return changed;
450}
451
452static int manager_setup_timezone_change(Manager *m) {
a5cc7e5a 453 _cleanup_(sd_event_source_unrefp) sd_event_source *new_event = NULL;
bbf5fd8e
LP
454 int r;
455
456 assert(m);
457
638cece4 458 if (MANAGER_IS_TEST_RUN(m))
bbf5fd8e
LP
459 return 0;
460
461 /* We watch /etc/localtime for three events: change of the link count (which might mean removal from /etc even
462 * though another link might be kept), renames, and file close operations after writing. Note we don't bother
463 * with IN_DELETE_SELF, as that would just report when the inode is removed entirely, i.e. after the link count
464 * went to zero and all fds to it are closed.
465 *
466 * Note that we never follow symlinks here. This is a simplification, but should cover almost all cases
467 * correctly.
468 *
469 * Note that we create the new event source first here, before releasing the old one. This should optimize
470 * behaviour as this way sd-event can reuse the old watch in case the inode didn't change. */
471
472 r = sd_event_add_inotify(m->event, &new_event, "/etc/localtime",
473 IN_ATTRIB|IN_MOVE_SELF|IN_CLOSE_WRITE|IN_DONT_FOLLOW, manager_dispatch_timezone_change, m);
0cb21d8c
LP
474 if (r == -ENOENT) {
475 /* If the file doesn't exist yet, subscribe to /etc instead, and wait until it is created either by
476 * O_CREATE or by rename() */
477
478 log_debug_errno(r, "/etc/localtime doesn't exist yet, watching /etc instead.");
bbf5fd8e
LP
479 r = sd_event_add_inotify(m->event, &new_event, "/etc",
480 IN_CREATE|IN_MOVED_TO|IN_ONLYDIR, manager_dispatch_timezone_change, m);
0cb21d8c 481 }
bbf5fd8e
LP
482 if (r < 0)
483 return log_error_errno(r, "Failed to create timezone change event source: %m");
484
a5cc7e5a
LP
485 /* Schedule this slightly earlier than the .timer event sources */
486 r = sd_event_source_set_priority(new_event, SD_EVENT_PRIORITY_NORMAL-1);
487 if (r < 0)
488 return log_error_errno(r, "Failed to set priority of timezone change event sources: %m");
489
bbf5fd8e 490 sd_event_source_unref(m->timezone_change_event_source);
a5cc7e5a 491 m->timezone_change_event_source = TAKE_PTR(new_event);
bbf5fd8e
LP
492
493 return 0;
494}
495
80876c20 496static int enable_special_signals(Manager *m) {
718db961 497 _cleanup_close_ int fd = -1;
80876c20
LP
498
499 assert(m);
500
638cece4 501 if (MANAGER_IS_TEST_RUN(m))
37453b3a
EV
502 return 0;
503
a41b539e 504 /* Enable that we get SIGINT on control-alt-del. In containers
c9999773
LP
505 * this will fail with EPERM (older) or EINVAL (newer), so
506 * ignore that. */
4c701096 507 if (reboot(RB_DISABLE_CAD) < 0 && !IN_SET(errno, EPERM, EINVAL))
56f64d95 508 log_warning_errno(errno, "Failed to enable ctrl-alt-del handling: %m");
80876c20 509
a41b539e
LP
510 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
511 if (fd < 0) {
512 /* Support systems without virtual console */
513 if (fd != -ENOENT)
56f64d95 514 log_warning_errno(errno, "Failed to open /dev/tty0: %m");
a41b539e 515 } else {
80876c20
LP
516 /* Enable that we get SIGWINCH on kbrequest */
517 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
56f64d95 518 log_warning_errno(errno, "Failed to enable kbrequest handling: %m");
80876c20
LP
519 }
520
521 return 0;
522}
523
8750ac02
ZJS
524#define RTSIG_IF_AVAILABLE(signum) (signum <= SIGRTMAX ? signum : -1)
525
ce578209 526static int manager_setup_signals(Manager *m) {
b92bea5d
ZJS
527 struct sigaction sa = {
528 .sa_handler = SIG_DFL,
529 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
530 };
718db961
LP
531 sigset_t mask;
532 int r;
60918275 533
ce578209
LP
534 assert(m);
535
57c0c30e
LP
536 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
537
4dffec14
LP
538 /* We make liberal use of realtime signals here. On
539 * Linux/glibc we have 30 of them (with the exception of Linux
540 * on hppa, see below), between SIGRTMIN+0 ... SIGRTMIN+30
541 * (aka SIGRTMAX). */
7d793605 542
4dffec14 543 assert_se(sigemptyset(&mask) == 0);
7d793605
LP
544 sigset_add_many(&mask,
545 SIGCHLD, /* Child died */
546 SIGTERM, /* Reexecute daemon */
547 SIGHUP, /* Reload configuration */
54d04cd1 548 SIGUSR1, /* systemd: reconnect to D-Bus */
7d793605
LP
549 SIGUSR2, /* systemd: dump status */
550 SIGINT, /* Kernel sends us this on control-alt-del */
551 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
552 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
4dffec14 553
7d793605 554 SIGRTMIN+0, /* systemd: start default.target */
0003d1ab 555 SIGRTMIN+1, /* systemd: isolate rescue.target */
7d793605
LP
556 SIGRTMIN+2, /* systemd: isolate emergency.target */
557 SIGRTMIN+3, /* systemd: start halt.target */
558 SIGRTMIN+4, /* systemd: start poweroff.target */
559 SIGRTMIN+5, /* systemd: start reboot.target */
0003d1ab 560 SIGRTMIN+6, /* systemd: start kexec.target */
4dffec14
LP
561
562 /* ... space for more special targets ... */
563
0003d1ab
LP
564 SIGRTMIN+13, /* systemd: Immediate halt */
565 SIGRTMIN+14, /* systemd: Immediate poweroff */
566 SIGRTMIN+15, /* systemd: Immediate reboot */
567 SIGRTMIN+16, /* systemd: Immediate kexec */
4dffec14
LP
568
569 /* ... space for more immediate system state changes ... */
570
0658666b
LP
571 SIGRTMIN+20, /* systemd: enable status messages */
572 SIGRTMIN+21, /* systemd: disable status messages */
253ee27a
LP
573 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
574 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
600b704e 575 SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
463aef23 576 SIGRTMIN+25, /* systemd: reexecute manager */
4dffec14 577
8750ac02
ZJS
578 /* Apparently Linux on hppa had fewer RT signals until v3.18,
579 * SIGRTMAX was SIGRTMIN+25, and then SIGRTMIN was lowered,
580 * see commit v3.17-7614-g1f25df2eff.
581 *
582 * We cannot unconditionally make use of those signals here,
583 * so let's use a runtime check. Since these commands are
584 * accessible by different means and only really a safety
585 * net, the missing functionality on hppa shouldn't matter.
586 */
587
588 RTSIG_IF_AVAILABLE(SIGRTMIN+26), /* systemd: set log target to journal-or-kmsg */
589 RTSIG_IF_AVAILABLE(SIGRTMIN+27), /* systemd: set log target to console */
590 RTSIG_IF_AVAILABLE(SIGRTMIN+28), /* systemd: set log target to kmsg */
591 RTSIG_IF_AVAILABLE(SIGRTMIN+29), /* systemd: set log target to syslog-or-kmsg (obsolete) */
4dffec14
LP
592
593 /* ... one free signal here SIGRTMIN+30 ... */
7d793605 594 -1);
ce578209
LP
595 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
596
718db961
LP
597 m->signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
598 if (m->signal_fd < 0)
ce578209
LP
599 return -errno;
600
151b9b96 601 r = sd_event_add_io(m->event, &m->signal_event_source, m->signal_fd, EPOLLIN, manager_dispatch_signal_fd, m);
718db961
LP
602 if (r < 0)
603 return r;
ce578209 604
7dfbe2e3
TG
605 (void) sd_event_source_set_description(m->signal_event_source, "manager-signal");
606
d8fdc620
LP
607 /* Process signals a bit earlier than the rest of things, but later than notify_fd processing, so that the
608 * notify processing can still figure out to which process/service a message belongs, before we reap the
609 * process. Also, process this before handling cgroup notifications, so that we always collect child exit
610 * status information before detecting that there's no process in a cgroup. */
611 r = sd_event_source_set_priority(m->signal_event_source, SD_EVENT_PRIORITY_NORMAL-6);
29083707
LP
612 if (r < 0)
613 return r;
614
463d0d15 615 if (MANAGER_IS_SYSTEM(m))
80876c20 616 return enable_special_signals(m);
e1414003 617
ce578209
LP
618 return 0;
619}
620
1ad6e8b3 621static char** sanitize_environment(char **l) {
f069efb4 622
47cf8ff2 623 /* Let's remove some environment variables that we need ourselves to communicate with our clients */
f069efb4 624 strv_env_unset_many(
1ad6e8b3 625 l,
8047ac8f
LP
626 "CACHE_DIRECTORY",
627 "CONFIGURATION_DIRECTORY",
bb0c0d6f 628 "CREDENTIALS_DIRECTORY",
47cf8ff2
LP
629 "EXIT_CODE",
630 "EXIT_STATUS",
631 "INVOCATION_ID",
632 "JOURNAL_STREAM",
633 "LISTEN_FDNAMES",
634 "LISTEN_FDS",
635 "LISTEN_PID",
8047ac8f 636 "LOGS_DIRECTORY",
f069efb4
LP
637 "MAINPID",
638 "MANAGERPID",
47cf8ff2 639 "NOTIFY_SOCKET",
dcf3c3c3 640 "PIDFILE",
47cf8ff2
LP
641 "REMOTE_ADDR",
642 "REMOTE_PORT",
8047ac8f 643 "RUNTIME_DIRECTORY",
47cf8ff2 644 "SERVICE_RESULT",
8047ac8f 645 "STATE_DIRECTORY",
f069efb4
LP
646 "WATCHDOG_PID",
647 "WATCHDOG_USEC",
648 NULL);
47cf8ff2
LP
649
650 /* Let's order the environment alphabetically, just to make it pretty */
305757d8 651 return strv_sort(l);
f069efb4
LP
652}
653
79a224c4 654int manager_default_environment(Manager *m) {
db11487d
ZJS
655 int r;
656
71ecc858
LP
657 assert(m);
658
1ad6e8b3
LP
659 m->transient_environment = strv_free(m->transient_environment);
660
463d0d15 661 if (MANAGER_IS_SYSTEM(m)) {
e21fea24
KS
662 /* The system manager always starts with a clean
663 * environment for its children. It does not import
71cb7d30 664 * the kernel's or the parents' exported variables.
e21fea24 665 *
71cb7d30 666 * The initial passed environment is untouched to keep
e21fea24
KS
667 * /proc/self/environ valid; it is used for tagging
668 * the init process inside containers. */
1ad6e8b3 669 m->transient_environment = strv_new("PATH=" DEFAULT_PATH);
db11487d
ZJS
670 if (!m->transient_environment)
671 return log_oom();
e21fea24
KS
672
673 /* Import locale variables LC_*= from configuration */
1ad6e8b3 674 (void) locale_setup(&m->transient_environment);
db11487d 675 } else {
aaf057c4 676 /* The user manager passes its own environment along to its children, except for $PATH. */
1ad6e8b3 677 m->transient_environment = strv_copy(environ);
db11487d
ZJS
678 if (!m->transient_environment)
679 return log_oom();
680
aaf057c4 681 r = strv_env_replace_strdup(&m->transient_environment, "PATH=" DEFAULT_USER_PATH);
db11487d
ZJS
682 if (r < 0)
683 return log_oom();
db11487d 684 }
8b55b8c4 685
1ad6e8b3 686 sanitize_environment(m->transient_environment);
9d5a3757 687
e21fea24 688 return 0;
71ecc858
LP
689}
690
3536f49e
YW
691static int manager_setup_prefix(Manager *m) {
692 struct table_entry {
693 uint64_t type;
694 const char *suffix;
695 };
696
72fd1768 697 static const struct table_entry paths_system[_EXEC_DIRECTORY_TYPE_MAX] = {
9978e631
ZJS
698 [EXEC_DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME, NULL },
699 [EXEC_DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE, NULL },
700 [EXEC_DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE, NULL },
701 [EXEC_DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS, NULL },
3536f49e
YW
702 [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_SYSTEM_CONFIGURATION, NULL },
703 };
704
72fd1768 705 static const struct table_entry paths_user[_EXEC_DIRECTORY_TYPE_MAX] = {
9978e631
ZJS
706 [EXEC_DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME, NULL },
707 [EXEC_DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION, NULL },
708 [EXEC_DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE, NULL },
709 [EXEC_DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
710 [EXEC_DIRECTORY_CONFIGURATION] = { SD_PATH_USER_CONFIGURATION, NULL },
3536f49e
YW
711 };
712
3536f49e
YW
713 assert(m);
714
24b45970
ZJS
715 const struct table_entry *p = MANAGER_IS_SYSTEM(m) ? paths_system : paths_user;
716 int r;
3536f49e 717
24b45970 718 for (ExecDirectoryType i = 0; i < _EXEC_DIRECTORY_TYPE_MAX; i++) {
51327bcc 719 r = sd_path_lookup(p[i].type, p[i].suffix, &m->prefix[i]);
3536f49e 720 if (r < 0)
998df7ce
ZJS
721 return log_warning_errno(r, "Failed to lookup %s path: %m",
722 exec_directory_type_to_string(i));
3536f49e
YW
723 }
724
725 return 0;
726}
727
e8630e69
ZJS
728static void manager_free_unit_name_maps(Manager *m) {
729 m->unit_id_map = hashmap_free(m->unit_id_map);
730 m->unit_name_map = hashmap_free(m->unit_name_map);
3fb2326f 731 m->unit_path_cache = set_free(m->unit_path_cache);
c2911d48 732 m->unit_cache_timestamp_hash = 0;
e8630e69
ZJS
733}
734
279d81dd
LP
735static int manager_setup_run_queue(Manager *m) {
736 int r;
737
738 assert(m);
739 assert(!m->run_queue_event_source);
740
741 r = sd_event_add_defer(m->event, &m->run_queue_event_source, manager_dispatch_run_queue, m);
742 if (r < 0)
743 return r;
744
745 r = sd_event_source_set_priority(m->run_queue_event_source, SD_EVENT_PRIORITY_IDLE);
746 if (r < 0)
747 return r;
748
749 r = sd_event_source_set_enabled(m->run_queue_event_source, SD_EVENT_OFF);
750 if (r < 0)
751 return r;
752
753 (void) sd_event_source_set_description(m->run_queue_event_source, "manager-run-queue");
754
755 return 0;
756}
757
575b300b
LP
758static int manager_setup_sigchld_event_source(Manager *m) {
759 int r;
760
761 assert(m);
762 assert(!m->sigchld_event_source);
763
764 r = sd_event_add_defer(m->event, &m->sigchld_event_source, manager_dispatch_sigchld, m);
765 if (r < 0)
766 return r;
767
768 r = sd_event_source_set_priority(m->sigchld_event_source, SD_EVENT_PRIORITY_NORMAL-7);
769 if (r < 0)
770 return r;
771
772 r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
773 if (r < 0)
774 return r;
775
776 (void) sd_event_source_set_description(m->sigchld_event_source, "manager-sigchld");
777
778 return 0;
779}
780
2ad591a3
LP
781static int manager_find_credentials_dirs(Manager *m) {
782 const char *e;
783 int r;
784
785 assert(m);
786
787 r = get_credentials_dir(&e);
788 if (r < 0) {
789 if (r != -ENXIO)
790 log_debug_errno(r, "Failed to determine credentials directory, ignoring: %m");
791 } else {
792 m->received_credentials_directory = strdup(e);
793 if (!m->received_credentials_directory)
794 return -ENOMEM;
795 }
796
797 r = get_encrypted_credentials_dir(&e);
798 if (r < 0) {
799 if (r != -ENXIO)
800 log_debug_errno(r, "Failed to determine encrypted credentials directory, ignoring: %m");
801 } else {
802 m->received_encrypted_credentials_directory = strdup(e);
803 if (!m->received_encrypted_credentials_directory)
804 return -ENOMEM;
805 }
806
807 return 0;
808}
809
b380b643 810int manager_new(LookupScope scope, ManagerTestRunFlags test_run_flags, Manager **_m) {
c70cac54 811 _cleanup_(manager_freep) Manager *m = NULL;
e3dd987c 812 int r;
8e274523
LP
813
814 assert(_m);
b380b643 815 assert(IN_SET(scope, LOOKUP_SCOPE_SYSTEM, LOOKUP_SCOPE_USER));
ce578209 816
3ad228ce 817 m = new(Manager, 1);
915b3753 818 if (!m)
8e274523 819 return -ENOMEM;
60918275 820
3ad228ce
LP
821 *m = (Manager) {
822 .unit_file_scope = scope,
823 .objective = _MANAGER_OBJECTIVE_INVALID,
824
36cf4507
ZJS
825 .status_unit_format = STATUS_UNIT_FORMAT_DEFAULT,
826
3ad228ce
LP
827 .default_timer_accuracy_usec = USEC_PER_MINUTE,
828 .default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT,
829 .default_tasks_accounting = true,
3a0f06c4 830 .default_tasks_max = TASKS_MAX_UNSET,
3ad228ce
LP
831 .default_timeout_start_usec = DEFAULT_TIMEOUT_USEC,
832 .default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC,
833 .default_restart_usec = DEFAULT_RESTART_USEC,
834
835 .original_log_level = -1,
836 .original_log_target = _LOG_TARGET_INVALID,
837
986935cf
FB
838 .watchdog_overridden[WATCHDOG_RUNTIME] = USEC_INFINITY,
839 .watchdog_overridden[WATCHDOG_REBOOT] = USEC_INFINITY,
840 .watchdog_overridden[WATCHDOG_KEXEC] = USEC_INFINITY,
5717062e 841 .watchdog_overridden[WATCHDOG_PRETIMEOUT] = USEC_INFINITY,
986935cf 842
44a41954
FB
843 .show_status_overridden = _SHOW_STATUS_INVALID,
844
3ad228ce
LP
845 .notify_fd = -1,
846 .cgroups_agent_fd = -1,
847 .signal_fd = -1,
3ad228ce
LP
848 .user_lookup_fds = { -1, -1 },
849 .private_listen_fd = -1,
850 .dev_autofs_fd = -1,
851 .cgroup_inotify_fd = -1,
852 .pin_cgroupfs_fd = -1,
853 .ask_password_inotify_fd = -1,
854 .idle_pipe = { -1, -1, -1, -1},
855
856 /* start as id #1, so that we can leave #0 around as "null-like" value */
857 .current_job_id = 1,
858
859 .have_ask_password = -EINVAL, /* we don't know */
860 .first_boot = -1,
861 .test_run_flags = test_run_flags,
afcfaa69
LP
862
863 .default_oom_policy = OOM_STOP,
3ad228ce 864 };
80876c20 865
349cc4a5 866#if ENABLE_EFI
463d0d15 867 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0)
9f9f0342
LP
868 boot_timestamps(m->timestamps + MANAGER_TIMESTAMP_USERSPACE,
869 m->timestamps + MANAGER_TIMESTAMP_FIRMWARE,
870 m->timestamps + MANAGER_TIMESTAMP_LOADER);
463d0d15
LP
871#endif
872
f2341e0a 873 /* Prepare log fields we can use for structured logging */
463d0d15
LP
874 if (MANAGER_IS_SYSTEM(m)) {
875 m->unit_log_field = "UNIT=";
876 m->unit_log_format_string = "UNIT=%s";
4b58153d
LP
877
878 m->invocation_log_field = "INVOCATION_ID=";
f1c50bec 879 m->invocation_log_format_string = "INVOCATION_ID=%s";
463d0d15
LP
880 } else {
881 m->unit_log_field = "USER_UNIT=";
882 m->unit_log_format_string = "USER_UNIT=%s";
4b58153d
LP
883
884 m->invocation_log_field = "USER_INVOCATION_ID=";
f1c50bec 885 m->invocation_log_format_string = "USER_INVOCATION_ID=%s";
463d0d15 886 }
f2341e0a 887
2e5c94b9 888 /* Reboot immediately if the user hits C-A-D more often than 7x per 2s */
8c227e7f 889 m->ctrl_alt_del_ratelimit = (RateLimit) { .interval = 2 * USEC_PER_SEC, .burst = 7 };
2e5c94b9 890
e21fea24
KS
891 r = manager_default_environment(m);
892 if (r < 0)
c70cac54 893 return r;
1137a57c 894
d5099efc 895 r = hashmap_ensure_allocated(&m->units, &string_hash_ops);
718db961 896 if (r < 0)
c70cac54 897 return r;
60918275 898
548f6937 899 r = hashmap_ensure_allocated(&m->cgroup_unit, &path_hash_ops);
718db961 900 if (r < 0)
c70cac54 901 return r;
9152c765 902
d5099efc 903 r = hashmap_ensure_allocated(&m->watch_bus, &string_hash_ops);
718db961 904 if (r < 0)
c70cac54 905 return r;
05e343b7 906
da8e1782
MO
907 r = prioq_ensure_allocated(&m->run_queue, compare_job_priority);
908 if (r < 0)
909 return r;
910
e8112e67 911 r = manager_setup_prefix(m);
718db961 912 if (r < 0)
c70cac54 913 return r;
8742514c 914
2ad591a3
LP
915 r = manager_find_credentials_dirs(m);
916 if (r < 0)
917 return r;
bb0c0d6f 918
e8112e67 919 r = sd_event_default(&m->event);
8742514c 920 if (r < 0)
c70cac54 921 return r;
9152c765 922
e8112e67 923 r = manager_setup_run_queue(m);
a1d32bac 924 if (r < 0)
c70cac54 925 return r;
8e274523 926
5dd2f5ff 927 if (FLAGS_SET(test_run_flags, MANAGER_TEST_RUN_MINIMAL)) {
e8112e67
ZJS
928 m->cgroup_root = strdup("");
929 if (!m->cgroup_root)
930 return -ENOMEM;
931 } else {
932 r = manager_setup_signals(m);
933 if (r < 0)
934 return r;
8c47c732 935
e8112e67
ZJS
936 r = manager_setup_cgroup(m);
937 if (r < 0)
938 return r;
575b300b 939
e8112e67
ZJS
940 r = manager_setup_time_change(m);
941 if (r < 0)
942 return r;
9670d583 943
bbf5fd8e
LP
944 r = manager_read_timezone_stat(m);
945 if (r < 0)
946 return r;
947
ea5c5f68 948 (void) manager_setup_timezone_change(m);
bbf5fd8e 949
e8112e67
ZJS
950 r = manager_setup_sigchld_event_source(m);
951 if (r < 0)
952 return r;
b1994387
ILG
953
954#if HAVE_LIBBPF
ba187c9c 955 if (MANAGER_IS_SYSTEM(m) && lsm_bpf_supported(/* initialize = */ true)) {
b1994387
ILG
956 r = lsm_bpf_setup(m);
957 if (r < 0)
299d9417 958 log_warning_errno(r, "Failed to setup LSM BPF, ignoring: %m");
b1994387
ILG
959 }
960#endif
e8112e67 961 }
e27fe688 962
2f8c48b6
AZ
963 if (test_run_flags == 0) {
964 if (MANAGER_IS_SYSTEM(m))
965 r = mkdir_label("/run/systemd/units", 0755);
966 else {
967 _cleanup_free_ char *units_path = NULL;
968 r = xdg_user_runtime_dir(&units_path, "/systemd/units");
969 if (r < 0)
970 return r;
971 r = mkdir_p_label(units_path, 0755);
972 }
973
d3070fbd 974 if (r < 0 && r != -EEXIST)
c70cac54 975 return r;
d3070fbd
LP
976 }
977
e27fe688
LP
978 m->taint_usr =
979 !in_initrd() &&
db55bbf2 980 dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) > 0;
e27fe688 981
232f6754
ZJS
982 /* Note that we do not set up the notify fd here. We do that after deserialization,
983 * since they might have gotten serialized across the reexec. */
3536f49e 984
1cc6c93a
YW
985 *_m = TAKE_PTR(m);
986
8e274523 987 return 0;
60918275
LP
988}
989
d86f9d52 990static int manager_setup_notify(Manager *m) {
7181dbdb 991 int r;
d86f9d52 992
638cece4 993 if (MANAGER_IS_TEST_RUN(m))
0d8c31ff
ZJS
994 return 0;
995
d86f9d52
LP
996 if (m->notify_fd < 0) {
997 _cleanup_close_ int fd = -1;
f36a9d59
ZJS
998 union sockaddr_union sa;
999 socklen_t sa_len;
d86f9d52
LP
1000
1001 /* First free all secondary fields */
a1e58e8e 1002 m->notify_socket = mfree(m->notify_socket);
5dcadb4c 1003 m->notify_event_source = sd_event_source_disable_unref(m->notify_event_source);
d86f9d52
LP
1004
1005 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
4a62c710
MS
1006 if (fd < 0)
1007 return log_error_errno(errno, "Failed to allocate notification socket: %m");
d86f9d52 1008
28e7e934 1009 fd_increase_rxbuf(fd, NOTIFY_RCVBUF_SIZE);
a47806fa 1010
b910cc72 1011 m->notify_socket = path_join(m->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/notify");
498e87d6
LP
1012 if (!m->notify_socket)
1013 return log_oom();
1014
f36a9d59
ZJS
1015 r = sockaddr_un_set_path(&sa.un, m->notify_socket);
1016 if (r < 0)
1017 return log_error_errno(r, "Notify socket '%s' not valid for AF_UNIX socket address, refusing.",
1018 m->notify_socket);
1019 sa_len = r;
15a3e96f 1020
498e87d6 1021 (void) mkdir_parents_label(m->notify_socket, 0755);
fbda85b0 1022 (void) sockaddr_un_unlink(&sa.un);
7181dbdb 1023
45ae2f72 1024 r = mac_selinux_bind(fd, &sa.sa, sa_len);
4a62c710 1025 if (r < 0)
45ae2f72 1026 return log_error_errno(r, "bind(%s) failed: %m", m->notify_socket);
d86f9d52 1027
2ff48e98 1028 r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
4a62c710 1029 if (r < 0)
2ff48e98 1030 return log_error_errno(r, "SO_PASSCRED failed: %m");
d86f9d52 1031
c10d6bdb 1032 m->notify_fd = TAKE_FD(fd);
d86f9d52
LP
1033
1034 log_debug("Using notification socket %s", m->notify_socket);
1035 }
1036
1037 if (!m->notify_event_source) {
151b9b96 1038 r = sd_event_add_io(m->event, &m->notify_event_source, m->notify_fd, EPOLLIN, manager_dispatch_notify_fd, m);
895b3a7b
MS
1039 if (r < 0)
1040 return log_error_errno(r, "Failed to allocate notify event source: %m");
d86f9d52 1041
d8fdc620
LP
1042 /* Process notification messages a bit earlier than SIGCHLD, so that we can still identify to which
1043 * service an exit message belongs. */
575b300b 1044 r = sd_event_source_set_priority(m->notify_event_source, SD_EVENT_PRIORITY_NORMAL-8);
23bbb0de
MS
1045 if (r < 0)
1046 return log_error_errno(r, "Failed to set priority of notify event source: %m");
7dfbe2e3
TG
1047
1048 (void) sd_event_source_set_description(m->notify_event_source, "manager-notify");
d86f9d52
LP
1049 }
1050
1051 return 0;
1052}
1053
d8fdc620
LP
1054static int manager_setup_cgroups_agent(Manager *m) {
1055
1056 static const union sockaddr_union sa = {
1057 .un.sun_family = AF_UNIX,
1058 .un.sun_path = "/run/systemd/cgroups-agent",
1059 };
1060 int r;
1061
1062 /* This creates a listening socket we receive cgroups agent messages on. We do not use D-Bus for delivering
1063 * these messages from the cgroups agent binary to PID 1, as the cgroups agent binary is very short-living, and
1064 * each instance of it needs a new D-Bus connection. Since D-Bus connections are SOCK_STREAM/AF_UNIX, on
1065 * overloaded systems the backlog of the D-Bus socket becomes relevant, as not more than the configured number
1066 * of D-Bus connections may be queued until the kernel will start dropping further incoming connections,
1067 * possibly resulting in lost cgroups agent messages. To avoid this, we'll use a private SOCK_DGRAM/AF_UNIX
1068 * socket, where no backlog is relevant as communication may take place without an actual connect() cycle, and
1069 * we thus won't lose messages.
1070 *
1071 * Note that PID 1 will forward the agent message to system bus, so that the user systemd instance may listen
1072 * to it. The system instance hence listens on this special socket, but the user instances listen on the system
1073 * bus for these messages. */
1074
638cece4 1075 if (MANAGER_IS_TEST_RUN(m))
d8fdc620
LP
1076 return 0;
1077
1078 if (!MANAGER_IS_SYSTEM(m))
1079 return 0;
1080
c22800e4 1081 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
b4cccbc1
LP
1082 if (r < 0)
1083 return log_error_errno(r, "Failed to determine whether unified cgroups hierarchy is used: %m");
1084 if (r > 0) /* We don't need this anymore on the unified hierarchy */
d8fdc620
LP
1085 return 0;
1086
1087 if (m->cgroups_agent_fd < 0) {
1088 _cleanup_close_ int fd = -1;
1089
1090 /* First free all secondary fields */
5dcadb4c 1091 m->cgroups_agent_event_source = sd_event_source_disable_unref(m->cgroups_agent_event_source);
d8fdc620
LP
1092
1093 fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
1094 if (fd < 0)
1095 return log_error_errno(errno, "Failed to allocate cgroups agent socket: %m");
1096
28e7e934 1097 fd_increase_rxbuf(fd, CGROUPS_AGENT_RCVBUF_SIZE);
d8fdc620 1098
155b6876 1099 (void) sockaddr_un_unlink(&sa.un);
d8fdc620
LP
1100
1101 /* Only allow root to connect to this socket */
1102 RUN_WITH_UMASK(0077)
fc2fffe7 1103 r = bind(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
d8fdc620
LP
1104 if (r < 0)
1105 return log_error_errno(errno, "bind(%s) failed: %m", sa.un.sun_path);
1106
0b7e8b32 1107 m->cgroups_agent_fd = TAKE_FD(fd);
d8fdc620
LP
1108 }
1109
1110 if (!m->cgroups_agent_event_source) {
1111 r = sd_event_add_io(m->event, &m->cgroups_agent_event_source, m->cgroups_agent_fd, EPOLLIN, manager_dispatch_cgroups_agent_fd, m);
1112 if (r < 0)
1113 return log_error_errno(r, "Failed to allocate cgroups agent event source: %m");
1114
cbe83389
LP
1115 /* Process cgroups notifications early. Note that when the agent notification is received
1116 * we'll just enqueue the unit in the cgroup empty queue, hence pick a high priority than
1117 * that. Also see handling of cgroup inotify for the unified cgroup stuff. */
1118 r = sd_event_source_set_priority(m->cgroups_agent_event_source, SD_EVENT_PRIORITY_NORMAL-9);
d8fdc620
LP
1119 if (r < 0)
1120 return log_error_errno(r, "Failed to set priority of cgroups agent event source: %m");
1121
1122 (void) sd_event_source_set_description(m->cgroups_agent_event_source, "manager-cgroups-agent");
1123 }
1124
1125 return 0;
1126}
1127
00d9ef85
LP
1128static int manager_setup_user_lookup_fd(Manager *m) {
1129 int r;
1130
1131 assert(m);
1132
1133 /* Set up the socket pair used for passing UID/GID resolution results from forked off processes to PID
1134 * 1. Background: we can't do name lookups (NSS) from PID 1, since it might involve IPC and thus activation,
1135 * and we might hence deadlock on ourselves. Hence we do all user/group lookups asynchronously from the forked
1136 * off processes right before executing the binaries to start. In order to be able to clean up any IPC objects
1137 * created by a unit (see RemoveIPC=) we need to know in PID 1 the used UID/GID of the executed processes,
1138 * hence we establish this communication channel so that forked off processes can pass their UID/GID
1139 * information back to PID 1. The forked off processes send their resolved UID/GID to PID 1 in a simple
1140 * datagram, along with their unit name, so that we can share one communication socket pair among all units for
1141 * this purpose.
1142 *
1143 * You might wonder why we need a communication channel for this that is independent of the usual notification
1144 * socket scheme (i.e. $NOTIFY_SOCKET). The primary difference is about trust: data sent via the $NOTIFY_SOCKET
1145 * channel is only accepted if it originates from the right unit and if reception was enabled for it. The user
1146 * lookup socket OTOH is only accessible by PID 1 and its children until they exec(), and always available.
1147 *
1148 * Note that this function is called under two circumstances: when we first initialize (in which case we
1149 * allocate both the socket pair and the event source to listen on it), and when we deserialize after a reload
1150 * (in which case the socket pair already exists but we still need to allocate the event source for it). */
1151
1152 if (m->user_lookup_fds[0] < 0) {
1153
1154 /* Free all secondary fields */
1155 safe_close_pair(m->user_lookup_fds);
5dcadb4c 1156 m->user_lookup_event_source = sd_event_source_disable_unref(m->user_lookup_event_source);
00d9ef85
LP
1157
1158 if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, m->user_lookup_fds) < 0)
1159 return log_error_errno(errno, "Failed to allocate user lookup socket: %m");
1160
28e7e934 1161 (void) fd_increase_rxbuf(m->user_lookup_fds[0], NOTIFY_RCVBUF_SIZE);
00d9ef85
LP
1162 }
1163
1164 if (!m->user_lookup_event_source) {
1165 r = sd_event_add_io(m->event, &m->user_lookup_event_source, m->user_lookup_fds[0], EPOLLIN, manager_dispatch_user_lookup_fd, m);
1166 if (r < 0)
1167 return log_error_errno(errno, "Failed to allocate user lookup event source: %m");
1168
1169 /* Process even earlier than the notify event source, so that we always know first about valid UID/GID
1170 * resolutions */
67ae4e8d 1171 r = sd_event_source_set_priority(m->user_lookup_event_source, SD_EVENT_PRIORITY_NORMAL-11);
00d9ef85 1172 if (r < 0)
5238e957 1173 return log_error_errno(errno, "Failed to set priority of user lookup event source: %m");
00d9ef85
LP
1174
1175 (void) sd_event_source_set_description(m->user_lookup_event_source, "user-lookup");
1176 }
1177
1178 return 0;
1179}
1180
23a177ef 1181static unsigned manager_dispatch_cleanup_queue(Manager *m) {
595ed347 1182 Unit *u;
23a177ef
LP
1183 unsigned n = 0;
1184
1185 assert(m);
1186
595ed347
MS
1187 while ((u = m->cleanup_queue)) {
1188 assert(u->in_cleanup_queue);
23a177ef 1189
595ed347 1190 unit_free(u);
23a177ef
LP
1191 n++;
1192 }
1193
1194 return n;
1195}
1196
eced69b3 1197enum {
35b8ca3a 1198 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
eced69b3
LP
1199 GC_OFFSET_UNSURE, /* No clue */
1200 GC_OFFSET_GOOD, /* We still need this unit */
1201 GC_OFFSET_BAD, /* We don't need this unit anymore */
1202 _GC_OFFSET_MAX
1203};
1204
00d9ef85 1205static void unit_gc_mark_good(Unit *u, unsigned gc_marker) {
4892084f
LN
1206 Unit *other;
1207
1208 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
1209
1210 /* Recursively mark referenced units as GOOD as well */
15ed3c3a 1211 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCES)
4892084f
LN
1212 if (other->gc_marker == gc_marker + GC_OFFSET_UNSURE)
1213 unit_gc_mark_good(other, gc_marker);
1214}
1215
eced69b3 1216static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
701cc384 1217 Unit *other;
eced69b3 1218 bool is_bad;
701cc384
LP
1219
1220 assert(u);
1221
4c701096
YW
1222 if (IN_SET(u->gc_marker - gc_marker,
1223 GC_OFFSET_GOOD, GC_OFFSET_BAD, GC_OFFSET_UNSURE, GC_OFFSET_IN_PATH))
701cc384
LP
1224 return;
1225
ac155bb8 1226 if (u->in_cleanup_queue)
701cc384
LP
1227 goto bad;
1228
f2f725e5 1229 if (!unit_may_gc(u))
701cc384
LP
1230 goto good;
1231
ac155bb8 1232 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
eced69b3
LP
1233
1234 is_bad = true;
1235
15ed3c3a 1236 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_REFERENCED_BY) {
701cc384
LP
1237 unit_gc_sweep(other, gc_marker);
1238
ac155bb8 1239 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
701cc384 1240 goto good;
eced69b3 1241
ac155bb8 1242 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
eced69b3 1243 is_bad = false;
701cc384
LP
1244 }
1245
ef3fc326
ZJS
1246 LIST_FOREACH(refs_by_target, ref, u->refs_by_target) {
1247 unit_gc_sweep(ref->source, gc_marker);
2641f02e 1248
ef3fc326
ZJS
1249 if (ref->source->gc_marker == gc_marker + GC_OFFSET_GOOD)
1250 goto good;
2641f02e 1251
ef3fc326
ZJS
1252 if (ref->source->gc_marker != gc_marker + GC_OFFSET_BAD)
1253 is_bad = false;
2641f02e 1254 }
701cc384 1255
eced69b3
LP
1256 if (is_bad)
1257 goto bad;
1258
1259 /* We were unable to find anything out about this entry, so
1260 * let's investigate it later */
ac155bb8 1261 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
eced69b3
LP
1262 unit_add_to_gc_queue(u);
1263 return;
1264
701cc384 1265bad:
eced69b3
LP
1266 /* We definitely know that this one is not useful anymore, so
1267 * let's mark it for deletion */
ac155bb8 1268 u->gc_marker = gc_marker + GC_OFFSET_BAD;
eced69b3 1269 unit_add_to_cleanup_queue(u);
701cc384
LP
1270 return;
1271
1272good:
4892084f 1273 unit_gc_mark_good(u, gc_marker);
701cc384
LP
1274}
1275
c5a97ed1
LP
1276static unsigned manager_dispatch_gc_unit_queue(Manager *m) {
1277 unsigned n = 0, gc_marker;
595ed347 1278 Unit *u;
701cc384
LP
1279
1280 assert(m);
1281
cf1265e1 1282 /* log_debug("Running GC..."); */
701cc384 1283
eced69b3
LP
1284 m->gc_marker += _GC_OFFSET_MAX;
1285 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
c9c0cadb 1286 m->gc_marker = 1;
701cc384 1287
eced69b3
LP
1288 gc_marker = m->gc_marker;
1289
c5a97ed1 1290 while ((u = m->gc_unit_queue)) {
595ed347 1291 assert(u->in_gc_queue);
701cc384 1292
595ed347 1293 unit_gc_sweep(u, gc_marker);
eced69b3 1294
c5a97ed1 1295 LIST_REMOVE(gc_queue, m->gc_unit_queue, u);
595ed347 1296 u->in_gc_queue = false;
701cc384
LP
1297
1298 n++;
1299
4c701096
YW
1300 if (IN_SET(u->gc_marker - gc_marker,
1301 GC_OFFSET_BAD, GC_OFFSET_UNSURE)) {
cc3bc3e6 1302 if (u->id)
f2341e0a 1303 log_unit_debug(u, "Collecting.");
595ed347
MS
1304 u->gc_marker = gc_marker + GC_OFFSET_BAD;
1305 unit_add_to_cleanup_queue(u);
701cc384
LP
1306 }
1307 }
1308
701cc384
LP
1309 return n;
1310}
1311
c5a97ed1
LP
1312static unsigned manager_dispatch_gc_job_queue(Manager *m) {
1313 unsigned n = 0;
1314 Job *j;
1315
1316 assert(m);
1317
1318 while ((j = m->gc_job_queue)) {
1319 assert(j->in_gc_queue);
1320
1321 LIST_REMOVE(gc_queue, m->gc_job_queue, j);
1322 j->in_gc_queue = false;
1323
1324 n++;
1325
2ab3050f 1326 if (!job_may_gc(j))
c5a97ed1
LP
1327 continue;
1328
1329 log_unit_debug(j->unit, "Collecting job.");
1330 (void) job_finish_and_invalidate(j, JOB_COLLECTED, false, false);
1331 }
1332
1333 return n;
1334}
1335
a3c1168a
LP
1336static unsigned manager_dispatch_stop_when_unneeded_queue(Manager *m) {
1337 unsigned n = 0;
1338 Unit *u;
1339 int r;
1340
1341 assert(m);
1342
1343 while ((u = m->stop_when_unneeded_queue)) {
1344 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
a3c1168a
LP
1345
1346 assert(u->in_stop_when_unneeded_queue);
1347 LIST_REMOVE(stop_when_unneeded_queue, m->stop_when_unneeded_queue, u);
1348 u->in_stop_when_unneeded_queue = false;
1349
1350 n++;
1351
1352 if (!unit_is_unneeded(u))
1353 continue;
1354
1355 log_unit_debug(u, "Unit is not needed anymore.");
1356
1357 /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1358 * service being unnecessary after a while. */
1359
0bc488c9 1360 if (!ratelimit_below(&u->auto_start_stop_ratelimit)) {
a3c1168a
LP
1361 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1362 continue;
1363 }
1364
1365 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
50cbaba4 1366 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, NULL, &error, NULL);
a3c1168a
LP
1367 if (r < 0)
1368 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1369 }
1370
1371 return n;
1372}
1373
0bc488c9
LP
1374static unsigned manager_dispatch_start_when_upheld_queue(Manager *m) {
1375 unsigned n = 0;
1376 Unit *u;
1377 int r;
1378
1379 assert(m);
1380
1381 while ((u = m->start_when_upheld_queue)) {
1382 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1383 Unit *culprit = NULL;
1384
1385 assert(u->in_start_when_upheld_queue);
1386 LIST_REMOVE(start_when_upheld_queue, m->start_when_upheld_queue, u);
1387 u->in_start_when_upheld_queue = false;
1388
1389 n++;
1390
1391 if (!unit_is_upheld_by_active(u, &culprit))
1392 continue;
1393
1394 log_unit_debug(u, "Unit is started because upheld by active unit %s.", culprit->id);
1395
1396 /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1397 * service being unnecessary after a while. */
1398
1399 if (!ratelimit_below(&u->auto_start_stop_ratelimit)) {
1400 log_unit_warning(u, "Unit needs to be started because active unit %s upholds it, but not starting since we tried this too often recently.", culprit->id);
1401 continue;
1402 }
1403
1404 r = manager_add_job(u->manager, JOB_START, u, JOB_FAIL, NULL, &error, NULL);
1405 if (r < 0)
1406 log_unit_warning_errno(u, r, "Failed to enqueue start job, ignoring: %s", bus_error_message(&error, r));
1407 }
1408
1409 return n;
1410}
1411
56c59592
LP
1412static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
1413 unsigned n = 0;
1414 Unit *u;
1415 int r;
1416
1417 assert(m);
1418
1419 while ((u = m->stop_when_bound_queue)) {
1420 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1421 Unit *culprit = NULL;
1422
1423 assert(u->in_stop_when_bound_queue);
1424 LIST_REMOVE(stop_when_bound_queue, m->stop_when_bound_queue, u);
1425 u->in_stop_when_bound_queue = false;
1426
1427 n++;
1428
1429 if (!unit_is_bound_by_inactive(u, &culprit))
1430 continue;
1431
1432 log_unit_debug(u, "Unit is stopped because bound to inactive unit %s.", culprit->id);
1433
1434 /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
1435 * service being unnecessary after a while. */
1436
1437 if (!ratelimit_below(&u->auto_start_stop_ratelimit)) {
1438 log_unit_warning(u, "Unit needs to be stopped because it is bound to inactive unit %s it, but not stopping since we tried this too often recently.", culprit->id);
1439 continue;
1440 }
1441
1442 r = manager_add_job(u->manager, JOB_STOP, u, JOB_REPLACE, NULL, &error, NULL);
1443 if (r < 0)
1444 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1445 }
1446
1447 return n;
1448}
1449
a16e1123 1450static void manager_clear_jobs_and_units(Manager *m) {
a16e1123 1451 Unit *u;
60918275
LP
1452
1453 assert(m);
1454
87f0e418
LP
1455 while ((u = hashmap_first(m->units)))
1456 unit_free(u);
964e0949
LP
1457
1458 manager_dispatch_cleanup_queue(m);
1459
1460 assert(!m->load_queue);
da8e1782 1461 assert(prioq_isempty(m->run_queue));
964e0949
LP
1462 assert(!m->dbus_unit_queue);
1463 assert(!m->dbus_job_queue);
1464 assert(!m->cleanup_queue);
c5a97ed1
LP
1465 assert(!m->gc_unit_queue);
1466 assert(!m->gc_job_queue);
13e72103
MK
1467 assert(!m->cgroup_realize_queue);
1468 assert(!m->cgroup_empty_queue);
1469 assert(!m->cgroup_oom_queue);
1470 assert(!m->target_deps_queue);
a3c1168a 1471 assert(!m->stop_when_unneeded_queue);
0bc488c9 1472 assert(!m->start_when_upheld_queue);
56c59592 1473 assert(!m->stop_when_bound_queue);
964e0949 1474
964e0949
LP
1475 assert(hashmap_isempty(m->jobs));
1476 assert(hashmap_isempty(m->units));
9e9e2b72
MS
1477
1478 m->n_on_console = 0;
1479 m->n_running_jobs = 0;
1e75824c
MK
1480 m->n_installed_jobs = 0;
1481 m->n_failed_jobs = 0;
a16e1123
LP
1482}
1483
06d8d842 1484Manager* manager_free(Manager *m) {
06d8d842
ZJS
1485 if (!m)
1486 return NULL;
a16e1123
LP
1487
1488 manager_clear_jobs_and_units(m);
23a177ef 1489
24b45970 1490 for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++)
7824bbeb
LP
1491 if (unit_vtable[c]->shutdown)
1492 unit_vtable[c]->shutdown(m);
1493
86036b26
LP
1494 /* Keep the cgroup hierarchy in place except when we know we are going down for good */
1495 manager_shutdown_cgroup(m, IN_SET(m->objective, MANAGER_EXIT, MANAGER_REBOOT, MANAGER_POWEROFF, MANAGER_HALT, MANAGER_KEXEC));
8e274523 1496
07a78643 1497 lookup_paths_flush_generator(&m->lookup_paths);
5a1e9937 1498
5e8d1c9a 1499 bus_done(m);
19d22d43 1500 manager_varlink_done(m);
ea430986 1501
e8a565cb
YW
1502 exec_runtime_vacuum(m);
1503 hashmap_free(m->exec_runtime_by_id);
1504
29206d46
LP
1505 dynamic_user_vacuum(m, false);
1506 hashmap_free(m->dynamic_users);
1507
87f0e418 1508 hashmap_free(m->units);
4b58153d 1509 hashmap_free(m->units_by_invocation_id);
60918275 1510 hashmap_free(m->jobs);
62a76913 1511 hashmap_free(m->watch_pids);
05e343b7 1512 hashmap_free(m->watch_bus);
9152c765 1513
da8e1782
MO
1514 prioq_free(m->run_queue);
1515
95ae05c0 1516 set_free(m->startup_units);
f755e3b7
LP
1517 set_free(m->failed_units);
1518
718db961 1519 sd_event_source_unref(m->signal_event_source);
575b300b 1520 sd_event_source_unref(m->sigchld_event_source);
718db961 1521 sd_event_source_unref(m->notify_event_source);
d8fdc620 1522 sd_event_source_unref(m->cgroups_agent_event_source);
718db961 1523 sd_event_source_unref(m->time_change_event_source);
bbf5fd8e 1524 sd_event_source_unref(m->timezone_change_event_source);
718db961 1525 sd_event_source_unref(m->jobs_in_progress_event_source);
752b5905 1526 sd_event_source_unref(m->run_queue_event_source);
00d9ef85 1527 sd_event_source_unref(m->user_lookup_event_source);
718db961 1528
03e334a1
LP
1529 safe_close(m->signal_fd);
1530 safe_close(m->notify_fd);
d8fdc620 1531 safe_close(m->cgroups_agent_fd);
00d9ef85 1532 safe_close_pair(m->user_lookup_fds);
718db961 1533
e46b13c8
ZJS
1534 manager_close_ask_password(m);
1535
718db961
LP
1536 manager_close_idle_pipe(m);
1537
1538 sd_event_unref(m->event);
60918275 1539
c952c6ec
LP
1540 free(m->notify_socket);
1541
84e3543e 1542 lookup_paths_free(&m->lookup_paths);
1ad6e8b3
LP
1543 strv_free(m->transient_environment);
1544 strv_free(m->client_environment);
036643a2 1545
4ad49000 1546 hashmap_free(m->cgroup_unit);
e8630e69 1547 manager_free_unit_name_maps(m);
33be102a 1548
664f88a7
LP
1549 free(m->switch_root);
1550 free(m->switch_root_init);
1551
aa5ae971
ŁS
1552 free(m->default_smack_process_label);
1553
31ce987c 1554 rlimit_free_all(m->rlimit);
c93ff2e9 1555
a57f7e2c
LP
1556 assert(hashmap_isempty(m->units_requiring_mounts_for));
1557 hashmap_free(m->units_requiring_mounts_for);
1558
00d9ef85
LP
1559 hashmap_free(m->uid_refs);
1560 hashmap_free(m->gid_refs);
1561
24b45970 1562 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
35aba85a 1563 m->prefix[dt] = mfree(m->prefix[dt]);
2ad591a3
LP
1564 free(m->received_credentials_directory);
1565 free(m->received_encrypted_credentials_directory);
35aba85a 1566
aff3a9e1
LB
1567 free(m->watchdog_pretimeout_governor);
1568 free(m->watchdog_pretimeout_governor_overridden);
1569
b1994387
ILG
1570#if BPF_FRAMEWORK
1571 lsm_bpf_destroy(m->restrict_fs);
1572#endif
1573
6b430fdb 1574 return mfree(m);
60918275
LP
1575}
1576
04eb582a 1577static void manager_enumerate_perpetual(Manager *m) {
04eb582a
LP
1578 assert(m);
1579
1545051c 1580 if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
b1d5246d
ZJS
1581 return;
1582
04eb582a 1583 /* Let's ask every type to load all units from disk/kernel that it might know */
24b45970 1584 for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
04eb582a
LP
1585 if (!unit_type_supported(c)) {
1586 log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
1587 continue;
1588 }
1589
1590 if (unit_vtable[c]->enumerate_perpetual)
1591 unit_vtable[c]->enumerate_perpetual(m);
1592 }
1593}
1594
a1113e08 1595static void manager_enumerate(Manager *m) {
f50e0a01
LP
1596 assert(m);
1597
1545051c 1598 if (FLAGS_SET(m->test_run_flags, MANAGER_TEST_RUN_MINIMAL))
b1d5246d
ZJS
1599 return;
1600
04eb582a 1601 /* Let's ask every type to load all units from disk/kernel that it might know */
24b45970 1602 for (UnitType c = 0; c < _UNIT_TYPE_MAX; c++) {
1c2e9646 1603 if (!unit_type_supported(c)) {
03afec3c 1604 log_debug("Unit type .%s is not supported on this system.", unit_type_to_string(c));
0faacd47 1605 continue;
a57f7e2c 1606 }
f50e0a01 1607
94b01dae
ZJS
1608 if (unit_vtable[c]->enumerate)
1609 unit_vtable[c]->enumerate(m);
0faacd47
LP
1610 }
1611
f50e0a01 1612 manager_dispatch_load_queue(m);
a16e1123
LP
1613}
1614
007c6337 1615static void manager_coldplug(Manager *m) {
a16e1123
LP
1616 Unit *u;
1617 char *k;
007c6337 1618 int r;
a16e1123
LP
1619
1620 assert(m);
f50e0a01 1621
28e5e1e9 1622 log_debug("Invoking unit coldplug() handlers%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
f0831ed2
LP
1623
1624 /* Let's place the units back into their deserialized state */
90e74a66 1625 HASHMAP_FOREACH_KEY(u, k, m->units) {
f50e0a01
LP
1626
1627 /* ignore aliases */
ac155bb8 1628 if (u->id != k)
f50e0a01
LP
1629 continue;
1630
007c6337
LP
1631 r = unit_coldplug(u);
1632 if (r < 0)
1633 log_warning_errno(r, "We couldn't coldplug %s, proceeding anyway: %m", u->id);
f50e0a01 1634 }
a16e1123
LP
1635}
1636
f0831ed2 1637static void manager_catchup(Manager *m) {
f0831ed2
LP
1638 Unit *u;
1639 char *k;
1640
1641 assert(m);
1642
28e5e1e9 1643 log_debug("Invoking unit catchup() handlers%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
f0831ed2
LP
1644
1645 /* Let's catch up on any state changes that happened while we were reloading/reexecing */
90e74a66 1646 HASHMAP_FOREACH_KEY(u, k, m->units) {
f0831ed2
LP
1647
1648 /* ignore aliases */
1649 if (u->id != k)
1650 continue;
1651
1652 unit_catchup(u);
1653 }
1654}
1655
9ff1a6f1 1656static void manager_distribute_fds(Manager *m, FDSet *fds) {
9ff1a6f1 1657 Unit *u;
9588bc32
LP
1658
1659 assert(m);
1660
90e74a66 1661 HASHMAP_FOREACH(u, m->units) {
9588bc32
LP
1662
1663 if (fdset_size(fds) <= 0)
1664 break;
1665
9ff1a6f1
LP
1666 if (!UNIT_VTABLE(u)->distribute_fds)
1667 continue;
9588bc32 1668
9ff1a6f1
LP
1669 UNIT_VTABLE(u)->distribute_fds(u, fds);
1670 }
9588bc32
LP
1671}
1672
8559b3b7
LP
1673static bool manager_dbus_is_running(Manager *m, bool deserialized) {
1674 Unit *u;
1675
1676 assert(m);
1677
1678 /* This checks whether the dbus instance we are supposed to expose our APIs on is up. We check both the socket
1679 * and the service unit. If the 'deserialized' parameter is true we'll check the deserialized state of the unit
1680 * rather than the current one. */
1681
638cece4 1682 if (MANAGER_IS_TEST_RUN(m))
8559b3b7
LP
1683 return false;
1684
8559b3b7
LP
1685 u = manager_get_unit(m, SPECIAL_DBUS_SOCKET);
1686 if (!u)
1687 return false;
1688 if ((deserialized ? SOCKET(u)->deserialized_state : SOCKET(u)->state) != SOCKET_RUNNING)
1689 return false;
1690
1691 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1692 if (!u)
1693 return false;
1694 if (!IN_SET((deserialized ? SERVICE(u)->deserialized_state : SERVICE(u)->state), SERVICE_RUNNING, SERVICE_RELOAD))
1695 return false;
1696
1697 return true;
1698}
1699
9d4c195c
LP
1700static void manager_setup_bus(Manager *m) {
1701 assert(m);
1702
1703 /* Let's set up our private bus connection now, unconditionally */
1704 (void) bus_init_private(m);
1705
1706 /* If we are in --user mode also connect to the system bus now */
1707 if (MANAGER_IS_USER(m))
1708 (void) bus_init_system(m);
1709
1710 /* Let's connect to the bus now, but only if the unit is supposed to be up */
1711 if (manager_dbus_is_running(m, MANAGER_IS_RELOADING(m))) {
1712 (void) bus_init_api(m);
1713
1714 if (MANAGER_IS_SYSTEM(m))
1715 (void) bus_init_system(m);
1716 }
1717}
1718
159f1e76
LP
1719static void manager_preset_all(Manager *m) {
1720 int r;
1721
1722 assert(m);
1723
1724 if (m->first_boot <= 0)
1725 return;
1726
1727 if (!MANAGER_IS_SYSTEM(m))
1728 return;
1729
638cece4 1730 if (MANAGER_IS_TEST_RUN(m))
159f1e76
LP
1731 return;
1732
1733 /* If this is the first boot, and we are in the host system, then preset everything */
93651582
JL
1734 UnitFilePresetMode mode = FIRST_BOOT_FULL_PRESET ? UNIT_FILE_PRESET_FULL : UNIT_FILE_PRESET_ENABLE_ONLY;
1735
1736 r = unit_file_preset_all(LOOKUP_SCOPE_SYSTEM, 0, NULL, mode, NULL, 0);
159f1e76
LP
1737 if (r < 0)
1738 log_full_errno(r == -EEXIST ? LOG_NOTICE : LOG_WARNING, r,
1739 "Failed to populate /etc with preset unit settings, ignoring: %m");
1740 else
1741 log_info("Populated /etc with preset unit settings.");
1742}
1743
5ce5e1ad
LP
1744static void manager_ready(Manager *m) {
1745 assert(m);
1746
1747 /* After having loaded everything, do the final round of catching up with what might have changed */
1748
1749 m->objective = MANAGER_OK; /* Tell everyone we are up now */
1750
1751 /* It might be safe to log to the journal now and connect to dbus */
1752 manager_recheck_journal(m);
1753 manager_recheck_dbus(m);
1754
5ce5e1ad
LP
1755 /* Let's finally catch up with any changes that took place while we were reloading/reexecing */
1756 manager_catchup(m);
c6e892bc 1757
15b9243c 1758 /* Create a file which will indicate when the manager started loading units the last time. */
4b3ad81b
LB
1759 if (MANAGER_IS_SYSTEM(m))
1760 (void) touch_file("/run/systemd/systemd-units-load", false,
1761 m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].realtime ?: now(CLOCK_REALTIME),
1762 UID_INVALID, GID_INVALID, 0444);
15b9243c 1763
c6e892bc 1764 m->honor_device_enumeration = true;
5ce5e1ad
LP
1765}
1766
a01ba4b2 1767Manager* manager_reloading_start(Manager *m) {
d147e2b6 1768 m->n_reloading++;
49fbe940 1769 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_UNITS_LOAD);
d147e2b6
ZJS
1770 return m;
1771}
49fbe940 1772
a01ba4b2 1773void manager_reloading_stopp(Manager **m) {
d147e2b6
ZJS
1774 if (*m) {
1775 assert((*m)->n_reloading > 0);
1776 (*m)->n_reloading--;
1777 }
1778}
1779
2a7cf953 1780int manager_startup(Manager *m, FILE *serialization, FDSet *fds, const char *root) {
17f01ace 1781 int r;
a16e1123
LP
1782
1783 assert(m);
1784
a1f31f47
ZJS
1785 /* If we are running in test mode, we still want to run the generators,
1786 * but we should not touch the real generator directories. */
99aad9a2
ZJS
1787 r = lookup_paths_init_or_warn(&m->lookup_paths, m->unit_file_scope,
1788 MANAGER_IS_TEST_RUN(m) ? LOOKUP_PATHS_TEMPORARY_GENERATED : 0,
1789 root);
e801700e 1790 if (r < 0)
99aad9a2 1791 return r;
5a1e9937 1792
d4ee7bd8 1793 dual_timestamp_get(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_START));
eb523bfb
LP
1794 r = manager_run_environment_generators(m);
1795 if (r >= 0)
1796 r = manager_run_generators(m);
d4ee7bd8 1797 dual_timestamp_get(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_GENERATORS_FINISH));
07719a21
LP
1798 if (r < 0)
1799 return r;
1800
159f1e76 1801 manager_preset_all(m);
572986ca 1802
581fef8d 1803 lookup_paths_log(&m->lookup_paths);
572986ca 1804
4df7d537
ZJS
1805 {
1806 /* This block is (optionally) done with the reloading counter bumped */
d7ac0952 1807 _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
4df7d537
ZJS
1808
1809 /* If we will deserialize make sure that during enumeration this is already known, so we increase the
1810 * counter here already */
1811 if (serialization)
1812 reloading = manager_reloading_start(m);
1813
1814 /* First, enumerate what we can from all config files */
1815 dual_timestamp_get(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_START));
1816 manager_enumerate_perpetual(m);
1817 manager_enumerate(m);
1818 dual_timestamp_get(m->timestamps + manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_UNITS_LOAD_FINISH));
1819
1820 /* Second, deserialize if there is something to deserialize */
1821 if (serialization) {
1822 r = manager_deserialize(m, serialization, fds);
1823 if (r < 0)
1824 return log_error_errno(r, "Deserialization failed: %m");
1825 }
01e10de3 1826
4df7d537
ZJS
1827 /* Any fds left? Find some unit which wants them. This is useful to allow container managers to pass
1828 * some file descriptors to us pre-initialized. This enables socket-based activation of entire
1829 * containers. */
1830 manager_distribute_fds(m, fds);
d86f9d52 1831
4df7d537
ZJS
1832 /* We might have deserialized the notify fd, but if we didn't then let's create the bus now */
1833 r = manager_setup_notify(m);
1834 if (r < 0)
1835 /* No sense to continue without notifications, our children would fail anyway. */
1836 return r;
d8fdc620 1837
4df7d537
ZJS
1838 r = manager_setup_cgroups_agent(m);
1839 if (r < 0)
1840 /* Likewise, no sense to continue without empty cgroup notifications. */
1841 return r;
00d9ef85 1842
4df7d537
ZJS
1843 r = manager_setup_user_lookup_fd(m);
1844 if (r < 0)
1845 /* This shouldn't fail, except if things are really broken. */
1846 return r;
8559b3b7 1847
4df7d537
ZJS
1848 /* Connect to the bus if we are good for it */
1849 manager_setup_bus(m);
e3dd987c 1850
5238e957 1851 /* Now that we are connected to all possible buses, let's deserialize who is tracking us. */
4df7d537
ZJS
1852 r = bus_track_coldplug(m, &m->subscribed, false, m->deserialized_subscribed);
1853 if (r < 0)
1854 log_warning_errno(r, "Failed to deserialized tracked clients, ignoring: %m");
1855 m->deserialized_subscribed = strv_free(m->deserialized_subscribed);
a16e1123 1856
19d22d43
LP
1857 r = manager_varlink_init(m);
1858 if (r < 0)
064a5c14 1859 log_warning_errno(r, "Failed to set up Varlink, ignoring: %m");
19d22d43 1860
4df7d537
ZJS
1861 /* Third, fire things up! */
1862 manager_coldplug(m);
3ad2afb6 1863
4df7d537
ZJS
1864 /* Clean up runtime objects */
1865 manager_vacuum(m);
71445ae7 1866
4df7d537
ZJS
1867 if (serialization)
1868 /* Let's wait for the UnitNew/JobNew messages being sent, before we notify that the
1869 * reload is finished */
1870 m->send_reloading_done = true;
9f611ad8
LP
1871 }
1872
5ce5e1ad 1873 manager_ready(m);
f0831ed2 1874
17f01ace 1875 return 0;
f50e0a01
LP
1876}
1877
50cbaba4
LP
1878int manager_add_job(
1879 Manager *m,
1880 JobType type,
1881 Unit *unit,
1882 JobMode mode,
1883 Set *affected_jobs,
1884 sd_bus_error *error,
1885 Job **ret) {
1886
7527cb52 1887 Transaction *tr;
50cbaba4 1888 int r;
e5b5ae50
LP
1889
1890 assert(m);
1891 assert(type < _JOB_TYPE_MAX);
87f0e418 1892 assert(unit);
e5b5ae50 1893 assert(mode < _JOB_MODE_MAX);
60918275 1894
7358dc02 1895 if (mode == JOB_ISOLATE && type != JOB_START)
1b09b81c 1896 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "Isolate is only valid for start.");
c497c7a9 1897
7358dc02 1898 if (mode == JOB_ISOLATE && !unit->allow_isolate)
1b09b81c 1899 return sd_bus_error_set(error, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
2528a7a6 1900
1f0f9f21 1901 if (mode == JOB_TRIGGERING && type != JOB_STOP)
1b09b81c 1902 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "--job-mode=triggering is only valid for stop.");
1f0f9f21 1903
f2341e0a 1904 log_unit_debug(unit, "Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
9f04bd52 1905
c6497ccb 1906 type = job_type_collapse(type, unit);
e0209d83 1907
23ade460 1908 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
7527cb52
MS
1909 if (!tr)
1910 return -ENOMEM;
11dd41ce 1911
4bd29fe5 1912 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, false,
3742095b 1913 IN_SET(mode, JOB_IGNORE_DEPENDENCIES, JOB_IGNORE_REQUIREMENTS),
50cbaba4 1914 mode == JOB_IGNORE_DEPENDENCIES, error);
7527cb52
MS
1915 if (r < 0)
1916 goto tr_abort;
c497c7a9 1917
7527cb52
MS
1918 if (mode == JOB_ISOLATE) {
1919 r = transaction_add_isolate_jobs(tr, m);
1920 if (r < 0)
1921 goto tr_abort;
1922 }
1923
1f0f9f21
KK
1924 if (mode == JOB_TRIGGERING) {
1925 r = transaction_add_triggering_jobs(tr, unit);
1926 if (r < 0)
1927 goto tr_abort;
1928 }
1929
50cbaba4 1930 r = transaction_activate(tr, m, mode, affected_jobs, error);
7527cb52
MS
1931 if (r < 0)
1932 goto tr_abort;
e5b5ae50 1933
f2341e0a 1934 log_unit_debug(unit,
66870f90
ZJS
1935 "Enqueued job %s/%s as %u", unit->id,
1936 job_type_to_string(type), (unsigned) tr->anchor_job->id);
f50e0a01 1937
50cbaba4
LP
1938 if (ret)
1939 *ret = tr->anchor_job;
60918275 1940
7527cb52 1941 transaction_free(tr);
e5b5ae50 1942 return 0;
7527cb52
MS
1943
1944tr_abort:
1945 transaction_abort(tr);
1946 transaction_free(tr);
1947 return r;
e5b5ae50 1948}
60918275 1949
50cbaba4 1950int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, sd_bus_error *e, Job **ret) {
4440b27d 1951 Unit *unit = NULL; /* just to appease gcc, initialization is not really necessary */
28247076
LP
1952 int r;
1953
1954 assert(m);
1955 assert(type < _JOB_TYPE_MAX);
1956 assert(name);
1957 assert(mode < _JOB_MODE_MAX);
1958
c3090674
LP
1959 r = manager_load_unit(m, name, NULL, NULL, &unit);
1960 if (r < 0)
28247076 1961 return r;
4440b27d 1962 assert(unit);
28247076 1963
50cbaba4 1964 return manager_add_job(m, type, unit, mode, affected_jobs, e, ret);
53f18416
LP
1965}
1966
50cbaba4 1967int manager_add_job_by_name_and_warn(Manager *m, JobType type, const char *name, JobMode mode, Set *affected_jobs, Job **ret) {
4afd3348 1968 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
53f18416
LP
1969 int r;
1970
1971 assert(m);
1972 assert(type < _JOB_TYPE_MAX);
1973 assert(name);
1974 assert(mode < _JOB_MODE_MAX);
1975
50cbaba4 1976 r = manager_add_job_by_name(m, type, name, mode, affected_jobs, &error, ret);
53f18416
LP
1977 if (r < 0)
1978 return log_warning_errno(r, "Failed to enqueue %s job for %s: %s", job_mode_to_string(mode), name, bus_error_message(&error, r));
1979
1980 return r;
28247076
LP
1981}
1982
15d167f8
JW
1983int manager_propagate_reload(Manager *m, Unit *unit, JobMode mode, sd_bus_error *e) {
1984 int r;
1985 Transaction *tr;
1986
1987 assert(m);
1988 assert(unit);
1989 assert(mode < _JOB_MODE_MAX);
1990 assert(mode != JOB_ISOLATE); /* Isolate is only valid for start */
1991
1992 tr = transaction_new(mode == JOB_REPLACE_IRREVERSIBLY);
1993 if (!tr)
1994 return -ENOMEM;
1995
1996 /* We need an anchor job */
1997 r = transaction_add_job_and_dependencies(tr, JOB_NOP, unit, NULL, false, false, true, true, e);
1998 if (r < 0)
1999 goto tr_abort;
2000
2001 /* Failure in adding individual dependencies is ignored, so this always succeeds. */
2002 transaction_add_propagate_reload_jobs(tr, unit, tr->anchor_job, mode == JOB_IGNORE_DEPENDENCIES, e);
2003
50cbaba4 2004 r = transaction_activate(tr, m, mode, NULL, e);
15d167f8
JW
2005 if (r < 0)
2006 goto tr_abort;
2007
2008 transaction_free(tr);
2009 return 0;
2010
2011tr_abort:
2012 transaction_abort(tr);
2013 transaction_free(tr);
2014 return r;
2015}
2016
60918275
LP
2017Job *manager_get_job(Manager *m, uint32_t id) {
2018 assert(m);
2019
2020 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
2021}
2022
87f0e418 2023Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
2024 assert(m);
2025 assert(name);
2026
87f0e418 2027 return hashmap_get(m->units, name);
60918275
LP
2028}
2029
19496554
MS
2030static int manager_dispatch_target_deps_queue(Manager *m) {
2031 Unit *u;
19496554
MS
2032 int r = 0;
2033
19496554
MS
2034 assert(m);
2035
2036 while ((u = m->target_deps_queue)) {
15ed3c3a
LP
2037 _cleanup_free_ Unit **targets = NULL;
2038 int n_targets;
2039
19496554
MS
2040 assert(u->in_target_deps_queue);
2041
2042 LIST_REMOVE(target_deps_queue, u->manager->target_deps_queue, u);
2043 u->in_target_deps_queue = false;
2044
15ed3c3a
LP
2045 /* Take an "atomic" snapshot of dependencies here, as the call below will likely modify the
2046 * dependencies, and we can't have it that hash tables we iterate through are modified while
2047 * we are iterating through them. */
2048 n_targets = unit_get_dependency_array(u, UNIT_ATOM_DEFAULT_TARGET_DEPENDENCIES, &targets);
2049 if (n_targets < 0)
2050 return n_targets;
19496554 2051
15ed3c3a
LP
2052 for (int i = 0; i < n_targets; i++) {
2053 r = unit_add_default_target_dependency(u, targets[i]);
2054 if (r < 0)
2055 return r;
19496554
MS
2056 }
2057 }
2058
2059 return r;
2060}
2061
c1e1601e 2062unsigned manager_dispatch_load_queue(Manager *m) {
595ed347 2063 Unit *u;
c1e1601e 2064 unsigned n = 0;
60918275
LP
2065
2066 assert(m);
2067
223dabab
LP
2068 /* Make sure we are not run recursively */
2069 if (m->dispatching_load_queue)
c1e1601e 2070 return 0;
223dabab
LP
2071
2072 m->dispatching_load_queue = true;
2073
87f0e418 2074 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
2075 * tries to load its data until the queue is empty */
2076
595ed347
MS
2077 while ((u = m->load_queue)) {
2078 assert(u->in_load_queue);
034c6ed7 2079
595ed347 2080 unit_load(u);
c1e1601e 2081 n++;
60918275
LP
2082 }
2083
223dabab 2084 m->dispatching_load_queue = false;
19496554
MS
2085
2086 /* Dispatch the units waiting for their target dependencies to be added now, as all targets that we know about
2087 * should be loaded and have aliases resolved */
2088 (void) manager_dispatch_target_deps_queue(m);
2089
c1e1601e 2090 return n;
60918275
LP
2091}
2092
81be2388 2093bool manager_unit_cache_should_retry_load(Unit *u) {
cda66772
LB
2094 assert(u);
2095
81be2388
ZJS
2096 /* Automatic reloading from disk only applies to units which were not found sometime in the past, and
2097 * the not-found stub is kept pinned in the unit graph by dependencies. For units that were
2098 * previously loaded, we don't do automatic reloading, and daemon-reload is necessary to update. */
cda66772
LB
2099 if (u->load_state != UNIT_NOT_FOUND)
2100 return false;
2101
81be2388
ZJS
2102 /* The cache has been updated since the last time we tried to load the unit. There might be new
2103 * fragment paths to read. */
c2911d48 2104 if (u->manager->unit_cache_timestamp_hash != u->fragment_not_found_timestamp_hash)
cda66772 2105 return true;
d904afc7 2106
81be2388 2107 /* The cache needs to be updated because there are modifications on disk. */
c2911d48 2108 return !lookup_paths_timestamp_hash_same(&u->manager->lookup_paths, u->manager->unit_cache_timestamp_hash, NULL);
d904afc7
LB
2109}
2110
c2756a68
LP
2111int manager_load_unit_prepare(
2112 Manager *m,
2113 const char *name,
2114 const char *path,
718db961 2115 sd_bus_error *e,
c2756a68
LP
2116 Unit **_ret) {
2117
dc409696 2118 _cleanup_(unit_freep) Unit *cleanup_ret = NULL;
87f0e418 2119 Unit *ret;
7d17cfbc 2120 UnitType t;
60918275
LP
2121 int r;
2122
2123 assert(m);
7a6a095a 2124 assert(_ret);
60918275 2125
526e3cbb 2126 /* This will prepare the unit for loading, but not actually load anything from disk. */
0301abf4 2127
526e3cbb 2128 if (path && !path_is_absolute(path))
718db961 2129 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Path %s is not absolute.", path);
9e2f7c11 2130
08f46856
BR
2131 if (!name) {
2132 /* 'name' and 'path' must not both be null. Check here 'path' using assert_se() to
2133 * workaround a bug in gcc that generates a -Wnonnull warning when calling basename(),
2134 * but this cannot be possible in any code path (See #6119). */
2135 assert_se(path);
2b6bf07d 2136 name = basename(path);
08f46856 2137 }
9e2f7c11 2138
7d17cfbc
MS
2139 t = unit_name_to_type(name);
2140
5d512d54
LN
2141 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
2142 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE))
2143 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is missing the instance name.", name);
2144
718db961 2145 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS, "Unit name %s is not valid.", name);
5d512d54 2146 }
60918275 2147
7d17cfbc
MS
2148 ret = manager_get_unit(m, name);
2149 if (ret) {
d904afc7
LB
2150 /* The time-based cache allows to start new units without daemon-reload,
2151 * but if they are already referenced (because of dependencies or ordering)
2152 * then we have to force a load of the fragment. As an optimization, check
2153 * first if anything in the usual paths was modified since the last time
7233e91a
LB
2154 * the cache was loaded. Also check if the last time an attempt to load the
2155 * unit was made was before the most recent cache refresh, so that we know
81be2388 2156 * we need to try again — even if the cache is current, it might have been
7233e91a
LB
2157 * updated in a different context before we had a chance to retry loading
2158 * this particular unit. */
81be2388 2159 if (manager_unit_cache_should_retry_load(ret))
d904afc7
LB
2160 ret->load_state = UNIT_STUB;
2161 else {
2162 *_ret = ret;
2163 return 1;
2164 }
2165 } else {
2166 ret = cleanup_ret = unit_new(m, unit_vtable[t]->object_size);
2167 if (!ret)
2168 return -ENOMEM;
034c6ed7 2169 }
60918275 2170
7d17cfbc 2171 if (path) {
d904afc7
LB
2172 r = free_and_strdup(&ret->fragment_path, path);
2173 if (r < 0)
2174 return r;
7d17cfbc 2175 }
0301abf4 2176
1058cbf2 2177 r = unit_add_name(ret, name);
dc409696 2178 if (r < 0)
1ffba6fe 2179 return r;
60918275 2180
87f0e418 2181 unit_add_to_load_queue(ret);
c1e1601e 2182 unit_add_to_dbus_queue(ret);
949061f0 2183 unit_add_to_gc_queue(ret);
c1e1601e 2184
7a6a095a 2185 *_ret = ret;
dc409696 2186 cleanup_ret = NULL;
db06e3b6
LP
2187
2188 return 0;
2189}
2190
c2756a68
LP
2191int manager_load_unit(
2192 Manager *m,
2193 const char *name,
2194 const char *path,
718db961 2195 sd_bus_error *e,
c2756a68
LP
2196 Unit **_ret) {
2197
db06e3b6
LP
2198 int r;
2199
2200 assert(m);
7a6a095a 2201 assert(_ret);
db06e3b6
LP
2202
2203 /* This will load the service information files, but not actually
2204 * start any services or anything. */
2205
c3090674
LP
2206 r = manager_load_unit_prepare(m, name, path, e, _ret);
2207 if (r != 0)
db06e3b6
LP
2208 return r;
2209
f50e0a01 2210 manager_dispatch_load_queue(m);
60918275 2211
7a6a095a 2212 *_ret = unit_follow_merge(*_ret);
4109ede7
ZJS
2213 return 0;
2214}
2215
2216int manager_load_startable_unit_or_warn(
2217 Manager *m,
2218 const char *name,
2219 const char *path,
2220 Unit **ret) {
2221
2222 /* Load a unit, make sure it loaded fully and is not masked. */
2223
2224 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2225 Unit *unit;
2226 int r;
2227
2228 r = manager_load_unit(m, name, path, &error, &unit);
2229 if (r < 0)
2230 return log_error_errno(r, "Failed to load %s %s: %s",
8ace1db7 2231 name ? "unit" : "unit file", name ?: path,
4109ede7 2232 bus_error_message(&error, r));
8ace1db7
LP
2233
2234 r = bus_unit_validate_load_state(unit, &error);
2235 if (r < 0)
2236 return log_error_errno(r, "%s", bus_error_message(&error, r));
9e2f7c11 2237
4109ede7 2238 *ret = unit;
60918275
LP
2239 return 0;
2240}
a66d02c3 2241
7fad411c
LP
2242void manager_clear_jobs(Manager *m) {
2243 Job *j;
2244
2245 assert(m);
2246
7fad411c 2247 while ((j = hashmap_first(m->jobs)))
5273510e 2248 /* No need to recurse. We're cancelling all jobs. */
833f92ad 2249 job_finish_and_invalidate(j, JOB_CANCELED, false, false);
7fad411c 2250}
83c60c9f 2251
f75f613d
FB
2252void manager_unwatch_pid(Manager *m, pid_t pid) {
2253 assert(m);
2254
2255 /* First let's drop the unit keyed as "pid". */
2256 (void) hashmap_remove(m->watch_pids, PID_TO_PTR(pid));
2257
2258 /* Then, let's also drop the array keyed by -pid. */
2259 free(hashmap_remove(m->watch_pids, PID_TO_PTR(-pid)));
2260}
2261
752b5905
LP
2262static int manager_dispatch_run_queue(sd_event_source *source, void *userdata) {
2263 Manager *m = userdata;
83c60c9f 2264 Job *j;
034c6ed7 2265
752b5905
LP
2266 assert(source);
2267 assert(m);
9152c765 2268
da8e1782 2269 while ((j = prioq_peek(m->run_queue))) {
ac1135be 2270 assert(j->installed);
034c6ed7
LP
2271 assert(j->in_run_queue);
2272
6e64994d 2273 (void) job_run_and_invalidate(j);
9152c765 2274 }
034c6ed7 2275
a0b64226 2276 if (m->n_running_jobs > 0)
03b717a3
MS
2277 manager_watch_jobs_in_progress(m);
2278
31a7eb86
ZJS
2279 if (m->n_on_console > 0)
2280 manager_watch_idle_pipe(m);
2281
752b5905 2282 return 1;
c1e1601e
LP
2283}
2284
b0c4b282
LP
2285void manager_trigger_run_queue(Manager *m) {
2286 int r;
2287
2288 assert(m);
2289
2290 r = sd_event_source_set_enabled(
2291 m->run_queue_event_source,
2292 prioq_isempty(m->run_queue) ? SD_EVENT_OFF : SD_EVENT_ONESHOT);
2293 if (r < 0)
2294 log_warning_errno(r, "Failed to enable job run queue event source, ignoring: %m");
2295}
2296
9588bc32 2297static unsigned manager_dispatch_dbus_queue(Manager *m) {
e0a08581 2298 unsigned n = 0, budget;
595ed347 2299 Unit *u;
e0a08581 2300 Job *j;
c1e1601e
LP
2301
2302 assert(m);
2303
b8d381c4
LP
2304 /* When we are reloading, let's not wait with generating signals, since we need to exit the manager as quickly
2305 * as we can. There's no point in throttling generation of signals in that case. */
2306 if (MANAGER_IS_RELOADING(m) || m->send_reloading_done || m->pending_reload_message)
f5fbe71d 2307 budget = UINT_MAX; /* infinite budget in this case */
b8d381c4
LP
2308 else {
2309 /* Anything to do at all? */
2310 if (!m->dbus_unit_queue && !m->dbus_job_queue)
2311 return 0;
2312
2313 /* Do we have overly many messages queued at the moment? If so, let's not enqueue more on top, let's
2314 * sit this cycle out, and process things in a later cycle when the queues got a bit emptier. */
2315 if (manager_bus_n_queued_write(m) > MANAGER_BUS_BUSY_THRESHOLD)
2316 return 0;
2317
2318 /* Only process a certain number of units/jobs per event loop iteration. Even if the bus queue wasn't
2319 * overly full before this call we shouldn't increase it in size too wildly in one step, and we
2320 * shouldn't monopolize CPU time with generating these messages. Note the difference in counting of
2321 * this "budget" and the "threshold" above: the "budget" is decreased only once per generated message,
5238e957
BB
2322 * regardless how many buses/direct connections it is enqueued on, while the "threshold" is applied to
2323 * each queued instance of bus message, i.e. if the same message is enqueued to five buses/direct
b8d381c4
LP
2324 * connections it will be counted five times. This difference in counting ("references"
2325 * vs. "instances") is primarily a result of the fact that it's easier to implement it this way,
2326 * however it also reflects the thinking that the "threshold" should put a limit on used queue memory,
2327 * i.e. space, while the "budget" should put a limit on time. Also note that the "threshold" is
2328 * currently chosen much higher than the "budget". */
2329 budget = MANAGER_BUS_MESSAGE_BUDGET;
2330 }
e0a08581 2331
b8d381c4 2332 while (budget != 0 && (u = m->dbus_unit_queue)) {
e0a08581 2333
595ed347 2334 assert(u->in_dbus_queue);
c1e1601e 2335
595ed347 2336 bus_unit_send_change_signal(u);
b8d381c4
LP
2337 n++;
2338
f5fbe71d 2339 if (budget != UINT_MAX)
b8d381c4 2340 budget--;
c1e1601e
LP
2341 }
2342
b8d381c4 2343 while (budget != 0 && (j = m->dbus_job_queue)) {
c1e1601e
LP
2344 assert(j->in_dbus_queue);
2345
2346 bus_job_send_change_signal(j);
b8d381c4
LP
2347 n++;
2348
f5fbe71d 2349 if (budget != UINT_MAX)
b8d381c4 2350 budget--;
c1e1601e
LP
2351 }
2352
b8d381c4 2353 if (m->send_reloading_done) {
71445ae7 2354 m->send_reloading_done = false;
718db961 2355 bus_manager_send_reloading(m, false);
b8d381c4 2356 n++;
71445ae7
LP
2357 }
2358
b8d381c4 2359 if (m->pending_reload_message) {
209de525 2360 bus_send_pending_reload_message(m);
e0a08581
LP
2361 n++;
2362 }
718db961 2363
c1e1601e 2364 return n;
9152c765
LP
2365}
2366
d8fdc620
LP
2367static int manager_dispatch_cgroups_agent_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2368 Manager *m = userdata;
60473f0c 2369 char buf[PATH_MAX];
d8fdc620
LP
2370 ssize_t n;
2371
2372 n = recv(fd, buf, sizeof(buf), 0);
2373 if (n < 0)
2374 return log_error_errno(errno, "Failed to read cgroups agent message: %m");
2375 if (n == 0) {
2376 log_error("Got zero-length cgroups agent message, ignoring.");
2377 return 0;
2378 }
2379 if ((size_t) n >= sizeof(buf)) {
2380 log_error("Got overly long cgroups agent message, ignoring.");
2381 return 0;
2382 }
2383
2384 if (memchr(buf, 0, n)) {
2385 log_error("Got cgroups agent message with embedded NUL byte, ignoring.");
2386 return 0;
2387 }
2388 buf[n] = 0;
2389
2390 manager_notify_cgroup_empty(m, buf);
d5f15326 2391 (void) bus_forward_agent_released(m, buf);
d8fdc620
LP
2392
2393 return 0;
2394}
2395
5151b4cc 2396static bool manager_process_barrier_fd(char * const *tags, FDSet *fds) {
4f07ddfa
KKD
2397
2398 /* nothing else must be sent when using BARRIER=1 */
5151b4cc
BR
2399 if (strv_contains(tags, "BARRIER=1")) {
2400 if (strv_length(tags) == 1) {
2401 if (fdset_size(fds) != 1)
2402 log_warning("Got incorrect number of fds with BARRIER=1, closing them.");
2403 } else
2404 log_warning("Extra notification messages sent with BARRIER=1, ignoring everything.");
2405
2406 /* Drop the message if BARRIER=1 was found */
4f07ddfa 2407 return true;
5151b4cc 2408 }
4f07ddfa
KKD
2409
2410 return false;
2411}
2412
db256aab
LP
2413static void manager_invoke_notify_message(
2414 Manager *m,
2415 Unit *u,
2416 const struct ucred *ucred,
5151b4cc 2417 char * const *tags,
db256aab
LP
2418 FDSet *fds) {
2419
5ba6985b
LP
2420 assert(m);
2421 assert(u);
db256aab 2422 assert(ucred);
5151b4cc 2423 assert(tags);
5ba6985b 2424
62a76913 2425 if (u->notifygen == m->notifygen) /* Already invoked on this same unit in this same iteration? */
5ba6985b 2426 return;
62a76913
LP
2427 u->notifygen = m->notifygen;
2428
5151b4cc 2429 if (UNIT_VTABLE(u)->notify_message)
db256aab 2430 UNIT_VTABLE(u)->notify_message(u, ucred, tags, fds);
62a76913 2431
5151b4cc
BR
2432 else if (DEBUG_LOGGING) {
2433 _cleanup_free_ char *buf = NULL, *x = NULL, *y = NULL;
a86b7675 2434
5151b4cc
BR
2435 buf = strv_join(tags, ", ");
2436 if (buf)
2437 x = ellipsize(buf, 20, 90);
a86b7675 2438 if (x)
da5fb861
LP
2439 y = cescape(x);
2440
a86b7675
ZJS
2441 log_unit_debug(u, "Got notification message \"%s\", ignoring.", strnull(y));
2442 }
5ba6985b
LP
2443}
2444
718db961 2445static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
3d0b8a55 2446
b215b0ed 2447 _cleanup_fdset_free_ FDSet *fds = NULL;
718db961 2448 Manager *m = userdata;
b215b0ed
DH
2449 char buf[NOTIFY_BUFFER_MAX+1];
2450 struct iovec iovec = {
2451 .iov_base = buf,
2452 .iov_len = sizeof(buf)-1,
2453 };
fb29cdbe
LP
2454 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred)) +
2455 CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)) control;
b215b0ed
DH
2456 struct msghdr msghdr = {
2457 .msg_iov = &iovec,
2458 .msg_iovlen = 1,
2459 .msg_control = &control,
2460 .msg_controllen = sizeof(control),
2461 };
2462
2463 struct cmsghdr *cmsg;
2464 struct ucred *ucred = NULL;
62a76913 2465 _cleanup_free_ Unit **array_copy = NULL;
5151b4cc 2466 _cleanup_strv_free_ char **tags = NULL;
62a76913 2467 Unit *u1, *u2, **array;
b215b0ed 2468 int r, *fd_array = NULL;
da6053d0 2469 size_t n_fds = 0;
62a76913 2470 bool found = false;
8c47c732
LP
2471 ssize_t n;
2472
2473 assert(m);
718db961
LP
2474 assert(m->notify_fd == fd);
2475
2476 if (revents != EPOLLIN) {
2477 log_warning("Got unexpected poll event for notify fd.");
2478 return 0;
2479 }
8c47c732 2480
3691bcf3 2481 n = recvmsg_safe(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC|MSG_TRUNC);
8add30a0
YW
2482 if (n < 0) {
2483 if (ERRNO_IS_TRANSIENT(n))
2484 return 0; /* Spurious wakeup, try again */
2485 if (n == -EXFULL) {
2486 log_warning("Got message with truncated control data (too many fds sent?), ignoring.");
2487 return 0;
2488 }
3691bcf3
LP
2489 /* If this is any other, real error, then let's stop processing this socket. This of course
2490 * means we won't take notification messages anymore, but that's still better than busy
2491 * looping around this: being woken up over and over again but being unable to actually read
2492 * the message off the socket. */
2493 return log_error_errno(n, "Failed to receive notification message: %m");
8add30a0 2494 }
a354329f 2495
b215b0ed
DH
2496 CMSG_FOREACH(cmsg, &msghdr) {
2497 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
a354329f 2498
3691bcf3 2499 assert(!fd_array);
b215b0ed
DH
2500 fd_array = (int*) CMSG_DATA(cmsg);
2501 n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
a354329f 2502
b215b0ed
DH
2503 } else if (cmsg->cmsg_level == SOL_SOCKET &&
2504 cmsg->cmsg_type == SCM_CREDENTIALS &&
2505 cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {
a354329f 2506
3691bcf3 2507 assert(!ucred);
b215b0ed 2508 ucred = (struct ucred*) CMSG_DATA(cmsg);
a354329f 2509 }
b215b0ed 2510 }
a354329f 2511
b215b0ed
DH
2512 if (n_fds > 0) {
2513 assert(fd_array);
a354329f 2514
b215b0ed
DH
2515 r = fdset_new_array(&fds, fd_array, n_fds);
2516 if (r < 0) {
2517 close_many(fd_array, n_fds);
9987750e
FB
2518 log_oom();
2519 return 0;
a354329f 2520 }
b215b0ed 2521 }
8c47c732 2522
15e23e8c 2523 if (!ucred || !pid_is_valid(ucred->pid)) {
b215b0ed
DH
2524 log_warning("Received notify message without valid credentials. Ignoring.");
2525 return 0;
2526 }
8c47c732 2527
045a3d59 2528 if ((size_t) n >= sizeof(buf) || (msghdr.msg_flags & MSG_TRUNC)) {
b215b0ed
DH
2529 log_warning("Received notify message exceeded maximum size. Ignoring.");
2530 return 0;
2531 }
8c47c732 2532
875ca88d
LP
2533 /* As extra safety check, let's make sure the string we get doesn't contain embedded NUL bytes. We permit one
2534 * trailing NUL byte in the message, but don't expect it. */
2535 if (n > 1 && memchr(buf, 0, n-1)) {
2536 log_warning("Received notify message with embedded NUL bytes. Ignoring.");
2537 return 0;
2538 }
2539
5151b4cc 2540 /* Make sure it's NUL-terminated, then parse it to obtain the tags list */
b215b0ed 2541 buf[n] = 0;
5151b4cc
BR
2542 tags = strv_split_newlines(buf);
2543 if (!tags) {
2544 log_oom();
2545 return 0;
2546 }
8c47c732 2547
4f07ddfa 2548 /* possibly a barrier fd, let's see */
5151b4cc 2549 if (manager_process_barrier_fd(tags, fds))
4f07ddfa
KKD
2550 return 0;
2551
62a76913
LP
2552 /* Increase the generation counter used for filtering out duplicate unit invocations. */
2553 m->notifygen++;
2554
2555 /* Notify every unit that might be interested, which might be multiple. */
b215b0ed 2556 u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid);
62a76913
LP
2557 u2 = hashmap_get(m->watch_pids, PID_TO_PTR(ucred->pid));
2558 array = hashmap_get(m->watch_pids, PID_TO_PTR(-ucred->pid));
2559 if (array) {
2560 size_t k = 0;
5ba6985b 2561
62a76913
LP
2562 while (array[k])
2563 k++;
5ba6985b 2564
62a76913
LP
2565 array_copy = newdup(Unit*, array, k+1);
2566 if (!array_copy)
2567 log_oom();
2568 }
2569 /* And now invoke the per-unit callbacks. Note that manager_invoke_notify_message() will handle duplicate units
2570 * make sure we only invoke each unit's handler once. */
2571 if (u1) {
5151b4cc 2572 manager_invoke_notify_message(m, u1, ucred, tags, fds);
62a76913
LP
2573 found = true;
2574 }
2575 if (u2) {
5151b4cc 2576 manager_invoke_notify_message(m, u2, ucred, tags, fds);
62a76913
LP
2577 found = true;
2578 }
2579 if (array_copy)
2580 for (size_t i = 0; array_copy[i]; i++) {
5151b4cc 2581 manager_invoke_notify_message(m, array_copy[i], ucred, tags, fds);
62a76913
LP
2582 found = true;
2583 }
8c47c732 2584
62a76913
LP
2585 if (!found)
2586 log_warning("Cannot find unit for notify message of PID "PID_FMT", ignoring.", ucred->pid);
a354329f 2587
b215b0ed 2588 if (fdset_size(fds) > 0)
5fd2c135 2589 log_warning("Got extra auxiliary fds with notification message, closing them.");
8c47c732
LP
2590
2591 return 0;
2592}
2593
62a76913
LP
2594static void manager_invoke_sigchld_event(
2595 Manager *m,
2596 Unit *u,
2597 const siginfo_t *si) {
36f20ae3 2598
5ba6985b
LP
2599 assert(m);
2600 assert(u);
2601 assert(si);
2602
62a76913
LP
2603 /* Already invoked the handler of this unit in this iteration? Then don't process this again */
2604 if (u->sigchldgen == m->sigchldgen)
2605 return;
2606 u->sigchldgen = m->sigchldgen;
5ba6985b 2607
62a76913 2608 log_unit_debug(u, "Child "PID_FMT" belongs to %s.", si->si_pid, u->id);
5ba6985b 2609 unit_unwatch_pid(u, si->si_pid);
e57051f5 2610
62a76913
LP
2611 if (UNIT_VTABLE(u)->sigchld_event)
2612 UNIT_VTABLE(u)->sigchld_event(u, si->si_pid, si->si_code, si->si_status);
5ba6985b
LP
2613}
2614
575b300b
LP
2615static int manager_dispatch_sigchld(sd_event_source *source, void *userdata) {
2616 Manager *m = userdata;
2617 siginfo_t si = {};
2618 int r;
2619
2620 assert(source);
9152c765
LP
2621 assert(m);
2622
0a51b45c 2623 /* First we call waitid() for a PID and do not reap the zombie. That way we can still access /proc/$PID for it
575b300b 2624 * while it is a zombie. */
9152c765 2625
575b300b 2626 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
acbb0225 2627
8afabc50
AJ
2628 if (errno != ECHILD)
2629 log_error_errno(errno, "Failed to peek for child with waitid(), ignoring: %m");
acbb0225 2630
8afabc50 2631 goto turn_off;
575b300b 2632 }
4112df16 2633
575b300b
LP
2634 if (si.si_pid <= 0)
2635 goto turn_off;
2636
2637 if (IN_SET(si.si_code, CLD_EXITED, CLD_KILLED, CLD_DUMPED)) {
62a76913 2638 _cleanup_free_ Unit **array_copy = NULL;
575b300b 2639 _cleanup_free_ char *name = NULL;
62a76913 2640 Unit *u1, *u2, **array;
575b300b
LP
2641
2642 (void) get_process_comm(si.si_pid, &name);
2643
2644 log_debug("Child "PID_FMT" (%s) died (code=%s, status=%i/%s)",
2645 si.si_pid, strna(name),
2646 sigchld_code_to_string(si.si_code),
2647 si.si_status,
2648 strna(si.si_code == CLD_EXITED
2649 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2650 : signal_to_string(si.si_status)));
2651
62a76913
LP
2652 /* Increase the generation counter used for filtering out duplicate unit invocations */
2653 m->sigchldgen++;
2654
2655 /* And now figure out the unit this belongs to, it might be multiple... */
575b300b 2656 u1 = manager_get_unit_by_pid_cgroup(m, si.si_pid);
62a76913
LP
2657 u2 = hashmap_get(m->watch_pids, PID_TO_PTR(si.si_pid));
2658 array = hashmap_get(m->watch_pids, PID_TO_PTR(-si.si_pid));
2659 if (array) {
2660 size_t n = 0;
2661
5238e957 2662 /* Count how many entries the array has */
62a76913
LP
2663 while (array[n])
2664 n++;
2665
2666 /* Make a copy of the array so that we don't trip up on the array changing beneath us */
2667 array_copy = newdup(Unit*, array, n+1);
2668 if (!array_copy)
2669 log_oom();
2670 }
2671
2672 /* Finally, execute them all. Note that u1, u2 and the array might contain duplicates, but
2673 * that's fine, manager_invoke_sigchld_event() will ensure we only invoke the handlers once for
2674 * each iteration. */
2ba6ae6b
ZJS
2675 if (u1) {
2676 /* We check for oom condition, in case we got SIGCHLD before the oom notification.
2677 * We only do this for the cgroup the PID belonged to. */
2678 (void) unit_check_oom(u1);
2679
288bd406 2680 /* We check if systemd-oomd performed a kill so that we log and notify appropriately */
fe8d22fb
AZ
2681 (void) unit_check_oomd_kill(u1);
2682
62a76913 2683 manager_invoke_sigchld_event(m, u1, &si);
2ba6ae6b 2684 }
62a76913
LP
2685 if (u2)
2686 manager_invoke_sigchld_event(m, u2, &si);
2687 if (array_copy)
2688 for (size_t i = 0; array_copy[i]; i++)
2689 manager_invoke_sigchld_event(m, array_copy[i], &si);
575b300b 2690 }
9152c765 2691
575b300b
LP
2692 /* And now, we actually reap the zombie. */
2693 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
2694 log_error_errno(errno, "Failed to dequeue child, ignoring: %m");
2695 return 0;
2696 }
9152c765 2697
575b300b 2698 return 0;
8c47c732 2699
575b300b
LP
2700turn_off:
2701 /* All children processed for now, turn off event source */
4112df16 2702
575b300b
LP
2703 r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_OFF);
2704 if (r < 0)
2705 return log_error_errno(r, "Failed to disable SIGCHLD event source: %m");
9152c765
LP
2706
2707 return 0;
2708}
2709
5f968096
ZJS
2710static void manager_start_special(Manager *m, const char *name, JobMode mode) {
2711 Job *job;
398ef8ba 2712
5f968096
ZJS
2713 if (manager_add_job_by_name_and_warn(m, JOB_START, name, mode, NULL, &job) < 0)
2714 return;
1e001f52 2715
5f968096
ZJS
2716 const char *s = unit_status_string(job->unit, NULL);
2717
2718 log_info("Activating special unit %s...", s);
3889fc6f
ZJS
2719
2720 sd_notifyf(false,
2721 "STATUS=Activating special unit %s...", s);
2722 m->status_ready = false;
28247076
LP
2723}
2724
24dd31c1
LN
2725static void manager_handle_ctrl_alt_del(Manager *m) {
2726 /* If the user presses C-A-D more than
2727 * 7 times within 2s, we reboot/shutdown immediately,
2728 * unless it was disabled in system.conf */
2729
7994ac1d 2730 if (ratelimit_below(&m->ctrl_alt_del_ratelimit) || m->cad_burst_action == EMERGENCY_ACTION_NONE)
5f968096 2731 manager_start_special(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
ae8c7939 2732 else
7af67e9a 2733 emergency_action(m, m->cad_burst_action, EMERGENCY_ACTION_WARN, NULL, -1,
ae8c7939 2734 "Ctrl-Alt-Del was pressed more than 7 times within 2s");
24dd31c1
LN
2735}
2736
718db961
LP
2737static int manager_dispatch_signal_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2738 Manager *m = userdata;
9152c765
LP
2739 ssize_t n;
2740 struct signalfd_siginfo sfsi;
dacd6cee 2741 int r;
9152c765
LP
2742
2743 assert(m);
718db961
LP
2744 assert(m->signal_fd == fd);
2745
2746 if (revents != EPOLLIN) {
2747 log_warning("Got unexpected events from signal file descriptor.");
2748 return 0;
2749 }
9152c765 2750
575b300b 2751 n = read(m->signal_fd, &sfsi, sizeof(sfsi));
8add30a0
YW
2752 if (n < 0) {
2753 if (ERRNO_IS_TRANSIENT(errno))
575b300b 2754 return 0;
9152c765 2755
575b300b
LP
2756 /* We return an error here, which will kill this handler,
2757 * to avoid a busy loop on read error. */
2758 return log_error_errno(errno, "Reading from signal fd failed: %m");
2759 }
8add30a0
YW
2760 if (n != sizeof(sfsi)) {
2761 log_warning("Truncated read from signal fd (%zu bytes), ignoring!", n);
2762 return 0;
2763 }
9152c765 2764
575b300b
LP
2765 log_received_signal(sfsi.ssi_signo == SIGCHLD ||
2766 (sfsi.ssi_signo == SIGTERM && MANAGER_IS_USER(m))
2767 ? LOG_DEBUG : LOG_INFO,
2768 &sfsi);
1e001f52 2769
575b300b 2770 switch (sfsi.ssi_signo) {
b9cd2ec1 2771
575b300b
LP
2772 case SIGCHLD:
2773 r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
2774 if (r < 0)
8afabc50 2775 log_warning_errno(r, "Failed to enable SIGCHLD event source, ignoring: %m");
b9cd2ec1 2776
575b300b 2777 break;
84e9af1e 2778
575b300b
LP
2779 case SIGTERM:
2780 if (MANAGER_IS_SYSTEM(m)) {
ba0c7754 2781 /* This is for compatibility with the original sysvinit */
c52b19d6
LP
2782 if (verify_run_space_and_log("Refusing to reexecute") < 0)
2783 break;
2784
2785 m->objective = MANAGER_REEXECUTE;
a1b256b0 2786 break;
575b300b 2787 }
84e9af1e 2788
575b300b
LP
2789 _fallthrough_;
2790 case SIGINT:
2791 if (MANAGER_IS_SYSTEM(m))
2792 manager_handle_ctrl_alt_del(m);
2793 else
5f968096 2794 manager_start_special(m, SPECIAL_EXIT_TARGET, JOB_REPLACE_IRREVERSIBLY);
575b300b 2795 break;
84e9af1e 2796
575b300b 2797 case SIGWINCH:
ba0c7754 2798 /* This is a nop on non-init */
575b300b 2799 if (MANAGER_IS_SYSTEM(m))
5f968096 2800 manager_start_special(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
84e9af1e 2801
575b300b 2802 break;
84e9af1e 2803
575b300b 2804 case SIGPWR:
ba0c7754 2805 /* This is a nop on non-init */
575b300b 2806 if (MANAGER_IS_SYSTEM(m))
5f968096 2807 manager_start_special(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
6632c602 2808
575b300b 2809 break;
57ee42ce 2810
8559b3b7 2811 case SIGUSR1:
8559b3b7 2812 if (manager_dbus_is_running(m, false)) {
575b300b 2813 log_info("Trying to reconnect to bus...");
575b300b 2814
8559b3b7
LP
2815 (void) bus_init_api(m);
2816
2817 if (MANAGER_IS_SYSTEM(m))
2818 (void) bus_init_system(m);
5f968096
ZJS
2819 } else
2820 manager_start_special(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
57ee42ce 2821
575b300b 2822 break;
575b300b
LP
2823
2824 case SIGUSR2: {
2825 _cleanup_free_ char *dump = NULL;
2826
2827 r = manager_get_dump_string(m, &dump);
2828 if (r < 0) {
2829 log_warning_errno(errno, "Failed to acquire manager dump: %m");
57ee42ce
LP
2830 break;
2831 }
2832
575b300b
LP
2833 log_dump(LOG_INFO, dump);
2834 break;
2835 }
2149e37c 2836
575b300b 2837 case SIGHUP:
c52b19d6
LP
2838 if (verify_run_space_and_log("Refusing to reload") < 0)
2839 break;
2840
2841 m->objective = MANAGER_RELOAD;
575b300b
LP
2842 break;
2843
2844 default: {
2845
2846 /* Starting SIGRTMIN+0 */
2847 static const struct {
2848 const char *target;
2849 JobMode mode;
2850 } target_table[] = {
2851 [0] = { SPECIAL_DEFAULT_TARGET, JOB_ISOLATE },
2852 [1] = { SPECIAL_RESCUE_TARGET, JOB_ISOLATE },
2853 [2] = { SPECIAL_EMERGENCY_TARGET, JOB_ISOLATE },
2854 [3] = { SPECIAL_HALT_TARGET, JOB_REPLACE_IRREVERSIBLY },
2855 [4] = { SPECIAL_POWEROFF_TARGET, JOB_REPLACE_IRREVERSIBLY },
2856 [5] = { SPECIAL_REBOOT_TARGET, JOB_REPLACE_IRREVERSIBLY },
2857 [6] = { SPECIAL_KEXEC_TARGET, JOB_REPLACE_IRREVERSIBLY },
2858 };
2859
2860 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
af41e508 2861 static const ManagerObjective objective_table[] = {
575b300b
LP
2862 [0] = MANAGER_HALT,
2863 [1] = MANAGER_POWEROFF,
2864 [2] = MANAGER_REBOOT,
2865 [3] = MANAGER_KEXEC,
2866 };
b2cdc666 2867
575b300b
LP
2868 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2869 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2870 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
5f968096 2871 manager_start_special(m, target_table[idx].target, target_table[idx].mode);
1005d14f 2872 break;
2149e37c 2873 }
1005d14f 2874
575b300b 2875 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
af41e508
LP
2876 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(objective_table)) {
2877 m->objective = objective_table[sfsi.ssi_signo - SIGRTMIN - 13];
575b300b
LP
2878 break;
2879 }
2880
2881 switch (sfsi.ssi_signo - SIGRTMIN) {
2882
2883 case 20:
43bba15a 2884 manager_override_show_status(m, SHOW_STATUS_YES, "signal");
a16e1123
LP
2885 break;
2886
575b300b 2887 case 21:
43bba15a 2888 manager_override_show_status(m, SHOW_STATUS_NO, "signal");
575b300b 2889 break;
7d793605 2890
575b300b 2891 case 22:
a6ecbf83 2892 manager_override_log_level(m, LOG_DEBUG);
575b300b
LP
2893 break;
2894
2895 case 23:
a6ecbf83 2896 manager_restore_original_log_level(m);
575b300b 2897 break;
0003d1ab 2898
575b300b
LP
2899 case 24:
2900 if (MANAGER_IS_USER(m)) {
af41e508 2901 m->objective = MANAGER_EXIT;
575b300b 2902 return 0;
0658666b 2903 }
9152c765 2904
575b300b
LP
2905 /* This is a nop on init */
2906 break;
2907
463aef23
FB
2908 case 25:
2909 m->objective = MANAGER_REEXECUTE;
2910 break;
2911
575b300b
LP
2912 case 26:
2913 case 29: /* compatibility: used to be mapped to LOG_TARGET_SYSLOG_OR_KMSG */
bda7d78b 2914 manager_restore_original_log_target(m);
575b300b
LP
2915 break;
2916
2917 case 27:
bda7d78b 2918 manager_override_log_target(m, LOG_TARGET_CONSOLE);
575b300b
LP
2919 break;
2920
2921 case 28:
bda7d78b 2922 manager_override_log_target(m, LOG_TARGET_KMSG);
575b300b
LP
2923 break;
2924
2925 default:
2926 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
2927 }
2928 }}
034c6ed7
LP
2929
2930 return 0;
2931}
2932
718db961
LP
2933static int manager_dispatch_time_change_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2934 Manager *m = userdata;
718db961 2935 Unit *u;
034c6ed7
LP
2936
2937 assert(m);
034c6ed7 2938
a80c1575 2939 log_struct(LOG_DEBUG,
2b044526 2940 "MESSAGE_ID=" SD_MESSAGE_TIME_CHANGE_STR,
a1230ff9 2941 LOG_MESSAGE("Time has been changed"));
034c6ed7 2942
718db961 2943 /* Restart the watch */
7feedd18 2944 (void) manager_setup_time_change(m);
4e434314 2945
90e74a66 2946 HASHMAP_FOREACH(u, m->units)
718db961
LP
2947 if (UNIT_VTABLE(u)->time_change)
2948 UNIT_VTABLE(u)->time_change(u);
ea430986 2949
718db961
LP
2950 return 0;
2951}
ea430986 2952
bbf5fd8e
LP
2953static int manager_dispatch_timezone_change(
2954 sd_event_source *source,
2955 const struct inotify_event *e,
2956 void *userdata) {
2957
2958 Manager *m = userdata;
2959 int changed;
bbf5fd8e
LP
2960 Unit *u;
2961
2962 assert(m);
2963
2964 log_debug("inotify event for /etc/localtime");
2965
2966 changed = manager_read_timezone_stat(m);
f20db199 2967 if (changed <= 0)
bbf5fd8e 2968 return changed;
bbf5fd8e
LP
2969
2970 /* Something changed, restart the watch, to ensure we watch the new /etc/localtime if it changed */
2971 (void) manager_setup_timezone_change(m);
2972
2973 /* Read the new timezone */
2974 tzset();
2975
2976 log_debug("Timezone has been changed (now: %s).", tzname[daylight]);
2977
90e74a66 2978 HASHMAP_FOREACH(u, m->units)
bbf5fd8e
LP
2979 if (UNIT_VTABLE(u)->timezone_change)
2980 UNIT_VTABLE(u)->timezone_change(u);
2981
2982 return 0;
2983}
2984
718db961
LP
2985static int manager_dispatch_idle_pipe_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2986 Manager *m = userdata;
8742514c 2987
718db961
LP
2988 assert(m);
2989 assert(m->idle_pipe[2] == fd);
8742514c 2990
5a69973f
LP
2991 /* There's at least one Type=idle child that just gave up on us waiting for the boot process to complete. Let's
2992 * now turn off any further console output if there's at least one service that needs console access, so that
2993 * from now on our own output should not spill into that service's output anymore. After all, we support
2994 * Type=idle only to beautify console output and it generally is set on services that want to own the console
2995 * exclusively without our interference. */
718db961 2996 m->no_console_output = m->n_on_console > 0;
03b717a3 2997
5a69973f
LP
2998 /* Acknowledge the child's request, and let all all other children know too that they shouldn't wait any longer
2999 * by closing the pipes towards them, which is what they are waiting for. */
718db961 3000 manager_close_idle_pipe(m);
03b717a3 3001
718db961
LP
3002 return 0;
3003}
31a7eb86 3004
718db961
LP
3005static int manager_dispatch_jobs_in_progress(sd_event_source *source, usec_t usec, void *userdata) {
3006 Manager *m = userdata;
fd08a840 3007 int r;
31a7eb86 3008
718db961 3009 assert(m);
fd08a840 3010 assert(source);
9152c765 3011
718db961 3012 manager_print_jobs_in_progress(m);
fd08a840 3013
39cf0351 3014 r = sd_event_source_set_time_relative(source, JOBS_IN_PROGRESS_PERIOD_USEC);
fd08a840
ZJS
3015 if (r < 0)
3016 return r;
3017
3018 return sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
9152c765
LP
3019}
3020
3021int manager_loop(Manager *m) {
8c227e7f 3022 RateLimit rl = { .interval = 1*USEC_PER_SEC, .burst = 50000 };
9152c765 3023 int r;
9152c765
LP
3024
3025 assert(m);
1fb70e66 3026 assert(m->objective == MANAGER_OK); /* Ensure manager_startup() has been called */
9152c765 3027
b0c918b9
LP
3028 manager_check_finished(m);
3029
575b300b
LP
3030 /* There might still be some zombies hanging around from before we were exec()'ed. Let's reap them. */
3031 r = sd_event_source_set_enabled(m->sigchld_event_source, SD_EVENT_ON);
e96d6be7 3032 if (r < 0)
575b300b 3033 return log_error_errno(r, "Failed to enable SIGCHLD event source: %m");
a4312405 3034
af41e508 3035 while (m->objective == MANAGER_OK) {
9152c765 3036
ae4a0ec4 3037 (void) watchdog_ping();
e96d6be7 3038
7994ac1d 3039 if (!ratelimit_below(&rl)) {
ea430986
LP
3040 /* Yay, something is going seriously wrong, pause a little */
3041 log_warning("Looping too fast. Throttling execution a little.");
3042 sleep(1);
3043 }
3044
37a8e683 3045 if (manager_dispatch_load_queue(m) > 0)
23a177ef
LP
3046 continue;
3047
c5a97ed1
LP
3048 if (manager_dispatch_gc_job_queue(m) > 0)
3049 continue;
3050
3051 if (manager_dispatch_gc_unit_queue(m) > 0)
701cc384
LP
3052 continue;
3053
cf1265e1 3054 if (manager_dispatch_cleanup_queue(m) > 0)
c1e1601e 3055 continue;
034c6ed7 3056
91a6073e 3057 if (manager_dispatch_cgroup_realize_queue(m) > 0)
c1e1601e
LP
3058 continue;
3059
0bc488c9
LP
3060 if (manager_dispatch_start_when_upheld_queue(m) > 0)
3061 continue;
3062
56c59592
LP
3063 if (manager_dispatch_stop_when_bound_queue(m) > 0)
3064 continue;
3065
a3c1168a
LP
3066 if (manager_dispatch_stop_when_unneeded_queue(m) > 0)
3067 continue;
3068
c1e1601e 3069 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 3070 continue;
ea430986 3071
c5f8a179 3072 /* Sleep for watchdog runtime wait time */
12663295 3073 r = sd_event_run(m->event, watchdog_runtime_wait());
23bbb0de
MS
3074 if (r < 0)
3075 return log_error_errno(r, "Failed to run event loop: %m");
a16e1123 3076 }
957ca890 3077
af41e508 3078 return m->objective;
83c60c9f 3079}
ea430986 3080
718db961 3081int manager_load_unit_from_dbus_path(Manager *m, const char *s, sd_bus_error *e, Unit **_u) {
ede3a796 3082 _cleanup_free_ char *n = NULL;
4b58153d 3083 sd_id128_t invocation_id;
ea430986 3084 Unit *u;
80fbf05e 3085 int r;
ea430986
LP
3086
3087 assert(m);
3088 assert(s);
3089 assert(_u);
3090
ede3a796
LP
3091 r = unit_name_from_dbus_path(s, &n);
3092 if (r < 0)
3093 return r;
ea430986 3094
4b58153d
LP
3095 /* Permit addressing units by invocation ID: if the passed bus path is suffixed by a 128bit ID then we use it
3096 * as invocation ID. */
3097 r = sd_id128_from_string(n, &invocation_id);
3098 if (r >= 0) {
3099 u = hashmap_get(m->units_by_invocation_id, &invocation_id);
3100 if (u) {
3101 *_u = u;
3102 return 0;
3103 }
3104
930c124c
ZJS
3105 return sd_bus_error_setf(e, BUS_ERROR_NO_UNIT_FOR_INVOCATION_ID,
3106 "No unit with the specified invocation ID " SD_ID128_FORMAT_STR " known.",
3107 SD_ID128_FORMAT_VAL(invocation_id));
4b58153d
LP
3108 }
3109
00c83b43 3110 /* If this didn't work, we check if this is a unit name */
930c124c
ZJS
3111 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
3112 _cleanup_free_ char *nn = NULL;
3113
3114 nn = cescape(n);
3115 return sd_bus_error_setf(e, SD_BUS_ERROR_INVALID_ARGS,
3116 "Unit name %s is neither a valid invocation ID nor unit name.", strnull(nn));
3117 }
00c83b43 3118
80fbf05e 3119 r = manager_load_unit(m, n, NULL, e, &u);
80fbf05e
MS
3120 if (r < 0)
3121 return r;
ea430986
LP
3122
3123 *_u = u;
ea430986
LP
3124 return 0;
3125}
86fbf370
LP
3126
3127int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
718db961 3128 const char *p;
86fbf370 3129 unsigned id;
718db961 3130 Job *j;
86fbf370
LP
3131 int r;
3132
3133 assert(m);
3134 assert(s);
3135 assert(_j);
3136
718db961
LP
3137 p = startswith(s, "/org/freedesktop/systemd1/job/");
3138 if (!p)
86fbf370
LP
3139 return -EINVAL;
3140
718db961 3141 r = safe_atou(p, &id);
8742514c 3142 if (r < 0)
86fbf370
LP
3143 return r;
3144
8742514c
LP
3145 j = manager_get_job(m, id);
3146 if (!j)
86fbf370
LP
3147 return -ENOENT;
3148
3149 *_j = j;
3150
3151 return 0;
3152}
dfcd764e 3153
4927fcae 3154void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
e537352b 3155
349cc4a5 3156#if HAVE_AUDIT
2ba11090 3157 _cleanup_free_ char *p = NULL;
0aa281df 3158 const char *msg;
7410616c 3159 int audit_fd, r;
e537352b 3160
463d0d15 3161 if (!MANAGER_IS_SYSTEM(m))
a1a078ee
LP
3162 return;
3163
c1165f82
LP
3164 audit_fd = get_audit_fd();
3165 if (audit_fd < 0)
e537352b
LP
3166 return;
3167
bbd3a7ba
LP
3168 /* Don't generate audit events if the service was already
3169 * started and we're just deserializing */
2c289ea8 3170 if (MANAGER_IS_RELOADING(m))
bbd3a7ba
LP
3171 return;
3172
ac155bb8 3173 if (u->type != UNIT_SERVICE)
f1dd0c3f
LP
3174 return;
3175
7410616c
LP
3176 r = unit_name_to_prefix_and_instance(u->id, &p);
3177 if (r < 0) {
3178 log_error_errno(r, "Failed to extract prefix and instance of unit name: %m");
e537352b
LP
3179 return;
3180 }
3181
63c372cb 3182 msg = strjoina("unit=", p);
0aa281df
LP
3183 if (audit_log_user_comm_message(audit_fd, type, msg, "systemd", NULL, NULL, NULL, success) < 0) {
3184 if (errno == EPERM)
391ade86 3185 /* We aren't allowed to send audit messages?
44785992 3186 * Then let's not retry again. */
c1165f82 3187 close_audit_fd();
0aa281df 3188 else
56f64d95 3189 log_warning_errno(errno, "Failed to send audit message: %m");
391ade86 3190 }
4927fcae 3191#endif
e537352b 3192
e537352b
LP
3193}
3194
e983b760 3195void manager_send_unit_plymouth(Manager *m, Unit *u) {
fc2fffe7 3196 static const union sockaddr_union sa = PLYMOUTH_SOCKET;
2ba11090
ZJS
3197 _cleanup_free_ char *message = NULL;
3198 _cleanup_close_ int fd = -1;
fc2fffe7 3199 int n = 0;
e983b760
LP
3200
3201 /* Don't generate plymouth events if the service was already
3202 * started and we're just deserializing */
2c289ea8 3203 if (MANAGER_IS_RELOADING(m))
e983b760
LP
3204 return;
3205
463d0d15 3206 if (!MANAGER_IS_SYSTEM(m))
e983b760
LP
3207 return;
3208
75f86906 3209 if (detect_container() > 0)
3772995a
LP
3210 return;
3211
ec2ce0c5 3212 if (!IN_SET(u->type, UNIT_SERVICE, UNIT_MOUNT, UNIT_SWAP))
e983b760
LP
3213 return;
3214
3215 /* We set SOCK_NONBLOCK here so that we rather drop the
3216 * message then wait for plymouth */
e62d8c39
ZJS
3217 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
3218 if (fd < 0) {
56f64d95 3219 log_error_errno(errno, "socket() failed: %m");
e983b760
LP
3220 return;
3221 }
3222
fc2fffe7 3223 if (connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)) < 0) {
f60a028a 3224 if (!IN_SET(errno, EAGAIN, ENOENT) && !ERRNO_IS_DISCONNECT(errno))
56f64d95 3225 log_error_errno(errno, "connect() failed: %m");
2ba11090 3226 return;
e983b760
LP
3227 }
3228
305757d8
ZJS
3229 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0)
3230 return (void) log_oom();
e983b760
LP
3231
3232 errno = 0;
2ba11090 3233 if (write(fd, message, n + 1) != n + 1)
f60a028a 3234 if (!IN_SET(errno, EAGAIN, ENOENT) && !ERRNO_IS_DISCONNECT(errno))
56f64d95 3235 log_error_errno(errno, "Failed to write Plymouth message: %m");
e983b760
LP
3236}
3237
986935cf
FB
3238usec_t manager_get_watchdog(Manager *m, WatchdogType t) {
3239 assert(m);
3240
3241 if (MANAGER_IS_USER(m))
3242 return USEC_INFINITY;
3243
3244 if (timestamp_is_set(m->watchdog_overridden[t]))
3245 return m->watchdog_overridden[t];
3246
3247 return m->watchdog[t];
3248}
3249
3250void manager_set_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
986935cf
FB
3251
3252 assert(m);
3253
3254 if (MANAGER_IS_USER(m))
3255 return;
3256
3257 if (m->watchdog[t] == timeout)
3258 return;
3259
5717062e 3260 if (t == WATCHDOG_RUNTIME) {
f16890f8
FB
3261 if (!timestamp_is_set(m->watchdog_overridden[WATCHDOG_RUNTIME]))
3262 (void) watchdog_setup(timeout);
5717062e
CK
3263 } else if (t == WATCHDOG_PRETIMEOUT)
3264 if (m->watchdog_overridden[WATCHDOG_PRETIMEOUT] == USEC_INFINITY)
3265 (void) watchdog_setup_pretimeout(timeout);
986935cf 3266
61927b9f 3267 m->watchdog[t] = timeout;
986935cf
FB
3268}
3269
aac47032 3270void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout) {
986935cf
FB
3271
3272 assert(m);
3273
3274 if (MANAGER_IS_USER(m))
aac47032 3275 return;
986935cf
FB
3276
3277 if (m->watchdog_overridden[t] == timeout)
aac47032 3278 return;
986935cf
FB
3279
3280 if (t == WATCHDOG_RUNTIME) {
2628b98f 3281 usec_t usec = timestamp_is_set(timeout) ? timeout : m->watchdog[t];
986935cf 3282
f16890f8 3283 (void) watchdog_setup(usec);
5717062e
CK
3284 } else if (t == WATCHDOG_PRETIMEOUT)
3285 (void) watchdog_setup_pretimeout(timeout);
986935cf 3286
61927b9f 3287 m->watchdog_overridden[t] = timeout;
986935cf
FB
3288}
3289
aff3a9e1
LB
3290int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor) {
3291 _cleanup_free_ char *p = NULL;
3292 int r;
3293
3294 assert(m);
3295
3296 if (MANAGER_IS_USER(m))
3297 return 0;
3298
3299 if (streq_ptr(m->watchdog_pretimeout_governor, governor))
3300 return 0;
3301
3302 p = strdup(governor);
3303 if (!p)
3304 return -ENOMEM;
3305
3306 r = watchdog_setup_pretimeout_governor(governor);
3307 if (r < 0)
3308 return r;
3309
3310 return free_and_replace(m->watchdog_pretimeout_governor, p);
3311}
3312
3313int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor) {
3314 _cleanup_free_ char *p = NULL;
3315 int r;
3316
3317 assert(m);
3318
3319 if (MANAGER_IS_USER(m))
3320 return 0;
3321
3322 if (streq_ptr(m->watchdog_pretimeout_governor_overridden, governor))
3323 return 0;
3324
3325 p = strdup(governor);
3326 if (!p)
3327 return -ENOMEM;
3328
3329 r = watchdog_setup_pretimeout_governor(governor);
3330 if (r < 0)
3331 return r;
3332
3333 return free_and_replace(m->watchdog_pretimeout_governor_overridden, p);
3334}
3335
a16e1123 3336int manager_reload(Manager *m) {
d7ac0952 3337 _unused_ _cleanup_(manager_reloading_stopp) Manager *reloading = NULL;
51d122af 3338 _cleanup_fdset_free_ FDSet *fds = NULL;
6a33af40
LP
3339 _cleanup_fclose_ FILE *f = NULL;
3340 int r;
a16e1123
LP
3341
3342 assert(m);
3343
07719a21
LP
3344 r = manager_open_serialization(m, &f);
3345 if (r < 0)
6a33af40 3346 return log_error_errno(r, "Failed to create serialization file: %m");
38c52d46 3347
07719a21 3348 fds = fdset_new();
6a33af40
LP
3349 if (!fds)
3350 return log_oom();
3351
d147e2b6
ZJS
3352 /* We are officially in reload mode from here on. */
3353 reloading = manager_reloading_start(m);
a16e1123 3354
b3680f49 3355 r = manager_serialize(m, f, fds, false);
d147e2b6 3356 if (r < 0)
d68c645b 3357 return r;
a16e1123 3358
d147e2b6
ZJS
3359 if (fseeko(f, 0, SEEK_SET) < 0)
3360 return log_error_errno(errno, "Failed to seek to beginning of serialization: %m");
a16e1123 3361
6a33af40 3362 /* 💀 This is the point of no return, from here on there is no way back. 💀 */
d147e2b6 3363 reloading = NULL;
6a33af40
LP
3364
3365 bus_manager_send_reloading(m, true);
3366
3367 /* Start by flushing out all jobs and units, all generated units, all runtime environments, all dynamic users
3368 * and everything else that is worth flushing out. We'll get it all back from the serialization — if we need
7802194a 3369 * it. */
6a33af40 3370
a16e1123 3371 manager_clear_jobs_and_units(m);
07a78643 3372 lookup_paths_flush_generator(&m->lookup_paths);
84e3543e 3373 lookup_paths_free(&m->lookup_paths);
e8a565cb 3374 exec_runtime_vacuum(m);
29206d46 3375 dynamic_user_vacuum(m, false);
00d9ef85
LP
3376 m->uid_refs = hashmap_free(m->uid_refs);
3377 m->gid_refs = hashmap_free(m->gid_refs);
2ded0c04 3378
99aad9a2 3379 r = lookup_paths_init_or_warn(&m->lookup_paths, m->unit_file_scope, 0, NULL);
6a33af40 3380 if (r < 0)
99aad9a2 3381 return r;
5a1e9937 3382
6a33af40
LP
3383 (void) manager_run_environment_generators(m);
3384 (void) manager_run_generators(m);
64691d20 3385
581fef8d 3386 lookup_paths_log(&m->lookup_paths);
07719a21 3387
91e0ee5f 3388 /* We flushed out generated files, for which we don't watch mtime, so we should flush the old map. */
e8630e69 3389 manager_free_unit_name_maps(m);
5a1e9937 3390
6a33af40 3391 /* First, enumerate what we can from kernel and suchlike */
3ad2afb6 3392 manager_enumerate_perpetual(m);
ba64af90 3393 manager_enumerate(m);
a16e1123
LP
3394
3395 /* Second, deserialize our stored data */
6a33af40
LP
3396 r = manager_deserialize(m, f, fds);
3397 if (r < 0)
3398 log_warning_errno(r, "Deserialization failed, proceeding anyway: %m");
a16e1123 3399
6a33af40 3400 /* We don't need the serialization anymore */
62b0cbb3 3401 f = safe_fclose(f);
a16e1123 3402
6a33af40
LP
3403 /* Re-register notify_fd as event source, and set up other sockets/communication channels we might need */
3404 (void) manager_setup_notify(m);
3405 (void) manager_setup_cgroups_agent(m);
3406 (void) manager_setup_user_lookup_fd(m);
00d9ef85 3407
a16e1123 3408 /* Third, fire things up! */
007c6337 3409 manager_coldplug(m);
a16e1123 3410
5197be06
LP
3411 /* Clean up runtime objects no longer referenced */
3412 manager_vacuum(m);
e8a565cb 3413
3deed59a
AA
3414 /* Clean up deserialized tracked clients */
3415 m->deserialized_subscribed = strv_free(m->deserialized_subscribed);
3416
6a33af40 3417 /* Consider the reload process complete now. */
31dc1ca3
LP
3418 assert(m->n_reloading > 0);
3419 m->n_reloading--;
3420
c6e892bc
YW
3421 /* On manager reloading, device tag data should exists, thus, we should honor the results of device
3422 * enumeration. The flag should be always set correctly by the serialized data, but it may fail. So,
3423 * let's always set the flag here for safety. */
3424 m->honor_device_enumeration = true;
3425
5ce5e1ad 3426 manager_ready(m);
8936a5e3 3427
71445ae7 3428 m->send_reloading_done = true;
6a33af40 3429 return 0;
a16e1123
LP
3430}
3431
fdf20a31 3432void manager_reset_failed(Manager *m) {
5632e374 3433 Unit *u;
5632e374
LP
3434
3435 assert(m);
3436
90e74a66 3437 HASHMAP_FOREACH(u, m->units)
fdf20a31 3438 unit_reset_failed(u);
5632e374
LP
3439}
3440
31afa0a4 3441bool manager_unit_inactive_or_pending(Manager *m, const char *name) {
8f6df3fa
LP
3442 Unit *u;
3443
3444 assert(m);
3445 assert(name);
3446
3447 /* Returns true if the unit is inactive or going down */
bd0af849
ZJS
3448 u = manager_get_unit(m, name);
3449 if (!u)
8f6df3fa
LP
3450 return true;
3451
31afa0a4 3452 return unit_inactive_or_pending(u);
8f6df3fa
LP
3453}
3454
d8eb10d6
ZJS
3455static void log_taint_string(Manager *m) {
3456 _cleanup_free_ char *taint = NULL;
3457
3458 assert(m);
3459
3460 if (MANAGER_IS_USER(m) || m->taint_logged)
3461 return;
3462
3463 m->taint_logged = true; /* only check for taint once */
3464
3465 taint = manager_taint_string(m);
3466 if (isempty(taint))
3467 return;
3468
3469 log_struct(LOG_NOTICE,
3470 LOG_MESSAGE("System is tainted: %s", taint),
3471 "TAINT=%s", taint,
a1230ff9 3472 "MESSAGE_ID=" SD_MESSAGE_TAINTED_STR);
d8eb10d6
ZJS
3473}
3474
56dacdbc 3475static void manager_notify_finished(Manager *m) {
915b3753 3476 usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
b0c918b9 3477
638cece4 3478 if (MANAGER_IS_TEST_RUN(m))
b0c918b9
LP
3479 return;
3480
463d0d15 3481 if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
dc3c9f5e
ZJS
3482 char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
3483 = {};
3484 char *p = buf;
3485 size_t size = sizeof buf;
e03ae661 3486
9f9f0342
LP
3487 /* Note that MANAGER_TIMESTAMP_KERNEL's monotonic value is always at 0, and
3488 * MANAGER_TIMESTAMP_FIRMWARE's and MANAGER_TIMESTAMP_LOADER's monotonic value should be considered
915b3753
LP
3489 * negative values. */
3490
9f9f0342
LP
3491 firmware_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic - m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic;
3492 loader_usec = m->timestamps[MANAGER_TIMESTAMP_LOADER].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
3493 userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
3494 total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
18fa6b27 3495
dd1db3c2 3496 if (firmware_usec > 0)
5291f26d 3497 size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
dd1db3c2 3498 if (loader_usec > 0)
5291f26d 3499 size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
dd1db3c2 3500
9f9f0342 3501 if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
18fa6b27 3502
7802194a 3503 /* The initrd case on bare-metal */
9f9f0342
LP
3504 kernel_usec = m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
3505 initrd_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_INITRD].monotonic;
18fa6b27 3506
e12919e8 3507 log_struct(LOG_INFO,
2b044526 3508 "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
e12919e8
LP
3509 "KERNEL_USEC="USEC_FMT, kernel_usec,
3510 "INITRD_USEC="USEC_FMT, initrd_usec,
3511 "USERSPACE_USEC="USEC_FMT, userspace_usec,
dd1db3c2
YW
3512 LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
3513 buf,
5291f26d
ZJS
3514 FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3515 FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
3516 FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3517 FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
18fa6b27 3518 } else {
7802194a 3519 /* The initrd-less case on bare-metal */
9f9f0342
LP
3520
3521 kernel_usec = m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic - m->timestamps[MANAGER_TIMESTAMP_KERNEL].monotonic;
18fa6b27
LP
3522 initrd_usec = 0;
3523
81270860 3524 log_struct(LOG_INFO,
2b044526 3525 "MESSAGE_ID=" SD_MESSAGE_STARTUP_FINISHED_STR,
e12919e8 3526 "KERNEL_USEC="USEC_FMT, kernel_usec,
ccd06097 3527 "USERSPACE_USEC="USEC_FMT, userspace_usec,
dd1db3c2
YW
3528 LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
3529 buf,
5291f26d
ZJS
3530 FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
3531 FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
3532 FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
e12919e8
LP
3533 }
3534 } else {
4adf314b 3535 /* The container and --user case */
e12919e8 3536 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
9f9f0342 3537 total_usec = userspace_usec = m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic - m->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
e12919e8
LP
3538
3539 log_struct(LOG_INFO,
2b044526 3540 "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR,
e12919e8 3541 "USERSPACE_USEC="USEC_FMT, userspace_usec,
e2cc6eca 3542 LOG_MESSAGE("Startup finished in %s.",
5291f26d 3543 FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
18fa6b27 3544 }
b0c918b9 3545
718db961 3546 bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
530345e7 3547
d8eb10d6 3548 log_taint_string(m);
b0c918b9
LP
3549}
3550
6d932659 3551static void user_manager_send_ready(Manager *m) {
4bf4f50f
ZJS
3552 int r;
3553
4adf314b
LP
3554 assert(m);
3555
3556 /* We send READY=1 on reaching basic.target only when running in --user mode. */
3557 if (!MANAGER_IS_USER(m) || m->ready_sent)
3558 return;
3559
d4341b76
ZJS
3560 r = sd_notify(false,
3561 "READY=1\n"
3562 "STATUS=Reached " SPECIAL_BASIC_TARGET ".");
4bf4f50f
ZJS
3563 if (r < 0)
3564 log_warning_errno(r, "Failed to send readiness notification, ignoring: %m");
3565
6d932659
ZJS
3566 m->ready_sent = true;
3567 m->status_ready = false;
3568}
3569
3570static void manager_send_ready(Manager *m) {
4bf4f50f
ZJS
3571 int r;
3572
6d932659
ZJS
3573 if (m->ready_sent && m->status_ready)
3574 /* Skip the notification if nothing changed. */
3575 return;
3576
028f7d3a
ZJS
3577 r = sd_notify(false,
3578 "READY=1\n"
3579 "STATUS=Ready.");
4bf4f50f
ZJS
3580 if (r < 0)
3581 log_full_errno(m->ready_sent ? LOG_DEBUG : LOG_WARNING, r,
3582 "Failed to send readiness notification, ignoring: %m");
3583
6d932659 3584 m->ready_sent = m->status_ready = true;
4adf314b
LP
3585}
3586
3587static void manager_check_basic_target(Manager *m) {
3588 Unit *u;
3589
3590 assert(m);
3591
3592 /* Small shortcut */
3593 if (m->ready_sent && m->taint_logged)
3594 return;
3595
3596 u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
3597 if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
3598 return;
3599
3600 /* For user managers, send out READY=1 as soon as we reach basic.target */
6d932659 3601 user_manager_send_ready(m);
4adf314b
LP
3602
3603 /* Log the taint string as soon as we reach basic.target */
3604 log_taint_string(m);
3605}
3606
56dacdbc 3607void manager_check_finished(Manager *m) {
56dacdbc
ZJS
3608 assert(m);
3609
2c289ea8 3610 if (MANAGER_IS_RELOADING(m))
aad1976f
LP
3611 return;
3612
4259d202
LP
3613 /* Verify that we have entered the event loop already, and not left it again. */
3614 if (!MANAGER_IS_RUNNING(m))
9771b62d
LP
3615 return;
3616
4adf314b 3617 manager_check_basic_target(m);
0c2826c6 3618
56dacdbc 3619 if (hashmap_size(m->jobs) > 0) {
56dacdbc 3620 if (m->jobs_in_progress_event_source)
2ae56591 3621 /* Ignore any failure, this is only for feedback */
1b4154a8
ZJS
3622 (void) sd_event_source_set_time(m->jobs_in_progress_event_source,
3623 manager_watch_jobs_next_time(m));
56dacdbc
ZJS
3624 return;
3625 }
3626
a4ac27c1
ZJS
3627 /* The jobs hashmap tends to grow a lot during boot, and then it's not reused until shutdown. Let's
3628 kill the hashmap if it is relatively large. */
3629 if (hashmap_buckets(m->jobs) > hashmap_size(m->units) / 10)
3630 m->jobs = hashmap_free(m->jobs);
3631
6d932659
ZJS
3632 manager_send_ready(m);
3633
9c1b17c3
YW
3634 /* Notify Type=idle units that we are done now */
3635 manager_close_idle_pipe(m);
3636
6d932659
ZJS
3637 if (MANAGER_IS_FINISHED(m))
3638 return;
3639
7365a296 3640 manager_flip_auto_status(m, false, "boot finished");
56dacdbc 3641
56dacdbc 3642 /* Turn off confirm spawn now */
7d5ceb64 3643 m->confirm_spawn = NULL;
56dacdbc
ZJS
3644
3645 /* No need to update ask password status when we're going non-interactive */
3646 manager_close_ask_password(m);
3647
3648 /* This is no longer the first boot */
3649 manager_set_first_boot(m, false);
3650
9f9f0342 3651 dual_timestamp_get(m->timestamps + MANAGER_TIMESTAMP_FINISH);
56dacdbc
ZJS
3652
3653 manager_notify_finished(m);
3654
e7ab4d1a 3655 manager_invalidate_startup_units(m);
56dacdbc
ZJS
3656}
3657
64691d20 3658static bool generator_path_any(const char* const* paths) {
64691d20
ZJS
3659 bool found = false;
3660
3661 /* Optimize by skipping the whole process by not creating output directories
3662 * if no generators are found. */
2034c8b8 3663 STRV_FOREACH(path, paths)
64691d20
ZJS
3664 if (access(*path, F_OK) == 0)
3665 found = true;
3666 else if (errno != ENOENT)
3667 log_warning_errno(errno, "Failed to open generator directory %s: %m", *path);
3668
3669 return found;
3670}
3671
64691d20
ZJS
3672static int manager_run_environment_generators(Manager *m) {
3673 char **tmp = NULL; /* this is only used in the forked process, no cleanup here */
cccf5703 3674 _cleanup_strv_free_ char **paths = NULL;
1ad6e8b3
LP
3675 void* args[] = {
3676 [STDOUT_GENERATE] = &tmp,
3677 [STDOUT_COLLECT] = &tmp,
3678 [STDOUT_CONSUME] = &m->transient_environment,
3679 };
e3b8d063 3680 int r;
64691d20 3681
638cece4 3682 if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_ENV_GENERATORS))
e0a3da1f
ZJS
3683 return 0;
3684
cccf5703
BB
3685 paths = env_generator_binary_paths(MANAGER_IS_SYSTEM(m));
3686 if (!paths)
3687 return log_oom();
64691d20 3688
cccf5703 3689 if (!generator_path_any((const char* const*) paths))
64691d20
ZJS
3690 return 0;
3691
e3b8d063 3692 RUN_WITH_UMASK(0022)
cccf5703 3693 r = execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC, gather_environment,
43f565c6
YW
3694 args, NULL, m->transient_environment,
3695 EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
e3b8d063 3696 return r;
64691d20
ZJS
3697}
3698
82c5db16
LP
3699static int build_generator_environment(Manager *m, char ***ret) {
3700 _cleanup_strv_free_ char **nl = NULL;
3701 Virtualization v;
3702 int r;
3703
3704 assert(m);
3705 assert(ret);
3706
3707 /* Generators oftentimes want to know some basic facts about the environment they run in, in order to
3708 * adjust generated units to that. Let's pass down some bits of information that are easy for us to
3709 * determine (but a bit harder for generator scripts to determine), as environment variables. */
3710
3711 nl = strv_copy(m->transient_environment);
3712 if (!nl)
3713 return -ENOMEM;
3714
3715 r = strv_env_assign(&nl, "SYSTEMD_SCOPE", MANAGER_IS_SYSTEM(m) ? "system" : "user");
3716 if (r < 0)
3717 return r;
3718
3719 if (MANAGER_IS_SYSTEM(m)) {
3720 /* Note that $SYSTEMD_IN_INITRD may be used to override the initrd detection in much of our
3721 * codebase. This is hence more than purely informational. It will shortcut detection of the
3722 * initrd state if generators invoke our own tools. But that's OK, as it would come to the
3723 * same results (hopefully). */
3724 r = strv_env_assign(&nl, "SYSTEMD_IN_INITRD", one_zero(in_initrd()));
3725 if (r < 0)
3726 return r;
3727
3728 if (m->first_boot >= 0) {
3729 r = strv_env_assign(&nl, "SYSTEMD_FIRST_BOOT", one_zero(m->first_boot));
3730 if (r < 0)
3731 return r;
3732 }
3733 }
3734
3735 v = detect_virtualization();
3736 if (v < 0)
3737 log_debug_errno(v, "Failed to detect virtualization, ignoring: %m");
3738 else if (v > 0) {
3739 const char *s;
3740
3741 s = strjoina(VIRTUALIZATION_IS_VM(v) ? "vm:" :
3742 VIRTUALIZATION_IS_CONTAINER(v) ? "container:" : ":",
3743 virtualization_to_string(v));
3744
3745 r = strv_env_assign(&nl, "SYSTEMD_VIRTUALIZATION", s);
3746 if (r < 0)
3747 return r;
3748 }
3749
3750 r = strv_env_assign(&nl, "SYSTEMD_ARCHITECTURE", architecture_to_string(uname_architecture()));
3751 if (r < 0)
3752 return r;
3753
3754 *ret = TAKE_PTR(nl);
3755 return 0;
3756}
3757
e801700e 3758static int manager_run_generators(Manager *m) {
82c5db16 3759 _cleanup_strv_free_ char **paths = NULL, **ge = NULL;
07719a21 3760 int r;
5a1e9937
LP
3761
3762 assert(m);
3763
638cece4 3764 if (MANAGER_IS_TEST_RUN(m) && !(m->test_run_flags & MANAGER_TEST_RUN_GENERATORS))
e0a3da1f
ZJS
3765 return 0;
3766
9183df70 3767 paths = generator_binary_paths(m->unit_file_scope);
e801700e
ZJS
3768 if (!paths)
3769 return log_oom();
5a1e9937 3770
64691d20
ZJS
3771 if (!generator_path_any((const char* const*) paths))
3772 return 0;
5a1e9937 3773
cd64fd56 3774 r = lookup_paths_mkdir_generator(&m->lookup_paths);
7eb4f326
LP
3775 if (r < 0) {
3776 log_error_errno(r, "Failed to create generator directories: %m");
07719a21 3777 goto finish;
7eb4f326 3778 }
5a1e9937 3779
82c5db16
LP
3780 const char *argv[] = {
3781 NULL, /* Leave this empty, execute_directory() will fill something in */
3782 m->lookup_paths.generator,
3783 m->lookup_paths.generator_early,
3784 m->lookup_paths.generator_late,
3785 NULL,
3786 };
3787
3788 r = build_generator_environment(m, &ge);
3789 if (r < 0) {
3790 log_error_errno(r, "Failed to build generator environment: %m");
3791 goto finish;
3792 }
5a1e9937 3793
718db961 3794 RUN_WITH_UMASK(0022)
82c5db16
LP
3795 (void) execute_directories(
3796 (const char* const*) paths,
3797 DEFAULT_TIMEOUT_USEC,
3798 /* callbacks= */ NULL, /* callback_args= */ NULL,
3799 (char**) argv,
3800 ge,
3801 EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS | EXEC_DIR_SET_SYSTEMD_EXEC_PID);
7eb4f326
LP
3802
3803 r = 0;
5a1e9937 3804
718db961 3805finish:
cd64fd56 3806 lookup_paths_trim_generator(&m->lookup_paths);
e801700e 3807 return r;
5a1e9937
LP
3808}
3809
1ad6e8b3
LP
3810int manager_transient_environment_add(Manager *m, char **plus) {
3811 char **a;
3812
3813 assert(m);
3814
3815 if (strv_isempty(plus))
3816 return 0;
3817
4ab3d29f 3818 a = strv_env_merge(m->transient_environment, plus);
1ad6e8b3 3819 if (!a)
2fbbbf9a 3820 return log_oom();
1ad6e8b3
LP
3821
3822 sanitize_environment(a);
3823
3824 return strv_free_and_replace(m->transient_environment, a);
3825}
3826
3827int manager_client_environment_modify(
3828 Manager *m,
3829 char **minus,
3830 char **plus) {
3831
718db961 3832 char **a = NULL, **b = NULL, **l;
1ad6e8b3 3833
97d0e5f8 3834 assert(m);
bcd8e6d1 3835
1ad6e8b3
LP
3836 if (strv_isempty(minus) && strv_isempty(plus))
3837 return 0;
3838
3839 l = m->client_environment;
bcd8e6d1 3840
718db961
LP
3841 if (!strv_isempty(minus)) {
3842 a = strv_env_delete(l, 1, minus);
3843 if (!a)
3844 return -ENOMEM;
3845
3846 l = a;
3847 }
3848
3849 if (!strv_isempty(plus)) {
4ab3d29f 3850 b = strv_env_merge(l, plus);
aa9f8a30
AH
3851 if (!b) {
3852 strv_free(a);
718db961 3853 return -ENOMEM;
aa9f8a30 3854 }
bcd8e6d1 3855
718db961
LP
3856 l = b;
3857 }
3858
1ad6e8b3
LP
3859 if (m->client_environment != l)
3860 strv_free(m->client_environment);
3861
718db961
LP
3862 if (a != l)
3863 strv_free(a);
3864 if (b != l)
3865 strv_free(b);
3866
1ad6e8b3
LP
3867 m->client_environment = sanitize_environment(l);
3868 return 0;
3869}
3870
3871int manager_get_effective_environment(Manager *m, char ***ret) {
3872 char **l;
3873
3874 assert(m);
3875 assert(ret);
3876
4ab3d29f 3877 l = strv_env_merge(m->transient_environment, m->client_environment);
1ad6e8b3
LP
3878 if (!l)
3879 return -ENOMEM;
f069efb4 3880
1ad6e8b3 3881 *ret = l;
97d0e5f8
UTL
3882 return 0;
3883}
3884
aa5ae971
ŁS
3885int manager_set_default_smack_process_label(Manager *m, const char *label) {
3886 assert(m);
3887
3888#ifdef SMACK_DEFAULT_PROCESS_LABEL
3889 if (!label)
3890 return free_and_strdup(&m->default_smack_process_label, SMACK_DEFAULT_PROCESS_LABEL);
3891#endif
3892 if (streq_ptr(label, "/"))
3893 return free_and_strdup(&m->default_smack_process_label, NULL);
3894
3895 return free_and_strdup(&m->default_smack_process_label, label);
3896}
3897
c93ff2e9 3898int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
c93ff2e9
FC
3899 assert(m);
3900
5b10116e 3901 for (unsigned i = 0; i < _RLIMIT_MAX; i++) {
d9814c76
EV
3902 m->rlimit[i] = mfree(m->rlimit[i]);
3903
07719a21
LP
3904 if (!default_rlimit[i])
3905 continue;
c93ff2e9 3906
07719a21
LP
3907 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
3908 if (!m->rlimit[i])
3ce40911 3909 return log_oom();
c93ff2e9
FC
3910 }
3911
3912 return 0;
3913}
3914
8559b3b7
LP
3915void manager_recheck_dbus(Manager *m) {
3916 assert(m);
3917
3918 /* Connects to the bus if the dbus service and socket are running. If we are running in user mode this is all
3919 * it does. In system mode we'll also connect to the system bus (which will most likely just reuse the
3920 * connection of the API bus). That's because the system bus after all runs as service of the system instance,
3921 * while in the user instance we can assume it's already there. */
3922
31dc1ca3
LP
3923 if (MANAGER_IS_RELOADING(m))
3924 return; /* don't check while we are reloading… */
3925
8559b3b7
LP
3926 if (manager_dbus_is_running(m, false)) {
3927 (void) bus_init_api(m);
3928
3929 if (MANAGER_IS_SYSTEM(m))
3930 (void) bus_init_system(m);
3931 } else {
3932 (void) bus_done_api(m);
3933
3934 if (MANAGER_IS_SYSTEM(m))
3935 (void) bus_done_system(m);
3936 }
3937}
3938
d075092f 3939static bool manager_journal_is_running(Manager *m) {
f1dd0c3f
LP
3940 Unit *u;
3941
3942 assert(m);
3943
638cece4 3944 if (MANAGER_IS_TEST_RUN(m))
7d814a19
LP
3945 return false;
3946
d075092f 3947 /* If we are the user manager we can safely assume that the journal is up */
463d0d15 3948 if (!MANAGER_IS_SYSTEM(m))
d075092f 3949 return true;
f1dd0c3f 3950
d075092f 3951 /* Check that the socket is not only up, but in RUNNING state */
731a676c 3952 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
d075092f
LP
3953 if (!u)
3954 return false;
3955 if (SOCKET(u)->state != SOCKET_RUNNING)
3956 return false;
f1dd0c3f 3957
d075092f 3958 /* Similar, check if the daemon itself is fully up, too */
731a676c 3959 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
d075092f
LP
3960 if (!u)
3961 return false;
217677ab 3962 if (!IN_SET(SERVICE(u)->state, SERVICE_RELOAD, SERVICE_RUNNING))
d075092f
LP
3963 return false;
3964
3965 return true;
3966}
3967
6123dfaa
ZJS
3968void disable_printk_ratelimit(void) {
3969 /* Disable kernel's printk ratelimit.
3970 *
3971 * Logging to /dev/kmsg is most useful during early boot and shutdown, where normal logging
3972 * mechanisms are not available. The semantics of this sysctl are such that any kernel command-line
3973 * setting takes precedence. */
3974 int r;
3975
3976 r = sysctl_write("kernel/printk_devkmsg", "on");
3977 if (r < 0)
3978 log_debug_errno(r, "Failed to set sysctl kernel.printk_devkmsg=on: %m");
3979}
3980
d075092f
LP
3981void manager_recheck_journal(Manager *m) {
3982
3983 assert(m);
3984
3985 /* Don't bother with this unless we are in the special situation of being PID 1 */
3986 if (getpid_cached() != 1)
731a676c 3987 return;
f1dd0c3f 3988
31dc1ca3
LP
3989 /* Don't check this while we are reloading, things might still change */
3990 if (MANAGER_IS_RELOADING(m))
3991 return;
3992
cedf5088
LP
3993 /* The journal is fully and entirely up? If so, let's permit logging to it, if that's configured. If the
3994 * journal is down, don't ever log to it, otherwise we might end up deadlocking ourselves as we might trigger
3995 * an activation ourselves we can't fulfill. */
3996 log_set_prohibit_ipc(!manager_journal_is_running(m));
cc2b9e6b 3997 log_open();
f1dd0c3f
LP
3998}
3999
44a41954
FB
4000static ShowStatus manager_get_show_status(Manager *m) {
4001 assert(m);
4002
4003 if (MANAGER_IS_USER(m))
4004 return _SHOW_STATUS_INVALID;
4005
4006 if (m->show_status_overridden != _SHOW_STATUS_INVALID)
4007 return m->show_status_overridden;
4008
4009 return m->show_status;
4010}
4011
4012bool manager_get_show_status_on(Manager *m) {
4013 assert(m);
4014
4015 return show_status_on(manager_get_show_status(m));
4016}
b309078a 4017
3ceb3471
FB
4018static void set_show_status_marker(bool b) {
4019 if (b)
4020 (void) touch("/run/systemd/show-status");
4021 else
4022 (void) unlink("/run/systemd/show-status");
4023}
4024
44a41954 4025void manager_set_show_status(Manager *m, ShowStatus mode, const char *reason) {
27d340c7 4026 assert(m);
44a41954 4027 assert(reason);
0d066dd1 4028 assert(mode >= 0 && mode < _SHOW_STATUS_MAX);
27d340c7 4029
44a41954 4030 if (MANAGER_IS_USER(m))
27d340c7
LP
4031 return;
4032
ef15d3e1
ZJS
4033 if (mode == m->show_status)
4034 return;
4035
44a41954
FB
4036 if (m->show_status_overridden == _SHOW_STATUS_INVALID) {
4037 bool enabled;
4038
4039 enabled = show_status_on(mode);
4040 log_debug("%s (%s) showing of status (%s).",
4041 enabled ? "Enabling" : "Disabling",
4042 strna(show_status_to_string(mode)),
4043 reason);
4044
3ceb3471 4045 set_show_status_marker(enabled);
44a41954
FB
4046 }
4047
4048 m->show_status = mode;
4049}
4050
43bba15a 4051void manager_override_show_status(Manager *m, ShowStatus mode, const char *reason) {
44a41954
FB
4052 assert(m);
4053 assert(mode < _SHOW_STATUS_MAX);
4054
4055 if (MANAGER_IS_USER(m))
4056 return;
4057
4058 if (mode == m->show_status_overridden)
4059 return;
4060
4061 m->show_status_overridden = mode;
4062
4063 if (mode == _SHOW_STATUS_INVALID)
4064 mode = m->show_status;
4065
ef15d3e1 4066 log_debug("%s (%s) showing of status (%s).",
44a41954 4067 m->show_status_overridden != _SHOW_STATUS_INVALID ? "Overriding" : "Restoring",
ef15d3e1
ZJS
4068 strna(show_status_to_string(mode)),
4069 reason);
b309078a 4070
3ceb3471 4071 set_show_status_marker(show_status_on(mode));
27d340c7
LP
4072}
4073
7d5ceb64
FB
4074const char *manager_get_confirm_spawn(Manager *m) {
4075 static int last_errno = 0;
7d5ceb64
FB
4076 struct stat st;
4077 int r;
4078
ea758432
LP
4079 assert(m);
4080
7d5ceb64
FB
4081 /* Here's the deal: we want to test the validity of the console but don't want
4082 * PID1 to go through the whole console process which might block. But we also
4083 * want to warn the user only once if something is wrong with the console so we
4084 * cannot do the sanity checks after spawning our children. So here we simply do
4085 * really basic tests to hopefully trap common errors.
4086 *
4087 * If the console suddenly disappear at the time our children will really it
4088 * then they will simply fail to acquire it and a positive answer will be
2aed63f4 4089 * assumed. New children will fall back to /dev/console though.
7d5ceb64
FB
4090 *
4091 * Note: TTYs are devices that can come and go any time, and frequently aren't
4092 * available yet during early boot (consider a USB rs232 dongle...). If for any
2aed63f4 4093 * reason the configured console is not ready, we fall back to the default
7d5ceb64
FB
4094 * console. */
4095
ea758432
LP
4096 if (!m->confirm_spawn || path_equal(m->confirm_spawn, "/dev/console"))
4097 return m->confirm_spawn;
7d5ceb64 4098
ea758432
LP
4099 if (stat(m->confirm_spawn, &st) < 0) {
4100 r = -errno;
7d5ceb64 4101 goto fail;
ea758432 4102 }
7d5ceb64
FB
4103
4104 if (!S_ISCHR(st.st_mode)) {
ea758432 4105 r = -ENOTTY;
7d5ceb64
FB
4106 goto fail;
4107 }
4108
4109 last_errno = 0;
ea758432
LP
4110 return m->confirm_spawn;
4111
7d5ceb64 4112fail:
ea758432
LP
4113 if (last_errno != r)
4114 last_errno = log_warning_errno(r, "Failed to open %s, using default console: %m", m->confirm_spawn);
4115
7d5ceb64
FB
4116 return "/dev/console";
4117}
4118
e2680723
LP
4119void manager_set_first_boot(Manager *m, bool b) {
4120 assert(m);
4121
463d0d15 4122 if (!MANAGER_IS_SYSTEM(m))
e2680723
LP
4123 return;
4124
ae2a2c53
LP
4125 if (m->first_boot != (int) b) {
4126 if (b)
4127 (void) touch("/run/systemd/first-boot");
4128 else
4129 (void) unlink("/run/systemd/first-boot");
4130 }
e2680723 4131
ae2a2c53 4132 m->first_boot = b;
e2680723
LP
4133}
4134
b0eb2944
FB
4135void manager_disable_confirm_spawn(void) {
4136 (void) touch("/run/systemd/confirm_spawn_disabled");
4137}
4138
4139bool manager_is_confirm_spawn_disabled(Manager *m) {
4140 if (!m->confirm_spawn)
4141 return true;
4142
4143 return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
4144}
4145
0d6d3cf0
FB
4146static bool manager_should_show_status(Manager *m, StatusType type) {
4147 assert(m);
4148
4149 if (!MANAGER_IS_SYSTEM(m))
4150 return false;
4151
4152 if (m->no_console_output)
4153 return false;
4154
4155 if (!IN_SET(manager_state(m), MANAGER_INITIALIZING, MANAGER_STARTING, MANAGER_STOPPING))
4156 return false;
4157
4158 /* If we cannot find out the status properly, just proceed. */
4159 if (type != STATUS_TYPE_EMERGENCY && manager_check_ask_password(m) > 0)
4160 return false;
4161
4162 if (type == STATUS_TYPE_NOTICE && m->show_status != SHOW_STATUS_NO)
4163 return true;
4164
44a41954 4165 return manager_get_show_status_on(m);
0d6d3cf0
FB
4166}
4167
127d5fd1 4168void manager_status_printf(Manager *m, StatusType type, const char *status, const char *format, ...) {
25cee550
MS
4169 va_list ap;
4170
cb6531be
ZJS
4171 /* If m is NULL, assume we're after shutdown and let the messages through. */
4172
0d6d3cf0 4173 if (m && !manager_should_show_status(m, type))
25cee550
MS
4174 return;
4175
03b717a3
MS
4176 /* XXX We should totally drop the check for ephemeral here
4177 * and thus effectively make 'Type=idle' pointless. */
cb6531be 4178 if (type == STATUS_TYPE_EPHEMERAL && m && m->n_on_console > 0)
03b717a3
MS
4179 return;
4180
25cee550 4181 va_start(ap, format);
a885727a 4182 status_vprintf(status, SHOW_STATUS_ELLIPSIZE|(type == STATUS_TYPE_EPHEMERAL ? SHOW_STATUS_EPHEMERAL : 0), format, ap);
25cee550
MS
4183 va_end(ap);
4184}
4185
ac19bdd0 4186Set* manager_get_units_requiring_mounts_for(Manager *m, const char *path) {
a57f7e2c
LP
4187 assert(m);
4188 assert(path);
4189
ac19bdd0
ZJS
4190 if (path_equal(path, "/"))
4191 path = "";
a57f7e2c 4192
ac19bdd0 4193 return hashmap_get(m->units_requiring_mounts_for, path);
a57f7e2c 4194}
e66cf1a3 4195
5269eb6b 4196int manager_update_failed_units(Manager *m, Unit *u, bool failed) {
03455c28 4197 unsigned size;
5269eb6b 4198 int r;
03455c28
LDM
4199
4200 assert(m);
4201 assert(u->manager == m);
4202
4203 size = set_size(m->failed_units);
4204
9fff8981 4205 if (failed) {
de7fef4b 4206 r = set_ensure_put(&m->failed_units, NULL, u);
5269eb6b
LP
4207 if (r < 0)
4208 return log_oom();
9fff8981 4209 } else
5269eb6b 4210 (void) set_remove(m->failed_units, u);
03455c28
LDM
4211
4212 if (set_size(m->failed_units) != size)
4213 bus_manager_send_change_signal(m);
5269eb6b
LP
4214
4215 return 0;
03455c28
LDM
4216}
4217
f755e3b7
LP
4218ManagerState manager_state(Manager *m) {
4219 Unit *u;
4220
4221 assert(m);
4222
f9d29f6d
JB
4223 /* Is the special shutdown target active or queued? If so, we are in shutdown state */
4224 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
4225 if (u && unit_active_or_pending(u))
4226 return MANAGER_STOPPING;
4227
f755e3b7 4228 /* Did we ever finish booting? If not then we are still starting up */
49d5666c 4229 if (!MANAGER_IS_FINISHED(m)) {
d81afec1
LP
4230
4231 u = manager_get_unit(m, SPECIAL_BASIC_TARGET);
4232 if (!u || !UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
4233 return MANAGER_INITIALIZING;
4234
f755e3b7 4235 return MANAGER_STARTING;
d81afec1 4236 }
f755e3b7 4237
45a7b16b
LP
4238 if (MANAGER_IS_SYSTEM(m)) {
4239 /* Are the rescue or emergency targets active or queued? If so we are in maintenance state */
4240 u = manager_get_unit(m, SPECIAL_RESCUE_TARGET);
4241 if (u && unit_active_or_pending(u))
4242 return MANAGER_MAINTENANCE;
f755e3b7 4243
45a7b16b
LP
4244 u = manager_get_unit(m, SPECIAL_EMERGENCY_TARGET);
4245 if (u && unit_active_or_pending(u))
4246 return MANAGER_MAINTENANCE;
4247 }
f755e3b7
LP
4248
4249 /* Are there any failed units? If so, we are in degraded mode */
4250 if (set_size(m->failed_units) > 0)
4251 return MANAGER_DEGRADED;
4252
4253 return MANAGER_RUNNING;
4254}
4255
00d9ef85 4256static void manager_unref_uid_internal(
010becd9 4257 Hashmap *uid_refs,
00d9ef85
LP
4258 uid_t uid,
4259 bool destroy_now,
4260 int (*_clean_ipc)(uid_t uid)) {
4261
4262 uint32_t c, n;
4263
00d9ef85
LP
4264 assert(uid_is_valid(uid));
4265 assert(_clean_ipc);
4266
4267 /* A generic implementation, covering both manager_unref_uid() and manager_unref_gid(), under the assumption
4268 * that uid_t and gid_t are actually defined the same way, with the same validity rules.
4269 *
827d1ba7 4270 * We store a hashmap where the key is the UID/GID and the value is a 32bit reference counter, whose highest
00d9ef85
LP
4271 * bit is used as flag for marking UIDs/GIDs whose IPC objects to remove when the last reference to the UID/GID
4272 * is dropped. The flag is set to on, once at least one reference from a unit where RemoveIPC= is set is added
4273 * on a UID/GID. It is reset when the UID's/GID's reference counter drops to 0 again. */
4274
4275 assert_cc(sizeof(uid_t) == sizeof(gid_t));
4276 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
4277
4278 if (uid == 0) /* We don't keep track of root, and will never destroy it */
4279 return;
4280
010becd9 4281 c = PTR_TO_UINT32(hashmap_get(uid_refs, UID_TO_PTR(uid)));
00d9ef85
LP
4282
4283 n = c & ~DESTROY_IPC_FLAG;
4284 assert(n > 0);
4285 n--;
4286
4287 if (destroy_now && n == 0) {
010becd9 4288 hashmap_remove(uid_refs, UID_TO_PTR(uid));
00d9ef85
LP
4289
4290 if (c & DESTROY_IPC_FLAG) {
4291 log_debug("%s " UID_FMT " is no longer referenced, cleaning up its IPC.",
4292 _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4293 uid);
4294 (void) _clean_ipc(uid);
4295 }
4296 } else {
4297 c = n | (c & DESTROY_IPC_FLAG);
010becd9 4298 assert_se(hashmap_update(uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c)) >= 0);
00d9ef85
LP
4299 }
4300}
4301
4302void manager_unref_uid(Manager *m, uid_t uid, bool destroy_now) {
010becd9 4303 manager_unref_uid_internal(m->uid_refs, uid, destroy_now, clean_ipc_by_uid);
00d9ef85
LP
4304}
4305
4306void manager_unref_gid(Manager *m, gid_t gid, bool destroy_now) {
010becd9 4307 manager_unref_uid_internal(m->gid_refs, (uid_t) gid, destroy_now, clean_ipc_by_gid);
00d9ef85
LP
4308}
4309
4310static int manager_ref_uid_internal(
00d9ef85
LP
4311 Hashmap **uid_refs,
4312 uid_t uid,
4313 bool clean_ipc) {
4314
4315 uint32_t c, n;
4316 int r;
4317
00d9ef85
LP
4318 assert(uid_refs);
4319 assert(uid_is_valid(uid));
4320
4321 /* A generic implementation, covering both manager_ref_uid() and manager_ref_gid(), under the assumption
4322 * that uid_t and gid_t are actually defined the same way, with the same validity rules. */
4323
4324 assert_cc(sizeof(uid_t) == sizeof(gid_t));
4325 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
4326
4327 if (uid == 0) /* We don't keep track of root, and will never destroy it */
4328 return 0;
4329
4330 r = hashmap_ensure_allocated(uid_refs, &trivial_hash_ops);
4331 if (r < 0)
4332 return r;
4333
4334 c = PTR_TO_UINT32(hashmap_get(*uid_refs, UID_TO_PTR(uid)));
4335
4336 n = c & ~DESTROY_IPC_FLAG;
4337 n++;
4338
4339 if (n & DESTROY_IPC_FLAG) /* check for overflow */
4340 return -EOVERFLOW;
4341
4342 c = n | (c & DESTROY_IPC_FLAG) | (clean_ipc ? DESTROY_IPC_FLAG : 0);
4343
4344 return hashmap_replace(*uid_refs, UID_TO_PTR(uid), UINT32_TO_PTR(c));
4345}
4346
4347int manager_ref_uid(Manager *m, uid_t uid, bool clean_ipc) {
010becd9 4348 return manager_ref_uid_internal(&m->uid_refs, uid, clean_ipc);
00d9ef85
LP
4349}
4350
4351int manager_ref_gid(Manager *m, gid_t gid, bool clean_ipc) {
010becd9 4352 return manager_ref_uid_internal(&m->gid_refs, (uid_t) gid, clean_ipc);
00d9ef85
LP
4353}
4354
4355static void manager_vacuum_uid_refs_internal(
010becd9 4356 Hashmap *uid_refs,
00d9ef85
LP
4357 int (*_clean_ipc)(uid_t uid)) {
4358
00d9ef85
LP
4359 void *p, *k;
4360
00d9ef85
LP
4361 assert(_clean_ipc);
4362
010becd9 4363 HASHMAP_FOREACH_KEY(p, k, uid_refs) {
00d9ef85
LP
4364 uint32_t c, n;
4365 uid_t uid;
4366
4367 uid = PTR_TO_UID(k);
4368 c = PTR_TO_UINT32(p);
4369
4370 n = c & ~DESTROY_IPC_FLAG;
4371 if (n > 0)
4372 continue;
4373
4374 if (c & DESTROY_IPC_FLAG) {
4375 log_debug("Found unreferenced %s " UID_FMT " after reload/reexec. Cleaning up.",
4376 _clean_ipc == clean_ipc_by_uid ? "UID" : "GID",
4377 uid);
4378 (void) _clean_ipc(uid);
4379 }
4380
010becd9 4381 assert_se(hashmap_remove(uid_refs, k) == p);
00d9ef85
LP
4382 }
4383}
4384
06a4eb07 4385static void manager_vacuum_uid_refs(Manager *m) {
010becd9 4386 manager_vacuum_uid_refs_internal(m->uid_refs, clean_ipc_by_uid);
00d9ef85
LP
4387}
4388
06a4eb07 4389static void manager_vacuum_gid_refs(Manager *m) {
010becd9 4390 manager_vacuum_uid_refs_internal(m->gid_refs, clean_ipc_by_gid);
00d9ef85
LP
4391}
4392
06a4eb07
FB
4393static void manager_vacuum(Manager *m) {
4394 assert(m);
4395
4396 /* Release any dynamic users no longer referenced */
4397 dynamic_user_vacuum(m, true);
4398
4399 /* Release any references to UIDs/GIDs no longer referenced, and destroy any IPC owned by them */
4400 manager_vacuum_uid_refs(m);
4401 manager_vacuum_gid_refs(m);
4402
4403 /* Release any runtimes no longer referenced */
4404 exec_runtime_vacuum(m);
4405}
4406
00d9ef85
LP
4407int manager_dispatch_user_lookup_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
4408 struct buffer {
4409 uid_t uid;
4410 gid_t gid;
4411 char unit_name[UNIT_NAME_MAX+1];
4412 } _packed_ buffer;
4413
4414 Manager *m = userdata;
4415 ssize_t l;
4416 size_t n;
4417 Unit *u;
4418
4419 assert_se(source);
4420 assert_se(m);
4421
4422 /* Invoked whenever a child process succeeded resolving its user/group to use and sent us the resulting UID/GID
4423 * in a datagram. We parse the datagram here and pass it off to the unit, so that it can add a reference to the
4424 * UID/GID so that it can destroy the UID/GID's IPC objects when the reference counter drops to 0. */
4425
4426 l = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
4427 if (l < 0) {
8add30a0 4428 if (ERRNO_IS_TRANSIENT(errno))
00d9ef85
LP
4429 return 0;
4430
4431 return log_error_errno(errno, "Failed to read from user lookup fd: %m");
4432 }
4433
4434 if ((size_t) l <= offsetof(struct buffer, unit_name)) {
4435 log_warning("Received too short user lookup message, ignoring.");
4436 return 0;
4437 }
4438
4439 if ((size_t) l > offsetof(struct buffer, unit_name) + UNIT_NAME_MAX) {
4440 log_warning("Received too long user lookup message, ignoring.");
4441 return 0;
4442 }
4443
4444 if (!uid_is_valid(buffer.uid) && !gid_is_valid(buffer.gid)) {
4445 log_warning("Got user lookup message with invalid UID/GID pair, ignoring.");
4446 return 0;
4447 }
4448
4449 n = (size_t) l - offsetof(struct buffer, unit_name);
4450 if (memchr(buffer.unit_name, 0, n)) {
4451 log_warning("Received lookup message with embedded NUL character, ignoring.");
4452 return 0;
4453 }
4454
4455 buffer.unit_name[n] = 0;
4456 u = manager_get_unit(m, buffer.unit_name);
4457 if (!u) {
4458 log_debug("Got user lookup message but unit doesn't exist, ignoring.");
4459 return 0;
4460 }
4461
4462 log_unit_debug(u, "User lookup succeeded: uid=" UID_FMT " gid=" GID_FMT, buffer.uid, buffer.gid);
4463
4464 unit_notify_user_lookup(u, buffer.uid, buffer.gid);
4465 return 0;
4466}
4467
63e8df04
LP
4468static int short_uid_range(const char *path) {
4469 _cleanup_free_ UidRange *p = NULL;
4470 size_t n = 0;
4471 int r;
4472
4473 assert(path);
4474
4475 /* Taint systemd if we the UID range assigned to this environment doesn't at least cover 0…65534,
4476 * i.e. from root to nobody. */
4477
4478 r = uid_range_load_userns(&p, &n, path);
4479 if (ERRNO_IS_NOT_SUPPORTED(r))
4480 return false;
4481 if (r < 0)
4482 return log_debug_errno(r, "Failed to load %s: %m", path);
4483
4484 return !uid_range_covers(p, n, 0, 65535);
4485}
4486
83fe5d8a
ZJS
4487char* manager_taint_string(const Manager *m) {
4488 /* Returns a "taint string", e.g. "local-hwclock:var-run-bad". Only things that are detected at
4489 * runtime should be tagged here. For stuff that is known during compilation, emit a warning in the
63e8df04 4490 * configuration phase. */
198ce932 4491
af6b0ecc
LP
4492 assert(m);
4493
4bd03515 4494 const char* stage[13] = {};
83fe5d8a 4495 size_t n = 0;
af6b0ecc
LP
4496
4497 if (m->taint_usr)
83fe5d8a 4498 stage[n++] = "split-usr";
af6b0ecc 4499
31cd2dd9
LB
4500 _cleanup_free_ char *usrbin = NULL;
4501 if (readlink_malloc("/bin", &usrbin) < 0 || !PATH_IN_SET(usrbin, "usr/bin", "/usr/bin"))
4502 stage[n++] = "unmerged-usr";
4503
af6b0ecc 4504 if (access("/proc/cgroups", F_OK) < 0)
83fe5d8a 4505 stage[n++] = "cgroups-missing";
af6b0ecc 4506
82f30632 4507 if (cg_all_unified() == 0)
83fe5d8a 4508 stage[n++] = "cgroupsv1";
82f30632 4509
af6b0ecc 4510 if (clock_is_localtime(NULL) > 0)
83fe5d8a 4511 stage[n++] = "local-hwclock";
af6b0ecc 4512
4bd03515
ZJS
4513 if (os_release_support_ended(NULL, true) > 0)
4514 stage[n++] = "support-ended";
4515
83fe5d8a
ZJS
4516 _cleanup_free_ char *destination = NULL;
4517 if (readlink_malloc("/var/run", &destination) < 0 ||
4518 !PATH_IN_SET(destination, "../run", "/run"))
4519 stage[n++] = "var-run-bad";
af6b0ecc 4520
83fe5d8a
ZJS
4521 _cleanup_free_ char *overflowuid = NULL, *overflowgid = NULL;
4522 if (read_one_line_file("/proc/sys/kernel/overflowuid", &overflowuid) >= 0 &&
4523 !streq(overflowuid, "65534"))
4524 stage[n++] = "overflowuid-not-65534";
4525 if (read_one_line_file("/proc/sys/kernel/overflowgid", &overflowgid) >= 0 &&
4526 !streq(overflowgid, "65534"))
4527 stage[n++] = "overflowgid-not-65534";
90d7464d 4528
83fe5d8a 4529 struct utsname uts;
40efaaed
LP
4530 assert_se(uname(&uts) >= 0);
4531 if (strverscmp_improved(uts.release, KERNEL_BASELINE_VERSION) < 0)
83fe5d8a 4532 stage[n++] = "old-kernel";
40efaaed 4533
63e8df04 4534 if (short_uid_range("/proc/self/uid_map") > 0)
83fe5d8a 4535 stage[n++] = "short-uid-range";
63e8df04 4536 if (short_uid_range("/proc/self/gid_map") > 0)
83fe5d8a 4537 stage[n++] = "short-gid-range";
63e8df04 4538
83fe5d8a 4539 assert(n < ELEMENTSOF(stage) - 1); /* One extra for NULL terminator */
af6b0ecc 4540
83fe5d8a 4541 return strv_join((char**) stage, ":");
af6b0ecc
LP
4542}
4543
adefcf28
LP
4544void manager_ref_console(Manager *m) {
4545 assert(m);
4546
4547 m->n_on_console++;
4548}
4549
4550void manager_unref_console(Manager *m) {
4551
4552 assert(m->n_on_console > 0);
4553 m->n_on_console--;
4554
4555 if (m->n_on_console == 0)
4556 m->no_console_output = false; /* unset no_console_output flag, since the console is definitely free now */
4557}
4558
a6ecbf83
FB
4559void manager_override_log_level(Manager *m, int level) {
4560 _cleanup_free_ char *s = NULL;
4561 assert(m);
4562
4563 if (!m->log_level_overridden) {
4564 m->original_log_level = log_get_max_level();
4565 m->log_level_overridden = true;
4566 }
4567
4568 (void) log_level_to_string_alloc(level, &s);
4569 log_info("Setting log level to %s.", strna(s));
4570
4571 log_set_max_level(level);
4572}
4573
4574void manager_restore_original_log_level(Manager *m) {
4575 _cleanup_free_ char *s = NULL;
4576 assert(m);
4577
4578 if (!m->log_level_overridden)
4579 return;
4580
4581 (void) log_level_to_string_alloc(m->original_log_level, &s);
4582 log_info("Restoring log level to original (%s).", strna(s));
4583
4584 log_set_max_level(m->original_log_level);
4585 m->log_level_overridden = false;
4586}
4587
bda7d78b
FB
4588void manager_override_log_target(Manager *m, LogTarget target) {
4589 assert(m);
4590
4591 if (!m->log_target_overridden) {
4592 m->original_log_target = log_get_target();
4593 m->log_target_overridden = true;
4594 }
4595
4596 log_info("Setting log target to %s.", log_target_to_string(target));
4597 log_set_target(target);
4598}
4599
4600void manager_restore_original_log_target(Manager *m) {
4601 assert(m);
4602
4603 if (!m->log_target_overridden)
4604 return;
4605
4606 log_info("Restoring log target to original %s.", log_target_to_string(m->original_log_target));
4607
4608 log_set_target(m->original_log_target);
4609 m->log_target_overridden = false;
4610}
4611
d4ee7bd8
YW
4612ManagerTimestamp manager_timestamp_initrd_mangle(ManagerTimestamp s) {
4613 if (in_initrd() &&
4614 s >= MANAGER_TIMESTAMP_SECURITY_START &&
4615 s <= MANAGER_TIMESTAMP_UNITS_LOAD_FINISH)
4616 return s - MANAGER_TIMESTAMP_SECURITY_START + MANAGER_TIMESTAMP_INITRD_SECURITY_START;
4617 return s;
4618}
4619
f755e3b7 4620static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
d81afec1 4621 [MANAGER_INITIALIZING] = "initializing",
48d83e33
ZJS
4622 [MANAGER_STARTING] = "starting",
4623 [MANAGER_RUNNING] = "running",
4624 [MANAGER_DEGRADED] = "degraded",
4625 [MANAGER_MAINTENANCE] = "maintenance",
4626 [MANAGER_STOPPING] = "stopping",
f755e3b7
LP
4627};
4628
4629DEFINE_STRING_TABLE_LOOKUP(manager_state, ManagerState);
9f9f0342
LP
4630
4631static const char *const manager_timestamp_table[_MANAGER_TIMESTAMP_MAX] = {
48d83e33
ZJS
4632 [MANAGER_TIMESTAMP_FIRMWARE] = "firmware",
4633 [MANAGER_TIMESTAMP_LOADER] = "loader",
4634 [MANAGER_TIMESTAMP_KERNEL] = "kernel",
4635 [MANAGER_TIMESTAMP_INITRD] = "initrd",
4636 [MANAGER_TIMESTAMP_USERSPACE] = "userspace",
4637 [MANAGER_TIMESTAMP_FINISH] = "finish",
4638 [MANAGER_TIMESTAMP_SECURITY_START] = "security-start",
4639 [MANAGER_TIMESTAMP_SECURITY_FINISH] = "security-finish",
4640 [MANAGER_TIMESTAMP_GENERATORS_START] = "generators-start",
4641 [MANAGER_TIMESTAMP_GENERATORS_FINISH] = "generators-finish",
4642 [MANAGER_TIMESTAMP_UNITS_LOAD_START] = "units-load-start",
4643 [MANAGER_TIMESTAMP_UNITS_LOAD_FINISH] = "units-load-finish",
49fbe940 4644 [MANAGER_TIMESTAMP_UNITS_LOAD] = "units-load",
48d83e33
ZJS
4645 [MANAGER_TIMESTAMP_INITRD_SECURITY_START] = "initrd-security-start",
4646 [MANAGER_TIMESTAMP_INITRD_SECURITY_FINISH] = "initrd-security-finish",
4647 [MANAGER_TIMESTAMP_INITRD_GENERATORS_START] = "initrd-generators-start",
d4ee7bd8 4648 [MANAGER_TIMESTAMP_INITRD_GENERATORS_FINISH] = "initrd-generators-finish",
48d83e33 4649 [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_START] = "initrd-units-load-start",
d4ee7bd8 4650 [MANAGER_TIMESTAMP_INITRD_UNITS_LOAD_FINISH] = "initrd-units-load-finish",
9f9f0342
LP
4651};
4652
4653DEFINE_STRING_TABLE_LOOKUP(manager_timestamp, ManagerTimestamp);
afcfaa69
LP
4654
4655static const char* const oom_policy_table[_OOM_POLICY_MAX] = {
4656 [OOM_CONTINUE] = "continue",
48d83e33
ZJS
4657 [OOM_STOP] = "stop",
4658 [OOM_KILL] = "kill",
afcfaa69
LP
4659};
4660
4661DEFINE_STRING_TABLE_LOOKUP(oom_policy, OOMPolicy);