]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/unit.c
44f1d5e206ed690782f30178bed5aed2aad9d897
[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 Unit *t;
1087 int r;
1088
1089 assert(u);
1090
1091 /* Load a .{service,socket,...} file */
1092 r = unit_load_fragment(u);
1093 if (r < 0)
1094 return r;
1095
1096 if (u->load_state == UNIT_STUB)
1097 return -ENOENT;
1098
1099 /* If the unit is an alias and the final unit has already been
1100 * loaded, there's no point in reloading the dropins one more time. */
1101 t = unit_follow_merge(u);
1102 if (t != u && t->load_state != UNIT_STUB)
1103 return 0;
1104
1105 return unit_load_dropin(t);
1106 }
1107
1108 /* Common implementation for multiple backends */
1109 int unit_load_fragment_and_dropin_optional(Unit *u) {
1110 Unit *t;
1111 int r;
1112
1113 assert(u);
1114
1115 /* Same as unit_load_fragment_and_dropin(), but whether
1116 * something can be loaded or not doesn't matter. */
1117
1118 /* Load a .service file */
1119 r = unit_load_fragment(u);
1120 if (r < 0)
1121 return r;
1122
1123 if (u->load_state == UNIT_STUB)
1124 u->load_state = UNIT_LOADED;
1125
1126 /* If the unit is an alias and the final unit has already been
1127 * loaded, there's no point in reloading the dropins one more time. */
1128 t = unit_follow_merge(u);
1129 if (t != u && t->load_state != UNIT_STUB)
1130 return 0;
1131
1132 return unit_load_dropin(t);
1133 }
1134
1135 int unit_add_default_target_dependency(Unit *u, Unit *target) {
1136 assert(u);
1137 assert(target);
1138
1139 if (target->type != UNIT_TARGET)
1140 return 0;
1141
1142 /* Only add the dependency if both units are loaded, so that
1143 * that loop check below is reliable */
1144 if (u->load_state != UNIT_LOADED ||
1145 target->load_state != UNIT_LOADED)
1146 return 0;
1147
1148 /* If either side wants no automatic dependencies, then let's
1149 * skip this */
1150 if (!u->default_dependencies ||
1151 !target->default_dependencies)
1152 return 0;
1153
1154 /* Don't create loops */
1155 if (set_get(target->dependencies[UNIT_BEFORE], u))
1156 return 0;
1157
1158 return unit_add_dependency(target, UNIT_AFTER, u, true);
1159 }
1160
1161 static int unit_add_target_dependencies(Unit *u) {
1162
1163 static const UnitDependency deps[] = {
1164 UNIT_REQUIRED_BY,
1165 UNIT_REQUISITE_OF,
1166 UNIT_WANTED_BY,
1167 UNIT_BOUND_BY
1168 };
1169
1170 Unit *target;
1171 Iterator i;
1172 unsigned k;
1173 int r = 0;
1174
1175 assert(u);
1176
1177 for (k = 0; k < ELEMENTSOF(deps); k++)
1178 SET_FOREACH(target, u->dependencies[deps[k]], i) {
1179 r = unit_add_default_target_dependency(u, target);
1180 if (r < 0)
1181 return r;
1182 }
1183
1184 return r;
1185 }
1186
1187 static int unit_add_slice_dependencies(Unit *u) {
1188 assert(u);
1189
1190 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1191 return 0;
1192
1193 if (UNIT_ISSET(u->slice))
1194 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
1195
1196 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1197 return 0;
1198
1199 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
1200 }
1201
1202 static int unit_add_mount_dependencies(Unit *u) {
1203 char **i;
1204 int r;
1205
1206 assert(u);
1207
1208 STRV_FOREACH(i, u->requires_mounts_for) {
1209 char prefix[strlen(*i) + 1];
1210
1211 PATH_FOREACH_PREFIX_MORE(prefix, *i) {
1212 _cleanup_free_ char *p = NULL;
1213 Unit *m;
1214
1215 r = unit_name_from_path(prefix, ".mount", &p);
1216 if (r < 0)
1217 return r;
1218
1219 m = manager_get_unit(u->manager, p);
1220 if (!m) {
1221 /* Make sure to load the mount unit if
1222 * it exists. If so the dependencies
1223 * on this unit will be added later
1224 * during the loading of the mount
1225 * unit. */
1226 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
1227 continue;
1228 }
1229 if (m == u)
1230 continue;
1231
1232 if (m->load_state != UNIT_LOADED)
1233 continue;
1234
1235 r = unit_add_dependency(u, UNIT_AFTER, m, true);
1236 if (r < 0)
1237 return r;
1238
1239 if (m->fragment_path) {
1240 r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
1241 if (r < 0)
1242 return r;
1243 }
1244 }
1245 }
1246
1247 return 0;
1248 }
1249
1250 static int unit_add_startup_units(Unit *u) {
1251 CGroupContext *c;
1252 int r;
1253
1254 c = unit_get_cgroup_context(u);
1255 if (!c)
1256 return 0;
1257
1258 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1259 c->startup_io_weight == CGROUP_WEIGHT_INVALID &&
1260 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
1261 return 0;
1262
1263 r = set_ensure_allocated(&u->manager->startup_units, NULL);
1264 if (r < 0)
1265 return r;
1266
1267 return set_put(u->manager->startup_units, u);
1268 }
1269
1270 int unit_load(Unit *u) {
1271 int r;
1272
1273 assert(u);
1274
1275 if (u->in_load_queue) {
1276 LIST_REMOVE(load_queue, u->manager->load_queue, u);
1277 u->in_load_queue = false;
1278 }
1279
1280 if (u->type == _UNIT_TYPE_INVALID)
1281 return -EINVAL;
1282
1283 if (u->load_state != UNIT_STUB)
1284 return 0;
1285
1286 if (u->transient_file) {
1287 r = fflush_and_check(u->transient_file);
1288 if (r < 0)
1289 goto fail;
1290
1291 fclose(u->transient_file);
1292 u->transient_file = NULL;
1293
1294 u->fragment_mtime = now(CLOCK_REALTIME);
1295 }
1296
1297 if (UNIT_VTABLE(u)->load) {
1298 r = UNIT_VTABLE(u)->load(u);
1299 if (r < 0)
1300 goto fail;
1301 }
1302
1303 if (u->load_state == UNIT_STUB) {
1304 r = -ENOENT;
1305 goto fail;
1306 }
1307
1308 if (u->load_state == UNIT_LOADED) {
1309
1310 r = unit_add_target_dependencies(u);
1311 if (r < 0)
1312 goto fail;
1313
1314 r = unit_add_slice_dependencies(u);
1315 if (r < 0)
1316 goto fail;
1317
1318 r = unit_add_mount_dependencies(u);
1319 if (r < 0)
1320 goto fail;
1321
1322 r = unit_add_startup_units(u);
1323 if (r < 0)
1324 goto fail;
1325
1326 if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
1327 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1328 r = -EINVAL;
1329 goto fail;
1330 }
1331
1332 unit_update_cgroup_members_masks(u);
1333 }
1334
1335 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
1336
1337 unit_add_to_dbus_queue(unit_follow_merge(u));
1338 unit_add_to_gc_queue(u);
1339
1340 return 0;
1341
1342 fail:
1343 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
1344 u->load_error = r;
1345 unit_add_to_dbus_queue(u);
1346 unit_add_to_gc_queue(u);
1347
1348 log_unit_debug_errno(u, r, "Failed to load configuration: %m");
1349
1350 return r;
1351 }
1352
1353 static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
1354 Condition *c;
1355 int triggered = -1;
1356
1357 assert(u);
1358 assert(to_string);
1359
1360 /* If the condition list is empty, then it is true */
1361 if (!first)
1362 return true;
1363
1364 /* Otherwise, if all of the non-trigger conditions apply and
1365 * if any of the trigger conditions apply (unless there are
1366 * none) we return true */
1367 LIST_FOREACH(conditions, c, first) {
1368 int r;
1369
1370 r = condition_test(c);
1371 if (r < 0)
1372 log_unit_warning(u,
1373 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1374 to_string(c->type),
1375 c->trigger ? "|" : "",
1376 c->negate ? "!" : "",
1377 c->parameter);
1378 else
1379 log_unit_debug(u,
1380 "%s=%s%s%s %s.",
1381 to_string(c->type),
1382 c->trigger ? "|" : "",
1383 c->negate ? "!" : "",
1384 c->parameter,
1385 condition_result_to_string(c->result));
1386
1387 if (!c->trigger && r <= 0)
1388 return false;
1389
1390 if (c->trigger && triggered <= 0)
1391 triggered = r > 0;
1392 }
1393
1394 return triggered != 0;
1395 }
1396
1397 static bool unit_condition_test(Unit *u) {
1398 assert(u);
1399
1400 dual_timestamp_get(&u->condition_timestamp);
1401 u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
1402
1403 return u->condition_result;
1404 }
1405
1406 static bool unit_assert_test(Unit *u) {
1407 assert(u);
1408
1409 dual_timestamp_get(&u->assert_timestamp);
1410 u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
1411
1412 return u->assert_result;
1413 }
1414
1415 void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
1416 DISABLE_WARNING_FORMAT_NONLITERAL;
1417 manager_status_printf(u->manager, STATUS_TYPE_NORMAL, status, unit_status_msg_format, unit_description(u));
1418 REENABLE_WARNING;
1419 }
1420
1421 _pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
1422 const char *format;
1423 const UnitStatusMessageFormats *format_table;
1424
1425 assert(u);
1426 assert(IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD));
1427
1428 if (t != JOB_RELOAD) {
1429 format_table = &UNIT_VTABLE(u)->status_message_formats;
1430 if (format_table) {
1431 format = format_table->starting_stopping[t == JOB_STOP];
1432 if (format)
1433 return format;
1434 }
1435 }
1436
1437 /* Return generic strings */
1438 if (t == JOB_START)
1439 return "Starting %s.";
1440 else if (t == JOB_STOP)
1441 return "Stopping %s.";
1442 else
1443 return "Reloading %s.";
1444 }
1445
1446 static void unit_status_print_starting_stopping(Unit *u, JobType t) {
1447 const char *format;
1448
1449 assert(u);
1450
1451 /* Reload status messages have traditionally not been printed to console. */
1452 if (!IN_SET(t, JOB_START, JOB_STOP))
1453 return;
1454
1455 format = unit_get_status_message_format(u, t);
1456
1457 DISABLE_WARNING_FORMAT_NONLITERAL;
1458 unit_status_printf(u, "", format);
1459 REENABLE_WARNING;
1460 }
1461
1462 static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
1463 const char *format;
1464 char buf[LINE_MAX];
1465 sd_id128_t mid;
1466
1467 assert(u);
1468
1469 if (!IN_SET(t, JOB_START, JOB_STOP, JOB_RELOAD))
1470 return;
1471
1472 if (log_on_console())
1473 return;
1474
1475 /* We log status messages for all units and all operations. */
1476
1477 format = unit_get_status_message_format(u, t);
1478
1479 DISABLE_WARNING_FORMAT_NONLITERAL;
1480 snprintf(buf, sizeof buf, format, unit_description(u));
1481 REENABLE_WARNING;
1482
1483 mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
1484 t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
1485 SD_MESSAGE_UNIT_RELOADING;
1486
1487 /* Note that we deliberately use LOG_MESSAGE() instead of
1488 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1489 * closely what is written to screen using the status output,
1490 * which is supposed the highest level, friendliest output
1491 * possible, which means we should avoid the low-level unit
1492 * name. */
1493 log_struct(LOG_INFO,
1494 LOG_MESSAGE_ID(mid),
1495 LOG_UNIT_ID(u),
1496 LOG_MESSAGE("%s", buf),
1497 NULL);
1498 }
1499
1500 void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
1501 assert(u);
1502 assert(t >= 0);
1503 assert(t < _JOB_TYPE_MAX);
1504
1505 unit_status_log_starting_stopping_reloading(u, t);
1506 unit_status_print_starting_stopping(u, t);
1507 }
1508
1509 int unit_start_limit_test(Unit *u) {
1510 assert(u);
1511
1512 if (ratelimit_test(&u->start_limit)) {
1513 u->start_limit_hit = false;
1514 return 0;
1515 }
1516
1517 log_unit_warning(u, "Start request repeated too quickly.");
1518 u->start_limit_hit = true;
1519
1520 return emergency_action(u->manager, u->start_limit_action, u->reboot_arg, "unit failed");
1521 }
1522
1523 bool unit_shall_confirm_spawn(Unit *u) {
1524
1525 if (manager_is_confirm_spawn_disabled(u->manager))
1526 return false;
1527
1528 /* For some reasons units remaining in the same process group
1529 * as PID 1 fail to acquire the console even if it's not used
1530 * by any process. So skip the confirmation question for them. */
1531 return !unit_get_exec_context(u)->same_pgrp;
1532 }
1533
1534 /* Errors:
1535 * -EBADR: This unit type does not support starting.
1536 * -EALREADY: Unit is already started.
1537 * -EAGAIN: An operation is already in progress. Retry later.
1538 * -ECANCELED: Too many requests for now.
1539 * -EPROTO: Assert failed
1540 * -EINVAL: Unit not loaded
1541 * -EOPNOTSUPP: Unit type not supported
1542 */
1543 int unit_start(Unit *u) {
1544 UnitActiveState state;
1545 Unit *following;
1546
1547 assert(u);
1548
1549 /* If this is already started, then this will succeed. Note
1550 * that this will even succeed if this unit is not startable
1551 * by the user. This is relied on to detect when we need to
1552 * wait for units and when waiting is finished. */
1553 state = unit_active_state(u);
1554 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1555 return -EALREADY;
1556
1557 /* Units that aren't loaded cannot be started */
1558 if (u->load_state != UNIT_LOADED)
1559 return -EINVAL;
1560
1561 /* If the conditions failed, don't do anything at all. If we
1562 * already are activating this call might still be useful to
1563 * speed up activation in case there is some hold-off time,
1564 * but we don't want to recheck the condition in that case. */
1565 if (state != UNIT_ACTIVATING &&
1566 !unit_condition_test(u)) {
1567 log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
1568 return -EALREADY;
1569 }
1570
1571 /* If the asserts failed, fail the entire job */
1572 if (state != UNIT_ACTIVATING &&
1573 !unit_assert_test(u)) {
1574 log_unit_notice(u, "Starting requested but asserts failed.");
1575 return -EPROTO;
1576 }
1577
1578 /* Units of types that aren't supported cannot be
1579 * started. Note that we do this test only after the condition
1580 * checks, so that we rather return condition check errors
1581 * (which are usually not considered a true failure) than "not
1582 * supported" errors (which are considered a failure).
1583 */
1584 if (!unit_supported(u))
1585 return -EOPNOTSUPP;
1586
1587 /* Forward to the main object, if we aren't it. */
1588 following = unit_following(u);
1589 if (following) {
1590 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
1591 return unit_start(following);
1592 }
1593
1594 /* If it is stopped, but we cannot start it, then fail */
1595 if (!UNIT_VTABLE(u)->start)
1596 return -EBADR;
1597
1598 /* We don't suppress calls to ->start() here when we are
1599 * already starting, to allow this request to be used as a
1600 * "hurry up" call, for example when the unit is in some "auto
1601 * restart" state where it waits for a holdoff timer to elapse
1602 * before it will start again. */
1603
1604 unit_add_to_dbus_queue(u);
1605
1606 return UNIT_VTABLE(u)->start(u);
1607 }
1608
1609 bool unit_can_start(Unit *u) {
1610 assert(u);
1611
1612 if (u->load_state != UNIT_LOADED)
1613 return false;
1614
1615 if (!unit_supported(u))
1616 return false;
1617
1618 return !!UNIT_VTABLE(u)->start;
1619 }
1620
1621 bool unit_can_isolate(Unit *u) {
1622 assert(u);
1623
1624 return unit_can_start(u) &&
1625 u->allow_isolate;
1626 }
1627
1628 /* Errors:
1629 * -EBADR: This unit type does not support stopping.
1630 * -EALREADY: Unit is already stopped.
1631 * -EAGAIN: An operation is already in progress. Retry later.
1632 */
1633 int unit_stop(Unit *u) {
1634 UnitActiveState state;
1635 Unit *following;
1636
1637 assert(u);
1638
1639 state = unit_active_state(u);
1640 if (UNIT_IS_INACTIVE_OR_FAILED(state))
1641 return -EALREADY;
1642
1643 following = unit_following(u);
1644 if (following) {
1645 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
1646 return unit_stop(following);
1647 }
1648
1649 if (!UNIT_VTABLE(u)->stop)
1650 return -EBADR;
1651
1652 unit_add_to_dbus_queue(u);
1653
1654 return UNIT_VTABLE(u)->stop(u);
1655 }
1656
1657 bool unit_can_stop(Unit *u) {
1658 assert(u);
1659
1660 if (!unit_supported(u))
1661 return false;
1662
1663 if (u->perpetual)
1664 return false;
1665
1666 return !!UNIT_VTABLE(u)->stop;
1667 }
1668
1669 /* Errors:
1670 * -EBADR: This unit type does not support reloading.
1671 * -ENOEXEC: Unit is not started.
1672 * -EAGAIN: An operation is already in progress. Retry later.
1673 */
1674 int unit_reload(Unit *u) {
1675 UnitActiveState state;
1676 Unit *following;
1677
1678 assert(u);
1679
1680 if (u->load_state != UNIT_LOADED)
1681 return -EINVAL;
1682
1683 if (!unit_can_reload(u))
1684 return -EBADR;
1685
1686 state = unit_active_state(u);
1687 if (state == UNIT_RELOADING)
1688 return -EALREADY;
1689
1690 if (state != UNIT_ACTIVE) {
1691 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
1692 return -ENOEXEC;
1693 }
1694
1695 following = unit_following(u);
1696 if (following) {
1697 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
1698 return unit_reload(following);
1699 }
1700
1701 unit_add_to_dbus_queue(u);
1702
1703 return UNIT_VTABLE(u)->reload(u);
1704 }
1705
1706 bool unit_can_reload(Unit *u) {
1707 assert(u);
1708
1709 if (!UNIT_VTABLE(u)->reload)
1710 return false;
1711
1712 if (!UNIT_VTABLE(u)->can_reload)
1713 return true;
1714
1715 return UNIT_VTABLE(u)->can_reload(u);
1716 }
1717
1718 static void unit_check_unneeded(Unit *u) {
1719
1720 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1721
1722 static const UnitDependency needed_dependencies[] = {
1723 UNIT_REQUIRED_BY,
1724 UNIT_REQUISITE_OF,
1725 UNIT_WANTED_BY,
1726 UNIT_BOUND_BY,
1727 };
1728
1729 Unit *other;
1730 Iterator i;
1731 unsigned j;
1732 int r;
1733
1734 assert(u);
1735
1736 /* If this service shall be shut down when unneeded then do
1737 * so. */
1738
1739 if (!u->stop_when_unneeded)
1740 return;
1741
1742 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1743 return;
1744
1745 for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
1746 SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
1747 if (unit_active_or_pending(other))
1748 return;
1749
1750 /* If stopping a unit fails continuously we might enter a stop
1751 * loop here, hence stop acting on the service being
1752 * unnecessary after a while. */
1753 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1754 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1755 return;
1756 }
1757
1758 log_unit_info(u, "Unit not needed anymore. Stopping.");
1759
1760 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
1761 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
1762 if (r < 0)
1763 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1764 }
1765
1766 static void unit_check_binds_to(Unit *u) {
1767 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1768 bool stop = false;
1769 Unit *other;
1770 Iterator i;
1771 int r;
1772
1773 assert(u);
1774
1775 if (u->job)
1776 return;
1777
1778 if (unit_active_state(u) != UNIT_ACTIVE)
1779 return;
1780
1781 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
1782 if (other->job)
1783 continue;
1784
1785 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
1786 continue;
1787
1788 stop = true;
1789 break;
1790 }
1791
1792 if (!stop)
1793 return;
1794
1795 /* If stopping a unit fails continuously we might enter a stop
1796 * loop here, hence stop acting on the service being
1797 * unnecessary after a while. */
1798 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1799 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
1800 return;
1801 }
1802
1803 assert(other);
1804 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
1805
1806 /* A unit we need to run is gone. Sniff. Let's stop this. */
1807 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
1808 if (r < 0)
1809 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
1810 }
1811
1812 static void retroactively_start_dependencies(Unit *u) {
1813 Iterator i;
1814 Unit *other;
1815
1816 assert(u);
1817 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1818
1819 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1820 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1821 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1822 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
1823
1824 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
1825 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1826 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1827 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
1828
1829 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1830 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
1831 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
1832 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
1833
1834 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], 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 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
1839 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1840 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
1841 }
1842
1843 static void retroactively_stop_dependencies(Unit *u) {
1844 Iterator i;
1845 Unit *other;
1846
1847 assert(u);
1848 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1849
1850 /* Pull down units which are bound to us recursively if enabled */
1851 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
1852 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1853 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
1854 }
1855
1856 static void check_unneeded_dependencies(Unit *u) {
1857 Iterator i;
1858 Unit *other;
1859
1860 assert(u);
1861 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1862
1863 /* Garbage collect services that might not be needed anymore, if enabled */
1864 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1865 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1866 unit_check_unneeded(other);
1867 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1868 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1869 unit_check_unneeded(other);
1870 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
1871 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1872 unit_check_unneeded(other);
1873 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
1874 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1875 unit_check_unneeded(other);
1876 }
1877
1878 void unit_start_on_failure(Unit *u) {
1879 Unit *other;
1880 Iterator i;
1881
1882 assert(u);
1883
1884 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
1885 return;
1886
1887 log_unit_info(u, "Triggering OnFailure= dependencies.");
1888
1889 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
1890 int r;
1891
1892 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
1893 if (r < 0)
1894 log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
1895 }
1896 }
1897
1898 void unit_trigger_notify(Unit *u) {
1899 Unit *other;
1900 Iterator i;
1901
1902 assert(u);
1903
1904 SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
1905 if (UNIT_VTABLE(other)->trigger_notify)
1906 UNIT_VTABLE(other)->trigger_notify(other, u);
1907 }
1908
1909 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
1910 Manager *m;
1911 bool unexpected;
1912
1913 assert(u);
1914 assert(os < _UNIT_ACTIVE_STATE_MAX);
1915 assert(ns < _UNIT_ACTIVE_STATE_MAX);
1916
1917 /* Note that this is called for all low-level state changes,
1918 * even if they might map to the same high-level
1919 * UnitActiveState! That means that ns == os is an expected
1920 * behavior here. For example: if a mount point is remounted
1921 * this function will be called too! */
1922
1923 m = u->manager;
1924
1925 /* Update timestamps for state changes */
1926 if (!MANAGER_IS_RELOADING(m)) {
1927 dual_timestamp_get(&u->state_change_timestamp);
1928
1929 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
1930 u->inactive_exit_timestamp = u->state_change_timestamp;
1931 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
1932 u->inactive_enter_timestamp = u->state_change_timestamp;
1933
1934 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
1935 u->active_enter_timestamp = u->state_change_timestamp;
1936 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
1937 u->active_exit_timestamp = u->state_change_timestamp;
1938 }
1939
1940 /* Keep track of failed units */
1941 (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
1942
1943 /* Make sure the cgroup is always removed when we become inactive */
1944 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1945 unit_prune_cgroup(u);
1946
1947 /* Note that this doesn't apply to RemainAfterExit services exiting
1948 * successfully, since there's no change of state in that case. Which is
1949 * why it is handled in service_set_state() */
1950 if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1951 ExecContext *ec;
1952
1953 ec = unit_get_exec_context(u);
1954 if (ec && exec_context_may_touch_console(ec)) {
1955 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1956 m->n_on_console--;
1957
1958 if (m->n_on_console == 0)
1959 /* unset no_console_output flag, since the console is free */
1960 m->no_console_output = false;
1961 } else
1962 m->n_on_console++;
1963 }
1964 }
1965
1966 if (u->job) {
1967 unexpected = false;
1968
1969 if (u->job->state == JOB_WAITING)
1970
1971 /* So we reached a different state for this
1972 * job. Let's see if we can run it now if it
1973 * failed previously due to EAGAIN. */
1974 job_add_to_run_queue(u->job);
1975
1976 /* Let's check whether this state change constitutes a
1977 * finished job, or maybe contradicts a running job and
1978 * hence needs to invalidate jobs. */
1979
1980 switch (u->job->type) {
1981
1982 case JOB_START:
1983 case JOB_VERIFY_ACTIVE:
1984
1985 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
1986 job_finish_and_invalidate(u->job, JOB_DONE, true, false);
1987 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
1988 unexpected = true;
1989
1990 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
1991 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
1992 }
1993
1994 break;
1995
1996 case JOB_RELOAD:
1997 case JOB_RELOAD_OR_START:
1998 case JOB_TRY_RELOAD:
1999
2000 if (u->job->state == JOB_RUNNING) {
2001 if (ns == UNIT_ACTIVE)
2002 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true, false);
2003 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
2004 unexpected = true;
2005
2006 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2007 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
2008 }
2009 }
2010
2011 break;
2012
2013 case JOB_STOP:
2014 case JOB_RESTART:
2015 case JOB_TRY_RESTART:
2016
2017 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2018 job_finish_and_invalidate(u->job, JOB_DONE, true, false);
2019 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
2020 unexpected = true;
2021 job_finish_and_invalidate(u->job, JOB_FAILED, true, false);
2022 }
2023
2024 break;
2025
2026 default:
2027 assert_not_reached("Job type unknown");
2028 }
2029
2030 } else
2031 unexpected = true;
2032
2033 if (!MANAGER_IS_RELOADING(m)) {
2034
2035 /* If this state change happened without being
2036 * requested by a job, then let's retroactively start
2037 * or stop dependencies. We skip that step when
2038 * deserializing, since we don't want to create any
2039 * additional jobs just because something is already
2040 * activated. */
2041
2042 if (unexpected) {
2043 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
2044 retroactively_start_dependencies(u);
2045 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2046 retroactively_stop_dependencies(u);
2047 }
2048
2049 /* stop unneeded units regardless if going down was expected or not */
2050 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2051 check_unneeded_dependencies(u);
2052
2053 if (ns != os && ns == UNIT_FAILED) {
2054 log_unit_notice(u, "Unit entered failed state.");
2055 unit_start_on_failure(u);
2056 }
2057 }
2058
2059 /* Some names are special */
2060 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
2061
2062 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
2063 /* The bus might have just become available,
2064 * hence try to connect to it, if we aren't
2065 * yet connected. */
2066 bus_init(m, true);
2067
2068 if (u->type == UNIT_SERVICE &&
2069 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
2070 !MANAGER_IS_RELOADING(m)) {
2071 /* Write audit record if we have just finished starting up */
2072 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
2073 u->in_audit = true;
2074 }
2075
2076 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
2077 manager_send_unit_plymouth(m, u);
2078
2079 } else {
2080
2081 /* We don't care about D-Bus here, since we'll get an
2082 * asynchronous notification for it anyway. */
2083
2084 if (u->type == UNIT_SERVICE &&
2085 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
2086 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
2087 !MANAGER_IS_RELOADING(m)) {
2088
2089 /* Hmm, if there was no start record written
2090 * write it now, so that we always have a nice
2091 * pair */
2092 if (!u->in_audit) {
2093 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
2094
2095 if (ns == UNIT_INACTIVE)
2096 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
2097 } else
2098 /* Write audit record if we have just finished shutting down */
2099 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
2100
2101 u->in_audit = false;
2102 }
2103 }
2104
2105 manager_recheck_journal(m);
2106 unit_trigger_notify(u);
2107
2108 if (!MANAGER_IS_RELOADING(u->manager)) {
2109 /* Maybe we finished startup and are now ready for
2110 * being stopped because unneeded? */
2111 unit_check_unneeded(u);
2112
2113 /* Maybe we finished startup, but something we needed
2114 * has vanished? Let's die then. (This happens when
2115 * something BindsTo= to a Type=oneshot unit, as these
2116 * units go directly from starting to inactive,
2117 * without ever entering started.) */
2118 unit_check_binds_to(u);
2119 }
2120
2121 unit_add_to_dbus_queue(u);
2122 unit_add_to_gc_queue(u);
2123 }
2124
2125 int unit_watch_pid(Unit *u, pid_t pid) {
2126 int q, r;
2127
2128 assert(u);
2129 assert(pid >= 1);
2130
2131 /* Watch a specific PID. We only support one or two units
2132 * watching each PID for now, not more. */
2133
2134 r = set_ensure_allocated(&u->pids, NULL);
2135 if (r < 0)
2136 return r;
2137
2138 r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
2139 if (r < 0)
2140 return r;
2141
2142 r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2143 if (r == -EEXIST) {
2144 r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
2145 if (r < 0)
2146 return r;
2147
2148 r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2149 }
2150
2151 q = set_put(u->pids, PID_TO_PTR(pid));
2152 if (q < 0)
2153 return q;
2154
2155 return r;
2156 }
2157
2158 void unit_unwatch_pid(Unit *u, pid_t pid) {
2159 assert(u);
2160 assert(pid >= 1);
2161
2162 (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2163 (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2164 (void) set_remove(u->pids, PID_TO_PTR(pid));
2165 }
2166
2167 void unit_unwatch_all_pids(Unit *u) {
2168 assert(u);
2169
2170 while (!set_isempty(u->pids))
2171 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
2172
2173 u->pids = set_free(u->pids);
2174 }
2175
2176 void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
2177 Iterator i;
2178 void *e;
2179
2180 assert(u);
2181
2182 /* Cleans dead PIDs from our list */
2183
2184 SET_FOREACH(e, u->pids, i) {
2185 pid_t pid = PTR_TO_PID(e);
2186
2187 if (pid == except1 || pid == except2)
2188 continue;
2189
2190 if (!pid_is_unwaited(pid))
2191 unit_unwatch_pid(u, pid);
2192 }
2193 }
2194
2195 bool unit_job_is_applicable(Unit *u, JobType j) {
2196 assert(u);
2197 assert(j >= 0 && j < _JOB_TYPE_MAX);
2198
2199 switch (j) {
2200
2201 case JOB_VERIFY_ACTIVE:
2202 case JOB_START:
2203 case JOB_NOP:
2204 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2205 * startable by us but may appear due to external events, and it thus makes sense to permit enqueing
2206 * jobs for it. */
2207 return true;
2208
2209 case JOB_STOP:
2210 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2211 * external events), hence it makes no sense to permit enqueing such a request either. */
2212 return !u->perpetual;
2213
2214 case JOB_RESTART:
2215 case JOB_TRY_RESTART:
2216 return unit_can_stop(u) && unit_can_start(u);
2217
2218 case JOB_RELOAD:
2219 case JOB_TRY_RELOAD:
2220 return unit_can_reload(u);
2221
2222 case JOB_RELOAD_OR_START:
2223 return unit_can_reload(u) && unit_can_start(u);
2224
2225 default:
2226 assert_not_reached("Invalid job type");
2227 }
2228 }
2229
2230 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2231 assert(u);
2232
2233 /* Only warn about some unit types */
2234 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2235 return;
2236
2237 if (streq_ptr(u->id, other))
2238 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2239 else
2240 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
2241 }
2242
2243 int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
2244
2245 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2246 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
2247 [UNIT_WANTS] = UNIT_WANTED_BY,
2248 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
2249 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
2250 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
2251 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
2252 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
2253 [UNIT_WANTED_BY] = UNIT_WANTS,
2254 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
2255 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
2256 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
2257 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
2258 [UNIT_BEFORE] = UNIT_AFTER,
2259 [UNIT_AFTER] = UNIT_BEFORE,
2260 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
2261 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
2262 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
2263 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
2264 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
2265 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
2266 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
2267 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
2268 };
2269 int r, q = 0, v = 0, w = 0;
2270 Unit *orig_u = u, *orig_other = other;
2271
2272 assert(u);
2273 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
2274 assert(other);
2275
2276 u = unit_follow_merge(u);
2277 other = unit_follow_merge(other);
2278
2279 /* We won't allow dependencies on ourselves. We will not
2280 * consider them an error however. */
2281 if (u == other) {
2282 maybe_warn_about_dependency(orig_u, orig_other->id, d);
2283 return 0;
2284 }
2285
2286 if (d == UNIT_BEFORE && other->type == UNIT_DEVICE) {
2287 log_unit_warning(u, "Dependency Before=%s ignored (.device units cannot be delayed)", other->id);
2288 return 0;
2289 }
2290
2291 r = set_ensure_allocated(&u->dependencies[d], NULL);
2292 if (r < 0)
2293 return r;
2294
2295 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
2296 r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
2297 if (r < 0)
2298 return r;
2299 }
2300
2301 if (add_reference) {
2302 r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
2303 if (r < 0)
2304 return r;
2305
2306 r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
2307 if (r < 0)
2308 return r;
2309 }
2310
2311 q = set_put(u->dependencies[d], other);
2312 if (q < 0)
2313 return q;
2314
2315 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
2316 v = set_put(other->dependencies[inverse_table[d]], u);
2317 if (v < 0) {
2318 r = v;
2319 goto fail;
2320 }
2321 }
2322
2323 if (add_reference) {
2324 w = set_put(u->dependencies[UNIT_REFERENCES], other);
2325 if (w < 0) {
2326 r = w;
2327 goto fail;
2328 }
2329
2330 r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
2331 if (r < 0)
2332 goto fail;
2333 }
2334
2335 unit_add_to_dbus_queue(u);
2336 return 0;
2337
2338 fail:
2339 if (q > 0)
2340 set_remove(u->dependencies[d], other);
2341
2342 if (v > 0)
2343 set_remove(other->dependencies[inverse_table[d]], u);
2344
2345 if (w > 0)
2346 set_remove(u->dependencies[UNIT_REFERENCES], other);
2347
2348 return r;
2349 }
2350
2351 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
2352 int r;
2353
2354 assert(u);
2355
2356 r = unit_add_dependency(u, d, other, add_reference);
2357 if (r < 0)
2358 return r;
2359
2360 return unit_add_dependency(u, e, other, add_reference);
2361 }
2362
2363 static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
2364 int r;
2365
2366 assert(u);
2367 assert(name || path);
2368 assert(buf);
2369 assert(ret);
2370
2371 if (!name)
2372 name = basename(path);
2373
2374 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2375 *buf = NULL;
2376 *ret = name;
2377 return 0;
2378 }
2379
2380 if (u->instance)
2381 r = unit_name_replace_instance(name, u->instance, buf);
2382 else {
2383 _cleanup_free_ char *i = NULL;
2384
2385 r = unit_name_to_prefix(u->id, &i);
2386 if (r < 0)
2387 return r;
2388
2389 r = unit_name_replace_instance(name, i, buf);
2390 }
2391 if (r < 0)
2392 return r;
2393
2394 *ret = *buf;
2395 return 0;
2396 }
2397
2398 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
2399 _cleanup_free_ char *buf = NULL;
2400 Unit *other;
2401 int r;
2402
2403 assert(u);
2404 assert(name || path);
2405
2406 r = resolve_template(u, name, path, &buf, &name);
2407 if (r < 0)
2408 return r;
2409
2410 r = manager_load_unit(u->manager, name, path, NULL, &other);
2411 if (r < 0)
2412 return r;
2413
2414 return unit_add_dependency(u, d, other, add_reference);
2415 }
2416
2417 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
2418 _cleanup_free_ char *buf = NULL;
2419 Unit *other;
2420 int r;
2421
2422 assert(u);
2423 assert(name || path);
2424
2425 r = resolve_template(u, name, path, &buf, &name);
2426 if (r < 0)
2427 return r;
2428
2429 r = manager_load_unit(u->manager, name, path, NULL, &other);
2430 if (r < 0)
2431 return r;
2432
2433 return unit_add_two_dependencies(u, d, e, other, add_reference);
2434 }
2435
2436 int set_unit_path(const char *p) {
2437 /* This is mostly for debug purposes */
2438 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
2439 return -errno;
2440
2441 return 0;
2442 }
2443
2444 char *unit_dbus_path(Unit *u) {
2445 assert(u);
2446
2447 if (!u->id)
2448 return NULL;
2449
2450 return unit_dbus_path_from_name(u->id);
2451 }
2452
2453 char *unit_dbus_path_invocation_id(Unit *u) {
2454 assert(u);
2455
2456 if (sd_id128_is_null(u->invocation_id))
2457 return NULL;
2458
2459 return unit_dbus_path_from_name(u->invocation_id_string);
2460 }
2461
2462 int unit_set_slice(Unit *u, Unit *slice) {
2463 assert(u);
2464 assert(slice);
2465
2466 /* Sets the unit slice if it has not been set before. Is extra
2467 * careful, to only allow this for units that actually have a
2468 * cgroup context. Also, we don't allow to set this for slices
2469 * (since the parent slice is derived from the name). Make
2470 * sure the unit we set is actually a slice. */
2471
2472 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2473 return -EOPNOTSUPP;
2474
2475 if (u->type == UNIT_SLICE)
2476 return -EINVAL;
2477
2478 if (unit_active_state(u) != UNIT_INACTIVE)
2479 return -EBUSY;
2480
2481 if (slice->type != UNIT_SLICE)
2482 return -EINVAL;
2483
2484 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
2485 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
2486 return -EPERM;
2487
2488 if (UNIT_DEREF(u->slice) == slice)
2489 return 0;
2490
2491 /* Disallow slice changes if @u is already bound to cgroups */
2492 if (UNIT_ISSET(u->slice) && u->cgroup_realized)
2493 return -EBUSY;
2494
2495 unit_ref_unset(&u->slice);
2496 unit_ref_set(&u->slice, slice);
2497 return 1;
2498 }
2499
2500 int unit_set_default_slice(Unit *u) {
2501 _cleanup_free_ char *b = NULL;
2502 const char *slice_name;
2503 Unit *slice;
2504 int r;
2505
2506 assert(u);
2507
2508 if (UNIT_ISSET(u->slice))
2509 return 0;
2510
2511 if (u->instance) {
2512 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
2513
2514 /* Implicitly place all instantiated units in their
2515 * own per-template slice */
2516
2517 r = unit_name_to_prefix(u->id, &prefix);
2518 if (r < 0)
2519 return r;
2520
2521 /* The prefix is already escaped, but it might include
2522 * "-" which has a special meaning for slice units,
2523 * hence escape it here extra. */
2524 escaped = unit_name_escape(prefix);
2525 if (!escaped)
2526 return -ENOMEM;
2527
2528 if (MANAGER_IS_SYSTEM(u->manager))
2529 b = strjoin("system-", escaped, ".slice");
2530 else
2531 b = strappend(escaped, ".slice");
2532 if (!b)
2533 return -ENOMEM;
2534
2535 slice_name = b;
2536 } else
2537 slice_name =
2538 MANAGER_IS_SYSTEM(u->manager) && !unit_has_name(u, SPECIAL_INIT_SCOPE)
2539 ? SPECIAL_SYSTEM_SLICE
2540 : SPECIAL_ROOT_SLICE;
2541
2542 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
2543 if (r < 0)
2544 return r;
2545
2546 return unit_set_slice(u, slice);
2547 }
2548
2549 const char *unit_slice_name(Unit *u) {
2550 assert(u);
2551
2552 if (!UNIT_ISSET(u->slice))
2553 return NULL;
2554
2555 return UNIT_DEREF(u->slice)->id;
2556 }
2557
2558 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
2559 _cleanup_free_ char *t = NULL;
2560 int r;
2561
2562 assert(u);
2563 assert(type);
2564 assert(_found);
2565
2566 r = unit_name_change_suffix(u->id, type, &t);
2567 if (r < 0)
2568 return r;
2569 if (unit_has_name(u, t))
2570 return -EINVAL;
2571
2572 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
2573 assert(r < 0 || *_found != u);
2574 return r;
2575 }
2576
2577 static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2578 const char *name, *old_owner, *new_owner;
2579 Unit *u = userdata;
2580 int r;
2581
2582 assert(message);
2583 assert(u);
2584
2585 r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
2586 if (r < 0) {
2587 bus_log_parse_error(r);
2588 return 0;
2589 }
2590
2591 if (UNIT_VTABLE(u)->bus_name_owner_change)
2592 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2593
2594 return 0;
2595 }
2596
2597 int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
2598 const char *match;
2599
2600 assert(u);
2601 assert(bus);
2602 assert(name);
2603
2604 if (u->match_bus_slot)
2605 return -EBUSY;
2606
2607 match = strjoina("type='signal',"
2608 "sender='org.freedesktop.DBus',"
2609 "path='/org/freedesktop/DBus',"
2610 "interface='org.freedesktop.DBus',"
2611 "member='NameOwnerChanged',"
2612 "arg0='", name, "'");
2613
2614 return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
2615 }
2616
2617 int unit_watch_bus_name(Unit *u, const char *name) {
2618 int r;
2619
2620 assert(u);
2621 assert(name);
2622
2623 /* Watch a specific name on the bus. We only support one unit
2624 * watching each name for now. */
2625
2626 if (u->manager->api_bus) {
2627 /* If the bus is already available, install the match directly.
2628 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
2629 r = unit_install_bus_match(u, u->manager->api_bus, name);
2630 if (r < 0)
2631 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
2632 }
2633
2634 r = hashmap_put(u->manager->watch_bus, name, u);
2635 if (r < 0) {
2636 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2637 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
2638 }
2639
2640 return 0;
2641 }
2642
2643 void unit_unwatch_bus_name(Unit *u, const char *name) {
2644 assert(u);
2645 assert(name);
2646
2647 hashmap_remove_value(u->manager->watch_bus, name, u);
2648 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2649 }
2650
2651 bool unit_can_serialize(Unit *u) {
2652 assert(u);
2653
2654 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2655 }
2656
2657 int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
2658 int r;
2659
2660 assert(u);
2661 assert(f);
2662 assert(fds);
2663
2664 if (unit_can_serialize(u)) {
2665 ExecRuntime *rt;
2666
2667 r = UNIT_VTABLE(u)->serialize(u, f, fds);
2668 if (r < 0)
2669 return r;
2670
2671 rt = unit_get_exec_runtime(u);
2672 if (rt) {
2673 r = exec_runtime_serialize(u, rt, f, fds);
2674 if (r < 0)
2675 return r;
2676 }
2677 }
2678
2679 dual_timestamp_serialize(f, "state-change-timestamp", &u->state_change_timestamp);
2680
2681 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2682 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2683 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2684 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
2685
2686 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
2687 dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
2688
2689 if (dual_timestamp_is_set(&u->condition_timestamp))
2690 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
2691
2692 if (dual_timestamp_is_set(&u->assert_timestamp))
2693 unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
2694
2695 unit_serialize_item(u, f, "transient", yes_no(u->transient));
2696
2697 unit_serialize_item_format(u, f, "cpu-usage-base", "%" PRIu64, u->cpu_usage_base);
2698 if (u->cpu_usage_last != NSEC_INFINITY)
2699 unit_serialize_item_format(u, f, "cpu-usage-last", "%" PRIu64, u->cpu_usage_last);
2700
2701 if (u->cgroup_path)
2702 unit_serialize_item(u, f, "cgroup", u->cgroup_path);
2703 unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
2704
2705 if (uid_is_valid(u->ref_uid))
2706 unit_serialize_item_format(u, f, "ref-uid", UID_FMT, u->ref_uid);
2707 if (gid_is_valid(u->ref_gid))
2708 unit_serialize_item_format(u, f, "ref-gid", GID_FMT, u->ref_gid);
2709
2710 if (!sd_id128_is_null(u->invocation_id))
2711 unit_serialize_item_format(u, f, "invocation-id", SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id));
2712
2713 bus_track_serialize(u->bus_track, f, "ref");
2714
2715 if (serialize_jobs) {
2716 if (u->job) {
2717 fprintf(f, "job\n");
2718 job_serialize(u->job, f);
2719 }
2720
2721 if (u->nop_job) {
2722 fprintf(f, "job\n");
2723 job_serialize(u->nop_job, f);
2724 }
2725 }
2726
2727 /* End marker */
2728 fputc('\n', f);
2729 return 0;
2730 }
2731
2732 int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2733 assert(u);
2734 assert(f);
2735 assert(key);
2736
2737 if (!value)
2738 return 0;
2739
2740 fputs(key, f);
2741 fputc('=', f);
2742 fputs(value, f);
2743 fputc('\n', f);
2744
2745 return 1;
2746 }
2747
2748 int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
2749 _cleanup_free_ char *c = NULL;
2750
2751 assert(u);
2752 assert(f);
2753 assert(key);
2754
2755 if (!value)
2756 return 0;
2757
2758 c = cescape(value);
2759 if (!c)
2760 return -ENOMEM;
2761
2762 fputs(key, f);
2763 fputc('=', f);
2764 fputs(c, f);
2765 fputc('\n', f);
2766
2767 return 1;
2768 }
2769
2770 int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
2771 int copy;
2772
2773 assert(u);
2774 assert(f);
2775 assert(key);
2776
2777 if (fd < 0)
2778 return 0;
2779
2780 copy = fdset_put_dup(fds, fd);
2781 if (copy < 0)
2782 return copy;
2783
2784 fprintf(f, "%s=%i\n", key, copy);
2785 return 1;
2786 }
2787
2788 void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2789 va_list ap;
2790
2791 assert(u);
2792 assert(f);
2793 assert(key);
2794 assert(format);
2795
2796 fputs(key, f);
2797 fputc('=', f);
2798
2799 va_start(ap, format);
2800 vfprintf(f, format, ap);
2801 va_end(ap);
2802
2803 fputc('\n', f);
2804 }
2805
2806 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
2807 ExecRuntime **rt = NULL;
2808 size_t offset;
2809 int r;
2810
2811 assert(u);
2812 assert(f);
2813 assert(fds);
2814
2815 offset = UNIT_VTABLE(u)->exec_runtime_offset;
2816 if (offset > 0)
2817 rt = (ExecRuntime**) ((uint8_t*) u + offset);
2818
2819 for (;;) {
2820 char line[LINE_MAX], *l, *v;
2821 size_t k;
2822
2823 if (!fgets(line, sizeof(line), f)) {
2824 if (feof(f))
2825 return 0;
2826 return -errno;
2827 }
2828
2829 char_array_0(line);
2830 l = strstrip(line);
2831
2832 /* End marker */
2833 if (isempty(l))
2834 break;
2835
2836 k = strcspn(l, "=");
2837
2838 if (l[k] == '=') {
2839 l[k] = 0;
2840 v = l+k+1;
2841 } else
2842 v = l+k;
2843
2844 if (streq(l, "job")) {
2845 if (v[0] == '\0') {
2846 /* new-style serialized job */
2847 Job *j;
2848
2849 j = job_new_raw(u);
2850 if (!j)
2851 return log_oom();
2852
2853 r = job_deserialize(j, f);
2854 if (r < 0) {
2855 job_free(j);
2856 return r;
2857 }
2858
2859 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2860 if (r < 0) {
2861 job_free(j);
2862 return r;
2863 }
2864
2865 r = job_install_deserialized(j);
2866 if (r < 0) {
2867 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2868 job_free(j);
2869 return r;
2870 }
2871 } else /* legacy for pre-44 */
2872 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
2873 continue;
2874 } else if (streq(l, "state-change-timestamp")) {
2875 dual_timestamp_deserialize(v, &u->state_change_timestamp);
2876 continue;
2877 } else if (streq(l, "inactive-exit-timestamp")) {
2878 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
2879 continue;
2880 } else if (streq(l, "active-enter-timestamp")) {
2881 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
2882 continue;
2883 } else if (streq(l, "active-exit-timestamp")) {
2884 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
2885 continue;
2886 } else if (streq(l, "inactive-enter-timestamp")) {
2887 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
2888 continue;
2889 } else if (streq(l, "condition-timestamp")) {
2890 dual_timestamp_deserialize(v, &u->condition_timestamp);
2891 continue;
2892 } else if (streq(l, "assert-timestamp")) {
2893 dual_timestamp_deserialize(v, &u->assert_timestamp);
2894 continue;
2895 } else if (streq(l, "condition-result")) {
2896
2897 r = parse_boolean(v);
2898 if (r < 0)
2899 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2900 else
2901 u->condition_result = r;
2902
2903 continue;
2904
2905 } else if (streq(l, "assert-result")) {
2906
2907 r = parse_boolean(v);
2908 if (r < 0)
2909 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
2910 else
2911 u->assert_result = r;
2912
2913 continue;
2914
2915 } else if (streq(l, "transient")) {
2916
2917 r = parse_boolean(v);
2918 if (r < 0)
2919 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
2920 else
2921 u->transient = r;
2922
2923 continue;
2924
2925 } else if (STR_IN_SET(l, "cpu-usage-base", "cpuacct-usage-base")) {
2926
2927 r = safe_atou64(v, &u->cpu_usage_base);
2928 if (r < 0)
2929 log_unit_debug(u, "Failed to parse CPU usage base %s, ignoring.", v);
2930
2931 continue;
2932
2933 } else if (streq(l, "cpu-usage-last")) {
2934
2935 r = safe_atou64(v, &u->cpu_usage_last);
2936 if (r < 0)
2937 log_unit_debug(u, "Failed to read CPU usage last %s, ignoring.", v);
2938
2939 continue;
2940
2941 } else if (streq(l, "cgroup")) {
2942
2943 r = unit_set_cgroup_path(u, v);
2944 if (r < 0)
2945 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
2946
2947 (void) unit_watch_cgroup(u);
2948
2949 continue;
2950 } else if (streq(l, "cgroup-realized")) {
2951 int b;
2952
2953 b = parse_boolean(v);
2954 if (b < 0)
2955 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
2956 else
2957 u->cgroup_realized = b;
2958
2959 continue;
2960
2961 } else if (streq(l, "ref-uid")) {
2962 uid_t uid;
2963
2964 r = parse_uid(v, &uid);
2965 if (r < 0)
2966 log_unit_debug(u, "Failed to parse referenced UID %s, ignoring.", v);
2967 else
2968 unit_ref_uid_gid(u, uid, GID_INVALID);
2969
2970 continue;
2971
2972 } else if (streq(l, "ref-gid")) {
2973 gid_t gid;
2974
2975 r = parse_gid(v, &gid);
2976 if (r < 0)
2977 log_unit_debug(u, "Failed to parse referenced GID %s, ignoring.", v);
2978 else
2979 unit_ref_uid_gid(u, UID_INVALID, gid);
2980
2981 } else if (streq(l, "ref")) {
2982
2983 r = strv_extend(&u->deserialized_refs, v);
2984 if (r < 0)
2985 log_oom();
2986
2987 continue;
2988 } else if (streq(l, "invocation-id")) {
2989 sd_id128_t id;
2990
2991 r = sd_id128_from_string(v, &id);
2992 if (r < 0)
2993 log_unit_debug(u, "Failed to parse invocation id %s, ignoring.", v);
2994 else {
2995 r = unit_set_invocation_id(u, id);
2996 if (r < 0)
2997 log_unit_warning_errno(u, r, "Failed to set invocation ID for unit: %m");
2998 }
2999
3000 continue;
3001 }
3002
3003 if (unit_can_serialize(u)) {
3004 if (rt) {
3005 r = exec_runtime_deserialize_item(u, rt, l, v, fds);
3006 if (r < 0) {
3007 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
3008 continue;
3009 }
3010
3011 /* Returns positive if key was handled by the call */
3012 if (r > 0)
3013 continue;
3014 }
3015
3016 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
3017 if (r < 0)
3018 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
3019 }
3020 }
3021
3022 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
3023 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
3024 * before 228 where the base for timeouts was not persistent across reboots. */
3025
3026 if (!dual_timestamp_is_set(&u->state_change_timestamp))
3027 dual_timestamp_get(&u->state_change_timestamp);
3028
3029 return 0;
3030 }
3031
3032 int unit_add_node_link(Unit *u, const char *what, bool wants, UnitDependency dep) {
3033 Unit *device;
3034 _cleanup_free_ char *e = NULL;
3035 int r;
3036
3037 assert(u);
3038
3039 /* Adds in links to the device node that this unit is based on */
3040 if (isempty(what))
3041 return 0;
3042
3043 if (!is_device_path(what))
3044 return 0;
3045
3046 /* When device units aren't supported (such as in a
3047 * container), don't create dependencies on them. */
3048 if (!unit_type_supported(UNIT_DEVICE))
3049 return 0;
3050
3051 r = unit_name_from_path(what, ".device", &e);
3052 if (r < 0)
3053 return r;
3054
3055 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
3056 if (r < 0)
3057 return r;
3058
3059 if (dep == UNIT_REQUIRES && device_shall_be_bound_by(device, u))
3060 dep = UNIT_BINDS_TO;
3061
3062 r = unit_add_two_dependencies(u, UNIT_AFTER,
3063 MANAGER_IS_SYSTEM(u->manager) ? dep : UNIT_WANTS,
3064 device, true);
3065 if (r < 0)
3066 return r;
3067
3068 if (wants) {
3069 r = unit_add_dependency(device, UNIT_WANTS, u, false);
3070 if (r < 0)
3071 return r;
3072 }
3073
3074 return 0;
3075 }
3076
3077 int unit_coldplug(Unit *u) {
3078 int r = 0, q;
3079 char **i;
3080
3081 assert(u);
3082
3083 /* Make sure we don't enter a loop, when coldplugging
3084 * recursively. */
3085 if (u->coldplugged)
3086 return 0;
3087
3088 u->coldplugged = true;
3089
3090 STRV_FOREACH(i, u->deserialized_refs) {
3091 q = bus_unit_track_add_name(u, *i);
3092 if (q < 0 && r >= 0)
3093 r = q;
3094 }
3095 u->deserialized_refs = strv_free(u->deserialized_refs);
3096
3097 if (UNIT_VTABLE(u)->coldplug) {
3098 q = UNIT_VTABLE(u)->coldplug(u);
3099 if (q < 0 && r >= 0)
3100 r = q;
3101 }
3102
3103 if (u->job) {
3104 q = job_coldplug(u->job);
3105 if (q < 0 && r >= 0)
3106 r = q;
3107 }
3108
3109 return r;
3110 }
3111
3112 static bool fragment_mtime_newer(const char *path, usec_t mtime, bool path_masked) {
3113 struct stat st;
3114
3115 if (!path)
3116 return false;
3117
3118 if (stat(path, &st) < 0)
3119 /* What, cannot access this anymore? */
3120 return true;
3121
3122 if (path_masked)
3123 /* For masked files check if they are still so */
3124 return !null_or_empty(&st);
3125 else
3126 /* For non-empty files check the mtime */
3127 return timespec_load(&st.st_mtim) > mtime;
3128
3129 return false;
3130 }
3131
3132 bool unit_need_daemon_reload(Unit *u) {
3133 _cleanup_strv_free_ char **t = NULL;
3134 char **path;
3135
3136 assert(u);
3137
3138 /* For unit files, we allow masking… */
3139 if (fragment_mtime_newer(u->fragment_path, u->fragment_mtime,
3140 u->load_state == UNIT_MASKED))
3141 return true;
3142
3143 /* Source paths should not be masked… */
3144 if (fragment_mtime_newer(u->source_path, u->source_mtime, false))
3145 return true;
3146
3147 (void) unit_find_dropin_paths(u, &t);
3148 if (!strv_equal(u->dropin_paths, t))
3149 return true;
3150
3151 /* … any drop-ins that are masked are simply omitted from the list. */
3152 STRV_FOREACH(path, u->dropin_paths)
3153 if (fragment_mtime_newer(*path, u->dropin_mtime, false))
3154 return true;
3155
3156 return false;
3157 }
3158
3159 void unit_reset_failed(Unit *u) {
3160 assert(u);
3161
3162 if (UNIT_VTABLE(u)->reset_failed)
3163 UNIT_VTABLE(u)->reset_failed(u);
3164
3165 RATELIMIT_RESET(u->start_limit);
3166 u->start_limit_hit = false;
3167 }
3168
3169 Unit *unit_following(Unit *u) {
3170 assert(u);
3171
3172 if (UNIT_VTABLE(u)->following)
3173 return UNIT_VTABLE(u)->following(u);
3174
3175 return NULL;
3176 }
3177
3178 bool unit_stop_pending(Unit *u) {
3179 assert(u);
3180
3181 /* This call does check the current state of the unit. It's
3182 * hence useful to be called from state change calls of the
3183 * unit itself, where the state isn't updated yet. This is
3184 * different from unit_inactive_or_pending() which checks both
3185 * the current state and for a queued job. */
3186
3187 return u->job && u->job->type == JOB_STOP;
3188 }
3189
3190 bool unit_inactive_or_pending(Unit *u) {
3191 assert(u);
3192
3193 /* Returns true if the unit is inactive or going down */
3194
3195 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
3196 return true;
3197
3198 if (unit_stop_pending(u))
3199 return true;
3200
3201 return false;
3202 }
3203
3204 bool unit_active_or_pending(Unit *u) {
3205 assert(u);
3206
3207 /* Returns true if the unit is active or going up */
3208
3209 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
3210 return true;
3211
3212 if (u->job &&
3213 (u->job->type == JOB_START ||
3214 u->job->type == JOB_RELOAD_OR_START ||
3215 u->job->type == JOB_RESTART))
3216 return true;
3217
3218 return false;
3219 }
3220
3221 int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
3222 assert(u);
3223 assert(w >= 0 && w < _KILL_WHO_MAX);
3224 assert(SIGNAL_VALID(signo));
3225
3226 if (!UNIT_VTABLE(u)->kill)
3227 return -EOPNOTSUPP;
3228
3229 return UNIT_VTABLE(u)->kill(u, w, signo, error);
3230 }
3231
3232 static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
3233 Set *pid_set;
3234 int r;
3235
3236 pid_set = set_new(NULL);
3237 if (!pid_set)
3238 return NULL;
3239
3240 /* Exclude the main/control pids from being killed via the cgroup */
3241 if (main_pid > 0) {
3242 r = set_put(pid_set, PID_TO_PTR(main_pid));
3243 if (r < 0)
3244 goto fail;
3245 }
3246
3247 if (control_pid > 0) {
3248 r = set_put(pid_set, PID_TO_PTR(control_pid));
3249 if (r < 0)
3250 goto fail;
3251 }
3252
3253 return pid_set;
3254
3255 fail:
3256 set_free(pid_set);
3257 return NULL;
3258 }
3259
3260 int unit_kill_common(
3261 Unit *u,
3262 KillWho who,
3263 int signo,
3264 pid_t main_pid,
3265 pid_t control_pid,
3266 sd_bus_error *error) {
3267
3268 int r = 0;
3269 bool killed = false;
3270
3271 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
3272 if (main_pid < 0)
3273 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
3274 else if (main_pid == 0)
3275 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
3276 }
3277
3278 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
3279 if (control_pid < 0)
3280 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
3281 else if (control_pid == 0)
3282 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
3283 }
3284
3285 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
3286 if (control_pid > 0) {
3287 if (kill(control_pid, signo) < 0)
3288 r = -errno;
3289 else
3290 killed = true;
3291 }
3292
3293 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
3294 if (main_pid > 0) {
3295 if (kill(main_pid, signo) < 0)
3296 r = -errno;
3297 else
3298 killed = true;
3299 }
3300
3301 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
3302 _cleanup_set_free_ Set *pid_set = NULL;
3303 int q;
3304
3305 /* Exclude the main/control pids from being killed via the cgroup */
3306 pid_set = unit_pid_set(main_pid, control_pid);
3307 if (!pid_set)
3308 return -ENOMEM;
3309
3310 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, 0, pid_set, NULL, NULL);
3311 if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3312 r = q;
3313 else
3314 killed = true;
3315 }
3316
3317 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL))
3318 return -ESRCH;
3319
3320 return r;
3321 }
3322
3323 int unit_following_set(Unit *u, Set **s) {
3324 assert(u);
3325 assert(s);
3326
3327 if (UNIT_VTABLE(u)->following_set)
3328 return UNIT_VTABLE(u)->following_set(u, s);
3329
3330 *s = NULL;
3331 return 0;
3332 }
3333
3334 UnitFileState unit_get_unit_file_state(Unit *u) {
3335 int r;
3336
3337 assert(u);
3338
3339 if (u->unit_file_state < 0 && u->fragment_path) {
3340 r = unit_file_get_state(
3341 u->manager->unit_file_scope,
3342 NULL,
3343 basename(u->fragment_path),
3344 &u->unit_file_state);
3345 if (r < 0)
3346 u->unit_file_state = UNIT_FILE_BAD;
3347 }
3348
3349 return u->unit_file_state;
3350 }
3351
3352 int unit_get_unit_file_preset(Unit *u) {
3353 assert(u);
3354
3355 if (u->unit_file_preset < 0 && u->fragment_path)
3356 u->unit_file_preset = unit_file_query_preset(
3357 u->manager->unit_file_scope,
3358 NULL,
3359 basename(u->fragment_path));
3360
3361 return u->unit_file_preset;
3362 }
3363
3364 Unit* unit_ref_set(UnitRef *ref, Unit *u) {
3365 assert(ref);
3366 assert(u);
3367
3368 if (ref->unit)
3369 unit_ref_unset(ref);
3370
3371 ref->unit = u;
3372 LIST_PREPEND(refs, u->refs, ref);
3373 return u;
3374 }
3375
3376 void unit_ref_unset(UnitRef *ref) {
3377 assert(ref);
3378
3379 if (!ref->unit)
3380 return;
3381
3382 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
3383 * be unreferenced now. */
3384 unit_add_to_gc_queue(ref->unit);
3385
3386 LIST_REMOVE(refs, ref->unit->refs, ref);
3387 ref->unit = NULL;
3388 }
3389
3390 static int user_from_unit_name(Unit *u, char **ret) {
3391
3392 static const uint8_t hash_key[] = {
3393 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
3394 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
3395 };
3396
3397 _cleanup_free_ char *n = NULL;
3398 int r;
3399
3400 r = unit_name_to_prefix(u->id, &n);
3401 if (r < 0)
3402 return r;
3403
3404 if (valid_user_group_name(n)) {
3405 *ret = n;
3406 n = NULL;
3407 return 0;
3408 }
3409
3410 /* If we can't use the unit name as a user name, then let's hash it and use that */
3411 if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
3412 return -ENOMEM;
3413
3414 return 0;
3415 }
3416
3417 int unit_patch_contexts(Unit *u) {
3418 CGroupContext *cc;
3419 ExecContext *ec;
3420 unsigned i;
3421 int r;
3422
3423 assert(u);
3424
3425 /* Patch in the manager defaults into the exec and cgroup
3426 * contexts, _after_ the rest of the settings have been
3427 * initialized */
3428
3429 ec = unit_get_exec_context(u);
3430 if (ec) {
3431 /* This only copies in the ones that need memory */
3432 for (i = 0; i < _RLIMIT_MAX; i++)
3433 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
3434 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
3435 if (!ec->rlimit[i])
3436 return -ENOMEM;
3437 }
3438
3439 if (MANAGER_IS_USER(u->manager) &&
3440 !ec->working_directory) {
3441
3442 r = get_home_dir(&ec->working_directory);
3443 if (r < 0)
3444 return r;
3445
3446 /* Allow user services to run, even if the
3447 * home directory is missing */
3448 ec->working_directory_missing_ok = true;
3449 }
3450
3451 if (ec->private_devices)
3452 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
3453
3454 if (ec->protect_kernel_modules)
3455 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
3456
3457 if (ec->dynamic_user) {
3458 if (!ec->user) {
3459 r = user_from_unit_name(u, &ec->user);
3460 if (r < 0)
3461 return r;
3462 }
3463
3464 if (!ec->group) {
3465 ec->group = strdup(ec->user);
3466 if (!ec->group)
3467 return -ENOMEM;
3468 }
3469
3470 /* If the dynamic user option is on, let's make sure that the unit can't leave its UID/GID
3471 * around in the file system or on IPC objects. Hence enforce a strict sandbox. */
3472
3473 ec->private_tmp = true;
3474 ec->remove_ipc = true;
3475 ec->protect_system = PROTECT_SYSTEM_STRICT;
3476 if (ec->protect_home == PROTECT_HOME_NO)
3477 ec->protect_home = PROTECT_HOME_READ_ONLY;
3478 }
3479 }
3480
3481 cc = unit_get_cgroup_context(u);
3482 if (cc) {
3483
3484 if (ec &&
3485 ec->private_devices &&
3486 cc->device_policy == CGROUP_AUTO)
3487 cc->device_policy = CGROUP_CLOSED;
3488 }
3489
3490 return 0;
3491 }
3492
3493 ExecContext *unit_get_exec_context(Unit *u) {
3494 size_t offset;
3495 assert(u);
3496
3497 if (u->type < 0)
3498 return NULL;
3499
3500 offset = UNIT_VTABLE(u)->exec_context_offset;
3501 if (offset <= 0)
3502 return NULL;
3503
3504 return (ExecContext*) ((uint8_t*) u + offset);
3505 }
3506
3507 KillContext *unit_get_kill_context(Unit *u) {
3508 size_t offset;
3509 assert(u);
3510
3511 if (u->type < 0)
3512 return NULL;
3513
3514 offset = UNIT_VTABLE(u)->kill_context_offset;
3515 if (offset <= 0)
3516 return NULL;
3517
3518 return (KillContext*) ((uint8_t*) u + offset);
3519 }
3520
3521 CGroupContext *unit_get_cgroup_context(Unit *u) {
3522 size_t offset;
3523
3524 if (u->type < 0)
3525 return NULL;
3526
3527 offset = UNIT_VTABLE(u)->cgroup_context_offset;
3528 if (offset <= 0)
3529 return NULL;
3530
3531 return (CGroupContext*) ((uint8_t*) u + offset);
3532 }
3533
3534 ExecRuntime *unit_get_exec_runtime(Unit *u) {
3535 size_t offset;
3536
3537 if (u->type < 0)
3538 return NULL;
3539
3540 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3541 if (offset <= 0)
3542 return NULL;
3543
3544 return *(ExecRuntime**) ((uint8_t*) u + offset);
3545 }
3546
3547 static const char* unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode) {
3548 assert(u);
3549
3550 if (!IN_SET(mode, UNIT_RUNTIME, UNIT_PERSISTENT))
3551 return NULL;
3552
3553 if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
3554 return u->manager->lookup_paths.transient;
3555
3556 if (mode == UNIT_RUNTIME)
3557 return u->manager->lookup_paths.runtime_control;
3558
3559 if (mode == UNIT_PERSISTENT)
3560 return u->manager->lookup_paths.persistent_control;
3561
3562 return NULL;
3563 }
3564
3565 int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
3566 _cleanup_free_ char *p = NULL, *q = NULL;
3567 const char *dir, *wrapped;
3568 int r;
3569
3570 assert(u);
3571
3572 if (u->transient_file) {
3573 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
3574 * write to the transient unit file. */
3575 fputs(data, u->transient_file);
3576 fputc('\n', u->transient_file);
3577 return 0;
3578 }
3579
3580 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3581 return 0;
3582
3583 dir = unit_drop_in_dir(u, mode);
3584 if (!dir)
3585 return -EINVAL;
3586
3587 wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
3588 "# or an equivalent operation. Do not edit.\n",
3589 data,
3590 "\n");
3591
3592 r = drop_in_file(dir, u->id, 50, name, &p, &q);
3593 if (r < 0)
3594 return r;
3595
3596 (void) mkdir_p(p, 0755);
3597 r = write_string_file_atomic_label(q, wrapped);
3598 if (r < 0)
3599 return r;
3600
3601 r = strv_push(&u->dropin_paths, q);
3602 if (r < 0)
3603 return r;
3604 q = NULL;
3605
3606 strv_uniq(u->dropin_paths);
3607
3608 u->dropin_mtime = now(CLOCK_REALTIME);
3609
3610 return 0;
3611 }
3612
3613 int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3614 _cleanup_free_ char *p = NULL;
3615 va_list ap;
3616 int r;
3617
3618 assert(u);
3619 assert(name);
3620 assert(format);
3621
3622 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3623 return 0;
3624
3625 va_start(ap, format);
3626 r = vasprintf(&p, format, ap);
3627 va_end(ap);
3628
3629 if (r < 0)
3630 return -ENOMEM;
3631
3632 return unit_write_drop_in(u, mode, name, p);
3633 }
3634
3635 int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
3636 const char *ndata;
3637
3638 assert(u);
3639 assert(name);
3640 assert(data);
3641
3642 if (!UNIT_VTABLE(u)->private_section)
3643 return -EINVAL;
3644
3645 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3646 return 0;
3647
3648 ndata = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
3649
3650 return unit_write_drop_in(u, mode, name, ndata);
3651 }
3652
3653 int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3654 _cleanup_free_ char *p = NULL;
3655 va_list ap;
3656 int r;
3657
3658 assert(u);
3659 assert(name);
3660 assert(format);
3661
3662 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
3663 return 0;
3664
3665 va_start(ap, format);
3666 r = vasprintf(&p, format, ap);
3667 va_end(ap);
3668
3669 if (r < 0)
3670 return -ENOMEM;
3671
3672 return unit_write_drop_in_private(u, mode, name, p);
3673 }
3674
3675 int unit_make_transient(Unit *u) {
3676 FILE *f;
3677 char *path;
3678
3679 assert(u);
3680
3681 if (!UNIT_VTABLE(u)->can_transient)
3682 return -EOPNOTSUPP;
3683
3684 path = strjoin(u->manager->lookup_paths.transient, "/", u->id);
3685 if (!path)
3686 return -ENOMEM;
3687
3688 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
3689 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
3690
3691 RUN_WITH_UMASK(0022) {
3692 f = fopen(path, "we");
3693 if (!f) {
3694 free(path);
3695 return -errno;
3696 }
3697 }
3698
3699 if (u->transient_file)
3700 fclose(u->transient_file);
3701 u->transient_file = f;
3702
3703 free(u->fragment_path);
3704 u->fragment_path = path;
3705
3706 u->source_path = mfree(u->source_path);
3707 u->dropin_paths = strv_free(u->dropin_paths);
3708 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
3709
3710 u->load_state = UNIT_STUB;
3711 u->load_error = 0;
3712 u->transient = true;
3713
3714 unit_add_to_dbus_queue(u);
3715 unit_add_to_gc_queue(u);
3716
3717 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
3718 u->transient_file);
3719
3720 return 0;
3721 }
3722
3723 static void log_kill(pid_t pid, int sig, void *userdata) {
3724 _cleanup_free_ char *comm = NULL;
3725
3726 (void) get_process_comm(pid, &comm);
3727
3728 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
3729 only, like for example systemd's own PAM stub process. */
3730 if (comm && comm[0] == '(')
3731 return;
3732
3733 log_unit_notice(userdata,
3734 "Killing process " PID_FMT " (%s) with signal SIG%s.",
3735 pid,
3736 strna(comm),
3737 signal_to_string(sig));
3738 }
3739
3740 static int operation_to_signal(KillContext *c, KillOperation k) {
3741 assert(c);
3742
3743 switch (k) {
3744
3745 case KILL_TERMINATE:
3746 case KILL_TERMINATE_AND_LOG:
3747 return c->kill_signal;
3748
3749 case KILL_KILL:
3750 return SIGKILL;
3751
3752 case KILL_ABORT:
3753 return SIGABRT;
3754
3755 default:
3756 assert_not_reached("KillOperation unknown");
3757 }
3758 }
3759
3760 int unit_kill_context(
3761 Unit *u,
3762 KillContext *c,
3763 KillOperation k,
3764 pid_t main_pid,
3765 pid_t control_pid,
3766 bool main_pid_alien) {
3767
3768 bool wait_for_exit = false, send_sighup;
3769 cg_kill_log_func_t log_func = NULL;
3770 int sig, r;
3771
3772 assert(u);
3773 assert(c);
3774
3775 /* Kill the processes belonging to this unit, in preparation for shutting the unit down.
3776 * Returns > 0 if we killed something worth waiting for, 0 otherwise. */
3777
3778 if (c->kill_mode == KILL_NONE)
3779 return 0;
3780
3781 sig = operation_to_signal(c, k);
3782
3783 send_sighup =
3784 c->send_sighup &&
3785 IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
3786 sig != SIGHUP;
3787
3788 if (k != KILL_TERMINATE || IN_SET(sig, SIGKILL, SIGABRT))
3789 log_func = log_kill;
3790
3791 if (main_pid > 0) {
3792 if (log_func)
3793 log_func(main_pid, sig, u);
3794
3795 r = kill_and_sigcont(main_pid, sig);
3796 if (r < 0 && r != -ESRCH) {
3797 _cleanup_free_ char *comm = NULL;
3798 (void) get_process_comm(main_pid, &comm);
3799
3800 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
3801 } else {
3802 if (!main_pid_alien)
3803 wait_for_exit = true;
3804
3805 if (r != -ESRCH && send_sighup)
3806 (void) kill(main_pid, SIGHUP);
3807 }
3808 }
3809
3810 if (control_pid > 0) {
3811 if (log_func)
3812 log_func(control_pid, sig, u);
3813
3814 r = kill_and_sigcont(control_pid, sig);
3815 if (r < 0 && r != -ESRCH) {
3816 _cleanup_free_ char *comm = NULL;
3817 (void) get_process_comm(control_pid, &comm);
3818
3819 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
3820 } else {
3821 wait_for_exit = true;
3822
3823 if (r != -ESRCH && send_sighup)
3824 (void) kill(control_pid, SIGHUP);
3825 }
3826 }
3827
3828 if (u->cgroup_path &&
3829 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
3830 _cleanup_set_free_ Set *pid_set = NULL;
3831
3832 /* Exclude the main/control pids from being killed via the cgroup */
3833 pid_set = unit_pid_set(main_pid, control_pid);
3834 if (!pid_set)
3835 return -ENOMEM;
3836
3837 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
3838 sig,
3839 CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
3840 pid_set,
3841 log_func, u);
3842 if (r < 0) {
3843 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
3844 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
3845
3846 } else if (r > 0) {
3847
3848 /* FIXME: For now, on the legacy hierarchy, we
3849 * will not wait for the cgroup members to die
3850 * if we are running in a container or if this
3851 * is a delegation unit, simply because cgroup
3852 * notification is unreliable in these
3853 * cases. It doesn't work at all in
3854 * containers, and outside of containers it
3855 * can be confused easily by left-over
3856 * directories in the cgroup — which however
3857 * should not exist in non-delegated units. On
3858 * the unified hierarchy that's different,
3859 * there we get proper events. Hence rely on
3860 * them.*/
3861
3862 if (cg_unified(SYSTEMD_CGROUP_CONTROLLER) > 0 ||
3863 (detect_container() == 0 && !unit_cgroup_delegate(u)))
3864 wait_for_exit = true;
3865
3866 if (send_sighup) {
3867 set_free(pid_set);
3868
3869 pid_set = unit_pid_set(main_pid, control_pid);
3870 if (!pid_set)
3871 return -ENOMEM;
3872
3873 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
3874 SIGHUP,
3875 CGROUP_IGNORE_SELF,
3876 pid_set,
3877 NULL, NULL);
3878 }
3879 }
3880 }
3881
3882 return wait_for_exit;
3883 }
3884
3885 int unit_require_mounts_for(Unit *u, const char *path) {
3886 char prefix[strlen(path) + 1], *p;
3887 int r;
3888
3889 assert(u);
3890 assert(path);
3891
3892 /* Registers a unit for requiring a certain path and all its
3893 * prefixes. We keep a simple array of these paths in the
3894 * unit, since its usually short. However, we build a prefix
3895 * table for all possible prefixes so that new appearing mount
3896 * units can easily determine which units to make themselves a
3897 * dependency of. */
3898
3899 if (!path_is_absolute(path))
3900 return -EINVAL;
3901
3902 p = strdup(path);
3903 if (!p)
3904 return -ENOMEM;
3905
3906 path_kill_slashes(p);
3907
3908 if (!path_is_safe(p)) {
3909 free(p);
3910 return -EPERM;
3911 }
3912
3913 if (strv_contains(u->requires_mounts_for, p)) {
3914 free(p);
3915 return 0;
3916 }
3917
3918 r = strv_consume(&u->requires_mounts_for, p);
3919 if (r < 0)
3920 return r;
3921
3922 PATH_FOREACH_PREFIX_MORE(prefix, p) {
3923 Set *x;
3924
3925 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
3926 if (!x) {
3927 char *q;
3928
3929 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
3930 if (r < 0)
3931 return r;
3932
3933 q = strdup(prefix);
3934 if (!q)
3935 return -ENOMEM;
3936
3937 x = set_new(NULL);
3938 if (!x) {
3939 free(q);
3940 return -ENOMEM;
3941 }
3942
3943 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
3944 if (r < 0) {
3945 free(q);
3946 set_free(x);
3947 return r;
3948 }
3949 }
3950
3951 r = set_put(x, u);
3952 if (r < 0)
3953 return r;
3954 }
3955
3956 return 0;
3957 }
3958
3959 int unit_setup_exec_runtime(Unit *u) {
3960 ExecRuntime **rt;
3961 size_t offset;
3962 Iterator i;
3963 Unit *other;
3964
3965 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3966 assert(offset > 0);
3967
3968 /* Check if there already is an ExecRuntime for this unit? */
3969 rt = (ExecRuntime**) ((uint8_t*) u + offset);
3970 if (*rt)
3971 return 0;
3972
3973 /* Try to get it from somebody else */
3974 SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
3975
3976 *rt = unit_get_exec_runtime(other);
3977 if (*rt) {
3978 exec_runtime_ref(*rt);
3979 return 0;
3980 }
3981 }
3982
3983 return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
3984 }
3985
3986 int unit_setup_dynamic_creds(Unit *u) {
3987 ExecContext *ec;
3988 DynamicCreds *dcreds;
3989 size_t offset;
3990
3991 assert(u);
3992
3993 offset = UNIT_VTABLE(u)->dynamic_creds_offset;
3994 assert(offset > 0);
3995 dcreds = (DynamicCreds*) ((uint8_t*) u + offset);
3996
3997 ec = unit_get_exec_context(u);
3998 assert(ec);
3999
4000 if (!ec->dynamic_user)
4001 return 0;
4002
4003 return dynamic_creds_acquire(dcreds, u->manager, ec->user, ec->group);
4004 }
4005
4006 bool unit_type_supported(UnitType t) {
4007 if (_unlikely_(t < 0))
4008 return false;
4009 if (_unlikely_(t >= _UNIT_TYPE_MAX))
4010 return false;
4011
4012 if (!unit_vtable[t]->supported)
4013 return true;
4014
4015 return unit_vtable[t]->supported();
4016 }
4017
4018 void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
4019 int r;
4020
4021 assert(u);
4022 assert(where);
4023
4024 r = dir_is_empty(where);
4025 if (r > 0)
4026 return;
4027 if (r < 0) {
4028 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
4029 return;
4030 }
4031
4032 log_struct(LOG_NOTICE,
4033 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
4034 LOG_UNIT_ID(u),
4035 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
4036 "WHERE=%s", where,
4037 NULL);
4038 }
4039
4040 int unit_fail_if_symlink(Unit *u, const char* where) {
4041 int r;
4042
4043 assert(u);
4044 assert(where);
4045
4046 r = is_symlink(where);
4047 if (r < 0) {
4048 log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
4049 return 0;
4050 }
4051 if (r == 0)
4052 return 0;
4053
4054 log_struct(LOG_ERR,
4055 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
4056 LOG_UNIT_ID(u),
4057 LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
4058 "WHERE=%s", where,
4059 NULL);
4060
4061 return -ELOOP;
4062 }
4063
4064 bool unit_is_pristine(Unit *u) {
4065 assert(u);
4066
4067 /* Check if the unit already exists or is already around,
4068 * in a number of different ways. Note that to cater for unit
4069 * types such as slice, we are generally fine with units that
4070 * are marked UNIT_LOADED even though nothing was
4071 * actually loaded, as those unit types don't require a file
4072 * on disk to validly load. */
4073
4074 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
4075 u->fragment_path ||
4076 u->source_path ||
4077 !strv_isempty(u->dropin_paths) ||
4078 u->job ||
4079 u->merged_into);
4080 }
4081
4082 pid_t unit_control_pid(Unit *u) {
4083 assert(u);
4084
4085 if (UNIT_VTABLE(u)->control_pid)
4086 return UNIT_VTABLE(u)->control_pid(u);
4087
4088 return 0;
4089 }
4090
4091 pid_t unit_main_pid(Unit *u) {
4092 assert(u);
4093
4094 if (UNIT_VTABLE(u)->main_pid)
4095 return UNIT_VTABLE(u)->main_pid(u);
4096
4097 return 0;
4098 }
4099
4100 static void unit_unref_uid_internal(
4101 Unit *u,
4102 uid_t *ref_uid,
4103 bool destroy_now,
4104 void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
4105
4106 assert(u);
4107 assert(ref_uid);
4108 assert(_manager_unref_uid);
4109
4110 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
4111 * gid_t are actually the same time, with the same validity rules.
4112 *
4113 * Drops a reference to UID/GID from a unit. */
4114
4115 assert_cc(sizeof(uid_t) == sizeof(gid_t));
4116 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
4117
4118 if (!uid_is_valid(*ref_uid))
4119 return;
4120
4121 _manager_unref_uid(u->manager, *ref_uid, destroy_now);
4122 *ref_uid = UID_INVALID;
4123 }
4124
4125 void unit_unref_uid(Unit *u, bool destroy_now) {
4126 unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
4127 }
4128
4129 void unit_unref_gid(Unit *u, bool destroy_now) {
4130 unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
4131 }
4132
4133 static int unit_ref_uid_internal(
4134 Unit *u,
4135 uid_t *ref_uid,
4136 uid_t uid,
4137 bool clean_ipc,
4138 int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
4139
4140 int r;
4141
4142 assert(u);
4143 assert(ref_uid);
4144 assert(uid_is_valid(uid));
4145 assert(_manager_ref_uid);
4146
4147 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
4148 * are actually the same type, and have the same validity rules.
4149 *
4150 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
4151 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
4152 * drops to zero. */
4153
4154 assert_cc(sizeof(uid_t) == sizeof(gid_t));
4155 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
4156
4157 if (*ref_uid == uid)
4158 return 0;
4159
4160 if (uid_is_valid(*ref_uid)) /* Already set? */
4161 return -EBUSY;
4162
4163 r = _manager_ref_uid(u->manager, uid, clean_ipc);
4164 if (r < 0)
4165 return r;
4166
4167 *ref_uid = uid;
4168 return 1;
4169 }
4170
4171 int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
4172 return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
4173 }
4174
4175 int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
4176 return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
4177 }
4178
4179 static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
4180 int r = 0, q = 0;
4181
4182 assert(u);
4183
4184 /* Reference both a UID and a GID in one go. Either references both, or neither. */
4185
4186 if (uid_is_valid(uid)) {
4187 r = unit_ref_uid(u, uid, clean_ipc);
4188 if (r < 0)
4189 return r;
4190 }
4191
4192 if (gid_is_valid(gid)) {
4193 q = unit_ref_gid(u, gid, clean_ipc);
4194 if (q < 0) {
4195 if (r > 0)
4196 unit_unref_uid(u, false);
4197
4198 return q;
4199 }
4200 }
4201
4202 return r > 0 || q > 0;
4203 }
4204
4205 int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
4206 ExecContext *c;
4207 int r;
4208
4209 assert(u);
4210
4211 c = unit_get_exec_context(u);
4212
4213 r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
4214 if (r < 0)
4215 return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
4216
4217 return r;
4218 }
4219
4220 void unit_unref_uid_gid(Unit *u, bool destroy_now) {
4221 assert(u);
4222
4223 unit_unref_uid(u, destroy_now);
4224 unit_unref_gid(u, destroy_now);
4225 }
4226
4227 void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
4228 int r;
4229
4230 assert(u);
4231
4232 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
4233 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
4234 * objects when no service references the UID/GID anymore. */
4235
4236 r = unit_ref_uid_gid(u, uid, gid);
4237 if (r > 0)
4238 bus_unit_send_change_signal(u);
4239 }
4240
4241 int unit_set_invocation_id(Unit *u, sd_id128_t id) {
4242 int r;
4243
4244 assert(u);
4245
4246 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
4247
4248 if (sd_id128_equal(u->invocation_id, id))
4249 return 0;
4250
4251 if (!sd_id128_is_null(u->invocation_id))
4252 (void) hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
4253
4254 if (sd_id128_is_null(id)) {
4255 r = 0;
4256 goto reset;
4257 }
4258
4259 r = hashmap_ensure_allocated(&u->manager->units_by_invocation_id, &id128_hash_ops);
4260 if (r < 0)
4261 goto reset;
4262
4263 u->invocation_id = id;
4264 sd_id128_to_string(id, u->invocation_id_string);
4265
4266 r = hashmap_put(u->manager->units_by_invocation_id, &u->invocation_id, u);
4267 if (r < 0)
4268 goto reset;
4269
4270 return 0;
4271
4272 reset:
4273 u->invocation_id = SD_ID128_NULL;
4274 u->invocation_id_string[0] = 0;
4275 return r;
4276 }
4277
4278 int unit_acquire_invocation_id(Unit *u) {
4279 sd_id128_t id;
4280 int r;
4281
4282 assert(u);
4283
4284 r = sd_id128_randomize(&id);
4285 if (r < 0)
4286 return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
4287
4288 r = unit_set_invocation_id(u, id);
4289 if (r < 0)
4290 return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
4291
4292 return 0;
4293 }