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