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