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