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