chiark / gitweb /
util: don't AND cx with cx
[elogind.git] / src / unit.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 <sys/timerfd.h>
27 #include <sys/poll.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <sys/stat.h>
31
32 #include "set.h"
33 #include "unit.h"
34 #include "macro.h"
35 #include "strv.h"
36 #include "load-fragment.h"
37 #include "load-dropin.h"
38 #include "log.h"
39 #include "unit-name.h"
40 #include "specifier.h"
41 #include "dbus-unit.h"
42 #include "special.h"
43 #include "cgroup-util.h"
44 #include "missing.h"
45
46 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
47         [UNIT_SERVICE] = &service_vtable,
48         [UNIT_TIMER] = &timer_vtable,
49         [UNIT_SOCKET] = &socket_vtable,
50         [UNIT_TARGET] = &target_vtable,
51         [UNIT_DEVICE] = &device_vtable,
52         [UNIT_MOUNT] = &mount_vtable,
53         [UNIT_AUTOMOUNT] = &automount_vtable,
54         [UNIT_SNAPSHOT] = &snapshot_vtable,
55         [UNIT_SWAP] = &swap_vtable,
56         [UNIT_PATH] = &path_vtable
57 };
58
59 Unit *unit_new(Manager *m) {
60         Unit *u;
61
62         assert(m);
63
64         if (!(u = new0(Unit, 1)))
65                 return NULL;
66
67         if (!(u->meta.names = set_new(string_hash_func, string_compare_func))) {
68                 free(u);
69                 return NULL;
70         }
71
72         u->meta.manager = m;
73         u->meta.type = _UNIT_TYPE_INVALID;
74         u->meta.deserialized_job = _JOB_TYPE_INVALID;
75         u->meta.default_dependencies = true;
76
77         return u;
78 }
79
80 bool unit_has_name(Unit *u, const char *name) {
81         assert(u);
82         assert(name);
83
84         return !!set_get(u->meta.names, (char*) name);
85 }
86
87 int unit_add_name(Unit *u, const char *text) {
88         UnitType t;
89         char *s, *i = NULL;
90         int r;
91
92         assert(u);
93         assert(text);
94
95         if (unit_name_is_template(text)) {
96                 if (!u->meta.instance)
97                         return -EINVAL;
98
99                 s = unit_name_replace_instance(text, u->meta.instance);
100         } else
101                 s = strdup(text);
102
103         if (!s)
104                 return -ENOMEM;
105
106         if (!unit_name_is_valid(s, false)) {
107                 r = -EINVAL;
108                 goto fail;
109         }
110
111         assert_se((t = unit_name_to_type(s)) >= 0);
112
113         if (u->meta.type != _UNIT_TYPE_INVALID && t != u->meta.type) {
114                 r = -EINVAL;
115                 goto fail;
116         }
117
118         if ((r = unit_name_to_instance(s, &i)) < 0)
119                 goto fail;
120
121         if (i && unit_vtable[t]->no_instances) {
122                 r = -EINVAL;
123                 goto fail;
124         }
125
126         /* Ensure that this unit is either instanced or not instanced,
127          * but not both. */
128         if (u->meta.type != _UNIT_TYPE_INVALID && !u->meta.instance != !i) {
129                 r = -EINVAL;
130                 goto fail;
131         }
132
133         if (unit_vtable[t]->no_alias &&
134             !set_isempty(u->meta.names) &&
135             !set_get(u->meta.names, s)) {
136                 r = -EEXIST;
137                 goto fail;
138         }
139
140         if (hashmap_size(u->meta.manager->units) >= MANAGER_MAX_NAMES) {
141                 r = -E2BIG;
142                 goto fail;
143         }
144
145         if ((r = set_put(u->meta.names, s)) < 0) {
146                 if (r == -EEXIST)
147                         r = 0;
148                 goto fail;
149         }
150
151         if ((r = hashmap_put(u->meta.manager->units, s, u)) < 0) {
152                 set_remove(u->meta.names, s);
153                 goto fail;
154         }
155
156         if (u->meta.type == _UNIT_TYPE_INVALID) {
157
158                 u->meta.type = t;
159                 u->meta.id = s;
160                 u->meta.instance = i;
161
162                 LIST_PREPEND(Meta, units_per_type, u->meta.manager->units_per_type[t], &u->meta);
163
164                 if (UNIT_VTABLE(u)->init)
165                         UNIT_VTABLE(u)->init(u);
166         } else
167                 free(i);
168
169         unit_add_to_dbus_queue(u);
170         return 0;
171
172 fail:
173         free(s);
174         free(i);
175
176         return r;
177 }
178
179 int unit_choose_id(Unit *u, const char *name) {
180         char *s, *t = NULL, *i;
181         int r;
182
183         assert(u);
184         assert(name);
185
186         if (unit_name_is_template(name)) {
187
188                 if (!u->meta.instance)
189                         return -EINVAL;
190
191                 if (!(t = unit_name_replace_instance(name, u->meta.instance)))
192                         return -ENOMEM;
193
194                 name = t;
195         }
196
197         /* Selects one of the names of this unit as the id */
198         s = set_get(u->meta.names, (char*) name);
199         free(t);
200
201         if (!s)
202                 return -ENOENT;
203
204         if ((r = unit_name_to_instance(s, &i)) < 0)
205                 return r;
206
207         u->meta.id = s;
208
209         free(u->meta.instance);
210         u->meta.instance = i;
211
212         unit_add_to_dbus_queue(u);
213
214         return 0;
215 }
216
217 int unit_set_description(Unit *u, const char *description) {
218         char *s;
219
220         assert(u);
221
222         if (!(s = strdup(description)))
223                 return -ENOMEM;
224
225         free(u->meta.description);
226         u->meta.description = s;
227
228         unit_add_to_dbus_queue(u);
229         return 0;
230 }
231
232 bool unit_check_gc(Unit *u) {
233         assert(u);
234
235         if (u->meta.load_state == UNIT_STUB)
236                 return true;
237
238         if (UNIT_VTABLE(u)->no_gc)
239                 return true;
240
241         if (u->meta.no_gc)
242                 return true;
243
244         if (u->meta.job)
245                 return true;
246
247         if (unit_active_state(u) != UNIT_INACTIVE)
248                 return true;
249
250         if (UNIT_VTABLE(u)->check_gc)
251                 if (UNIT_VTABLE(u)->check_gc(u))
252                         return true;
253
254         return false;
255 }
256
257 void unit_add_to_load_queue(Unit *u) {
258         assert(u);
259         assert(u->meta.type != _UNIT_TYPE_INVALID);
260
261         if (u->meta.load_state != UNIT_STUB || u->meta.in_load_queue)
262                 return;
263
264         LIST_PREPEND(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
265         u->meta.in_load_queue = true;
266 }
267
268 void unit_add_to_cleanup_queue(Unit *u) {
269         assert(u);
270
271         if (u->meta.in_cleanup_queue)
272                 return;
273
274         LIST_PREPEND(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
275         u->meta.in_cleanup_queue = true;
276 }
277
278 void unit_add_to_gc_queue(Unit *u) {
279         assert(u);
280
281         if (u->meta.in_gc_queue || u->meta.in_cleanup_queue)
282                 return;
283
284         if (unit_check_gc(u))
285                 return;
286
287         LIST_PREPEND(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
288         u->meta.in_gc_queue = true;
289
290         u->meta.manager->n_in_gc_queue ++;
291
292         if (u->meta.manager->gc_queue_timestamp <= 0)
293                 u->meta.manager->gc_queue_timestamp = now(CLOCK_MONOTONIC);
294 }
295
296 void unit_add_to_dbus_queue(Unit *u) {
297         assert(u);
298         assert(u->meta.type != _UNIT_TYPE_INVALID);
299
300         if (u->meta.load_state == UNIT_STUB || u->meta.in_dbus_queue)
301                 return;
302
303         /* Shortcut things if nobody cares */
304         if (!bus_has_subscriber(u->meta.manager)) {
305                 u->meta.sent_dbus_new_signal = true;
306                 return;
307         }
308
309         LIST_PREPEND(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
310         u->meta.in_dbus_queue = true;
311 }
312
313 static void bidi_set_free(Unit *u, Set *s) {
314         Iterator i;
315         Unit *other;
316
317         assert(u);
318
319         /* Frees the set and makes sure we are dropped from the
320          * inverse pointers */
321
322         SET_FOREACH(other, s, i) {
323                 UnitDependency d;
324
325                 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
326                         set_remove(other->meta.dependencies[d], u);
327
328                 unit_add_to_gc_queue(other);
329         }
330
331         set_free(s);
332 }
333
334 void unit_free(Unit *u) {
335         UnitDependency d;
336         Iterator i;
337         char *t;
338
339         assert(u);
340
341         bus_unit_send_removed_signal(u);
342
343         if (u->meta.load_state != UNIT_STUB)
344                 if (UNIT_VTABLE(u)->done)
345                         UNIT_VTABLE(u)->done(u);
346
347         SET_FOREACH(t, u->meta.names, i)
348                 hashmap_remove_value(u->meta.manager->units, t, u);
349
350         if (u->meta.job)
351                 job_free(u->meta.job);
352
353         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
354                 bidi_set_free(u, u->meta.dependencies[d]);
355
356         if (u->meta.type != _UNIT_TYPE_INVALID)
357                 LIST_REMOVE(Meta, units_per_type, u->meta.manager->units_per_type[u->meta.type], &u->meta);
358
359         if (u->meta.in_load_queue)
360                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
361
362         if (u->meta.in_dbus_queue)
363                 LIST_REMOVE(Meta, dbus_queue, u->meta.manager->dbus_unit_queue, &u->meta);
364
365         if (u->meta.in_cleanup_queue)
366                 LIST_REMOVE(Meta, cleanup_queue, u->meta.manager->cleanup_queue, &u->meta);
367
368         if (u->meta.in_gc_queue) {
369                 LIST_REMOVE(Meta, gc_queue, u->meta.manager->gc_queue, &u->meta);
370                 u->meta.manager->n_in_gc_queue--;
371         }
372
373         cgroup_bonding_free_list(u->meta.cgroup_bondings, u->meta.manager->n_serializing <= 0);
374
375         free(u->meta.description);
376         free(u->meta.fragment_path);
377
378         set_free_free(u->meta.names);
379
380         condition_free_list(u->meta.conditions);
381
382         free(u->meta.instance);
383         free(u);
384 }
385
386 UnitActiveState unit_active_state(Unit *u) {
387         assert(u);
388
389         if (u->meta.load_state == UNIT_MERGED)
390                 return unit_active_state(unit_follow_merge(u));
391
392         /* After a reload it might happen that a unit is not correctly
393          * loaded but still has a process around. That's why we won't
394          * shortcut failed loading to UNIT_INACTIVE_FAILED. */
395
396         return UNIT_VTABLE(u)->active_state(u);
397 }
398
399 const char* unit_sub_state_to_string(Unit *u) {
400         assert(u);
401
402         return UNIT_VTABLE(u)->sub_state_to_string(u);
403 }
404
405 static void complete_move(Set **s, Set **other) {
406         assert(s);
407         assert(other);
408
409         if (!*other)
410                 return;
411
412         if (*s)
413                 set_move(*s, *other);
414         else {
415                 *s = *other;
416                 *other = NULL;
417         }
418 }
419
420 static void merge_names(Unit *u, Unit *other) {
421         char *t;
422         Iterator i;
423
424         assert(u);
425         assert(other);
426
427         complete_move(&u->meta.names, &other->meta.names);
428
429         set_free_free(other->meta.names);
430         other->meta.names = NULL;
431         other->meta.id = NULL;
432
433         SET_FOREACH(t, u->meta.names, i)
434                 assert_se(hashmap_replace(u->meta.manager->units, t, u) == 0);
435 }
436
437 static void merge_dependencies(Unit *u, Unit *other, UnitDependency d) {
438         Iterator i;
439         Unit *back;
440         int r;
441
442         assert(u);
443         assert(other);
444         assert(d < _UNIT_DEPENDENCY_MAX);
445
446         /* Fix backwards pointers */
447         SET_FOREACH(back, other->meta.dependencies[d], i) {
448                 UnitDependency k;
449
450                 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
451                         if ((r = set_remove_and_put(back->meta.dependencies[k], other, u)) < 0) {
452
453                                 if (r == -EEXIST)
454                                         set_remove(back->meta.dependencies[k], other);
455                                 else
456                                         assert(r == -ENOENT);
457                         }
458         }
459
460         complete_move(&u->meta.dependencies[d], &other->meta.dependencies[d]);
461
462         set_free(other->meta.dependencies[d]);
463         other->meta.dependencies[d] = NULL;
464 }
465
466 int unit_merge(Unit *u, Unit *other) {
467         UnitDependency d;
468
469         assert(u);
470         assert(other);
471         assert(u->meta.manager == other->meta.manager);
472         assert(u->meta.type != _UNIT_TYPE_INVALID);
473
474         other = unit_follow_merge(other);
475
476         if (other == u)
477                 return 0;
478
479         if (u->meta.type != other->meta.type)
480                 return -EINVAL;
481
482         if (!u->meta.instance != !other->meta.instance)
483                 return -EINVAL;
484
485         if (other->meta.load_state != UNIT_STUB &&
486             other->meta.load_state != UNIT_ERROR)
487                 return -EEXIST;
488
489         if (other->meta.job)
490                 return -EEXIST;
491
492         if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
493                 return -EEXIST;
494
495         /* Merge names */
496         merge_names(u, other);
497
498         /* Merge dependencies */
499         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
500                 merge_dependencies(u, other, d);
501
502         other->meta.load_state = UNIT_MERGED;
503         other->meta.merged_into = u;
504
505         /* If there is still some data attached to the other node, we
506          * don't need it anymore, and can free it. */
507         if (other->meta.load_state != UNIT_STUB)
508                 if (UNIT_VTABLE(other)->done)
509                         UNIT_VTABLE(other)->done(other);
510
511         unit_add_to_dbus_queue(u);
512         unit_add_to_cleanup_queue(other);
513
514         return 0;
515 }
516
517 int unit_merge_by_name(Unit *u, const char *name) {
518         Unit *other;
519         int r;
520         char *s = NULL;
521
522         assert(u);
523         assert(name);
524
525         if (unit_name_is_template(name)) {
526                 if (!u->meta.instance)
527                         return -EINVAL;
528
529                 if (!(s = unit_name_replace_instance(name, u->meta.instance)))
530                         return -ENOMEM;
531
532                 name = s;
533         }
534
535         if (!(other = manager_get_unit(u->meta.manager, name)))
536                 r = unit_add_name(u, name);
537         else
538                 r = unit_merge(u, other);
539
540         free(s);
541         return r;
542 }
543
544 Unit* unit_follow_merge(Unit *u) {
545         assert(u);
546
547         while (u->meta.load_state == UNIT_MERGED)
548                 assert_se(u = u->meta.merged_into);
549
550         return u;
551 }
552
553 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
554         int r;
555
556         assert(u);
557         assert(c);
558
559         if (c->std_output != EXEC_OUTPUT_KMSG &&
560             c->std_output != EXEC_OUTPUT_SYSLOG &&
561             c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
562             c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
563             c->std_error != EXEC_OUTPUT_KMSG &&
564             c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
565             c->std_error != EXEC_OUTPUT_KMSG &&
566             c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
567                 return 0;
568
569         /* If syslog or kernel logging is requested, make sure our own
570          * logging daemon is run first. */
571
572         if (u->meta.manager->running_as == MANAGER_SYSTEM)
573                 if ((r = unit_add_two_dependencies_by_name(u, UNIT_REQUIRES, UNIT_AFTER, SPECIAL_LOGGER_SOCKET, NULL, true)) < 0)
574                         return r;
575
576         return 0;
577 }
578
579 const char *unit_description(Unit *u) {
580         assert(u);
581
582         if (u->meta.description)
583                 return u->meta.description;
584
585         return strna(u->meta.id);
586 }
587
588 void unit_dump(Unit *u, FILE *f, const char *prefix) {
589         char *t;
590         UnitDependency d;
591         Iterator i;
592         char *p2;
593         const char *prefix2;
594         CGroupBonding *b;
595         char
596                 timestamp1[FORMAT_TIMESTAMP_MAX],
597                 timestamp2[FORMAT_TIMESTAMP_MAX],
598                 timestamp3[FORMAT_TIMESTAMP_MAX],
599                 timestamp4[FORMAT_TIMESTAMP_MAX],
600                 timespan[FORMAT_TIMESPAN_MAX];
601         Unit *following;
602
603         assert(u);
604         assert(u->meta.type >= 0);
605
606         if (!prefix)
607                 prefix = "";
608         p2 = strappend(prefix, "\t");
609         prefix2 = p2 ? p2 : prefix;
610
611         fprintf(f,
612                 "%s-> Unit %s:\n"
613                 "%s\tDescription: %s\n"
614                 "%s\tInstance: %s\n"
615                 "%s\tUnit Load State: %s\n"
616                 "%s\tUnit Active State: %s\n"
617                 "%s\tInactive Exit Timestamp: %s\n"
618                 "%s\tActive Enter Timestamp: %s\n"
619                 "%s\tActive Exit Timestamp: %s\n"
620                 "%s\tInactive Enter Timestamp: %s\n"
621                 "%s\tGC Check Good: %s\n"
622                 "%s\tNeed Daemon Reload: %s\n",
623                 prefix, u->meta.id,
624                 prefix, unit_description(u),
625                 prefix, strna(u->meta.instance),
626                 prefix, unit_load_state_to_string(u->meta.load_state),
627                 prefix, unit_active_state_to_string(unit_active_state(u)),
628                 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.inactive_exit_timestamp.realtime)),
629                 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->meta.active_enter_timestamp.realtime)),
630                 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->meta.active_exit_timestamp.realtime)),
631                 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->meta.inactive_enter_timestamp.realtime)),
632                 prefix, yes_no(unit_check_gc(u)),
633                 prefix, yes_no(unit_need_daemon_reload(u)));
634
635         SET_FOREACH(t, u->meta.names, i)
636                 fprintf(f, "%s\tName: %s\n", prefix, t);
637
638         if ((following = unit_following(u)))
639                 fprintf(f, "%s\tFollowing: %s\n", prefix, following->meta.id);
640
641         if (u->meta.fragment_path)
642                 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->meta.fragment_path);
643
644         if (u->meta.job_timeout > 0)
645                 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->meta.job_timeout));
646
647         condition_dump_list(u->meta.conditions, f, prefix);
648
649         if (dual_timestamp_is_set(&u->meta.condition_timestamp))
650                 fprintf(f,
651                         "%s\tCondition Timestamp: %s\n"
652                         "%s\tCondition Result: %s\n",
653                         prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->meta.condition_timestamp.realtime)),
654                         prefix, yes_no(u->meta.condition_result));
655
656         for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
657                 Unit *other;
658
659                 SET_FOREACH(other, u->meta.dependencies[d], i)
660                         fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->meta.id);
661         }
662
663         if (u->meta.load_state == UNIT_LOADED) {
664                 fprintf(f,
665                         "%s\tStopWhenUnneeded: %s\n"
666                         "%s\tRefuseManualStart: %s\n"
667                         "%s\tRefuseManualStop: %s\n"
668                         "%s\tDefaultDependencies: %s\n"
669                         "%s\tOnFailureIsolate: %s\n"
670                         "%s\tIgnoreOnIsolate: %s\n",
671                         prefix, yes_no(u->meta.stop_when_unneeded),
672                         prefix, yes_no(u->meta.refuse_manual_start),
673                         prefix, yes_no(u->meta.refuse_manual_stop),
674                         prefix, yes_no(u->meta.default_dependencies),
675                         prefix, yes_no(u->meta.on_failure_isolate),
676                         prefix, yes_no(u->meta.ignore_on_isolate));
677
678                 LIST_FOREACH(by_unit, b, u->meta.cgroup_bondings)
679                         fprintf(f, "%s\tControlGroup: %s:%s\n",
680                                 prefix, b->controller, b->path);
681
682                 if (UNIT_VTABLE(u)->dump)
683                         UNIT_VTABLE(u)->dump(u, f, prefix2);
684
685         } else if (u->meta.load_state == UNIT_MERGED)
686                 fprintf(f,
687                         "%s\tMerged into: %s\n",
688                         prefix, u->meta.merged_into->meta.id);
689         else if (u->meta.load_state == UNIT_ERROR)
690                 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->meta.load_error));
691
692
693         if (u->meta.job)
694                 job_dump(u->meta.job, f, prefix2);
695
696         free(p2);
697 }
698
699 /* Common implementation for multiple backends */
700 int unit_load_fragment_and_dropin(Unit *u) {
701         int r;
702
703         assert(u);
704
705         /* Load a .service file */
706         if ((r = unit_load_fragment(u)) < 0)
707                 return r;
708
709         if (u->meta.load_state == UNIT_STUB)
710                 return -ENOENT;
711
712         /* Load drop-in directory data */
713         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
714                 return r;
715
716         return 0;
717 }
718
719 /* Common implementation for multiple backends */
720 int unit_load_fragment_and_dropin_optional(Unit *u) {
721         int r;
722
723         assert(u);
724
725         /* Same as unit_load_fragment_and_dropin(), but whether
726          * something can be loaded or not doesn't matter. */
727
728         /* Load a .service file */
729         if ((r = unit_load_fragment(u)) < 0)
730                 return r;
731
732         if (u->meta.load_state == UNIT_STUB)
733                 u->meta.load_state = UNIT_LOADED;
734
735         /* Load drop-in directory data */
736         if ((r = unit_load_dropin(unit_follow_merge(u))) < 0)
737                 return r;
738
739         return 0;
740 }
741
742 int unit_add_default_target_dependency(Unit *u, Unit *target) {
743         assert(u);
744         assert(target);
745
746         if (target->meta.type != UNIT_TARGET)
747                 return 0;
748
749         /* Only add the dependency if both units are loaded, so that
750          * that loop check below is reliable */
751         if (u->meta.load_state != UNIT_LOADED ||
752             target->meta.load_state != UNIT_LOADED)
753                 return 0;
754
755         /* If either side wants no automatic dependencies, then let's
756          * skip this */
757         if (!u->meta.default_dependencies ||
758             target->meta.default_dependencies)
759                 return 0;
760
761         /* Don't create loops */
762         if (set_get(target->meta.dependencies[UNIT_BEFORE], u))
763                 return 0;
764
765         return unit_add_dependency(target, UNIT_AFTER, u, true);
766 }
767
768 static int unit_add_default_dependencies(Unit *u) {
769         static const UnitDependency deps[] = {
770                 UNIT_REQUIRED_BY,
771                 UNIT_REQUIRED_BY_OVERRIDABLE,
772                 UNIT_WANTED_BY,
773                 UNIT_BOUND_BY
774         };
775
776         Unit *target;
777         Iterator i;
778         int r;
779         unsigned k;
780
781         assert(u);
782
783         for (k = 0; k < ELEMENTSOF(deps); k++)
784                 SET_FOREACH(target, u->meta.dependencies[deps[k]], i)
785                         if ((r = unit_add_default_target_dependency(u, target)) < 0)
786                                 return r;
787
788         return 0;
789 }
790
791 int unit_load(Unit *u) {
792         int r;
793
794         assert(u);
795
796         if (u->meta.in_load_queue) {
797                 LIST_REMOVE(Meta, load_queue, u->meta.manager->load_queue, &u->meta);
798                 u->meta.in_load_queue = false;
799         }
800
801         if (u->meta.type == _UNIT_TYPE_INVALID)
802                 return -EINVAL;
803
804         if (u->meta.load_state != UNIT_STUB)
805                 return 0;
806
807         if (UNIT_VTABLE(u)->load)
808                 if ((r = UNIT_VTABLE(u)->load(u)) < 0)
809                         goto fail;
810
811         if (u->meta.load_state == UNIT_STUB) {
812                 r = -ENOENT;
813                 goto fail;
814         }
815
816         if (u->meta.load_state == UNIT_LOADED &&
817             u->meta.default_dependencies)
818                 if ((r = unit_add_default_dependencies(u)) < 0)
819                         goto fail;
820
821         if (u->meta.on_failure_isolate &&
822             set_size(u->meta.dependencies[UNIT_ON_FAILURE]) > 1) {
823
824                 log_error("More than one OnFailure= dependencies specified for %s but OnFailureIsolate= enabled. Refusing.",
825                           u->meta.id);
826
827                 r = -EINVAL;
828                 goto fail;
829         }
830
831         assert((u->meta.load_state != UNIT_MERGED) == !u->meta.merged_into);
832
833         unit_add_to_dbus_queue(unit_follow_merge(u));
834         unit_add_to_gc_queue(u);
835
836         return 0;
837
838 fail:
839         u->meta.load_state = UNIT_ERROR;
840         u->meta.load_error = r;
841         unit_add_to_dbus_queue(u);
842
843         log_debug("Failed to load configuration for %s: %s", u->meta.id, strerror(-r));
844
845         return r;
846 }
847
848 bool unit_condition_test(Unit *u) {
849         assert(u);
850
851         dual_timestamp_get(&u->meta.condition_timestamp);
852         u->meta.condition_result = condition_test_list(u->meta.conditions);
853
854         return u->meta.condition_result;
855 }
856
857 /* Errors:
858  *         -EBADR:     This unit type does not support starting.
859  *         -EALREADY:  Unit is already started.
860  *         -EAGAIN:    An operation is already in progress. Retry later.
861  *         -ECANCELED: Too many requests for now.
862  */
863 int unit_start(Unit *u) {
864         UnitActiveState state;
865         Unit *following;
866
867         assert(u);
868
869         if (u->meta.load_state != UNIT_LOADED)
870                 return -EINVAL;
871
872         /* If this is already (being) started, then this will
873          * succeed. Note that this will even succeed if this unit is
874          * not startable by the user. This is relied on to detect when
875          * we need to wait for units and when waiting is finished. */
876         state = unit_active_state(u);
877         if (UNIT_IS_ACTIVE_OR_RELOADING(state))
878                 return -EALREADY;
879
880         /* If the conditions failed, don't do anything at all */
881         if (!unit_condition_test(u)) {
882                 log_debug("Starting of %s requested but condition failed. Ignoring.", u->meta.id);
883                 return -EALREADY;
884         }
885
886         /* Forward to the main object, if we aren't it. */
887         if ((following = unit_following(u))) {
888                 log_debug("Redirecting start request from %s to %s.", u->meta.id, following->meta.id);
889                 return unit_start(following);
890         }
891
892         /* If it is stopped, but we cannot start it, then fail */
893         if (!UNIT_VTABLE(u)->start)
894                 return -EBADR;
895
896         /* We don't suppress calls to ->start() here when we are
897          * already starting, to allow this request to be used as a
898          * "hurry up" call, for example when the unit is in some "auto
899          * restart" state where it waits for a holdoff timer to elapse
900          * before it will start again. */
901
902         unit_add_to_dbus_queue(u);
903
904         unit_status_printf(u, "Starting %s...\n", unit_description(u));
905         return UNIT_VTABLE(u)->start(u);
906 }
907
908 bool unit_can_start(Unit *u) {
909         assert(u);
910
911         return !!UNIT_VTABLE(u)->start;
912 }
913
914 bool unit_can_isolate(Unit *u) {
915         assert(u);
916
917         return unit_can_start(u) &&
918                 u->meta.allow_isolate;
919 }
920
921 /* Errors:
922  *         -EBADR:    This unit type does not support stopping.
923  *         -EALREADY: Unit is already stopped.
924  *         -EAGAIN:   An operation is already in progress. Retry later.
925  */
926 int unit_stop(Unit *u) {
927         UnitActiveState state;
928         Unit *following;
929
930         assert(u);
931
932         state = unit_active_state(u);
933         if (UNIT_IS_INACTIVE_OR_FAILED(state))
934                 return -EALREADY;
935
936         if ((following = unit_following(u))) {
937                 log_debug("Redirecting stop request from %s to %s.", u->meta.id, following->meta.id);
938                 return unit_stop(following);
939         }
940
941         if (!UNIT_VTABLE(u)->stop)
942                 return -EBADR;
943
944         unit_add_to_dbus_queue(u);
945
946         unit_status_printf(u, "Stopping %s...\n", unit_description(u));
947         return UNIT_VTABLE(u)->stop(u);
948 }
949
950 /* Errors:
951  *         -EBADR:    This unit type does not support reloading.
952  *         -ENOEXEC:  Unit is not started.
953  *         -EAGAIN:   An operation is already in progress. Retry later.
954  */
955 int unit_reload(Unit *u) {
956         UnitActiveState state;
957         Unit *following;
958
959         assert(u);
960
961         if (u->meta.load_state != UNIT_LOADED)
962                 return -EINVAL;
963
964         if (!unit_can_reload(u))
965                 return -EBADR;
966
967         state = unit_active_state(u);
968         if (state == UNIT_RELOADING)
969                 return -EALREADY;
970
971         if (state != UNIT_ACTIVE)
972                 return -ENOEXEC;
973
974         if ((following = unit_following(u))) {
975                 log_debug("Redirecting reload request from %s to %s.", u->meta.id, following->meta.id);
976                 return unit_reload(following);
977         }
978
979         unit_add_to_dbus_queue(u);
980         return UNIT_VTABLE(u)->reload(u);
981 }
982
983 bool unit_can_reload(Unit *u) {
984         assert(u);
985
986         if (!UNIT_VTABLE(u)->reload)
987                 return false;
988
989         if (!UNIT_VTABLE(u)->can_reload)
990                 return true;
991
992         return UNIT_VTABLE(u)->can_reload(u);
993 }
994
995 static void unit_check_unneeded(Unit *u) {
996         Iterator i;
997         Unit *other;
998
999         assert(u);
1000
1001         /* If this service shall be shut down when unneeded then do
1002          * so. */
1003
1004         if (!u->meta.stop_when_unneeded)
1005                 return;
1006
1007         if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1008                 return;
1009
1010         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY], i)
1011                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1012                         return;
1013
1014         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRED_BY_OVERRIDABLE], i)
1015                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1016                         return;
1017
1018         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTED_BY], i)
1019                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1020                         return;
1021
1022         SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1023                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1024                         return;
1025
1026         log_info("Service %s is not needed anymore. Stopping.", u->meta.id);
1027
1028         /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1029         manager_add_job(u->meta.manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1030 }
1031
1032 static void retroactively_start_dependencies(Unit *u) {
1033         Iterator i;
1034         Unit *other;
1035
1036         assert(u);
1037         assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1038
1039         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1040                 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1041                     !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1042                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1043
1044         SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1045                 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1046                     !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1047                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1048
1049         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1050                 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1051                     !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1052                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1053
1054         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1055                 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1056                     !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1057                         manager_add_job(u->meta.manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
1058
1059         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1060                 if (!set_get(u->meta.dependencies[UNIT_AFTER], other) &&
1061                     !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1062                         manager_add_job(u->meta.manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
1063
1064         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTS], i)
1065                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1066                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1067
1068         SET_FOREACH(other, u->meta.dependencies[UNIT_CONFLICTED_BY], i)
1069                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1070                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1071 }
1072
1073 static void retroactively_stop_dependencies(Unit *u) {
1074         Iterator i;
1075         Unit *other;
1076
1077         assert(u);
1078         assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1079
1080         /* Pull down units which are bound to us recursively if enabled */
1081         SET_FOREACH(other, u->meta.dependencies[UNIT_BOUND_BY], i)
1082                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1083                         manager_add_job(u->meta.manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
1084
1085         /* Garbage collect services that might not be needed anymore, if enabled */
1086         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES], i)
1087                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1088                         unit_check_unneeded(other);
1089         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1090                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1091                         unit_check_unneeded(other);
1092         SET_FOREACH(other, u->meta.dependencies[UNIT_WANTS], i)
1093                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1094                         unit_check_unneeded(other);
1095         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE], i)
1096                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1097                         unit_check_unneeded(other);
1098         SET_FOREACH(other, u->meta.dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
1099                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1100                         unit_check_unneeded(other);
1101         SET_FOREACH(other, u->meta.dependencies[UNIT_BIND_TO], i)
1102                 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1103                         unit_check_unneeded(other);
1104 }
1105
1106 void unit_trigger_on_failure(Unit *u) {
1107         Unit *other;
1108         Iterator i;
1109
1110         assert(u);
1111
1112         if (set_size(u->meta.dependencies[UNIT_ON_FAILURE]) <= 0)
1113                 return;
1114
1115         log_info("Triggering OnFailure= dependencies of %s.", u->meta.id);
1116
1117         SET_FOREACH(other, u->meta.dependencies[UNIT_ON_FAILURE], i) {
1118                 int r;
1119
1120                 if ((r = manager_add_job(u->meta.manager, JOB_START, other, u->meta.on_failure_isolate ? JOB_ISOLATE : JOB_REPLACE, true, NULL, NULL)) < 0)
1121                         log_error("Failed to enqueue OnFailure= job: %s", strerror(-r));
1122         }
1123 }
1124
1125 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1126         bool unexpected;
1127
1128         assert(u);
1129         assert(os < _UNIT_ACTIVE_STATE_MAX);
1130         assert(ns < _UNIT_ACTIVE_STATE_MAX);
1131
1132         /* Note that this is called for all low-level state changes,
1133          * even if they might map to the same high-level
1134          * UnitActiveState! That means that ns == os is OK an expected
1135          * behaviour here. For example: if a mount point is remounted
1136          * this function will be called too! */
1137
1138         if (u->meta.manager->n_deserializing <= 0) {
1139                 dual_timestamp ts;
1140
1141                 dual_timestamp_get(&ts);
1142
1143                 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1144                         u->meta.inactive_exit_timestamp = ts;
1145                 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1146                         u->meta.inactive_enter_timestamp = ts;
1147
1148                 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1149                         u->meta.active_enter_timestamp = ts;
1150                 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1151                         u->meta.active_exit_timestamp = ts;
1152
1153                 timer_unit_notify(u, ns);
1154                 path_unit_notify(u, ns);
1155         }
1156
1157         if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1158                 cgroup_bonding_trim_list(u->meta.cgroup_bondings, true);
1159
1160         if (u->meta.job) {
1161                 unexpected = false;
1162
1163                 if (u->meta.job->state == JOB_WAITING)
1164
1165                         /* So we reached a different state for this
1166                          * job. Let's see if we can run it now if it
1167                          * failed previously due to EAGAIN. */
1168                         job_add_to_run_queue(u->meta.job);
1169
1170                 /* Let's check whether this state change constitutes a
1171                  * finished job, or maybe contradicts a running job and
1172                  * hence needs to invalidate jobs. */
1173
1174                 switch (u->meta.job->type) {
1175
1176                 case JOB_START:
1177                 case JOB_VERIFY_ACTIVE:
1178
1179                         if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1180                                 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1181                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1182                                 unexpected = true;
1183
1184                                 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1185                                         job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1186                         }
1187
1188                         break;
1189
1190                 case JOB_RELOAD:
1191                 case JOB_RELOAD_OR_START:
1192
1193                         if (u->meta.job->state == JOB_RUNNING) {
1194                                 if (ns == UNIT_ACTIVE)
1195                                         job_finish_and_invalidate(u->meta.job, reload_success ? JOB_DONE : JOB_FAILED);
1196                                 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1197                                         unexpected = true;
1198
1199                                         if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1200                                                 job_finish_and_invalidate(u->meta.job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE);
1201                                 }
1202                         }
1203
1204                         break;
1205
1206                 case JOB_STOP:
1207                 case JOB_RESTART:
1208                 case JOB_TRY_RESTART:
1209
1210                         if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1211                                 job_finish_and_invalidate(u->meta.job, JOB_DONE);
1212                         else if (u->meta.job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1213                                 unexpected = true;
1214                                 job_finish_and_invalidate(u->meta.job, JOB_FAILED);
1215                         }
1216
1217                         break;
1218
1219                 default:
1220                         assert_not_reached("Job type unknown");
1221                 }
1222
1223         } else
1224                 unexpected = true;
1225
1226         if (u->meta.manager->n_deserializing <= 0) {
1227
1228                 /* If this state change happened without being
1229                  * requested by a job, then let's retroactively start
1230                  * or stop dependencies. We skip that step when
1231                  * deserializing, since we don't want to create any
1232                  * additional jobs just because something is already
1233                  * activated. */
1234
1235                 if (unexpected) {
1236                         if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1237                                 retroactively_start_dependencies(u);
1238                         else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1239                                 retroactively_stop_dependencies(u);
1240                 }
1241
1242                 if (ns != os && ns == UNIT_FAILED) {
1243                         log_notice("Unit %s entered failed state.", u->meta.id);
1244                         unit_trigger_on_failure(u);
1245                 }
1246         }
1247
1248         /* Some names are special */
1249         if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1250
1251                 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1252                         /* The bus just might have become available,
1253                          * hence try to connect to it, if we aren't
1254                          * yet connected. */
1255                         bus_init(u->meta.manager, true);
1256
1257                 if (u->meta.type == UNIT_SERVICE &&
1258                     !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1259                     u->meta.manager->n_deserializing <= 0) {
1260                         /* Write audit record if we have just finished starting up */
1261                         manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, true);
1262                         u->meta.in_audit = true;
1263                 }
1264
1265                 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1266                         manager_send_unit_plymouth(u->meta.manager, u);
1267
1268         } else {
1269
1270                 /* We don't care about D-Bus here, since we'll get an
1271                  * asynchronous notification for it anyway. */
1272
1273                 if (u->meta.type == UNIT_SERVICE &&
1274                     UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1275                     !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1276                     u->meta.manager->n_deserializing <= 0) {
1277
1278                         /* Hmm, if there was no start record written
1279                          * write it now, so that we always have a nice
1280                          * pair */
1281                         if (!u->meta.in_audit) {
1282                                 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
1283
1284                                 if (ns == UNIT_INACTIVE)
1285                                         manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, true);
1286                         } else
1287                                 /* Write audit record if we have just finished shutting down */
1288                                 manager_send_unit_audit(u->meta.manager, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
1289
1290                         u->meta.in_audit = false;
1291                 }
1292         }
1293
1294         manager_recheck_syslog(u->meta.manager);
1295
1296         /* Maybe we finished startup and are now ready for being
1297          * stopped because unneeded? */
1298         unit_check_unneeded(u);
1299
1300         unit_add_to_dbus_queue(u);
1301         unit_add_to_gc_queue(u);
1302 }
1303
1304 int unit_watch_fd(Unit *u, int fd, uint32_t events, Watch *w) {
1305         struct epoll_event ev;
1306
1307         assert(u);
1308         assert(fd >= 0);
1309         assert(w);
1310         assert(w->type == WATCH_INVALID || (w->type == WATCH_FD && w->fd == fd && w->data.unit == u));
1311
1312         zero(ev);
1313         ev.data.ptr = w;
1314         ev.events = events;
1315
1316         if (epoll_ctl(u->meta.manager->epoll_fd,
1317                       w->type == WATCH_INVALID ? EPOLL_CTL_ADD : EPOLL_CTL_MOD,
1318                       fd,
1319                       &ev) < 0)
1320                 return -errno;
1321
1322         w->fd = fd;
1323         w->type = WATCH_FD;
1324         w->data.unit = u;
1325
1326         return 0;
1327 }
1328
1329 void unit_unwatch_fd(Unit *u, Watch *w) {
1330         assert(u);
1331         assert(w);
1332
1333         if (w->type == WATCH_INVALID)
1334                 return;
1335
1336         assert(w->type == WATCH_FD);
1337         assert(w->data.unit == u);
1338         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1339
1340         w->fd = -1;
1341         w->type = WATCH_INVALID;
1342         w->data.unit = NULL;
1343 }
1344
1345 int unit_watch_pid(Unit *u, pid_t pid) {
1346         assert(u);
1347         assert(pid >= 1);
1348
1349         /* Watch a specific PID. We only support one unit watching
1350          * each PID for now. */
1351
1352         return hashmap_put(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1353 }
1354
1355 void unit_unwatch_pid(Unit *u, pid_t pid) {
1356         assert(u);
1357         assert(pid >= 1);
1358
1359         hashmap_remove_value(u->meta.manager->watch_pids, LONG_TO_PTR(pid), u);
1360 }
1361
1362 int unit_watch_timer(Unit *u, usec_t delay, Watch *w) {
1363         struct itimerspec its;
1364         int flags, fd;
1365         bool ours;
1366
1367         assert(u);
1368         assert(w);
1369         assert(w->type == WATCH_INVALID || (w->type == WATCH_UNIT_TIMER && w->data.unit == u));
1370
1371         /* This will try to reuse the old timer if there is one */
1372
1373         if (w->type == WATCH_UNIT_TIMER) {
1374                 assert(w->data.unit == u);
1375                 assert(w->fd >= 0);
1376
1377                 ours = false;
1378                 fd = w->fd;
1379         } else if (w->type == WATCH_INVALID) {
1380
1381                 ours = true;
1382                 if ((fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
1383                         return -errno;
1384         } else
1385                 assert_not_reached("Invalid watch type");
1386
1387         zero(its);
1388
1389         if (delay <= 0) {
1390                 /* Set absolute time in the past, but not 0, since we
1391                  * don't want to disarm the timer */
1392                 its.it_value.tv_sec = 0;
1393                 its.it_value.tv_nsec = 1;
1394
1395                 flags = TFD_TIMER_ABSTIME;
1396         } else {
1397                 timespec_store(&its.it_value, delay);
1398                 flags = 0;
1399         }
1400
1401         /* This will also flush the elapse counter */
1402         if (timerfd_settime(fd, flags, &its, NULL) < 0)
1403                 goto fail;
1404
1405         if (w->type == WATCH_INVALID) {
1406                 struct epoll_event ev;
1407
1408                 zero(ev);
1409                 ev.data.ptr = w;
1410                 ev.events = EPOLLIN;
1411
1412                 if (epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1413                         goto fail;
1414         }
1415
1416         w->type = WATCH_UNIT_TIMER;
1417         w->fd = fd;
1418         w->data.unit = u;
1419
1420         return 0;
1421
1422 fail:
1423         if (ours)
1424                 close_nointr_nofail(fd);
1425
1426         return -errno;
1427 }
1428
1429 void unit_unwatch_timer(Unit *u, Watch *w) {
1430         assert(u);
1431         assert(w);
1432
1433         if (w->type == WATCH_INVALID)
1434                 return;
1435
1436         assert(w->type == WATCH_UNIT_TIMER);
1437         assert(w->data.unit == u);
1438         assert(w->fd >= 0);
1439
1440         assert_se(epoll_ctl(u->meta.manager->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
1441         close_nointr_nofail(w->fd);
1442
1443         w->fd = -1;
1444         w->type = WATCH_INVALID;
1445         w->data.unit = NULL;
1446 }
1447
1448 bool unit_job_is_applicable(Unit *u, JobType j) {
1449         assert(u);
1450         assert(j >= 0 && j < _JOB_TYPE_MAX);
1451
1452         switch (j) {
1453
1454         case JOB_VERIFY_ACTIVE:
1455         case JOB_START:
1456         case JOB_STOP:
1457                 return true;
1458
1459         case JOB_RESTART:
1460         case JOB_TRY_RESTART:
1461                 return unit_can_start(u);
1462
1463         case JOB_RELOAD:
1464                 return unit_can_reload(u);
1465
1466         case JOB_RELOAD_OR_START:
1467                 return unit_can_reload(u) && unit_can_start(u);
1468
1469         default:
1470                 assert_not_reached("Invalid job type");
1471         }
1472 }
1473
1474 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
1475
1476         static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
1477                 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
1478                 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1479                 [UNIT_WANTS] = UNIT_WANTED_BY,
1480                 [UNIT_REQUISITE] = UNIT_REQUIRED_BY,
1481                 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
1482                 [UNIT_BIND_TO] = UNIT_BOUND_BY,
1483                 [UNIT_REQUIRED_BY] = _UNIT_DEPENDENCY_INVALID,
1484                 [UNIT_REQUIRED_BY_OVERRIDABLE] = _UNIT_DEPENDENCY_INVALID,
1485                 [UNIT_WANTED_BY] = _UNIT_DEPENDENCY_INVALID,
1486                 [UNIT_BOUND_BY] = UNIT_BIND_TO,
1487                 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
1488                 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
1489                 [UNIT_BEFORE] = UNIT_AFTER,
1490                 [UNIT_AFTER] = UNIT_BEFORE,
1491                 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
1492                 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
1493                 [UNIT_REFERENCED_BY] = UNIT_REFERENCES
1494         };
1495         int r, q = 0, v = 0, w = 0;
1496
1497         assert(u);
1498         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1499         assert(other);
1500
1501         u = unit_follow_merge(u);
1502         other = unit_follow_merge(other);
1503
1504         /* We won't allow dependencies on ourselves. We will not
1505          * consider them an error however. */
1506         if (u == other)
1507                 return 0;
1508
1509         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1510                 return r;
1511
1512         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1513                 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1514                         return r;
1515
1516         if (add_reference)
1517                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1518                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1519                         return r;
1520
1521         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1522                 return q;
1523
1524         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1525                 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1526                         r = v;
1527                         goto fail;
1528                 }
1529
1530         if (add_reference) {
1531                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1532                         r = w;
1533                         goto fail;
1534                 }
1535
1536                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1537                         goto fail;
1538         }
1539
1540         unit_add_to_dbus_queue(u);
1541         return 0;
1542
1543 fail:
1544         if (q > 0)
1545                 set_remove(u->meta.dependencies[d], other);
1546
1547         if (v > 0)
1548                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1549
1550         if (w > 0)
1551                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1552
1553         return r;
1554 }
1555
1556 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1557         int r;
1558
1559         assert(u);
1560
1561         if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1562                 return r;
1563
1564         if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1565                 return r;
1566
1567         return 0;
1568 }
1569
1570 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1571         char *s;
1572
1573         assert(u);
1574         assert(name || path);
1575
1576         if (!name)
1577                 name = file_name_from_path(path);
1578
1579         if (!unit_name_is_template(name)) {
1580                 *p = NULL;
1581                 return name;
1582         }
1583
1584         if (u->meta.instance)
1585                 s = unit_name_replace_instance(name, u->meta.instance);
1586         else {
1587                 char *i;
1588
1589                 if (!(i = unit_name_to_prefix(u->meta.id)))
1590                         return NULL;
1591
1592                 s = unit_name_replace_instance(name, i);
1593                 free(i);
1594         }
1595
1596         if (!s)
1597                 return NULL;
1598
1599         *p = s;
1600         return s;
1601 }
1602
1603 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1604         Unit *other;
1605         int r;
1606         char *s;
1607
1608         assert(u);
1609         assert(name || path);
1610
1611         if (!(name = resolve_template(u, name, path, &s)))
1612                 return -ENOMEM;
1613
1614         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1615                 goto finish;
1616
1617         r = unit_add_dependency(u, d, other, add_reference);
1618
1619 finish:
1620         free(s);
1621         return r;
1622 }
1623
1624 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1625         Unit *other;
1626         int r;
1627         char *s;
1628
1629         assert(u);
1630         assert(name || path);
1631
1632         if (!(name = resolve_template(u, name, path, &s)))
1633                 return -ENOMEM;
1634
1635         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1636                 goto finish;
1637
1638         r = unit_add_two_dependencies(u, d, e, other, add_reference);
1639
1640 finish:
1641         free(s);
1642         return r;
1643 }
1644
1645 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1646         Unit *other;
1647         int r;
1648         char *s;
1649
1650         assert(u);
1651         assert(name || path);
1652
1653         if (!(name = resolve_template(u, name, path, &s)))
1654                 return -ENOMEM;
1655
1656         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1657                 goto finish;
1658
1659         r = unit_add_dependency(other, d, u, add_reference);
1660
1661 finish:
1662         free(s);
1663         return r;
1664 }
1665
1666 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1667         Unit *other;
1668         int r;
1669         char *s;
1670
1671         assert(u);
1672         assert(name || path);
1673
1674         if (!(name = resolve_template(u, name, path, &s)))
1675                 return -ENOMEM;
1676
1677         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1678                 goto finish;
1679
1680         if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1681                 goto finish;
1682
1683 finish:
1684         free(s);
1685         return r;
1686 }
1687
1688 int set_unit_path(const char *p) {
1689         char *cwd, *c;
1690         int r;
1691
1692         /* This is mostly for debug purposes */
1693
1694         if (path_is_absolute(p)) {
1695                 if (!(c = strdup(p)))
1696                         return -ENOMEM;
1697         } else {
1698                 if (!(cwd = get_current_dir_name()))
1699                         return -errno;
1700
1701                 r = asprintf(&c, "%s/%s", cwd, p);
1702                 free(cwd);
1703
1704                 if (r < 0)
1705                         return -ENOMEM;
1706         }
1707
1708         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1709                 r = -errno;
1710                 free(c);
1711                 return r;
1712         }
1713
1714         return 0;
1715 }
1716
1717 char *unit_dbus_path(Unit *u) {
1718         char *p, *e;
1719
1720         assert(u);
1721
1722         if (!u->meta.id)
1723                 return NULL;
1724
1725         if (!(e = bus_path_escape(u->meta.id)))
1726                 return NULL;
1727
1728         p = strappend("/org/freedesktop/systemd1/unit/", e);
1729         free(e);
1730
1731         return p;
1732 }
1733
1734 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1735         int r;
1736
1737         assert(u);
1738         assert(b);
1739
1740         assert(b->path);
1741
1742         if (!b->controller)
1743                 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1744                         return -ENOMEM;
1745
1746         /* Ensure this hasn't been added yet */
1747         assert(!b->unit);
1748
1749         if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1750                 CGroupBonding *l;
1751
1752                 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1753                 LIST_PREPEND(CGroupBonding, by_path, l, b);
1754
1755                 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1756                         LIST_REMOVE(CGroupBonding, by_path, l, b);
1757                         return r;
1758                 }
1759         }
1760
1761         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1762         b->unit = u;
1763
1764         return 0;
1765 }
1766
1767 static char *default_cgroup_path(Unit *u) {
1768         char *p;
1769         int r;
1770
1771         assert(u);
1772
1773         if (u->meta.instance) {
1774                 char *t;
1775
1776                 if (!(t = unit_name_template(u->meta.id)))
1777                         return NULL;
1778
1779                 r = asprintf(&p, "%s/%s/%s", u->meta.manager->cgroup_hierarchy, t, u->meta.instance);
1780                 free(t);
1781         } else
1782                 r = asprintf(&p, "%s/%s", u->meta.manager->cgroup_hierarchy, u->meta.id);
1783
1784         return r < 0 ? NULL : p;
1785 }
1786
1787 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1788         char *controller = NULL, *path = NULL;
1789         CGroupBonding *b = NULL;
1790         int r;
1791
1792         assert(u);
1793         assert(name);
1794
1795         if ((r = cg_split_spec(name, &controller, &path)) < 0)
1796                 return r;
1797
1798         if (!path)
1799                 path = default_cgroup_path(u);
1800
1801         if (!controller)
1802                 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1803
1804         if (!path || !controller) {
1805                 free(path);
1806                 free(controller);
1807
1808                 return -ENOMEM;
1809         }
1810
1811         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1812                 r = -EEXIST;
1813                 goto fail;
1814         }
1815
1816         if (!(b = new0(CGroupBonding, 1))) {
1817                 r = -ENOMEM;
1818                 goto fail;
1819         }
1820
1821         b->controller = controller;
1822         b->path = path;
1823         b->ours = false;
1824
1825         if ((r = unit_add_cgroup(u, b)) < 0)
1826                 goto fail;
1827
1828         return 0;
1829
1830 fail:
1831         free(path);
1832         free(controller);
1833         free(b);
1834
1835         return r;
1836 }
1837
1838 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1839         CGroupBonding *b = NULL;
1840         int r = -ENOMEM;
1841
1842         assert(u);
1843
1844         if (!controller)
1845                 controller = SYSTEMD_CGROUP_CONTROLLER;
1846
1847         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller))
1848                 return 0;
1849
1850         if (!(b = new0(CGroupBonding, 1)))
1851                 return -ENOMEM;
1852
1853         if (!(b->controller = strdup(controller)))
1854                 goto fail;
1855
1856         if (!(b->path = default_cgroup_path(u)))
1857                 goto fail;
1858
1859         b->ours = true;
1860         b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1861
1862         if ((r = unit_add_cgroup(u, b)) < 0)
1863                 goto fail;
1864
1865         return 0;
1866
1867 fail:
1868         free(b->path);
1869         free(b->controller);
1870         free(b);
1871
1872         return r;
1873 }
1874
1875 int unit_add_default_cgroups(Unit *u) {
1876         char **c;
1877         int r;
1878         assert(u);
1879
1880         /* Adds in the default cgroups, if they weren't specified
1881          * otherwise. */
1882
1883         if (!u->meta.manager->cgroup_hierarchy)
1884                 return 0;
1885
1886         if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1887                 return r;
1888
1889         STRV_FOREACH(c, u->meta.manager->default_controllers)
1890                 if ((r = unit_add_one_default_cgroup(u, *c)) < 0)
1891                         return r;
1892
1893         return 0;
1894 }
1895
1896 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1897         assert(u);
1898
1899         return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1900 }
1901
1902 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
1903         char *t;
1904         int r;
1905
1906         assert(u);
1907         assert(type);
1908         assert(_found);
1909
1910         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1911                 return -ENOMEM;
1912
1913         assert(!unit_has_name(u, t));
1914
1915         r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
1916         free(t);
1917
1918         assert(r < 0 || *_found != u);
1919
1920         return r;
1921 }
1922
1923 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
1924         Unit *found;
1925         char *t;
1926
1927         assert(u);
1928         assert(type);
1929         assert(_found);
1930
1931         if (!(t = unit_name_change_suffix(u->meta.id, type)))
1932                 return -ENOMEM;
1933
1934         assert(!unit_has_name(u, t));
1935
1936         found = manager_get_unit(u->meta.manager, t);
1937         free(t);
1938
1939         if (!found)
1940                 return -ENOENT;
1941
1942         *_found = found;
1943         return 0;
1944 }
1945
1946 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
1947         Unit *u = userdata;
1948         assert(u);
1949
1950         return unit_name_to_prefix_and_instance(u->meta.id);
1951 }
1952
1953 static char *specifier_prefix(char specifier, void *data, void *userdata) {
1954         Unit *u = userdata;
1955         assert(u);
1956
1957         return unit_name_to_prefix(u->meta.id);
1958 }
1959
1960 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
1961         Unit *u = userdata;
1962         char *p, *r;
1963
1964         assert(u);
1965
1966         if (!(p = unit_name_to_prefix(u->meta.id)))
1967                 return NULL;
1968
1969         r = unit_name_unescape(p);
1970         free(p);
1971
1972         return r;
1973 }
1974
1975 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
1976         Unit *u = userdata;
1977         assert(u);
1978
1979         if (u->meta.instance)
1980                 return unit_name_unescape(u->meta.instance);
1981
1982         return strdup("");
1983 }
1984
1985 static char *specifier_filename(char specifier, void *data, void *userdata) {
1986         Unit *u = userdata;
1987         assert(u);
1988
1989         if (u->meta.instance)
1990                 return unit_name_path_unescape(u->meta.instance);
1991
1992         return unit_name_to_path(u->meta.instance);
1993 }
1994
1995 char *unit_name_printf(Unit *u, const char* format) {
1996
1997         /*
1998          * This will use the passed string as format string and
1999          * replace the following specifiers:
2000          *
2001          * %n: the full id of the unit                 (foo@bar.waldo)
2002          * %N: the id of the unit without the suffix   (foo@bar)
2003          * %p: the prefix                              (foo)
2004          * %i: the instance                            (bar)
2005          */
2006
2007         const Specifier table[] = {
2008                 { 'n', specifier_string,              u->meta.id },
2009                 { 'N', specifier_prefix_and_instance, NULL },
2010                 { 'p', specifier_prefix,              NULL },
2011                 { 'i', specifier_string,              u->meta.instance },
2012                 { 0, NULL, NULL }
2013         };
2014
2015         assert(u);
2016         assert(format);
2017
2018         return specifier_printf(format, table, u);
2019 }
2020
2021 char *unit_full_printf(Unit *u, const char *format) {
2022
2023         /* This is similar to unit_name_printf() but also supports
2024          * unescaping */
2025
2026         const Specifier table[] = {
2027                 { 'n', specifier_string,              u->meta.id },
2028                 { 'N', specifier_prefix_and_instance, NULL },
2029                 { 'p', specifier_prefix,              NULL },
2030                 { 'P', specifier_prefix_unescaped,    NULL },
2031                 { 'i', specifier_string,              u->meta.instance },
2032                 { 'I', specifier_instance_unescaped,  NULL },
2033                 { 'f', specifier_filename,            NULL },
2034                 { 0, NULL, NULL }
2035         };
2036
2037         assert(u);
2038         assert(format);
2039
2040         return specifier_printf(format, table, u);
2041 }
2042
2043 char **unit_full_printf_strv(Unit *u, char **l) {
2044         size_t n;
2045         char **r, **i, **j;
2046
2047         /* Applies unit_full_printf to every entry in l */
2048
2049         assert(u);
2050
2051         n = strv_length(l);
2052         if (!(r = new(char*, n+1)))
2053                 return NULL;
2054
2055         for (i = l, j = r; *i; i++, j++)
2056                 if (!(*j = unit_full_printf(u, *i)))
2057                         goto fail;
2058
2059         *j = NULL;
2060         return r;
2061
2062 fail:
2063         for (j--; j >= r; j--)
2064                 free(*j);
2065
2066         free(r);
2067
2068         return NULL;
2069 }
2070
2071 int unit_watch_bus_name(Unit *u, const char *name) {
2072         assert(u);
2073         assert(name);
2074
2075         /* Watch a specific name on the bus. We only support one unit
2076          * watching each name for now. */
2077
2078         return hashmap_put(u->meta.manager->watch_bus, name, u);
2079 }
2080
2081 void unit_unwatch_bus_name(Unit *u, const char *name) {
2082         assert(u);
2083         assert(name);
2084
2085         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
2086 }
2087
2088 bool unit_can_serialize(Unit *u) {
2089         assert(u);
2090
2091         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2092 }
2093
2094 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2095         int r;
2096
2097         assert(u);
2098         assert(f);
2099         assert(fds);
2100
2101         if (!unit_can_serialize(u))
2102                 return 0;
2103
2104         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2105                 return r;
2106
2107         if (u->meta.job)
2108                 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
2109
2110         dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->meta.inactive_exit_timestamp);
2111         dual_timestamp_serialize(f, "active-enter-timestamp", &u->meta.active_enter_timestamp);
2112         dual_timestamp_serialize(f, "active-exit-timestamp", &u->meta.active_exit_timestamp);
2113         dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->meta.inactive_enter_timestamp);
2114         dual_timestamp_serialize(f, "condition-timestamp", &u->meta.condition_timestamp);
2115
2116         if (dual_timestamp_is_set(&u->meta.condition_timestamp))
2117                 unit_serialize_item(u, f, "condition-result", yes_no(u->meta.condition_result));
2118
2119         /* End marker */
2120         fputc('\n', f);
2121         return 0;
2122 }
2123
2124 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2125         va_list ap;
2126
2127         assert(u);
2128         assert(f);
2129         assert(key);
2130         assert(format);
2131
2132         fputs(key, f);
2133         fputc('=', f);
2134
2135         va_start(ap, format);
2136         vfprintf(f, format, ap);
2137         va_end(ap);
2138
2139         fputc('\n', f);
2140 }
2141
2142 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2143         assert(u);
2144         assert(f);
2145         assert(key);
2146         assert(value);
2147
2148         fprintf(f, "%s=%s\n", key, value);
2149 }
2150
2151 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2152         int r;
2153
2154         assert(u);
2155         assert(f);
2156         assert(fds);
2157
2158         if (!unit_can_serialize(u))
2159                 return 0;
2160
2161         for (;;) {
2162                 char line[LINE_MAX], *l, *v;
2163                 size_t k;
2164
2165                 if (!fgets(line, sizeof(line), f)) {
2166                         if (feof(f))
2167                                 return 0;
2168                         return -errno;
2169                 }
2170
2171                 char_array_0(line);
2172                 l = strstrip(line);
2173
2174                 /* End marker */
2175                 if (l[0] == 0)
2176                         return 0;
2177
2178                 k = strcspn(l, "=");
2179
2180                 if (l[k] == '=') {
2181                         l[k] = 0;
2182                         v = l+k+1;
2183                 } else
2184                         v = l+k;
2185
2186                 if (streq(l, "job")) {
2187                         JobType type;
2188
2189                         if ((type = job_type_from_string(v)) < 0)
2190                                 log_debug("Failed to parse job type value %s", v);
2191                         else
2192                                 u->meta.deserialized_job = type;
2193
2194                         continue;
2195                 } else if (streq(l, "inactive-exit-timestamp")) {
2196                         dual_timestamp_deserialize(v, &u->meta.inactive_exit_timestamp);
2197                         continue;
2198                 } else if (streq(l, "active-enter-timestamp")) {
2199                         dual_timestamp_deserialize(v, &u->meta.active_enter_timestamp);
2200                         continue;
2201                 } else if (streq(l, "active-exit-timestamp")) {
2202                         dual_timestamp_deserialize(v, &u->meta.active_exit_timestamp);
2203                         continue;
2204                 } else if (streq(l, "inactive-enter-timestamp")) {
2205                         dual_timestamp_deserialize(v, &u->meta.inactive_enter_timestamp);
2206                         continue;
2207                 } else if (streq(l, "condition-timestamp")) {
2208                         dual_timestamp_deserialize(v, &u->meta.condition_timestamp);
2209                         continue;
2210                 } else if (streq(l, "condition-result")) {
2211                         int b;
2212
2213                         if ((b = parse_boolean(v)) < 0)
2214                                 log_debug("Failed to parse condition result value %s", v);
2215                         else
2216                                 u->meta.condition_result = b;
2217
2218                         continue;
2219                 }
2220
2221                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2222                         return r;
2223         }
2224 }
2225
2226 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2227         Unit *device;
2228         char *e;
2229         int r;
2230
2231         assert(u);
2232
2233         if (!what)
2234                 return 0;
2235
2236         /* Adds in links to the device node that this unit is based on */
2237
2238         if (!is_device_path(what))
2239                 return 0;
2240
2241         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2242                 return -ENOMEM;
2243
2244         r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2245         free(e);
2246
2247         if (r < 0)
2248                 return r;
2249
2250         if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2251                 return r;
2252
2253         if (wants)
2254                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2255                         return r;
2256
2257         return 0;
2258 }
2259
2260 int unit_coldplug(Unit *u) {
2261         int r;
2262
2263         assert(u);
2264
2265         if (UNIT_VTABLE(u)->coldplug)
2266                 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2267                         return r;
2268
2269         if (u->meta.deserialized_job >= 0) {
2270                 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL)) < 0)
2271                         return r;
2272
2273                 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2274         }
2275
2276         return 0;
2277 }
2278
2279 void unit_status_printf(Unit *u, const char *format, ...) {
2280         va_list ap;
2281
2282         assert(u);
2283         assert(format);
2284
2285         if (!UNIT_VTABLE(u)->show_status)
2286                 return;
2287
2288         if (u->meta.manager->running_as != MANAGER_SYSTEM)
2289                 return;
2290
2291         /* If Plymouth is running make sure we show the status, so
2292          * that there's something nice to see when people press Esc */
2293
2294         if (!u->meta.manager->show_status && !plymouth_running())
2295                 return;
2296
2297         if (!manager_is_booting_or_shutting_down(u->meta.manager))
2298                 return;
2299
2300         va_start(ap, format);
2301         status_vprintf(format, ap);
2302         va_end(ap);
2303 }
2304
2305 bool unit_need_daemon_reload(Unit *u) {
2306         struct stat st;
2307
2308         assert(u);
2309
2310         if (!u->meta.fragment_path)
2311                 return false;
2312
2313         zero(st);
2314         if (stat(u->meta.fragment_path, &st) < 0)
2315                 /* What, cannot access this anymore? */
2316                 return true;
2317
2318         return
2319                 u->meta.fragment_mtime &&
2320                 timespec_load(&st.st_mtim) != u->meta.fragment_mtime;
2321 }
2322
2323 void unit_reset_failed(Unit *u) {
2324         assert(u);
2325
2326         if (UNIT_VTABLE(u)->reset_failed)
2327                 UNIT_VTABLE(u)->reset_failed(u);
2328 }
2329
2330 Unit *unit_following(Unit *u) {
2331         assert(u);
2332
2333         if (UNIT_VTABLE(u)->following)
2334                 return UNIT_VTABLE(u)->following(u);
2335
2336         return NULL;
2337 }
2338
2339 bool unit_pending_inactive(Unit *u) {
2340         assert(u);
2341
2342         /* Returns true if the unit is inactive or going down */
2343
2344         if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2345                 return true;
2346
2347         if (u->meta.job && u->meta.job->type == JOB_STOP)
2348                 return true;
2349
2350         return false;
2351 }
2352
2353 bool unit_pending_active(Unit *u) {
2354         assert(u);
2355
2356         /* Returns true if the unit is inactive or going down */
2357
2358         if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2359                 return true;
2360
2361         if (u->meta.job &&
2362             (u->meta.job->type == JOB_START ||
2363              u->meta.job->type == JOB_RELOAD_OR_START ||
2364              u->meta.job->type == JOB_RESTART))
2365                 return true;
2366
2367         return false;
2368 }
2369
2370 UnitType unit_name_to_type(const char *n) {
2371         UnitType t;
2372
2373         assert(n);
2374
2375         for (t = 0; t < _UNIT_TYPE_MAX; t++)
2376                 if (endswith(n, unit_vtable[t]->suffix))
2377                         return t;
2378
2379         return _UNIT_TYPE_INVALID;
2380 }
2381
2382 bool unit_name_is_valid(const char *n, bool template_ok) {
2383         UnitType t;
2384
2385         t = unit_name_to_type(n);
2386         if (t < 0 || t >= _UNIT_TYPE_MAX)
2387                 return false;
2388
2389         return unit_name_is_valid_no_type(n, template_ok);
2390 }
2391
2392 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2393         assert(u);
2394         assert(w >= 0 && w < _KILL_WHO_MAX);
2395         assert(m >= 0 && m < _KILL_MODE_MAX);
2396         assert(signo > 0);
2397         assert(signo < _NSIG);
2398
2399         if (m == KILL_NONE)
2400                 return 0;
2401
2402         if (!UNIT_VTABLE(u)->kill)
2403                 return -ENOTSUP;
2404
2405         return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2406 }
2407
2408
2409 int unit_following_set(Unit *u, Set **s) {
2410         assert(u);
2411         assert(s);
2412
2413         if (UNIT_VTABLE(u)->following_set)
2414                 return UNIT_VTABLE(u)->following_set(u, s);
2415
2416         *s = NULL;
2417         return 0;
2418 }
2419
2420 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2421         [UNIT_STUB] = "stub",
2422         [UNIT_LOADED] = "loaded",
2423         [UNIT_ERROR] = "error",
2424         [UNIT_MERGED] = "merged",
2425         [UNIT_MASKED] = "masked"
2426 };
2427
2428 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2429
2430 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2431         [UNIT_ACTIVE] = "active",
2432         [UNIT_RELOADING] = "reloading",
2433         [UNIT_INACTIVE] = "inactive",
2434         [UNIT_FAILED] = "failed",
2435         [UNIT_ACTIVATING] = "activating",
2436         [UNIT_DEACTIVATING] = "deactivating"
2437 };
2438
2439 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2440
2441 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2442         [UNIT_REQUIRES] = "Requires",
2443         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2444         [UNIT_WANTS] = "Wants",
2445         [UNIT_REQUISITE] = "Requisite",
2446         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2447         [UNIT_REQUIRED_BY] = "RequiredBy",
2448         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2449         [UNIT_BIND_TO] = "BindTo",
2450         [UNIT_WANTED_BY] = "WantedBy",
2451         [UNIT_CONFLICTS] = "Conflicts",
2452         [UNIT_CONFLICTED_BY] = "ConflictedBy",
2453         [UNIT_BOUND_BY] = "BoundBy",
2454         [UNIT_BEFORE] = "Before",
2455         [UNIT_AFTER] = "After",
2456         [UNIT_REFERENCES] = "References",
2457         [UNIT_REFERENCED_BY] = "ReferencedBy",
2458         [UNIT_ON_FAILURE] = "OnFailure"
2459 };
2460
2461 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);