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