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