chiark / gitweb /
869c99f5c5685bd719a1c4b965d20cd98c13d118
[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
40 #ifdef HAVE_AUDIT
41 #include <libaudit.h>
42 #endif
43
44 #include <systemd/sd-daemon.h>
45
46 #include "manager.h"
47 #include "hashmap.h"
48 #include "macro.h"
49 #include "strv.h"
50 #include "log.h"
51 #include "util.h"
52 #include "mkdir.h"
53 #include "ratelimit.h"
54 #include "cgroup.h"
55 #include "mount-setup.h"
56 #include "unit-name.h"
57 #include "dbus-unit.h"
58 #include "dbus-job.h"
59 #include "missing.h"
60 #include "path-lookup.h"
61 #include "special.h"
62 #include "bus-errors.h"
63 #include "exit-status.h"
64 #include "virt.h"
65 #include "watchdog.h"
66
67 /* As soon as 16 units are in our GC queue, make sure to run a gc sweep */
68 #define GC_QUEUE_ENTRIES_MAX 16
69
70 /* As soon as 5s passed since a unit was added to our GC queue, make sure to run a gc sweep */
71 #define GC_QUEUE_USEC_MAX (10*USEC_PER_SEC)
72
73 /* Where clients shall send notification messages to */
74 #define NOTIFY_SOCKET_SYSTEM "/run/systemd/notify"
75 #define NOTIFY_SOCKET_USER "@/org/freedesktop/systemd1/notify"
76
77 static int manager_setup_notify(Manager *m) {
78         union {
79                 struct sockaddr sa;
80                 struct sockaddr_un un;
81         } sa;
82         struct epoll_event ev;
83         int one = 1, r;
84         mode_t u;
85
86         assert(m);
87
88         m->notify_watch.type = WATCH_NOTIFY;
89         if ((m->notify_watch.fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
90                 log_error("Failed to allocate notification socket: %m");
91                 return -errno;
92         }
93
94         zero(sa);
95         sa.sa.sa_family = AF_UNIX;
96
97         if (getpid() != 1)
98                 snprintf(sa.un.sun_path, sizeof(sa.un.sun_path), NOTIFY_SOCKET_USER "/%llu", random_ull());
99         else {
100                 unlink(NOTIFY_SOCKET_SYSTEM);
101                 strncpy(sa.un.sun_path, NOTIFY_SOCKET_SYSTEM, sizeof(sa.un.sun_path));
102         }
103
104         if (sa.un.sun_path[0] == '@')
105                 sa.un.sun_path[0] = 0;
106
107         u = umask(0111);
108         r = bind(m->notify_watch.fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1));
109         umask(u);
110
111         if (r < 0) {
112                 log_error("bind() failed: %m");
113                 return -errno;
114         }
115
116         if (setsockopt(m->notify_watch.fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0) {
117                 log_error("SO_PASSCRED failed: %m");
118                 return -errno;
119         }
120
121         zero(ev);
122         ev.events = EPOLLIN;
123         ev.data.ptr = &m->notify_watch;
124
125         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->notify_watch.fd, &ev) < 0)
126                 return -errno;
127
128         if (sa.un.sun_path[0] == 0)
129                 sa.un.sun_path[0] = '@';
130
131         if (!(m->notify_socket = strdup(sa.un.sun_path)))
132                 return -ENOMEM;
133
134         log_debug("Using notification socket %s", m->notify_socket);
135
136         return 0;
137 }
138
139 static int enable_special_signals(Manager *m) {
140         int fd;
141
142         assert(m);
143
144         /* Enable that we get SIGINT on control-alt-del. In containers
145          * this will fail with EPERM, so ignore that. */
146         if (reboot(RB_DISABLE_CAD) < 0 && errno != EPERM)
147                 log_warning("Failed to enable ctrl-alt-del handling: %m");
148
149         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
150         if (fd < 0) {
151                 /* Support systems without virtual console */
152                 if (fd != -ENOENT)
153                         log_warning("Failed to open /dev/tty0: %m");
154         } else {
155                 /* Enable that we get SIGWINCH on kbrequest */
156                 if (ioctl(fd, KDSIGACCEPT, SIGWINCH) < 0)
157                         log_warning("Failed to enable kbrequest handling: %s", strerror(errno));
158
159                 close_nointr_nofail(fd);
160         }
161
162         return 0;
163 }
164
165 static int manager_setup_signals(Manager *m) {
166         sigset_t mask;
167         struct epoll_event ev;
168         struct sigaction sa;
169
170         assert(m);
171
172         /* We are not interested in SIGSTOP and friends. */
173         zero(sa);
174         sa.sa_handler = SIG_DFL;
175         sa.sa_flags = SA_NOCLDSTOP|SA_RESTART;
176         assert_se(sigaction(SIGCHLD, &sa, NULL) == 0);
177
178         assert_se(sigemptyset(&mask) == 0);
179
180         sigset_add_many(&mask,
181                         SIGCHLD,     /* Child died */
182                         SIGTERM,     /* Reexecute daemon */
183                         SIGHUP,      /* Reload configuration */
184                         SIGUSR1,     /* systemd/upstart: reconnect to D-Bus */
185                         SIGUSR2,     /* systemd: dump status */
186                         SIGINT,      /* Kernel sends us this on control-alt-del */
187                         SIGWINCH,    /* Kernel sends us this on kbrequest (alt-arrowup) */
188                         SIGPWR,      /* Some kernel drivers and upsd send us this on power failure */
189                         SIGRTMIN+0,  /* systemd: start default.target */
190                         SIGRTMIN+1,  /* systemd: isolate rescue.target */
191                         SIGRTMIN+2,  /* systemd: isolate emergency.target */
192                         SIGRTMIN+3,  /* systemd: start halt.target */
193                         SIGRTMIN+4,  /* systemd: start poweroff.target */
194                         SIGRTMIN+5,  /* systemd: start reboot.target */
195                         SIGRTMIN+6,  /* systemd: start kexec.target */
196                         SIGRTMIN+13, /* systemd: Immediate halt */
197                         SIGRTMIN+14, /* systemd: Immediate poweroff */
198                         SIGRTMIN+15, /* systemd: Immediate reboot */
199                         SIGRTMIN+16, /* systemd: Immediate kexec */
200                         SIGRTMIN+20, /* systemd: enable status messages */
201                         SIGRTMIN+21, /* systemd: disable status messages */
202                         SIGRTMIN+22, /* systemd: set log level to LOG_DEBUG */
203                         SIGRTMIN+23, /* systemd: set log level to LOG_INFO */
204                         SIGRTMIN+26, /* systemd: set log target to journal-or-kmsg */
205                         SIGRTMIN+27, /* systemd: set log target to console */
206                         SIGRTMIN+28, /* systemd: set log target to kmsg */
207                         SIGRTMIN+29, /* systemd: set log target to syslog-or-kmsg */
208                         -1);
209         assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) == 0);
210
211         m->signal_watch.type = WATCH_SIGNAL;
212         if ((m->signal_watch.fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC)) < 0)
213                 return -errno;
214
215         zero(ev);
216         ev.events = EPOLLIN;
217         ev.data.ptr = &m->signal_watch;
218
219         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->signal_watch.fd, &ev) < 0)
220                 return -errno;
221
222         if (m->running_as == MANAGER_SYSTEM)
223                 return enable_special_signals(m);
224
225         return 0;
226 }
227
228 static void manager_strip_environment(Manager *m) {
229         assert(m);
230
231         /* Remove variables from the inherited set that are part of
232          * the container interface:
233          * http://www.freedesktop.org/wiki/Software/systemd/ContainerInterface */
234         strv_remove_prefix(m->environment, "container=");
235         strv_remove_prefix(m->environment, "container_");
236
237         /* Remove variables from the inherited set that are part of
238          * the initrd interface:
239          * http://www.freedesktop.org/wiki/Software/systemd/InitrdInterface */
240         strv_remove_prefix(m->environment, "RD_");
241 }
242
243 int manager_new(ManagerRunningAs running_as, Manager **_m) {
244         Manager *m;
245         int r = -ENOMEM;
246
247         assert(_m);
248         assert(running_as >= 0);
249         assert(running_as < _MANAGER_RUNNING_AS_MAX);
250
251         if (!(m = new0(Manager, 1)))
252                 return -ENOMEM;
253
254         dual_timestamp_get(&m->startup_timestamp);
255
256         m->running_as = running_as;
257         m->name_data_slot = m->conn_data_slot = m->subscribed_data_slot = -1;
258         m->exit_code = _MANAGER_EXIT_CODE_INVALID;
259         m->pin_cgroupfs_fd = -1;
260
261 #ifdef HAVE_AUDIT
262         m->audit_fd = -1;
263 #endif
264
265         m->signal_watch.fd = m->mount_watch.fd = m->udev_watch.fd = m->epoll_fd = m->dev_autofs_fd = m->swap_watch.fd = -1;
266         m->current_job_id = 1; /* start as id #1, so that we can leave #0 around as "null-like" value */
267
268         m->environment = strv_copy(environ);
269         if (!m->environment)
270                 goto fail;
271
272         manager_strip_environment(m);
273
274         if (running_as == MANAGER_SYSTEM) {
275                 m->default_controllers = strv_new("cpu", NULL);
276                 if (!m->default_controllers)
277                         goto fail;
278         }
279
280         if (!(m->units = hashmap_new(string_hash_func, string_compare_func)))
281                 goto fail;
282
283         if (!(m->jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
284                 goto fail;
285
286         if (!(m->transaction_jobs = hashmap_new(trivial_hash_func, trivial_compare_func)))
287                 goto fail;
288
289         if (!(m->watch_pids = hashmap_new(trivial_hash_func, trivial_compare_func)))
290                 goto fail;
291
292         if (!(m->cgroup_bondings = hashmap_new(string_hash_func, string_compare_func)))
293                 goto fail;
294
295         if (!(m->watch_bus = hashmap_new(string_hash_func, string_compare_func)))
296                 goto fail;
297
298         if ((m->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
299                 goto fail;
300
301         if ((r = lookup_paths_init(&m->lookup_paths, m->running_as, true)) < 0)
302                 goto fail;
303
304         if ((r = manager_setup_signals(m)) < 0)
305                 goto fail;
306
307         if ((r = manager_setup_cgroup(m)) < 0)
308                 goto fail;
309
310         if ((r = manager_setup_notify(m)) < 0)
311                 goto fail;
312
313         /* Try to connect to the busses, if possible. */
314         if ((r = bus_init(m, running_as != MANAGER_SYSTEM)) < 0)
315                 goto fail;
316
317 #ifdef HAVE_AUDIT
318         if ((m->audit_fd = audit_open()) < 0 &&
319             /* If the kernel lacks netlink or audit support,
320              * don't worry about it. */
321             errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT)
322                 log_error("Failed to connect to audit log: %m");
323 #endif
324
325         m->taint_usr = dir_is_empty("/usr") > 0;
326
327         *_m = m;
328         return 0;
329
330 fail:
331         manager_free(m);
332         return r;
333 }
334
335 static unsigned manager_dispatch_cleanup_queue(Manager *m) {
336         Unit *u;
337         unsigned n = 0;
338
339         assert(m);
340
341         while ((u = m->cleanup_queue)) {
342                 assert(u->in_cleanup_queue);
343
344                 unit_free(u);
345                 n++;
346         }
347
348         return n;
349 }
350
351 enum {
352         GC_OFFSET_IN_PATH,  /* This one is on the path we were traveling */
353         GC_OFFSET_UNSURE,   /* No clue */
354         GC_OFFSET_GOOD,     /* We still need this unit */
355         GC_OFFSET_BAD,      /* We don't need this unit anymore */
356         _GC_OFFSET_MAX
357 };
358
359 static void unit_gc_sweep(Unit *u, unsigned gc_marker) {
360         Iterator i;
361         Unit *other;
362         bool is_bad;
363
364         assert(u);
365
366         if (u->gc_marker == gc_marker + GC_OFFSET_GOOD ||
367             u->gc_marker == gc_marker + GC_OFFSET_BAD ||
368             u->gc_marker == gc_marker + GC_OFFSET_IN_PATH)
369                 return;
370
371         if (u->in_cleanup_queue)
372                 goto bad;
373
374         if (unit_check_gc(u))
375                 goto good;
376
377         u->gc_marker = gc_marker + GC_OFFSET_IN_PATH;
378
379         is_bad = true;
380
381         SET_FOREACH(other, u->dependencies[UNIT_REFERENCED_BY], i) {
382                 unit_gc_sweep(other, gc_marker);
383
384                 if (other->gc_marker == gc_marker + GC_OFFSET_GOOD)
385                         goto good;
386
387                 if (other->gc_marker != gc_marker + GC_OFFSET_BAD)
388                         is_bad = false;
389         }
390
391         if (is_bad)
392                 goto bad;
393
394         /* We were unable to find anything out about this entry, so
395          * let's investigate it later */
396         u->gc_marker = gc_marker + GC_OFFSET_UNSURE;
397         unit_add_to_gc_queue(u);
398         return;
399
400 bad:
401         /* We definitely know that this one is not useful anymore, so
402          * let's mark it for deletion */
403         u->gc_marker = gc_marker + GC_OFFSET_BAD;
404         unit_add_to_cleanup_queue(u);
405         return;
406
407 good:
408         u->gc_marker = gc_marker + GC_OFFSET_GOOD;
409 }
410
411 static unsigned manager_dispatch_gc_queue(Manager *m) {
412         Unit *u;
413         unsigned n = 0;
414         unsigned gc_marker;
415
416         assert(m);
417
418         if ((m->n_in_gc_queue < GC_QUEUE_ENTRIES_MAX) &&
419             (m->gc_queue_timestamp <= 0 ||
420              (m->gc_queue_timestamp + GC_QUEUE_USEC_MAX) > now(CLOCK_MONOTONIC)))
421                 return 0;
422
423         log_debug("Running GC...");
424
425         m->gc_marker += _GC_OFFSET_MAX;
426         if (m->gc_marker + _GC_OFFSET_MAX <= _GC_OFFSET_MAX)
427                 m->gc_marker = 1;
428
429         gc_marker = m->gc_marker;
430
431         while ((u = m->gc_queue)) {
432                 assert(u->in_gc_queue);
433
434                 unit_gc_sweep(u, gc_marker);
435
436                 LIST_REMOVE(Unit, gc_queue, m->gc_queue, u);
437                 u->in_gc_queue = false;
438
439                 n++;
440
441                 if (u->gc_marker == gc_marker + GC_OFFSET_BAD ||
442                     u->gc_marker == gc_marker + GC_OFFSET_UNSURE) {
443                         log_debug("Collecting %s", u->id);
444                         u->gc_marker = gc_marker + GC_OFFSET_BAD;
445                         unit_add_to_cleanup_queue(u);
446                 }
447         }
448
449         m->n_in_gc_queue = 0;
450         m->gc_queue_timestamp = 0;
451
452         return n;
453 }
454
455 static void manager_clear_jobs_and_units(Manager *m) {
456         Job *j;
457         Unit *u;
458
459         assert(m);
460
461         while ((j = hashmap_first(m->transaction_jobs)))
462                 job_free(j);
463
464         while ((u = hashmap_first(m->units)))
465                 unit_free(u);
466
467         manager_dispatch_cleanup_queue(m);
468
469         assert(!m->load_queue);
470         assert(!m->run_queue);
471         assert(!m->dbus_unit_queue);
472         assert(!m->dbus_job_queue);
473         assert(!m->cleanup_queue);
474         assert(!m->gc_queue);
475
476         assert(hashmap_isempty(m->transaction_jobs));
477         assert(hashmap_isempty(m->jobs));
478         assert(hashmap_isempty(m->units));
479 }
480
481 void manager_free(Manager *m) {
482         UnitType c;
483
484         assert(m);
485
486         manager_clear_jobs_and_units(m);
487
488         for (c = 0; c < _UNIT_TYPE_MAX; c++)
489                 if (unit_vtable[c]->shutdown)
490                         unit_vtable[c]->shutdown(m);
491
492         /* If we reexecute ourselves, we keep the root cgroup
493          * around */
494         manager_shutdown_cgroup(m, m->exit_code != MANAGER_REEXECUTE);
495
496         manager_undo_generators(m);
497
498         bus_done(m);
499
500         hashmap_free(m->units);
501         hashmap_free(m->jobs);
502         hashmap_free(m->transaction_jobs);
503         hashmap_free(m->watch_pids);
504         hashmap_free(m->watch_bus);
505
506         if (m->epoll_fd >= 0)
507                 close_nointr_nofail(m->epoll_fd);
508         if (m->signal_watch.fd >= 0)
509                 close_nointr_nofail(m->signal_watch.fd);
510         if (m->notify_watch.fd >= 0)
511                 close_nointr_nofail(m->notify_watch.fd);
512
513 #ifdef HAVE_AUDIT
514         if (m->audit_fd >= 0)
515                 audit_close(m->audit_fd);
516 #endif
517
518         free(m->notify_socket);
519
520         lookup_paths_free(&m->lookup_paths);
521         strv_free(m->environment);
522
523         strv_free(m->default_controllers);
524
525         hashmap_free(m->cgroup_bondings);
526         set_free_free(m->unit_path_cache);
527
528         free(m);
529 }
530
531 int manager_enumerate(Manager *m) {
532         int r = 0, q;
533         UnitType c;
534
535         assert(m);
536
537         /* Let's ask every type to load all units from disk/kernel
538          * that it might know */
539         for (c = 0; c < _UNIT_TYPE_MAX; c++)
540                 if (unit_vtable[c]->enumerate)
541                         if ((q = unit_vtable[c]->enumerate(m)) < 0)
542                                 r = q;
543
544         manager_dispatch_load_queue(m);
545         return r;
546 }
547
548 int manager_coldplug(Manager *m) {
549         int r = 0, q;
550         Iterator i;
551         Unit *u;
552         char *k;
553
554         assert(m);
555
556         /* Then, let's set up their initial state. */
557         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
558
559                 /* ignore aliases */
560                 if (u->id != k)
561                         continue;
562
563                 if ((q = unit_coldplug(u)) < 0)
564                         r = q;
565         }
566
567         return r;
568 }
569
570 static void manager_build_unit_path_cache(Manager *m) {
571         char **i;
572         DIR *d = NULL;
573         int r;
574
575         assert(m);
576
577         set_free_free(m->unit_path_cache);
578
579         if (!(m->unit_path_cache = set_new(string_hash_func, string_compare_func))) {
580                 log_error("Failed to allocate unit path cache.");
581                 return;
582         }
583
584         /* This simply builds a list of files we know exist, so that
585          * we don't always have to go to disk */
586
587         STRV_FOREACH(i, m->lookup_paths.unit_path) {
588                 struct dirent *de;
589
590                 if (!(d = opendir(*i))) {
591                         log_error("Failed to open directory: %m");
592                         continue;
593                 }
594
595                 while ((de = readdir(d))) {
596                         char *p;
597
598                         if (ignore_file(de->d_name))
599                                 continue;
600
601                         p = join(streq(*i, "/") ? "" : *i, "/", de->d_name, NULL);
602                         if (!p) {
603                                 r = -ENOMEM;
604                                 goto fail;
605                         }
606
607                         if ((r = set_put(m->unit_path_cache, p)) < 0) {
608                                 free(p);
609                                 goto fail;
610                         }
611                 }
612
613                 closedir(d);
614                 d = NULL;
615         }
616
617         return;
618
619 fail:
620         log_error("Failed to build unit path cache: %s", strerror(-r));
621
622         set_free_free(m->unit_path_cache);
623         m->unit_path_cache = NULL;
624
625         if (d)
626                 closedir(d);
627 }
628
629 int manager_startup(Manager *m, FILE *serialization, FDSet *fds) {
630         int r, q;
631
632         assert(m);
633
634         manager_run_generators(m);
635
636         manager_build_unit_path_cache(m);
637
638         /* If we will deserialize make sure that during enumeration
639          * this is already known, so we increase the counter here
640          * already */
641         if (serialization)
642                 m->n_reloading ++;
643
644         /* First, enumerate what we can from all config files */
645         r = manager_enumerate(m);
646
647         /* Second, deserialize if there is something to deserialize */
648         if (serialization)
649                 if ((q = manager_deserialize(m, serialization, fds)) < 0)
650                         r = q;
651
652         /* Third, fire things up! */
653         if ((q = manager_coldplug(m)) < 0)
654                 r = q;
655
656         if (serialization) {
657                 assert(m->n_reloading > 0);
658                 m->n_reloading --;
659         }
660
661         return r;
662 }
663
664 static void transaction_delete_job(Manager *m, Job *j, bool delete_dependencies) {
665         assert(m);
666         assert(j);
667
668         /* Deletes one job from the transaction */
669
670         manager_transaction_unlink_job(m, j, delete_dependencies);
671
672         if (!j->installed)
673                 job_free(j);
674 }
675
676 static void transaction_delete_unit(Manager *m, Unit *u) {
677         Job *j;
678
679         /* Deletes all jobs associated with a certain unit from the
680          * transaction */
681
682         while ((j = hashmap_get(m->transaction_jobs, u)))
683                 transaction_delete_job(m, j, true);
684 }
685
686 static void transaction_clean_dependencies(Manager *m) {
687         Iterator i;
688         Job *j;
689
690         assert(m);
691
692         /* Drops all dependencies of all installed jobs */
693
694         HASHMAP_FOREACH(j, m->jobs, i) {
695                 while (j->subject_list)
696                         job_dependency_free(j->subject_list);
697                 while (j->object_list)
698                         job_dependency_free(j->object_list);
699         }
700
701         assert(!m->transaction_anchor);
702 }
703
704 static void transaction_abort(Manager *m) {
705         Job *j;
706
707         assert(m);
708
709         while ((j = hashmap_first(m->transaction_jobs)))
710                 if (j->installed)
711                         transaction_delete_job(m, j, true);
712                 else
713                         job_free(j);
714
715         assert(hashmap_isempty(m->transaction_jobs));
716
717         transaction_clean_dependencies(m);
718 }
719
720 static void transaction_find_jobs_that_matter_to_anchor(Manager *m, Job *j, unsigned generation) {
721         JobDependency *l;
722
723         assert(m);
724
725         /* A recursive sweep through the graph that marks all units
726          * that matter to the anchor job, i.e. are directly or
727          * indirectly a dependency of the anchor job via paths that
728          * are fully marked as mattering. */
729
730         if (j)
731                 l = j->subject_list;
732         else
733                 l = m->transaction_anchor;
734
735         LIST_FOREACH(subject, l, l) {
736
737                 /* This link does not matter */
738                 if (!l->matters)
739                         continue;
740
741                 /* This unit has already been marked */
742                 if (l->object->generation == generation)
743                         continue;
744
745                 l->object->matters_to_anchor = true;
746                 l->object->generation = generation;
747
748                 transaction_find_jobs_that_matter_to_anchor(m, l->object, generation);
749         }
750 }
751
752 static void transaction_merge_and_delete_job(Manager *m, Job *j, Job *other, JobType t) {
753         JobDependency *l, *last;
754
755         assert(j);
756         assert(other);
757         assert(j->unit == other->unit);
758         assert(!j->installed);
759
760         /* Merges 'other' into 'j' and then deletes j. */
761
762         j->type = t;
763         j->state = JOB_WAITING;
764         j->override = j->override || other->override;
765
766         j->matters_to_anchor = j->matters_to_anchor || other->matters_to_anchor;
767
768         /* Patch us in as new owner of the JobDependency objects */
769         last = NULL;
770         LIST_FOREACH(subject, l, other->subject_list) {
771                 assert(l->subject == other);
772                 l->subject = j;
773                 last = l;
774         }
775
776         /* Merge both lists */
777         if (last) {
778                 last->subject_next = j->subject_list;
779                 if (j->subject_list)
780                         j->subject_list->subject_prev = last;
781                 j->subject_list = other->subject_list;
782         }
783
784         /* Patch us in as new owner of the JobDependency objects */
785         last = NULL;
786         LIST_FOREACH(object, l, other->object_list) {
787                 assert(l->object == other);
788                 l->object = j;
789                 last = l;
790         }
791
792         /* Merge both lists */
793         if (last) {
794                 last->object_next = j->object_list;
795                 if (j->object_list)
796                         j->object_list->object_prev = last;
797                 j->object_list = other->object_list;
798         }
799
800         /* Kill the other job */
801         other->subject_list = NULL;
802         other->object_list = NULL;
803         transaction_delete_job(m, other, true);
804 }
805 static bool job_is_conflicted_by(Job *j) {
806         JobDependency *l;
807
808         assert(j);
809
810         /* Returns true if this job is pulled in by a least one
811          * ConflictedBy dependency. */
812
813         LIST_FOREACH(object, l, j->object_list)
814                 if (l->conflicts)
815                         return true;
816
817         return false;
818 }
819
820 static int delete_one_unmergeable_job(Manager *m, Job *j) {
821         Job *k;
822
823         assert(j);
824
825         /* Tries to delete one item in the linked list
826          * j->transaction_next->transaction_next->... that conflicts
827          * with another one, in an attempt to make an inconsistent
828          * transaction work. */
829
830         /* We rely here on the fact that if a merged with b does not
831          * merge with c, either a or b merge with c neither */
832         LIST_FOREACH(transaction, j, j)
833                 LIST_FOREACH(transaction, k, j->transaction_next) {
834                         Job *d;
835
836                         /* Is this one mergeable? Then skip it */
837                         if (job_type_is_mergeable(j->type, k->type))
838                                 continue;
839
840                         /* Ok, we found two that conflict, let's see if we can
841                          * drop one of them */
842                         if (!j->matters_to_anchor && !k->matters_to_anchor) {
843
844                                 /* Both jobs don't matter, so let's
845                                  * find the one that is smarter to
846                                  * remove. Let's think positive and
847                                  * rather remove stops then starts --
848                                  * except if something is being
849                                  * stopped because it is conflicted by
850                                  * another unit in which case we
851                                  * rather remove the start. */
852
853                                 log_debug("Looking at job %s/%s conflicted_by=%s", j->unit->id, job_type_to_string(j->type), yes_no(j->type == JOB_STOP && job_is_conflicted_by(j)));
854                                 log_debug("Looking at job %s/%s conflicted_by=%s", k->unit->id, job_type_to_string(k->type), yes_no(k->type == JOB_STOP && job_is_conflicted_by(k)));
855
856                                 if (j->type == JOB_STOP) {
857
858                                         if (job_is_conflicted_by(j))
859                                                 d = k;
860                                         else
861                                                 d = j;
862
863                                 } else if (k->type == JOB_STOP) {
864
865                                         if (job_is_conflicted_by(k))
866                                                 d = j;
867                                         else
868                                                 d = k;
869                                 } else
870                                         d = j;
871
872                         } else if (!j->matters_to_anchor)
873                                 d = j;
874                         else if (!k->matters_to_anchor)
875                                 d = k;
876                         else
877                                 return -ENOEXEC;
878
879                         /* Ok, we can drop one, so let's do so. */
880                         log_debug("Fixing conflicting jobs by deleting job %s/%s", d->unit->id, job_type_to_string(d->type));
881                         transaction_delete_job(m, d, true);
882                         return 0;
883                 }
884
885         return -EINVAL;
886 }
887
888 static int transaction_merge_jobs(Manager *m, DBusError *e) {
889         Job *j;
890         Iterator i;
891         int r;
892
893         assert(m);
894
895         /* First step, check whether any of the jobs for one specific
896          * task conflict. If so, try to drop one of them. */
897         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
898                 JobType t;
899                 Job *k;
900
901                 t = j->type;
902                 LIST_FOREACH(transaction, k, j->transaction_next) {
903                         if (job_type_merge(&t, k->type) >= 0)
904                                 continue;
905
906                         /* OK, we could not merge all jobs for this
907                          * action. Let's see if we can get rid of one
908                          * of them */
909
910                         if ((r = delete_one_unmergeable_job(m, j)) >= 0)
911                                 /* Ok, we managed to drop one, now
912                                  * let's ask our callers to call us
913                                  * again after garbage collecting */
914                                 return -EAGAIN;
915
916                         /* We couldn't merge anything. Failure */
917                         dbus_set_error(e, BUS_ERROR_TRANSACTION_JOBS_CONFLICTING, "Transaction contains conflicting jobs '%s' and '%s' for %s. Probably contradicting requirement dependencies configured.",
918                                        job_type_to_string(t), job_type_to_string(k->type), k->unit->id);
919                         return r;
920                 }
921         }
922
923         /* Second step, merge the jobs. */
924         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
925                 JobType t = j->type;
926                 Job *k;
927
928                 /* Merge all transactions */
929                 LIST_FOREACH(transaction, k, j->transaction_next)
930                         assert_se(job_type_merge(&t, k->type) == 0);
931
932                 /* If an active job is mergeable, merge it too */
933                 if (j->unit->job)
934                         job_type_merge(&t, j->unit->job->type); /* Might fail. Which is OK */
935
936                 while ((k = j->transaction_next)) {
937                         if (j->installed) {
938                                 transaction_merge_and_delete_job(m, k, j, t);
939                                 j = k;
940                         } else
941                                 transaction_merge_and_delete_job(m, j, k, t);
942                 }
943
944                 if (j->unit->job && !j->installed)
945                         transaction_merge_and_delete_job(m, j, j->unit->job, t);
946
947                 assert(!j->transaction_next);
948                 assert(!j->transaction_prev);
949         }
950
951         return 0;
952 }
953
954 static void transaction_drop_redundant(Manager *m) {
955         bool again;
956
957         assert(m);
958
959         /* Goes through the transaction and removes all jobs that are
960          * a noop */
961
962         do {
963                 Job *j;
964                 Iterator i;
965
966                 again = false;
967
968                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
969                         bool changes_something = false;
970                         Job *k;
971
972                         LIST_FOREACH(transaction, k, j) {
973
974                                 if (!job_is_anchor(k) &&
975                                     (k->installed || job_type_is_redundant(k->type, unit_active_state(k->unit))) &&
976                                     (!k->unit->job || !job_type_is_conflicting(k->type, k->unit->job->type)))
977                                         continue;
978
979                                 changes_something = true;
980                                 break;
981                         }
982
983                         if (changes_something)
984                                 continue;
985
986                         /* log_debug("Found redundant job %s/%s, dropping.", j->unit->id, job_type_to_string(j->type)); */
987                         transaction_delete_job(m, j, false);
988                         again = true;
989                         break;
990                 }
991
992         } while (again);
993 }
994
995 static bool unit_matters_to_anchor(Unit *u, Job *j) {
996         assert(u);
997         assert(!j->transaction_prev);
998
999         /* Checks whether at least one of the jobs for this unit
1000          * matters to the anchor. */
1001
1002         LIST_FOREACH(transaction, j, j)
1003                 if (j->matters_to_anchor)
1004                         return true;
1005
1006         return false;
1007 }
1008
1009 static int transaction_verify_order_one(Manager *m, Job *j, Job *from, unsigned generation, DBusError *e) {
1010         Iterator i;
1011         Unit *u;
1012         int r;
1013
1014         assert(m);
1015         assert(j);
1016         assert(!j->transaction_prev);
1017
1018         /* Does a recursive sweep through the ordering graph, looking
1019          * for a cycle. If we find cycle we try to break it. */
1020
1021         /* Have we seen this before? */
1022         if (j->generation == generation) {
1023                 Job *k, *delete;
1024
1025                 /* If the marker is NULL we have been here already and
1026                  * decided the job was loop-free from here. Hence
1027                  * shortcut things and return right-away. */
1028                 if (!j->marker)
1029                         return 0;
1030
1031                 /* So, the marker is not NULL and we already have been
1032                  * here. We have a cycle. Let's try to break it. We go
1033                  * backwards in our path and try to find a suitable
1034                  * job to remove. We use the marker to find our way
1035                  * back, since smart how we are we stored our way back
1036                  * in there. */
1037                 log_warning("Found ordering cycle on %s/%s", j->unit->id, job_type_to_string(j->type));
1038
1039                 delete = NULL;
1040                 for (k = from; k; k = ((k->generation == generation && k->marker != k) ? k->marker : NULL)) {
1041
1042                         log_info("Walked on cycle path to %s/%s", k->unit->id, job_type_to_string(k->type));
1043
1044                         if (!delete &&
1045                             !k->installed &&
1046                             !unit_matters_to_anchor(k->unit, k)) {
1047                                 /* Ok, we can drop this one, so let's
1048                                  * do so. */
1049                                 delete = k;
1050                         }
1051
1052                         /* Check if this in fact was the beginning of
1053                          * the cycle */
1054                         if (k == j)
1055                                 break;
1056                 }
1057
1058
1059                 if (delete) {
1060                         log_warning("Breaking ordering cycle by deleting job %s/%s", delete->unit->id, job_type_to_string(delete->type));
1061                         transaction_delete_unit(m, delete->unit);
1062                         return -EAGAIN;
1063                 }
1064
1065                 log_error("Unable to break cycle");
1066
1067                 dbus_set_error(e, BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC, "Transaction order is cyclic. See system logs for details.");
1068                 return -ENOEXEC;
1069         }
1070
1071         /* Make the marker point to where we come from, so that we can
1072          * find our way backwards if we want to break a cycle. We use
1073          * a special marker for the beginning: we point to
1074          * ourselves. */
1075         j->marker = from ? from : j;
1076         j->generation = generation;
1077
1078         /* We assume that the the dependencies are bidirectional, and
1079          * hence can ignore UNIT_AFTER */
1080         SET_FOREACH(u, j->unit->dependencies[UNIT_BEFORE], i) {
1081                 Job *o;
1082
1083                 /* Is there a job for this unit? */
1084                 if (!(o = hashmap_get(m->transaction_jobs, u)))
1085
1086                         /* Ok, there is no job for this in the
1087                          * transaction, but maybe there is already one
1088                          * running? */
1089                         if (!(o = u->job))
1090                                 continue;
1091
1092                 if ((r = transaction_verify_order_one(m, o, j, generation, e)) < 0)
1093                         return r;
1094         }
1095
1096         /* Ok, let's backtrack, and remember that this entry is not on
1097          * our path anymore. */
1098         j->marker = NULL;
1099
1100         return 0;
1101 }
1102
1103 static int transaction_verify_order(Manager *m, unsigned *generation, DBusError *e) {
1104         Job *j;
1105         int r;
1106         Iterator i;
1107         unsigned g;
1108
1109         assert(m);
1110         assert(generation);
1111
1112         /* Check if the ordering graph is cyclic. If it is, try to fix
1113          * that up by dropping one of the jobs. */
1114
1115         g = (*generation)++;
1116
1117         HASHMAP_FOREACH(j, m->transaction_jobs, i)
1118                 if ((r = transaction_verify_order_one(m, j, NULL, g, e)) < 0)
1119                         return r;
1120
1121         return 0;
1122 }
1123
1124 static void transaction_collect_garbage(Manager *m) {
1125         bool again;
1126
1127         assert(m);
1128
1129         /* Drop jobs that are not required by any other job */
1130
1131         do {
1132                 Iterator i;
1133                 Job *j;
1134
1135                 again = false;
1136
1137                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1138                         if (j->object_list) {
1139                                 /* log_debug("Keeping job %s/%s because of %s/%s", */
1140                                 /*           j->unit->id, job_type_to_string(j->type), */
1141                                 /*           j->object_list->subject ? j->object_list->subject->unit->id : "root", */
1142                                 /*           j->object_list->subject ? job_type_to_string(j->object_list->subject->type) : "root"); */
1143                                 continue;
1144                         }
1145
1146                         /* log_debug("Garbage collecting job %s/%s", j->unit->id, job_type_to_string(j->type)); */
1147                         transaction_delete_job(m, j, true);
1148                         again = true;
1149                         break;
1150                 }
1151
1152         } while (again);
1153 }
1154
1155 static int transaction_is_destructive(Manager *m, DBusError *e) {
1156         Iterator i;
1157         Job *j;
1158
1159         assert(m);
1160
1161         /* Checks whether applying this transaction means that
1162          * existing jobs would be replaced */
1163
1164         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1165
1166                 /* Assume merged */
1167                 assert(!j->transaction_prev);
1168                 assert(!j->transaction_next);
1169
1170                 if (j->unit->job &&
1171                     j->unit->job != j &&
1172                     !job_type_is_superset(j->type, j->unit->job->type)) {
1173
1174                         dbus_set_error(e, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE, "Transaction is destructive.");
1175                         return -EEXIST;
1176                 }
1177         }
1178
1179         return 0;
1180 }
1181
1182 static void transaction_minimize_impact(Manager *m) {
1183         bool again;
1184         assert(m);
1185
1186         /* Drops all unnecessary jobs that reverse already active jobs
1187          * or that stop a running service. */
1188
1189         do {
1190                 Job *j;
1191                 Iterator i;
1192
1193                 again = false;
1194
1195                 HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1196                         LIST_FOREACH(transaction, j, j) {
1197                                 bool stops_running_service, changes_existing_job;
1198
1199                                 /* If it matters, we shouldn't drop it */
1200                                 if (j->matters_to_anchor)
1201                                         continue;
1202
1203                                 /* Would this stop a running service?
1204                                  * Would this change an existing job?
1205                                  * If so, let's drop this entry */
1206
1207                                 stops_running_service =
1208                                         j->type == JOB_STOP && UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(j->unit));
1209
1210                                 changes_existing_job =
1211                                         j->unit->job &&
1212                                         job_type_is_conflicting(j->type, j->unit->job->type);
1213
1214                                 if (!stops_running_service && !changes_existing_job)
1215                                         continue;
1216
1217                                 if (stops_running_service)
1218                                         log_debug("%s/%s would stop a running service.", j->unit->id, job_type_to_string(j->type));
1219
1220                                 if (changes_existing_job)
1221                                         log_debug("%s/%s would change existing job.", j->unit->id, job_type_to_string(j->type));
1222
1223                                 /* Ok, let's get rid of this */
1224                                 log_debug("Deleting %s/%s to minimize impact.", j->unit->id, job_type_to_string(j->type));
1225
1226                                 transaction_delete_job(m, j, true);
1227                                 again = true;
1228                                 break;
1229                         }
1230
1231                         if (again)
1232                                 break;
1233                 }
1234
1235         } while (again);
1236 }
1237
1238 static int transaction_apply(Manager *m, JobMode mode) {
1239         Iterator i;
1240         Job *j;
1241         int r;
1242
1243         /* Moves the transaction jobs to the set of active jobs */
1244
1245         if (mode == JOB_ISOLATE) {
1246
1247                 /* When isolating first kill all installed jobs which
1248                  * aren't part of the new transaction */
1249         rescan:
1250                 HASHMAP_FOREACH(j, m->jobs, i) {
1251                         assert(j->installed);
1252
1253                         if (hashmap_get(m->transaction_jobs, j->unit))
1254                                 continue;
1255
1256                         /* 'j' itself is safe to remove, but if other jobs
1257                            are invalidated recursively, our iterator may become
1258                            invalid and we need to start over. */
1259                         if (job_finish_and_invalidate(j, JOB_CANCELED) > 0)
1260                                 goto rescan;
1261                 }
1262         }
1263
1264         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1265                 /* Assume merged */
1266                 assert(!j->transaction_prev);
1267                 assert(!j->transaction_next);
1268
1269                 if (j->installed)
1270                         continue;
1271
1272                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1273                         goto rollback;
1274         }
1275
1276         while ((j = hashmap_steal_first(m->transaction_jobs))) {
1277                 if (j->installed) {
1278                         /* log_debug("Skipping already installed job %s/%s as %u", j->unit->id, job_type_to_string(j->type), (unsigned) j->id); */
1279                         continue;
1280                 }
1281
1282                 if (j->unit->job)
1283                         job_free(j->unit->job);
1284
1285                 j->unit->job = j;
1286                 j->installed = true;
1287                 m->n_installed_jobs ++;
1288
1289                 /* We're fully installed. Now let's free data we don't
1290                  * need anymore. */
1291
1292                 assert(!j->transaction_next);
1293                 assert(!j->transaction_prev);
1294
1295                 job_add_to_run_queue(j);
1296                 job_add_to_dbus_queue(j);
1297                 job_start_timer(j);
1298
1299                 log_debug("Installed new job %s/%s as %u", j->unit->id, job_type_to_string(j->type), (unsigned) j->id);
1300         }
1301
1302         /* As last step, kill all remaining job dependencies. */
1303         transaction_clean_dependencies(m);
1304
1305         return 0;
1306
1307 rollback:
1308
1309         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1310                 if (j->installed)
1311                         continue;
1312
1313                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1314         }
1315
1316         return r;
1317 }
1318
1319 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1320         int r;
1321         unsigned generation = 1;
1322
1323         assert(m);
1324
1325         /* This applies the changes recorded in transaction_jobs to
1326          * the actual list of jobs, if possible. */
1327
1328         /* First step: figure out which jobs matter */
1329         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1330
1331         /* Second step: Try not to stop any running services if
1332          * we don't have to. Don't try to reverse running
1333          * jobs if we don't have to. */
1334         if (mode == JOB_FAIL)
1335                 transaction_minimize_impact(m);
1336
1337         /* Third step: Drop redundant jobs */
1338         transaction_drop_redundant(m);
1339
1340         for (;;) {
1341                 /* Fourth step: Let's remove unneeded jobs that might
1342                  * be lurking. */
1343                 if (mode != JOB_ISOLATE)
1344                         transaction_collect_garbage(m);
1345
1346                 /* Fifth step: verify order makes sense and correct
1347                  * cycles if necessary and possible */
1348                 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1349                         break;
1350
1351                 if (r != -EAGAIN) {
1352                         log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1353                         goto rollback;
1354                 }
1355
1356                 /* Let's see if the resulting transaction ordering
1357                  * graph is still cyclic... */
1358         }
1359
1360         for (;;) {
1361                 /* Sixth step: let's drop unmergeable entries if
1362                  * necessary and possible, merge entries we can
1363                  * merge */
1364                 if ((r = transaction_merge_jobs(m, e)) >= 0)
1365                         break;
1366
1367                 if (r != -EAGAIN) {
1368                         log_warning("Requested transaction contains unmergeable jobs: %s", bus_error(e, r));
1369                         goto rollback;
1370                 }
1371
1372                 /* Seventh step: an entry got dropped, let's garbage
1373                  * collect its dependencies. */
1374                 if (mode != JOB_ISOLATE)
1375                         transaction_collect_garbage(m);
1376
1377                 /* Let's see if the resulting transaction still has
1378                  * unmergeable entries ... */
1379         }
1380
1381         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1382         transaction_drop_redundant(m);
1383
1384         /* Ninth step: check whether we can actually apply this */
1385         if (mode == JOB_FAIL)
1386                 if ((r = transaction_is_destructive(m, e)) < 0) {
1387                         log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1388                         goto rollback;
1389                 }
1390
1391         /* Tenth step: apply changes */
1392         if ((r = transaction_apply(m, mode)) < 0) {
1393                 log_warning("Failed to apply transaction: %s", strerror(-r));
1394                 goto rollback;
1395         }
1396
1397         assert(hashmap_isempty(m->transaction_jobs));
1398         assert(!m->transaction_anchor);
1399
1400         return 0;
1401
1402 rollback:
1403         transaction_abort(m);
1404         return r;
1405 }
1406
1407 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1408         Job *j, *f;
1409
1410         assert(m);
1411         assert(unit);
1412
1413         /* Looks for an existing prospective job and returns that. If
1414          * it doesn't exist it is created and added to the prospective
1415          * jobs list. */
1416
1417         f = hashmap_get(m->transaction_jobs, unit);
1418
1419         LIST_FOREACH(transaction, j, f) {
1420                 assert(j->unit == unit);
1421
1422                 if (j->type == type) {
1423                         if (is_new)
1424                                 *is_new = false;
1425                         return j;
1426                 }
1427         }
1428
1429         if (unit->job && unit->job->type == type)
1430                 j = unit->job;
1431         else if (!(j = job_new(m, type, unit)))
1432                 return NULL;
1433
1434         j->generation = 0;
1435         j->marker = NULL;
1436         j->matters_to_anchor = false;
1437         j->override = override;
1438
1439         LIST_PREPEND(Job, transaction, f, j);
1440
1441         if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1442                 job_free(j);
1443                 return NULL;
1444         }
1445
1446         if (is_new)
1447                 *is_new = true;
1448
1449         /* log_debug("Added job %s/%s to transaction.", unit->id, job_type_to_string(type)); */
1450
1451         return j;
1452 }
1453
1454 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1455         assert(m);
1456         assert(j);
1457
1458         if (j->transaction_prev)
1459                 j->transaction_prev->transaction_next = j->transaction_next;
1460         else if (j->transaction_next)
1461                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1462         else
1463                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1464
1465         if (j->transaction_next)
1466                 j->transaction_next->transaction_prev = j->transaction_prev;
1467
1468         j->transaction_prev = j->transaction_next = NULL;
1469
1470         while (j->subject_list)
1471                 job_dependency_free(j->subject_list);
1472
1473         while (j->object_list) {
1474                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1475
1476                 job_dependency_free(j->object_list);
1477
1478                 if (other && delete_dependencies) {
1479                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1480                                   other->unit->id, job_type_to_string(other->type),
1481                                   j->unit->id, job_type_to_string(j->type));
1482                         transaction_delete_job(m, other, delete_dependencies);
1483                 }
1484         }
1485 }
1486
1487 static int transaction_add_job_and_dependencies(
1488                 Manager *m,
1489                 JobType type,
1490                 Unit *unit,
1491                 Job *by,
1492                 bool matters,
1493                 bool override,
1494                 bool conflicts,
1495                 bool ignore_requirements,
1496                 bool ignore_order,
1497                 DBusError *e,
1498                 Job **_ret) {
1499         Job *ret;
1500         Iterator i;
1501         Unit *dep;
1502         int r;
1503         bool is_new;
1504
1505         assert(m);
1506         assert(type < _JOB_TYPE_MAX);
1507         assert(unit);
1508
1509         /* log_debug("Pulling in %s/%s from %s/%s", */
1510         /*           unit->id, job_type_to_string(type), */
1511         /*           by ? by->unit->id : "NA", */
1512         /*           by ? job_type_to_string(by->type) : "NA"); */
1513
1514         if (unit->load_state != UNIT_LOADED &&
1515             unit->load_state != UNIT_ERROR &&
1516             unit->load_state != UNIT_MASKED) {
1517                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->id);
1518                 return -EINVAL;
1519         }
1520
1521         if (type != JOB_STOP && unit->load_state == UNIT_ERROR) {
1522                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1523                                "Unit %s failed to load: %s. "
1524                                "See system logs and 'systemctl status %s' for details.",
1525                                unit->id,
1526                                strerror(-unit->load_error),
1527                                unit->id);
1528                 return -EINVAL;
1529         }
1530
1531         if (type != JOB_STOP && unit->load_state == UNIT_MASKED) {
1532                 dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->id);
1533                 return -EINVAL;
1534         }
1535
1536         if (!unit_job_is_applicable(unit, type)) {
1537                 dbus_set_error(e, BUS_ERROR_JOB_TYPE_NOT_APPLICABLE, "Job type %s is not applicable for unit %s.", job_type_to_string(type), unit->id);
1538                 return -EBADR;
1539         }
1540
1541         /* First add the job. */
1542         if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1543                 return -ENOMEM;
1544
1545         ret->ignore_order = ret->ignore_order || ignore_order;
1546
1547         /* Then, add a link to the job. */
1548         if (!job_dependency_new(by, ret, matters, conflicts))
1549                 return -ENOMEM;
1550
1551         if (is_new && !ignore_requirements) {
1552                 Set *following;
1553
1554                 /* If we are following some other unit, make sure we
1555                  * add all dependencies of everybody following. */
1556                 if (unit_following_set(ret->unit, &following) > 0) {
1557                         SET_FOREACH(dep, following, i)
1558                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, false, override, false, false, ignore_order, e, NULL)) < 0) {
1559                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1560
1561                                         if (e)
1562                                                 dbus_error_free(e);
1563                                 }
1564
1565                         set_free(following);
1566                 }
1567
1568                 /* Finally, recursively add in all dependencies. */
1569                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1570                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRES], i)
1571                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1572                                         if (r != -EBADR)
1573                                                 goto fail;
1574
1575                                         if (e)
1576                                                 dbus_error_free(e);
1577                                 }
1578
1579                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_BIND_TO], i)
1580                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1581
1582                                         if (r != -EBADR)
1583                                                 goto fail;
1584
1585                                         if (e)
1586                                                 dbus_error_free(e);
1587                                 }
1588
1589                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1590                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, false, ignore_order, e, NULL)) < 0) {
1591                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1592
1593                                         if (e)
1594                                                 dbus_error_free(e);
1595                                 }
1596
1597                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_WANTS], i)
1598                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, false, ignore_order, e, NULL)) < 0) {
1599                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1600
1601                                         if (e)
1602                                                 dbus_error_free(e);
1603                                 }
1604
1605                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUISITE], i)
1606                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1607
1608                                         if (r != -EBADR)
1609                                                 goto fail;
1610
1611                                         if (e)
1612                                                 dbus_error_free(e);
1613                                 }
1614
1615                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1616                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, false, ignore_order, e, NULL)) < 0) {
1617                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1618
1619                                         if (e)
1620                                                 dbus_error_free(e);
1621                                 }
1622
1623                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_CONFLICTS], i)
1624                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, false, ignore_order, e, NULL)) < 0) {
1625
1626                                         if (r != -EBADR)
1627                                                 goto fail;
1628
1629                                         if (e)
1630                                                 dbus_error_free(e);
1631                                 }
1632
1633                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_CONFLICTED_BY], i)
1634                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, false, override, false, false, ignore_order, e, NULL)) < 0) {
1635                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1636
1637                                         if (e)
1638                                                 dbus_error_free(e);
1639                                 }
1640
1641                 }
1642
1643                 if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1644
1645                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_REQUIRED_BY], i)
1646                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1647
1648                                         if (r != -EBADR)
1649                                                 goto fail;
1650
1651                                         if (e)
1652                                                 dbus_error_free(e);
1653                                 }
1654
1655                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_BOUND_BY], i)
1656                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1657
1658                                         if (r != -EBADR)
1659                                                 goto fail;
1660
1661                                         if (e)
1662                                                 dbus_error_free(e);
1663                                 }
1664                 }
1665
1666                 if (type == JOB_RELOAD || type == JOB_RELOAD_OR_START) {
1667
1668                         SET_FOREACH(dep, ret->unit->dependencies[UNIT_PROPAGATE_RELOAD_TO], i) {
1669                                 r = transaction_add_job_and_dependencies(m, JOB_RELOAD, dep, ret, false, override, false, false, ignore_order, e, NULL);
1670
1671                                 if (r < 0) {
1672                                         log_warning("Cannot add dependency reload job for unit %s, ignoring: %s", dep->id, bus_error(e, r));
1673
1674                                         if (e)
1675                                                 dbus_error_free(e);
1676                                 }
1677                         }
1678                 }
1679
1680                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1681         }
1682
1683         if (_ret)
1684                 *_ret = ret;
1685
1686         return 0;
1687
1688 fail:
1689         return r;
1690 }
1691
1692 static int transaction_add_isolate_jobs(Manager *m) {
1693         Iterator i;
1694         Unit *u;
1695         char *k;
1696         int r;
1697
1698         assert(m);
1699
1700         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1701
1702                 /* ignore aliases */
1703                 if (u->id != k)
1704                         continue;
1705
1706                 if (u->ignore_on_isolate)
1707                         continue;
1708
1709                 /* No need to stop inactive jobs */
1710                 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->job)
1711                         continue;
1712
1713                 /* Is there already something listed for this? */
1714                 if (hashmap_get(m->transaction_jobs, u))
1715                         continue;
1716
1717                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, false, false, NULL, NULL)) < 0)
1718                         log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->id, strerror(-r));
1719         }
1720
1721         return 0;
1722 }
1723
1724 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1725         int r;
1726         Job *ret;
1727
1728         assert(m);
1729         assert(type < _JOB_TYPE_MAX);
1730         assert(unit);
1731         assert(mode < _JOB_MODE_MAX);
1732
1733         if (mode == JOB_ISOLATE && type != JOB_START) {
1734                 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1735                 return -EINVAL;
1736         }
1737
1738         if (mode == JOB_ISOLATE && !unit->allow_isolate) {
1739                 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1740                 return -EPERM;
1741         }
1742
1743         log_debug("Trying to enqueue job %s/%s/%s", unit->id, job_type_to_string(type), job_mode_to_string(mode));
1744
1745         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false,
1746                                                       mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
1747                                                       mode == JOB_IGNORE_DEPENDENCIES, e, &ret)) < 0) {
1748                 transaction_abort(m);
1749                 return r;
1750         }
1751
1752         if (mode == JOB_ISOLATE)
1753                 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1754                         transaction_abort(m);
1755                         return r;
1756                 }
1757
1758         if ((r = transaction_activate(m, mode, e)) < 0)
1759                 return r;
1760
1761         log_debug("Enqueued job %s/%s as %u", unit->id, job_type_to_string(type), (unsigned) ret->id);
1762
1763         if (_ret)
1764                 *_ret = ret;
1765
1766         return 0;
1767 }
1768
1769 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1770         Unit *unit;
1771         int r;
1772
1773         assert(m);
1774         assert(type < _JOB_TYPE_MAX);
1775         assert(name);
1776         assert(mode < _JOB_MODE_MAX);
1777
1778         if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1779                 return r;
1780
1781         return manager_add_job(m, type, unit, mode, override, e, _ret);
1782 }
1783
1784 Job *manager_get_job(Manager *m, uint32_t id) {
1785         assert(m);
1786
1787         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1788 }
1789
1790 Unit *manager_get_unit(Manager *m, const char *name) {
1791         assert(m);
1792         assert(name);
1793
1794         return hashmap_get(m->units, name);
1795 }
1796
1797 unsigned manager_dispatch_load_queue(Manager *m) {
1798         Unit *u;
1799         unsigned n = 0;
1800
1801         assert(m);
1802
1803         /* Make sure we are not run recursively */
1804         if (m->dispatching_load_queue)
1805                 return 0;
1806
1807         m->dispatching_load_queue = true;
1808
1809         /* Dispatches the load queue. Takes a unit from the queue and
1810          * tries to load its data until the queue is empty */
1811
1812         while ((u = m->load_queue)) {
1813                 assert(u->in_load_queue);
1814
1815                 unit_load(u);
1816                 n++;
1817         }
1818
1819         m->dispatching_load_queue = false;
1820         return n;
1821 }
1822
1823 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1824         Unit *ret;
1825         UnitType t;
1826         int r;
1827
1828         assert(m);
1829         assert(name || path);
1830
1831         /* This will prepare the unit for loading, but not actually
1832          * load anything from disk. */
1833
1834         if (path && !is_path(path)) {
1835                 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1836                 return -EINVAL;
1837         }
1838
1839         if (!name)
1840                 name = file_name_from_path(path);
1841
1842         t = unit_name_to_type(name);
1843
1844         if (t == _UNIT_TYPE_INVALID || !unit_name_is_valid_no_type(name, false)) {
1845                 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1846                 return -EINVAL;
1847         }
1848
1849         ret = manager_get_unit(m, name);
1850         if (ret) {
1851                 *_ret = ret;
1852                 return 1;
1853         }
1854
1855         ret = unit_new(m, unit_vtable[t]->object_size);
1856         if (!ret)
1857                 return -ENOMEM;
1858
1859         if (path) {
1860                 ret->fragment_path = strdup(path);
1861                 if (!ret->fragment_path) {
1862                         unit_free(ret);
1863                         return -ENOMEM;
1864                 }
1865         }
1866
1867         if ((r = unit_add_name(ret, name)) < 0) {
1868                 unit_free(ret);
1869                 return r;
1870         }
1871
1872         unit_add_to_load_queue(ret);
1873         unit_add_to_dbus_queue(ret);
1874         unit_add_to_gc_queue(ret);
1875
1876         if (_ret)
1877                 *_ret = ret;
1878
1879         return 0;
1880 }
1881
1882 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1883         int r;
1884
1885         assert(m);
1886
1887         /* This will load the service information files, but not actually
1888          * start any services or anything. */
1889
1890         if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1891                 return r;
1892
1893         manager_dispatch_load_queue(m);
1894
1895         if (_ret)
1896                 *_ret = unit_follow_merge(*_ret);
1897
1898         return 0;
1899 }
1900
1901 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1902         Iterator i;
1903         Job *j;
1904
1905         assert(s);
1906         assert(f);
1907
1908         HASHMAP_FOREACH(j, s->jobs, i)
1909                 job_dump(j, f, prefix);
1910 }
1911
1912 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1913         Iterator i;
1914         Unit *u;
1915         const char *t;
1916
1917         assert(s);
1918         assert(f);
1919
1920         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1921                 if (u->id == t)
1922                         unit_dump(u, f, prefix);
1923 }
1924
1925 void manager_clear_jobs(Manager *m) {
1926         Job *j;
1927
1928         assert(m);
1929
1930         transaction_abort(m);
1931
1932         while ((j = hashmap_first(m->jobs)))
1933                 job_finish_and_invalidate(j, JOB_CANCELED);
1934 }
1935
1936 unsigned manager_dispatch_run_queue(Manager *m) {
1937         Job *j;
1938         unsigned n = 0;
1939
1940         if (m->dispatching_run_queue)
1941                 return 0;
1942
1943         m->dispatching_run_queue = true;
1944
1945         while ((j = m->run_queue)) {
1946                 assert(j->installed);
1947                 assert(j->in_run_queue);
1948
1949                 job_run_and_invalidate(j);
1950                 n++;
1951         }
1952
1953         m->dispatching_run_queue = false;
1954         return n;
1955 }
1956
1957 unsigned manager_dispatch_dbus_queue(Manager *m) {
1958         Job *j;
1959         Unit *u;
1960         unsigned n = 0;
1961
1962         assert(m);
1963
1964         if (m->dispatching_dbus_queue)
1965                 return 0;
1966
1967         m->dispatching_dbus_queue = true;
1968
1969         while ((u = m->dbus_unit_queue)) {
1970                 assert(u->in_dbus_queue);
1971
1972                 bus_unit_send_change_signal(u);
1973                 n++;
1974         }
1975
1976         while ((j = m->dbus_job_queue)) {
1977                 assert(j->in_dbus_queue);
1978
1979                 bus_job_send_change_signal(j);
1980                 n++;
1981         }
1982
1983         m->dispatching_dbus_queue = false;
1984         return n;
1985 }
1986
1987 static int manager_process_notify_fd(Manager *m) {
1988         ssize_t n;
1989
1990         assert(m);
1991
1992         for (;;) {
1993                 char buf[4096];
1994                 struct msghdr msghdr;
1995                 struct iovec iovec;
1996                 struct ucred *ucred;
1997                 union {
1998                         struct cmsghdr cmsghdr;
1999                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
2000                 } control;
2001                 Unit *u;
2002                 char **tags;
2003
2004                 zero(iovec);
2005                 iovec.iov_base = buf;
2006                 iovec.iov_len = sizeof(buf)-1;
2007
2008                 zero(control);
2009                 zero(msghdr);
2010                 msghdr.msg_iov = &iovec;
2011                 msghdr.msg_iovlen = 1;
2012                 msghdr.msg_control = &control;
2013                 msghdr.msg_controllen = sizeof(control);
2014
2015                 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
2016                         if (n >= 0)
2017                                 return -EIO;
2018
2019                         if (errno == EAGAIN || errno == EINTR)
2020                                 break;
2021
2022                         return -errno;
2023                 }
2024
2025                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
2026                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
2027                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
2028                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
2029                         log_warning("Received notify message without credentials. Ignoring.");
2030                         continue;
2031                 }
2032
2033                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
2034
2035                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
2036                         if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
2037                                 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
2038                                 continue;
2039                         }
2040
2041                 assert((size_t) n < sizeof(buf));
2042                 buf[n] = 0;
2043                 if (!(tags = strv_split(buf, "\n\r")))
2044                         return -ENOMEM;
2045
2046                 log_debug("Got notification message for unit %s", u->id);
2047
2048                 if (UNIT_VTABLE(u)->notify_message)
2049                         UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
2050
2051                 strv_free(tags);
2052         }
2053
2054         return 0;
2055 }
2056
2057 static int manager_dispatch_sigchld(Manager *m) {
2058         assert(m);
2059
2060         for (;;) {
2061                 siginfo_t si;
2062                 Unit *u;
2063                 int r;
2064
2065                 zero(si);
2066
2067                 /* First we call waitd() for a PID and do not reap the
2068                  * zombie. That way we can still access /proc/$PID for
2069                  * it while it is a zombie. */
2070                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
2071
2072                         if (errno == ECHILD)
2073                                 break;
2074
2075                         if (errno == EINTR)
2076                                 continue;
2077
2078                         return -errno;
2079                 }
2080
2081                 if (si.si_pid <= 0)
2082                         break;
2083
2084                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
2085                         char *name = NULL;
2086
2087                         get_process_comm(si.si_pid, &name);
2088                         log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
2089                         free(name);
2090                 }
2091
2092                 /* Let's flush any message the dying child might still
2093                  * have queued for us. This ensures that the process
2094                  * still exists in /proc so that we can figure out
2095                  * which cgroup and hence unit it belongs to. */
2096                 if ((r = manager_process_notify_fd(m)) < 0)
2097                         return r;
2098
2099                 /* And now figure out the unit this belongs to */
2100                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
2101                         u = cgroup_unit_by_pid(m, si.si_pid);
2102
2103                 /* And now, we actually reap the zombie. */
2104                 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
2105                         if (errno == EINTR)
2106                                 continue;
2107
2108                         return -errno;
2109                 }
2110
2111                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
2112                         continue;
2113
2114                 log_debug("Child %lu died (code=%s, status=%i/%s)",
2115                           (long unsigned) si.si_pid,
2116                           sigchld_code_to_string(si.si_code),
2117                           si.si_status,
2118                           strna(si.si_code == CLD_EXITED
2119                                 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2120                                 : signal_to_string(si.si_status)));
2121
2122                 if (!u)
2123                         continue;
2124
2125                 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->id);
2126
2127                 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
2128                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
2129         }
2130
2131         return 0;
2132 }
2133
2134 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
2135         int r;
2136         DBusError error;
2137
2138         dbus_error_init(&error);
2139
2140         log_debug("Activating special unit %s", name);
2141
2142         if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
2143                 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
2144
2145         dbus_error_free(&error);
2146
2147         return r;
2148 }
2149
2150 static int manager_process_signal_fd(Manager *m) {
2151         ssize_t n;
2152         struct signalfd_siginfo sfsi;
2153         bool sigchld = false;
2154
2155         assert(m);
2156
2157         for (;;) {
2158                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
2159
2160                         if (n >= 0)
2161                                 return -EIO;
2162
2163                         if (errno == EINTR || errno == EAGAIN)
2164                                 break;
2165
2166                         return -errno;
2167                 }
2168
2169                 if (sfsi.ssi_pid > 0) {
2170                         char *p = NULL;
2171
2172                         get_process_comm(sfsi.ssi_pid, &p);
2173
2174                         log_debug("Received SIG%s from PID %lu (%s).",
2175                                   signal_to_string(sfsi.ssi_signo),
2176                                   (unsigned long) sfsi.ssi_pid, strna(p));
2177                         free(p);
2178                 } else
2179                         log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
2180
2181                 switch (sfsi.ssi_signo) {
2182
2183                 case SIGCHLD:
2184                         sigchld = true;
2185                         break;
2186
2187                 case SIGTERM:
2188                         if (m->running_as == MANAGER_SYSTEM) {
2189                                 /* This is for compatibility with the
2190                                  * original sysvinit */
2191                                 m->exit_code = MANAGER_REEXECUTE;
2192                                 break;
2193                         }
2194
2195                         /* Fall through */
2196
2197                 case SIGINT:
2198                         if (m->running_as == MANAGER_SYSTEM) {
2199                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
2200                                 break;
2201                         }
2202
2203                         /* Run the exit target if there is one, if not, just exit. */
2204                         if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
2205                                 m->exit_code = MANAGER_EXIT;
2206                                 return 0;
2207                         }
2208
2209                         break;
2210
2211                 case SIGWINCH:
2212                         if (m->running_as == MANAGER_SYSTEM)
2213                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2214
2215                         /* This is a nop on non-init */
2216                         break;
2217
2218                 case SIGPWR:
2219                         if (m->running_as == MANAGER_SYSTEM)
2220                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2221
2222                         /* This is a nop on non-init */
2223                         break;
2224
2225                 case SIGUSR1: {
2226                         Unit *u;
2227
2228                         u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2229
2230                         if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2231                                 log_info("Trying to reconnect to bus...");
2232                                 bus_init(m, true);
2233                         }
2234
2235                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2236                                 log_info("Loading D-Bus service...");
2237                                 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2238                         }
2239
2240                         break;
2241                 }
2242
2243                 case SIGUSR2: {
2244                         FILE *f;
2245                         char *dump = NULL;
2246                         size_t size;
2247
2248                         if (!(f = open_memstream(&dump, &size))) {
2249                                 log_warning("Failed to allocate memory stream.");
2250                                 break;
2251                         }
2252
2253                         manager_dump_units(m, f, "\t");
2254                         manager_dump_jobs(m, f, "\t");
2255
2256                         if (ferror(f)) {
2257                                 fclose(f);
2258                                 free(dump);
2259                                 log_warning("Failed to write status stream");
2260                                 break;
2261                         }
2262
2263                         fclose(f);
2264                         log_dump(LOG_INFO, dump);
2265                         free(dump);
2266
2267                         break;
2268                 }
2269
2270                 case SIGHUP:
2271                         m->exit_code = MANAGER_RELOAD;
2272                         break;
2273
2274                 default: {
2275
2276                         /* Starting SIGRTMIN+0 */
2277                         static const char * const target_table[] = {
2278                                 [0] = SPECIAL_DEFAULT_TARGET,
2279                                 [1] = SPECIAL_RESCUE_TARGET,
2280                                 [2] = SPECIAL_EMERGENCY_TARGET,
2281                                 [3] = SPECIAL_HALT_TARGET,
2282                                 [4] = SPECIAL_POWEROFF_TARGET,
2283                                 [5] = SPECIAL_REBOOT_TARGET,
2284                                 [6] = SPECIAL_KEXEC_TARGET
2285                         };
2286
2287                         /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2288                         static const ManagerExitCode code_table[] = {
2289                                 [0] = MANAGER_HALT,
2290                                 [1] = MANAGER_POWEROFF,
2291                                 [2] = MANAGER_REBOOT,
2292                                 [3] = MANAGER_KEXEC
2293                         };
2294
2295                         if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2296                             (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2297                                 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
2298                                 manager_start_target(m, target_table[idx],
2299                                                      (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
2300                                 break;
2301                         }
2302
2303                         if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2304                             (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2305                                 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2306                                 break;
2307                         }
2308
2309                         switch (sfsi.ssi_signo - SIGRTMIN) {
2310
2311                         case 20:
2312                                 log_debug("Enabling showing of status.");
2313                                 manager_set_show_status(m, true);
2314                                 break;
2315
2316                         case 21:
2317                                 log_debug("Disabling showing of status.");
2318                                 manager_set_show_status(m, false);
2319                                 break;
2320
2321                         case 22:
2322                                 log_set_max_level(LOG_DEBUG);
2323                                 log_notice("Setting log level to debug.");
2324                                 break;
2325
2326                         case 23:
2327                                 log_set_max_level(LOG_INFO);
2328                                 log_notice("Setting log level to info.");
2329                                 break;
2330
2331                         case 26:
2332                                 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2333                                 log_notice("Setting log target to journal-or-kmsg.");
2334                                 break;
2335
2336                         case 27:
2337                                 log_set_target(LOG_TARGET_CONSOLE);
2338                                 log_notice("Setting log target to console.");
2339                                 break;
2340
2341                         case 28:
2342                                 log_set_target(LOG_TARGET_KMSG);
2343                                 log_notice("Setting log target to kmsg.");
2344                                 break;
2345
2346                         case 29:
2347                                 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
2348                                 log_notice("Setting log target to syslog-or-kmsg.");
2349                                 break;
2350
2351                         default:
2352                                 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
2353                         }
2354                 }
2355                 }
2356         }
2357
2358         if (sigchld)
2359                 return manager_dispatch_sigchld(m);
2360
2361         return 0;
2362 }
2363
2364 static int process_event(Manager *m, struct epoll_event *ev) {
2365         int r;
2366         Watch *w;
2367
2368         assert(m);
2369         assert(ev);
2370
2371         assert_se(w = ev->data.ptr);
2372
2373         if (w->type == WATCH_INVALID)
2374                 return 0;
2375
2376         switch (w->type) {
2377
2378         case WATCH_SIGNAL:
2379
2380                 /* An incoming signal? */
2381                 if (ev->events != EPOLLIN)
2382                         return -EINVAL;
2383
2384                 if ((r = manager_process_signal_fd(m)) < 0)
2385                         return r;
2386
2387                 break;
2388
2389         case WATCH_NOTIFY:
2390
2391                 /* An incoming daemon notification event? */
2392                 if (ev->events != EPOLLIN)
2393                         return -EINVAL;
2394
2395                 if ((r = manager_process_notify_fd(m)) < 0)
2396                         return r;
2397
2398                 break;
2399
2400         case WATCH_FD:
2401
2402                 /* Some fd event, to be dispatched to the units */
2403                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2404                 break;
2405
2406         case WATCH_UNIT_TIMER:
2407         case WATCH_JOB_TIMER: {
2408                 uint64_t v;
2409                 ssize_t k;
2410
2411                 /* Some timer event, to be dispatched to the units */
2412                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2413
2414                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
2415                                 break;
2416
2417                         return k < 0 ? -errno : -EIO;
2418                 }
2419
2420                 if (w->type == WATCH_UNIT_TIMER)
2421                         UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2422                 else
2423                         job_timer_event(w->data.job, v, w);
2424                 break;
2425         }
2426
2427         case WATCH_MOUNT:
2428                 /* Some mount table change, intended for the mount subsystem */
2429                 mount_fd_event(m, ev->events);
2430                 break;
2431
2432         case WATCH_SWAP:
2433                 /* Some swap table change, intended for the swap subsystem */
2434                 swap_fd_event(m, ev->events);
2435                 break;
2436
2437         case WATCH_UDEV:
2438                 /* Some notification from udev, intended for the device subsystem */
2439                 device_fd_event(m, ev->events);
2440                 break;
2441
2442         case WATCH_DBUS_WATCH:
2443                 bus_watch_event(m, w, ev->events);
2444                 break;
2445
2446         case WATCH_DBUS_TIMEOUT:
2447                 bus_timeout_event(m, w, ev->events);
2448                 break;
2449
2450         default:
2451                 log_error("event type=%i", w->type);
2452                 assert_not_reached("Unknown epoll event type.");
2453         }
2454
2455         return 0;
2456 }
2457
2458 int manager_loop(Manager *m) {
2459         int r;
2460         int wait_msec = -1;
2461
2462         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
2463
2464         assert(m);
2465         m->exit_code = MANAGER_RUNNING;
2466
2467         /* Release the path cache */
2468         set_free_free(m->unit_path_cache);
2469         m->unit_path_cache = NULL;
2470
2471         manager_check_finished(m);
2472
2473         /* There might still be some zombies hanging around from
2474          * before we were exec()'ed. Leat's reap them */
2475         r = manager_dispatch_sigchld(m);
2476         if (r < 0)
2477                 return r;
2478
2479         /* Sleep for half the watchdog time */
2480         if (m->runtime_watchdog > 0 && m->running_as == MANAGER_SYSTEM)  {
2481                 wait_msec = (int) (m->runtime_watchdog / 2 / USEC_PER_MSEC);
2482                 if (wait_msec <= 0)
2483                         wait_msec = 1;
2484         }
2485
2486         while (m->exit_code == MANAGER_RUNNING) {
2487                 struct epoll_event event;
2488                 int n;
2489
2490                 if (wait_msec >= 0)
2491                         watchdog_ping();
2492
2493                 if (!ratelimit_test(&rl)) {
2494                         /* Yay, something is going seriously wrong, pause a little */
2495                         log_warning("Looping too fast. Throttling execution a little.");
2496                         sleep(1);
2497                         continue;
2498                 }
2499
2500                 if (manager_dispatch_load_queue(m) > 0)
2501                         continue;
2502
2503                 if (manager_dispatch_run_queue(m) > 0)
2504                         continue;
2505
2506                 if (bus_dispatch(m) > 0)
2507                         continue;
2508
2509                 if (manager_dispatch_cleanup_queue(m) > 0)
2510                         continue;
2511
2512                 if (manager_dispatch_gc_queue(m) > 0)
2513                         continue;
2514
2515                 if (manager_dispatch_dbus_queue(m) > 0)
2516                         continue;
2517
2518                 if (swap_dispatch_reload(m) > 0)
2519                         continue;
2520
2521                 n = epoll_wait(m->epoll_fd, &event, 1, wait_msec);
2522                 if (n < 0) {
2523
2524                         if (errno == EINTR)
2525                                 continue;
2526
2527                         return -errno;
2528                 } else if (n == 0)
2529                         continue;
2530
2531                 assert(n == 1);
2532
2533                 r = process_event(m, &event);
2534                 if (r < 0)
2535                         return r;
2536         }
2537
2538         return m->exit_code;
2539 }
2540
2541 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2542         char *n;
2543         Unit *u;
2544
2545         assert(m);
2546         assert(s);
2547         assert(_u);
2548
2549         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2550                 return -EINVAL;
2551
2552         if (!(n = bus_path_unescape(s+31)))
2553                 return -ENOMEM;
2554
2555         u = manager_get_unit(m, n);
2556         free(n);
2557
2558         if (!u)
2559                 return -ENOENT;
2560
2561         *_u = u;
2562
2563         return 0;
2564 }
2565
2566 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2567         Job *j;
2568         unsigned id;
2569         int r;
2570
2571         assert(m);
2572         assert(s);
2573         assert(_j);
2574
2575         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2576                 return -EINVAL;
2577
2578         if ((r = safe_atou(s + 30, &id)) < 0)
2579                 return r;
2580
2581         if (!(j = manager_get_job(m, id)))
2582                 return -ENOENT;
2583
2584         *_j = j;
2585
2586         return 0;
2587 }
2588
2589 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2590
2591 #ifdef HAVE_AUDIT
2592         char *p;
2593
2594         if (m->audit_fd < 0)
2595                 return;
2596
2597         /* Don't generate audit events if the service was already
2598          * started and we're just deserializing */
2599         if (m->n_reloading > 0)
2600                 return;
2601
2602         if (m->running_as != MANAGER_SYSTEM)
2603                 return;
2604
2605         if (u->type != UNIT_SERVICE)
2606                 return;
2607
2608         if (!(p = unit_name_to_prefix_and_instance(u->id))) {
2609                 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2610                 return;
2611         }
2612
2613         if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
2614                 log_warning("Failed to send audit message: %m");
2615
2616                 if (errno == EPERM) {
2617                         /* We aren't allowed to send audit messages?
2618                          * Then let's not retry again, to avoid
2619                          * spamming the user with the same and same
2620                          * messages over and over. */
2621
2622                         audit_close(m->audit_fd);
2623                         m->audit_fd = -1;
2624                 }
2625         }
2626
2627         free(p);
2628 #endif
2629
2630 }
2631
2632 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2633         int fd = -1;
2634         union sockaddr_union sa;
2635         int n = 0;
2636         char *message = NULL;
2637
2638         /* Don't generate plymouth events if the service was already
2639          * started and we're just deserializing */
2640         if (m->n_reloading > 0)
2641                 return;
2642
2643         if (m->running_as != MANAGER_SYSTEM)
2644                 return;
2645
2646         if (u->type != UNIT_SERVICE &&
2647             u->type != UNIT_MOUNT &&
2648             u->type != UNIT_SWAP)
2649                 return;
2650
2651         /* We set SOCK_NONBLOCK here so that we rather drop the
2652          * message then wait for plymouth */
2653         if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2654                 log_error("socket() failed: %m");
2655                 return;
2656         }
2657
2658         zero(sa);
2659         sa.sa.sa_family = AF_UNIX;
2660         strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
2661         if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
2662
2663                 if (errno != EPIPE &&
2664                     errno != EAGAIN &&
2665                     errno != ENOENT &&
2666                     errno != ECONNREFUSED &&
2667                     errno != ECONNRESET &&
2668                     errno != ECONNABORTED)
2669                         log_error("connect() failed: %m");
2670
2671                 goto finish;
2672         }
2673
2674         if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->id) + 1), u->id, &n) < 0) {
2675                 log_error("Out of memory");
2676                 goto finish;
2677         }
2678
2679         errno = 0;
2680         if (write(fd, message, n + 1) != n + 1) {
2681
2682                 if (errno != EPIPE &&
2683                     errno != EAGAIN &&
2684                     errno != ENOENT &&
2685                     errno != ECONNREFUSED &&
2686                     errno != ECONNRESET &&
2687                     errno != ECONNABORTED)
2688                         log_error("Failed to write Plymouth message: %m");
2689
2690                 goto finish;
2691         }
2692
2693 finish:
2694         if (fd >= 0)
2695                 close_nointr_nofail(fd);
2696
2697         free(message);
2698 }
2699
2700 void manager_dispatch_bus_name_owner_changed(
2701                 Manager *m,
2702                 const char *name,
2703                 const char* old_owner,
2704                 const char *new_owner) {
2705
2706         Unit *u;
2707
2708         assert(m);
2709         assert(name);
2710
2711         if (!(u = hashmap_get(m->watch_bus, name)))
2712                 return;
2713
2714         UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2715 }
2716
2717 void manager_dispatch_bus_query_pid_done(
2718                 Manager *m,
2719                 const char *name,
2720                 pid_t pid) {
2721
2722         Unit *u;
2723
2724         assert(m);
2725         assert(name);
2726         assert(pid >= 1);
2727
2728         if (!(u = hashmap_get(m->watch_bus, name)))
2729                 return;
2730
2731         UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2732 }
2733
2734 int manager_open_serialization(Manager *m, FILE **_f) {
2735         char *path = NULL;
2736         mode_t saved_umask;
2737         int fd;
2738         FILE *f;
2739
2740         assert(_f);
2741
2742         if (m->running_as == MANAGER_SYSTEM)
2743                 asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
2744         else
2745                 asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
2746
2747         if (!path)
2748                 return -ENOMEM;
2749
2750         saved_umask = umask(0077);
2751         fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2752         umask(saved_umask);
2753
2754         if (fd < 0) {
2755                 free(path);
2756                 return -errno;
2757         }
2758
2759         unlink(path);
2760
2761         log_debug("Serializing state to %s", path);
2762         free(path);
2763
2764         if (!(f = fdopen(fd, "w+")))
2765                 return -errno;
2766
2767         *_f = f;
2768
2769         return 0;
2770 }
2771
2772 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2773         Iterator i;
2774         Unit *u;
2775         const char *t;
2776         int r;
2777
2778         assert(m);
2779         assert(f);
2780         assert(fds);
2781
2782         m->n_reloading ++;
2783
2784         fprintf(f, "current-job-id=%i\n", m->current_job_id);
2785         fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
2786
2787         dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2788         dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
2789         dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2790
2791         fputc('\n', f);
2792
2793         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2794                 if (u->id != t)
2795                         continue;
2796
2797                 if (!unit_can_serialize(u))
2798                         continue;
2799
2800                 /* Start marker */
2801                 fputs(u->id, f);
2802                 fputc('\n', f);
2803
2804                 if ((r = unit_serialize(u, f, fds)) < 0) {
2805                         m->n_reloading --;
2806                         return r;
2807                 }
2808         }
2809
2810         assert(m->n_reloading > 0);
2811         m->n_reloading --;
2812
2813         if (ferror(f))
2814                 return -EIO;
2815
2816         r = bus_fdset_add_all(m, fds);
2817         if (r < 0)
2818                 return r;
2819
2820         return 0;
2821 }
2822
2823 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2824         int r = 0;
2825
2826         assert(m);
2827         assert(f);
2828
2829         log_debug("Deserializing state...");
2830
2831         m->n_reloading ++;
2832
2833         for (;;) {
2834                 char line[LINE_MAX], *l;
2835
2836                 if (!fgets(line, sizeof(line), f)) {
2837                         if (feof(f))
2838                                 r = 0;
2839                         else
2840                                 r = -errno;
2841
2842                         goto finish;
2843                 }
2844
2845                 char_array_0(line);
2846                 l = strstrip(line);
2847
2848                 if (l[0] == 0)
2849                         break;
2850
2851                 if (startswith(l, "current-job-id=")) {
2852                         uint32_t id;
2853
2854                         if (safe_atou32(l+15, &id) < 0)
2855                                 log_debug("Failed to parse current job id value %s", l+15);
2856                         else
2857                                 m->current_job_id = MAX(m->current_job_id, id);
2858                 } else if (startswith(l, "taint-usr=")) {
2859                         int b;
2860
2861                         if ((b = parse_boolean(l+10)) < 0)
2862                                 log_debug("Failed to parse taint /usr flag %s", l+10);
2863                         else
2864                                 m->taint_usr = m->taint_usr || b;
2865                 } else if (startswith(l, "initrd-timestamp="))
2866                         dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2867                 else if (startswith(l, "startup-timestamp="))
2868                         dual_timestamp_deserialize(l+18, &m->startup_timestamp);
2869                 else if (startswith(l, "finish-timestamp="))
2870                         dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2871                 else
2872                         log_debug("Unknown serialization item '%s'", l);
2873         }
2874
2875         for (;;) {
2876                 Unit *u;
2877                 char name[UNIT_NAME_MAX+2];
2878
2879                 /* Start marker */
2880                 if (!fgets(name, sizeof(name), f)) {
2881                         if (feof(f))
2882                                 r = 0;
2883                         else
2884                                 r = -errno;
2885
2886                         goto finish;
2887                 }
2888
2889                 char_array_0(name);
2890
2891                 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2892                         goto finish;
2893
2894                 if ((r = unit_deserialize(u, f, fds)) < 0)
2895                         goto finish;
2896         }
2897
2898 finish:
2899         if (ferror(f)) {
2900                 r = -EIO;
2901                 goto finish;
2902         }
2903
2904         assert(m->n_reloading > 0);
2905         m->n_reloading --;
2906
2907         return r;
2908 }
2909
2910 int manager_reload(Manager *m) {
2911         int r, q;
2912         FILE *f;
2913         FDSet *fds;
2914
2915         assert(m);
2916
2917         if ((r = manager_open_serialization(m, &f)) < 0)
2918                 return r;
2919
2920         m->n_reloading ++;
2921
2922         if (!(fds = fdset_new())) {
2923                 m->n_reloading --;
2924                 r = -ENOMEM;
2925                 goto finish;
2926         }
2927
2928         if ((r = manager_serialize(m, f, fds)) < 0) {
2929                 m->n_reloading --;
2930                 goto finish;
2931         }
2932
2933         if (fseeko(f, 0, SEEK_SET) < 0) {
2934                 m->n_reloading --;
2935                 r = -errno;
2936                 goto finish;
2937         }
2938
2939         /* From here on there is no way back. */
2940         manager_clear_jobs_and_units(m);
2941         manager_undo_generators(m);
2942
2943         /* Find new unit paths */
2944         lookup_paths_free(&m->lookup_paths);
2945         if ((q = lookup_paths_init(&m->lookup_paths, m->running_as, true)) < 0)
2946                 r = q;
2947
2948         manager_run_generators(m);
2949
2950         manager_build_unit_path_cache(m);
2951
2952         /* First, enumerate what we can from all config files */
2953         if ((q = manager_enumerate(m)) < 0)
2954                 r = q;
2955
2956         /* Second, deserialize our stored data */
2957         if ((q = manager_deserialize(m, f, fds)) < 0)
2958                 r = q;
2959
2960         fclose(f);
2961         f = NULL;
2962
2963         /* Third, fire things up! */
2964         if ((q = manager_coldplug(m)) < 0)
2965                 r = q;
2966
2967         assert(m->n_reloading > 0);
2968         m->n_reloading--;
2969
2970 finish:
2971         if (f)
2972                 fclose(f);
2973
2974         if (fds)
2975                 fdset_free(fds);
2976
2977         return r;
2978 }
2979
2980 bool manager_is_booting_or_shutting_down(Manager *m) {
2981         Unit *u;
2982
2983         assert(m);
2984
2985         /* Is the initial job still around? */
2986         if (manager_get_job(m, m->default_unit_job_id))
2987                 return true;
2988
2989         /* Is there a job for the shutdown target? */
2990         u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2991         if (u)
2992                 return !!u->job;
2993
2994         return false;
2995 }
2996
2997 void manager_reset_failed(Manager *m) {
2998         Unit *u;
2999         Iterator i;
3000
3001         assert(m);
3002
3003         HASHMAP_FOREACH(u, m->units, i)
3004                 unit_reset_failed(u);
3005 }
3006
3007 bool manager_unit_pending_inactive(Manager *m, const char *name) {
3008         Unit *u;
3009
3010         assert(m);
3011         assert(name);
3012
3013         /* Returns true if the unit is inactive or going down */
3014         if (!(u = manager_get_unit(m, name)))
3015                 return true;
3016
3017         return unit_pending_inactive(u);
3018 }
3019
3020 void manager_check_finished(Manager *m) {
3021         char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
3022         usec_t kernel_usec, initrd_usec, userspace_usec, total_usec;
3023
3024         assert(m);
3025
3026         if (dual_timestamp_is_set(&m->finish_timestamp))
3027                 return;
3028
3029         if (hashmap_size(m->jobs) > 0)
3030                 return;
3031
3032         dual_timestamp_get(&m->finish_timestamp);
3033
3034         if (m->running_as == MANAGER_SYSTEM && detect_container(NULL) <= 0) {
3035
3036                 userspace_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
3037                 total_usec = m->finish_timestamp.monotonic;
3038
3039                 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
3040
3041                         kernel_usec = m->initrd_timestamp.monotonic;
3042                         initrd_usec = m->startup_timestamp.monotonic - m->initrd_timestamp.monotonic;
3043
3044                         log_info("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
3045                                  format_timespan(kernel, sizeof(kernel), kernel_usec),
3046                                  format_timespan(initrd, sizeof(initrd), initrd_usec),
3047                                  format_timespan(userspace, sizeof(userspace), userspace_usec),
3048                                  format_timespan(sum, sizeof(sum), total_usec));
3049                 } else {
3050                         kernel_usec = m->startup_timestamp.monotonic;
3051                         initrd_usec = 0;
3052
3053                         log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
3054                                  format_timespan(kernel, sizeof(kernel), kernel_usec),
3055                                  format_timespan(userspace, sizeof(userspace), userspace_usec),
3056                                  format_timespan(sum, sizeof(sum), total_usec));
3057                 }
3058         } else {
3059                 userspace_usec = initrd_usec = kernel_usec = 0;
3060                 total_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
3061
3062                 log_debug("Startup finished in %s.",
3063                           format_timespan(sum, sizeof(sum), total_usec));
3064         }
3065
3066         bus_broadcast_finished(m, kernel_usec, initrd_usec, userspace_usec, total_usec);
3067
3068         sd_notifyf(false,
3069                    "READY=1\nSTATUS=Startup finished in %s.",
3070                    format_timespan(sum, sizeof(sum), total_usec));
3071 }
3072
3073 void manager_run_generators(Manager *m) {
3074         DIR *d = NULL;
3075         const char *generator_path;
3076         const char *argv[3];
3077         mode_t u;
3078
3079         assert(m);
3080
3081         generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
3082         if (!(d = opendir(generator_path))) {
3083
3084                 if (errno == ENOENT)
3085                         return;
3086
3087                 log_error("Failed to enumerate generator directory: %m");
3088                 return;
3089         }
3090
3091         if (!m->generator_unit_path) {
3092                 const char *p;
3093                 char user_path[] = "/tmp/systemd-generator-XXXXXX";
3094
3095                 if (m->running_as == MANAGER_SYSTEM && getpid() == 1) {
3096                         p = "/run/systemd/generator";
3097
3098                         if (mkdir_p(p, 0755) < 0) {
3099                                 log_error("Failed to create generator directory: %m");
3100                                 goto finish;
3101                         }
3102
3103                 } else {
3104                         if (!(p = mkdtemp(user_path))) {
3105                                 log_error("Failed to create generator directory: %m");
3106                                 goto finish;
3107                         }
3108                 }
3109
3110                 if (!(m->generator_unit_path = strdup(p))) {
3111                         log_error("Failed to allocate generator unit path.");
3112                         goto finish;
3113                 }
3114         }
3115
3116         argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
3117         argv[1] = m->generator_unit_path;
3118         argv[2] = NULL;
3119
3120         u = umask(0022);
3121         execute_directory(generator_path, d, (char**) argv);
3122         umask(u);
3123
3124         if (rmdir(m->generator_unit_path) >= 0) {
3125                 /* Uh? we were able to remove this dir? I guess that
3126                  * means the directory was empty, hence let's shortcut
3127                  * this */
3128
3129                 free(m->generator_unit_path);
3130                 m->generator_unit_path = NULL;
3131                 goto finish;
3132         }
3133
3134         if (!strv_find(m->lookup_paths.unit_path, m->generator_unit_path)) {
3135                 char **l;
3136
3137                 if (!(l = strv_append(m->lookup_paths.unit_path, m->generator_unit_path))) {
3138                         log_error("Failed to add generator directory to unit search path: %m");
3139                         goto finish;
3140                 }
3141
3142                 strv_free(m->lookup_paths.unit_path);
3143                 m->lookup_paths.unit_path = l;
3144
3145                 log_debug("Added generator unit path %s to search path.", m->generator_unit_path);
3146         }
3147
3148 finish:
3149         if (d)
3150                 closedir(d);
3151 }
3152
3153 void manager_undo_generators(Manager *m) {
3154         assert(m);
3155
3156         if (!m->generator_unit_path)
3157                 return;
3158
3159         strv_remove(m->lookup_paths.unit_path, m->generator_unit_path);
3160         rm_rf(m->generator_unit_path, false, true, false);
3161
3162         free(m->generator_unit_path);
3163         m->generator_unit_path = NULL;
3164 }
3165
3166 int manager_set_default_controllers(Manager *m, char **controllers) {
3167         char **l;
3168
3169         assert(m);
3170
3171         if (!(l = strv_copy(controllers)))
3172                 return -ENOMEM;
3173
3174         strv_free(m->default_controllers);
3175         m->default_controllers = l;
3176
3177         return 0;
3178 }
3179
3180 void manager_recheck_journal(Manager *m) {
3181         Unit *u;
3182
3183         assert(m);
3184
3185         if (m->running_as != MANAGER_SYSTEM)
3186                 return;
3187
3188         u = manager_get_unit(m, SPECIAL_JOURNALD_SOCKET);
3189         if (u && SOCKET(u)->state != SOCKET_RUNNING) {
3190                 log_close_journal();
3191                 return;
3192         }
3193
3194         u = manager_get_unit(m, SPECIAL_JOURNALD_SERVICE);
3195         if (u && SERVICE(u)->state != SERVICE_RUNNING) {
3196                 log_close_journal();
3197                 return;
3198         }
3199
3200         /* Hmm, OK, so the socket is fully up and the service is up
3201          * too, then let's make use of the thing. */
3202         log_open();
3203 }
3204
3205 void manager_set_show_status(Manager *m, bool b) {
3206         assert(m);
3207
3208         if (m->running_as != MANAGER_SYSTEM)
3209                 return;
3210
3211         m->show_status = b;
3212
3213         if (b)
3214                 touch("/run/systemd/show-status");
3215         else
3216                 unlink("/run/systemd/show-status");
3217 }
3218
3219 bool manager_get_show_status(Manager *m) {
3220         assert(m);
3221
3222         if (m->running_as != MANAGER_SYSTEM)
3223                 return false;
3224
3225         if (m->show_status)
3226                 return true;
3227
3228         /* If Plymouth is running make sure we show the status, so
3229          * that there's something nice to see when people press Esc */
3230
3231         return plymouth_running();
3232 }
3233
3234 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
3235         [MANAGER_SYSTEM] = "system",
3236         [MANAGER_USER] = "user"
3237 };
3238
3239 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);