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