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