]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/unit.c
Do not report masked units as changed (#2921)
[thirdparty/systemd.git] / src / core / unit.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25
26 #include "sd-id128.h"
27 #include "sd-messages.h"
28
29 #include "alloc-util.h"
30 #include "bus-common-errors.h"
31 #include "bus-util.h"
32 #include "cgroup-util.h"
33 #include "dbus-unit.h"
34 #include "dbus.h"
35 #include "dropin.h"
36 #include "escape.h"
37 #include "execute.h"
38 #include "fileio-label.h"
39 #include "formats-util.h"
40 #include "load-dropin.h"
41 #include "load-fragment.h"
42 #include "log.h"
43 #include "macro.h"
44 #include "missing.h"
45 #include "mkdir.h"
46 #include "parse-util.h"
47 #include "path-util.h"
48 #include "process-util.h"
49 #include "set.h"
50 #include "special.h"
51 #include "stat-util.h"
52 #include "stdio-util.h"
53 #include "string-util.h"
54 #include "strv.h"
55 #include "unit-name.h"
56 #include "unit.h"
57 #include "user-util.h"
58 #include "virt.h"
59
60 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
61 [UNIT_SERVICE] = &service_vtable,
62 [UNIT_SOCKET] = &socket_vtable,
63 [UNIT_BUSNAME] = &busname_vtable,
64 [UNIT_TARGET] = &target_vtable,
65 [UNIT_DEVICE] = &device_vtable,
66 [UNIT_MOUNT] = &mount_vtable,
67 [UNIT_AUTOMOUNT] = &automount_vtable,
68 [UNIT_SWAP] = &swap_vtable,
69 [UNIT_TIMER] = &timer_vtable,
70 [UNIT_PATH] = &path_vtable,
71 [UNIT_SLICE] = &slice_vtable,
72 [UNIT_SCOPE] = &scope_vtable
73 };
74
75 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
76
77 Unit *unit_new(Manager *m, size_t size) {
78 Unit *u;
79
80 assert(m);
81 assert(size >= sizeof(Unit));
82
83 u = malloc0(size);
84 if (!u)
85 return NULL;
86
87 u->names = set_new(&string_hash_ops);
88 if (!u->names) {
89 free(u);
90 return NULL;
91 }
92
93 u->manager = m;
94 u->type = _UNIT_TYPE_INVALID;
95 u->default_dependencies = true;
96 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
97 u->unit_file_preset = -1;
98 u->on_failure_job_mode = JOB_REPLACE;
99 u->cgroup_inotify_wd = -1;
100 u->job_timeout = USEC_INFINITY;
101
102 RATELIMIT_INIT(u->start_limit, m->default_start_limit_interval, m->default_start_limit_burst);
103 RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16);
104
105 return u;
106 }
107
108 bool unit_has_name(Unit *u, const char *name) {
109 assert(u);
110 assert(name);
111
112 return !!set_get(u->names, (char*) name);
113 }
114
115 static void unit_init(Unit *u) {
116 CGroupContext *cc;
117 ExecContext *ec;
118 KillContext *kc;
119
120 assert(u);
121 assert(u->manager);
122 assert(u->type >= 0);
123
124 cc = unit_get_cgroup_context(u);
125 if (cc) {
126 cgroup_context_init(cc);
127
128 /* Copy in the manager defaults into the cgroup
129 * context, _before_ the rest of the settings have
130 * been initialized */
131
132 cc->cpu_accounting = u->manager->default_cpu_accounting;
133 cc->blockio_accounting = u->manager->default_blockio_accounting;
134 cc->memory_accounting = u->manager->default_memory_accounting;
135 cc->tasks_accounting = u->manager->default_tasks_accounting;
136
137 if (u->type != UNIT_SLICE)
138 cc->tasks_max = u->manager->default_tasks_max;
139 }
140
141 ec = unit_get_exec_context(u);
142 if (ec)
143 exec_context_init(ec);
144
145 kc = unit_get_kill_context(u);
146 if (kc)
147 kill_context_init(kc);
148
149 if (UNIT_VTABLE(u)->init)
150 UNIT_VTABLE(u)->init(u);
151 }
152
153 int unit_add_name(Unit *u, const char *text) {
154 _cleanup_free_ char *s = NULL, *i = NULL;
155 UnitType t;
156 int r;
157
158 assert(u);
159 assert(text);
160
161 if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
162
163 if (!u->instance)
164 return -EINVAL;
165
166 r = unit_name_replace_instance(text, u->instance, &s);
167 if (r < 0)
168 return r;
169 } else {
170 s = strdup(text);
171 if (!s)
172 return -ENOMEM;
173 }
174
175 if (set_contains(u->names, s))
176 return 0;
177 if (hashmap_contains(u->manager->units, s))
178 return -EEXIST;
179
180 if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
181 return -EINVAL;
182
183 t = unit_name_to_type(s);
184 if (t < 0)
185 return -EINVAL;
186
187 if (u->type != _UNIT_TYPE_INVALID && t != u->type)
188 return -EINVAL;
189
190 r = unit_name_to_instance(s, &i);
191 if (r < 0)
192 return r;
193
194 if (i && unit_vtable[t]->no_instances)
195 return -EINVAL;
196
197 /* Ensure that this unit is either instanced or not instanced,
198 * but not both. Note that we do allow names with different
199 * instance names however! */
200 if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i)
201 return -EINVAL;
202
203 if (unit_vtable[t]->no_alias && !set_isempty(u->names))
204 return -EEXIST;
205
206 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
207 return -E2BIG;
208
209 r = set_put(u->names, s);
210 if (r < 0)
211 return r;
212 assert(r > 0);
213
214 r = hashmap_put(u->manager->units, s, u);
215 if (r < 0) {
216 (void) set_remove(u->names, s);
217 return r;
218 }
219
220 if (u->type == _UNIT_TYPE_INVALID) {
221 u->type = t;
222 u->id = s;
223 u->instance = i;
224
225 LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
226
227 unit_init(u);
228
229 i = NULL;
230 }
231
232 s = NULL;
233
234 unit_add_to_dbus_queue(u);
235 return 0;
236 }
237
238 int unit_choose_id(Unit *u, const char *name) {
239 _cleanup_free_ char *t = NULL;
240 char *s, *i;
241 int r;
242
243 assert(u);
244 assert(name);
245
246 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
247
248 if (!u->instance)
249 return -EINVAL;
250
251 r = unit_name_replace_instance(name, u->instance, &t);
252 if (r < 0)
253 return r;
254
255 name = t;
256 }
257
258 /* Selects one of the names of this unit as the id */
259 s = set_get(u->names, (char*) name);
260 if (!s)
261 return -ENOENT;
262
263 /* Determine the new instance from the new id */
264 r = unit_name_to_instance(s, &i);
265 if (r < 0)
266 return r;
267
268 u->id = s;
269
270 free(u->instance);
271 u->instance = i;
272
273 unit_add_to_dbus_queue(u);
274
275 return 0;
276 }
277
278 int unit_set_description(Unit *u, const char *description) {
279 char *s;
280
281 assert(u);
282
283 if (isempty(description))
284 s = NULL;
285 else {
286 s = strdup(description);
287 if (!s)
288 return -ENOMEM;
289 }
290
291 free(u->description);
292 u->description = s;
293
294 unit_add_to_dbus_queue(u);
295 return 0;
296 }
297
298 bool unit_check_gc(Unit *u) {
299 UnitActiveState state;
300 assert(u);
301
302 if (u->job)
303 return true;
304
305 if (u->nop_job)
306 return true;
307
308 state = unit_active_state(u);
309
310 /* If the unit is inactive and failed and no job is queued for
311 * it, then release its runtime resources */
312 if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
313 UNIT_VTABLE(u)->release_resources)
314 UNIT_VTABLE(u)->release_resources(u);
315
316 /* But we keep the unit object around for longer when it is
317 * referenced or configured to not be gc'ed */
318 if (state != UNIT_INACTIVE)
319 return true;
320
321 if (u->no_gc)
322 return true;
323
324 if (u->refs)
325 return true;
326
327 if (UNIT_VTABLE(u)->check_gc)
328 if (UNIT_VTABLE(u)->check_gc(u))
329 return true;
330
331 return false;
332 }
333
334 void unit_add_to_load_queue(Unit *u) {
335 assert(u);
336 assert(u->type != _UNIT_TYPE_INVALID);
337
338 if (u->load_state != UNIT_STUB || u->in_load_queue)
339 return;
340
341 LIST_PREPEND(load_queue, u->manager->load_queue, u);
342 u->in_load_queue = true;
343 }
344
345 void unit_add_to_cleanup_queue(Unit *u) {
346 assert(u);
347
348 if (u->in_cleanup_queue)
349 return;
350
351 LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
352 u->in_cleanup_queue = true;
353 }
354
355 void unit_add_to_gc_queue(Unit *u) {
356 assert(u);
357
358 if (u->in_gc_queue || u->in_cleanup_queue)
359 return;
360
361 if (unit_check_gc(u))
362 return;
363
364 LIST_PREPEND(gc_queue, u->manager->gc_queue, u);
365 u->in_gc_queue = true;
366
367 u->manager->n_in_gc_queue++;
368 }
369
370 void unit_add_to_dbus_queue(Unit *u) {
371 assert(u);
372 assert(u->type != _UNIT_TYPE_INVALID);
373
374 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
375 return;
376
377 /* Shortcut things if nobody cares */
378 if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
379 set_isempty(u->manager->private_buses)) {
380 u->sent_dbus_new_signal = true;
381 return;
382 }
383
384 LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
385 u->in_dbus_queue = true;
386 }
387
388 static void bidi_set_free(Unit *u, Set *s) {
389 Iterator i;
390 Unit *other;
391
392 assert(u);
393
394 /* Frees the set and makes sure we are dropped from the
395 * inverse pointers */
396
397 SET_FOREACH(other, s, i) {
398 UnitDependency d;
399
400 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
401 set_remove(other->dependencies[d], u);
402
403 unit_add_to_gc_queue(other);
404 }
405
406 set_free(s);
407 }
408
409 static void unit_remove_transient(Unit *u) {
410 char **i;
411
412 assert(u);
413
414 if (!u->transient)
415 return;
416
417 if (u->fragment_path)
418 (void) unlink(u->fragment_path);
419
420 STRV_FOREACH(i, u->dropin_paths) {
421 _cleanup_free_ char *p = NULL;
422
423 (void) unlink(*i);
424
425 p = dirname_malloc(*i);
426 if (p)
427 (void) rmdir(p);
428 }
429 }
430
431 static void unit_free_requires_mounts_for(Unit *u) {
432 char **j;
433
434 STRV_FOREACH(j, u->requires_mounts_for) {
435 char s[strlen(*j) + 1];
436
437 PATH_FOREACH_PREFIX_MORE(s, *j) {
438 char *y;
439 Set *x;
440
441 x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
442 if (!x)
443 continue;
444
445 set_remove(x, u);
446
447 if (set_isempty(x)) {
448 hashmap_remove(u->manager->units_requiring_mounts_for, y);
449 free(y);
450 set_free(x);
451 }
452 }
453 }
454
455 u->requires_mounts_for = strv_free(u->requires_mounts_for);
456 }
457
458 static void unit_done(Unit *u) {
459 ExecContext *ec;
460 CGroupContext *cc;
461
462 assert(u);
463
464 if (u->type < 0)
465 return;
466
467 if (UNIT_VTABLE(u)->done)
468 UNIT_VTABLE(u)->done(u);
469
470 ec = unit_get_exec_context(u);
471 if (ec)
472 exec_context_done(ec);
473
474 cc = unit_get_cgroup_context(u);
475 if (cc)
476 cgroup_context_done(cc);
477 }
478
479 void unit_free(Unit *u) {
480 UnitDependency d;
481 Iterator i;
482 char *t;
483
484 assert(u);
485
486 if (u->manager->n_reloading <= 0)
487 unit_remove_transient(u);
488
489 bus_unit_send_removed_signal(u);
490
491 unit_done(u);
492
493 sd_bus_slot_unref(u->match_bus_slot);
494
495 unit_free_requires_mounts_for(u);
496
497 SET_FOREACH(t, u->names, i)
498 hashmap_remove_value(u->manager->units, t, u);
499
500 if (u->job) {
501 Job *j = u->job;
502 job_uninstall(j);
503 job_free(j);
504 }
505
506 if (u->nop_job) {
507 Job *j = u->nop_job;
508 job_uninstall(j);
509 job_free(j);
510 }
511
512 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
513 bidi_set_free(u, u->dependencies[d]);
514
515 if (u->type != _UNIT_TYPE_INVALID)
516 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
517
518 if (u->in_load_queue)
519 LIST_REMOVE(load_queue, u->manager->load_queue, u);
520
521 if (u->in_dbus_queue)
522 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
523
524 if (u->in_cleanup_queue)
525 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
526
527 if (u->in_gc_queue) {
528 LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
529 u->manager->n_in_gc_queue--;
530 }
531
532 if (u->in_cgroup_queue)
533 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
534
535 unit_release_cgroup(u);
536
537 (void) manager_update_failed_units(u->manager, u, false);
538 set_remove(u->manager->startup_units, u);
539
540 free(u->description);
541 strv_free(u->documentation);
542 free(u->fragment_path);
543 free(u->source_path);
544 strv_free(u->dropin_paths);
545 free(u->instance);
546
547 free(u->job_timeout_reboot_arg);
548
549 set_free_free(u->names);
550
551 unit_unwatch_all_pids(u);
552
553 condition_free_list(u->conditions);
554 condition_free_list(u->asserts);
555
556 free(u->reboot_arg);
557
558 unit_ref_unset(&u->slice);
559
560 while (u->refs)
561 unit_ref_unset(u->refs);
562
563 free(u);
564 }
565
566 UnitActiveState unit_active_state(Unit *u) {
567 assert(u);
568
569 if (u->load_state == UNIT_MERGED)
570 return unit_active_state(unit_follow_merge(u));
571
572 /* After a reload it might happen that a unit is not correctly
573 * loaded but still has a process around. That's why we won't
574 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
575
576 return UNIT_VTABLE(u)->active_state(u);
577 }
578
579 const char* unit_sub_state_to_string(Unit *u) {
580 assert(u);
581
582 return UNIT_VTABLE(u)->sub_state_to_string(u);
583 }
584
585 static int complete_move(Set **s, Set **other) {
586 int r;
587
588 assert(s);
589 assert(other);
590
591 if (!*other)
592 return 0;
593
594 if (*s) {
595 r = set_move(*s, *other);
596 if (r < 0)
597 return r;
598 } else {
599 *s = *other;
600 *other = NULL;
601 }
602
603 return 0;
604 }
605
606 static int merge_names(Unit *u, Unit *other) {
607 char *t;
608 Iterator i;
609 int r;
610
611 assert(u);
612 assert(other);
613
614 r = complete_move(&u->names, &other->names);
615 if (r < 0)
616 return r;
617
618 set_free_free(other->names);
619 other->names = NULL;
620 other->id = NULL;
621
622 SET_FOREACH(t, u->names, i)
623 assert_se(hashmap_replace(u->manager->units, t, u) == 0);
624
625 return 0;
626 }
627
628 static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
629 unsigned n_reserve;
630
631 assert(u);
632 assert(other);
633 assert(d < _UNIT_DEPENDENCY_MAX);
634
635 /*
636 * If u does not have this dependency set allocated, there is no need
637 * to reserve anything. In that case other's set will be transferred
638 * as a whole to u by complete_move().
639 */
640 if (!u->dependencies[d])
641 return 0;
642
643 /* merge_dependencies() will skip a u-on-u dependency */
644 n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
645
646 return set_reserve(u->dependencies[d], n_reserve);
647 }
648
649 static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
650 Iterator i;
651 Unit *back;
652 int r;
653
654 assert(u);
655 assert(other);
656 assert(d < _UNIT_DEPENDENCY_MAX);
657
658 /* Fix backwards pointers */
659 SET_FOREACH(back, other->dependencies[d], i) {
660 UnitDependency k;
661
662 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
663 /* Do not add dependencies between u and itself */
664 if (back == u) {
665 if (set_remove(back->dependencies[k], other))
666 maybe_warn_about_dependency(u, other_id, k);
667 } else {
668 r = set_remove_and_put(back->dependencies[k], other, u);
669 if (r == -EEXIST)
670 set_remove(back->dependencies[k], other);
671 else
672 assert(r >= 0 || r == -ENOENT);
673 }
674 }
675 }
676
677 /* Also do not move dependencies on u to itself */
678 back = set_remove(other->dependencies[d], u);
679 if (back)
680 maybe_warn_about_dependency(u, other_id, d);
681
682 /* The move cannot fail. The caller must have performed a reservation. */
683 assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
684
685 other->dependencies[d] = set_free(other->dependencies[d]);
686 }
687
688 int unit_merge(Unit *u, Unit *other) {
689 UnitDependency d;
690 const char *other_id = NULL;
691 int r;
692
693 assert(u);
694 assert(other);
695 assert(u->manager == other->manager);
696 assert(u->type != _UNIT_TYPE_INVALID);
697
698 other = unit_follow_merge(other);
699
700 if (other == u)
701 return 0;
702
703 if (u->type != other->type)
704 return -EINVAL;
705
706 if (!u->instance != !other->instance)
707 return -EINVAL;
708
709 if (other->load_state != UNIT_STUB &&
710 other->load_state != UNIT_NOT_FOUND)
711 return -EEXIST;
712
713 if (other->job)
714 return -EEXIST;
715
716 if (other->nop_job)
717 return -EEXIST;
718
719 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
720 return -EEXIST;
721
722 if (other->id)
723 other_id = strdupa(other->id);
724
725 /* Make reservations to ensure merge_dependencies() won't fail */
726 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
727 r = reserve_dependencies(u, other, d);
728 /*
729 * We don't rollback reservations if we fail. We don't have
730 * a way to undo reservations. A reservation is not a leak.
731 */
732 if (r < 0)
733 return r;
734 }
735
736 /* Merge names */
737 r = merge_names(u, other);
738 if (r < 0)
739 return r;
740
741 /* Redirect all references */
742 while (other->refs)
743 unit_ref_set(other->refs, u);
744
745 /* Merge dependencies */
746 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
747 merge_dependencies(u, other, other_id, d);
748
749 other->load_state = UNIT_MERGED;
750 other->merged_into = u;
751
752 /* If there is still some data attached to the other node, we
753 * don't need it anymore, and can free it. */
754 if (other->load_state != UNIT_STUB)
755 if (UNIT_VTABLE(other)->done)
756 UNIT_VTABLE(other)->done(other);
757
758 unit_add_to_dbus_queue(u);
759 unit_add_to_cleanup_queue(other);
760
761 return 0;
762 }
763
764 int unit_merge_by_name(Unit *u, const char *name) {
765 Unit *other;
766 int r;
767 _cleanup_free_ char *s = NULL;
768
769 assert(u);
770 assert(name);
771
772 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
773 if (!u->instance)
774 return -EINVAL;
775
776 r = unit_name_replace_instance(name, u->instance, &s);
777 if (r < 0)
778 return r;
779
780 name = s;
781 }
782
783 other = manager_get_unit(u->manager, name);
784 if (other)
785 return unit_merge(u, other);
786
787 return unit_add_name(u, name);
788 }
789
790 Unit* unit_follow_merge(Unit *u) {
791 assert(u);
792
793 while (u->load_state == UNIT_MERGED)
794 assert_se(u = u->merged_into);
795
796 return u;
797 }
798
799 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
800 int r;
801
802 assert(u);
803 assert(c);
804
805 if (c->working_directory) {
806 r = unit_require_mounts_for(u, c->working_directory);
807 if (r < 0)
808 return r;
809 }
810
811 if (c->root_directory) {
812 r = unit_require_mounts_for(u, c->root_directory);
813 if (r < 0)
814 return r;
815 }
816
817 if (u->manager->running_as != MANAGER_SYSTEM)
818 return 0;
819
820 if (c->private_tmp) {
821 r = unit_require_mounts_for(u, "/tmp");
822 if (r < 0)
823 return r;
824
825 r = unit_require_mounts_for(u, "/var/tmp");
826 if (r < 0)
827 return r;
828 }
829
830 if (c->std_output != EXEC_OUTPUT_KMSG &&
831 c->std_output != EXEC_OUTPUT_SYSLOG &&
832 c->std_output != EXEC_OUTPUT_JOURNAL &&
833 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
834 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
835 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
836 c->std_error != EXEC_OUTPUT_KMSG &&
837 c->std_error != EXEC_OUTPUT_SYSLOG &&
838 c->std_error != EXEC_OUTPUT_JOURNAL &&
839 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
840 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
841 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
842 return 0;
843
844 /* If syslog or kernel logging is requested, make sure our own
845 * logging daemon is run first. */
846
847 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
848 if (r < 0)
849 return r;
850
851 return 0;
852 }
853
854 const char *unit_description(Unit *u) {
855 assert(u);
856
857 if (u->description)
858 return u->description;
859
860 return strna(u->id);
861 }
862
863 void unit_dump(Unit *u, FILE *f, const char *prefix) {
864 char *t, **j;
865 UnitDependency d;
866 Iterator i;
867 const char *prefix2;
868 char
869 timestamp0[FORMAT_TIMESTAMP_MAX],
870 timestamp1[FORMAT_TIMESTAMP_MAX],
871 timestamp2[FORMAT_TIMESTAMP_MAX],
872 timestamp3[FORMAT_TIMESTAMP_MAX],
873 timestamp4[FORMAT_TIMESTAMP_MAX],
874 timespan[FORMAT_TIMESPAN_MAX];
875 Unit *following;
876 _cleanup_set_free_ Set *following_set = NULL;
877 int r;
878
879 assert(u);
880 assert(u->type >= 0);
881
882 prefix = strempty(prefix);
883 prefix2 = strjoina(prefix, "\t");
884
885 fprintf(f,
886 "%s-> Unit %s:\n"
887 "%s\tDescription: %s\n"
888 "%s\tInstance: %s\n"
889 "%s\tUnit Load State: %s\n"
890 "%s\tUnit Active State: %s\n"
891 "%s\tState Change Timestamp: %s\n"
892 "%s\tInactive Exit Timestamp: %s\n"
893 "%s\tActive Enter Timestamp: %s\n"
894 "%s\tActive Exit Timestamp: %s\n"
895 "%s\tInactive Enter Timestamp: %s\n"
896 "%s\tGC Check Good: %s\n"
897 "%s\tNeed Daemon Reload: %s\n"
898 "%s\tTransient: %s\n"
899 "%s\tSlice: %s\n"
900 "%s\tCGroup: %s\n"
901 "%s\tCGroup realized: %s\n"
902 "%s\tCGroup mask: 0x%x\n"
903 "%s\tCGroup members mask: 0x%x\n",
904 prefix, u->id,
905 prefix, unit_description(u),
906 prefix, strna(u->instance),
907 prefix, unit_load_state_to_string(u->load_state),
908 prefix, unit_active_state_to_string(unit_active_state(u)),
909 prefix, strna(format_timestamp(timestamp0, sizeof(timestamp0), u->state_change_timestamp.realtime)),
910 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
911 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
912 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
913 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
914 prefix, yes_no(unit_check_gc(u)),
915 prefix, yes_no(unit_need_daemon_reload(u)),
916 prefix, yes_no(u->transient),
917 prefix, strna(unit_slice_name(u)),
918 prefix, strna(u->cgroup_path),
919 prefix, yes_no(u->cgroup_realized),
920 prefix, u->cgroup_realized_mask,
921 prefix, u->cgroup_members_mask);
922
923 SET_FOREACH(t, u->names, i)
924 fprintf(f, "%s\tName: %s\n", prefix, t);
925
926 STRV_FOREACH(j, u->documentation)
927 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
928
929 following = unit_following(u);
930 if (following)
931 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
932
933 r = unit_following_set(u, &following_set);
934 if (r >= 0) {
935 Unit *other;
936
937 SET_FOREACH(other, following_set, i)
938 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
939 }
940
941 if (u->fragment_path)
942 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
943
944 if (u->source_path)
945 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
946
947 STRV_FOREACH(j, u->dropin_paths)
948 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
949
950 if (u->job_timeout != USEC_INFINITY)
951 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
952
953 if (u->job_timeout_action != FAILURE_ACTION_NONE)
954 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
955
956 if (u->job_timeout_reboot_arg)
957 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
958
959 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
960 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
961
962 if (dual_timestamp_is_set(&u->condition_timestamp))
963 fprintf(f,
964 "%s\tCondition Timestamp: %s\n"
965 "%s\tCondition Result: %s\n",
966 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
967 prefix, yes_no(u->condition_result));
968
969 if (dual_timestamp_is_set(&u->assert_timestamp))
970 fprintf(f,
971 "%s\tAssert Timestamp: %s\n"
972 "%s\tAssert Result: %s\n",
973 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
974 prefix, yes_no(u->assert_result));
975
976 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
977 Unit *other;
978
979 SET_FOREACH(other, u->dependencies[d], i)
980 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
981 }
982
983 if (!strv_isempty(u->requires_mounts_for)) {
984 fprintf(f,
985 "%s\tRequiresMountsFor:", prefix);
986
987 STRV_FOREACH(j, u->requires_mounts_for)
988 fprintf(f, " %s", *j);
989
990 fputs("\n", f);
991 }
992
993 if (u->load_state == UNIT_LOADED) {
994
995 fprintf(f,
996 "%s\tStopWhenUnneeded: %s\n"
997 "%s\tRefuseManualStart: %s\n"
998 "%s\tRefuseManualStop: %s\n"
999 "%s\tDefaultDependencies: %s\n"
1000 "%s\tOnFailureJobMode: %s\n"
1001 "%s\tIgnoreOnIsolate: %s\n",
1002 prefix, yes_no(u->stop_when_unneeded),
1003 prefix, yes_no(u->refuse_manual_start),
1004 prefix, yes_no(u->refuse_manual_stop),
1005 prefix, yes_no(u->default_dependencies),
1006 prefix, job_mode_to_string(u->on_failure_job_mode),
1007 prefix, yes_no(u->ignore_on_isolate));
1008
1009 if (UNIT_VTABLE(u)->dump)
1010 UNIT_VTABLE(u)->dump(u, f, prefix2);
1011
1012 } else if (u->load_state == UNIT_MERGED)
1013 fprintf(f,
1014 "%s\tMerged into: %s\n",
1015 prefix, u->merged_into->id);
1016 else if (u->load_state == UNIT_ERROR)
1017 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
1018
1019
1020 if (u->job)
1021 job_dump(u->job, f, prefix2);
1022
1023 if (u->nop_job)
1024 job_dump(u->nop_job, f, prefix2);
1025
1026 }
1027
1028 /* Common implementation for multiple backends */
1029 int unit_load_fragment_and_dropin(Unit *u) {
1030 int r;
1031
1032 assert(u);
1033
1034 /* Load a .{service,socket,...} file */
1035 r = unit_load_fragment(u);
1036 if (r < 0)
1037 return r;
1038
1039 if (u->load_state == UNIT_STUB)
1040 return -ENOENT;
1041
1042 /* Load drop-in directory data */
1043 r = unit_load_dropin(unit_follow_merge(u));
1044 if (r < 0)
1045 return r;
1046
1047 return 0;
1048 }
1049
1050 /* Common implementation for multiple backends */
1051 int unit_load_fragment_and_dropin_optional(Unit *u) {
1052 int r;
1053
1054 assert(u);
1055
1056 /* Same as unit_load_fragment_and_dropin(), but whether
1057 * something can be loaded or not doesn't matter. */
1058
1059 /* Load a .service file */
1060 r = unit_load_fragment(u);
1061 if (r < 0)
1062 return r;
1063
1064 if (u->load_state == UNIT_STUB)
1065 u->load_state = UNIT_LOADED;
1066
1067 /* Load drop-in directory data */
1068 r = unit_load_dropin(unit_follow_merge(u));
1069 if (r < 0)
1070 return r;
1071
1072 return 0;
1073 }
1074
1075 int unit_add_default_target_dependency(Unit *u, Unit *target) {
1076 assert(u);
1077 assert(target);
1078
1079 if (target->type != UNIT_TARGET)
1080 return 0;
1081
1082 /* Only add the dependency if both units are loaded, so that
1083 * that loop check below is reliable */
1084 if (u->load_state != UNIT_LOADED ||
1085 target->load_state != UNIT_LOADED)
1086 return 0;
1087
1088 /* If either side wants no automatic dependencies, then let's
1089 * skip this */
1090 if (!u->default_dependencies ||
1091 !target->default_dependencies)
1092 return 0;
1093
1094 /* Don't create loops */
1095 if (set_get(target->dependencies[UNIT_BEFORE], u))
1096 return 0;
1097
1098 return unit_add_dependency(target, UNIT_AFTER, u, true);
1099 }
1100
1101 static int unit_add_target_dependencies(Unit *u) {
1102
1103 static const UnitDependency deps[] = {
1104 UNIT_REQUIRED_BY,
1105 UNIT_REQUISITE_OF,
1106 UNIT_WANTED_BY,
1107 UNIT_BOUND_BY
1108 };
1109
1110 Unit *target;
1111 Iterator i;
1112 unsigned k;
1113 int r = 0;
1114
1115 assert(u);
1116
1117 for (k = 0; k < ELEMENTSOF(deps); k++)
1118 SET_FOREACH(target, u->dependencies[deps[k]], i) {
1119 r = unit_add_default_target_dependency(u, target);
1120 if (r < 0)
1121 return r;
1122 }
1123
1124 return r;
1125 }
1126
1127 static int unit_add_slice_dependencies(Unit *u) {
1128 assert(u);
1129
1130 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1131 return 0;
1132
1133 if (UNIT_ISSET(u->slice))
1134 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
1135
1136 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1137 return 0;
1138
1139 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
1140 }
1141
1142 static int unit_add_mount_dependencies(Unit *u) {
1143 char **i;
1144 int r;
1145
1146 assert(u);
1147
1148 STRV_FOREACH(i, u->requires_mounts_for) {
1149 char prefix[strlen(*i) + 1];
1150
1151 PATH_FOREACH_PREFIX_MORE(prefix, *i) {
1152 _cleanup_free_ char *p = NULL;
1153 Unit *m;
1154
1155 r = unit_name_from_path(prefix, ".mount", &p);
1156 if (r < 0)
1157 return r;
1158
1159 m = manager_get_unit(u->manager, p);
1160 if (!m) {
1161 /* Make sure to load the mount unit if
1162 * it exists. If so the dependencies
1163 * on this unit will be added later
1164 * during the loading of the mount
1165 * unit. */
1166 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
1167 continue;
1168 }
1169 if (m == u)
1170 continue;
1171
1172 if (m->load_state != UNIT_LOADED)
1173 continue;
1174
1175 r = unit_add_dependency(u, UNIT_AFTER, m, true);
1176 if (r < 0)
1177 return r;
1178
1179 if (m->fragment_path) {
1180 r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
1181 if (r < 0)
1182 return r;
1183 }
1184 }
1185 }
1186
1187 return 0;
1188 }
1189
1190 static int unit_add_startup_units(Unit *u) {
1191 CGroupContext *c;
1192 int r;
1193
1194 c = unit_get_cgroup_context(u);
1195 if (!c)
1196 return 0;
1197
1198 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1199 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
1200 return 0;
1201
1202 r = set_ensure_allocated(&u->manager->startup_units, NULL);
1203 if (r < 0)
1204 return r;
1205
1206 return set_put(u->manager->startup_units, u);
1207 }
1208
1209 int unit_load(Unit *u) {
1210 int r;
1211
1212 assert(u);
1213
1214 if (u->in_load_queue) {
1215 LIST_REMOVE(load_queue, u->manager->load_queue, u);
1216 u->in_load_queue = false;
1217 }
1218
1219 if (u->type == _UNIT_TYPE_INVALID)
1220 return -EINVAL;
1221
1222 if (u->load_state != UNIT_STUB)
1223 return 0;
1224
1225 if (UNIT_VTABLE(u)->load) {
1226 r = UNIT_VTABLE(u)->load(u);
1227 if (r < 0)
1228 goto fail;
1229 }
1230
1231 if (u->load_state == UNIT_STUB) {
1232 r = -ENOENT;
1233 goto fail;
1234 }
1235
1236 if (u->load_state == UNIT_LOADED) {
1237
1238 r = unit_add_target_dependencies(u);
1239 if (r < 0)
1240 goto fail;
1241
1242 r = unit_add_slice_dependencies(u);
1243 if (r < 0)
1244 goto fail;
1245
1246 r = unit_add_mount_dependencies(u);
1247 if (r < 0)
1248 goto fail;
1249
1250 r = unit_add_startup_units(u);
1251 if (r < 0)
1252 goto fail;
1253
1254 if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
1255 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1256 r = -EINVAL;
1257 goto fail;
1258 }
1259
1260 unit_update_cgroup_members_masks(u);
1261 }
1262
1263 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
1264
1265 unit_add_to_dbus_queue(unit_follow_merge(u));
1266 unit_add_to_gc_queue(u);
1267
1268 return 0;
1269
1270 fail:
1271 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
1272 u->load_error = r;
1273 unit_add_to_dbus_queue(u);
1274 unit_add_to_gc_queue(u);
1275
1276 log_unit_debug_errno(u, r, "Failed to load configuration: %m");
1277
1278 return r;
1279 }
1280
1281 static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
1282 Condition *c;
1283 int triggered = -1;
1284
1285 assert(u);
1286 assert(to_string);
1287
1288 /* If the condition list is empty, then it is true */
1289 if (!first)
1290 return true;
1291
1292 /* Otherwise, if all of the non-trigger conditions apply and
1293 * if any of the trigger conditions apply (unless there are
1294 * none) we return true */
1295 LIST_FOREACH(conditions, c, first) {
1296 int r;
1297
1298 r = condition_test(c);
1299 if (r < 0)
1300 log_unit_warning(u,
1301 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1302 to_string(c->type),
1303 c->trigger ? "|" : "",
1304 c->negate ? "!" : "",
1305 c->parameter);
1306 else
1307 log_unit_debug(u,
1308 "%s=%s%s%s %s.",
1309 to_string(c->type),
1310 c->trigger ? "|" : "",
1311 c->negate ? "!" : "",
1312 c->parameter,
1313 condition_result_to_string(c->result));
1314
1315 if (!c->trigger && r <= 0)
1316 return false;
1317
1318 if (c->trigger && triggered <= 0)
1319 triggered = r > 0;
1320 }
1321
1322 return triggered != 0;
1323 }
1324
1325 static bool unit_condition_test(Unit *u) {
1326 assert(u);
1327
1328 dual_timestamp_get(&u->condition_timestamp);
1329 u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
1330
1331 return u->condition_result;
1332 }
1333
1334 static bool unit_assert_test(Unit *u) {
1335 assert(u);
1336
1337 dual_timestamp_get(&u->assert_timestamp);
1338 u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
1339
1340 return u->assert_result;
1341 }
1342
1343 void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
1344 DISABLE_WARNING_FORMAT_NONLITERAL;
1345 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, status, unit_status_msg_format, unit_description(u));
1346 REENABLE_WARNING;
1347 }
1348
1349 _pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
1350 const char *format;
1351 const UnitStatusMessageFormats *format_table;
1352
1353 assert(u);
1354 assert(IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD));
1355
1356 if (t != JOB_RELOAD) {
1357 format_table = &UNIT_VTABLE(u)->status_message_formats;
1358 if (format_table) {
1359 format = format_table->starting_stopping[t == JOB_STOP];
1360 if (format)
1361 return format;
1362 }
1363 }
1364
1365 /* Return generic strings */
1366 if (t == JOB_START)
1367 return "Starting %s.";
1368 else if (t == JOB_STOP)
1369 return "Stopping %s.";
1370 else
1371 return "Reloading %s.";
1372 }
1373
1374 static void unit_status_print_starting_stopping(Unit *u, JobType t) {
1375 const char *format;
1376
1377 assert(u);
1378
1379 /* Reload status messages have traditionally not been printed to console. */
1380 if (!IN_SET(t, JOB_START, JOB_STOP))
1381 return;
1382
1383 format = unit_get_status_message_format(u, t);
1384
1385 DISABLE_WARNING_FORMAT_NONLITERAL;
1386 unit_status_printf(u, "", format);
1387 REENABLE_WARNING;
1388 }
1389
1390 static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
1391 const char *format;
1392 char buf[LINE_MAX];
1393 sd_id128_t mid;
1394
1395 assert(u);
1396
1397 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
1398 return;
1399
1400 if (log_on_console())
1401 return;
1402
1403 /* We log status messages for all units and all operations. */
1404
1405 format = unit_get_status_message_format(u, t);
1406
1407 DISABLE_WARNING_FORMAT_NONLITERAL;
1408 xsprintf(buf, format, unit_description(u));
1409 REENABLE_WARNING;
1410
1411 mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
1412 t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
1413 SD_MESSAGE_UNIT_RELOADING;
1414
1415 /* Note that we deliberately use LOG_MESSAGE() instead of
1416 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1417 * closely what is written to screen using the status output,
1418 * which is supposed the highest level, friendliest output
1419 * possible, which means we should avoid the low-level unit
1420 * name. */
1421 log_struct(LOG_INFO,
1422 LOG_MESSAGE_ID(mid),
1423 LOG_UNIT_ID(u),
1424 LOG_MESSAGE("%s", buf),
1425 NULL);
1426 }
1427
1428 void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
1429 assert(u);
1430 assert(t >= 0);
1431 assert(t < _JOB_TYPE_MAX);
1432
1433 unit_status_log_starting_stopping_reloading(u, t);
1434 unit_status_print_starting_stopping(u, t);
1435 }
1436
1437 static int unit_start_limit_test(Unit *u) {
1438 assert(u);
1439
1440 if (ratelimit_test(&u->start_limit)) {
1441 u->start_limit_hit = false;
1442 return 0;
1443 }
1444
1445 log_unit_warning(u, "Start request repeated too quickly.");
1446 u->start_limit_hit = true;
1447
1448 return failure_action(u->manager, u->start_limit_action, u->reboot_arg);
1449 }
1450
1451 /* Errors:
1452 * -EBADR: This unit type does not support starting.
1453 * -EALREADY: Unit is already started.
1454 * -EAGAIN: An operation is already in progress. Retry later.
1455 * -ECANCELED: Too many requests for now.
1456 * -EPROTO: Assert failed
1457 * -EINVAL: Unit not loaded
1458 * -EOPNOTSUPP: Unit type not supported
1459 */
1460 int unit_start(Unit *u) {
1461 UnitActiveState state;
1462 Unit *following;
1463 int r;
1464
1465 assert(u);
1466
1467 /* If this is already started, then this will succeed. Note
1468 * that this will even succeed if this unit is not startable
1469 * by the user. This is relied on to detect when we need to
1470 * wait for units and when waiting is finished. */
1471 state = unit_active_state(u);
1472 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1473 return -EALREADY;
1474
1475 /* Make sure we don't enter a busy loop of some kind. */
1476 r = unit_start_limit_test(u);
1477 if (r < 0)
1478 return r;
1479
1480 /* Units that aren't loaded cannot be started */
1481 if (u->load_state != UNIT_LOADED)
1482 return -EINVAL;
1483
1484 /* If the conditions failed, don't do anything at all. If we
1485 * already are activating this call might still be useful to
1486 * speed up activation in case there is some hold-off time,
1487 * but we don't want to recheck the condition in that case. */
1488 if (state != UNIT_ACTIVATING &&
1489 !unit_condition_test(u)) {
1490 log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
1491 return -EALREADY;
1492 }
1493
1494 /* If the asserts failed, fail the entire job */
1495 if (state != UNIT_ACTIVATING &&
1496 !unit_assert_test(u)) {
1497 log_unit_notice(u, "Starting requested but asserts failed.");
1498 return -EPROTO;
1499 }
1500
1501 /* Units of types that aren't supported cannot be
1502 * started. Note that we do this test only after the condition
1503 * checks, so that we rather return condition check errors
1504 * (which are usually not considered a true failure) than "not
1505 * supported" errors (which are considered a failure).
1506 */
1507 if (!unit_supported(u))
1508 return -EOPNOTSUPP;
1509
1510 /* Forward to the main object, if we aren't it. */
1511 following = unit_following(u);
1512 if (following) {
1513 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
1514 return unit_start(following);
1515 }
1516
1517 /* If it is stopped, but we cannot start it, then fail */
1518 if (!UNIT_VTABLE(u)->start)
1519 return -EBADR;
1520
1521 /* We don't suppress calls to ->start() here when we are
1522 * already starting, to allow this request to be used as a
1523 * "hurry up" call, for example when the unit is in some "auto
1524 * restart" state where it waits for a holdoff timer to elapse
1525 * before it will start again. */
1526
1527 unit_add_to_dbus_queue(u);
1528
1529 return UNIT_VTABLE(u)->start(u);
1530 }
1531
1532 bool unit_can_start(Unit *u) {
1533 assert(u);
1534
1535 if (u->load_state != UNIT_LOADED)
1536 return false;
1537
1538 if (!unit_supported(u))
1539 return false;
1540
1541 return !!UNIT_VTABLE(u)->start;
1542 }
1543
1544 bool unit_can_isolate(Unit *u) {
1545 assert(u);
1546
1547 return unit_can_start(u) &&
1548 u->allow_isolate;
1549 }
1550
1551 /* Errors:
1552 * -EBADR: This unit type does not support stopping.
1553 * -EALREADY: Unit is already stopped.
1554 * -EAGAIN: An operation is already in progress. Retry later.
1555 */
1556 int unit_stop(Unit *u) {
1557 UnitActiveState state;
1558 Unit *following;
1559
1560 assert(u);
1561
1562 state = unit_active_state(u);
1563 if (UNIT_IS_INACTIVE_OR_FAILED(state))
1564 return -EALREADY;
1565
1566 following = unit_following(u);
1567 if (following) {
1568 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
1569 return unit_stop(following);
1570 }
1571
1572 if (!UNIT_VTABLE(u)->stop)
1573 return -EBADR;
1574
1575 unit_add_to_dbus_queue(u);
1576
1577 return UNIT_VTABLE(u)->stop(u);
1578 }
1579
1580 /* Errors:
1581 * -EBADR: This unit type does not support reloading.
1582 * -ENOEXEC: Unit is not started.
1583 * -EAGAIN: An operation is already in progress. Retry later.
1584 */
1585 int unit_reload(Unit *u) {
1586 UnitActiveState state;
1587 Unit *following;
1588
1589 assert(u);
1590
1591 if (u->load_state != UNIT_LOADED)
1592 return -EINVAL;
1593
1594 if (!unit_can_reload(u))
1595 return -EBADR;
1596
1597 state = unit_active_state(u);
1598 if (state == UNIT_RELOADING)
1599 return -EALREADY;
1600
1601 if (state != UNIT_ACTIVE) {
1602 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
1603 return -ENOEXEC;
1604 }
1605
1606 following = unit_following(u);
1607 if (following) {
1608 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
1609 return unit_reload(following);
1610 }
1611
1612 unit_add_to_dbus_queue(u);
1613
1614 return UNIT_VTABLE(u)->reload(u);
1615 }
1616
1617 bool unit_can_reload(Unit *u) {
1618 assert(u);
1619
1620 if (!UNIT_VTABLE(u)->reload)
1621 return false;
1622
1623 if (!UNIT_VTABLE(u)->can_reload)
1624 return true;
1625
1626 return UNIT_VTABLE(u)->can_reload(u);
1627 }
1628
1629 static void unit_check_unneeded(Unit *u) {
1630
1631 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1632
1633 static const UnitDependency needed_dependencies[] = {
1634 UNIT_REQUIRED_BY,
1635 UNIT_REQUISITE_OF,
1636 UNIT_WANTED_BY,
1637 UNIT_BOUND_BY,
1638 };
1639
1640 Unit *other;
1641 Iterator i;
1642 unsigned j;
1643 int r;
1644
1645 assert(u);
1646
1647 /* If this service shall be shut down when unneeded then do
1648 * so. */
1649
1650 if (!u->stop_when_unneeded)
1651 return;
1652
1653 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1654 return;
1655
1656 for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
1657 SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
1658 if (unit_active_or_pending(other))
1659 return;
1660
1661 /* If stopping a unit fails continously we might enter a stop
1662 * loop here, hence stop acting on the service being
1663 * unnecessary after a while. */
1664 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1665 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1666 return;
1667 }
1668
1669 log_unit_info(u, "Unit not needed anymore. Stopping.");
1670
1671 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1672 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
1673 if (r < 0)
1674 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1675 }
1676
1677 static void unit_check_binds_to(Unit *u) {
1678 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1679 bool stop = false;
1680 Unit *other;
1681 Iterator i;
1682 int r;
1683
1684 assert(u);
1685
1686 if (u->job)
1687 return;
1688
1689 if (unit_active_state(u) != UNIT_ACTIVE)
1690 return;
1691
1692 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
1693 if (other->job)
1694 continue;
1695
1696 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
1697 continue;
1698
1699 stop = true;
1700 break;
1701 }
1702
1703 if (!stop)
1704 return;
1705
1706 /* If stopping a unit fails continously we might enter a stop
1707 * loop here, hence stop acting on the service being
1708 * unnecessary after a while. */
1709 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1710 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
1711 return;
1712 }
1713
1714 assert(other);
1715 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
1716
1717 /* A unit we need to run is gone. Sniff. Let's stop this. */
1718 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
1719 if (r < 0)
1720 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1721 }
1722
1723 static void retroactively_start_dependencies(Unit *u) {
1724 Iterator i;
1725 Unit *other;
1726
1727 assert(u);
1728 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1729
1730 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1731 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1732 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1733 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
1734
1735 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
1736 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1737 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1738 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
1739
1740 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1741 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1742 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1743 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
1744
1745 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
1746 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1747 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
1748
1749 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
1750 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1751 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
1752 }
1753
1754 static void retroactively_stop_dependencies(Unit *u) {
1755 Iterator i;
1756 Unit *other;
1757
1758 assert(u);
1759 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1760
1761 /* Pull down units which are bound to us recursively if enabled */
1762 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
1763 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1764 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
1765 }
1766
1767 static void check_unneeded_dependencies(Unit *u) {
1768 Iterator i;
1769 Unit *other;
1770
1771 assert(u);
1772 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1773
1774 /* Garbage collect services that might not be needed anymore, if enabled */
1775 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1776 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1777 unit_check_unneeded(other);
1778 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1779 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1780 unit_check_unneeded(other);
1781 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
1782 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1783 unit_check_unneeded(other);
1784 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
1785 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1786 unit_check_unneeded(other);
1787 }
1788
1789 void unit_start_on_failure(Unit *u) {
1790 Unit *other;
1791 Iterator i;
1792
1793 assert(u);
1794
1795 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
1796 return;
1797
1798 log_unit_info(u, "Triggering OnFailure= dependencies.");
1799
1800 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
1801 int r;
1802
1803 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
1804 if (r < 0)
1805 log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
1806 }
1807 }
1808
1809 void unit_trigger_notify(Unit *u) {
1810 Unit *other;
1811 Iterator i;
1812
1813 assert(u);
1814
1815 SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
1816 if (UNIT_VTABLE(other)->trigger_notify)
1817 UNIT_VTABLE(other)->trigger_notify(other, u);
1818 }
1819
1820 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1821 Manager *m;
1822 bool unexpected;
1823
1824 assert(u);
1825 assert(os < _UNIT_ACTIVE_STATE_MAX);
1826 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1827
1828 /* Note that this is called for all low-level state changes,
1829 * even if they might map to the same high-level
1830 * UnitActiveState! That means that ns == os is an expected
1831 * behavior here. For example: if a mount point is remounted
1832 * this function will be called too! */
1833
1834 m = u->manager;
1835
1836 /* Update timestamps for state changes */
1837 if (m->n_reloading <= 0) {
1838 dual_timestamp_get(&u->state_change_timestamp);
1839
1840 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1841 u->inactive_exit_timestamp = u->state_change_timestamp;
1842 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1843 u->inactive_enter_timestamp = u->state_change_timestamp;
1844
1845 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1846 u->active_enter_timestamp = u->state_change_timestamp;
1847 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1848 u->active_exit_timestamp = u->state_change_timestamp;
1849 }
1850
1851 /* Keep track of failed units */
1852 (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
1853
1854 /* Make sure the cgroup is always removed when we become inactive */
1855 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1856 unit_prune_cgroup(u);
1857
1858 /* Note that this doesn't apply to RemainAfterExit services exiting
1859 * successfully, since there's no change of state in that case. Which is
1860 * why it is handled in service_set_state() */
1861 if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1862 ExecContext *ec;
1863
1864 ec = unit_get_exec_context(u);
1865 if (ec && exec_context_may_touch_console(ec)) {
1866 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1867 m->n_on_console--;
1868
1869 if (m->n_on_console == 0)
1870 /* unset no_console_output flag, since the console is free */
1871 m->no_console_output = false;
1872 } else
1873 m->n_on_console++;
1874 }
1875 }
1876
1877 if (u->job) {
1878 unexpected = false;
1879
1880 if (u->job->state == JOB_WAITING)
1881
1882 /* So we reached a different state for this
1883 * job. Let's see if we can run it now if it
1884 * failed previously due to EAGAIN. */
1885 job_add_to_run_queue(u->job);
1886
1887 /* Let's check whether this state change constitutes a
1888 * finished job, or maybe contradicts a running job and
1889 * hence needs to invalidate jobs. */
1890
1891 switch (u->job->type) {
1892
1893 case JOB_START:
1894 case JOB_VERIFY_ACTIVE:
1895
1896 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1897 job_finish_and_invalidate(u->job, JOB_DONE, true);
1898 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1899 unexpected = true;
1900
1901 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1902 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
1903 }
1904
1905 break;
1906
1907 case JOB_RELOAD:
1908 case JOB_RELOAD_OR_START:
1909 case JOB_TRY_RELOAD:
1910
1911 if (u->job->state == JOB_RUNNING) {
1912 if (ns == UNIT_ACTIVE)
1913 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
1914 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
1915 unexpected = true;
1916
1917 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1918 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
1919 }
1920 }
1921
1922 break;
1923
1924 case JOB_STOP:
1925 case JOB_RESTART:
1926 case JOB_TRY_RESTART:
1927
1928 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1929 job_finish_and_invalidate(u->job, JOB_DONE, true);
1930 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
1931 unexpected = true;
1932 job_finish_and_invalidate(u->job, JOB_FAILED, true);
1933 }
1934
1935 break;
1936
1937 default:
1938 assert_not_reached("Job type unknown");
1939 }
1940
1941 } else
1942 unexpected = true;
1943
1944 if (m->n_reloading <= 0) {
1945
1946 /* If this state change happened without being
1947 * requested by a job, then let's retroactively start
1948 * or stop dependencies. We skip that step when
1949 * deserializing, since we don't want to create any
1950 * additional jobs just because something is already
1951 * activated. */
1952
1953 if (unexpected) {
1954 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1955 retroactively_start_dependencies(u);
1956 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1957 retroactively_stop_dependencies(u);
1958 }
1959
1960 /* stop unneeded units regardless if going down was expected or not */
1961 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1962 check_unneeded_dependencies(u);
1963
1964 if (ns != os && ns == UNIT_FAILED) {
1965 log_unit_notice(u, "Unit entered failed state.");
1966 unit_start_on_failure(u);
1967 }
1968 }
1969
1970 /* Some names are special */
1971 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1972
1973 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
1974 /* The bus might have just become available,
1975 * hence try to connect to it, if we aren't
1976 * yet connected. */
1977 bus_init(m, true);
1978
1979 if (u->type == UNIT_SERVICE &&
1980 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
1981 m->n_reloading <= 0) {
1982 /* Write audit record if we have just finished starting up */
1983 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
1984 u->in_audit = true;
1985 }
1986
1987 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
1988 manager_send_unit_plymouth(m, u);
1989
1990 } else {
1991
1992 /* We don't care about D-Bus here, since we'll get an
1993 * asynchronous notification for it anyway. */
1994
1995 if (u->type == UNIT_SERVICE &&
1996 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1997 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
1998 m->n_reloading <= 0) {
1999
2000 /* Hmm, if there was no start record written
2001 * write it now, so that we always have a nice
2002 * pair */
2003 if (!u->in_audit) {
2004 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
2005
2006 if (ns == UNIT_INACTIVE)
2007 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
2008 } else
2009 /* Write audit record if we have just finished shutting down */
2010 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
2011
2012 u->in_audit = false;
2013 }
2014 }
2015
2016 manager_recheck_journal(m);
2017 unit_trigger_notify(u);
2018
2019 if (u->manager->n_reloading <= 0) {
2020 /* Maybe we finished startup and are now ready for
2021 * being stopped because unneeded? */
2022 unit_check_unneeded(u);
2023
2024 /* Maybe we finished startup, but something we needed
2025 * has vanished? Let's die then. (This happens when
2026 * something BindsTo= to a Type=oneshot unit, as these
2027 * units go directly from starting to inactive,
2028 * without ever entering started.) */
2029 unit_check_binds_to(u);
2030 }
2031
2032 unit_add_to_dbus_queue(u);
2033 unit_add_to_gc_queue(u);
2034 }
2035
2036 int unit_watch_pid(Unit *u, pid_t pid) {
2037 int q, r;
2038
2039 assert(u);
2040 assert(pid >= 1);
2041
2042 /* Watch a specific PID. We only support one or two units
2043 * watching each PID for now, not more. */
2044
2045 r = set_ensure_allocated(&u->pids, NULL);
2046 if (r < 0)
2047 return r;
2048
2049 r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
2050 if (r < 0)
2051 return r;
2052
2053 r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2054 if (r == -EEXIST) {
2055 r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
2056 if (r < 0)
2057 return r;
2058
2059 r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2060 }
2061
2062 q = set_put(u->pids, PID_TO_PTR(pid));
2063 if (q < 0)
2064 return q;
2065
2066 return r;
2067 }
2068
2069 void unit_unwatch_pid(Unit *u, pid_t pid) {
2070 assert(u);
2071 assert(pid >= 1);
2072
2073 (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2074 (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2075 (void) set_remove(u->pids, PID_TO_PTR(pid));
2076 }
2077
2078 void unit_unwatch_all_pids(Unit *u) {
2079 assert(u);
2080
2081 while (!set_isempty(u->pids))
2082 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
2083
2084 u->pids = set_free(u->pids);
2085 }
2086
2087 void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
2088 Iterator i;
2089 void *e;
2090
2091 assert(u);
2092
2093 /* Cleans dead PIDs from our list */
2094
2095 SET_FOREACH(e, u->pids, i) {
2096 pid_t pid = PTR_TO_PID(e);
2097
2098 if (pid == except1 || pid == except2)
2099 continue;
2100
2101 if (!pid_is_unwaited(pid))
2102 unit_unwatch_pid(u, pid);
2103 }
2104 }
2105
2106 bool unit_job_is_applicable(Unit *u, JobType j) {
2107 assert(u);
2108 assert(j >= 0 && j < _JOB_TYPE_MAX);
2109
2110 switch (j) {
2111
2112 case JOB_VERIFY_ACTIVE:
2113 case JOB_START:
2114 case JOB_STOP:
2115 case JOB_NOP:
2116 return true;
2117
2118 case JOB_RESTART:
2119 case JOB_TRY_RESTART:
2120 return unit_can_start(u);
2121
2122 case JOB_RELOAD:
2123 case JOB_TRY_RELOAD:
2124 return unit_can_reload(u);
2125
2126 case JOB_RELOAD_OR_START:
2127 return unit_can_reload(u) && unit_can_start(u);
2128
2129 default:
2130 assert_not_reached("Invalid job type");
2131 }
2132 }
2133
2134 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2135 assert(u);
2136
2137 /* Only warn about some unit types */
2138 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2139 return;
2140
2141 if (streq_ptr(u->id, other))
2142 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2143 else
2144 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
2145 }
2146
2147 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
2148
2149 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2150 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
2151 [UNIT_WANTS] = UNIT_WANTED_BY,
2152 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
2153 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
2154 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
2155 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
2156 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
2157 [UNIT_WANTED_BY] = UNIT_WANTS,
2158 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
2159 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
2160 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
2161 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
2162 [UNIT_BEFORE] = UNIT_AFTER,
2163 [UNIT_AFTER] = UNIT_BEFORE,
2164 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
2165 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
2166 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
2167 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
2168 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
2169 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
2170 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
2171 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
2172 };
2173 int r, q = 0, v = 0, w = 0;
2174 Unit *orig_u = u, *orig_other = other;
2175
2176 assert(u);
2177 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
2178 assert(other);
2179
2180 u = unit_follow_merge(u);
2181 other = unit_follow_merge(other);
2182
2183 /* We won't allow dependencies on ourselves. We will not
2184 * consider them an error however. */
2185 if (u == other) {
2186 maybe_warn_about_dependency(orig_u, orig_other->id, d);
2187 return 0;
2188 }
2189
2190 r = set_ensure_allocated(&u->dependencies[d], NULL);
2191 if (r < 0)
2192 return r;
2193
2194 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
2195 r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
2196 if (r < 0)
2197 return r;
2198 }
2199
2200 if (add_reference) {
2201 r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
2202 if (r < 0)
2203 return r;
2204
2205 r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
2206 if (r < 0)
2207 return r;
2208 }
2209
2210 q = set_put(u->dependencies[d], other);
2211 if (q < 0)
2212 return q;
2213
2214 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
2215 v = set_put(other->dependencies[inverse_table[d]], u);
2216 if (v < 0) {
2217 r = v;
2218 goto fail;
2219 }
2220 }
2221
2222 if (add_reference) {
2223 w = set_put(u->dependencies[UNIT_REFERENCES], other);
2224 if (w < 0) {
2225 r = w;
2226 goto fail;
2227 }
2228
2229 r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
2230 if (r < 0)
2231 goto fail;
2232 }
2233
2234 unit_add_to_dbus_queue(u);
2235 return 0;
2236
2237 fail:
2238 if (q > 0)
2239 set_remove(u->dependencies[d], other);
2240
2241 if (v > 0)
2242 set_remove(other->dependencies[inverse_table[d]], u);
2243
2244 if (w > 0)
2245 set_remove(u->dependencies[UNIT_REFERENCES], other);
2246
2247 return r;
2248 }
2249
2250 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
2251 int r;
2252
2253 assert(u);
2254
2255 r = unit_add_dependency(u, d, other, add_reference);
2256 if (r < 0)
2257 return r;
2258
2259 return unit_add_dependency(u, e, other, add_reference);
2260 }
2261
2262 static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
2263 int r;
2264
2265 assert(u);
2266 assert(name || path);
2267 assert(buf);
2268 assert(ret);
2269
2270 if (!name)
2271 name = basename(path);
2272
2273 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2274 *buf = NULL;
2275 *ret = name;
2276 return 0;
2277 }
2278
2279 if (u->instance)
2280 r = unit_name_replace_instance(name, u->instance, buf);
2281 else {
2282 _cleanup_free_ char *i = NULL;
2283
2284 r = unit_name_to_prefix(u->id, &i);
2285 if (r < 0)
2286 return r;
2287
2288 r = unit_name_replace_instance(name, i, buf);
2289 }
2290 if (r < 0)
2291 return r;
2292
2293 *ret = *buf;
2294 return 0;
2295 }
2296
2297 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
2298 _cleanup_free_ char *buf = NULL;
2299 Unit *other;
2300 int r;
2301
2302 assert(u);
2303 assert(name || path);
2304
2305 r = resolve_template(u, name, path, &buf, &name);
2306 if (r < 0)
2307 return r;
2308
2309 r = manager_load_unit(u->manager, name, path, NULL, &other);
2310 if (r < 0)
2311 return r;
2312
2313 return unit_add_dependency(u, d, other, add_reference);
2314 }
2315
2316 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
2317 _cleanup_free_ char *buf = NULL;
2318 Unit *other;
2319 int r;
2320
2321 assert(u);
2322 assert(name || path);
2323
2324 r = resolve_template(u, name, path, &buf, &name);
2325 if (r < 0)
2326 return r;
2327
2328 r = manager_load_unit(u->manager, name, path, NULL, &other);
2329 if (r < 0)
2330 return r;
2331
2332 return unit_add_two_dependencies(u, d, e, other, add_reference);
2333 }
2334
2335 int set_unit_path(const char *p) {
2336 /* This is mostly for debug purposes */
2337 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
2338 return -errno;
2339
2340 return 0;
2341 }
2342
2343 char *unit_dbus_path(Unit *u) {
2344 assert(u);
2345
2346 if (!u->id)
2347 return NULL;
2348
2349 return unit_dbus_path_from_name(u->id);
2350 }
2351
2352 int unit_set_slice(Unit *u, Unit *slice) {
2353 assert(u);
2354 assert(slice);
2355
2356 /* Sets the unit slice if it has not been set before. Is extra
2357 * careful, to only allow this for units that actually have a
2358 * cgroup context. Also, we don't allow to set this for slices
2359 * (since the parent slice is derived from the name). Make
2360 * sure the unit we set is actually a slice. */
2361
2362 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2363 return -EOPNOTSUPP;
2364
2365 if (u->type == UNIT_SLICE)
2366 return -EINVAL;
2367
2368 if (unit_active_state(u) != UNIT_INACTIVE)
2369 return -EBUSY;
2370
2371 if (slice->type != UNIT_SLICE)
2372 return -EINVAL;
2373
2374 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
2375 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
2376 return -EPERM;
2377
2378 if (UNIT_DEREF(u->slice) == slice)
2379 return 0;
2380
2381 if (UNIT_ISSET(u->slice))
2382 return -EBUSY;
2383
2384 unit_ref_set(&u->slice, slice);
2385 return 1;
2386 }
2387
2388 int unit_set_default_slice(Unit *u) {
2389 _cleanup_free_ char *b = NULL;
2390 const char *slice_name;
2391 Unit *slice;
2392 int r;
2393
2394 assert(u);
2395
2396 if (UNIT_ISSET(u->slice))
2397 return 0;
2398
2399 if (u->instance) {
2400 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
2401
2402 /* Implicitly place all instantiated units in their
2403 * own per-template slice */
2404
2405 r = unit_name_to_prefix(u->id, &prefix);
2406 if (r < 0)
2407 return r;
2408
2409 /* The prefix is already escaped, but it might include
2410 * "-" which has a special meaning for slice units,
2411 * hence escape it here extra. */
2412 escaped = unit_name_escape(prefix);
2413 if (!escaped)
2414 return -ENOMEM;
2415
2416 if (u->manager->running_as == MANAGER_SYSTEM)
2417 b = strjoin("system-", escaped, ".slice", NULL);
2418 else
2419 b = strappend(escaped, ".slice");
2420 if (!b)
2421 return -ENOMEM;
2422
2423 slice_name = b;
2424 } else
2425 slice_name =
2426 u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
2427 ? SPECIAL_SYSTEM_SLICE
2428 : SPECIAL_ROOT_SLICE;
2429
2430 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
2431 if (r < 0)
2432 return r;
2433
2434 return unit_set_slice(u, slice);
2435 }
2436
2437 const char *unit_slice_name(Unit *u) {
2438 assert(u);
2439
2440 if (!UNIT_ISSET(u->slice))
2441 return NULL;
2442
2443 return UNIT_DEREF(u->slice)->id;
2444 }
2445
2446 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2447 _cleanup_free_ char *t = NULL;
2448 int r;
2449
2450 assert(u);
2451 assert(type);
2452 assert(_found);
2453
2454 r = unit_name_change_suffix(u->id, type, &t);
2455 if (r < 0)
2456 return r;
2457 if (unit_has_name(u, t))
2458 return -EINVAL;
2459
2460 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
2461 assert(r < 0 || *_found != u);
2462 return r;
2463 }
2464
2465 static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2466 const char *name, *old_owner, *new_owner;
2467 Unit *u = userdata;
2468 int r;
2469
2470 assert(message);
2471 assert(u);
2472
2473 r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
2474 if (r < 0) {
2475 bus_log_parse_error(r);
2476 return 0;
2477 }
2478
2479 if (UNIT_VTABLE(u)->bus_name_owner_change)
2480 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2481
2482 return 0;
2483 }
2484
2485 int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
2486 const char *match;
2487
2488 assert(u);
2489 assert(bus);
2490 assert(name);
2491
2492 if (u->match_bus_slot)
2493 return -EBUSY;
2494
2495 match = strjoina("type='signal',"
2496 "sender='org.freedesktop.DBus',"
2497 "path='/org/freedesktop/DBus',"
2498 "interface='org.freedesktop.DBus',"
2499 "member='NameOwnerChanged',"
2500 "arg0='", name, "'",
2501 NULL);
2502
2503 return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
2504 }
2505
2506 int unit_watch_bus_name(Unit *u, const char *name) {
2507 int r;
2508
2509 assert(u);
2510 assert(name);
2511
2512 /* Watch a specific name on the bus. We only support one unit
2513 * watching each name for now. */
2514
2515 if (u->manager->api_bus) {
2516 /* If the bus is already available, install the match directly.
2517 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
2518 r = unit_install_bus_match(u, u->manager->api_bus, name);
2519 if (r < 0)
2520 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
2521 }
2522
2523 r = hashmap_put(u->manager->watch_bus, name, u);
2524 if (r < 0) {
2525 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2526 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
2527 }
2528
2529 return 0;
2530 }
2531
2532 void unit_unwatch_bus_name(Unit *u, const char *name) {
2533 assert(u);
2534 assert(name);
2535
2536 hashmap_remove_value(u->manager->watch_bus, name, u);
2537 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2538 }
2539
2540 bool unit_can_serialize(Unit *u) {
2541 assert(u);
2542
2543 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2544 }
2545
2546 int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
2547 int r;
2548
2549 assert(u);
2550 assert(f);
2551 assert(fds);
2552
2553 if (unit_can_serialize(u)) {
2554 ExecRuntime *rt;
2555
2556 r = UNIT_VTABLE(u)->serialize(u, f, fds);
2557 if (r < 0)
2558 return r;
2559
2560 rt = unit_get_exec_runtime(u);
2561 if (rt) {
2562 r = exec_runtime_serialize(u, rt, f, fds);
2563 if (r < 0)
2564 return r;
2565 }
2566 }
2567
2568 dual_timestamp_serialize(f, "state-change-timestamp", &u->state_change_timestamp);
2569
2570 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2571 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2572 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2573 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
2574
2575 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
2576 dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
2577
2578 if (dual_timestamp_is_set(&u->condition_timestamp))
2579 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
2580
2581 if (dual_timestamp_is_set(&u->assert_timestamp))
2582 unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
2583
2584 unit_serialize_item(u, f, "transient", yes_no(u->transient));
2585 unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
2586
2587 if (u->cgroup_path)
2588 unit_serialize_item(u, f, "cgroup", u->cgroup_path);
2589 unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
2590
2591 if (serialize_jobs) {
2592 if (u->job) {
2593 fprintf(f, "job\n");
2594 job_serialize(u->job, f, fds);
2595 }
2596
2597 if (u->nop_job) {
2598 fprintf(f, "job\n");
2599 job_serialize(u->nop_job, f, fds);
2600 }
2601 }
2602
2603 /* End marker */
2604 fputc('\n', f);
2605 return 0;
2606 }
2607
2608 int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2609 assert(u);
2610 assert(f);
2611 assert(key);
2612
2613 if (!value)
2614 return 0;
2615
2616 fputs(key, f);
2617 fputc('=', f);
2618 fputs(value, f);
2619 fputc('\n', f);
2620
2621 return 1;
2622 }
2623
2624 int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
2625 _cleanup_free_ char *c = NULL;
2626
2627 assert(u);
2628 assert(f);
2629 assert(key);
2630
2631 if (!value)
2632 return 0;
2633
2634 c = cescape(value);
2635 if (!c)
2636 return -ENOMEM;
2637
2638 fputs(key, f);
2639 fputc('=', f);
2640 fputs(c, f);
2641 fputc('\n', f);
2642
2643 return 1;
2644 }
2645
2646 int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
2647 int copy;
2648
2649 assert(u);
2650 assert(f);
2651 assert(key);
2652
2653 if (fd < 0)
2654 return 0;
2655
2656 copy = fdset_put_dup(fds, fd);
2657 if (copy < 0)
2658 return copy;
2659
2660 fprintf(f, "%s=%i\n", key, copy);
2661 return 1;
2662 }
2663
2664 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2665 va_list ap;
2666
2667 assert(u);
2668 assert(f);
2669 assert(key);
2670 assert(format);
2671
2672 fputs(key, f);
2673 fputc('=', f);
2674
2675 va_start(ap, format);
2676 vfprintf(f, format, ap);
2677 va_end(ap);
2678
2679 fputc('\n', f);
2680 }
2681
2682 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2683 ExecRuntime **rt = NULL;
2684 size_t offset;
2685 int r;
2686
2687 assert(u);
2688 assert(f);
2689 assert(fds);
2690
2691 offset = UNIT_VTABLE(u)->exec_runtime_offset;
2692 if (offset > 0)
2693 rt = (ExecRuntime**) ((uint8_t*) u + offset);
2694
2695 for (;;) {
2696 char line[LINE_MAX], *l, *v;
2697 size_t k;
2698
2699 if (!fgets(line, sizeof(line), f)) {
2700 if (feof(f))
2701 return 0;
2702 return -errno;
2703 }
2704
2705 char_array_0(line);
2706 l = strstrip(line);
2707
2708 /* End marker */
2709 if (isempty(l))
2710 break;
2711
2712 k = strcspn(l, "=");
2713
2714 if (l[k] == '=') {
2715 l[k] = 0;
2716 v = l+k+1;
2717 } else
2718 v = l+k;
2719
2720 if (streq(l, "job")) {
2721 if (v[0] == '\0') {
2722 /* new-style serialized job */
2723 Job *j;
2724
2725 j = job_new_raw(u);
2726 if (!j)
2727 return log_oom();
2728
2729 r = job_deserialize(j, f, fds);
2730 if (r < 0) {
2731 job_free(j);
2732 return r;
2733 }
2734
2735 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2736 if (r < 0) {
2737 job_free(j);
2738 return r;
2739 }
2740
2741 r = job_install_deserialized(j);
2742 if (r < 0) {
2743 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2744 job_free(j);
2745 return r;
2746 }
2747 } else /* legacy for pre-44 */
2748 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
2749 continue;
2750 } else if (streq(l, "state-change-timestamp")) {
2751 dual_timestamp_deserialize(v, &u->state_change_timestamp);
2752 continue;
2753 } else if (streq(l, "inactive-exit-timestamp")) {
2754 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
2755 continue;
2756 } else if (streq(l, "active-enter-timestamp")) {
2757 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
2758 continue;
2759 } else if (streq(l, "active-exit-timestamp")) {
2760 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
2761 continue;
2762 } else if (streq(l, "inactive-enter-timestamp")) {
2763 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
2764 continue;
2765 } else if (streq(l, "condition-timestamp")) {
2766 dual_timestamp_deserialize(v, &u->condition_timestamp);
2767 continue;
2768 } else if (streq(l, "assert-timestamp")) {
2769 dual_timestamp_deserialize(v, &u->assert_timestamp);
2770 continue;
2771 } else if (streq(l, "condition-result")) {
2772
2773 r = parse_boolean(v);
2774 if (r < 0)
2775 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2776 else
2777 u->condition_result = r;
2778
2779 continue;
2780
2781 } else if (streq(l, "assert-result")) {
2782
2783 r = parse_boolean(v);
2784 if (r < 0)
2785 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
2786 else
2787 u->assert_result = r;
2788
2789 continue;
2790
2791 } else if (streq(l, "transient")) {
2792
2793 r = parse_boolean(v);
2794 if (r < 0)
2795 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
2796 else
2797 u->transient = r;
2798
2799 continue;
2800
2801 } else if (streq(l, "cpuacct-usage-base")) {
2802
2803 r = safe_atou64(v, &u->cpuacct_usage_base);
2804 if (r < 0)
2805 log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
2806
2807 continue;
2808
2809 } else if (streq(l, "cgroup")) {
2810
2811 r = unit_set_cgroup_path(u, v);
2812 if (r < 0)
2813 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
2814
2815 (void) unit_watch_cgroup(u);
2816
2817 continue;
2818 } else if (streq(l, "cgroup-realized")) {
2819 int b;
2820
2821 b = parse_boolean(v);
2822 if (b < 0)
2823 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
2824 else
2825 u->cgroup_realized = b;
2826
2827 continue;
2828 }
2829
2830 if (unit_can_serialize(u)) {
2831 if (rt) {
2832 r = exec_runtime_deserialize_item(u, rt, l, v, fds);
2833 if (r < 0) {
2834 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
2835 continue;
2836 }
2837
2838 /* Returns positive if key was handled by the call */
2839 if (r > 0)
2840 continue;
2841 }
2842
2843 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
2844 if (r < 0)
2845 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
2846 }
2847 }
2848
2849 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
2850 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
2851 * before 228 where the base for timeouts was not persistent across reboots. */
2852
2853 if (!dual_timestamp_is_set(&u->state_change_timestamp))
2854 dual_timestamp_get(&u->state_change_timestamp);
2855
2856 return 0;
2857 }
2858
2859 int unit_add_node_link(Unit *u, const char *what, bool wants, UnitDependency dep) {
2860 Unit *device;
2861 _cleanup_free_ char *e = NULL;
2862 int r;
2863
2864 assert(u);
2865
2866 /* Adds in links to the device node that this unit is based on */
2867 if (isempty(what))
2868 return 0;
2869
2870 if (!is_device_path(what))
2871 return 0;
2872
2873 /* When device units aren't supported (such as in a
2874 * container), don't create dependencies on them. */
2875 if (!unit_type_supported(UNIT_DEVICE))
2876 return 0;
2877
2878 r = unit_name_from_path(what, ".device", &e);
2879 if (r < 0)
2880 return r;
2881
2882 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
2883 if (r < 0)
2884 return r;
2885
2886 r = unit_add_two_dependencies(u, UNIT_AFTER,
2887 u->manager->running_as == MANAGER_SYSTEM ? dep : UNIT_WANTS,
2888 device, true);
2889 if (r < 0)
2890 return r;
2891
2892 if (wants) {
2893 r = unit_add_dependency(device, UNIT_WANTS, u, false);
2894 if (r < 0)
2895 return r;
2896 }
2897
2898 return 0;
2899 }
2900
2901 int unit_coldplug(Unit *u) {
2902 int r = 0, q = 0;
2903
2904 assert(u);
2905
2906 /* Make sure we don't enter a loop, when coldplugging
2907 * recursively. */
2908 if (u->coldplugged)
2909 return 0;
2910
2911 u->coldplugged = true;
2912
2913 if (UNIT_VTABLE(u)->coldplug)
2914 r = UNIT_VTABLE(u)->coldplug(u);
2915
2916 if (u->job)
2917 q = job_coldplug(u->job);
2918
2919 if (r < 0)
2920 return r;
2921 if (q < 0)
2922 return q;
2923
2924 return 0;
2925 }
2926
2927 static bool fragment_mtime_changed(const char *path, usec_t mtime) {
2928 struct stat st;
2929
2930 if (!path)
2931 return false;
2932
2933 if (stat(path, &st) < 0)
2934 /* What, cannot access this anymore? */
2935 return true;
2936
2937 if (mtime > 0)
2938 /* For non-empty files check the mtime */
2939 return timespec_load(&st.st_mtim) != mtime;
2940 else if (!null_or_empty(&st))
2941 /* For masked files check if they are still so */
2942 return true;
2943
2944 return false;
2945 }
2946
2947 bool unit_need_daemon_reload(Unit *u) {
2948 _cleanup_strv_free_ char **t = NULL;
2949 char **path;
2950 unsigned loaded_cnt, current_cnt;
2951
2952 assert(u);
2953
2954 if (fragment_mtime_changed(u->fragment_path, u->fragment_mtime) ||
2955 fragment_mtime_changed(u->source_path, u->source_mtime))
2956 return true;
2957
2958 (void) unit_find_dropin_paths(u, &t);
2959 loaded_cnt = strv_length(t);
2960 current_cnt = strv_length(u->dropin_paths);
2961
2962 if (loaded_cnt == current_cnt) {
2963 if (loaded_cnt == 0)
2964 return false;
2965
2966 if (strv_overlap(u->dropin_paths, t)) {
2967 STRV_FOREACH(path, u->dropin_paths)
2968 if (fragment_mtime_changed(*path, u->dropin_mtime))
2969 return true;
2970
2971 return false;
2972 }
2973 }
2974
2975 return true;
2976 }
2977
2978 void unit_reset_failed(Unit *u) {
2979 assert(u);
2980
2981 if (UNIT_VTABLE(u)->reset_failed)
2982 UNIT_VTABLE(u)->reset_failed(u);
2983
2984 RATELIMIT_RESET(u->start_limit);
2985 u->start_limit_hit = false;
2986 }
2987
2988 Unit *unit_following(Unit *u) {
2989 assert(u);
2990
2991 if (UNIT_VTABLE(u)->following)
2992 return UNIT_VTABLE(u)->following(u);
2993
2994 return NULL;
2995 }
2996
2997 bool unit_stop_pending(Unit *u) {
2998 assert(u);
2999
3000 /* This call does check the current state of the unit. It's
3001 * hence useful to be called from state change calls of the
3002 * unit itself, where the state isn't updated yet. This is
3003 * different from unit_inactive_or_pending() which checks both
3004 * the current state and for a queued job. */
3005
3006 return u->job && u->job->type == JOB_STOP;
3007 }
3008
3009 bool unit_inactive_or_pending(Unit *u) {
3010 assert(u);
3011
3012 /* Returns true if the unit is inactive or going down */
3013
3014 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
3015 return true;
3016
3017 if (unit_stop_pending(u))
3018 return true;
3019
3020 return false;
3021 }
3022
3023 bool unit_active_or_pending(Unit *u) {
3024 assert(u);
3025
3026 /* Returns true if the unit is active or going up */
3027
3028 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
3029 return true;
3030
3031 if (u->job &&
3032 (u->job->type == JOB_START ||
3033 u->job->type == JOB_RELOAD_OR_START ||
3034 u->job->type == JOB_RESTART))
3035 return true;
3036
3037 return false;
3038 }
3039
3040 int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
3041 assert(u);
3042 assert(w >= 0 && w < _KILL_WHO_MAX);
3043 assert(signo > 0);
3044 assert(signo < _NSIG);
3045
3046 if (!UNIT_VTABLE(u)->kill)
3047 return -EOPNOTSUPP;
3048
3049 return UNIT_VTABLE(u)->kill(u, w, signo, error);
3050 }
3051
3052 static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
3053 Set *pid_set;
3054 int r;
3055
3056 pid_set = set_new(NULL);
3057 if (!pid_set)
3058 return NULL;
3059
3060 /* Exclude the main/control pids from being killed via the cgroup */
3061 if (main_pid > 0) {
3062 r = set_put(pid_set, PID_TO_PTR(main_pid));
3063 if (r < 0)
3064 goto fail;
3065 }
3066
3067 if (control_pid > 0) {
3068 r = set_put(pid_set, PID_TO_PTR(control_pid));
3069 if (r < 0)
3070 goto fail;
3071 }
3072
3073 return pid_set;
3074
3075 fail:
3076 set_free(pid_set);
3077 return NULL;
3078 }
3079
3080 int unit_kill_common(
3081 Unit *u,
3082 KillWho who,
3083 int signo,
3084 pid_t main_pid,
3085 pid_t control_pid,
3086 sd_bus_error *error) {
3087
3088 int r = 0;
3089 bool killed = false;
3090
3091 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
3092 if (main_pid < 0)
3093 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
3094 else if (main_pid == 0)
3095 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3096 }
3097
3098 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
3099 if (control_pid < 0)
3100 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
3101 else if (control_pid == 0)
3102 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3103 }
3104
3105 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
3106 if (control_pid > 0) {
3107 if (kill(control_pid, signo) < 0)
3108 r = -errno;
3109 else
3110 killed = true;
3111 }
3112
3113 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
3114 if (main_pid > 0) {
3115 if (kill(main_pid, signo) < 0)
3116 r = -errno;
3117 else
3118 killed = true;
3119 }
3120
3121 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
3122 _cleanup_set_free_ Set *pid_set = NULL;
3123 int q;
3124
3125 /* Exclude the main/control pids from being killed via the cgroup */
3126 pid_set = unit_pid_set(main_pid, control_pid);
3127 if (!pid_set)
3128 return -ENOMEM;
3129
3130 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set);
3131 if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3132 r = q;
3133 else
3134 killed = true;
3135 }
3136
3137 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL))
3138 return -ESRCH;
3139
3140 return r;
3141 }
3142
3143 int unit_following_set(Unit *u, Set **s) {
3144 assert(u);
3145 assert(s);
3146
3147 if (UNIT_VTABLE(u)->following_set)
3148 return UNIT_VTABLE(u)->following_set(u, s);
3149
3150 *s = NULL;
3151 return 0;
3152 }
3153
3154 UnitFileState unit_get_unit_file_state(Unit *u) {
3155 int r;
3156
3157 assert(u);
3158
3159 if (u->unit_file_state < 0 && u->fragment_path) {
3160 r = unit_file_get_state(
3161 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
3162 NULL,
3163 basename(u->fragment_path),
3164 &u->unit_file_state);
3165 if (r < 0)
3166 u->unit_file_state = UNIT_FILE_BAD;
3167 }
3168
3169 return u->unit_file_state;
3170 }
3171
3172 int unit_get_unit_file_preset(Unit *u) {
3173 assert(u);
3174
3175 if (u->unit_file_preset < 0 && u->fragment_path)
3176 u->unit_file_preset = unit_file_query_preset(
3177 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
3178 NULL,
3179 basename(u->fragment_path));
3180
3181 return u->unit_file_preset;
3182 }
3183
3184 Unit* unit_ref_set(UnitRef *ref, Unit *u) {
3185 assert(ref);
3186 assert(u);
3187
3188 if (ref->unit)
3189 unit_ref_unset(ref);
3190
3191 ref->unit = u;
3192 LIST_PREPEND(refs, u->refs, ref);
3193 return u;
3194 }
3195
3196 void unit_ref_unset(UnitRef *ref) {
3197 assert(ref);
3198
3199 if (!ref->unit)
3200 return;
3201
3202 LIST_REMOVE(refs, ref->unit->refs, ref);
3203 ref->unit = NULL;
3204 }
3205
3206 int unit_patch_contexts(Unit *u) {
3207 CGroupContext *cc;
3208 ExecContext *ec;
3209 unsigned i;
3210 int r;
3211
3212 assert(u);
3213
3214 /* Patch in the manager defaults into the exec and cgroup
3215 * contexts, _after_ the rest of the settings have been
3216 * initialized */
3217
3218 ec = unit_get_exec_context(u);
3219 if (ec) {
3220 /* This only copies in the ones that need memory */
3221 for (i = 0; i < _RLIMIT_MAX; i++)
3222 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
3223 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
3224 if (!ec->rlimit[i])
3225 return -ENOMEM;
3226 }
3227
3228 if (u->manager->running_as == MANAGER_USER &&
3229 !ec->working_directory) {
3230
3231 r = get_home_dir(&ec->working_directory);
3232 if (r < 0)
3233 return r;
3234
3235 /* Allow user services to run, even if the
3236 * home directory is missing */
3237 ec->working_directory_missing_ok = true;
3238 }
3239
3240 if (u->manager->running_as == MANAGER_USER &&
3241 (ec->syscall_whitelist ||
3242 !set_isempty(ec->syscall_filter) ||
3243 !set_isempty(ec->syscall_archs) ||
3244 ec->address_families_whitelist ||
3245 !set_isempty(ec->address_families)))
3246 ec->no_new_privileges = true;
3247
3248 if (ec->private_devices)
3249 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_MKNOD);
3250 }
3251
3252 cc = unit_get_cgroup_context(u);
3253 if (cc) {
3254
3255 if (ec &&
3256 ec->private_devices &&
3257 cc->device_policy == CGROUP_AUTO)
3258 cc->device_policy = CGROUP_CLOSED;
3259 }
3260
3261 return 0;
3262 }
3263
3264 ExecContext *unit_get_exec_context(Unit *u) {
3265 size_t offset;
3266 assert(u);
3267
3268 if (u->type < 0)
3269 return NULL;
3270
3271 offset = UNIT_VTABLE(u)->exec_context_offset;
3272 if (offset <= 0)
3273 return NULL;
3274
3275 return (ExecContext*) ((uint8_t*) u + offset);
3276 }
3277
3278 KillContext *unit_get_kill_context(Unit *u) {
3279 size_t offset;
3280 assert(u);
3281
3282 if (u->type < 0)
3283 return NULL;
3284
3285 offset = UNIT_VTABLE(u)->kill_context_offset;
3286 if (offset <= 0)
3287 return NULL;
3288
3289 return (KillContext*) ((uint8_t*) u + offset);
3290 }
3291
3292 CGroupContext *unit_get_cgroup_context(Unit *u) {
3293 size_t offset;
3294
3295 if (u->type < 0)
3296 return NULL;
3297
3298 offset = UNIT_VTABLE(u)->cgroup_context_offset;
3299 if (offset <= 0)
3300 return NULL;
3301
3302 return (CGroupContext*) ((uint8_t*) u + offset);
3303 }
3304
3305 ExecRuntime *unit_get_exec_runtime(Unit *u) {
3306 size_t offset;
3307
3308 if (u->type < 0)
3309 return NULL;
3310
3311 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3312 if (offset <= 0)
3313 return NULL;
3314
3315 return *(ExecRuntime**) ((uint8_t*) u + offset);
3316 }
3317
3318 static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) {
3319 assert(u);
3320
3321 if (u->manager->running_as == MANAGER_USER) {
3322 int r;
3323
3324 if (mode == UNIT_PERSISTENT && !transient)
3325 r = user_config_home(dir);
3326 else
3327 r = user_runtime_dir(dir);
3328 if (r == 0)
3329 return -ENOENT;
3330
3331 return r;
3332 }
3333
3334 if (mode == UNIT_PERSISTENT && !transient)
3335 *dir = strdup("/etc/systemd/system");
3336 else
3337 *dir = strdup("/run/systemd/system");
3338 if (!*dir)
3339 return -ENOMEM;
3340
3341 return 0;
3342 }
3343
3344 int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
3345
3346 _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL;
3347 int r;
3348
3349 assert(u);
3350
3351 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3352 return 0;
3353
3354 r = unit_drop_in_dir(u, mode, u->transient, &dir);
3355 if (r < 0)
3356 return r;
3357
3358 r = write_drop_in(dir, u->id, 50, name, data);
3359 if (r < 0)
3360 return r;
3361
3362 r = drop_in_file(dir, u->id, 50, name, &p, &q);
3363 if (r < 0)
3364 return r;
3365
3366 r = strv_extend(&u->dropin_paths, q);
3367 if (r < 0)
3368 return r;
3369
3370 strv_sort(u->dropin_paths);
3371 strv_uniq(u->dropin_paths);
3372
3373 u->dropin_mtime = now(CLOCK_REALTIME);
3374
3375 return 0;
3376 }
3377
3378 int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3379 _cleanup_free_ char *p = NULL;
3380 va_list ap;
3381 int r;
3382
3383 assert(u);
3384 assert(name);
3385 assert(format);
3386
3387 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3388 return 0;
3389
3390 va_start(ap, format);
3391 r = vasprintf(&p, format, ap);
3392 va_end(ap);
3393
3394 if (r < 0)
3395 return -ENOMEM;
3396
3397 return unit_write_drop_in(u, mode, name, p);
3398 }
3399
3400 int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
3401 _cleanup_free_ char *ndata = NULL;
3402
3403 assert(u);
3404 assert(name);
3405 assert(data);
3406
3407 if (!UNIT_VTABLE(u)->private_section)
3408 return -EINVAL;
3409
3410 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3411 return 0;
3412
3413 ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL);
3414 if (!ndata)
3415 return -ENOMEM;
3416
3417 return unit_write_drop_in(u, mode, name, ndata);
3418 }
3419
3420 int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3421 _cleanup_free_ char *p = NULL;
3422 va_list ap;
3423 int r;
3424
3425 assert(u);
3426 assert(name);
3427 assert(format);
3428
3429 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3430 return 0;
3431
3432 va_start(ap, format);
3433 r = vasprintf(&p, format, ap);
3434 va_end(ap);
3435
3436 if (r < 0)
3437 return -ENOMEM;
3438
3439 return unit_write_drop_in_private(u, mode, name, p);
3440 }
3441
3442 int unit_make_transient(Unit *u) {
3443 assert(u);
3444
3445 if (!UNIT_VTABLE(u)->can_transient)
3446 return -EOPNOTSUPP;
3447
3448 u->load_state = UNIT_STUB;
3449 u->load_error = 0;
3450 u->transient = true;
3451
3452 u->fragment_path = mfree(u->fragment_path);
3453 u->source_path = mfree(u->source_path);
3454 u->dropin_paths = strv_free(u->dropin_paths);
3455 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
3456
3457 unit_add_to_dbus_queue(u);
3458 unit_add_to_gc_queue(u);
3459 unit_add_to_load_queue(u);
3460
3461 return 0;
3462 }
3463
3464 int unit_kill_context(
3465 Unit *u,
3466 KillContext *c,
3467 KillOperation k,
3468 pid_t main_pid,
3469 pid_t control_pid,
3470 bool main_pid_alien) {
3471
3472 bool wait_for_exit = false;
3473 int sig, r;
3474
3475 assert(u);
3476 assert(c);
3477
3478 if (c->kill_mode == KILL_NONE)
3479 return 0;
3480
3481 switch (k) {
3482 case KILL_KILL:
3483 sig = SIGKILL;
3484 break;
3485 case KILL_ABORT:
3486 sig = SIGABRT;
3487 break;
3488 case KILL_TERMINATE:
3489 sig = c->kill_signal;
3490 break;
3491 default:
3492 assert_not_reached("KillOperation unknown");
3493 }
3494
3495 if (main_pid > 0) {
3496 r = kill_and_sigcont(main_pid, sig);
3497
3498 if (r < 0 && r != -ESRCH) {
3499 _cleanup_free_ char *comm = NULL;
3500 get_process_comm(main_pid, &comm);
3501
3502 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
3503 } else {
3504 if (!main_pid_alien)
3505 wait_for_exit = true;
3506
3507 if (c->send_sighup && k == KILL_TERMINATE)
3508 (void) kill(main_pid, SIGHUP);
3509 }
3510 }
3511
3512 if (control_pid > 0) {
3513 r = kill_and_sigcont(control_pid, sig);
3514
3515 if (r < 0 && r != -ESRCH) {
3516 _cleanup_free_ char *comm = NULL;
3517 get_process_comm(control_pid, &comm);
3518
3519 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
3520 } else {
3521 wait_for_exit = true;
3522
3523 if (c->send_sighup && k == KILL_TERMINATE)
3524 (void) kill(control_pid, SIGHUP);
3525 }
3526 }
3527
3528 if (u->cgroup_path &&
3529 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
3530 _cleanup_set_free_ Set *pid_set = NULL;
3531
3532 /* Exclude the main/control pids from being killed via the cgroup */
3533 pid_set = unit_pid_set(main_pid, control_pid);
3534 if (!pid_set)
3535 return -ENOMEM;
3536
3537 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set);
3538 if (r < 0) {
3539 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3540 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
3541
3542 } else if (r > 0) {
3543
3544 /* FIXME: For now, on the legacy hierarchy, we
3545 * will not wait for the cgroup members to die
3546 * if we are running in a container or if this
3547 * is a delegation unit, simply because cgroup
3548 * notification is unreliable in these
3549 * cases. It doesn't work at all in
3550 * containers, and outside of containers it
3551 * can be confused easily by left-over
3552 * directories in the cgroup -- which however
3553 * should not exist in non-delegated units. On
3554 * the unified hierarchy that's different,
3555 * there we get proper events. Hence rely on
3556 * them.*/
3557
3558 if (cg_unified() > 0 ||
3559 (detect_container() == 0 && !unit_cgroup_delegate(u)))
3560 wait_for_exit = true;
3561
3562 if (c->send_sighup && k != KILL_KILL) {
3563 set_free(pid_set);
3564
3565 pid_set = unit_pid_set(main_pid, control_pid);
3566 if (!pid_set)
3567 return -ENOMEM;
3568
3569 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set);
3570 }
3571 }
3572 }
3573
3574 return wait_for_exit;
3575 }
3576
3577 int unit_require_mounts_for(Unit *u, const char *path) {
3578 char prefix[strlen(path) + 1], *p;
3579 int r;
3580
3581 assert(u);
3582 assert(path);
3583
3584 /* Registers a unit for requiring a certain path and all its
3585 * prefixes. We keep a simple array of these paths in the
3586 * unit, since its usually short. However, we build a prefix
3587 * table for all possible prefixes so that new appearing mount
3588 * units can easily determine which units to make themselves a
3589 * dependency of. */
3590
3591 if (!path_is_absolute(path))
3592 return -EINVAL;
3593
3594 p = strdup(path);
3595 if (!p)
3596 return -ENOMEM;
3597
3598 path_kill_slashes(p);
3599
3600 if (!path_is_safe(p)) {
3601 free(p);
3602 return -EPERM;
3603 }
3604
3605 if (strv_contains(u->requires_mounts_for, p)) {
3606 free(p);
3607 return 0;
3608 }
3609
3610 r = strv_consume(&u->requires_mounts_for, p);
3611 if (r < 0)
3612 return r;
3613
3614 PATH_FOREACH_PREFIX_MORE(prefix, p) {
3615 Set *x;
3616
3617 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
3618 if (!x) {
3619 char *q;
3620
3621 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
3622 if (r < 0)
3623 return r;
3624
3625 q = strdup(prefix);
3626 if (!q)
3627 return -ENOMEM;
3628
3629 x = set_new(NULL);
3630 if (!x) {
3631 free(q);
3632 return -ENOMEM;
3633 }
3634
3635 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
3636 if (r < 0) {
3637 free(q);
3638 set_free(x);
3639 return r;
3640 }
3641 }
3642
3643 r = set_put(x, u);
3644 if (r < 0)
3645 return r;
3646 }
3647
3648 return 0;
3649 }
3650
3651 int unit_setup_exec_runtime(Unit *u) {
3652 ExecRuntime **rt;
3653 size_t offset;
3654 Iterator i;
3655 Unit *other;
3656
3657 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3658 assert(offset > 0);
3659
3660 /* Check if there already is an ExecRuntime for this unit? */
3661 rt = (ExecRuntime**) ((uint8_t*) u + offset);
3662 if (*rt)
3663 return 0;
3664
3665 /* Try to get it from somebody else */
3666 SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
3667
3668 *rt = unit_get_exec_runtime(other);
3669 if (*rt) {
3670 exec_runtime_ref(*rt);
3671 return 0;
3672 }
3673 }
3674
3675 return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
3676 }
3677
3678 bool unit_type_supported(UnitType t) {
3679 if (_unlikely_(t < 0))
3680 return false;
3681 if (_unlikely_(t >= _UNIT_TYPE_MAX))
3682 return false;
3683
3684 if (!unit_vtable[t]->supported)
3685 return true;
3686
3687 return unit_vtable[t]->supported();
3688 }
3689
3690 void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
3691 int r;
3692
3693 assert(u);
3694 assert(where);
3695
3696 r = dir_is_empty(where);
3697 if (r > 0)
3698 return;
3699 if (r < 0) {
3700 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
3701 return;
3702 }
3703
3704 log_struct(LOG_NOTICE,
3705 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3706 LOG_UNIT_ID(u),
3707 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
3708 "WHERE=%s", where,
3709 NULL);
3710 }
3711
3712 int unit_fail_if_symlink(Unit *u, const char* where) {
3713 int r;
3714
3715 assert(u);
3716 assert(where);
3717
3718 r = is_symlink(where);
3719 if (r < 0) {
3720 log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
3721 return 0;
3722 }
3723 if (r == 0)
3724 return 0;
3725
3726 log_struct(LOG_ERR,
3727 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3728 LOG_UNIT_ID(u),
3729 LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
3730 "WHERE=%s", where,
3731 NULL);
3732
3733 return -ELOOP;
3734 }
3735
3736 bool unit_is_pristine(Unit *u) {
3737 assert(u);
3738
3739 /* Check if the unit already exists or is already around,
3740 * in a number of different ways. Note that to cater for unit
3741 * types such as slice, we are generally fine with units that
3742 * are marked UNIT_LOADED even even though nothing was
3743 * actually loaded, as those unit types don't require a file
3744 * on disk to validly load. */
3745
3746 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
3747 u->fragment_path ||
3748 u->source_path ||
3749 !strv_isempty(u->dropin_paths) ||
3750 u->job ||
3751 u->merged_into);
3752 }