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