]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/manager.c
nspawn: allow passing socket activation fds through nspawn
[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
LP
22#include <assert.h>
23#include <errno.h>
87d1515d 24#include <string.h>
9152c765
LP
25#include <sys/epoll.h>
26#include <signal.h>
27#include <sys/signalfd.h>
28#include <sys/wait.h>
29#include <unistd.h>
30#include <sys/poll.h>
e1414003
LP
31#include <sys/reboot.h>
32#include <sys/ioctl.h>
33#include <linux/kd.h>
80876c20
LP
34#include <termios.h>
35#include <fcntl.h>
a16e1123
LP
36#include <sys/types.h>
37#include <sys/stat.h>
fe51822e 38#include <dirent.h>
8742514c 39#include <sys/timerfd.h>
830f6caa
LP
40
41#ifdef HAVE_AUDIT
4927fcae 42#include <libaudit.h>
830f6caa 43#endif
60918275 44
877d54e9
LP
45#include "systemd/sd-daemon.h"
46#include "systemd/sd-id128.h"
47#include "systemd/sd-messages.h"
81527be1 48
60918275 49#include "manager.h"
75778e21 50#include "transaction.h"
60918275
LP
51#include "hashmap.h"
52#include "macro.h"
53#include "strv.h"
16354eff 54#include "log.h"
2a987ee8 55#include "util.h"
49e942b2 56#include "mkdir.h"
ea430986 57#include "ratelimit.h"
8e274523
LP
58#include "cgroup.h"
59#include "mount-setup.h"
9e2f7c11 60#include "unit-name.h"
4139c1b2
LP
61#include "dbus-unit.h"
62#include "dbus-job.h"
1137a57c 63#include "missing.h"
84e3543e 64#include "path-lookup.h"
514f4ef5 65#include "special.h"
398ef8ba 66#include "bus-errors.h"
d06dacd0 67#include "exit-status.h"
5dc4c17f 68#include "virt.h"
e96d6be7 69#include "watchdog.h"
b59e2465 70#include "cgroup-util.h"
9eb977db 71#include "path-util.h"
c1165f82 72#include "audit-fd.h"
60918275 73
701cc384
LP
74/* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
75#define GC_QUEUE_ENTRIES_MAX 16
76
77/* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
94b6dfa2 78#define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
701cc384 79
8c47c732 80/* Where clients shall send notification messages to */
29252e9e 81#define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
8c47c732
LP
82
83static int manager_setup_notify(Manager *m) {
84 union {
85 struct sockaddr sa;
86 struct sockaddr_un un;
87 } sa;
88 struct epoll_event ev;
29252e9e 89 int one = 1;
8c47c732
LP
90
91 assert(m);
92
93 m->notify_watch.type = WATCH_NOTIFY;
29252e9e
LP
94 m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
95 if (m->notify_watch.fd < 0) {
8c47c732
LP
96 log_error("Failed to allocate notification socket: %m");
97 return -errno;
98 }
99
100 zero(sa);
101 sa.sa.sa_family = AF_UNIX;
102
31f92a7d 103 if (getpid() != 1 || detect_container(NULL) > 0)
29252e9e
LP
104 snprintf(sa.un.sun_path, sizeof(sa.un.sun_path), NOTIFY_SOCKET "/%llu", random_ull());
105 else
106 strncpy(sa.un.sun_path, NOTIFY_SOCKET, sizeof(sa.un.sun_path));
8c47c732 107
29252e9e 108 sa.un.sun_path[0] = 0;
1d6702e8 109
29252e9e 110 if (bind(m->notify_watch.fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
8c47c732
LP
111 log_error("bind() failed: %m");
112 return -errno;
113 }
114
115 if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
116 log_error("SO_PASSCRED failed: %m");
117 return -errno;
118 }
119
120 zero(ev);
121 ev.events = EPOLLIN;
122 ev.data.ptr = &m->notify_watch;
123
8742514c
LP
124 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0) {
125 log_error("Failed to add timer change fd to epoll: %m");
8c47c732 126 return -errno;
8742514c 127 }
8c47c732 128
29252e9e
LP
129 sa.un.sun_path[0] = '@';
130 m->notify_socket = strdup(sa.un.sun_path);
131 if (!m->notify_socket)
8742514c 132 return log_oom();
8c47c732 133
b2bb3dbe
LP
134 log_debug("Using notification socket %s", m->notify_socket);
135
8c47c732
LP
136 return 0;
137}
138
8742514c
LP
139static int manager_setup_time_change(Manager *m) {
140 struct epoll_event ev;
141 struct itimerspec its;
142
143 assert(m);
144 assert(m->time_change_watch.type == WATCH_INVALID);
145
146 /* Uses TFD_TIMER_CANCEL_ON_SET to get notifications whenever
147 * CLOCK_REALTIME makes a jump relative to CLOCK_MONOTONIC */
148
149 m->time_change_watch.type = WATCH_TIME_CHANGE;
150 m->time_change_watch.fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
151 if (m->time_change_watch.fd < 0) {
152 log_error("Failed to create timerfd: %m");
153 return -errno;
154 }
155
156 zero(its);
8a3a1704
LP
157
158 /* We only care for the cancellation event, hence we set the
159 * timeout to the latest possible value. */
160 assert_cc(sizeof(time_t) == sizeof(long));
161 its.it_value.tv_sec = LONG_MAX;
162
8742514c
LP
163 if (timerfd_settime(m->time_change_watch.fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
164 log_debug("Failed to set up TFD_TIMER_CANCEL_ON_SET, ignoring: %m");
165 close_nointr_nofail(m->time_change_watch.fd);
166 watch_init(&m->time_change_watch);
167 return 0;
168 }
169
170 zero(ev);
171 ev.events = EPOLLIN;
172 ev.data.ptr = &m->time_change_watch;
173
174 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->time_change_watch.fd, &ev) < 0) {
175 log_error("Failed to add timer change fd to epoll: %m");
176 return -errno;
177 }
178
179 log_debug("Set up TFD_TIMER_CANCEL_ON_SET timerfd.");
180
181 return 0;
182}
183
80876c20 184static int enable_special_signals(Manager *m) {
4466ee6a 185 int fd;
80876c20
LP
186
187 assert(m);
188
a41b539e 189 /* Enable that we get SIGINT on control-alt-del. In containers
c9999773
LP
190 * this will fail with EPERM (older) or EINVAL (newer), so
191 * ignore that. */
192 if (reboot(RB_DISABLE_CAD) < 0 && errno != EPERM && errno != EINVAL)
80876c20
LP
193 log_warning("Failed to enable ctrl-alt-del handling: %m");
194
a41b539e
LP
195 fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
196 if (fd < 0) {
197 /* Support systems without virtual console */
198 if (fd != -ENOENT)
199 log_warning("Failed to open /dev/tty0: %m");
200 } else {
80876c20
LP
201 /* Enable that we get SIGWINCH on kbrequest */
202 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
203 log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
204
205 close_nointr_nofail(fd);
206 }
207
208 return 0;
209}
210
ce578209 211static int manager_setup_signals(Manager *m) {
9152c765
LP
212 sigset_t mask;
213 struct epoll_event ev;
57c0c30e 214 struct sigaction sa;
60918275 215
ce578209
LP
216 assert(m);
217
57c0c30e
LP
218 /* We are not interested in SIGSTOP and friends. */
219 zero(sa);
220 sa.sa_handler = SIG_DFL;
221 sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
222 assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
223
ce578209 224 assert_se(sigemptyset(&mask) == 0);
7d793605
LP
225
226 sigset_add_many(&mask,
227 SIGCHLD, /* Child died */
228 SIGTERM, /* Reexecute daemon */
229 SIGHUP, /* Reload configuration */
230 SIGUSR1, /* systemd/upstart: reconnect to D-Bus */
231 SIGUSR2, /* systemd: dump status */
232 SIGINT, /* Kernel sends us this on control-alt-del */
233 SIGWINCH, /* Kernel sends us this on kbrequest (alt-arrowup) */
234 SIGPWR, /* Some kernel drivers and upsd send us this on power failure */
235 SIGRTMIN+0, /* systemd: start default.target */
0003d1ab 236 SIGRTMIN+1, /* systemd: isolate rescue.target */
7d793605
LP
237 SIGRTMIN+2, /* systemd: isolate emergency.target */
238 SIGRTMIN+3, /* systemd: start halt.target */
239 SIGRTMIN+4, /* systemd: start poweroff.target */
240 SIGRTMIN+5, /* systemd: start reboot.target */
0003d1ab
LP
241 SIGRTMIN+6, /* systemd: start kexec.target */
242 SIGRTMIN+13, /* systemd: Immediate halt */
243 SIGRTMIN+14, /* systemd: Immediate poweroff */
244 SIGRTMIN+15, /* systemd: Immediate reboot */
245 SIGRTMIN+16, /* systemd: Immediate kexec */
0658666b
LP
246 SIGRTMIN+20, /* systemd: enable status messages */
247 SIGRTMIN+21, /* systemd: disable status messages */
253ee27a
LP
248 SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
249 SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
600b704e 250 SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
4cfa2c99 251 SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
253ee27a
LP
252 SIGRTMIN+27, /* systemd: set log target to console */
253 SIGRTMIN+28, /* systemd: set log target to kmsg */
254 SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg */
7d793605 255 -1);
ce578209
LP
256 assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
257
ef734fd6 258 m->signal_watch.type = WATCH_SIGNAL;
8742514c
LP
259 m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
260 if (m->signal_watch.fd < 0)
ce578209
LP
261 return -errno;
262
263 zero(ev);
264 ev.events = EPOLLIN;
265 ev.data.ptr = &m->signal_watch;
266
267 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
268 return -errno;
269
67445f4e 270 if (m->running_as == SYSTEMD_SYSTEM)
80876c20 271 return enable_special_signals(m);
e1414003 272
ce578209
LP
273 return 0;
274}
275
71ecc858
LP
276static void manager_strip_environment(Manager *m) {
277 assert(m);
278
279 /* Remove variables from the inherited set that are part of
280 * the container interface:
281 * http://www.freedesktop.org/wiki/Software/systemd/ContainerInterface */
282 strv_remove_prefix(m->environment, "container=");
283 strv_remove_prefix(m->environment, "container_");
284
285 /* Remove variables from the inherited set that are part of
286 * the initrd interface:
287 * http://www.freedesktop.org/wiki/Software/systemd/InitrdInterface */
288 strv_remove_prefix(m->environment, "RD_");
289}
290
67445f4e 291int manager_new(SystemdRunningAs running_as, Manager **_m) {
ce578209 292 Manager *m;
8e274523
LP
293 int r = -ENOMEM;
294
295 assert(_m);
a5dab5ce 296 assert(running_as >= 0);
67445f4e 297 assert(running_as < _SYSTEMD_RUNNING_AS_MAX);
ce578209 298
915b3753
LP
299 m = new0(Manager, 1);
300 if (!m)
8e274523 301 return -ENOMEM;
60918275 302
915b3753 303 dual_timestamp_get(&m->userspace_timestamp);
e537352b 304
a5dab5ce 305 m->running_as = running_as;
cbd37330 306 m->name_data_slot = m->conn_data_slot = m->subscribed_data_slot = -1;
a16e1123 307 m->exit_code = _MANAGER_EXIT_CODE_INVALID;
33be102a 308 m->pin_cgroupfs_fd = -1;
f2b68789 309 m->idle_pipe[0] = m->idle_pipe[1] = -1;
80876c20 310
8742514c
LP
311 watch_init(&m->signal_watch);
312 watch_init(&m->mount_watch);
313 watch_init(&m->swap_watch);
314 watch_init(&m->udev_watch);
315 watch_init(&m->time_change_watch);
316
317 m->epoll_fd = m->dev_autofs_fd = -1;
ea430986 318 m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
9152c765 319
71ecc858
LP
320 m->environment = strv_copy(environ);
321 if (!m->environment)
1137a57c
LP
322 goto fail;
323
71ecc858
LP
324 manager_strip_environment(m);
325
67445f4e 326 if (running_as == SYSTEMD_SYSTEM) {
88f06645
LP
327 m->default_controllers = strv_new("cpu", NULL);
328 if (!m->default_controllers)
329 goto fail;
330 }
06d4c99a 331
87f0e418 332 if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
60918275
LP
333 goto fail;
334
335 if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
336 goto fail;
337
9152c765
LP
338 if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
339 goto fail;
340
8e274523
LP
341 if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
342 goto fail;
343
05e343b7
LP
344 if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
345 goto fail;
346
8742514c
LP
347 m->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
348 if (m->epoll_fd < 0)
349 goto fail;
350
351 r = manager_setup_signals(m);
352 if (r < 0)
9152c765
LP
353 goto fail;
354
8742514c
LP
355 r = manager_setup_cgroup(m);
356 if (r < 0)
8e274523
LP
357 goto fail;
358
8742514c
LP
359 r = manager_setup_notify(m);
360 if (r < 0)
9152c765
LP
361 goto fail;
362
8742514c
LP
363 r = manager_setup_time_change(m);
364 if (r < 0)
8c47c732
LP
365 goto fail;
366
f278026d 367 /* Try to connect to the busses, if possible. */
8742514c
LP
368 r = bus_init(m, running_as != SYSTEMD_SYSTEM);
369 if (r < 0)
ea430986
LP
370 goto fail;
371
72bc8d00
LP
372 m->taint_usr = dir_is_empty("/usr") > 0;
373
8e274523
LP
374 *_m = m;
375 return 0;
60918275
LP
376
377fail:
378 manager_free(m);
8e274523 379 return r;
60918275
LP
380}
381
23a177ef 382static unsigned manager_dispatch_cleanup_queue(Manager *m) {
595ed347 383 Unit *u;
23a177ef
LP
384 unsigned n = 0;
385
386 assert(m);
387
595ed347
MS
388 while ((u = m->cleanup_queue)) {
389 assert(u->in_cleanup_queue);
23a177ef 390
595ed347 391 unit_free(u);
23a177ef
LP
392 n++;
393 }
394
395 return n;
396}
397
eced69b3 398enum {
35b8ca3a 399 GC_OFFSET_IN_PATH, /* This one is on the path we were traveling */
eced69b3
LP
400 GC_OFFSET_UNSURE, /* No clue */
401 GC_OFFSET_GOOD, /* We still need this unit */
402 GC_OFFSET_BAD, /* We don't need this unit anymore */
403 _GC_OFFSET_MAX
404};
405
406static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
701cc384
LP
407 Iterator i;
408 Unit *other;
eced69b3 409 bool is_bad;
701cc384
LP
410
411 assert(u);
412
ac155bb8
MS
413 if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
414 u->gc_marker == gc_marker + GC_OFFSET_BAD ||
415 u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
701cc384
LP
416 return;
417
ac155bb8 418 if (u->in_cleanup_queue)
701cc384
LP
419 goto bad;
420
421 if (unit_check_gc(u))
422 goto good;
423
ac155bb8 424 u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
eced69b3
LP
425
426 is_bad = true;
427
ac155bb8 428 SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
701cc384
LP
429 unit_gc_sweep(other, gc_marker);
430
ac155bb8 431 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
701cc384 432 goto good;
eced69b3 433
ac155bb8 434 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
eced69b3 435 is_bad = false;
701cc384
LP
436 }
437
eced69b3
LP
438 if (is_bad)
439 goto bad;
440
441 /* We were unable to find anything out about this entry, so
442 * let's investigate it later */
ac155bb8 443 u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
eced69b3
LP
444 unit_add_to_gc_queue(u);
445 return;
446
701cc384 447bad:
eced69b3
LP
448 /* We definitely know that this one is not useful anymore, so
449 * let's mark it for deletion */
ac155bb8 450 u->gc_marker = gc_marker + GC_OFFSET_BAD;
eced69b3 451 unit_add_to_cleanup_queue(u);
701cc384
LP
452 return;
453
454good:
ac155bb8 455 u->gc_marker = gc_marker + GC_OFFSET_GOOD;
701cc384
LP
456}
457
458static unsigned manager_dispatch_gc_queue(Manager *m) {
595ed347 459 Unit *u;
701cc384 460 unsigned n = 0;
eced69b3 461 unsigned gc_marker;
701cc384
LP
462
463 assert(m);
464
465 if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
466 (m->gc_queue_timestamp <= 0 ||
467 (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
468 return 0;
469
470 log_debug("Running GC...");
471
eced69b3
LP
472 m->gc_marker += _GC_OFFSET_MAX;
473 if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
c9c0cadb 474 m->gc_marker = 1;
701cc384 475
eced69b3
LP
476 gc_marker = m->gc_marker;
477
595ed347
MS
478 while ((u = m->gc_queue)) {
479 assert(u->in_gc_queue);
701cc384 480
595ed347 481 unit_gc_sweep(u, gc_marker);
eced69b3 482
595ed347
MS
483 LIST_REMOVE(Unit, gc_queue, m->gc_queue, u);
484 u->in_gc_queue = false;
701cc384
LP
485
486 n++;
487
595ed347
MS
488 if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
489 u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
490 log_debug("Collecting %s", u->id);
491 u->gc_marker = gc_marker + GC_OFFSET_BAD;
492 unit_add_to_cleanup_queue(u);
701cc384
LP
493 }
494 }
495
496 m->n_in_gc_queue = 0;
497 m->gc_queue_timestamp = 0;
498
499 return n;
500}
501
a16e1123 502static void manager_clear_jobs_and_units(Manager *m) {
a16e1123 503 Unit *u;
60918275
LP
504
505 assert(m);
506
87f0e418
LP
507 while ((u = hashmap_first(m->units)))
508 unit_free(u);
964e0949
LP
509
510 manager_dispatch_cleanup_queue(m);
511
512 assert(!m->load_queue);
513 assert(!m->run_queue);
514 assert(!m->dbus_unit_queue);
515 assert(!m->dbus_job_queue);
516 assert(!m->cleanup_queue);
517 assert(!m->gc_queue);
518
964e0949
LP
519 assert(hashmap_isempty(m->jobs));
520 assert(hashmap_isempty(m->units));
a16e1123
LP
521}
522
523void manager_free(Manager *m) {
524 UnitType c;
c93ff2e9 525 int i;
87f0e418 526
a16e1123
LP
527 assert(m);
528
529 manager_clear_jobs_and_units(m);
23a177ef 530
7824bbeb
LP
531 for (c = 0; c < _UNIT_TYPE_MAX; c++)
532 if (unit_vtable[c]->shutdown)
533 unit_vtable[c]->shutdown(m);
534
a16e1123
LP
535 /* If we reexecute ourselves, we keep the root cgroup
536 * around */
c6c18be3 537 manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
8e274523 538
5a1e9937
LP
539 manager_undo_generators(m);
540
5e8d1c9a 541 bus_done(m);
ea430986 542
87f0e418 543 hashmap_free(m->units);
60918275 544 hashmap_free(m->jobs);
9152c765 545 hashmap_free(m->watch_pids);
05e343b7 546 hashmap_free(m->watch_bus);
9152c765
LP
547
548 if (m->epoll_fd >= 0)
a16e1123 549 close_nointr_nofail(m->epoll_fd);
acbb0225 550 if (m->signal_watch.fd >= 0)
a16e1123 551 close_nointr_nofail(m->signal_watch.fd);
8c47c732
LP
552 if (m->notify_watch.fd >= 0)
553 close_nointr_nofail(m->notify_watch.fd);
8742514c
LP
554 if (m->time_change_watch.fd >= 0)
555 close_nointr_nofail(m->time_change_watch.fd);
60918275 556
c952c6ec
LP
557 free(m->notify_socket);
558
84e3543e 559 lookup_paths_free(&m->lookup_paths);
1137a57c 560 strv_free(m->environment);
036643a2 561
06d4c99a
LP
562 strv_free(m->default_controllers);
563
8e274523 564 hashmap_free(m->cgroup_bondings);
c6c18be3 565 set_free_free(m->unit_path_cache);
33be102a 566
f2b68789
LP
567 close_pipe(m->idle_pipe);
568
664f88a7
LP
569 free(m->switch_root);
570 free(m->switch_root_init);
571
c93ff2e9
FC
572 for (i = 0; i < RLIMIT_NLIMITS; i++)
573 free(m->rlimit[i]);
574
60918275
LP
575 free(m);
576}
577
a16e1123
LP
578int manager_enumerate(Manager *m) {
579 int r = 0, q;
f50e0a01 580 UnitType c;
f50e0a01
LP
581
582 assert(m);
583
a16e1123
LP
584 /* Let's ask every type to load all units from disk/kernel
585 * that it might know */
f50e0a01
LP
586 for (c = 0; c < _UNIT_TYPE_MAX; c++)
587 if (unit_vtable[c]->enumerate)
a16e1123
LP
588 if ((q = unit_vtable[c]->enumerate(m)) < 0)
589 r = q;
f50e0a01
LP
590
591 manager_dispatch_load_queue(m);
a16e1123
LP
592 return r;
593}
594
595int manager_coldplug(Manager *m) {
596 int r = 0, q;
597 Iterator i;
598 Unit *u;
599 char *k;
600
601 assert(m);
f50e0a01
LP
602
603 /* Then, let's set up their initial state. */
604 HASHMAP_FOREACH_KEY(u, k, m->units, i) {
605
606 /* ignore aliases */
ac155bb8 607 if (u->id != k)
f50e0a01
LP
608 continue;
609
cca098b0
LP
610 if ((q = unit_coldplug(u)) < 0)
611 r = q;
f50e0a01
LP
612 }
613
a16e1123
LP
614 return r;
615}
616
fe51822e
LP
617static void manager_build_unit_path_cache(Manager *m) {
618 char **i;
619 DIR *d = NULL;
620 int r;
621
622 assert(m);
623
624 set_free_free(m->unit_path_cache);
625
626 if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
627 log_error("Failed to allocate unit path cache.");
628 return;
629 }
630
631 /* This simply builds a list of files we know exist, so that
632 * we don't always have to go to disk */
633
634 STRV_FOREACH(i, m->lookup_paths.unit_path) {
635 struct dirent *de;
636
637 if (!(d = opendir(*i))) {
638 log_error("Failed to open directory: %m");
639 continue;
640 }
641
642 while ((de = readdir(d))) {
643 char *p;
644
645 if (ignore_file(de->d_name))
646 continue;
647
b7def684 648 p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
44d91056 649 if (!p) {
fe51822e
LP
650 r = -ENOMEM;
651 goto fail;
652 }
653
654 if ((r = set_put(m->unit_path_cache, p)) < 0) {
655 free(p);
656 goto fail;
657 }
658 }
659
660 closedir(d);
661 d = NULL;
662 }
663
664 return;
665
666fail:
667 log_error("Failed to build unit path cache: %s", strerror(-r));
668
669 set_free_free(m->unit_path_cache);
670 m->unit_path_cache = NULL;
671
672 if (d)
673 closedir(d);
674}
675
a16e1123
LP
676int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
677 int r, q;
678
679 assert(m);
680
5a1e9937
LP
681 manager_run_generators(m);
682
07719a21
LP
683 r = lookup_paths_init(
684 &m->lookup_paths, m->running_as, true,
685 m->generator_unit_path,
686 m->generator_unit_path_early,
687 m->generator_unit_path_late);
688 if (r < 0)
689 return r;
690
fe51822e
LP
691 manager_build_unit_path_cache(m);
692
9f611ad8
LP
693 /* If we will deserialize make sure that during enumeration
694 * this is already known, so we increase the counter here
695 * already */
696 if (serialization)
a7556052 697 m->n_reloading ++;
9f611ad8 698
a16e1123
LP
699 /* First, enumerate what we can from all config files */
700 r = manager_enumerate(m);
701
702 /* Second, deserialize if there is something to deserialize */
07719a21
LP
703 if (serialization) {
704 q = manager_deserialize(m, serialization, fds);
705 if (q < 0)
a16e1123 706 r = q;
07719a21 707 }
a16e1123
LP
708
709 /* Third, fire things up! */
07719a21
LP
710 q = manager_coldplug(m);
711 if (q < 0)
a16e1123
LP
712 r = q;
713
9f611ad8 714 if (serialization) {
a7556052
LP
715 assert(m->n_reloading > 0);
716 m->n_reloading --;
9f611ad8
LP
717 }
718
a16e1123 719 return r;
f50e0a01
LP
720}
721
398ef8ba 722int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
e5b5ae50 723 int r;
7527cb52 724 Transaction *tr;
e5b5ae50
LP
725
726 assert(m);
727 assert(type < _JOB_TYPE_MAX);
87f0e418 728 assert(unit);
e5b5ae50 729 assert(mode < _JOB_MODE_MAX);
60918275 730
398ef8ba
LP
731 if (mode == JOB_ISOLATE && type != JOB_START) {
732 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
c497c7a9 733 return -EINVAL;
398ef8ba 734 }
c497c7a9 735
ac155bb8 736 if (mode == JOB_ISOLATE && !unit->allow_isolate) {
2528a7a6
LP
737 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
738 return -EPERM;
739 }
740
ac155bb8 741 log_debug("Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
9f04bd52 742
e0209d83
MS
743 job_type_collapse(&type, unit);
744
7527cb52
MS
745 tr = transaction_new();
746 if (!tr)
747 return -ENOMEM;
11dd41ce 748
7527cb52
MS
749 r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, override, false,
750 mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
b94fbd30 751 mode == JOB_IGNORE_DEPENDENCIES, e);
7527cb52
MS
752 if (r < 0)
753 goto tr_abort;
c497c7a9 754
7527cb52
MS
755 if (mode == JOB_ISOLATE) {
756 r = transaction_add_isolate_jobs(tr, m);
757 if (r < 0)
758 goto tr_abort;
759 }
760
761 r = transaction_activate(tr, m, mode, e);
762 if (r < 0)
763 goto tr_abort;
e5b5ae50 764
b94fbd30 765 log_debug("Enqueued job %s/%s as %u", unit->id, job_type_to_string(type), (unsigned) tr->anchor_job->id);
f50e0a01 766
e5b5ae50 767 if (_ret)
b94fbd30 768 *_ret = tr->anchor_job;
60918275 769
7527cb52 770 transaction_free(tr);
e5b5ae50 771 return 0;
7527cb52
MS
772
773tr_abort:
774 transaction_abort(tr);
775 transaction_free(tr);
776 return r;
e5b5ae50 777}
60918275 778
398ef8ba 779int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
28247076
LP
780 Unit *unit;
781 int r;
782
783 assert(m);
784 assert(type < _JOB_TYPE_MAX);
785 assert(name);
786 assert(mode < _JOB_MODE_MAX);
787
c3090674
LP
788 r = manager_load_unit(m, name, NULL, NULL, &unit);
789 if (r < 0)
28247076
LP
790 return r;
791
398ef8ba 792 return manager_add_job(m, type, unit, mode, override, e, _ret);
28247076
LP
793}
794
60918275
LP
795Job *manager_get_job(Manager *m, uint32_t id) {
796 assert(m);
797
798 return hashmap_get(m->jobs, UINT32_TO_PTR(id));
799}
800
87f0e418 801Unit *manager_get_unit(Manager *m, const char *name) {
60918275
LP
802 assert(m);
803 assert(name);
804
87f0e418 805 return hashmap_get(m->units, name);
60918275
LP
806}
807
c1e1601e 808unsigned manager_dispatch_load_queue(Manager *m) {
595ed347 809 Unit *u;
c1e1601e 810 unsigned n = 0;
60918275
LP
811
812 assert(m);
813
223dabab
LP
814 /* Make sure we are not run recursively */
815 if (m->dispatching_load_queue)
c1e1601e 816 return 0;
223dabab
LP
817
818 m->dispatching_load_queue = true;
819
87f0e418 820 /* Dispatches the load queue. Takes a unit from the queue and
60918275
LP
821 * tries to load its data until the queue is empty */
822
595ed347
MS
823 while ((u = m->load_queue)) {
824 assert(u->in_load_queue);
034c6ed7 825
595ed347 826 unit_load(u);
c1e1601e 827 n++;
60918275
LP
828 }
829
223dabab 830 m->dispatching_load_queue = false;
c1e1601e 831 return n;
60918275
LP
832}
833
398ef8ba 834int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
87f0e418 835 Unit *ret;
7d17cfbc 836 UnitType t;
60918275
LP
837 int r;
838
839 assert(m);
9e2f7c11 840 assert(name || path);
60918275 841
db06e3b6
LP
842 /* This will prepare the unit for loading, but not actually
843 * load anything from disk. */
0301abf4 844
398ef8ba
LP
845 if (path && !is_path(path)) {
846 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
9e2f7c11 847 return -EINVAL;
398ef8ba 848 }
9e2f7c11
LP
849
850 if (!name)
9eb977db 851 name = path_get_file_name(path);
9e2f7c11 852
7d17cfbc
MS
853 t = unit_name_to_type(name);
854
5f739699 855 if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, false)) {
398ef8ba 856 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
9e2f7c11 857 return -EINVAL;
398ef8ba 858 }
60918275 859
7d17cfbc
MS
860 ret = manager_get_unit(m, name);
861 if (ret) {
034c6ed7 862 *_ret = ret;
413d6313 863 return 1;
034c6ed7 864 }
60918275 865
7d17cfbc
MS
866 ret = unit_new(m, unit_vtable[t]->object_size);
867 if (!ret)
60918275
LP
868 return -ENOMEM;
869
7d17cfbc 870 if (path) {
ac155bb8
MS
871 ret->fragment_path = strdup(path);
872 if (!ret->fragment_path) {
0301abf4
LP
873 unit_free(ret);
874 return -ENOMEM;
875 }
7d17cfbc 876 }
0301abf4 877
87f0e418
LP
878 if ((r = unit_add_name(ret, name)) < 0) {
879 unit_free(ret);
1ffba6fe 880 return r;
60918275
LP
881 }
882
87f0e418 883 unit_add_to_load_queue(ret);
c1e1601e 884 unit_add_to_dbus_queue(ret);
949061f0 885 unit_add_to_gc_queue(ret);
c1e1601e 886
db06e3b6
LP
887 if (_ret)
888 *_ret = ret;
889
890 return 0;
891}
892
398ef8ba 893int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
db06e3b6
LP
894 int r;
895
896 assert(m);
897
898 /* This will load the service information files, but not actually
899 * start any services or anything. */
900
c3090674
LP
901 r = manager_load_unit_prepare(m, name, path, e, _ret);
902 if (r != 0)
db06e3b6
LP
903 return r;
904
f50e0a01 905 manager_dispatch_load_queue(m);
60918275 906
9e2f7c11 907 if (_ret)
413d6313 908 *_ret = unit_follow_merge(*_ret);
9e2f7c11 909
60918275
LP
910 return 0;
911}
a66d02c3 912
cea8e32e 913void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
034c6ed7 914 Iterator i;
a66d02c3
LP
915 Job *j;
916
917 assert(s);
918 assert(f);
919
034c6ed7 920 HASHMAP_FOREACH(j, s->jobs, i)
cea8e32e 921 job_dump(j, f, prefix);
a66d02c3
LP
922}
923
87f0e418 924void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
034c6ed7 925 Iterator i;
87f0e418 926 Unit *u;
11dd41ce 927 const char *t;
a66d02c3
LP
928
929 assert(s);
930 assert(f);
931
87f0e418 932 HASHMAP_FOREACH_KEY(u, t, s->units, i)
ac155bb8 933 if (u->id == t)
87f0e418 934 unit_dump(u, f, prefix);
a66d02c3 935}
7fad411c
LP
936
937void manager_clear_jobs(Manager *m) {
938 Job *j;
939
940 assert(m);
941
7fad411c 942 while ((j = hashmap_first(m->jobs)))
5273510e
MS
943 /* No need to recurse. We're cancelling all jobs. */
944 job_finish_and_invalidate(j, JOB_CANCELED, false);
7fad411c 945}
83c60c9f 946
c1e1601e 947unsigned manager_dispatch_run_queue(Manager *m) {
83c60c9f 948 Job *j;
c1e1601e 949 unsigned n = 0;
83c60c9f 950
034c6ed7 951 if (m->dispatching_run_queue)
c1e1601e 952 return 0;
034c6ed7
LP
953
954 m->dispatching_run_queue = true;
9152c765 955
034c6ed7 956 while ((j = m->run_queue)) {
ac1135be 957 assert(j->installed);
034c6ed7
LP
958 assert(j->in_run_queue);
959
960 job_run_and_invalidate(j);
c1e1601e 961 n++;
9152c765 962 }
034c6ed7
LP
963
964 m->dispatching_run_queue = false;
c1e1601e
LP
965 return n;
966}
967
968unsigned manager_dispatch_dbus_queue(Manager *m) {
969 Job *j;
595ed347 970 Unit *u;
c1e1601e
LP
971 unsigned n = 0;
972
973 assert(m);
974
975 if (m->dispatching_dbus_queue)
976 return 0;
977
978 m->dispatching_dbus_queue = true;
979
595ed347
MS
980 while ((u = m->dbus_unit_queue)) {
981 assert(u->in_dbus_queue);
c1e1601e 982
595ed347 983 bus_unit_send_change_signal(u);
c1e1601e
LP
984 n++;
985 }
986
987 while ((j = m->dbus_job_queue)) {
988 assert(j->in_dbus_queue);
989
990 bus_job_send_change_signal(j);
991 n++;
992 }
993
994 m->dispatching_dbus_queue = false;
995 return n;
9152c765
LP
996}
997
8c47c732
LP
998static int manager_process_notify_fd(Manager *m) {
999 ssize_t n;
1000
1001 assert(m);
1002
1003 for (;;) {
1004 char buf[4096];
1005 struct msghdr msghdr;
1006 struct iovec iovec;
1007 struct ucred *ucred;
1008 union {
1009 struct cmsghdr cmsghdr;
1010 uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1011 } control;
1012 Unit *u;
1013 char **tags;
1014
1015 zero(iovec);
1016 iovec.iov_base = buf;
1017 iovec.iov_len = sizeof(buf)-1;
1018
1019 zero(control);
1020 zero(msghdr);
1021 msghdr.msg_iov = &iovec;
1022 msghdr.msg_iovlen = 1;
1023 msghdr.msg_control = &control;
1024 msghdr.msg_controllen = sizeof(control);
1025
1026 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1027 if (n >= 0)
1028 return -EIO;
1029
f6144808 1030 if (errno == EAGAIN || errno == EINTR)
8c47c732
LP
1031 break;
1032
1033 return -errno;
1034 }
1035
1036 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1037 control.cmsghdr.cmsg_level != SOL_SOCKET ||
1038 control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1039 control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1040 log_warning("Received notify message without credentials. Ignoring.");
1041 continue;
1042 }
1043
1044 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1045
c6c18be3 1046 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
8c47c732
LP
1047 if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1048 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1049 continue;
1050 }
1051
8c40acf7
LP
1052 assert((size_t) n < sizeof(buf));
1053 buf[n] = 0;
8c47c732
LP
1054 if (!(tags = strv_split(buf, "\n\r")))
1055 return -ENOMEM;
1056
ac155bb8 1057 log_debug("Got notification message for unit %s", u->id);
8c47c732
LP
1058
1059 if (UNIT_VTABLE(u)->notify_message)
c952c6ec 1060 UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
8c47c732
LP
1061
1062 strv_free(tags);
1063 }
1064
1065 return 0;
1066}
1067
034c6ed7 1068static int manager_dispatch_sigchld(Manager *m) {
9152c765
LP
1069 assert(m);
1070
1071 for (;;) {
1072 siginfo_t si;
87f0e418 1073 Unit *u;
8c47c732 1074 int r;
9152c765
LP
1075
1076 zero(si);
4112df16
LP
1077
1078 /* First we call waitd() for a PID and do not reap the
1079 * zombie. That way we can still access /proc/$PID for
1080 * it while it is a zombie. */
1081 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
acbb0225
LP
1082
1083 if (errno == ECHILD)
1084 break;
1085
4112df16
LP
1086 if (errno == EINTR)
1087 continue;
1088
9152c765 1089 return -errno;
acbb0225 1090 }
9152c765 1091
4112df16 1092 if (si.si_pid <= 0)
9152c765
LP
1093 break;
1094
15d5d9d9 1095 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
4112df16
LP
1096 char *name = NULL;
1097
87d2c1ff 1098 get_process_comm(si.si_pid, &name);
bb00e604 1099 log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
4112df16
LP
1100 free(name);
1101 }
1102
8c47c732
LP
1103 /* Let's flush any message the dying child might still
1104 * have queued for us. This ensures that the process
1105 * still exists in /proc so that we can figure out
1106 * which cgroup and hence unit it belongs to. */
1107 if ((r = manager_process_notify_fd(m)) < 0)
1108 return r;
1109
1110 /* And now figure out the unit this belongs to */
c6c18be3 1111 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
8c47c732
LP
1112 u = cgroup_unit_by_pid(m, si.si_pid);
1113
4112df16
LP
1114 /* And now, we actually reap the zombie. */
1115 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
1116 if (errno == EINTR)
1117 continue;
1118
1119 return -errno;
1120 }
1121
034c6ed7
LP
1122 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1123 continue;
1124
bb00e604
LP
1125 log_debug("Child %lu died (code=%s, status=%i/%s)",
1126 (long unsigned) si.si_pid,
4112df16
LP
1127 sigchld_code_to_string(si.si_code),
1128 si.si_status,
d06dacd0
LP
1129 strna(si.si_code == CLD_EXITED
1130 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
1131 : signal_to_string(si.si_status)));
acbb0225 1132
8c47c732 1133 if (!u)
9152c765
LP
1134 continue;
1135
ac155bb8 1136 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->id);
6c1a0478 1137
c6c18be3 1138 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
87f0e418 1139 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
9152c765
LP
1140 }
1141
1142 return 0;
1143}
1144
7d793605 1145static int manager_start_target(Manager *m, const char *name, JobMode mode) {
28247076 1146 int r;
398ef8ba
LP
1147 DBusError error;
1148
1149 dbus_error_init(&error);
1150
af2d49f7 1151 log_debug("Activating special unit %s", name);
1e001f52 1152
398ef8ba
LP
1153 if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
1154 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
28247076 1155
398ef8ba 1156 dbus_error_free(&error);
a1b256b0
LP
1157
1158 return r;
28247076
LP
1159}
1160
a16e1123 1161static int manager_process_signal_fd(Manager *m) {
9152c765
LP
1162 ssize_t n;
1163 struct signalfd_siginfo sfsi;
1164 bool sigchld = false;
1165
1166 assert(m);
1167
1168 for (;;) {
acbb0225 1169 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
9152c765
LP
1170
1171 if (n >= 0)
1172 return -EIO;
1173
63090775 1174 if (errno == EINTR || errno == EAGAIN)
acbb0225 1175 break;
9152c765
LP
1176
1177 return -errno;
1178 }
1179
67370238
LP
1180 if (sfsi.ssi_pid > 0) {
1181 char *p = NULL;
1182
87d2c1ff 1183 get_process_comm(sfsi.ssi_pid, &p);
dfa7f7e1 1184
67370238 1185 log_debug("Received SIG%s from PID %lu (%s).",
4e240ab0 1186 signal_to_string(sfsi.ssi_signo),
67370238
LP
1187 (unsigned long) sfsi.ssi_pid, strna(p));
1188 free(p);
1189 } else
4e240ab0 1190 log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
1e001f52 1191
b9cd2ec1
LP
1192 switch (sfsi.ssi_signo) {
1193
4112df16 1194 case SIGCHLD:
9152c765 1195 sigchld = true;
b9cd2ec1
LP
1196 break;
1197
6632c602 1198 case SIGTERM:
67445f4e 1199 if (m->running_as == SYSTEMD_SYSTEM) {
db06e3b6
LP
1200 /* This is for compatibility with the
1201 * original sysvinit */
e11dc4a2 1202 m->exit_code = MANAGER_REEXECUTE;
a1b256b0
LP
1203 break;
1204 }
84e9af1e 1205
a1b256b0 1206 /* Fall through */
e11dc4a2
LP
1207
1208 case SIGINT:
67445f4e 1209 if (m->running_as == SYSTEMD_SYSTEM) {
7d793605 1210 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
84e9af1e
LP
1211 break;
1212 }
1213
a1b256b0 1214 /* Run the exit target if there is one, if not, just exit. */
0003d1ab 1215 if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
a1b256b0
LP
1216 m->exit_code = MANAGER_EXIT;
1217 return 0;
1218 }
1219
1220 break;
84e9af1e 1221
28247076 1222 case SIGWINCH:
67445f4e 1223 if (m->running_as == SYSTEMD_SYSTEM)
7d793605 1224 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
84e9af1e 1225
28247076
LP
1226 /* This is a nop on non-init */
1227 break;
84e9af1e 1228
28247076 1229 case SIGPWR:
67445f4e 1230 if (m->running_as == SYSTEMD_SYSTEM)
7d793605 1231 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
84e9af1e 1232
28247076 1233 /* This is a nop on non-init */
84e9af1e 1234 break;
6632c602 1235
1005d14f 1236 case SIGUSR1: {
57ee42ce
LP
1237 Unit *u;
1238
1239 u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
1240
1241 if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
1242 log_info("Trying to reconnect to bus...");
3996fbe2 1243 bus_init(m, true);
57ee42ce
LP
1244 }
1245
1246 if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1247 log_info("Loading D-Bus service...");
7d793605 1248 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
57ee42ce
LP
1249 }
1250
1251 break;
1252 }
1253
2149e37c
LP
1254 case SIGUSR2: {
1255 FILE *f;
1256 char *dump = NULL;
1257 size_t size;
1258
1259 if (!(f = open_memstream(&dump, &size))) {
1260 log_warning("Failed to allocate memory stream.");
1261 break;
1262 }
1263
1264 manager_dump_units(m, f, "\t");
1265 manager_dump_jobs(m, f, "\t");
1266
1267 if (ferror(f)) {
1268 fclose(f);
1269 free(dump);
1270 log_warning("Failed to write status stream");
1271 break;
1272 }
1273
1274 fclose(f);
1275 log_dump(LOG_INFO, dump);
1276 free(dump);
1277
1005d14f 1278 break;
2149e37c 1279 }
1005d14f 1280
a16e1123
LP
1281 case SIGHUP:
1282 m->exit_code = MANAGER_RELOAD;
1283 break;
1284
7d793605 1285 default: {
253ee27a 1286
0003d1ab
LP
1287 /* Starting SIGRTMIN+0 */
1288 static const char * const target_table[] = {
7d793605
LP
1289 [0] = SPECIAL_DEFAULT_TARGET,
1290 [1] = SPECIAL_RESCUE_TARGET,
f057408c 1291 [2] = SPECIAL_EMERGENCY_TARGET,
7d793605
LP
1292 [3] = SPECIAL_HALT_TARGET,
1293 [4] = SPECIAL_POWEROFF_TARGET,
0003d1ab
LP
1294 [5] = SPECIAL_REBOOT_TARGET,
1295 [6] = SPECIAL_KEXEC_TARGET
1296 };
1297
1298 /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
1299 static const ManagerExitCode code_table[] = {
1300 [0] = MANAGER_HALT,
1301 [1] = MANAGER_POWEROFF,
1302 [2] = MANAGER_REBOOT,
1303 [3] = MANAGER_KEXEC
7d793605
LP
1304 };
1305
1306 if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
0003d1ab 1307 (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
764e9b5f
MS
1308 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
1309 manager_start_target(m, target_table[idx],
1310 (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
7d793605
LP
1311 break;
1312 }
1313
0003d1ab
LP
1314 if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
1315 (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
1316 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
1317 break;
1318 }
1319
0658666b
LP
1320 switch (sfsi.ssi_signo - SIGRTMIN) {
1321
1322 case 20:
1323 log_debug("Enabling showing of status.");
27d340c7 1324 manager_set_show_status(m, true);
0658666b
LP
1325 break;
1326
1327 case 21:
1328 log_debug("Disabling showing of status.");
27d340c7 1329 manager_set_show_status(m, false);
0658666b
LP
1330 break;
1331
253ee27a
LP
1332 case 22:
1333 log_set_max_level(LOG_DEBUG);
1334 log_notice("Setting log level to debug.");
1335 break;
1336
1337 case 23:
1338 log_set_max_level(LOG_INFO);
1339 log_notice("Setting log level to info.");
1340 break;
1341
600b704e
LP
1342 case 24:
1343 if (m->running_as == SYSTEMD_USER) {
1344 m->exit_code = MANAGER_EXIT;
1345 return 0;
1346 }
1347
1348 /* This is a nop on init */
1349 break;
1350
4cfa2c99
LP
1351 case 26:
1352 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1353 log_notice("Setting log target to journal-or-kmsg.");
1354 break;
1355
253ee27a
LP
1356 case 27:
1357 log_set_target(LOG_TARGET_CONSOLE);
1358 log_notice("Setting log target to console.");
1359 break;
1360
1361 case 28:
1362 log_set_target(LOG_TARGET_KMSG);
1363 log_notice("Setting log target to kmsg.");
1364 break;
1365
1366 case 29:
1367 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
1368 log_notice("Setting log target to syslog-or-kmsg.");
1369 break;
1370
0658666b 1371 default:
4e240ab0 1372 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
0658666b 1373 }
b9cd2ec1 1374 }
7d793605 1375 }
9152c765
LP
1376 }
1377
1378 if (sigchld)
034c6ed7
LP
1379 return manager_dispatch_sigchld(m);
1380
1381 return 0;
1382}
1383
a16e1123 1384static int process_event(Manager *m, struct epoll_event *ev) {
034c6ed7 1385 int r;
acbb0225 1386 Watch *w;
034c6ed7
LP
1387
1388 assert(m);
1389 assert(ev);
1390
3df5bf61 1391 assert_se(w = ev->data.ptr);
034c6ed7 1392
40dde66f
LP
1393 if (w->type == WATCH_INVALID)
1394 return 0;
1395
acbb0225 1396 switch (w->type) {
034c6ed7 1397
ef734fd6 1398 case WATCH_SIGNAL:
034c6ed7 1399
acbb0225 1400 /* An incoming signal? */
f94ea366 1401 if (ev->events != EPOLLIN)
acbb0225 1402 return -EINVAL;
034c6ed7 1403
a16e1123 1404 if ((r = manager_process_signal_fd(m)) < 0)
acbb0225 1405 return r;
034c6ed7 1406
acbb0225 1407 break;
034c6ed7 1408
8c47c732
LP
1409 case WATCH_NOTIFY:
1410
1411 /* An incoming daemon notification event? */
1412 if (ev->events != EPOLLIN)
1413 return -EINVAL;
1414
1415 if ((r = manager_process_notify_fd(m)) < 0)
1416 return r;
1417
1418 break;
1419
acbb0225 1420 case WATCH_FD:
034c6ed7 1421
acbb0225 1422 /* Some fd event, to be dispatched to the units */
ea430986 1423 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
acbb0225 1424 break;
034c6ed7 1425
faf919f1
LP
1426 case WATCH_UNIT_TIMER:
1427 case WATCH_JOB_TIMER: {
acbb0225
LP
1428 uint64_t v;
1429 ssize_t k;
034c6ed7 1430
acbb0225 1431 /* Some timer event, to be dispatched to the units */
68b29a9f
LP
1432 k = read(w->fd, &v, sizeof(v));
1433 if (k != sizeof(v)) {
034c6ed7 1434
acbb0225
LP
1435 if (k < 0 && (errno == EINTR || errno == EAGAIN))
1436 break;
034c6ed7 1437
8742514c 1438 log_error("Failed to read timer event counter: %s", k < 0 ? strerror(-k) : "Short read");
acbb0225 1439 return k < 0 ? -errno : -EIO;
034c6ed7
LP
1440 }
1441
faf919f1
LP
1442 if (w->type == WATCH_UNIT_TIMER)
1443 UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
1444 else
1445 job_timer_event(w->data.job, v, w);
acbb0225
LP
1446 break;
1447 }
1448
ef734fd6
LP
1449 case WATCH_MOUNT:
1450 /* Some mount table change, intended for the mount subsystem */
1451 mount_fd_event(m, ev->events);
1452 break;
1453
4e434314
LP
1454 case WATCH_SWAP:
1455 /* Some swap table change, intended for the swap subsystem */
1456 swap_fd_event(m, ev->events);
1457 break;
1458
f94ea366
LP
1459 case WATCH_UDEV:
1460 /* Some notification from udev, intended for the device subsystem */
1461 device_fd_event(m, ev->events);
1462 break;
1463
ea430986
LP
1464 case WATCH_DBUS_WATCH:
1465 bus_watch_event(m, w, ev->events);
1466 break;
1467
1468 case WATCH_DBUS_TIMEOUT:
1469 bus_timeout_event(m, w, ev->events);
1470 break;
1471
8742514c
LP
1472 case WATCH_TIME_CHANGE: {
1473 Unit *u;
1474 Iterator i;
1475
1476 log_struct(LOG_INFO,
1477 MESSAGE_ID(SD_MESSAGE_TIME_CHANGE),
1478 "MESSAGE=Time has been changed",
1479 NULL);
1480
1481 /* Restart the watch */
1482 close_nointr_nofail(m->time_change_watch.fd);
1483 watch_init(&m->time_change_watch);
1484 manager_setup_time_change(m);
1485
1486 HASHMAP_FOREACH(u, m->units, i) {
1487 if (UNIT_VTABLE(u)->time_change)
1488 UNIT_VTABLE(u)->time_change(u);
1489 }
1490
1491 break;
1492 }
1493
acbb0225 1494 default:
c5fd1e57 1495 log_error("event type=%i", w->type);
acbb0225 1496 assert_not_reached("Unknown epoll event type.");
034c6ed7 1497 }
9152c765
LP
1498
1499 return 0;
1500}
1501
1502int manager_loop(Manager *m) {
1503 int r;
9152c765 1504
fac9f8df 1505 RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
ea430986 1506
9152c765 1507 assert(m);
a16e1123 1508 m->exit_code = MANAGER_RUNNING;
9152c765 1509
fe51822e
LP
1510 /* Release the path cache */
1511 set_free_free(m->unit_path_cache);
1512 m->unit_path_cache = NULL;
1513
b0c918b9
LP
1514 manager_check_finished(m);
1515
a4312405
LP
1516 /* There might still be some zombies hanging around from
1517 * before we were exec()'ed. Leat's reap them */
e96d6be7
LP
1518 r = manager_dispatch_sigchld(m);
1519 if (r < 0)
a4312405
LP
1520 return r;
1521
a16e1123 1522 while (m->exit_code == MANAGER_RUNNING) {
957ca890
LP
1523 struct epoll_event event;
1524 int n;
c757a65b 1525 int wait_msec = -1;
9152c765 1526
67445f4e 1527 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM)
e96d6be7
LP
1528 watchdog_ping();
1529
ea430986
LP
1530 if (!ratelimit_test(&rl)) {
1531 /* Yay, something is going seriously wrong, pause a little */
1532 log_warning("Looping too fast. Throttling execution a little.");
1533 sleep(1);
e96d6be7 1534 continue;
ea430986
LP
1535 }
1536
37a8e683 1537 if (manager_dispatch_load_queue(m) > 0)
23a177ef
LP
1538 continue;
1539
37a8e683 1540 if (manager_dispatch_run_queue(m) > 0)
701cc384
LP
1541 continue;
1542
37a8e683 1543 if (bus_dispatch(m) > 0)
c1e1601e 1544 continue;
034c6ed7 1545
37a8e683 1546 if (manager_dispatch_cleanup_queue(m) > 0)
c1e1601e
LP
1547 continue;
1548
37a8e683 1549 if (manager_dispatch_gc_queue(m) > 0)
c1e1601e
LP
1550 continue;
1551
1552 if (manager_dispatch_dbus_queue(m) > 0)
ea430986 1553 continue;
ea430986 1554
e04aad61
LP
1555 if (swap_dispatch_reload(m) > 0)
1556 continue;
1557
c757a65b 1558 /* Sleep for half the watchdog time */
67445f4e 1559 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM) {
c757a65b
LP
1560 wait_msec = (int) (m->runtime_watchdog / 2 / USEC_PER_MSEC);
1561 if (wait_msec <= 0)
1562 wait_msec = 1;
1563 } else
1564 wait_msec = -1;
1565
e96d6be7
LP
1566 n = epoll_wait(m->epoll_fd, &event, 1, wait_msec);
1567 if (n < 0) {
9152c765 1568
6089f4a9 1569 if (errno == EINTR)
9152c765
LP
1570 continue;
1571
1572 return -errno;
e96d6be7
LP
1573 } else if (n == 0)
1574 continue;
9152c765 1575
957ca890 1576 assert(n == 1);
b9cd2ec1 1577
e96d6be7
LP
1578 r = process_event(m, &event);
1579 if (r < 0)
957ca890 1580 return r;
a16e1123 1581 }
957ca890 1582
a16e1123 1583 return m->exit_code;
83c60c9f 1584}
ea430986 1585
80fbf05e 1586int manager_load_unit_from_dbus_path(Manager *m, const char *s, DBusError *e, Unit **_u) {
ea430986
LP
1587 char *n;
1588 Unit *u;
80fbf05e 1589 int r;
ea430986
LP
1590
1591 assert(m);
1592 assert(s);
1593 assert(_u);
1594
1595 if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1596 return -EINVAL;
1597
80fbf05e
MS
1598 n = bus_path_unescape(s+31);
1599 if (!n)
ea430986
LP
1600 return -ENOMEM;
1601
80fbf05e 1602 r = manager_load_unit(m, n, NULL, e, &u);
ea430986
LP
1603 free(n);
1604
80fbf05e
MS
1605 if (r < 0)
1606 return r;
ea430986
LP
1607
1608 *_u = u;
1609
1610 return 0;
1611}
86fbf370
LP
1612
1613int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
1614 Job *j;
1615 unsigned id;
1616 int r;
1617
1618 assert(m);
1619 assert(s);
1620 assert(_j);
1621
1622 if (!startswith(s, "/org/freedesktop/systemd1/job/"))
1623 return -EINVAL;
1624
8742514c
LP
1625 r = safe_atou(s + 30, &id);
1626 if (r < 0)
86fbf370
LP
1627 return r;
1628
8742514c
LP
1629 j = manager_get_job(m, id);
1630 if (!j)
86fbf370
LP
1631 return -ENOENT;
1632
1633 *_j = j;
1634
1635 return 0;
1636}
dfcd764e 1637
4927fcae 1638void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
e537352b 1639
4927fcae
LP
1640#ifdef HAVE_AUDIT
1641 char *p;
c1165f82 1642 int audit_fd;
e537352b 1643
c1165f82
LP
1644 audit_fd = get_audit_fd();
1645 if (audit_fd < 0)
e537352b
LP
1646 return;
1647
bbd3a7ba
LP
1648 /* Don't generate audit events if the service was already
1649 * started and we're just deserializing */
a7556052 1650 if (m->n_reloading > 0)
bbd3a7ba
LP
1651 return;
1652
67445f4e 1653 if (m->running_as != SYSTEMD_SYSTEM)
f1dd0c3f
LP
1654 return;
1655
ac155bb8 1656 if (u->type != UNIT_SERVICE)
f1dd0c3f
LP
1657 return;
1658
ac155bb8 1659 if (!(p = unit_name_to_prefix_and_instance(u->id))) {
4927fcae 1660 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
e537352b
LP
1661 return;
1662 }
1663
c1165f82 1664 if (audit_log_user_comm_message(audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
391ade86
LP
1665 if (errno == EPERM) {
1666 /* We aren't allowed to send audit messages?
44785992 1667 * Then let's not retry again. */
c1165f82 1668 close_audit_fd();
44785992
LP
1669 } else
1670 log_warning("Failed to send audit message: %m");
391ade86 1671 }
e537352b 1672
4927fcae
LP
1673 free(p);
1674#endif
e537352b 1675
e537352b
LP
1676}
1677
e983b760
LP
1678void manager_send_unit_plymouth(Manager *m, Unit *u) {
1679 int fd = -1;
1680 union sockaddr_union sa;
1681 int n = 0;
1682 char *message = NULL;
e983b760
LP
1683
1684 /* Don't generate plymouth events if the service was already
1685 * started and we're just deserializing */
a7556052 1686 if (m->n_reloading > 0)
e983b760
LP
1687 return;
1688
67445f4e 1689 if (m->running_as != SYSTEMD_SYSTEM)
e983b760
LP
1690 return;
1691
ac155bb8
MS
1692 if (u->type != UNIT_SERVICE &&
1693 u->type != UNIT_MOUNT &&
1694 u->type != UNIT_SWAP)
e983b760
LP
1695 return;
1696
1697 /* We set SOCK_NONBLOCK here so that we rather drop the
1698 * message then wait for plymouth */
1699 if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
1700 log_error("socket() failed: %m");
1701 return;
1702 }
1703
1704 zero(sa);
1705 sa.sa.sa_family = AF_UNIX;
96707269
LP
1706 strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
1707 if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
e983b760
LP
1708
1709 if (errno != EPIPE &&
1710 errno != EAGAIN &&
1711 errno != ENOENT &&
1712 errno != ECONNREFUSED &&
1713 errno != ECONNRESET &&
1714 errno != ECONNABORTED)
1715 log_error("connect() failed: %m");
1716
1717 goto finish;
1718 }
1719
ac155bb8 1720 if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
0d0f0c50 1721 log_oom();
e983b760
LP
1722 goto finish;
1723 }
1724
1725 errno = 0;
bd40a2d8 1726 if (write(fd, message, n + 1) != n + 1) {
e983b760
LP
1727
1728 if (errno != EPIPE &&
1729 errno != EAGAIN &&
1730 errno != ENOENT &&
1731 errno != ECONNREFUSED &&
1732 errno != ECONNRESET &&
1733 errno != ECONNABORTED)
1734 log_error("Failed to write Plymouth message: %m");
1735
1736 goto finish;
1737 }
1738
1739finish:
1740 if (fd >= 0)
1741 close_nointr_nofail(fd);
1742
1743 free(message);
1744}
1745
05e343b7
LP
1746void manager_dispatch_bus_name_owner_changed(
1747 Manager *m,
1748 const char *name,
1749 const char* old_owner,
1750 const char *new_owner) {
1751
1752 Unit *u;
1753
1754 assert(m);
1755 assert(name);
1756
1757 if (!(u = hashmap_get(m->watch_bus, name)))
1758 return;
1759
1760 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
1761}
1762
1763void manager_dispatch_bus_query_pid_done(
1764 Manager *m,
1765 const char *name,
1766 pid_t pid) {
1767
1768 Unit *u;
1769
1770 assert(m);
1771 assert(name);
1772 assert(pid >= 1);
1773
1774 if (!(u = hashmap_get(m->watch_bus, name)))
1775 return;
1776
1777 UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
1778}
1779
d8d5ab98 1780int manager_open_serialization(Manager *m, FILE **_f) {
b925e726 1781 char *path = NULL;
a16e1123
LP
1782 mode_t saved_umask;
1783 int fd;
1784 FILE *f;
1785
1786 assert(_f);
1787
67445f4e 1788 if (m->running_as == SYSTEMD_SYSTEM)
2b583ce6 1789 asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
b925e726
LP
1790 else
1791 asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
d8d5ab98 1792
b925e726
LP
1793 if (!path)
1794 return -ENOMEM;
a16e1123
LP
1795
1796 saved_umask = umask(0077);
1797 fd = mkostemp(path, O_RDWR|O_CLOEXEC);
1798 umask(saved_umask);
1799
1800 if (fd < 0) {
1801 free(path);
1802 return -errno;
1803 }
1804
1805 unlink(path);
1806
1807 log_debug("Serializing state to %s", path);
1808 free(path);
1809
da19d5c1 1810 if (!(f = fdopen(fd, "w+")))
a16e1123
LP
1811 return -errno;
1812
1813 *_f = f;
1814
1815 return 0;
1816}
1817
6b78f9b4 1818int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool serialize_jobs) {
a16e1123
LP
1819 Iterator i;
1820 Unit *u;
1821 const char *t;
1822 int r;
1823
1824 assert(m);
1825 assert(f);
1826 assert(fds);
1827
a7556052 1828 m->n_reloading ++;
38c52d46 1829
01d67b43
LP
1830 fprintf(f, "current-job-id=%i\n", m->current_job_id);
1831 fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
33c5fae9
LP
1832 fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
1833 fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
01d67b43 1834
915b3753
LP
1835 dual_timestamp_serialize(f, "firmware-timestamp", &m->firmware_timestamp);
1836 dual_timestamp_serialize(f, "kernel-timestamp", &m->kernel_timestamp);
1837 dual_timestamp_serialize(f, "loader-timestamp", &m->loader_timestamp);
e9ddabc2 1838 dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
f38ed060 1839
26a1efdf 1840 if (!in_initrd()) {
915b3753 1841 dual_timestamp_serialize(f, "userspace-timestamp", &m->userspace_timestamp);
f38ed060
HH
1842 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
1843 }
47a483a1 1844
f2382a94
LP
1845 fputc('\n', f);
1846
a16e1123 1847 HASHMAP_FOREACH_KEY(u, t, m->units, i) {
ac155bb8 1848 if (u->id != t)
a16e1123
LP
1849 continue;
1850
1851 if (!unit_can_serialize(u))
1852 continue;
1853
1854 /* Start marker */
ac155bb8 1855 fputs(u->id, f);
a16e1123
LP
1856 fputc('\n', f);
1857
6b78f9b4 1858 if ((r = unit_serialize(u, f, fds, serialize_jobs)) < 0) {
a7556052 1859 m->n_reloading --;
a16e1123 1860 return r;
38c52d46 1861 }
a16e1123
LP
1862 }
1863
a7556052
LP
1864 assert(m->n_reloading > 0);
1865 m->n_reloading --;
38c52d46 1866
a16e1123
LP
1867 if (ferror(f))
1868 return -EIO;
1869
b23de6af
LP
1870 r = bus_fdset_add_all(m, fds);
1871 if (r < 0)
1872 return r;
1873
a16e1123
LP
1874 return 0;
1875}
1876
1877int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
1878 int r = 0;
1879
1880 assert(m);
1881 assert(f);
1882
1883 log_debug("Deserializing state...");
1884
a7556052 1885 m->n_reloading ++;
82c64bf5 1886
10f8e83c 1887 for (;;) {
20c03b7b 1888 char line[LINE_MAX], *l;
10f8e83c
LP
1889
1890 if (!fgets(line, sizeof(line), f)) {
1891 if (feof(f))
1892 r = 0;
1893 else
1894 r = -errno;
1895
1896 goto finish;
1897 }
1898
1899 char_array_0(line);
1900 l = strstrip(line);
1901
1902 if (l[0] == 0)
1903 break;
1904
01d67b43
LP
1905 if (startswith(l, "current-job-id=")) {
1906 uint32_t id;
1907
1908 if (safe_atou32(l+15, &id) < 0)
1909 log_debug("Failed to parse current job id value %s", l+15);
1910 else
1911 m->current_job_id = MAX(m->current_job_id, id);
33c5fae9
LP
1912 } else if (startswith(l, "n-installed-jobs=")) {
1913 uint32_t n;
1914
1915 if (safe_atou32(l+17, &n) < 0)
1916 log_debug("Failed to parse installed jobs counter %s", l+17);
1917 else
1918 m->n_installed_jobs += n;
1919 } else if (startswith(l, "n-failed-jobs=")) {
1920 uint32_t n;
1921
1922 if (safe_atou32(l+14, &n) < 0)
1923 log_debug("Failed to parse failed jobs counter %s", l+14);
1924 else
1925 m->n_failed_jobs += n;
01d67b43
LP
1926 } else if (startswith(l, "taint-usr=")) {
1927 int b;
1928
1929 if ((b = parse_boolean(l+10)) < 0)
1930 log_debug("Failed to parse taint /usr flag %s", l+10);
1931 else
1932 m->taint_usr = m->taint_usr || b;
915b3753
LP
1933 } else if (startswith(l, "firmware-timestamp="))
1934 dual_timestamp_deserialize(l+19, &m->firmware_timestamp);
1935 else if (startswith(l, "loader-timestamp="))
1936 dual_timestamp_deserialize(l+17, &m->loader_timestamp);
1937 else if (startswith(l, "kernel-timestamp="))
1938 dual_timestamp_deserialize(l+17, &m->kernel_timestamp);
1939 else if (startswith(l, "initrd-timestamp="))
e9ddabc2 1940 dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
915b3753
LP
1941 else if (startswith(l, "userspace-timestamp="))
1942 dual_timestamp_deserialize(l+20, &m->userspace_timestamp);
10717a1a 1943 else if (startswith(l, "finish-timestamp="))
799fd0fd 1944 dual_timestamp_deserialize(l+17, &m->finish_timestamp);
10717a1a 1945 else
10f8e83c
LP
1946 log_debug("Unknown serialization item '%s'", l);
1947 }
1948
a16e1123
LP
1949 for (;;) {
1950 Unit *u;
1951 char name[UNIT_NAME_MAX+2];
1952
1953 /* Start marker */
1954 if (!fgets(name, sizeof(name), f)) {
1955 if (feof(f))
10f8e83c
LP
1956 r = 0;
1957 else
1958 r = -errno;
a16e1123 1959
82c64bf5 1960 goto finish;
a16e1123
LP
1961 }
1962
1963 char_array_0(name);
1964
398ef8ba 1965 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
82c64bf5 1966 goto finish;
a16e1123
LP
1967
1968 if ((r = unit_deserialize(u, f, fds)) < 0)
82c64bf5 1969 goto finish;
a16e1123
LP
1970 }
1971
10f8e83c 1972finish:
82c64bf5
LP
1973 if (ferror(f)) {
1974 r = -EIO;
1975 goto finish;
1976 }
a16e1123 1977
a7556052
LP
1978 assert(m->n_reloading > 0);
1979 m->n_reloading --;
82c64bf5
LP
1980
1981 return r;
a16e1123
LP
1982}
1983
1984int manager_reload(Manager *m) {
1985 int r, q;
1986 FILE *f;
1987 FDSet *fds;
1988
1989 assert(m);
1990
07719a21
LP
1991 r = manager_open_serialization(m, &f);
1992 if (r < 0)
a16e1123
LP
1993 return r;
1994
a7556052 1995 m->n_reloading ++;
38c52d46 1996
07719a21
LP
1997 fds = fdset_new();
1998 if (!fds) {
a7556052 1999 m->n_reloading --;
a16e1123
LP
2000 r = -ENOMEM;
2001 goto finish;
2002 }
2003
6b78f9b4 2004 r = manager_serialize(m, f, fds, true);
07719a21 2005 if (r < 0) {
a7556052 2006 m->n_reloading --;
a16e1123 2007 goto finish;
38c52d46 2008 }
a16e1123
LP
2009
2010 if (fseeko(f, 0, SEEK_SET) < 0) {
a7556052 2011 m->n_reloading --;
a16e1123
LP
2012 r = -errno;
2013 goto finish;
2014 }
2015
2016 /* From here on there is no way back. */
2017 manager_clear_jobs_and_units(m);
5a1e9937 2018 manager_undo_generators(m);
84e3543e 2019 lookup_paths_free(&m->lookup_paths);
2ded0c04 2020
07719a21 2021 /* Find new unit paths */
5a1e9937
LP
2022 manager_run_generators(m);
2023
07719a21
LP
2024 q = lookup_paths_init(
2025 &m->lookup_paths, m->running_as, true,
2026 m->generator_unit_path,
2027 m->generator_unit_path_early,
2028 m->generator_unit_path_late);
2029 if (q < 0)
2030 r = q;
2031
5a1e9937
LP
2032 manager_build_unit_path_cache(m);
2033
a16e1123 2034 /* First, enumerate what we can from all config files */
07719a21
LP
2035 q = manager_enumerate(m);
2036 if (q < 0)
a16e1123
LP
2037 r = q;
2038
2039 /* Second, deserialize our stored data */
07719a21
LP
2040 q = manager_deserialize(m, f, fds);
2041 if (q < 0)
a16e1123
LP
2042 r = q;
2043
2044 fclose(f);
2045 f = NULL;
2046
2047 /* Third, fire things up! */
07719a21
LP
2048 q = manager_coldplug(m);
2049 if (q < 0)
a16e1123
LP
2050 r = q;
2051
a7556052
LP
2052 assert(m->n_reloading > 0);
2053 m->n_reloading--;
9f611ad8 2054
a16e1123
LP
2055finish:
2056 if (f)
2057 fclose(f);
2058
2059 if (fds)
2060 fdset_free(fds);
2061
2062 return r;
2063}
2064
9e58ff9c
LP
2065bool manager_is_booting_or_shutting_down(Manager *m) {
2066 Unit *u;
2067
2068 assert(m);
2069
2070 /* Is the initial job still around? */
bacbccb7 2071 if (manager_get_job(m, m->default_unit_job_id))
9e58ff9c
LP
2072 return true;
2073
2074 /* Is there a job for the shutdown target? */
27d340c7
LP
2075 u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2076 if (u)
ac155bb8 2077 return !!u->job;
9e58ff9c
LP
2078
2079 return false;
2080}
2081
fdf20a31 2082void manager_reset_failed(Manager *m) {
5632e374
LP
2083 Unit *u;
2084 Iterator i;
2085
2086 assert(m);
2087
2088 HASHMAP_FOREACH(u, m->units, i)
fdf20a31 2089 unit_reset_failed(u);
5632e374
LP
2090}
2091
8f6df3fa
LP
2092bool manager_unit_pending_inactive(Manager *m, const char *name) {
2093 Unit *u;
2094
2095 assert(m);
2096 assert(name);
2097
2098 /* Returns true if the unit is inactive or going down */
8f6df3fa
LP
2099 if (!(u = manager_get_unit(m, name)))
2100 return true;
2101
18ffdfda 2102 return unit_pending_inactive(u);
8f6df3fa
LP
2103}
2104
b0c918b9 2105void manager_check_finished(Manager *m) {
7ceba241 2106 char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
915b3753 2107 usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
b0c918b9
LP
2108
2109 assert(m);
2110
f2b68789 2111 if (hashmap_size(m->jobs) > 0)
b0c918b9
LP
2112 return;
2113
f2b68789
LP
2114 /* Notify Type=idle units that we are done now */
2115 close_pipe(m->idle_pipe);
2116
af6da548
LP
2117 /* Turn off confirm spawn now */
2118 m->confirm_spawn = false;
2119
f2b68789 2120 if (dual_timestamp_is_set(&m->finish_timestamp))
b0c918b9
LP
2121 return;
2122
2123 dual_timestamp_get(&m->finish_timestamp);
2124
67445f4e 2125 if (m->running_as == SYSTEMD_SYSTEM && detect_container(NULL) <= 0) {
e03ae661 2126
915b3753
LP
2127 /* Note that m->kernel_usec.monotonic is always at 0,
2128 * and m->firmware_usec.monotonic and
2129 * m->loader_usec.monotonic should be considered
2130 * negative values. */
2131
7ceba241
LP
2132 firmware_usec = m->firmware_timestamp.monotonic - m->loader_timestamp.monotonic;
2133 loader_usec = m->loader_timestamp.monotonic - m->kernel_timestamp.monotonic;
915b3753 2134 userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
7ceba241 2135 total_usec = m->firmware_timestamp.monotonic + m->finish_timestamp.monotonic;
18fa6b27 2136
e9ddabc2 2137 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
18fa6b27 2138
915b3753
LP
2139 kernel_usec = m->initrd_timestamp.monotonic - m->kernel_timestamp.monotonic;
2140 initrd_usec = m->userspace_timestamp.monotonic - m->initrd_timestamp.monotonic;
18fa6b27 2141
81270860
LP
2142 if (!log_on_console())
2143 log_struct(LOG_INFO,
1ca6783f 2144 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
81270860
LP
2145 "KERNEL_USEC=%llu", (unsigned long long) kernel_usec,
2146 "INITRD_USEC=%llu", (unsigned long long) initrd_usec,
2147 "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
2148 "MESSAGE=Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2149 format_timespan(kernel, sizeof(kernel), kernel_usec),
2150 format_timespan(initrd, sizeof(initrd), initrd_usec),
2151 format_timespan(userspace, sizeof(userspace), userspace_usec),
2152 format_timespan(sum, sizeof(sum), total_usec),
2153 NULL);
18fa6b27 2154 } else {
915b3753 2155 kernel_usec = m->userspace_timestamp.monotonic - m->kernel_timestamp.monotonic;
18fa6b27
LP
2156 initrd_usec = 0;
2157
81270860
LP
2158 if (!log_on_console())
2159 log_struct(LOG_INFO,
1ca6783f 2160 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
81270860
LP
2161 "KERNEL_USEC=%llu", (unsigned long long) kernel_usec,
2162 "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
2163 "MESSAGE=Startup finished in %s (kernel) + %s (userspace) = %s.",
2164 format_timespan(kernel, sizeof(kernel), kernel_usec),
2165 format_timespan(userspace, sizeof(userspace), userspace_usec),
2166 format_timespan(sum, sizeof(sum), total_usec),
2167 NULL);
18fa6b27
LP
2168 }
2169 } else {
915b3753
LP
2170 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
2171 total_usec = userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
877d54e9 2172
81270860
LP
2173 if (!log_on_console())
2174 log_struct(LOG_INFO,
1ca6783f 2175 MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
81270860
LP
2176 "USERSPACE_USEC=%llu", (unsigned long long) userspace_usec,
2177 "MESSAGE=Startup finished in %s.",
2178 format_timespan(sum, sizeof(sum), total_usec),
2179 NULL);
18fa6b27 2180 }
b0c918b9 2181
915b3753 2182 bus_broadcast_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
530345e7
LP
2183
2184 sd_notifyf(false,
2185 "READY=1\nSTATUS=Startup finished in %s.",
2186 format_timespan(sum, sizeof(sum), total_usec));
b0c918b9
LP
2187}
2188
07719a21
LP
2189static int create_generator_dir(Manager *m, char **generator, const char *name) {
2190 char *p;
2191 int r;
2192
2193 assert(m);
2194 assert(generator);
2195 assert(name);
2196
2197 if (*generator)
2198 return 0;
2199
67445f4e 2200 if (m->running_as == SYSTEMD_SYSTEM && getpid() == 1) {
07719a21
LP
2201
2202 p = strappend("/run/systemd/", name);
0d0f0c50
SL
2203 if (!p)
2204 return log_oom();
07719a21 2205
d2e54fae 2206 r = mkdir_p_label(p, 0755);
07719a21
LP
2207 if (r < 0) {
2208 log_error("Failed to create generator directory: %s", strerror(-r));
2209 free(p);
2210 return r;
2211 }
2212 } else {
b7def684 2213 p = strjoin("/tmp/systemd-", name, ".XXXXXX", NULL);
0d0f0c50
SL
2214 if (!p)
2215 return log_oom();
07719a21
LP
2216
2217 if (!mkdtemp(p)) {
2218 free(p);
2219 log_error("Failed to create generator directory: %m");
2220 return -errno;
2221 }
2222 }
2223
2224 *generator = p;
2225 return 0;
2226}
2227
2228static void trim_generator_dir(Manager *m, char **generator) {
2229 assert(m);
2230 assert(generator);
2231
2232 if (!*generator)
2233 return;
2234
2235 if (rmdir(*generator) >= 0) {
2236 free(*generator);
2237 *generator = NULL;
2238 }
2239
2240 return;
2241}
2242
5a1e9937
LP
2243void manager_run_generators(Manager *m) {
2244 DIR *d = NULL;
5a1e9937 2245 const char *generator_path;
07719a21 2246 const char *argv[5];
07f8a4aa 2247 mode_t u;
07719a21 2248 int r;
5a1e9937
LP
2249
2250 assert(m);
2251
67445f4e 2252 generator_path = m->running_as == SYSTEMD_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
07719a21
LP
2253 d = opendir(generator_path);
2254 if (!d) {
5a1e9937
LP
2255 if (errno == ENOENT)
2256 return;
2257
2258 log_error("Failed to enumerate generator directory: %m");
2259 return;
2260 }
2261
07719a21
LP
2262 r = create_generator_dir(m, &m->generator_unit_path, "generator");
2263 if (r < 0)
2264 goto finish;
f1d19aa4 2265
07719a21
LP
2266 r = create_generator_dir(m, &m->generator_unit_path_early, "generator.early");
2267 if (r < 0)
2268 goto finish;
5a1e9937 2269
07719a21
LP
2270 r = create_generator_dir(m, &m->generator_unit_path_late, "generator.late");
2271 if (r < 0)
2272 goto finish;
5a1e9937 2273
83cc030f
LP
2274 argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2275 argv[1] = m->generator_unit_path;
07719a21
LP
2276 argv[2] = m->generator_unit_path_early;
2277 argv[3] = m->generator_unit_path_late;
2278 argv[4] = NULL;
5a1e9937 2279
07f8a4aa 2280 u = umask(0022);
83cc030f 2281 execute_directory(generator_path, d, (char**) argv);
07f8a4aa 2282 umask(u);
5a1e9937 2283
07719a21
LP
2284 trim_generator_dir(m, &m->generator_unit_path);
2285 trim_generator_dir(m, &m->generator_unit_path_early);
2286 trim_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2287
2288finish:
2289 if (d)
2290 closedir(d);
5a1e9937
LP
2291}
2292
07719a21 2293static void remove_generator_dir(Manager *m, char **generator) {
5a1e9937 2294 assert(m);
07719a21 2295 assert(generator);
5a1e9937 2296
07719a21 2297 if (!*generator)
5a1e9937
LP
2298 return;
2299
07719a21
LP
2300 strv_remove(m->lookup_paths.unit_path, *generator);
2301 rm_rf(*generator, false, true, false);
5a1e9937 2302
07719a21
LP
2303 free(*generator);
2304 *generator = NULL;
2305}
2306
2307void manager_undo_generators(Manager *m) {
2308 assert(m);
2309
2310 remove_generator_dir(m, &m->generator_unit_path);
2311 remove_generator_dir(m, &m->generator_unit_path_early);
2312 remove_generator_dir(m, &m->generator_unit_path_late);
5a1e9937
LP
2313}
2314
06d4c99a
LP
2315int manager_set_default_controllers(Manager *m, char **controllers) {
2316 char **l;
2317
2318 assert(m);
2319
9156e799
LP
2320 l = strv_copy(controllers);
2321 if (!l)
06d4c99a
LP
2322 return -ENOMEM;
2323
2324 strv_free(m->default_controllers);
2325 m->default_controllers = l;
2326
b59e2465 2327 cg_shorten_controllers(m->default_controllers);
9156e799 2328
06d4c99a
LP
2329 return 0;
2330}
2331
c93ff2e9
FC
2332int manager_set_default_rlimits(Manager *m, struct rlimit **default_rlimit) {
2333 int i;
2334
2335 assert(m);
2336
2337 for (i = 0; i < RLIMIT_NLIMITS; i++) {
07719a21
LP
2338 if (!default_rlimit[i])
2339 continue;
c93ff2e9 2340
07719a21
LP
2341 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
2342 if (!m->rlimit[i])
2343 return -ENOMEM;
c93ff2e9
FC
2344 }
2345
2346 return 0;
2347}
2348
4cfa2c99 2349void manager_recheck_journal(Manager *m) {
f1dd0c3f
LP
2350 Unit *u;
2351
2352 assert(m);
2353
67445f4e 2354 if (m->running_as != SYSTEMD_SYSTEM)
f1dd0c3f
LP
2355 return;
2356
731a676c
LP
2357 u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
2358 if (u && SOCKET(u)->state != SOCKET_RUNNING) {
4cfa2c99 2359 log_close_journal();
731a676c 2360 return;
f1dd0c3f
LP
2361 }
2362
731a676c
LP
2363 u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
2364 if (u && SERVICE(u)->state != SERVICE_RUNNING) {
4cfa2c99 2365 log_close_journal();
731a676c
LP
2366 return;
2367 }
f1dd0c3f 2368
731a676c
LP
2369 /* Hmm, OK, so the socket is fully up and the service is up
2370 * too, then let's make use of the thing. */
f1dd0c3f
LP
2371 log_open();
2372}
2373
27d340c7
LP
2374void manager_set_show_status(Manager *m, bool b) {
2375 assert(m);
2376
67445f4e 2377 if (m->running_as != SYSTEMD_SYSTEM)
27d340c7
LP
2378 return;
2379
2380 m->show_status = b;
2381
2382 if (b)
2383 touch("/run/systemd/show-status");
2384 else
2385 unlink("/run/systemd/show-status");
2386}
2387
2388bool manager_get_show_status(Manager *m) {
2389 assert(m);
2390
67445f4e 2391 if (m->running_as != SYSTEMD_SYSTEM)
27d340c7
LP
2392 return false;
2393
2394 if (m->show_status)
2395 return true;
2396
2397 /* If Plymouth is running make sure we show the status, so
2398 * that there's something nice to see when people press Esc */
2399
2400 return plymouth_running();
2401}
68b29a9f
LP
2402
2403void watch_init(Watch *w) {
2404 assert(w);
2405
2406 w->type = WATCH_INVALID;
2407 w->fd = -1;
2408}