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