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