chiark / gitweb /
core: switch all log targets to go directly to the journal, instead via syslog
[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_journal(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                 [UNIT_PROPAGATE_RELOAD_TO] = UNIT_PROPAGATE_RELOAD_FROM,
1544                 [UNIT_PROPAGATE_RELOAD_FROM] = UNIT_PROPAGATE_RELOAD_TO
1545         };
1546         int r, q = 0, v = 0, w = 0;
1547
1548         assert(u);
1549         assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
1550         assert(other);
1551
1552         u = unit_follow_merge(u);
1553         other = unit_follow_merge(other);
1554
1555         /* We won't allow dependencies on ourselves. We will not
1556          * consider them an error however. */
1557         if (u == other)
1558                 return 0;
1559
1560         if ((r = set_ensure_allocated(&u->meta.dependencies[d], trivial_hash_func, trivial_compare_func)) < 0)
1561                 return r;
1562
1563         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1564                 if ((r = set_ensure_allocated(&other->meta.dependencies[inverse_table[d]], trivial_hash_func, trivial_compare_func)) < 0)
1565                         return r;
1566
1567         if (add_reference)
1568                 if ((r = set_ensure_allocated(&u->meta.dependencies[UNIT_REFERENCES], trivial_hash_func, trivial_compare_func)) < 0 ||
1569                     (r = set_ensure_allocated(&other->meta.dependencies[UNIT_REFERENCED_BY], trivial_hash_func, trivial_compare_func)) < 0)
1570                         return r;
1571
1572         if ((q = set_put(u->meta.dependencies[d], other)) < 0)
1573                 return q;
1574
1575         if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID)
1576                 if ((v = set_put(other->meta.dependencies[inverse_table[d]], u)) < 0) {
1577                         r = v;
1578                         goto fail;
1579                 }
1580
1581         if (add_reference) {
1582                 if ((w = set_put(u->meta.dependencies[UNIT_REFERENCES], other)) < 0) {
1583                         r = w;
1584                         goto fail;
1585                 }
1586
1587                 if ((r = set_put(other->meta.dependencies[UNIT_REFERENCED_BY], u)) < 0)
1588                         goto fail;
1589         }
1590
1591         unit_add_to_dbus_queue(u);
1592         return 0;
1593
1594 fail:
1595         if (q > 0)
1596                 set_remove(u->meta.dependencies[d], other);
1597
1598         if (v > 0)
1599                 set_remove(other->meta.dependencies[inverse_table[d]], u);
1600
1601         if (w > 0)
1602                 set_remove(u->meta.dependencies[UNIT_REFERENCES], other);
1603
1604         return r;
1605 }
1606
1607 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
1608         int r;
1609
1610         assert(u);
1611
1612         if ((r = unit_add_dependency(u, d, other, add_reference)) < 0)
1613                 return r;
1614
1615         if ((r = unit_add_dependency(u, e, other, add_reference)) < 0)
1616                 return r;
1617
1618         return 0;
1619 }
1620
1621 static const char *resolve_template(Unit *u, const char *name, const char*path, char **p) {
1622         char *s;
1623
1624         assert(u);
1625         assert(name || path);
1626
1627         if (!name)
1628                 name = file_name_from_path(path);
1629
1630         if (!unit_name_is_template(name)) {
1631                 *p = NULL;
1632                 return name;
1633         }
1634
1635         if (u->meta.instance)
1636                 s = unit_name_replace_instance(name, u->meta.instance);
1637         else {
1638                 char *i;
1639
1640                 if (!(i = unit_name_to_prefix(u->meta.id)))
1641                         return NULL;
1642
1643                 s = unit_name_replace_instance(name, i);
1644                 free(i);
1645         }
1646
1647         if (!s)
1648                 return NULL;
1649
1650         *p = s;
1651         return s;
1652 }
1653
1654 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1655         Unit *other;
1656         int r;
1657         char *s;
1658
1659         assert(u);
1660         assert(name || path);
1661
1662         if (!(name = resolve_template(u, name, path, &s)))
1663                 return -ENOMEM;
1664
1665         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1666                 goto finish;
1667
1668         r = unit_add_dependency(u, d, other, add_reference);
1669
1670 finish:
1671         free(s);
1672         return r;
1673 }
1674
1675 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1676         Unit *other;
1677         int r;
1678         char *s;
1679
1680         assert(u);
1681         assert(name || path);
1682
1683         if (!(name = resolve_template(u, name, path, &s)))
1684                 return -ENOMEM;
1685
1686         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1687                 goto finish;
1688
1689         r = unit_add_two_dependencies(u, d, e, other, add_reference);
1690
1691 finish:
1692         free(s);
1693         return r;
1694 }
1695
1696 int unit_add_dependency_by_name_inverse(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
1697         Unit *other;
1698         int r;
1699         char *s;
1700
1701         assert(u);
1702         assert(name || path);
1703
1704         if (!(name = resolve_template(u, name, path, &s)))
1705                 return -ENOMEM;
1706
1707         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1708                 goto finish;
1709
1710         r = unit_add_dependency(other, d, u, add_reference);
1711
1712 finish:
1713         free(s);
1714         return r;
1715 }
1716
1717 int unit_add_two_dependencies_by_name_inverse(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
1718         Unit *other;
1719         int r;
1720         char *s;
1721
1722         assert(u);
1723         assert(name || path);
1724
1725         if (!(name = resolve_template(u, name, path, &s)))
1726                 return -ENOMEM;
1727
1728         if ((r = manager_load_unit(u->meta.manager, name, path, NULL, &other)) < 0)
1729                 goto finish;
1730
1731         if ((r = unit_add_two_dependencies(other, d, e, u, add_reference)) < 0)
1732                 goto finish;
1733
1734 finish:
1735         free(s);
1736         return r;
1737 }
1738
1739 int set_unit_path(const char *p) {
1740         char *cwd, *c;
1741         int r;
1742
1743         /* This is mostly for debug purposes */
1744
1745         if (path_is_absolute(p)) {
1746                 if (!(c = strdup(p)))
1747                         return -ENOMEM;
1748         } else {
1749                 if (!(cwd = get_current_dir_name()))
1750                         return -errno;
1751
1752                 r = asprintf(&c, "%s/%s", cwd, p);
1753                 free(cwd);
1754
1755                 if (r < 0)
1756                         return -ENOMEM;
1757         }
1758
1759         if (setenv("SYSTEMD_UNIT_PATH", c, 0) < 0) {
1760                 r = -errno;
1761                 free(c);
1762                 return r;
1763         }
1764
1765         return 0;
1766 }
1767
1768 char *unit_dbus_path(Unit *u) {
1769         char *p, *e;
1770
1771         assert(u);
1772
1773         if (!u->meta.id)
1774                 return NULL;
1775
1776         if (!(e = bus_path_escape(u->meta.id)))
1777                 return NULL;
1778
1779         p = strappend("/org/freedesktop/systemd1/unit/", e);
1780         free(e);
1781
1782         return p;
1783 }
1784
1785 int unit_add_cgroup(Unit *u, CGroupBonding *b) {
1786         int r;
1787
1788         assert(u);
1789         assert(b);
1790
1791         assert(b->path);
1792
1793         if (!b->controller) {
1794                 if (!(b->controller = strdup(SYSTEMD_CGROUP_CONTROLLER)))
1795                         return -ENOMEM;
1796
1797                 b->ours = true;
1798         }
1799
1800         /* Ensure this hasn't been added yet */
1801         assert(!b->unit);
1802
1803         if (streq(b->controller, SYSTEMD_CGROUP_CONTROLLER)) {
1804                 CGroupBonding *l;
1805
1806                 l = hashmap_get(u->meta.manager->cgroup_bondings, b->path);
1807                 LIST_PREPEND(CGroupBonding, by_path, l, b);
1808
1809                 if ((r = hashmap_replace(u->meta.manager->cgroup_bondings, b->path, l)) < 0) {
1810                         LIST_REMOVE(CGroupBonding, by_path, l, b);
1811                         return r;
1812                 }
1813         }
1814
1815         LIST_PREPEND(CGroupBonding, by_unit, u->meta.cgroup_bondings, b);
1816         b->unit = u;
1817
1818         return 0;
1819 }
1820
1821 static char *default_cgroup_path(Unit *u) {
1822         char *p;
1823
1824         assert(u);
1825
1826         if (u->meta.instance) {
1827                 char *t;
1828
1829                 t = unit_name_template(u->meta.id);
1830                 if (!t)
1831                         return NULL;
1832
1833                 p = join(u->meta.manager->cgroup_hierarchy, "/", t, "/", u->meta.instance, NULL);
1834                 free(t);
1835         } else
1836                 p = join(u->meta.manager->cgroup_hierarchy, "/", u->meta.id, NULL);
1837
1838         return p;
1839 }
1840
1841 int unit_add_cgroup_from_text(Unit *u, const char *name) {
1842         char *controller = NULL, *path = NULL;
1843         CGroupBonding *b = NULL;
1844         bool ours = false;
1845         int r;
1846
1847         assert(u);
1848         assert(name);
1849
1850         if ((r = cg_split_spec(name, &controller, &path)) < 0)
1851                 return r;
1852
1853         if (!path) {
1854                 path = default_cgroup_path(u);
1855                 ours = true;
1856         }
1857
1858         if (!controller) {
1859                 controller = strdup(SYSTEMD_CGROUP_CONTROLLER);
1860                 ours = true;
1861         }
1862
1863         if (!path || !controller) {
1864                 free(path);
1865                 free(controller);
1866
1867                 return -ENOMEM;
1868         }
1869
1870         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller)) {
1871                 r = -EEXIST;
1872                 goto fail;
1873         }
1874
1875         if (!(b = new0(CGroupBonding, 1))) {
1876                 r = -ENOMEM;
1877                 goto fail;
1878         }
1879
1880         b->controller = controller;
1881         b->path = path;
1882         b->ours = ours;
1883         b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1884
1885         if ((r = unit_add_cgroup(u, b)) < 0)
1886                 goto fail;
1887
1888         return 0;
1889
1890 fail:
1891         free(path);
1892         free(controller);
1893         free(b);
1894
1895         return r;
1896 }
1897
1898 static int unit_add_one_default_cgroup(Unit *u, const char *controller) {
1899         CGroupBonding *b = NULL;
1900         int r = -ENOMEM;
1901
1902         assert(u);
1903
1904         if (!controller)
1905                 controller = SYSTEMD_CGROUP_CONTROLLER;
1906
1907         if (cgroup_bonding_find_list(u->meta.cgroup_bondings, controller))
1908                 return 0;
1909
1910         if (!(b = new0(CGroupBonding, 1)))
1911                 return -ENOMEM;
1912
1913         if (!(b->controller = strdup(controller)))
1914                 goto fail;
1915
1916         if (!(b->path = default_cgroup_path(u)))
1917                 goto fail;
1918
1919         b->ours = true;
1920         b->essential = streq(controller, SYSTEMD_CGROUP_CONTROLLER);
1921
1922         if ((r = unit_add_cgroup(u, b)) < 0)
1923                 goto fail;
1924
1925         return 0;
1926
1927 fail:
1928         free(b->path);
1929         free(b->controller);
1930         free(b);
1931
1932         return r;
1933 }
1934
1935 int unit_add_default_cgroups(Unit *u) {
1936         CGroupAttribute *a;
1937         char **c;
1938         int r;
1939
1940         assert(u);
1941
1942         /* Adds in the default cgroups, if they weren't specified
1943          * otherwise. */
1944
1945         if (!u->meta.manager->cgroup_hierarchy)
1946                 return 0;
1947
1948         if ((r = unit_add_one_default_cgroup(u, NULL)) < 0)
1949                 return r;
1950
1951         STRV_FOREACH(c, u->meta.manager->default_controllers)
1952                 unit_add_one_default_cgroup(u, *c);
1953
1954         LIST_FOREACH(by_unit, a, u->meta.cgroup_attributes)
1955                 unit_add_one_default_cgroup(u, a->controller);
1956
1957         return 0;
1958 }
1959
1960 CGroupBonding* unit_get_default_cgroup(Unit *u) {
1961         assert(u);
1962
1963         return cgroup_bonding_find_list(u->meta.cgroup_bondings, SYSTEMD_CGROUP_CONTROLLER);
1964 }
1965
1966 int unit_add_cgroup_attribute(Unit *u, const char *controller, const char *name, const char *value, CGroupAttributeMapCallback map_callback) {
1967         int r;
1968         char *c = NULL;
1969         CGroupAttribute *a;
1970
1971         assert(u);
1972         assert(name);
1973         assert(value);
1974
1975         if (!controller) {
1976                 const char *dot;
1977
1978                 dot = strchr(name, '.');
1979                 if (!dot)
1980                         return -EINVAL;
1981
1982                 c = strndup(name, dot - name);
1983                 if (!c)
1984                         return -ENOMEM;
1985
1986                 controller = c;
1987         }
1988
1989         if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
1990                 r = -EINVAL;
1991                 goto finish;
1992         }
1993
1994         a = new0(CGroupAttribute, 1);
1995         if (!a) {
1996                 r = -ENOMEM;
1997                 goto finish;
1998         }
1999
2000         if (c) {
2001                 a->controller = c;
2002                 c = NULL;
2003         } else
2004                 a->controller = strdup(controller);
2005
2006         a->name = strdup(name);
2007         a->value = strdup(value);
2008
2009         if (!a->controller || !a->name || !a->value) {
2010                 free(a->controller);
2011                 free(a->name);
2012                 free(a->value);
2013                 free(a);
2014
2015                 return -ENOMEM;
2016         }
2017
2018         a->map_callback = map_callback;
2019
2020         LIST_PREPEND(CGroupAttribute, by_unit, u->meta.cgroup_attributes, a);
2021
2022         r = 0;
2023
2024 finish:
2025         free(c);
2026         return r;
2027 }
2028
2029 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2030         char *t;
2031         int r;
2032
2033         assert(u);
2034         assert(type);
2035         assert(_found);
2036
2037         if (!(t = unit_name_change_suffix(u->meta.id, type)))
2038                 return -ENOMEM;
2039
2040         assert(!unit_has_name(u, t));
2041
2042         r = manager_load_unit(u->meta.manager, t, NULL, NULL, _found);
2043         free(t);
2044
2045         assert(r < 0 || *_found != u);
2046
2047         return r;
2048 }
2049
2050 int unit_get_related_unit(Unit *u, const char *type, Unit **_found) {
2051         Unit *found;
2052         char *t;
2053
2054         assert(u);
2055         assert(type);
2056         assert(_found);
2057
2058         if (!(t = unit_name_change_suffix(u->meta.id, type)))
2059                 return -ENOMEM;
2060
2061         assert(!unit_has_name(u, t));
2062
2063         found = manager_get_unit(u->meta.manager, t);
2064         free(t);
2065
2066         if (!found)
2067                 return -ENOENT;
2068
2069         *_found = found;
2070         return 0;
2071 }
2072
2073 static char *specifier_prefix_and_instance(char specifier, void *data, void *userdata) {
2074         Unit *u = userdata;
2075         assert(u);
2076
2077         return unit_name_to_prefix_and_instance(u->meta.id);
2078 }
2079
2080 static char *specifier_prefix(char specifier, void *data, void *userdata) {
2081         Unit *u = userdata;
2082         assert(u);
2083
2084         return unit_name_to_prefix(u->meta.id);
2085 }
2086
2087 static char *specifier_prefix_unescaped(char specifier, void *data, void *userdata) {
2088         Unit *u = userdata;
2089         char *p, *r;
2090
2091         assert(u);
2092
2093         if (!(p = unit_name_to_prefix(u->meta.id)))
2094                 return NULL;
2095
2096         r = unit_name_unescape(p);
2097         free(p);
2098
2099         return r;
2100 }
2101
2102 static char *specifier_instance_unescaped(char specifier, void *data, void *userdata) {
2103         Unit *u = userdata;
2104         assert(u);
2105
2106         if (u->meta.instance)
2107                 return unit_name_unescape(u->meta.instance);
2108
2109         return strdup("");
2110 }
2111
2112 static char *specifier_filename(char specifier, void *data, void *userdata) {
2113         Unit *u = userdata;
2114         assert(u);
2115
2116         if (u->meta.instance)
2117                 return unit_name_path_unescape(u->meta.instance);
2118
2119         return unit_name_to_path(u->meta.instance);
2120 }
2121
2122 static char *specifier_cgroup(char specifier, void *data, void *userdata) {
2123         Unit *u = userdata;
2124         assert(u);
2125
2126         return default_cgroup_path(u);
2127 }
2128
2129 static char *specifier_cgroup_root(char specifier, void *data, void *userdata) {
2130         Unit *u = userdata;
2131         char *p;
2132         assert(u);
2133
2134         if (specifier == 'r')
2135                 return strdup(u->meta.manager->cgroup_hierarchy);
2136
2137         if (parent_of_path(u->meta.manager->cgroup_hierarchy, &p) < 0)
2138                 return strdup("");
2139
2140         if (streq(p, "/")) {
2141                 free(p);
2142                 return strdup("");
2143         }
2144
2145         return p;
2146 }
2147
2148 static char *specifier_runtime(char specifier, void *data, void *userdata) {
2149         Unit *u = userdata;
2150         assert(u);
2151
2152         if (u->meta.manager->running_as == MANAGER_USER) {
2153                 const char *e;
2154
2155                 e = getenv("XDG_RUNTIME_DIR");
2156                 if (e)
2157                         return strdup(e);
2158         }
2159
2160         return strdup("/run");
2161 }
2162
2163 char *unit_name_printf(Unit *u, const char* format) {
2164
2165         /*
2166          * This will use the passed string as format string and
2167          * replace the following specifiers:
2168          *
2169          * %n: the full id of the unit                 (foo@bar.waldo)
2170          * %N: the id of the unit without the suffix   (foo@bar)
2171          * %p: the prefix                              (foo)
2172          * %i: the instance                            (bar)
2173          */
2174
2175         const Specifier table[] = {
2176                 { 'n', specifier_string,              u->meta.id },
2177                 { 'N', specifier_prefix_and_instance, NULL },
2178                 { 'p', specifier_prefix,              NULL },
2179                 { 'i', specifier_string,              u->meta.instance },
2180                 { 0, NULL, NULL }
2181         };
2182
2183         assert(u);
2184         assert(format);
2185
2186         return specifier_printf(format, table, u);
2187 }
2188
2189 char *unit_full_printf(Unit *u, const char *format) {
2190
2191         /* This is similar to unit_name_printf() but also supports
2192          * unescaping. Also, adds a couple of additional codes:
2193          *
2194          * %c cgroup path of unit
2195          * %r root cgroup path of this systemd instance (e.g. "/user/lennart/shared/systemd-4711")
2196          * %R parent of root cgroup path (e.g. "/usr/lennart/shared")
2197          * %t the runtime directory to place sockets in (e.g. "/run" or $XDG_RUNTIME_DIR)
2198          */
2199
2200         const Specifier table[] = {
2201                 { 'n', specifier_string,              u->meta.id },
2202                 { 'N', specifier_prefix_and_instance, NULL },
2203                 { 'p', specifier_prefix,              NULL },
2204                 { 'P', specifier_prefix_unescaped,    NULL },
2205                 { 'i', specifier_string,              u->meta.instance },
2206                 { 'I', specifier_instance_unescaped,  NULL },
2207                 { 'f', specifier_filename,            NULL },
2208                 { 'c', specifier_cgroup,              NULL },
2209                 { 'r', specifier_cgroup_root,         NULL },
2210                 { 'R', specifier_cgroup_root,         NULL },
2211                 { 't', specifier_runtime,             NULL },
2212                 { 0, NULL, NULL }
2213         };
2214
2215         assert(u);
2216         assert(format);
2217
2218         return specifier_printf(format, table, u);
2219 }
2220
2221 char **unit_full_printf_strv(Unit *u, char **l) {
2222         size_t n;
2223         char **r, **i, **j;
2224
2225         /* Applies unit_full_printf to every entry in l */
2226
2227         assert(u);
2228
2229         n = strv_length(l);
2230         if (!(r = new(char*, n+1)))
2231                 return NULL;
2232
2233         for (i = l, j = r; *i; i++, j++)
2234                 if (!(*j = unit_full_printf(u, *i)))
2235                         goto fail;
2236
2237         *j = NULL;
2238         return r;
2239
2240 fail:
2241         for (j--; j >= r; j--)
2242                 free(*j);
2243
2244         free(r);
2245
2246         return NULL;
2247 }
2248
2249 int unit_watch_bus_name(Unit *u, const char *name) {
2250         assert(u);
2251         assert(name);
2252
2253         /* Watch a specific name on the bus. We only support one unit
2254          * watching each name for now. */
2255
2256         return hashmap_put(u->meta.manager->watch_bus, name, u);
2257 }
2258
2259 void unit_unwatch_bus_name(Unit *u, const char *name) {
2260         assert(u);
2261         assert(name);
2262
2263         hashmap_remove_value(u->meta.manager->watch_bus, name, u);
2264 }
2265
2266 bool unit_can_serialize(Unit *u) {
2267         assert(u);
2268
2269         return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2270 }
2271
2272 int unit_serialize(Unit *u, FILE *f, FDSet *fds) {
2273         int r;
2274
2275         assert(u);
2276         assert(f);
2277         assert(fds);
2278
2279         if (!unit_can_serialize(u))
2280                 return 0;
2281
2282         if ((r = UNIT_VTABLE(u)->serialize(u, f, fds)) < 0)
2283                 return r;
2284
2285         if (u->meta.job)
2286                 unit_serialize_item(u, f, "job", job_type_to_string(u->meta.job->type));
2287
2288         dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->meta.inactive_exit_timestamp);
2289         dual_timestamp_serialize(f, "active-enter-timestamp", &u->meta.active_enter_timestamp);
2290         dual_timestamp_serialize(f, "active-exit-timestamp", &u->meta.active_exit_timestamp);
2291         dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->meta.inactive_enter_timestamp);
2292         dual_timestamp_serialize(f, "condition-timestamp", &u->meta.condition_timestamp);
2293
2294         if (dual_timestamp_is_set(&u->meta.condition_timestamp))
2295                 unit_serialize_item(u, f, "condition-result", yes_no(u->meta.condition_result));
2296
2297         /* End marker */
2298         fputc('\n', f);
2299         return 0;
2300 }
2301
2302 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2303         va_list ap;
2304
2305         assert(u);
2306         assert(f);
2307         assert(key);
2308         assert(format);
2309
2310         fputs(key, f);
2311         fputc('=', f);
2312
2313         va_start(ap, format);
2314         vfprintf(f, format, ap);
2315         va_end(ap);
2316
2317         fputc('\n', f);
2318 }
2319
2320 void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2321         assert(u);
2322         assert(f);
2323         assert(key);
2324         assert(value);
2325
2326         fprintf(f, "%s=%s\n", key, value);
2327 }
2328
2329 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2330         int r;
2331
2332         assert(u);
2333         assert(f);
2334         assert(fds);
2335
2336         if (!unit_can_serialize(u))
2337                 return 0;
2338
2339         for (;;) {
2340                 char line[LINE_MAX], *l, *v;
2341                 size_t k;
2342
2343                 if (!fgets(line, sizeof(line), f)) {
2344                         if (feof(f))
2345                                 return 0;
2346                         return -errno;
2347                 }
2348
2349                 char_array_0(line);
2350                 l = strstrip(line);
2351
2352                 /* End marker */
2353                 if (l[0] == 0)
2354                         return 0;
2355
2356                 k = strcspn(l, "=");
2357
2358                 if (l[k] == '=') {
2359                         l[k] = 0;
2360                         v = l+k+1;
2361                 } else
2362                         v = l+k;
2363
2364                 if (streq(l, "job")) {
2365                         JobType type;
2366
2367                         if ((type = job_type_from_string(v)) < 0)
2368                                 log_debug("Failed to parse job type value %s", v);
2369                         else
2370                                 u->meta.deserialized_job = type;
2371
2372                         continue;
2373                 } else if (streq(l, "inactive-exit-timestamp")) {
2374                         dual_timestamp_deserialize(v, &u->meta.inactive_exit_timestamp);
2375                         continue;
2376                 } else if (streq(l, "active-enter-timestamp")) {
2377                         dual_timestamp_deserialize(v, &u->meta.active_enter_timestamp);
2378                         continue;
2379                 } else if (streq(l, "active-exit-timestamp")) {
2380                         dual_timestamp_deserialize(v, &u->meta.active_exit_timestamp);
2381                         continue;
2382                 } else if (streq(l, "inactive-enter-timestamp")) {
2383                         dual_timestamp_deserialize(v, &u->meta.inactive_enter_timestamp);
2384                         continue;
2385                 } else if (streq(l, "condition-timestamp")) {
2386                         dual_timestamp_deserialize(v, &u->meta.condition_timestamp);
2387                         continue;
2388                 } else if (streq(l, "condition-result")) {
2389                         int b;
2390
2391                         if ((b = parse_boolean(v)) < 0)
2392                                 log_debug("Failed to parse condition result value %s", v);
2393                         else
2394                                 u->meta.condition_result = b;
2395
2396                         continue;
2397                 }
2398
2399                 if ((r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds)) < 0)
2400                         return r;
2401         }
2402 }
2403
2404 int unit_add_node_link(Unit *u, const char *what, bool wants) {
2405         Unit *device;
2406         char *e;
2407         int r;
2408
2409         assert(u);
2410
2411         if (!what)
2412                 return 0;
2413
2414         /* Adds in links to the device node that this unit is based on */
2415
2416         if (!is_device_path(what))
2417                 return 0;
2418
2419         if (!(e = unit_name_build_escape(what+1, NULL, ".device")))
2420                 return -ENOMEM;
2421
2422         r = manager_load_unit(u->meta.manager, e, NULL, NULL, &device);
2423         free(e);
2424
2425         if (r < 0)
2426                 return r;
2427
2428         if ((r = unit_add_two_dependencies(u, UNIT_AFTER, UNIT_BIND_TO, device, true)) < 0)
2429                 return r;
2430
2431         if (wants)
2432                 if ((r = unit_add_dependency(device, UNIT_WANTS, u, false)) < 0)
2433                         return r;
2434
2435         return 0;
2436 }
2437
2438 int unit_coldplug(Unit *u) {
2439         int r;
2440
2441         assert(u);
2442
2443         if (UNIT_VTABLE(u)->coldplug)
2444                 if ((r = UNIT_VTABLE(u)->coldplug(u)) < 0)
2445                         return r;
2446
2447         if (u->meta.deserialized_job >= 0) {
2448                 if ((r = manager_add_job(u->meta.manager, u->meta.deserialized_job, u, JOB_IGNORE_REQUIREMENTS, false, NULL, NULL)) < 0)
2449                         return r;
2450
2451                 u->meta.deserialized_job = _JOB_TYPE_INVALID;
2452         }
2453
2454         return 0;
2455 }
2456
2457 void unit_status_printf(Unit *u, const char *status, const char *format, ...) {
2458         va_list ap;
2459
2460         assert(u);
2461         assert(format);
2462
2463         if (!UNIT_VTABLE(u)->show_status)
2464                 return;
2465
2466         if (!manager_get_show_status(u->meta.manager))
2467                 return;
2468
2469         if (!manager_is_booting_or_shutting_down(u->meta.manager))
2470                 return;
2471
2472         va_start(ap, format);
2473         status_vprintf(status, true, format, ap);
2474         va_end(ap);
2475 }
2476
2477 bool unit_need_daemon_reload(Unit *u) {
2478         assert(u);
2479
2480         if (u->meta.fragment_path) {
2481                 struct stat st;
2482
2483                 zero(st);
2484                 if (stat(u->meta.fragment_path, &st) < 0)
2485                         /* What, cannot access this anymore? */
2486                         return true;
2487
2488                 if (u->meta.fragment_mtime > 0 &&
2489                     timespec_load(&st.st_mtim) != u->meta.fragment_mtime)
2490                         return true;
2491         }
2492
2493         if (UNIT_VTABLE(u)->need_daemon_reload)
2494                 return UNIT_VTABLE(u)->need_daemon_reload(u);
2495
2496         return false;
2497 }
2498
2499 void unit_reset_failed(Unit *u) {
2500         assert(u);
2501
2502         if (UNIT_VTABLE(u)->reset_failed)
2503                 UNIT_VTABLE(u)->reset_failed(u);
2504 }
2505
2506 Unit *unit_following(Unit *u) {
2507         assert(u);
2508
2509         if (UNIT_VTABLE(u)->following)
2510                 return UNIT_VTABLE(u)->following(u);
2511
2512         return NULL;
2513 }
2514
2515 bool unit_pending_inactive(Unit *u) {
2516         assert(u);
2517
2518         /* Returns true if the unit is inactive or going down */
2519
2520         if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
2521                 return true;
2522
2523         if (u->meta.job && u->meta.job->type == JOB_STOP)
2524                 return true;
2525
2526         return false;
2527 }
2528
2529 bool unit_pending_active(Unit *u) {
2530         assert(u);
2531
2532         /* Returns true if the unit is active or going up */
2533
2534         if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
2535                 return true;
2536
2537         if (u->meta.job &&
2538             (u->meta.job->type == JOB_START ||
2539              u->meta.job->type == JOB_RELOAD_OR_START ||
2540              u->meta.job->type == JOB_RESTART))
2541                 return true;
2542
2543         return false;
2544 }
2545
2546 UnitType unit_name_to_type(const char *n) {
2547         UnitType t;
2548
2549         assert(n);
2550
2551         for (t = 0; t < _UNIT_TYPE_MAX; t++)
2552                 if (endswith(n, unit_vtable[t]->suffix))
2553                         return t;
2554
2555         return _UNIT_TYPE_INVALID;
2556 }
2557
2558 bool unit_name_is_valid(const char *n, bool template_ok) {
2559         UnitType t;
2560
2561         t = unit_name_to_type(n);
2562         if (t < 0 || t >= _UNIT_TYPE_MAX)
2563                 return false;
2564
2565         return unit_name_is_valid_no_type(n, template_ok);
2566 }
2567
2568 int unit_kill(Unit *u, KillWho w, KillMode m, int signo, DBusError *error) {
2569         assert(u);
2570         assert(w >= 0 && w < _KILL_WHO_MAX);
2571         assert(m >= 0 && m < _KILL_MODE_MAX);
2572         assert(signo > 0);
2573         assert(signo < _NSIG);
2574
2575         if (m == KILL_NONE)
2576                 return 0;
2577
2578         if (!UNIT_VTABLE(u)->kill)
2579                 return -ENOTSUP;
2580
2581         return UNIT_VTABLE(u)->kill(u, w, m, signo, error);
2582 }
2583
2584 int unit_following_set(Unit *u, Set **s) {
2585         assert(u);
2586         assert(s);
2587
2588         if (UNIT_VTABLE(u)->following_set)
2589                 return UNIT_VTABLE(u)->following_set(u, s);
2590
2591         *s = NULL;
2592         return 0;
2593 }
2594
2595 UnitFileState unit_get_unit_file_state(Unit *u) {
2596         assert(u);
2597
2598         if (u->meta.unit_file_state < 0 && u->meta.fragment_path)
2599                 u->meta.unit_file_state = unit_file_get_state(
2600                                 u->meta.manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2601                                 NULL, file_name_from_path(u->meta.fragment_path));
2602
2603         return u->meta.unit_file_state;
2604 }
2605
2606 Unit* unit_ref_set(UnitRef *ref, Unit *u) {
2607         assert(ref);
2608         assert(u);
2609
2610         if (ref->unit)
2611                 unit_ref_unset(ref);
2612
2613         ref->unit = u;
2614         LIST_PREPEND(UnitRef, refs, u->meta.refs, ref);
2615         return u;
2616 }
2617
2618 void unit_ref_unset(UnitRef *ref) {
2619         assert(ref);
2620
2621         if (!ref->unit)
2622                 return;
2623
2624         LIST_REMOVE(UnitRef, refs, ref->unit->meta.refs, ref);
2625         ref->unit = NULL;
2626 }
2627
2628 static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = {
2629         [UNIT_STUB] = "stub",
2630         [UNIT_LOADED] = "loaded",
2631         [UNIT_ERROR] = "error",
2632         [UNIT_MERGED] = "merged",
2633         [UNIT_MASKED] = "masked"
2634 };
2635
2636 DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState);
2637
2638 static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = {
2639         [UNIT_ACTIVE] = "active",
2640         [UNIT_RELOADING] = "reloading",
2641         [UNIT_INACTIVE] = "inactive",
2642         [UNIT_FAILED] = "failed",
2643         [UNIT_ACTIVATING] = "activating",
2644         [UNIT_DEACTIVATING] = "deactivating"
2645 };
2646
2647 DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState);
2648
2649 static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = {
2650         [UNIT_REQUIRES] = "Requires",
2651         [UNIT_REQUIRES_OVERRIDABLE] = "RequiresOverridable",
2652         [UNIT_WANTS] = "Wants",
2653         [UNIT_REQUISITE] = "Requisite",
2654         [UNIT_REQUISITE_OVERRIDABLE] = "RequisiteOverridable",
2655         [UNIT_REQUIRED_BY] = "RequiredBy",
2656         [UNIT_REQUIRED_BY_OVERRIDABLE] = "RequiredByOverridable",
2657         [UNIT_BIND_TO] = "BindTo",
2658         [UNIT_WANTED_BY] = "WantedBy",
2659         [UNIT_CONFLICTS] = "Conflicts",
2660         [UNIT_CONFLICTED_BY] = "ConflictedBy",
2661         [UNIT_BOUND_BY] = "BoundBy",
2662         [UNIT_BEFORE] = "Before",
2663         [UNIT_AFTER] = "After",
2664         [UNIT_REFERENCES] = "References",
2665         [UNIT_REFERENCED_BY] = "ReferencedBy",
2666         [UNIT_ON_FAILURE] = "OnFailure",
2667         [UNIT_TRIGGERS] = "Triggers",
2668         [UNIT_TRIGGERED_BY] = "TriggeredBy",
2669         [UNIT_PROPAGATE_RELOAD_TO] = "PropagateReloadTo",
2670         [UNIT_PROPAGATE_RELOAD_FROM] = "PropagateReloadFrom"
2671 };
2672
2673 DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency);