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