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