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