chiark / gitweb /
1ddd8bae62497407e555bbe4cfa47a03f507754e
[elogind.git] / src / core / manager.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
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
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
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
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <string.h>
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>
31 #include <sys/reboot.h>
32 #include <sys/ioctl.h>
33 #include <linux/kd.h>
34 #include <termios.h>
35 #include <fcntl.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <dirent.h>
39 #include <sys/timerfd.h>
40
41 #ifdef HAVE_AUDIT
42 #include <libaudit.h>
43 #endif
44
45 #include "systemd/sd-daemon.h"
46 #include "systemd/sd-id128.h"
47 #include "systemd/sd-messages.h"
48
49 #include "manager.h"
50 #include "transaction.h"
51 #include "hashmap.h"
52 #include "macro.h"
53 #include "strv.h"
54 #include "log.h"
55 #include "util.h"
56 #include "mkdir.h"
57 #include "ratelimit.h"
58 #include "cgroup.h"
59 #include "mount-setup.h"
60 #include "unit-name.h"
61 #include "dbus-unit.h"
62 #include "dbus-job.h"
63 #include "missing.h"
64 #include "path-lookup.h"
65 #include "special.h"
66 #include "bus-errors.h"
67 #include "exit-status.h"
68 #include "virt.h"
69 #include "watchdog.h"
70 #include "cgroup-util.h"
71 #include "path-util.h"
72 #include "audit-fd.h"
73
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 */
78 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
79
80 /* Where clients shall send notification messages to */
81 #define NOTIFY_SOCKET "@/org/freedesktop/systemd1/notify"
82
83 static int manager_setup_notify(Manager *m) {
84         union {
85                 struct sockaddr sa;
86                 struct sockaddr_un un;
87         } sa;
88         struct epoll_event ev;
89         int one = 1;
90
91         assert(m);
92
93         m->notify_watch.type = WATCH_NOTIFY;
94         m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
95         if (m->notify_watch.fd < 0) {
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
103         if (getpid() != 1 || detect_container(NULL) > 0)
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));
107
108         sa.un.sun_path[0] = 0;
109
110         if (bind(m->notify_watch.fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
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
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");
126                 return -errno;
127         }
128
129         sa.un.sun_path[0] = '@';
130         m->notify_socket = strdup(sa.un.sun_path);
131         if (!m->notify_socket)
132                 return log_oom();
133
134         log_debug("Using notification socket %s", m->notify_socket);
135
136         return 0;
137 }
138
139 static 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);
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
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
184 static int enable_special_signals(Manager *m) {
185         int fd;
186
187         assert(m);
188
189         /* Enable that we get SIGINT on control-alt-del. In containers
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)
193                 log_warning("Failed to enable ctrl-alt-del handling: %m");
194
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 {
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
211 static int manager_setup_signals(Manager *m) {
212         sigset_t mask;
213         struct epoll_event ev;
214         struct sigaction sa;
215
216         assert(m);
217
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
224         assert_se(sigemptyset(&mask) == 0);
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 */
236                         SIGRTMIN+1,  /* systemd: isolate rescue.target */
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 */
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 */
246                         SIGRTMIN+20, /* systemd: enable status messages */
247                         SIGRTMIN+21, /* systemd: disable status messages */
248                         SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
249                         SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
250                         SIGRTMIN+24, /* systemd: Immediate exit (--user only) */
251                         SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
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 */
255                         -1);
256         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
257
258         m->signal_watch.type = WATCH_SIGNAL;
259         m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC);
260         if (m->signal_watch.fd < 0)
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
270         if (m->running_as == SYSTEMD_SYSTEM)
271                 return enable_special_signals(m);
272
273         return 0;
274 }
275
276 static 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
291 int manager_new(SystemdRunningAs running_as, Manager **_m) {
292         Manager *m;
293         int r = -ENOMEM;
294
295         assert(_m);
296         assert(running_as >= 0);
297         assert(running_as < _SYSTEMD_RUNNING_AS_MAX);
298
299         m = new0(Manager, 1);
300         if (!m)
301                 return -ENOMEM;
302
303         dual_timestamp_get(&m->userspace_timestamp);
304
305         m->running_as = running_as;
306         m->name_data_slot = m->conn_data_slot = m->subscribed_data_slot = -1;
307         m->exit_code = _MANAGER_EXIT_CODE_INVALID;
308         m->pin_cgroupfs_fd = -1;
309         m->idle_pipe[0] = m->idle_pipe[1] = -1;
310
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;
318         m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
319
320         m->environment = strv_copy(environ);
321         if (!m->environment)
322                 goto fail;
323
324         manager_strip_environment(m);
325
326         if (running_as == SYSTEMD_SYSTEM) {
327                 m->default_controllers = strv_new("cpu", NULL);
328                 if (!m->default_controllers)
329                         goto fail;
330         }
331
332         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
333                 goto fail;
334
335         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
336                 goto fail;
337
338         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
339                 goto fail;
340
341         if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
342                 goto fail;
343
344         if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
345                 goto fail;
346
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)
353                 goto fail;
354
355         r = manager_setup_cgroup(m);
356         if (r < 0)
357                 goto fail;
358
359         r = manager_setup_notify(m);
360         if (r < 0)
361                 goto fail;
362
363         r = manager_setup_time_change(m);
364         if (r < 0)
365                 goto fail;
366
367         /* Try to connect to the busses, if possible. */
368         r = bus_init(m, running_as != SYSTEMD_SYSTEM);
369         if (r < 0)
370                 goto fail;
371
372         m->taint_usr = dir_is_empty("/usr") > 0;
373
374         *_m = m;
375         return 0;
376
377 fail:
378         manager_free(m);
379         return r;
380 }
381
382 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
383         Unit *u;
384         unsigned n = 0;
385
386         assert(m);
387
388         while ((u = m->cleanup_queue)) {
389                 assert(u->in_cleanup_queue);
390
391                 unit_free(u);
392                 n++;
393         }
394
395         return n;
396 }
397
398 enum {
399         GC_OFFSET_IN_PATH,  /* This one is on the path we were traveling */
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
406 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
407         Iterator i;
408         Unit *other;
409         bool is_bad;
410
411         assert(u);
412
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)
416                 return;
417
418         if (u->in_cleanup_queue)
419                 goto bad;
420
421         if (unit_check_gc(u))
422                 goto good;
423
424         u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
425
426         is_bad = true;
427
428         SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
429                 unit_gc_sweep(other, gc_marker);
430
431                 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
432                         goto good;
433
434                 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
435                         is_bad = false;
436         }
437
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 */
443         u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
444         unit_add_to_gc_queue(u);
445         return;
446
447 bad:
448         /* We definitely know that this one is not useful anymore, so
449          * let's mark it for deletion */
450         u->gc_marker = gc_marker + GC_OFFSET_BAD;
451         unit_add_to_cleanup_queue(u);
452         return;
453
454 good:
455         u->gc_marker = gc_marker + GC_OFFSET_GOOD;
456 }
457
458 static unsigned manager_dispatch_gc_queue(Manager *m) {
459         Unit *u;
460         unsigned n = 0;
461         unsigned gc_marker;
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
472         m->gc_marker += _GC_OFFSET_MAX;
473         if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
474                 m->gc_marker = 1;
475
476         gc_marker = m->gc_marker;
477
478         while ((u = m->gc_queue)) {
479                 assert(u->in_gc_queue);
480
481                 unit_gc_sweep(u, gc_marker);
482
483                 LIST_REMOVE(Unit, gc_queue, m->gc_queue, u);
484                 u->in_gc_queue = false;
485
486                 n++;
487
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);
493                 }
494         }
495
496         m->n_in_gc_queue = 0;
497         m->gc_queue_timestamp = 0;
498
499         return n;
500 }
501
502 static void manager_clear_jobs_and_units(Manager *m) {
503         Unit *u;
504
505         assert(m);
506
507         while ((u = hashmap_first(m->units)))
508                 unit_free(u);
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
519         assert(hashmap_isempty(m->jobs));
520         assert(hashmap_isempty(m->units));
521 }
522
523 void manager_free(Manager *m) {
524         UnitType c;
525         int i;
526
527         assert(m);
528
529         manager_clear_jobs_and_units(m);
530
531         for (c = 0; c < _UNIT_TYPE_MAX; c++)
532                 if (unit_vtable[c]->shutdown)
533                         unit_vtable[c]->shutdown(m);
534
535         /* If we reexecute ourselves, we keep the root cgroup
536          * around */
537         manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
538
539         manager_undo_generators(m);
540
541         bus_done(m);
542
543         hashmap_free(m->units);
544         hashmap_free(m->jobs);
545         hashmap_free(m->watch_pids);
546         hashmap_free(m->watch_bus);
547
548         if (m->epoll_fd >= 0)
549                 close_nointr_nofail(m->epoll_fd);
550         if (m->signal_watch.fd >= 0)
551                 close_nointr_nofail(m->signal_watch.fd);
552         if (m->notify_watch.fd >= 0)
553                 close_nointr_nofail(m->notify_watch.fd);
554         if (m->time_change_watch.fd >= 0)
555                 close_nointr_nofail(m->time_change_watch.fd);
556
557         free(m->notify_socket);
558
559         lookup_paths_free(&m->lookup_paths);
560         strv_free(m->environment);
561
562         strv_free(m->default_controllers);
563
564         hashmap_free(m->cgroup_bondings);
565         set_free_free(m->unit_path_cache);
566
567         close_pipe(m->idle_pipe);
568
569         free(m->switch_root);
570         free(m->switch_root_init);
571
572         for (i = 0; i < RLIMIT_NLIMITS; i++)
573                 free(m->rlimit[i]);
574
575         free(m);
576 }
577
578 int manager_enumerate(Manager *m) {
579         int r = 0, q;
580         UnitType c;
581
582         assert(m);
583
584         /* Let's ask every type to load all units from disk/kernel
585          * that it might know */
586         for (c = 0; c < _UNIT_TYPE_MAX; c++)
587                 if (unit_vtable[c]->enumerate)
588                         if ((q = unit_vtable[c]->enumerate(m)) < 0)
589                                 r = q;
590
591         manager_dispatch_load_queue(m);
592         return r;
593 }
594
595 int manager_coldplug(Manager *m) {
596         int r = 0, q;
597         Iterator i;
598         Unit *u;
599         char *k;
600
601         assert(m);
602
603         /* Then, let's set up their initial state. */
604         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
605
606                 /* ignore aliases */
607                 if (u->id != k)
608                         continue;
609
610                 if ((q = unit_coldplug(u)) < 0)
611                         r = q;
612         }
613
614         return r;
615 }
616
617 static 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
648                         p = strjoin(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
649                         if (!p) {
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
666 fail:
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
676 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
677         int r, q;
678
679         assert(m);
680
681         manager_run_generators(m);
682
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
691         manager_build_unit_path_cache(m);
692
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)
697                 m->n_reloading ++;
698
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 */
703         if (serialization) {
704                 q = manager_deserialize(m, serialization, fds);
705                 if (q < 0)
706                         r = q;
707         }
708
709         /* Third, fire things up! */
710         q = manager_coldplug(m);
711         if (q < 0)
712                 r = q;
713
714         if (serialization) {
715                 assert(m->n_reloading > 0);
716                 m->n_reloading --;
717         }
718
719         return r;
720 }
721
722 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
723         int r;
724         Transaction *tr;
725
726         assert(m);
727         assert(type < _JOB_TYPE_MAX);
728         assert(unit);
729         assert(mode < _JOB_MODE_MAX);
730
731         if (mode == JOB_ISOLATE && type != JOB_START) {
732                 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
733                 return -EINVAL;
734         }
735
736         if (mode == JOB_ISOLATE && !unit->allow_isolate) {
737                 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
738                 return -EPERM;
739         }
740
741         log_debug("Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
742
743         job_type_collapse(&type, unit);
744
745         tr = transaction_new();
746         if (!tr)
747                 return -ENOMEM;
748
749         r = transaction_add_job_and_dependencies(tr, type, unit, NULL, true, override, false,
750                                                  mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
751                                                  mode == JOB_IGNORE_DEPENDENCIES, e);
752         if (r < 0)
753                 goto tr_abort;
754
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;
764
765         log_debug("Enqueued job %s/%s as %u", unit->id, job_type_to_string(type), (unsigned) tr->anchor_job->id);
766
767         if (_ret)
768                 *_ret = tr->anchor_job;
769
770         transaction_free(tr);
771         return 0;
772
773 tr_abort:
774         transaction_abort(tr);
775         transaction_free(tr);
776         return r;
777 }
778
779 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
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
788         r = manager_load_unit(m, name, NULL, NULL, &unit);
789         if (r < 0)
790                 return r;
791
792         return manager_add_job(m, type, unit, mode, override, e, _ret);
793 }
794
795 Job *manager_get_job(Manager *m, uint32_t id) {
796         assert(m);
797
798         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
799 }
800
801 Unit *manager_get_unit(Manager *m, const char *name) {
802         assert(m);
803         assert(name);
804
805         return hashmap_get(m->units, name);
806 }
807
808 unsigned manager_dispatch_load_queue(Manager *m) {
809         Unit *u;
810         unsigned n = 0;
811
812         assert(m);
813
814         /* Make sure we are not run recursively */
815         if (m->dispatching_load_queue)
816                 return 0;
817
818         m->dispatching_load_queue = true;
819
820         /* Dispatches the load queue. Takes a unit from the queue and
821          * tries to load its data until the queue is empty */
822
823         while ((u = m->load_queue)) {
824                 assert(u->in_load_queue);
825
826                 unit_load(u);
827                 n++;
828         }
829
830         m->dispatching_load_queue = false;
831         return n;
832 }
833
834 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
835         Unit *ret;
836         UnitType t;
837         int r;
838
839         assert(m);
840         assert(name || path);
841
842         /* This will prepare the unit for loading, but not actually
843          * load anything from disk. */
844
845         if (path && !is_path(path)) {
846                 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
847                 return -EINVAL;
848         }
849
850         if (!name)
851                 name = path_get_file_name(path);
852
853         t = unit_name_to_type(name);
854
855         if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid(name, false)) {
856                 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
857                 return -EINVAL;
858         }
859
860         ret = manager_get_unit(m, name);
861         if (ret) {
862                 *_ret = ret;
863                 return 1;
864         }
865
866         ret = unit_new(m, unit_vtable[t]->object_size);
867         if (!ret)
868                 return -ENOMEM;
869
870         if (path) {
871                 ret->fragment_path = strdup(path);
872                 if (!ret->fragment_path) {
873                         unit_free(ret);
874                         return -ENOMEM;
875                 }
876         }
877
878         if ((r = unit_add_name(ret, name)) < 0) {
879                 unit_free(ret);
880                 return r;
881         }
882
883         unit_add_to_load_queue(ret);
884         unit_add_to_dbus_queue(ret);
885         unit_add_to_gc_queue(ret);
886
887         if (_ret)
888                 *_ret = ret;
889
890         return 0;
891 }
892
893 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
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
901         r = manager_load_unit_prepare(m, name, path, e, _ret);
902         if (r != 0)
903                 return r;
904
905         manager_dispatch_load_queue(m);
906
907         if (_ret)
908                 *_ret = unit_follow_merge(*_ret);
909
910         return 0;
911 }
912
913 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
914         Iterator i;
915         Job *j;
916
917         assert(s);
918         assert(f);
919
920         HASHMAP_FOREACH(j, s->jobs, i)
921                 job_dump(j, f, prefix);
922 }
923
924 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
925         Iterator i;
926         Unit *u;
927         const char *t;
928
929         assert(s);
930         assert(f);
931
932         HASHMAP_FOREACH_KEY(u, t, s->units, i)
933                 if (u->id == t)
934                         unit_dump(u, f, prefix);
935 }
936
937 void manager_clear_jobs(Manager *m) {
938         Job *j;
939
940         assert(m);
941
942         while ((j = hashmap_first(m->jobs)))
943                 /* No need to recurse. We're cancelling all jobs. */
944                 job_finish_and_invalidate(j, JOB_CANCELED, false);
945 }
946
947 unsigned manager_dispatch_run_queue(Manager *m) {
948         Job *j;
949         unsigned n = 0;
950
951         if (m->dispatching_run_queue)
952                 return 0;
953
954         m->dispatching_run_queue = true;
955
956         while ((j = m->run_queue)) {
957                 assert(j->installed);
958                 assert(j->in_run_queue);
959
960                 job_run_and_invalidate(j);
961                 n++;
962         }
963
964         m->dispatching_run_queue = false;
965         return n;
966 }
967
968 unsigned manager_dispatch_dbus_queue(Manager *m) {
969         Job *j;
970         Unit *u;
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
980         while ((u = m->dbus_unit_queue)) {
981                 assert(u->in_dbus_queue);
982
983                 bus_unit_send_change_signal(u);
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;
996 }
997
998 static 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
1030                         if (errno == EAGAIN || errno == EINTR)
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
1046                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
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
1052                 assert((size_t) n < sizeof(buf));
1053                 buf[n] = 0;
1054                 if (!(tags = strv_split(buf, "\n\r")))
1055                         return -ENOMEM;
1056
1057                 log_debug("Got notification message for unit %s", u->id);
1058
1059                 if (UNIT_VTABLE(u)->notify_message)
1060                         UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1061
1062                 strv_free(tags);
1063         }
1064
1065         return 0;
1066 }
1067
1068 static int manager_dispatch_sigchld(Manager *m) {
1069         assert(m);
1070
1071         for (;;) {
1072                 siginfo_t si;
1073                 Unit *u;
1074                 int r;
1075
1076                 zero(si);
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) {
1082
1083                         if (errno == ECHILD)
1084                                 break;
1085
1086                         if (errno == EINTR)
1087                                 continue;
1088
1089                         return -errno;
1090                 }
1091
1092                 if (si.si_pid <= 0)
1093                         break;
1094
1095                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
1096                         char *name = NULL;
1097
1098                         get_process_comm(si.si_pid, &name);
1099                         log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
1100                         free(name);
1101                 }
1102
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 */
1111                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
1112                         u = cgroup_unit_by_pid(m, si.si_pid);
1113
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
1122                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
1123                         continue;
1124
1125                 log_debug("Child %lu died (code=%s, status=%i/%s)",
1126                           (long unsigned) si.si_pid,
1127                           sigchld_code_to_string(si.si_code),
1128                           si.si_status,
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)));
1132
1133                 if (!u)
1134                         continue;
1135
1136                 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->id);
1137
1138                 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
1139                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
1140         }
1141
1142         return 0;
1143 }
1144
1145 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
1146         int r;
1147         DBusError error;
1148
1149         dbus_error_init(&error);
1150
1151         log_debug("Activating special unit %s", name);
1152
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));
1155
1156         dbus_error_free(&error);
1157
1158         return r;
1159 }
1160
1161 static int manager_process_signal_fd(Manager *m) {
1162         ssize_t n;
1163         struct signalfd_siginfo sfsi;
1164         bool sigchld = false;
1165
1166         assert(m);
1167
1168         for (;;) {
1169                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
1170
1171                         if (n >= 0)
1172                                 return -EIO;
1173
1174                         if (errno == EINTR || errno == EAGAIN)
1175                                 break;
1176
1177                         return -errno;
1178                 }
1179
1180                 if (sfsi.ssi_pid > 0) {
1181                         char *p = NULL;
1182
1183                         get_process_comm(sfsi.ssi_pid, &p);
1184
1185                         log_debug("Received SIG%s from PID %lu (%s).",
1186                                   signal_to_string(sfsi.ssi_signo),
1187                                   (unsigned long) sfsi.ssi_pid, strna(p));
1188                         free(p);
1189                 } else
1190                         log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
1191
1192                 switch (sfsi.ssi_signo) {
1193
1194                 case SIGCHLD:
1195                         sigchld = true;
1196                         break;
1197
1198                 case SIGTERM:
1199                         if (m->running_as == SYSTEMD_SYSTEM) {
1200                                 /* This is for compatibility with the
1201                                  * original sysvinit */
1202                                 m->exit_code = MANAGER_REEXECUTE;
1203                                 break;
1204                         }
1205
1206                         /* Fall through */
1207
1208                 case SIGINT:
1209                         if (m->running_as == SYSTEMD_SYSTEM) {
1210                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
1211                                 break;
1212                         }
1213
1214                         /* Run the exit target if there is one, if not, just exit. */
1215                         if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
1216                                 m->exit_code = MANAGER_EXIT;
1217                                 return 0;
1218                         }
1219
1220                         break;
1221
1222                 case SIGWINCH:
1223                         if (m->running_as == SYSTEMD_SYSTEM)
1224                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
1225
1226                         /* This is a nop on non-init */
1227                         break;
1228
1229                 case SIGPWR:
1230                         if (m->running_as == SYSTEMD_SYSTEM)
1231                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
1232
1233                         /* This is a nop on non-init */
1234                         break;
1235
1236                 case SIGUSR1: {
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...");
1243                                 bus_init(m, true);
1244                         }
1245
1246                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
1247                                 log_info("Loading D-Bus service...");
1248                                 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
1249                         }
1250
1251                         break;
1252                 }
1253
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
1278                         break;
1279                 }
1280
1281                 case SIGHUP:
1282                         m->exit_code = MANAGER_RELOAD;
1283                         break;
1284
1285                 default: {
1286
1287                         /* Starting SIGRTMIN+0 */
1288                         static const char * const target_table[] = {
1289                                 [0] = SPECIAL_DEFAULT_TARGET,
1290                                 [1] = SPECIAL_RESCUE_TARGET,
1291                                 [2] = SPECIAL_EMERGENCY_TARGET,
1292                                 [3] = SPECIAL_HALT_TARGET,
1293                                 [4] = SPECIAL_POWEROFF_TARGET,
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
1304                         };
1305
1306                         if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
1307                             (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
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);
1311                                 break;
1312                         }
1313
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
1320                         switch (sfsi.ssi_signo - SIGRTMIN) {
1321
1322                         case 20:
1323                                 log_debug("Enabling showing of status.");
1324                                 manager_set_show_status(m, true);
1325                                 break;
1326
1327                         case 21:
1328                                 log_debug("Disabling showing of status.");
1329                                 manager_set_show_status(m, false);
1330                                 break;
1331
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
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
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
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
1371                         default:
1372                                 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
1373                         }
1374                 }
1375                 }
1376         }
1377
1378         if (sigchld)
1379                 return manager_dispatch_sigchld(m);
1380
1381         return 0;
1382 }
1383
1384 static int process_event(Manager *m, struct epoll_event *ev) {
1385         int r;
1386         Watch *w;
1387
1388         assert(m);
1389         assert(ev);
1390
1391         assert_se(w = ev->data.ptr);
1392
1393         if (w->type == WATCH_INVALID)
1394                 return 0;
1395
1396         switch (w->type) {
1397
1398         case WATCH_SIGNAL:
1399
1400                 /* An incoming signal? */
1401                 if (ev->events != EPOLLIN)
1402                         return -EINVAL;
1403
1404                 if ((r = manager_process_signal_fd(m)) < 0)
1405                         return r;
1406
1407                 break;
1408
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
1420         case WATCH_FD:
1421
1422                 /* Some fd event, to be dispatched to the units */
1423                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
1424                 break;
1425
1426         case WATCH_UNIT_TIMER:
1427         case WATCH_JOB_TIMER: {
1428                 uint64_t v;
1429                 ssize_t k;
1430
1431                 /* Some timer event, to be dispatched to the units */
1432                 k = read(w->fd, &v, sizeof(v));
1433                 if (k != sizeof(v)) {
1434
1435                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
1436                                 break;
1437
1438                         log_error("Failed to read timer event counter: %s", k < 0 ? strerror(-k) : "Short read");
1439                         return k < 0 ? -errno : -EIO;
1440                 }
1441
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);
1446                 break;
1447         }
1448
1449         case WATCH_MOUNT:
1450                 /* Some mount table change, intended for the mount subsystem */
1451                 mount_fd_event(m, ev->events);
1452                 break;
1453
1454         case WATCH_SWAP:
1455                 /* Some swap table change, intended for the swap subsystem */
1456                 swap_fd_event(m, ev->events);
1457                 break;
1458
1459         case WATCH_UDEV:
1460                 /* Some notification from udev, intended for the device subsystem */
1461                 device_fd_event(m, ev->events);
1462                 break;
1463
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
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
1494         default:
1495                 log_error("event type=%i", w->type);
1496                 assert_not_reached("Unknown epoll event type.");
1497         }
1498
1499         return 0;
1500 }
1501
1502 int manager_loop(Manager *m) {
1503         int r;
1504
1505         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
1506
1507         assert(m);
1508         m->exit_code = MANAGER_RUNNING;
1509
1510         /* Release the path cache */
1511         set_free_free(m->unit_path_cache);
1512         m->unit_path_cache = NULL;
1513
1514         manager_check_finished(m);
1515
1516         /* There might still be some zombies hanging around from
1517          * before we were exec()'ed. Leat's reap them */
1518         r = manager_dispatch_sigchld(m);
1519         if (r < 0)
1520                 return r;
1521
1522         while (m->exit_code == MANAGER_RUNNING) {
1523                 struct epoll_event event;
1524                 int n;
1525                 int wait_msec = -1;
1526
1527                 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM)
1528                         watchdog_ping();
1529
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);
1534                         continue;
1535                 }
1536
1537                 if (manager_dispatch_load_queue(m) > 0)
1538                         continue;
1539
1540                 if (manager_dispatch_run_queue(m) > 0)
1541                         continue;
1542
1543                 if (bus_dispatch(m) > 0)
1544                         continue;
1545
1546                 if (manager_dispatch_cleanup_queue(m) > 0)
1547                         continue;
1548
1549                 if (manager_dispatch_gc_queue(m) > 0)
1550                         continue;
1551
1552                 if (manager_dispatch_dbus_queue(m) > 0)
1553                         continue;
1554
1555                 if (swap_dispatch_reload(m) > 0)
1556                         continue;
1557
1558                 /* Sleep for half the watchdog time */
1559                 if (m->runtime_watchdog > 0 && m->running_as == SYSTEMD_SYSTEM) {
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
1566                 n = epoll_wait(m->epoll_fd, &event, 1, wait_msec);
1567                 if (n < 0) {
1568
1569                         if (errno == EINTR)
1570                                 continue;
1571
1572                         return -errno;
1573                 } else if (n == 0)
1574                         continue;
1575
1576                 assert(n == 1);
1577
1578                 r = process_event(m, &event);
1579                 if (r < 0)
1580                         return r;
1581         }
1582
1583         return m->exit_code;
1584 }
1585
1586 int manager_load_unit_from_dbus_path(Manager *m, const char *s, DBusError *e, Unit **_u) {
1587         char *n;
1588         Unit *u;
1589         int r;
1590
1591         assert(m);
1592         assert(s);
1593         assert(_u);
1594
1595         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
1596                 return -EINVAL;
1597
1598         n = bus_path_unescape(s+31);
1599         if (!n)
1600                 return -ENOMEM;
1601
1602         r = manager_load_unit(m, n, NULL, e, &u);
1603         free(n);
1604
1605         if (r < 0)
1606                 return r;
1607
1608         *_u = u;
1609
1610         return 0;
1611 }
1612
1613 int 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
1625         r = safe_atou(s + 30, &id);
1626         if (r < 0)
1627                 return r;
1628
1629         j = manager_get_job(m, id);
1630         if (!j)
1631                 return -ENOENT;
1632
1633         *_j = j;
1634
1635         return 0;
1636 }
1637
1638 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
1639
1640 #ifdef HAVE_AUDIT
1641         char *p;
1642         int audit_fd;
1643
1644         audit_fd = get_audit_fd();
1645         if (audit_fd < 0)
1646                 return;
1647
1648         /* Don't generate audit events if the service was already
1649          * started and we're just deserializing */
1650         if (m->n_reloading > 0)
1651                 return;
1652
1653         if (m->running_as != SYSTEMD_SYSTEM)
1654                 return;
1655
1656         if (u->type != UNIT_SERVICE)
1657                 return;
1658
1659         if (!(p = unit_name_to_prefix_and_instance(u->id))) {
1660                 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
1661                 return;
1662         }
1663
1664         if (audit_log_user_comm_message(audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
1665                 if (errno == EPERM) {
1666                         /* We aren't allowed to send audit messages?
1667                          * Then let's not retry again. */
1668                         close_audit_fd();
1669                 } else
1670                         log_warning("Failed to send audit message: %m");
1671         }
1672
1673         free(p);
1674 #endif
1675
1676 }
1677
1678 void 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;
1683
1684         /* Don't generate plymouth events if the service was already
1685          * started and we're just deserializing */
1686         if (m->n_reloading > 0)
1687                 return;
1688
1689         if (m->running_as != SYSTEMD_SYSTEM)
1690                 return;
1691
1692         if (u->type != UNIT_SERVICE &&
1693             u->type != UNIT_MOUNT &&
1694             u->type != UNIT_SWAP)
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;
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) {
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
1720         if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
1721                 log_oom();
1722                 goto finish;
1723         }
1724
1725         errno = 0;
1726         if (write(fd, message, n + 1) != n + 1) {
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
1739 finish:
1740         if (fd >= 0)
1741                 close_nointr_nofail(fd);
1742
1743         free(message);
1744 }
1745
1746 void 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
1763 void 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
1780 int manager_open_serialization(Manager *m, FILE **_f) {
1781         char *path = NULL;
1782         mode_t saved_umask;
1783         int fd;
1784         FILE *f;
1785
1786         assert(_f);
1787
1788         if (m->running_as == SYSTEMD_SYSTEM)
1789                 asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
1790         else
1791                 asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
1792
1793         if (!path)
1794                 return -ENOMEM;
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
1810         if (!(f = fdopen(fd, "w+")))
1811                 return -errno;
1812
1813         *_f = f;
1814
1815         return 0;
1816 }
1817
1818 int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool serialize_jobs) {
1819         Iterator i;
1820         Unit *u;
1821         const char *t;
1822         int r;
1823
1824         assert(m);
1825         assert(f);
1826         assert(fds);
1827
1828         m->n_reloading ++;
1829
1830         fprintf(f, "current-job-id=%i\n", m->current_job_id);
1831         fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
1832         fprintf(f, "n-installed-jobs=%u\n", m->n_installed_jobs);
1833         fprintf(f, "n-failed-jobs=%u\n", m->n_failed_jobs);
1834
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);
1838         dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
1839
1840         if (!in_initrd()) {
1841                 dual_timestamp_serialize(f, "userspace-timestamp", &m->userspace_timestamp);
1842                 dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
1843         }
1844
1845         fputc('\n', f);
1846
1847         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
1848                 if (u->id != t)
1849                         continue;
1850
1851                 if (!unit_can_serialize(u))
1852                         continue;
1853
1854                 /* Start marker */
1855                 fputs(u->id, f);
1856                 fputc('\n', f);
1857
1858                 if ((r = unit_serialize(u, f, fds, serialize_jobs)) < 0) {
1859                         m->n_reloading --;
1860                         return r;
1861                 }
1862         }
1863
1864         assert(m->n_reloading > 0);
1865         m->n_reloading --;
1866
1867         if (ferror(f))
1868                 return -EIO;
1869
1870         r = bus_fdset_add_all(m, fds);
1871         if (r < 0)
1872                 return r;
1873
1874         return 0;
1875 }
1876
1877 int 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
1885         m->n_reloading ++;
1886
1887         for (;;) {
1888                 char line[LINE_MAX], *l;
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
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);
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;
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;
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="))
1940                         dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
1941                 else if (startswith(l, "userspace-timestamp="))
1942                         dual_timestamp_deserialize(l+20, &m->userspace_timestamp);
1943                 else if (startswith(l, "finish-timestamp="))
1944                         dual_timestamp_deserialize(l+17, &m->finish_timestamp);
1945                 else
1946                         log_debug("Unknown serialization item '%s'", l);
1947         }
1948
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))
1956                                 r = 0;
1957                         else
1958                                 r = -errno;
1959
1960                         goto finish;
1961                 }
1962
1963                 char_array_0(name);
1964
1965                 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
1966                         goto finish;
1967
1968                 if ((r = unit_deserialize(u, f, fds)) < 0)
1969                         goto finish;
1970         }
1971
1972 finish:
1973         if (ferror(f)) {
1974                 r = -EIO;
1975                 goto finish;
1976         }
1977
1978         assert(m->n_reloading > 0);
1979         m->n_reloading --;
1980
1981         return r;
1982 }
1983
1984 int manager_reload(Manager *m) {
1985         int r, q;
1986         FILE *f;
1987         FDSet *fds;
1988
1989         assert(m);
1990
1991         r = manager_open_serialization(m, &f);
1992         if (r < 0)
1993                 return r;
1994
1995         m->n_reloading ++;
1996
1997         fds = fdset_new();
1998         if (!fds) {
1999                 m->n_reloading --;
2000                 r = -ENOMEM;
2001                 goto finish;
2002         }
2003
2004         r = manager_serialize(m, f, fds, true);
2005         if (r < 0) {
2006                 m->n_reloading --;
2007                 goto finish;
2008         }
2009
2010         if (fseeko(f, 0, SEEK_SET) < 0) {
2011                 m->n_reloading --;
2012                 r = -errno;
2013                 goto finish;
2014         }
2015
2016         /* From here on there is no way back. */
2017         manager_clear_jobs_and_units(m);
2018         manager_undo_generators(m);
2019         lookup_paths_free(&m->lookup_paths);
2020
2021         /* Find new unit paths */
2022         manager_run_generators(m);
2023
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
2032         manager_build_unit_path_cache(m);
2033
2034         /* First, enumerate what we can from all config files */
2035         q = manager_enumerate(m);
2036         if (q < 0)
2037                 r = q;
2038
2039         /* Second, deserialize our stored data */
2040         q = manager_deserialize(m, f, fds);
2041         if (q < 0)
2042                 r = q;
2043
2044         fclose(f);
2045         f = NULL;
2046
2047         /* Third, fire things up! */
2048         q = manager_coldplug(m);
2049         if (q < 0)
2050                 r = q;
2051
2052         assert(m->n_reloading > 0);
2053         m->n_reloading--;
2054
2055 finish:
2056         if (f)
2057                 fclose(f);
2058
2059         if (fds)
2060                 fdset_free(fds);
2061
2062         return r;
2063 }
2064
2065 bool manager_is_booting_or_shutting_down(Manager *m) {
2066         Unit *u;
2067
2068         assert(m);
2069
2070         /* Is the initial job still around? */
2071         if (manager_get_job(m, m->default_unit_job_id))
2072                 return true;
2073
2074         /* Is there a job for the shutdown target? */
2075         u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2076         if (u)
2077                 return !!u->job;
2078
2079         return false;
2080 }
2081
2082 void manager_reset_failed(Manager *m) {
2083         Unit *u;
2084         Iterator i;
2085
2086         assert(m);
2087
2088         HASHMAP_FOREACH(u, m->units, i)
2089                 unit_reset_failed(u);
2090 }
2091
2092 bool 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 */
2099         if (!(u = manager_get_unit(m, name)))
2100                 return true;
2101
2102         return unit_pending_inactive(u);
2103 }
2104
2105 void manager_check_finished(Manager *m) {
2106         char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2107         usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
2108
2109         assert(m);
2110
2111         if (hashmap_size(m->jobs) > 0)
2112                 return;
2113
2114         /* Notify Type=idle units that we are done now */
2115         close_pipe(m->idle_pipe);
2116
2117         /* Turn off confirm spawn now */
2118         m->confirm_spawn = false;
2119
2120         if (dual_timestamp_is_set(&m->finish_timestamp))
2121                 return;
2122
2123         dual_timestamp_get(&m->finish_timestamp);
2124
2125         if (m->running_as == SYSTEMD_SYSTEM && detect_container(NULL) <= 0) {
2126
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
2132                 firmware_usec = m->firmware_timestamp.monotonic - m->loader_timestamp.monotonic;
2133                 loader_usec = m->loader_timestamp.monotonic - m->kernel_timestamp.monotonic;
2134                 userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
2135                 total_usec = m->firmware_timestamp.monotonic + m->finish_timestamp.monotonic;
2136
2137                 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
2138
2139                         kernel_usec = m->initrd_timestamp.monotonic - m->kernel_timestamp.monotonic;
2140                         initrd_usec = m->userspace_timestamp.monotonic - m->initrd_timestamp.monotonic;
2141
2142                         if (!log_on_console())
2143                                 log_struct(LOG_INFO,
2144                                            MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
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);
2154                 } else {
2155                         kernel_usec = m->userspace_timestamp.monotonic - m->kernel_timestamp.monotonic;
2156                         initrd_usec = 0;
2157
2158                         if (!log_on_console())
2159                                 log_struct(LOG_INFO,
2160                                            MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
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);
2168                 }
2169         } else {
2170                 firmware_usec = loader_usec = initrd_usec = kernel_usec = 0;
2171                 total_usec = userspace_usec = m->finish_timestamp.monotonic - m->userspace_timestamp.monotonic;
2172
2173                 if (!log_on_console())
2174                         log_struct(LOG_INFO,
2175                                    MESSAGE_ID(SD_MESSAGE_STARTUP_FINISHED),
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);
2180         }
2181
2182         bus_broadcast_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
2183
2184         sd_notifyf(false,
2185                    "READY=1\nSTATUS=Startup finished in %s.",
2186                    format_timespan(sum, sizeof(sum), total_usec));
2187 }
2188
2189 static 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
2200         if (m->running_as == SYSTEMD_SYSTEM && getpid() == 1) {
2201
2202                 p = strappend("/run/systemd/", name);
2203                 if (!p)
2204                         return log_oom();
2205
2206                 r = mkdir_p_label(p, 0755);
2207                 if (r < 0) {
2208                         log_error("Failed to create generator directory: %s", strerror(-r));
2209                         free(p);
2210                         return r;
2211                 }
2212         } else {
2213                 p = strjoin("/tmp/systemd-", name, ".XXXXXX", NULL);
2214                 if (!p)
2215                         return log_oom();
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
2228 static 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
2243 void manager_run_generators(Manager *m) {
2244         DIR *d = NULL;
2245         const char *generator_path;
2246         const char *argv[5];
2247         mode_t u;
2248         int r;
2249
2250         assert(m);
2251
2252         generator_path = m->running_as == SYSTEMD_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
2253         d = opendir(generator_path);
2254         if (!d) {
2255                 if (errno == ENOENT)
2256                         return;
2257
2258                 log_error("Failed to enumerate generator directory: %m");
2259                 return;
2260         }
2261
2262         r = create_generator_dir(m, &m->generator_unit_path, "generator");
2263         if (r < 0)
2264                 goto finish;
2265
2266         r = create_generator_dir(m, &m->generator_unit_path_early, "generator.early");
2267         if (r < 0)
2268                 goto finish;
2269
2270         r = create_generator_dir(m, &m->generator_unit_path_late, "generator.late");
2271         if (r < 0)
2272                 goto finish;
2273
2274         argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
2275         argv[1] = m->generator_unit_path;
2276         argv[2] = m->generator_unit_path_early;
2277         argv[3] = m->generator_unit_path_late;
2278         argv[4] = NULL;
2279
2280         u = umask(0022);
2281         execute_directory(generator_path, d, (char**) argv);
2282         umask(u);
2283
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);
2287
2288 finish:
2289         if (d)
2290                 closedir(d);
2291 }
2292
2293 static void remove_generator_dir(Manager *m, char **generator) {
2294         assert(m);
2295         assert(generator);
2296
2297         if (!*generator)
2298                 return;
2299
2300         strv_remove(m->lookup_paths.unit_path, *generator);
2301         rm_rf(*generator, false, true, false);
2302
2303         free(*generator);
2304         *generator = NULL;
2305 }
2306
2307 void 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);
2313 }
2314
2315 int manager_set_default_controllers(Manager *m, char **controllers) {
2316         char **l;
2317
2318         assert(m);
2319
2320         l = strv_copy(controllers);
2321         if (!l)
2322                 return -ENOMEM;
2323
2324         strv_free(m->default_controllers);
2325         m->default_controllers = l;
2326
2327         cg_shorten_controllers(m->default_controllers);
2328
2329         return 0;
2330 }
2331
2332 int 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++) {
2338                 if (!default_rlimit[i])
2339                         continue;
2340
2341                 m->rlimit[i] = newdup(struct rlimit, default_rlimit[i], 1);
2342                 if (!m->rlimit[i])
2343                         return -ENOMEM;
2344         }
2345
2346         return 0;
2347 }
2348
2349 void manager_recheck_journal(Manager *m) {
2350         Unit *u;
2351
2352         assert(m);
2353
2354         if (m->running_as != SYSTEMD_SYSTEM)
2355                 return;
2356
2357         u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
2358         if (u && SOCKET(u)->state != SOCKET_RUNNING) {
2359                 log_close_journal();
2360                 return;
2361         }
2362
2363         u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
2364         if (u && SERVICE(u)->state != SERVICE_RUNNING) {
2365                 log_close_journal();
2366                 return;
2367         }
2368
2369         /* Hmm, OK, so the socket is fully up and the service is up
2370          * too, then let's make use of the thing. */
2371         log_open();
2372 }
2373
2374 void manager_set_show_status(Manager *m, bool b) {
2375         assert(m);
2376
2377         if (m->running_as != SYSTEMD_SYSTEM)
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
2388 bool manager_get_show_status(Manager *m) {
2389         assert(m);
2390
2391         if (m->running_as != SYSTEMD_SYSTEM)
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 }
2402
2403 void watch_init(Watch *w) {
2404         assert(w);
2405
2406         w->type = WATCH_INVALID;
2407         w->fd = -1;
2408 }