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