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