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