chiark / gitweb /
journal: properly implement matching with multiple matches
[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                 HASHMAP_FOREACH(j, m->jobs, i) {
1218                         assert(j->installed);
1219
1220                         if (hashmap_get(m->transaction_jobs, j->unit))
1221                                 continue;
1222
1223                         job_finish_and_invalidate(j, JOB_CANCELED);
1224                 }
1225         }
1226
1227         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1228                 /* Assume merged */
1229                 assert(!j->transaction_prev);
1230                 assert(!j->transaction_next);
1231
1232                 if (j->installed)
1233                         continue;
1234
1235                 if ((r = hashmap_put(m->jobs, UINT32_TO_PTR(j->id), j)) < 0)
1236                         goto rollback;
1237         }
1238
1239         while ((j = hashmap_steal_first(m->transaction_jobs))) {
1240                 if (j->installed) {
1241                         /* log_debug("Skipping already installed job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id); */
1242                         continue;
1243                 }
1244
1245                 if (j->unit->meta.job)
1246                         job_free(j->unit->meta.job);
1247
1248                 j->unit->meta.job = j;
1249                 j->installed = true;
1250                 m->n_installed_jobs ++;
1251
1252                 /* We're fully installed. Now let's free data we don't
1253                  * need anymore. */
1254
1255                 assert(!j->transaction_next);
1256                 assert(!j->transaction_prev);
1257
1258                 job_add_to_run_queue(j);
1259                 job_add_to_dbus_queue(j);
1260                 job_start_timer(j);
1261
1262                 log_debug("Installed new job %s/%s as %u", j->unit->meta.id, job_type_to_string(j->type), (unsigned) j->id);
1263         }
1264
1265         /* As last step, kill all remaining job dependencies. */
1266         transaction_clean_dependencies(m);
1267
1268         return 0;
1269
1270 rollback:
1271
1272         HASHMAP_FOREACH(j, m->transaction_jobs, i) {
1273                 if (j->installed)
1274                         continue;
1275
1276                 hashmap_remove(m->jobs, UINT32_TO_PTR(j->id));
1277         }
1278
1279         return r;
1280 }
1281
1282 static int transaction_activate(Manager *m, JobMode mode, DBusError *e) {
1283         int r;
1284         unsigned generation = 1;
1285
1286         assert(m);
1287
1288         /* This applies the changes recorded in transaction_jobs to
1289          * the actual list of jobs, if possible. */
1290
1291         /* First step: figure out which jobs matter */
1292         transaction_find_jobs_that_matter_to_anchor(m, NULL, generation++);
1293
1294         /* Second step: Try not to stop any running services if
1295          * we don't have to. Don't try to reverse running
1296          * jobs if we don't have to. */
1297         if (mode == JOB_FAIL)
1298                 transaction_minimize_impact(m);
1299
1300         /* Third step: Drop redundant jobs */
1301         transaction_drop_redundant(m);
1302
1303         for (;;) {
1304                 /* Fourth step: Let's remove unneeded jobs that might
1305                  * be lurking. */
1306                 if (mode != JOB_ISOLATE)
1307                         transaction_collect_garbage(m);
1308
1309                 /* Fifth step: verify order makes sense and correct
1310                  * cycles if necessary and possible */
1311                 if ((r = transaction_verify_order(m, &generation, e)) >= 0)
1312                         break;
1313
1314                 if (r != -EAGAIN) {
1315                         log_warning("Requested transaction contains an unfixable cyclic ordering dependency: %s", bus_error(e, r));
1316                         goto rollback;
1317                 }
1318
1319                 /* Let's see if the resulting transaction ordering
1320                  * graph is still cyclic... */
1321         }
1322
1323         for (;;) {
1324                 /* Sixth step: let's drop unmergeable entries if
1325                  * necessary and possible, merge entries we can
1326                  * merge */
1327                 if ((r = transaction_merge_jobs(m, e)) >= 0)
1328                         break;
1329
1330                 if (r != -EAGAIN) {
1331                         log_warning("Requested transaction contains unmergeable jobs: %s", bus_error(e, r));
1332                         goto rollback;
1333                 }
1334
1335                 /* Seventh step: an entry got dropped, let's garbage
1336                  * collect its dependencies. */
1337                 if (mode != JOB_ISOLATE)
1338                         transaction_collect_garbage(m);
1339
1340                 /* Let's see if the resulting transaction still has
1341                  * unmergeable entries ... */
1342         }
1343
1344         /* Eights step: Drop redundant jobs again, if the merging now allows us to drop more. */
1345         transaction_drop_redundant(m);
1346
1347         /* Ninth step: check whether we can actually apply this */
1348         if (mode == JOB_FAIL)
1349                 if ((r = transaction_is_destructive(m, e)) < 0) {
1350                         log_notice("Requested transaction contradicts existing jobs: %s", bus_error(e, r));
1351                         goto rollback;
1352                 }
1353
1354         /* Tenth step: apply changes */
1355         if ((r = transaction_apply(m, mode)) < 0) {
1356                 log_warning("Failed to apply transaction: %s", strerror(-r));
1357                 goto rollback;
1358         }
1359
1360         assert(hashmap_isempty(m->transaction_jobs));
1361         assert(!m->transaction_anchor);
1362
1363         return 0;
1364
1365 rollback:
1366         transaction_abort(m);
1367         return r;
1368 }
1369
1370 static Job* transaction_add_one_job(Manager *m, JobType type, Unit *unit, bool override, bool *is_new) {
1371         Job *j, *f;
1372
1373         assert(m);
1374         assert(unit);
1375
1376         /* Looks for an existing prospective job and returns that. If
1377          * it doesn't exist it is created and added to the prospective
1378          * jobs list. */
1379
1380         f = hashmap_get(m->transaction_jobs, unit);
1381
1382         LIST_FOREACH(transaction, j, f) {
1383                 assert(j->unit == unit);
1384
1385                 if (j->type == type) {
1386                         if (is_new)
1387                                 *is_new = false;
1388                         return j;
1389                 }
1390         }
1391
1392         if (unit->meta.job && unit->meta.job->type == type)
1393                 j = unit->meta.job;
1394         else if (!(j = job_new(m, type, unit)))
1395                 return NULL;
1396
1397         j->generation = 0;
1398         j->marker = NULL;
1399         j->matters_to_anchor = false;
1400         j->override = override;
1401
1402         LIST_PREPEND(Job, transaction, f, j);
1403
1404         if (hashmap_replace(m->transaction_jobs, unit, f) < 0) {
1405                 job_free(j);
1406                 return NULL;
1407         }
1408
1409         if (is_new)
1410                 *is_new = true;
1411
1412         /* log_debug("Added job %s/%s to transaction.", unit->meta.id, job_type_to_string(type)); */
1413
1414         return j;
1415 }
1416
1417 void manager_transaction_unlink_job(Manager *m, Job *j, bool delete_dependencies) {
1418         assert(m);
1419         assert(j);
1420
1421         if (j->transaction_prev)
1422                 j->transaction_prev->transaction_next = j->transaction_next;
1423         else if (j->transaction_next)
1424                 hashmap_replace(m->transaction_jobs, j->unit, j->transaction_next);
1425         else
1426                 hashmap_remove_value(m->transaction_jobs, j->unit, j);
1427
1428         if (j->transaction_next)
1429                 j->transaction_next->transaction_prev = j->transaction_prev;
1430
1431         j->transaction_prev = j->transaction_next = NULL;
1432
1433         while (j->subject_list)
1434                 job_dependency_free(j->subject_list);
1435
1436         while (j->object_list) {
1437                 Job *other = j->object_list->matters ? j->object_list->subject : NULL;
1438
1439                 job_dependency_free(j->object_list);
1440
1441                 if (other && delete_dependencies) {
1442                         log_debug("Deleting job %s/%s as dependency of job %s/%s",
1443                                   other->unit->meta.id, job_type_to_string(other->type),
1444                                   j->unit->meta.id, job_type_to_string(j->type));
1445                         transaction_delete_job(m, other, delete_dependencies);
1446                 }
1447         }
1448 }
1449
1450 static int transaction_add_job_and_dependencies(
1451                 Manager *m,
1452                 JobType type,
1453                 Unit *unit,
1454                 Job *by,
1455                 bool matters,
1456                 bool override,
1457                 bool conflicts,
1458                 bool ignore_requirements,
1459                 bool ignore_order,
1460                 DBusError *e,
1461                 Job **_ret) {
1462         Job *ret;
1463         Iterator i;
1464         Unit *dep;
1465         int r;
1466         bool is_new;
1467
1468         assert(m);
1469         assert(type < _JOB_TYPE_MAX);
1470         assert(unit);
1471
1472         /* log_debug("Pulling in %s/%s from %s/%s", */
1473         /*           unit->meta.id, job_type_to_string(type), */
1474         /*           by ? by->unit->meta.id : "NA", */
1475         /*           by ? job_type_to_string(by->type) : "NA"); */
1476
1477         if (unit->meta.load_state != UNIT_LOADED &&
1478             unit->meta.load_state != UNIT_ERROR &&
1479             unit->meta.load_state != UNIT_MASKED) {
1480                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED, "Unit %s is not loaded properly.", unit->meta.id);
1481                 return -EINVAL;
1482         }
1483
1484         if (type != JOB_STOP && unit->meta.load_state == UNIT_ERROR) {
1485                 dbus_set_error(e, BUS_ERROR_LOAD_FAILED,
1486                                "Unit %s failed to load: %s. "
1487                                "See system logs and 'systemctl status %s' for details.",
1488                                unit->meta.id,
1489                                strerror(-unit->meta.load_error),
1490                                unit->meta.id);
1491                 return -EINVAL;
1492         }
1493
1494         if (type != JOB_STOP && unit->meta.load_state == UNIT_MASKED) {
1495                 dbus_set_error(e, BUS_ERROR_MASKED, "Unit %s is masked.", unit->meta.id);
1496                 return -EINVAL;
1497         }
1498
1499         if (!unit_job_is_applicable(unit, type)) {
1500                 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);
1501                 return -EBADR;
1502         }
1503
1504         /* First add the job. */
1505         if (!(ret = transaction_add_one_job(m, type, unit, override, &is_new)))
1506                 return -ENOMEM;
1507
1508         ret->ignore_order = ret->ignore_order || ignore_order;
1509
1510         /* Then, add a link to the job. */
1511         if (!job_dependency_new(by, ret, matters, conflicts))
1512                 return -ENOMEM;
1513
1514         if (is_new && !ignore_requirements) {
1515                 Set *following;
1516
1517                 /* If we are following some other unit, make sure we
1518                  * add all dependencies of everybody following. */
1519                 if (unit_following_set(ret->unit, &following) > 0) {
1520                         SET_FOREACH(dep, following, i)
1521                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, false, override, false, false, ignore_order, e, NULL)) < 0) {
1522                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1523
1524                                         if (e)
1525                                                 dbus_error_free(e);
1526                                 }
1527
1528                         set_free(following);
1529                 }
1530
1531                 /* Finally, recursively add in all dependencies. */
1532                 if (type == JOB_START || type == JOB_RELOAD_OR_START) {
1533                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES], i)
1534                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1535                                         if (r != -EBADR)
1536                                                 goto fail;
1537
1538                                         if (e)
1539                                                 dbus_error_free(e);
1540                                 }
1541
1542                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BIND_TO], i)
1543                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1544
1545                                         if (r != -EBADR)
1546                                                 goto fail;
1547
1548                                         if (e)
1549                                                 dbus_error_free(e);
1550                                 }
1551
1552                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1553                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, !override, override, false, false, ignore_order, e, NULL)) < 0) {
1554                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1555
1556                                         if (e)
1557                                                 dbus_error_free(e);
1558                                 }
1559
1560                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_WANTS], i)
1561                                 if ((r = transaction_add_job_and_dependencies(m, JOB_START, dep, ret, false, false, false, false, ignore_order, e, NULL)) < 0) {
1562                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1563
1564                                         if (e)
1565                                                 dbus_error_free(e);
1566                                 }
1567
1568                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE], i)
1569                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1570
1571                                         if (r != -EBADR)
1572                                                 goto fail;
1573
1574                                         if (e)
1575                                                 dbus_error_free(e);
1576                                 }
1577
1578                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1579                                 if ((r = transaction_add_job_and_dependencies(m, JOB_VERIFY_ACTIVE, dep, ret, !override, override, false, false, ignore_order, e, NULL)) < 0) {
1580                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1581
1582                                         if (e)
1583                                                 dbus_error_free(e);
1584                                 }
1585
1586                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTS], i)
1587                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, true, override, true, false, ignore_order, e, NULL)) < 0) {
1588
1589                                         if (r != -EBADR)
1590                                                 goto fail;
1591
1592                                         if (e)
1593                                                 dbus_error_free(e);
1594                                 }
1595
1596                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_CONFLICTED_BY], i)
1597                                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, dep, ret, false, override, false, false, ignore_order, e, NULL)) < 0) {
1598                                         log_warning("Cannot add dependency job for unit %s, ignoring: %s", dep->meta.id, bus_error(e, r));
1599
1600                                         if (e)
1601                                                 dbus_error_free(e);
1602                                 }
1603
1604                 } else if (type == JOB_STOP || type == JOB_RESTART || type == JOB_TRY_RESTART) {
1605
1606                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_REQUIRED_BY], i)
1607                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1608
1609                                         if (r != -EBADR)
1610                                                 goto fail;
1611
1612                                         if (e)
1613                                                 dbus_error_free(e);
1614                                 }
1615
1616                         SET_FOREACH(dep, ret->unit->meta.dependencies[UNIT_BOUND_BY], i)
1617                                 if ((r = transaction_add_job_and_dependencies(m, type, dep, ret, true, override, false, false, ignore_order, e, NULL)) < 0) {
1618
1619                                         if (r != -EBADR)
1620                                                 goto fail;
1621
1622                                         if (e)
1623                                                 dbus_error_free(e);
1624                                 }
1625                 }
1626
1627                 /* JOB_VERIFY_STARTED, JOB_RELOAD require no dependency handling */
1628         }
1629
1630         if (_ret)
1631                 *_ret = ret;
1632
1633         return 0;
1634
1635 fail:
1636         return r;
1637 }
1638
1639 static int transaction_add_isolate_jobs(Manager *m) {
1640         Iterator i;
1641         Unit *u;
1642         char *k;
1643         int r;
1644
1645         assert(m);
1646
1647         HASHMAP_FOREACH_KEY(u, k, m->units, i) {
1648
1649                 /* ignore aliases */
1650                 if (u->meta.id != k)
1651                         continue;
1652
1653                 if (u->meta.ignore_on_isolate)
1654                         continue;
1655
1656                 /* No need to stop inactive jobs */
1657                 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) && !u->meta.job)
1658                         continue;
1659
1660                 /* Is there already something listed for this? */
1661                 if (hashmap_get(m->transaction_jobs, u))
1662                         continue;
1663
1664                 if ((r = transaction_add_job_and_dependencies(m, JOB_STOP, u, NULL, true, false, false, false, false, NULL, NULL)) < 0)
1665                         log_warning("Cannot add isolate job for unit %s, ignoring: %s", u->meta.id, strerror(-r));
1666         }
1667
1668         return 0;
1669 }
1670
1671 int manager_add_job(Manager *m, JobType type, Unit *unit, JobMode mode, bool override, DBusError *e, Job **_ret) {
1672         int r;
1673         Job *ret;
1674
1675         assert(m);
1676         assert(type < _JOB_TYPE_MAX);
1677         assert(unit);
1678         assert(mode < _JOB_MODE_MAX);
1679
1680         if (mode == JOB_ISOLATE && type != JOB_START) {
1681                 dbus_set_error(e, BUS_ERROR_INVALID_JOB_MODE, "Isolate is only valid for start.");
1682                 return -EINVAL;
1683         }
1684
1685         if (mode == JOB_ISOLATE && !unit->meta.allow_isolate) {
1686                 dbus_set_error(e, BUS_ERROR_NO_ISOLATION, "Operation refused, unit may not be isolated.");
1687                 return -EPERM;
1688         }
1689
1690         log_debug("Trying to enqueue job %s/%s/%s", unit->meta.id, job_type_to_string(type), job_mode_to_string(mode));
1691
1692         if ((r = transaction_add_job_and_dependencies(m, type, unit, NULL, true, override, false,
1693                                                       mode == JOB_IGNORE_DEPENDENCIES || mode == JOB_IGNORE_REQUIREMENTS,
1694                                                       mode == JOB_IGNORE_DEPENDENCIES, e, &ret)) < 0) {
1695                 transaction_abort(m);
1696                 return r;
1697         }
1698
1699         if (mode == JOB_ISOLATE)
1700                 if ((r = transaction_add_isolate_jobs(m)) < 0) {
1701                         transaction_abort(m);
1702                         return r;
1703                 }
1704
1705         if ((r = transaction_activate(m, mode, e)) < 0)
1706                 return r;
1707
1708         log_debug("Enqueued job %s/%s as %u", unit->meta.id, job_type_to_string(type), (unsigned) ret->id);
1709
1710         if (_ret)
1711                 *_ret = ret;
1712
1713         return 0;
1714 }
1715
1716 int manager_add_job_by_name(Manager *m, JobType type, const char *name, JobMode mode, bool override, DBusError *e, Job **_ret) {
1717         Unit *unit;
1718         int r;
1719
1720         assert(m);
1721         assert(type < _JOB_TYPE_MAX);
1722         assert(name);
1723         assert(mode < _JOB_MODE_MAX);
1724
1725         if ((r = manager_load_unit(m, name, NULL, NULL, &unit)) < 0)
1726                 return r;
1727
1728         return manager_add_job(m, type, unit, mode, override, e, _ret);
1729 }
1730
1731 Job *manager_get_job(Manager *m, uint32_t id) {
1732         assert(m);
1733
1734         return hashmap_get(m->jobs, UINT32_TO_PTR(id));
1735 }
1736
1737 Unit *manager_get_unit(Manager *m, const char *name) {
1738         assert(m);
1739         assert(name);
1740
1741         return hashmap_get(m->units, name);
1742 }
1743
1744 unsigned manager_dispatch_load_queue(Manager *m) {
1745         Meta *meta;
1746         unsigned n = 0;
1747
1748         assert(m);
1749
1750         /* Make sure we are not run recursively */
1751         if (m->dispatching_load_queue)
1752                 return 0;
1753
1754         m->dispatching_load_queue = true;
1755
1756         /* Dispatches the load queue. Takes a unit from the queue and
1757          * tries to load its data until the queue is empty */
1758
1759         while ((meta = m->load_queue)) {
1760                 assert(meta->in_load_queue);
1761
1762                 unit_load((Unit*) meta);
1763                 n++;
1764         }
1765
1766         m->dispatching_load_queue = false;
1767         return n;
1768 }
1769
1770 int manager_load_unit_prepare(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1771         Unit *ret;
1772         int r;
1773
1774         assert(m);
1775         assert(name || path);
1776
1777         /* This will prepare the unit for loading, but not actually
1778          * load anything from disk. */
1779
1780         if (path && !is_path(path)) {
1781                 dbus_set_error(e, BUS_ERROR_INVALID_PATH, "Path %s is not absolute.", path);
1782                 return -EINVAL;
1783         }
1784
1785         if (!name)
1786                 name = file_name_from_path(path);
1787
1788         if (!unit_name_is_valid(name, false)) {
1789                 dbus_set_error(e, BUS_ERROR_INVALID_NAME, "Unit name %s is not valid.", name);
1790                 return -EINVAL;
1791         }
1792
1793         if ((ret = manager_get_unit(m, name))) {
1794                 *_ret = ret;
1795                 return 1;
1796         }
1797
1798         if (!(ret = unit_new(m)))
1799                 return -ENOMEM;
1800
1801         if (path)
1802                 if (!(ret->meta.fragment_path = strdup(path))) {
1803                         unit_free(ret);
1804                         return -ENOMEM;
1805                 }
1806
1807         if ((r = unit_add_name(ret, name)) < 0) {
1808                 unit_free(ret);
1809                 return r;
1810         }
1811
1812         unit_add_to_load_queue(ret);
1813         unit_add_to_dbus_queue(ret);
1814         unit_add_to_gc_queue(ret);
1815
1816         if (_ret)
1817                 *_ret = ret;
1818
1819         return 0;
1820 }
1821
1822 int manager_load_unit(Manager *m, const char *name, const char *path, DBusError *e, Unit **_ret) {
1823         int r;
1824
1825         assert(m);
1826
1827         /* This will load the service information files, but not actually
1828          * start any services or anything. */
1829
1830         if ((r = manager_load_unit_prepare(m, name, path, e, _ret)) != 0)
1831                 return r;
1832
1833         manager_dispatch_load_queue(m);
1834
1835         if (_ret)
1836                 *_ret = unit_follow_merge(*_ret);
1837
1838         return 0;
1839 }
1840
1841 void manager_dump_jobs(Manager *s, FILE *f, const char *prefix) {
1842         Iterator i;
1843         Job *j;
1844
1845         assert(s);
1846         assert(f);
1847
1848         HASHMAP_FOREACH(j, s->jobs, i)
1849                 job_dump(j, f, prefix);
1850 }
1851
1852 void manager_dump_units(Manager *s, FILE *f, const char *prefix) {
1853         Iterator i;
1854         Unit *u;
1855         const char *t;
1856
1857         assert(s);
1858         assert(f);
1859
1860         HASHMAP_FOREACH_KEY(u, t, s->units, i)
1861                 if (u->meta.id == t)
1862                         unit_dump(u, f, prefix);
1863 }
1864
1865 void manager_clear_jobs(Manager *m) {
1866         Job *j;
1867
1868         assert(m);
1869
1870         transaction_abort(m);
1871
1872         while ((j = hashmap_first(m->jobs)))
1873                 job_finish_and_invalidate(j, JOB_CANCELED);
1874 }
1875
1876 unsigned manager_dispatch_run_queue(Manager *m) {
1877         Job *j;
1878         unsigned n = 0;
1879
1880         if (m->dispatching_run_queue)
1881                 return 0;
1882
1883         m->dispatching_run_queue = true;
1884
1885         while ((j = m->run_queue)) {
1886                 assert(j->installed);
1887                 assert(j->in_run_queue);
1888
1889                 job_run_and_invalidate(j);
1890                 n++;
1891         }
1892
1893         m->dispatching_run_queue = false;
1894         return n;
1895 }
1896
1897 unsigned manager_dispatch_dbus_queue(Manager *m) {
1898         Job *j;
1899         Meta *meta;
1900         unsigned n = 0;
1901
1902         assert(m);
1903
1904         if (m->dispatching_dbus_queue)
1905                 return 0;
1906
1907         m->dispatching_dbus_queue = true;
1908
1909         while ((meta = m->dbus_unit_queue)) {
1910                 assert(meta->in_dbus_queue);
1911
1912                 bus_unit_send_change_signal((Unit*) meta);
1913                 n++;
1914         }
1915
1916         while ((j = m->dbus_job_queue)) {
1917                 assert(j->in_dbus_queue);
1918
1919                 bus_job_send_change_signal(j);
1920                 n++;
1921         }
1922
1923         m->dispatching_dbus_queue = false;
1924         return n;
1925 }
1926
1927 static int manager_process_notify_fd(Manager *m) {
1928         ssize_t n;
1929
1930         assert(m);
1931
1932         for (;;) {
1933                 char buf[4096];
1934                 struct msghdr msghdr;
1935                 struct iovec iovec;
1936                 struct ucred *ucred;
1937                 union {
1938                         struct cmsghdr cmsghdr;
1939                         uint8_t buf[CMSG_SPACE(sizeof(struct ucred))];
1940                 } control;
1941                 Unit *u;
1942                 char **tags;
1943
1944                 zero(iovec);
1945                 iovec.iov_base = buf;
1946                 iovec.iov_len = sizeof(buf)-1;
1947
1948                 zero(control);
1949                 zero(msghdr);
1950                 msghdr.msg_iov = &iovec;
1951                 msghdr.msg_iovlen = 1;
1952                 msghdr.msg_control = &control;
1953                 msghdr.msg_controllen = sizeof(control);
1954
1955                 if ((n = recvmsg(m->notify_watch.fd, &msghdr, MSG_DONTWAIT)) <= 0) {
1956                         if (n >= 0)
1957                                 return -EIO;
1958
1959                         if (errno == EAGAIN || errno == EINTR)
1960                                 break;
1961
1962                         return -errno;
1963                 }
1964
1965                 if (msghdr.msg_controllen < CMSG_LEN(sizeof(struct ucred)) ||
1966                     control.cmsghdr.cmsg_level != SOL_SOCKET ||
1967                     control.cmsghdr.cmsg_type != SCM_CREDENTIALS ||
1968                     control.cmsghdr.cmsg_len != CMSG_LEN(sizeof(struct ucred))) {
1969                         log_warning("Received notify message without credentials. Ignoring.");
1970                         continue;
1971                 }
1972
1973                 ucred = (struct ucred*) CMSG_DATA(&control.cmsghdr);
1974
1975                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(ucred->pid))))
1976                         if (!(u = cgroup_unit_by_pid(m, ucred->pid))) {
1977                                 log_warning("Cannot find unit for notify message of PID %lu.", (unsigned long) ucred->pid);
1978                                 continue;
1979                         }
1980
1981                 assert((size_t) n < sizeof(buf));
1982                 buf[n] = 0;
1983                 if (!(tags = strv_split(buf, "\n\r")))
1984                         return -ENOMEM;
1985
1986                 log_debug("Got notification message for unit %s", u->meta.id);
1987
1988                 if (UNIT_VTABLE(u)->notify_message)
1989                         UNIT_VTABLE(u)->notify_message(u, ucred->pid, tags);
1990
1991                 strv_free(tags);
1992         }
1993
1994         return 0;
1995 }
1996
1997 static int manager_dispatch_sigchld(Manager *m) {
1998         assert(m);
1999
2000         for (;;) {
2001                 siginfo_t si;
2002                 Unit *u;
2003                 int r;
2004
2005                 zero(si);
2006
2007                 /* First we call waitd() for a PID and do not reap the
2008                  * zombie. That way we can still access /proc/$PID for
2009                  * it while it is a zombie. */
2010                 if (waitid(P_ALL, 0, &si, WEXITED|WNOHANG|WNOWAIT) < 0) {
2011
2012                         if (errno == ECHILD)
2013                                 break;
2014
2015                         if (errno == EINTR)
2016                                 continue;
2017
2018                         return -errno;
2019                 }
2020
2021                 if (si.si_pid <= 0)
2022                         break;
2023
2024                 if (si.si_code == CLD_EXITED || si.si_code == CLD_KILLED || si.si_code == CLD_DUMPED) {
2025                         char *name = NULL;
2026
2027                         get_process_comm(si.si_pid, &name);
2028                         log_debug("Got SIGCHLD for process %lu (%s)", (unsigned long) si.si_pid, strna(name));
2029                         free(name);
2030                 }
2031
2032                 /* Let's flush any message the dying child might still
2033                  * have queued for us. This ensures that the process
2034                  * still exists in /proc so that we can figure out
2035                  * which cgroup and hence unit it belongs to. */
2036                 if ((r = manager_process_notify_fd(m)) < 0)
2037                         return r;
2038
2039                 /* And now figure out the unit this belongs to */
2040                 if (!(u = hashmap_get(m->watch_pids, LONG_TO_PTR(si.si_pid))))
2041                         u = cgroup_unit_by_pid(m, si.si_pid);
2042
2043                 /* And now, we actually reap the zombie. */
2044                 if (waitid(P_PID, si.si_pid, &si, WEXITED) < 0) {
2045                         if (errno == EINTR)
2046                                 continue;
2047
2048                         return -errno;
2049                 }
2050
2051                 if (si.si_code != CLD_EXITED && si.si_code != CLD_KILLED && si.si_code != CLD_DUMPED)
2052                         continue;
2053
2054                 log_debug("Child %lu died (code=%s, status=%i/%s)",
2055                           (long unsigned) si.si_pid,
2056                           sigchld_code_to_string(si.si_code),
2057                           si.si_status,
2058                           strna(si.si_code == CLD_EXITED
2059                                 ? exit_status_to_string(si.si_status, EXIT_STATUS_FULL)
2060                                 : signal_to_string(si.si_status)));
2061
2062                 if (!u)
2063                         continue;
2064
2065                 log_debug("Child %lu belongs to %s", (long unsigned) si.si_pid, u->meta.id);
2066
2067                 hashmap_remove(m->watch_pids, LONG_TO_PTR(si.si_pid));
2068                 UNIT_VTABLE(u)->sigchld_event(u, si.si_pid, si.si_code, si.si_status);
2069         }
2070
2071         return 0;
2072 }
2073
2074 static int manager_start_target(Manager *m, const char *name, JobMode mode) {
2075         int r;
2076         DBusError error;
2077
2078         dbus_error_init(&error);
2079
2080         log_debug("Activating special unit %s", name);
2081
2082         if ((r = manager_add_job_by_name(m, JOB_START, name, mode, true, &error, NULL)) < 0)
2083                 log_error("Failed to enqueue %s job: %s", name, bus_error(&error, r));
2084
2085         dbus_error_free(&error);
2086
2087         return r;
2088 }
2089
2090 static int manager_process_signal_fd(Manager *m) {
2091         ssize_t n;
2092         struct signalfd_siginfo sfsi;
2093         bool sigchld = false;
2094
2095         assert(m);
2096
2097         for (;;) {
2098                 if ((n = read(m->signal_watch.fd, &sfsi, sizeof(sfsi))) != sizeof(sfsi)) {
2099
2100                         if (n >= 0)
2101                                 return -EIO;
2102
2103                         if (errno == EINTR || errno == EAGAIN)
2104                                 break;
2105
2106                         return -errno;
2107                 }
2108
2109                 if (sfsi.ssi_pid > 0) {
2110                         char *p = NULL;
2111
2112                         get_process_comm(sfsi.ssi_pid, &p);
2113
2114                         log_debug("Received SIG%s from PID %lu (%s).",
2115                                   signal_to_string(sfsi.ssi_signo),
2116                                   (unsigned long) sfsi.ssi_pid, strna(p));
2117                         free(p);
2118                 } else
2119                         log_debug("Received SIG%s.", signal_to_string(sfsi.ssi_signo));
2120
2121                 switch (sfsi.ssi_signo) {
2122
2123                 case SIGCHLD:
2124                         sigchld = true;
2125                         break;
2126
2127                 case SIGTERM:
2128                         if (m->running_as == MANAGER_SYSTEM) {
2129                                 /* This is for compatibility with the
2130                                  * original sysvinit */
2131                                 m->exit_code = MANAGER_REEXECUTE;
2132                                 break;
2133                         }
2134
2135                         /* Fall through */
2136
2137                 case SIGINT:
2138                         if (m->running_as == MANAGER_SYSTEM) {
2139                                 manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
2140                                 break;
2141                         }
2142
2143                         /* Run the exit target if there is one, if not, just exit. */
2144                         if (manager_start_target(m, SPECIAL_EXIT_TARGET, JOB_REPLACE) < 0) {
2145                                 m->exit_code = MANAGER_EXIT;
2146                                 return 0;
2147                         }
2148
2149                         break;
2150
2151                 case SIGWINCH:
2152                         if (m->running_as == MANAGER_SYSTEM)
2153                                 manager_start_target(m, SPECIAL_KBREQUEST_TARGET, JOB_REPLACE);
2154
2155                         /* This is a nop on non-init */
2156                         break;
2157
2158                 case SIGPWR:
2159                         if (m->running_as == MANAGER_SYSTEM)
2160                                 manager_start_target(m, SPECIAL_SIGPWR_TARGET, JOB_REPLACE);
2161
2162                         /* This is a nop on non-init */
2163                         break;
2164
2165                 case SIGUSR1: {
2166                         Unit *u;
2167
2168                         u = manager_get_unit(m, SPECIAL_DBUS_SERVICE);
2169
2170                         if (!u || UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u))) {
2171                                 log_info("Trying to reconnect to bus...");
2172                                 bus_init(m, true);
2173                         }
2174
2175                         if (!u || !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u))) {
2176                                 log_info("Loading D-Bus service...");
2177                                 manager_start_target(m, SPECIAL_DBUS_SERVICE, JOB_REPLACE);
2178                         }
2179
2180                         break;
2181                 }
2182
2183                 case SIGUSR2: {
2184                         FILE *f;
2185                         char *dump = NULL;
2186                         size_t size;
2187
2188                         if (!(f = open_memstream(&dump, &size))) {
2189                                 log_warning("Failed to allocate memory stream.");
2190                                 break;
2191                         }
2192
2193                         manager_dump_units(m, f, "\t");
2194                         manager_dump_jobs(m, f, "\t");
2195
2196                         if (ferror(f)) {
2197                                 fclose(f);
2198                                 free(dump);
2199                                 log_warning("Failed to write status stream");
2200                                 break;
2201                         }
2202
2203                         fclose(f);
2204                         log_dump(LOG_INFO, dump);
2205                         free(dump);
2206
2207                         break;
2208                 }
2209
2210                 case SIGHUP:
2211                         m->exit_code = MANAGER_RELOAD;
2212                         break;
2213
2214                 default: {
2215
2216                         /* Starting SIGRTMIN+0 */
2217                         static const char * const target_table[] = {
2218                                 [0] = SPECIAL_DEFAULT_TARGET,
2219                                 [1] = SPECIAL_RESCUE_TARGET,
2220                                 [2] = SPECIAL_EMERGENCY_TARGET,
2221                                 [3] = SPECIAL_HALT_TARGET,
2222                                 [4] = SPECIAL_POWEROFF_TARGET,
2223                                 [5] = SPECIAL_REBOOT_TARGET,
2224                                 [6] = SPECIAL_KEXEC_TARGET
2225                         };
2226
2227                         /* Starting SIGRTMIN+13, so that target halt and system halt are 10 apart */
2228                         static const ManagerExitCode code_table[] = {
2229                                 [0] = MANAGER_HALT,
2230                                 [1] = MANAGER_POWEROFF,
2231                                 [2] = MANAGER_REBOOT,
2232                                 [3] = MANAGER_KEXEC
2233                         };
2234
2235                         if ((int) sfsi.ssi_signo >= SIGRTMIN+0 &&
2236                             (int) sfsi.ssi_signo < SIGRTMIN+(int) ELEMENTSOF(target_table)) {
2237                                 int idx = (int) sfsi.ssi_signo - SIGRTMIN;
2238                                 manager_start_target(m, target_table[idx],
2239                                                      (idx == 1 || idx == 2) ? JOB_ISOLATE : JOB_REPLACE);
2240                                 break;
2241                         }
2242
2243                         if ((int) sfsi.ssi_signo >= SIGRTMIN+13 &&
2244                             (int) sfsi.ssi_signo < SIGRTMIN+13+(int) ELEMENTSOF(code_table)) {
2245                                 m->exit_code = code_table[sfsi.ssi_signo - SIGRTMIN - 13];
2246                                 break;
2247                         }
2248
2249                         switch (sfsi.ssi_signo - SIGRTMIN) {
2250
2251                         case 20:
2252                                 log_debug("Enabling showing of status.");
2253                                 manager_set_show_status(m, true);
2254                                 break;
2255
2256                         case 21:
2257                                 log_debug("Disabling showing of status.");
2258                                 manager_set_show_status(m, false);
2259                                 break;
2260
2261                         case 22:
2262                                 log_set_max_level(LOG_DEBUG);
2263                                 log_notice("Setting log level to debug.");
2264                                 break;
2265
2266                         case 23:
2267                                 log_set_max_level(LOG_INFO);
2268                                 log_notice("Setting log level to info.");
2269                                 break;
2270
2271                         case 27:
2272                                 log_set_target(LOG_TARGET_CONSOLE);
2273                                 log_notice("Setting log target to console.");
2274                                 break;
2275
2276                         case 28:
2277                                 log_set_target(LOG_TARGET_KMSG);
2278                                 log_notice("Setting log target to kmsg.");
2279                                 break;
2280
2281                         case 29:
2282                                 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
2283                                 log_notice("Setting log target to syslog-or-kmsg.");
2284                                 break;
2285
2286                         default:
2287                                 log_warning("Got unhandled signal <%s>.", signal_to_string(sfsi.ssi_signo));
2288                         }
2289                 }
2290                 }
2291         }
2292
2293         if (sigchld)
2294                 return manager_dispatch_sigchld(m);
2295
2296         return 0;
2297 }
2298
2299 static int process_event(Manager *m, struct epoll_event *ev) {
2300         int r;
2301         Watch *w;
2302
2303         assert(m);
2304         assert(ev);
2305
2306         assert_se(w = ev->data.ptr);
2307
2308         if (w->type == WATCH_INVALID)
2309                 return 0;
2310
2311         switch (w->type) {
2312
2313         case WATCH_SIGNAL:
2314
2315                 /* An incoming signal? */
2316                 if (ev->events != EPOLLIN)
2317                         return -EINVAL;
2318
2319                 if ((r = manager_process_signal_fd(m)) < 0)
2320                         return r;
2321
2322                 break;
2323
2324         case WATCH_NOTIFY:
2325
2326                 /* An incoming daemon notification event? */
2327                 if (ev->events != EPOLLIN)
2328                         return -EINVAL;
2329
2330                 if ((r = manager_process_notify_fd(m)) < 0)
2331                         return r;
2332
2333                 break;
2334
2335         case WATCH_FD:
2336
2337                 /* Some fd event, to be dispatched to the units */
2338                 UNIT_VTABLE(w->data.unit)->fd_event(w->data.unit, w->fd, ev->events, w);
2339                 break;
2340
2341         case WATCH_UNIT_TIMER:
2342         case WATCH_JOB_TIMER: {
2343                 uint64_t v;
2344                 ssize_t k;
2345
2346                 /* Some timer event, to be dispatched to the units */
2347                 if ((k = read(w->fd, &v, sizeof(v))) != sizeof(v)) {
2348
2349                         if (k < 0 && (errno == EINTR || errno == EAGAIN))
2350                                 break;
2351
2352                         return k < 0 ? -errno : -EIO;
2353                 }
2354
2355                 if (w->type == WATCH_UNIT_TIMER)
2356                         UNIT_VTABLE(w->data.unit)->timer_event(w->data.unit, v, w);
2357                 else
2358                         job_timer_event(w->data.job, v, w);
2359                 break;
2360         }
2361
2362         case WATCH_MOUNT:
2363                 /* Some mount table change, intended for the mount subsystem */
2364                 mount_fd_event(m, ev->events);
2365                 break;
2366
2367         case WATCH_SWAP:
2368                 /* Some swap table change, intended for the swap subsystem */
2369                 swap_fd_event(m, ev->events);
2370                 break;
2371
2372         case WATCH_UDEV:
2373                 /* Some notification from udev, intended for the device subsystem */
2374                 device_fd_event(m, ev->events);
2375                 break;
2376
2377         case WATCH_DBUS_WATCH:
2378                 bus_watch_event(m, w, ev->events);
2379                 break;
2380
2381         case WATCH_DBUS_TIMEOUT:
2382                 bus_timeout_event(m, w, ev->events);
2383                 break;
2384
2385         default:
2386                 log_error("event type=%i", w->type);
2387                 assert_not_reached("Unknown epoll event type.");
2388         }
2389
2390         return 0;
2391 }
2392
2393 int manager_loop(Manager *m) {
2394         int r;
2395
2396         RATELIMIT_DEFINE(rl, 1*USEC_PER_SEC, 50000);
2397
2398         assert(m);
2399         m->exit_code = MANAGER_RUNNING;
2400
2401         /* Release the path cache */
2402         set_free_free(m->unit_path_cache);
2403         m->unit_path_cache = NULL;
2404
2405         manager_check_finished(m);
2406
2407         /* There might still be some zombies hanging around from
2408          * before we were exec()'ed. Leat's reap them */
2409         if ((r = manager_dispatch_sigchld(m)) < 0)
2410                 return r;
2411
2412         while (m->exit_code == MANAGER_RUNNING) {
2413                 struct epoll_event event;
2414                 int n;
2415
2416                 if (!ratelimit_test(&rl)) {
2417                         /* Yay, something is going seriously wrong, pause a little */
2418                         log_warning("Looping too fast. Throttling execution a little.");
2419                         sleep(1);
2420                 }
2421
2422                 if (manager_dispatch_load_queue(m) > 0)
2423                         continue;
2424
2425                 if (manager_dispatch_run_queue(m) > 0)
2426                         continue;
2427
2428                 if (bus_dispatch(m) > 0)
2429                         continue;
2430
2431                 if (manager_dispatch_cleanup_queue(m) > 0)
2432                         continue;
2433
2434                 if (manager_dispatch_gc_queue(m) > 0)
2435                         continue;
2436
2437                 if (manager_dispatch_dbus_queue(m) > 0)
2438                         continue;
2439
2440                 if (swap_dispatch_reload(m) > 0)
2441                         continue;
2442
2443                 if ((n = epoll_wait(m->epoll_fd, &event, 1, -1)) < 0) {
2444
2445                         if (errno == EINTR)
2446                                 continue;
2447
2448                         return -errno;
2449                 }
2450
2451                 assert(n == 1);
2452
2453                 if ((r = process_event(m, &event)) < 0)
2454                         return r;
2455         }
2456
2457         return m->exit_code;
2458 }
2459
2460 int manager_get_unit_from_dbus_path(Manager *m, const char *s, Unit **_u) {
2461         char *n;
2462         Unit *u;
2463
2464         assert(m);
2465         assert(s);
2466         assert(_u);
2467
2468         if (!startswith(s, "/org/freedesktop/systemd1/unit/"))
2469                 return -EINVAL;
2470
2471         if (!(n = bus_path_unescape(s+31)))
2472                 return -ENOMEM;
2473
2474         u = manager_get_unit(m, n);
2475         free(n);
2476
2477         if (!u)
2478                 return -ENOENT;
2479
2480         *_u = u;
2481
2482         return 0;
2483 }
2484
2485 int manager_get_job_from_dbus_path(Manager *m, const char *s, Job **_j) {
2486         Job *j;
2487         unsigned id;
2488         int r;
2489
2490         assert(m);
2491         assert(s);
2492         assert(_j);
2493
2494         if (!startswith(s, "/org/freedesktop/systemd1/job/"))
2495                 return -EINVAL;
2496
2497         if ((r = safe_atou(s + 30, &id)) < 0)
2498                 return r;
2499
2500         if (!(j = manager_get_job(m, id)))
2501                 return -ENOENT;
2502
2503         *_j = j;
2504
2505         return 0;
2506 }
2507
2508 void manager_send_unit_audit(Manager *m, Unit *u, int type, bool success) {
2509
2510 #ifdef HAVE_AUDIT
2511         char *p;
2512
2513         if (m->audit_fd < 0)
2514                 return;
2515
2516         /* Don't generate audit events if the service was already
2517          * started and we're just deserializing */
2518         if (m->n_reloading > 0)
2519                 return;
2520
2521         if (m->running_as != MANAGER_SYSTEM)
2522                 return;
2523
2524         if (u->meta.type != UNIT_SERVICE)
2525                 return;
2526
2527         if (!(p = unit_name_to_prefix_and_instance(u->meta.id))) {
2528                 log_error("Failed to allocate unit name for audit message: %s", strerror(ENOMEM));
2529                 return;
2530         }
2531
2532         if (audit_log_user_comm_message(m->audit_fd, type, "", p, NULL, NULL, NULL, success) < 0) {
2533                 log_warning("Failed to send audit message: %m");
2534
2535                 if (errno == EPERM) {
2536                         /* We aren't allowed to send audit messages?
2537                          * Then let's not retry again, to avoid
2538                          * spamming the user with the same and same
2539                          * messages over and over. */
2540
2541                         audit_close(m->audit_fd);
2542                         m->audit_fd = -1;
2543                 }
2544         }
2545
2546         free(p);
2547 #endif
2548
2549 }
2550
2551 void manager_send_unit_plymouth(Manager *m, Unit *u) {
2552         int fd = -1;
2553         union sockaddr_union sa;
2554         int n = 0;
2555         char *message = NULL;
2556
2557         /* Don't generate plymouth events if the service was already
2558          * started and we're just deserializing */
2559         if (m->n_reloading > 0)
2560                 return;
2561
2562         if (m->running_as != MANAGER_SYSTEM)
2563                 return;
2564
2565         if (u->meta.type != UNIT_SERVICE &&
2566             u->meta.type != UNIT_MOUNT &&
2567             u->meta.type != UNIT_SWAP)
2568                 return;
2569
2570         /* We set SOCK_NONBLOCK here so that we rather drop the
2571          * message then wait for plymouth */
2572         if ((fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0)) < 0) {
2573                 log_error("socket() failed: %m");
2574                 return;
2575         }
2576
2577         zero(sa);
2578         sa.sa.sa_family = AF_UNIX;
2579         strncpy(sa.un.sun_path+1, "/org/freedesktop/plymouthd", sizeof(sa.un.sun_path)-1);
2580         if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + strlen(sa.un.sun_path+1)) < 0) {
2581
2582                 if (errno != EPIPE &&
2583                     errno != EAGAIN &&
2584                     errno != ENOENT &&
2585                     errno != ECONNREFUSED &&
2586                     errno != ECONNRESET &&
2587                     errno != ECONNABORTED)
2588                         log_error("connect() failed: %m");
2589
2590                 goto finish;
2591         }
2592
2593         if (asprintf(&message, "U\002%c%s%n", (int) (strlen(u->meta.id) + 1), u->meta.id, &n) < 0) {
2594                 log_error("Out of memory");
2595                 goto finish;
2596         }
2597
2598         errno = 0;
2599         if (write(fd, message, n + 1) != n + 1) {
2600
2601                 if (errno != EPIPE &&
2602                     errno != EAGAIN &&
2603                     errno != ENOENT &&
2604                     errno != ECONNREFUSED &&
2605                     errno != ECONNRESET &&
2606                     errno != ECONNABORTED)
2607                         log_error("Failed to write Plymouth message: %m");
2608
2609                 goto finish;
2610         }
2611
2612 finish:
2613         if (fd >= 0)
2614                 close_nointr_nofail(fd);
2615
2616         free(message);
2617 }
2618
2619 void manager_dispatch_bus_name_owner_changed(
2620                 Manager *m,
2621                 const char *name,
2622                 const char* old_owner,
2623                 const char *new_owner) {
2624
2625         Unit *u;
2626
2627         assert(m);
2628         assert(name);
2629
2630         if (!(u = hashmap_get(m->watch_bus, name)))
2631                 return;
2632
2633         UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2634 }
2635
2636 void manager_dispatch_bus_query_pid_done(
2637                 Manager *m,
2638                 const char *name,
2639                 pid_t pid) {
2640
2641         Unit *u;
2642
2643         assert(m);
2644         assert(name);
2645         assert(pid >= 1);
2646
2647         if (!(u = hashmap_get(m->watch_bus, name)))
2648                 return;
2649
2650         UNIT_VTABLE(u)->bus_query_pid_done(u, name, pid);
2651 }
2652
2653 int manager_open_serialization(Manager *m, FILE **_f) {
2654         char *path = NULL;
2655         mode_t saved_umask;
2656         int fd;
2657         FILE *f;
2658
2659         assert(_f);
2660
2661         if (m->running_as == MANAGER_SYSTEM)
2662                 asprintf(&path, "/run/systemd/dump-%lu-XXXXXX", (unsigned long) getpid());
2663         else
2664                 asprintf(&path, "/tmp/systemd-dump-%lu-XXXXXX", (unsigned long) getpid());
2665
2666         if (!path)
2667                 return -ENOMEM;
2668
2669         saved_umask = umask(0077);
2670         fd = mkostemp(path, O_RDWR|O_CLOEXEC);
2671         umask(saved_umask);
2672
2673         if (fd < 0) {
2674                 free(path);
2675                 return -errno;
2676         }
2677
2678         unlink(path);
2679
2680         log_debug("Serializing state to %s", path);
2681         free(path);
2682
2683         if (!(f = fdopen(fd, "w+")))
2684                 return -errno;
2685
2686         *_f = f;
2687
2688         return 0;
2689 }
2690
2691 int manager_serialize(Manager *m, FILE *f, FDSet *fds) {
2692         Iterator i;
2693         Unit *u;
2694         const char *t;
2695         int r;
2696
2697         assert(m);
2698         assert(f);
2699         assert(fds);
2700
2701         m->n_reloading ++;
2702
2703         fprintf(f, "current-job-id=%i\n", m->current_job_id);
2704         fprintf(f, "taint-usr=%s\n", yes_no(m->taint_usr));
2705
2706         dual_timestamp_serialize(f, "initrd-timestamp", &m->initrd_timestamp);
2707         dual_timestamp_serialize(f, "startup-timestamp", &m->startup_timestamp);
2708         dual_timestamp_serialize(f, "finish-timestamp", &m->finish_timestamp);
2709
2710         fputc('\n', f);
2711
2712         HASHMAP_FOREACH_KEY(u, t, m->units, i) {
2713                 if (u->meta.id != t)
2714                         continue;
2715
2716                 if (!unit_can_serialize(u))
2717                         continue;
2718
2719                 /* Start marker */
2720                 fputs(u->meta.id, f);
2721                 fputc('\n', f);
2722
2723                 if ((r = unit_serialize(u, f, fds)) < 0) {
2724                         m->n_reloading --;
2725                         return r;
2726                 }
2727         }
2728
2729         assert(m->n_reloading > 0);
2730         m->n_reloading --;
2731
2732         if (ferror(f))
2733                 return -EIO;
2734
2735         r = bus_fdset_add_all(m, fds);
2736         if (r < 0)
2737                 return r;
2738
2739         return 0;
2740 }
2741
2742 int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
2743         int r = 0;
2744
2745         assert(m);
2746         assert(f);
2747
2748         log_debug("Deserializing state...");
2749
2750         m->n_reloading ++;
2751
2752         for (;;) {
2753                 char line[LINE_MAX], *l;
2754
2755                 if (!fgets(line, sizeof(line), f)) {
2756                         if (feof(f))
2757                                 r = 0;
2758                         else
2759                                 r = -errno;
2760
2761                         goto finish;
2762                 }
2763
2764                 char_array_0(line);
2765                 l = strstrip(line);
2766
2767                 if (l[0] == 0)
2768                         break;
2769
2770                 if (startswith(l, "current-job-id=")) {
2771                         uint32_t id;
2772
2773                         if (safe_atou32(l+15, &id) < 0)
2774                                 log_debug("Failed to parse current job id value %s", l+15);
2775                         else
2776                                 m->current_job_id = MAX(m->current_job_id, id);
2777                 } else if (startswith(l, "taint-usr=")) {
2778                         int b;
2779
2780                         if ((b = parse_boolean(l+10)) < 0)
2781                                 log_debug("Failed to parse taint /usr flag %s", l+10);
2782                         else
2783                                 m->taint_usr = m->taint_usr || b;
2784                 } else if (startswith(l, "initrd-timestamp="))
2785                         dual_timestamp_deserialize(l+17, &m->initrd_timestamp);
2786                 else if (startswith(l, "startup-timestamp="))
2787                         dual_timestamp_deserialize(l+18, &m->startup_timestamp);
2788                 else if (startswith(l, "finish-timestamp="))
2789                         dual_timestamp_deserialize(l+17, &m->finish_timestamp);
2790                 else
2791                         log_debug("Unknown serialization item '%s'", l);
2792         }
2793
2794         for (;;) {
2795                 Unit *u;
2796                 char name[UNIT_NAME_MAX+2];
2797
2798                 /* Start marker */
2799                 if (!fgets(name, sizeof(name), f)) {
2800                         if (feof(f))
2801                                 r = 0;
2802                         else
2803                                 r = -errno;
2804
2805                         goto finish;
2806                 }
2807
2808                 char_array_0(name);
2809
2810                 if ((r = manager_load_unit(m, strstrip(name), NULL, NULL, &u)) < 0)
2811                         goto finish;
2812
2813                 if ((r = unit_deserialize(u, f, fds)) < 0)
2814                         goto finish;
2815         }
2816
2817 finish:
2818         if (ferror(f)) {
2819                 r = -EIO;
2820                 goto finish;
2821         }
2822
2823         assert(m->n_reloading > 0);
2824         m->n_reloading --;
2825
2826         return r;
2827 }
2828
2829 int manager_reload(Manager *m) {
2830         int r, q;
2831         FILE *f;
2832         FDSet *fds;
2833
2834         assert(m);
2835
2836         if ((r = manager_open_serialization(m, &f)) < 0)
2837                 return r;
2838
2839         m->n_reloading ++;
2840
2841         if (!(fds = fdset_new())) {
2842                 m->n_reloading --;
2843                 r = -ENOMEM;
2844                 goto finish;
2845         }
2846
2847         if ((r = manager_serialize(m, f, fds)) < 0) {
2848                 m->n_reloading --;
2849                 goto finish;
2850         }
2851
2852         if (fseeko(f, 0, SEEK_SET) < 0) {
2853                 m->n_reloading --;
2854                 r = -errno;
2855                 goto finish;
2856         }
2857
2858         /* From here on there is no way back. */
2859         manager_clear_jobs_and_units(m);
2860         manager_undo_generators(m);
2861
2862         /* Find new unit paths */
2863         lookup_paths_free(&m->lookup_paths);
2864         if ((q = lookup_paths_init(&m->lookup_paths, m->running_as, true)) < 0)
2865                 r = q;
2866
2867         manager_run_generators(m);
2868
2869         manager_build_unit_path_cache(m);
2870
2871         /* First, enumerate what we can from all config files */
2872         if ((q = manager_enumerate(m)) < 0)
2873                 r = q;
2874
2875         /* Second, deserialize our stored data */
2876         if ((q = manager_deserialize(m, f, fds)) < 0)
2877                 r = q;
2878
2879         fclose(f);
2880         f = NULL;
2881
2882         /* Third, fire things up! */
2883         if ((q = manager_coldplug(m)) < 0)
2884                 r = q;
2885
2886         assert(m->n_reloading > 0);
2887         m->n_reloading--;
2888
2889 finish:
2890         if (f)
2891                 fclose(f);
2892
2893         if (fds)
2894                 fdset_free(fds);
2895
2896         return r;
2897 }
2898
2899 bool manager_is_booting_or_shutting_down(Manager *m) {
2900         Unit *u;
2901
2902         assert(m);
2903
2904         /* Is the initial job still around? */
2905         if (manager_get_job(m, 1))
2906                 return true;
2907
2908         /* Is there a job for the shutdown target? */
2909         u = manager_get_unit(m, SPECIAL_SHUTDOWN_TARGET);
2910         if (u)
2911                 return !!u->meta.job;
2912
2913         return false;
2914 }
2915
2916 void manager_reset_failed(Manager *m) {
2917         Unit *u;
2918         Iterator i;
2919
2920         assert(m);
2921
2922         HASHMAP_FOREACH(u, m->units, i)
2923                 unit_reset_failed(u);
2924 }
2925
2926 bool manager_unit_pending_inactive(Manager *m, const char *name) {
2927         Unit *u;
2928
2929         assert(m);
2930         assert(name);
2931
2932         /* Returns true if the unit is inactive or going down */
2933         if (!(u = manager_get_unit(m, name)))
2934                 return true;
2935
2936         return unit_pending_inactive(u);
2937 }
2938
2939 void manager_check_finished(Manager *m) {
2940         char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
2941         usec_t kernel_usec = 0, initrd_usec = 0, userspace_usec = 0, total_usec = 0;
2942
2943         assert(m);
2944
2945         if (dual_timestamp_is_set(&m->finish_timestamp))
2946                 return;
2947
2948         if (hashmap_size(m->jobs) > 0)
2949                 return;
2950
2951         dual_timestamp_get(&m->finish_timestamp);
2952
2953         if (m->running_as == MANAGER_SYSTEM && detect_container(NULL) <= 0) {
2954
2955                 userspace_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
2956                 total_usec = m->finish_timestamp.monotonic;
2957
2958                 if (dual_timestamp_is_set(&m->initrd_timestamp)) {
2959
2960                         kernel_usec = m->initrd_timestamp.monotonic;
2961                         initrd_usec = m->startup_timestamp.monotonic - m->initrd_timestamp.monotonic;
2962
2963                         log_info("Startup finished in %s (kernel) + %s (initrd) + %s (userspace) = %s.",
2964                                  format_timespan(kernel, sizeof(kernel), kernel_usec),
2965                                  format_timespan(initrd, sizeof(initrd), initrd_usec),
2966                                  format_timespan(userspace, sizeof(userspace), userspace_usec),
2967                                  format_timespan(sum, sizeof(sum), total_usec));
2968                 } else {
2969                         kernel_usec = m->startup_timestamp.monotonic;
2970                         initrd_usec = 0;
2971
2972                         log_info("Startup finished in %s (kernel) + %s (userspace) = %s.",
2973                                  format_timespan(kernel, sizeof(kernel), kernel_usec),
2974                                  format_timespan(userspace, sizeof(userspace), userspace_usec),
2975                                  format_timespan(sum, sizeof(sum), total_usec));
2976                 }
2977         } else {
2978                 userspace_usec = initrd_usec = kernel_usec = 0;
2979                 total_usec = m->finish_timestamp.monotonic - m->startup_timestamp.monotonic;
2980
2981                 log_debug("Startup finished in %s.",
2982                           format_timespan(sum, sizeof(sum), total_usec));
2983         }
2984
2985         bus_broadcast_finished(m, kernel_usec, initrd_usec, userspace_usec, total_usec);
2986
2987         sd_notifyf(false,
2988                    "READY=1\nSTATUS=Startup finished in %s.",
2989                    format_timespan(sum, sizeof(sum), total_usec));
2990 }
2991
2992 void manager_run_generators(Manager *m) {
2993         DIR *d = NULL;
2994         const char *generator_path;
2995         const char *argv[3];
2996         mode_t u;
2997
2998         assert(m);
2999
3000         generator_path = m->running_as == MANAGER_SYSTEM ? SYSTEM_GENERATOR_PATH : USER_GENERATOR_PATH;
3001         if (!(d = opendir(generator_path))) {
3002
3003                 if (errno == ENOENT)
3004                         return;
3005
3006                 log_error("Failed to enumerate generator directory: %m");
3007                 return;
3008         }
3009
3010         if (!m->generator_unit_path) {
3011                 const char *p;
3012                 char user_path[] = "/tmp/systemd-generator-XXXXXX";
3013
3014                 if (m->running_as == MANAGER_SYSTEM && getpid() == 1) {
3015                         p = "/run/systemd/generator";
3016
3017                         if (mkdir_p(p, 0755) < 0) {
3018                                 log_error("Failed to create generator directory: %m");
3019                                 goto finish;
3020                         }
3021
3022                 } else {
3023                         if (!(p = mkdtemp(user_path))) {
3024                                 log_error("Failed to create generator directory: %m");
3025                                 goto finish;
3026                         }
3027                 }
3028
3029                 if (!(m->generator_unit_path = strdup(p))) {
3030                         log_error("Failed to allocate generator unit path.");
3031                         goto finish;
3032                 }
3033         }
3034
3035         argv[0] = NULL; /* Leave this empty, execute_directory() will fill something in */
3036         argv[1] = m->generator_unit_path;
3037         argv[2] = NULL;
3038
3039         u = umask(0022);
3040         execute_directory(generator_path, d, (char**) argv);
3041         umask(u);
3042
3043         if (rmdir(m->generator_unit_path) >= 0) {
3044                 /* Uh? we were able to remove this dir? I guess that
3045                  * means the directory was empty, hence let's shortcut
3046                  * this */
3047
3048                 free(m->generator_unit_path);
3049                 m->generator_unit_path = NULL;
3050                 goto finish;
3051         }
3052
3053         if (!strv_find(m->lookup_paths.unit_path, m->generator_unit_path)) {
3054                 char **l;
3055
3056                 if (!(l = strv_append(m->lookup_paths.unit_path, m->generator_unit_path))) {
3057                         log_error("Failed to add generator directory to unit search path: %m");
3058                         goto finish;
3059                 }
3060
3061                 strv_free(m->lookup_paths.unit_path);
3062                 m->lookup_paths.unit_path = l;
3063
3064                 log_debug("Added generator unit path %s to search path.", m->generator_unit_path);
3065         }
3066
3067 finish:
3068         if (d)
3069                 closedir(d);
3070 }
3071
3072 void manager_undo_generators(Manager *m) {
3073         assert(m);
3074
3075         if (!m->generator_unit_path)
3076                 return;
3077
3078         strv_remove(m->lookup_paths.unit_path, m->generator_unit_path);
3079         rm_rf(m->generator_unit_path, false, true, false);
3080
3081         free(m->generator_unit_path);
3082         m->generator_unit_path = NULL;
3083 }
3084
3085 int manager_set_default_controllers(Manager *m, char **controllers) {
3086         char **l;
3087
3088         assert(m);
3089
3090         if (!(l = strv_copy(controllers)))
3091                 return -ENOMEM;
3092
3093         strv_free(m->default_controllers);
3094         m->default_controllers = l;
3095
3096         return 0;
3097 }
3098
3099 void manager_recheck_syslog(Manager *m) {
3100         Unit *u;
3101
3102         assert(m);
3103
3104         if (m->running_as != MANAGER_SYSTEM)
3105                 return;
3106
3107         if ((u = manager_get_unit(m, SPECIAL_SYSLOG_SOCKET))) {
3108                 SocketState state;
3109
3110                 state = SOCKET(u)->state;
3111
3112                 if (state != SOCKET_DEAD &&
3113                     state != SOCKET_FAILED &&
3114                     state != SOCKET_RUNNING) {
3115
3116                         /* Hmm, the socket is not set up, or is still
3117                          * listening, let's better not try to use
3118                          * it. Note that we have no problem if the
3119                          * socket is completely down, since there
3120                          * might be a foreign /dev/log socket around
3121                          * and we want to make use of that.
3122                          */
3123
3124                         log_close_syslog();
3125                         return;
3126                 }
3127         }
3128
3129         if ((u = manager_get_unit(m, SPECIAL_SYSLOG_TARGET)))
3130                 if (TARGET(u)->state != TARGET_ACTIVE) {
3131                         log_close_syslog();
3132                         return;
3133                 }
3134
3135         /* Hmm, OK, so the socket is either fully up, or fully down,
3136          * and the target is up, then let's make use of the socket */
3137         log_open();
3138 }
3139
3140 void manager_set_show_status(Manager *m, bool b) {
3141         assert(m);
3142
3143         if (m->running_as != MANAGER_SYSTEM)
3144                 return;
3145
3146         m->show_status = b;
3147
3148         if (b)
3149                 touch("/run/systemd/show-status");
3150         else
3151                 unlink("/run/systemd/show-status");
3152 }
3153
3154 bool manager_get_show_status(Manager *m) {
3155         assert(m);
3156
3157         if (m->running_as != MANAGER_SYSTEM)
3158                 return false;
3159
3160         if (m->show_status)
3161                 return true;
3162
3163         /* If Plymouth is running make sure we show the status, so
3164          * that there's something nice to see when people press Esc */
3165
3166         return plymouth_running();
3167 }
3168
3169 static const char* const manager_running_as_table[_MANAGER_RUNNING_AS_MAX] = {
3170         [MANAGER_SYSTEM] = "system",
3171         [MANAGER_USER] = "user"
3172 };
3173
3174 DEFINE_STRING_TABLE_LOOKUP(manager_running_as, ManagerRunningAs);