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