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