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