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