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