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