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