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