]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/unit.c
journalctl: rotation is not a reason to warn, but certainly noteworthy
[thirdparty/systemd.git] / src / core / unit.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <stdlib.h>
5 #include <sys/prctl.h>
6 #include <unistd.h>
7
8 #include "sd-id128.h"
9 #include "sd-messages.h"
10
11 #include "all-units.h"
12 #include "alloc-util.h"
13 #include "bpf-firewall.h"
14 #include "bus-common-errors.h"
15 #include "bus-util.h"
16 #include "cgroup-setup.h"
17 #include "cgroup-util.h"
18 #include "core-varlink.h"
19 #include "dbus-unit.h"
20 #include "dbus.h"
21 #include "dropin.h"
22 #include "escape.h"
23 #include "execute.h"
24 #include "fd-util.h"
25 #include "fileio-label.h"
26 #include "fileio.h"
27 #include "format-util.h"
28 #include "id128-util.h"
29 #include "io-util.h"
30 #include "install.h"
31 #include "label.h"
32 #include "load-dropin.h"
33 #include "load-fragment.h"
34 #include "log.h"
35 #include "macro.h"
36 #include "missing_audit.h"
37 #include "mkdir.h"
38 #include "parse-util.h"
39 #include "path-util.h"
40 #include "process-util.h"
41 #include "rm-rf.h"
42 #include "serialize.h"
43 #include "set.h"
44 #include "signal-util.h"
45 #include "sparse-endian.h"
46 #include "special.h"
47 #include "specifier.h"
48 #include "stat-util.h"
49 #include "stdio-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
52 #include "strv.h"
53 #include "terminal-util.h"
54 #include "tmpfile-util.h"
55 #include "umask-util.h"
56 #include "unit-name.h"
57 #include "unit.h"
58 #include "user-util.h"
59 #include "virt.h"
60
61 /* Thresholds for logging at INFO level about resource consumption */
62 #define MENTIONWORTHY_CPU_NSEC (1 * NSEC_PER_SEC)
63 #define MENTIONWORTHY_IO_BYTES (1024 * 1024ULL)
64 #define MENTIONWORTHY_IP_BYTES (0ULL)
65
66 /* Thresholds for logging at INFO level about resource consumption */
67 #define NOTICEWORTHY_CPU_NSEC (10*60 * NSEC_PER_SEC) /* 10 minutes */
68 #define NOTICEWORTHY_IO_BYTES (10 * 1024 * 1024ULL) /* 10 MB */
69 #define NOTICEWORTHY_IP_BYTES (128 * 1024 * 1024ULL) /* 128 MB */
70
71 const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
72 [UNIT_SERVICE] = &service_vtable,
73 [UNIT_SOCKET] = &socket_vtable,
74 [UNIT_TARGET] = &target_vtable,
75 [UNIT_DEVICE] = &device_vtable,
76 [UNIT_MOUNT] = &mount_vtable,
77 [UNIT_AUTOMOUNT] = &automount_vtable,
78 [UNIT_SWAP] = &swap_vtable,
79 [UNIT_TIMER] = &timer_vtable,
80 [UNIT_PATH] = &path_vtable,
81 [UNIT_SLICE] = &slice_vtable,
82 [UNIT_SCOPE] = &scope_vtable,
83 };
84
85 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
86
87 Unit *unit_new(Manager *m, size_t size) {
88 Unit *u;
89
90 assert(m);
91 assert(size >= sizeof(Unit));
92
93 u = malloc0(size);
94 if (!u)
95 return NULL;
96
97 u->manager = m;
98 u->type = _UNIT_TYPE_INVALID;
99 u->default_dependencies = true;
100 u->unit_file_state = _UNIT_FILE_STATE_INVALID;
101 u->unit_file_preset = -1;
102 u->on_failure_job_mode = JOB_REPLACE;
103 u->cgroup_control_inotify_wd = -1;
104 u->cgroup_memory_inotify_wd = -1;
105 u->job_timeout = USEC_INFINITY;
106 u->job_running_timeout = USEC_INFINITY;
107 u->ref_uid = UID_INVALID;
108 u->ref_gid = GID_INVALID;
109 u->cpu_usage_last = NSEC_INFINITY;
110 u->cgroup_invalidated_mask |= CGROUP_MASK_BPF_FIREWALL;
111 u->failure_action_exit_status = u->success_action_exit_status = -1;
112
113 u->ip_accounting_ingress_map_fd = -1;
114 u->ip_accounting_egress_map_fd = -1;
115 u->ipv4_allow_map_fd = -1;
116 u->ipv6_allow_map_fd = -1;
117 u->ipv4_deny_map_fd = -1;
118 u->ipv6_deny_map_fd = -1;
119
120 u->last_section_private = -1;
121
122 u->start_ratelimit = (RateLimit) { m->default_start_limit_interval, m->default_start_limit_burst };
123 u->auto_stop_ratelimit = (RateLimit) { 10 * USEC_PER_SEC, 16 };
124
125 for (CGroupIOAccountingMetric i = 0; i < _CGROUP_IO_ACCOUNTING_METRIC_MAX; i++)
126 u->io_accounting_last[i] = UINT64_MAX;
127
128 return u;
129 }
130
131 int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret) {
132 _cleanup_(unit_freep) Unit *u = NULL;
133 int r;
134
135 u = unit_new(m, size);
136 if (!u)
137 return -ENOMEM;
138
139 r = unit_add_name(u, name);
140 if (r < 0)
141 return r;
142
143 *ret = TAKE_PTR(u);
144
145 return r;
146 }
147
148 bool unit_has_name(const Unit *u, const char *name) {
149 assert(u);
150 assert(name);
151
152 return streq_ptr(name, u->id) ||
153 set_contains(u->aliases, name);
154 }
155
156 static void unit_init(Unit *u) {
157 CGroupContext *cc;
158 ExecContext *ec;
159 KillContext *kc;
160
161 assert(u);
162 assert(u->manager);
163 assert(u->type >= 0);
164
165 cc = unit_get_cgroup_context(u);
166 if (cc) {
167 cgroup_context_init(cc);
168
169 /* Copy in the manager defaults into the cgroup
170 * context, _before_ the rest of the settings have
171 * been initialized */
172
173 cc->cpu_accounting = u->manager->default_cpu_accounting;
174 cc->io_accounting = u->manager->default_io_accounting;
175 cc->blockio_accounting = u->manager->default_blockio_accounting;
176 cc->memory_accounting = u->manager->default_memory_accounting;
177 cc->tasks_accounting = u->manager->default_tasks_accounting;
178 cc->ip_accounting = u->manager->default_ip_accounting;
179
180 if (u->type != UNIT_SLICE)
181 cc->tasks_max = u->manager->default_tasks_max;
182 }
183
184 ec = unit_get_exec_context(u);
185 if (ec) {
186 exec_context_init(ec);
187
188 if (MANAGER_IS_SYSTEM(u->manager))
189 ec->keyring_mode = EXEC_KEYRING_SHARED;
190 else {
191 ec->keyring_mode = EXEC_KEYRING_INHERIT;
192
193 /* User manager might have its umask redefined by PAM or UMask=. In this
194 * case let the units it manages inherit this value by default. They can
195 * still tune this value through their own unit file */
196 (void) get_process_umask(getpid_cached(), &ec->umask);
197 }
198 }
199
200 kc = unit_get_kill_context(u);
201 if (kc)
202 kill_context_init(kc);
203
204 if (UNIT_VTABLE(u)->init)
205 UNIT_VTABLE(u)->init(u);
206 }
207
208 static int unit_add_alias(Unit *u, char *donated_name) {
209 int r;
210
211 /* Make sure that u->names is allocated. We may leave u->names
212 * empty if we fail later, but this is not a problem. */
213 r = set_ensure_put(&u->aliases, &string_hash_ops, donated_name);
214 if (r < 0)
215 return r;
216 assert(r > 0);
217
218 return 0;
219 }
220
221 int unit_add_name(Unit *u, const char *text) {
222 _cleanup_free_ char *name = NULL, *instance = NULL;
223 UnitType t;
224 int r;
225
226 assert(u);
227 assert(text);
228
229 if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
230 if (!u->instance)
231 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
232 "instance is not set when adding name '%s': %m", text);
233
234 r = unit_name_replace_instance(text, u->instance, &name);
235 if (r < 0)
236 return log_unit_debug_errno(u, r,
237 "failed to build instance name from '%s': %m", text);
238 } else {
239 name = strdup(text);
240 if (!name)
241 return -ENOMEM;
242 }
243
244 if (unit_has_name(u, name))
245 return 0;
246
247 if (hashmap_contains(u->manager->units, name))
248 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
249 "unit already exist when adding name '%s': %m", name);
250
251 if (!unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
252 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
253 "name '%s' is invalid: %m", name);
254
255 t = unit_name_to_type(name);
256 if (t < 0)
257 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
258 "failed to derive unit type from name '%s': %m", name);
259
260 if (u->type != _UNIT_TYPE_INVALID && t != u->type)
261 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
262 "unit type is illegal: u->type(%d) and t(%d) for name '%s': %m",
263 u->type, t, name);
264
265 r = unit_name_to_instance(name, &instance);
266 if (r < 0)
267 return log_unit_debug_errno(u, r, "failed to extract instance from name '%s': %m", name);
268
269 if (instance && !unit_type_may_template(t))
270 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL), "templates are not allowed for name '%s': %m", name);
271
272 /* Ensure that this unit either has no instance, or that the instance matches. */
273 if (u->type != _UNIT_TYPE_INVALID && !streq_ptr(u->instance, instance))
274 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EINVAL),
275 "cannot add name %s, the instances don't match (\"%s\" != \"%s\").",
276 name, instance, u->instance);
277
278 if (u->id && !unit_type_may_alias(t))
279 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EEXIST),
280 "cannot add name %s, aliases are not allowed for %s units.",
281 name, unit_type_to_string(t));
282
283 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
284 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(E2BIG), "cannot add name, manager has too many units: %m");
285
286 /* Add name to the global hashmap first, because that's easier to undo */
287 r = hashmap_put(u->manager->units, name, u);
288 if (r < 0)
289 return log_unit_debug_errno(u, r, "add unit to hashmap failed for name '%s': %m", text);
290
291 if (u->id) {
292 r = unit_add_alias(u, name); /* unit_add_alias() takes ownership of the name on success */
293 if (r < 0) {
294 hashmap_remove(u->manager->units, name);
295 return r;
296 }
297 TAKE_PTR(name);
298
299 } else {
300 /* A new name, we don't need the set yet. */
301 assert(u->type == _UNIT_TYPE_INVALID);
302 assert(!u->instance);
303
304 u->type = t;
305 u->id = TAKE_PTR(name);
306 u->instance = TAKE_PTR(instance);
307
308 LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
309 unit_init(u);
310 }
311
312 unit_add_to_dbus_queue(u);
313 return 0;
314 }
315
316 int unit_choose_id(Unit *u, const char *name) {
317 _cleanup_free_ char *t = NULL;
318 char *s;
319 int r;
320
321 assert(u);
322 assert(name);
323
324 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
325 if (!u->instance)
326 return -EINVAL;
327
328 r = unit_name_replace_instance(name, u->instance, &t);
329 if (r < 0)
330 return r;
331
332 name = t;
333 }
334
335 if (streq_ptr(u->id, name))
336 return 0; /* Nothing to do. */
337
338 /* Selects one of the aliases of this unit as the id */
339 s = set_get(u->aliases, (char*) name);
340 if (!s)
341 return -ENOENT;
342
343 if (u->id) {
344 r = set_remove_and_put(u->aliases, name, u->id);
345 if (r < 0)
346 return r;
347 } else
348 assert_se(set_remove(u->aliases, name)); /* see set_get() above… */
349
350 u->id = s; /* Old u->id is now stored in the set, and s is not stored anywhere */
351 unit_add_to_dbus_queue(u);
352
353 return 0;
354 }
355
356 int unit_set_description(Unit *u, const char *description) {
357 int r;
358
359 assert(u);
360
361 r = free_and_strdup(&u->description, empty_to_null(description));
362 if (r < 0)
363 return r;
364 if (r > 0)
365 unit_add_to_dbus_queue(u);
366
367 return 0;
368 }
369
370 bool unit_may_gc(Unit *u) {
371 UnitActiveState state;
372 int r;
373
374 assert(u);
375
376 /* Checks whether the unit is ready to be unloaded for garbage collection.
377 * Returns true when the unit may be collected, and false if there's some
378 * reason to keep it loaded.
379 *
380 * References from other units are *not* checked here. Instead, this is done
381 * in unit_gc_sweep(), but using markers to properly collect dependency loops.
382 */
383
384 if (u->job)
385 return false;
386
387 if (u->nop_job)
388 return false;
389
390 state = unit_active_state(u);
391
392 /* If the unit is inactive and failed and no job is queued for it, then release its runtime resources */
393 if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
394 UNIT_VTABLE(u)->release_resources)
395 UNIT_VTABLE(u)->release_resources(u);
396
397 if (u->perpetual)
398 return false;
399
400 if (sd_bus_track_count(u->bus_track) > 0)
401 return false;
402
403 /* But we keep the unit object around for longer when it is referenced or configured to not be gc'ed */
404 switch (u->collect_mode) {
405
406 case COLLECT_INACTIVE:
407 if (state != UNIT_INACTIVE)
408 return false;
409
410 break;
411
412 case COLLECT_INACTIVE_OR_FAILED:
413 if (!IN_SET(state, UNIT_INACTIVE, UNIT_FAILED))
414 return false;
415
416 break;
417
418 default:
419 assert_not_reached("Unknown garbage collection mode");
420 }
421
422 if (u->cgroup_path) {
423 /* If the unit has a cgroup, then check whether there's anything in it. If so, we should stay
424 * around. Units with active processes should never be collected. */
425
426 r = cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path);
427 if (r < 0)
428 log_unit_debug_errno(u, r, "Failed to determine whether cgroup %s is empty: %m", u->cgroup_path);
429 if (r <= 0)
430 return false;
431 }
432
433 if (UNIT_VTABLE(u)->may_gc && !UNIT_VTABLE(u)->may_gc(u))
434 return false;
435
436 return true;
437 }
438
439 void unit_add_to_load_queue(Unit *u) {
440 assert(u);
441 assert(u->type != _UNIT_TYPE_INVALID);
442
443 if (u->load_state != UNIT_STUB || u->in_load_queue)
444 return;
445
446 LIST_PREPEND(load_queue, u->manager->load_queue, u);
447 u->in_load_queue = true;
448 }
449
450 void unit_add_to_cleanup_queue(Unit *u) {
451 assert(u);
452
453 if (u->in_cleanup_queue)
454 return;
455
456 LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
457 u->in_cleanup_queue = true;
458 }
459
460 void unit_add_to_gc_queue(Unit *u) {
461 assert(u);
462
463 if (u->in_gc_queue || u->in_cleanup_queue)
464 return;
465
466 if (!unit_may_gc(u))
467 return;
468
469 LIST_PREPEND(gc_queue, u->manager->gc_unit_queue, u);
470 u->in_gc_queue = true;
471 }
472
473 void unit_add_to_dbus_queue(Unit *u) {
474 assert(u);
475 assert(u->type != _UNIT_TYPE_INVALID);
476
477 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
478 return;
479
480 /* Shortcut things if nobody cares */
481 if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
482 sd_bus_track_count(u->bus_track) <= 0 &&
483 set_isempty(u->manager->private_buses)) {
484 u->sent_dbus_new_signal = true;
485 return;
486 }
487
488 LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
489 u->in_dbus_queue = true;
490 }
491
492 void unit_submit_to_stop_when_unneeded_queue(Unit *u) {
493 assert(u);
494
495 if (u->in_stop_when_unneeded_queue)
496 return;
497
498 if (!u->stop_when_unneeded)
499 return;
500
501 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
502 return;
503
504 LIST_PREPEND(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
505 u->in_stop_when_unneeded_queue = true;
506 }
507
508 static void bidi_set_free(Unit *u, Hashmap *h) {
509 Unit *other;
510 void *v;
511
512 assert(u);
513
514 /* Frees the hashmap and makes sure we are dropped from the inverse pointers */
515
516 HASHMAP_FOREACH_KEY(v, other, h) {
517 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
518 hashmap_remove(other->dependencies[d], u);
519
520 unit_add_to_gc_queue(other);
521 }
522
523 hashmap_free(h);
524 }
525
526 static void unit_remove_transient(Unit *u) {
527 char **i;
528
529 assert(u);
530
531 if (!u->transient)
532 return;
533
534 if (u->fragment_path)
535 (void) unlink(u->fragment_path);
536
537 STRV_FOREACH(i, u->dropin_paths) {
538 _cleanup_free_ char *p = NULL, *pp = NULL;
539
540 p = dirname_malloc(*i); /* Get the drop-in directory from the drop-in file */
541 if (!p)
542 continue;
543
544 pp = dirname_malloc(p); /* Get the config directory from the drop-in directory */
545 if (!pp)
546 continue;
547
548 /* Only drop transient drop-ins */
549 if (!path_equal(u->manager->lookup_paths.transient, pp))
550 continue;
551
552 (void) unlink(*i);
553 (void) rmdir(p);
554 }
555 }
556
557 static void unit_free_requires_mounts_for(Unit *u) {
558 assert(u);
559
560 for (;;) {
561 _cleanup_free_ char *path;
562
563 path = hashmap_steal_first_key(u->requires_mounts_for);
564 if (!path)
565 break;
566 else {
567 char s[strlen(path) + 1];
568
569 PATH_FOREACH_PREFIX_MORE(s, path) {
570 char *y;
571 Set *x;
572
573 x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
574 if (!x)
575 continue;
576
577 (void) set_remove(x, u);
578
579 if (set_isempty(x)) {
580 (void) hashmap_remove(u->manager->units_requiring_mounts_for, y);
581 free(y);
582 set_free(x);
583 }
584 }
585 }
586 }
587
588 u->requires_mounts_for = hashmap_free(u->requires_mounts_for);
589 }
590
591 static void unit_done(Unit *u) {
592 ExecContext *ec;
593 CGroupContext *cc;
594
595 assert(u);
596
597 if (u->type < 0)
598 return;
599
600 if (UNIT_VTABLE(u)->done)
601 UNIT_VTABLE(u)->done(u);
602
603 ec = unit_get_exec_context(u);
604 if (ec)
605 exec_context_done(ec);
606
607 cc = unit_get_cgroup_context(u);
608 if (cc)
609 cgroup_context_done(cc);
610 }
611
612 void unit_free(Unit *u) {
613 char *t;
614
615 if (!u)
616 return;
617
618 u->transient_file = safe_fclose(u->transient_file);
619
620 if (!MANAGER_IS_RELOADING(u->manager))
621 unit_remove_transient(u);
622
623 bus_unit_send_removed_signal(u);
624
625 unit_done(u);
626
627 unit_dequeue_rewatch_pids(u);
628
629 sd_bus_slot_unref(u->match_bus_slot);
630 sd_bus_track_unref(u->bus_track);
631 u->deserialized_refs = strv_free(u->deserialized_refs);
632 u->pending_freezer_message = sd_bus_message_unref(u->pending_freezer_message);
633
634 unit_free_requires_mounts_for(u);
635
636 SET_FOREACH(t, u->aliases)
637 hashmap_remove_value(u->manager->units, t, u);
638 if (u->id)
639 hashmap_remove_value(u->manager->units, u->id, u);
640
641 if (!sd_id128_is_null(u->invocation_id))
642 hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
643
644 if (u->job) {
645 Job *j = u->job;
646 job_uninstall(j);
647 job_free(j);
648 }
649
650 if (u->nop_job) {
651 Job *j = u->nop_job;
652 job_uninstall(j);
653 job_free(j);
654 }
655
656 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
657 bidi_set_free(u, u->dependencies[d]);
658
659 /* A unit is being dropped from the tree, make sure our family is realized properly. Do this after we
660 * detach the unit from slice tree in order to eliminate its effect on controller masks. */
661 if (UNIT_ISSET(u->slice))
662 unit_add_family_to_cgroup_realize_queue(UNIT_DEREF(u->slice));
663
664 if (u->on_console)
665 manager_unref_console(u->manager);
666
667 unit_release_cgroup(u);
668
669 if (!MANAGER_IS_RELOADING(u->manager))
670 unit_unlink_state_files(u);
671
672 unit_unref_uid_gid(u, false);
673
674 (void) manager_update_failed_units(u->manager, u, false);
675 set_remove(u->manager->startup_units, u);
676
677 unit_unwatch_all_pids(u);
678
679 unit_ref_unset(&u->slice);
680 while (u->refs_by_target)
681 unit_ref_unset(u->refs_by_target);
682
683 if (u->type != _UNIT_TYPE_INVALID)
684 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
685
686 if (u->in_load_queue)
687 LIST_REMOVE(load_queue, u->manager->load_queue, u);
688
689 if (u->in_dbus_queue)
690 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
691
692 if (u->in_gc_queue)
693 LIST_REMOVE(gc_queue, u->manager->gc_unit_queue, u);
694
695 if (u->in_cgroup_realize_queue)
696 LIST_REMOVE(cgroup_realize_queue, u->manager->cgroup_realize_queue, u);
697
698 if (u->in_cgroup_empty_queue)
699 LIST_REMOVE(cgroup_empty_queue, u->manager->cgroup_empty_queue, u);
700
701 if (u->in_cleanup_queue)
702 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
703
704 if (u->in_target_deps_queue)
705 LIST_REMOVE(target_deps_queue, u->manager->target_deps_queue, u);
706
707 if (u->in_stop_when_unneeded_queue)
708 LIST_REMOVE(stop_when_unneeded_queue, u->manager->stop_when_unneeded_queue, u);
709
710 safe_close(u->ip_accounting_ingress_map_fd);
711 safe_close(u->ip_accounting_egress_map_fd);
712
713 safe_close(u->ipv4_allow_map_fd);
714 safe_close(u->ipv6_allow_map_fd);
715 safe_close(u->ipv4_deny_map_fd);
716 safe_close(u->ipv6_deny_map_fd);
717
718 bpf_program_unref(u->ip_bpf_ingress);
719 bpf_program_unref(u->ip_bpf_ingress_installed);
720 bpf_program_unref(u->ip_bpf_egress);
721 bpf_program_unref(u->ip_bpf_egress_installed);
722
723 set_free(u->ip_bpf_custom_ingress);
724 set_free(u->ip_bpf_custom_egress);
725 set_free(u->ip_bpf_custom_ingress_installed);
726 set_free(u->ip_bpf_custom_egress_installed);
727
728 bpf_program_unref(u->bpf_device_control_installed);
729
730 condition_free_list(u->conditions);
731 condition_free_list(u->asserts);
732
733 free(u->description);
734 strv_free(u->documentation);
735 free(u->fragment_path);
736 free(u->source_path);
737 strv_free(u->dropin_paths);
738 free(u->instance);
739
740 free(u->job_timeout_reboot_arg);
741 free(u->reboot_arg);
742
743 set_free_free(u->aliases);
744 free(u->id);
745
746 free(u);
747 }
748
749 FreezerState unit_freezer_state(Unit *u) {
750 assert(u);
751
752 return u->freezer_state;
753 }
754
755 int unit_freezer_state_kernel(Unit *u, FreezerState *ret) {
756 char *values[1] = {};
757 int r;
758
759 assert(u);
760
761 r = cg_get_keyed_attribute(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, "cgroup.events",
762 STRV_MAKE("frozen"), values);
763 if (r < 0)
764 return r;
765
766 r = _FREEZER_STATE_INVALID;
767
768 if (values[0]) {
769 if (streq(values[0], "0"))
770 r = FREEZER_RUNNING;
771 else if (streq(values[0], "1"))
772 r = FREEZER_FROZEN;
773 }
774
775 free(values[0]);
776 *ret = r;
777
778 return 0;
779 }
780
781 UnitActiveState unit_active_state(Unit *u) {
782 assert(u);
783
784 if (u->load_state == UNIT_MERGED)
785 return unit_active_state(unit_follow_merge(u));
786
787 /* After a reload it might happen that a unit is not correctly
788 * loaded but still has a process around. That's why we won't
789 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
790
791 return UNIT_VTABLE(u)->active_state(u);
792 }
793
794 const char* unit_sub_state_to_string(Unit *u) {
795 assert(u);
796
797 return UNIT_VTABLE(u)->sub_state_to_string(u);
798 }
799
800 static int hashmap_complete_move(Hashmap **s, Hashmap **other) {
801 assert(s);
802 assert(other);
803
804 if (!*other)
805 return 0;
806
807 if (*s)
808 return hashmap_move(*s, *other);
809 else
810 *s = TAKE_PTR(*other);
811
812 return 0;
813 }
814
815 static int merge_names(Unit *u, Unit *other) {
816 char *name;
817 int r;
818
819 assert(u);
820 assert(other);
821
822 r = unit_add_alias(u, other->id);
823 if (r < 0)
824 return r;
825
826 r = set_move(u->aliases, other->aliases);
827 if (r < 0) {
828 set_remove(u->aliases, other->id);
829 return r;
830 }
831
832 TAKE_PTR(other->id);
833 other->aliases = set_free_free(other->aliases);
834
835 SET_FOREACH(name, u->aliases)
836 assert_se(hashmap_replace(u->manager->units, name, u) == 0);
837
838 return 0;
839 }
840
841 static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
842 unsigned n_reserve;
843
844 assert(u);
845 assert(other);
846 assert(d < _UNIT_DEPENDENCY_MAX);
847
848 /*
849 * If u does not have this dependency set allocated, there is no need
850 * to reserve anything. In that case other's set will be transferred
851 * as a whole to u by complete_move().
852 */
853 if (!u->dependencies[d])
854 return 0;
855
856 /* merge_dependencies() will skip a u-on-u dependency */
857 n_reserve = hashmap_size(other->dependencies[d]) - !!hashmap_get(other->dependencies[d], u);
858
859 return hashmap_reserve(u->dependencies[d], n_reserve);
860 }
861
862 static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
863 Unit *back;
864 void *v;
865 int r;
866
867 /* Merges all dependencies of type 'd' of the unit 'other' into the deps of the unit 'u' */
868
869 assert(u);
870 assert(other);
871 assert(d < _UNIT_DEPENDENCY_MAX);
872
873 /* Fix backwards pointers. Let's iterate through all dependent units of the other unit. */
874 HASHMAP_FOREACH_KEY(v, back, other->dependencies[d])
875
876 /* Let's now iterate through the dependencies of that dependencies of the other units,
877 * looking for pointers back, and let's fix them up, to instead point to 'u'. */
878 for (UnitDependency k = 0; k < _UNIT_DEPENDENCY_MAX; k++)
879 if (back == u) {
880 /* Do not add dependencies between u and itself. */
881 if (hashmap_remove(back->dependencies[k], other))
882 maybe_warn_about_dependency(u, other_id, k);
883 } else {
884 UnitDependencyInfo di_u, di_other;
885
886 /* Let's drop this dependency between "back" and "other", and let's create it between
887 * "back" and "u" instead. Let's merge the bit masks of the dependency we are moving,
888 * and any such dependency which might already exist */
889
890 di_other.data = hashmap_get(back->dependencies[k], other);
891 if (!di_other.data)
892 continue; /* dependency isn't set, let's try the next one */
893
894 di_u.data = hashmap_get(back->dependencies[k], u);
895
896 UnitDependencyInfo di_merged = {
897 .origin_mask = di_u.origin_mask | di_other.origin_mask,
898 .destination_mask = di_u.destination_mask | di_other.destination_mask,
899 };
900
901 r = hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data);
902 if (r < 0)
903 log_warning_errno(r, "Failed to remove/replace: back=%s other=%s u=%s: %m", back->id, other_id, u->id);
904 assert(r >= 0);
905
906 /* assert_se(hashmap_remove_and_replace(back->dependencies[k], other, u, di_merged.data) >= 0); */
907 }
908
909 /* Also do not move dependencies on u to itself */
910 back = hashmap_remove(other->dependencies[d], u);
911 if (back)
912 maybe_warn_about_dependency(u, other_id, d);
913
914 /* The move cannot fail. The caller must have performed a reservation. */
915 assert_se(hashmap_complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
916
917 other->dependencies[d] = hashmap_free(other->dependencies[d]);
918 }
919
920 int unit_merge(Unit *u, Unit *other) {
921 const char *other_id = NULL;
922 int r;
923
924 assert(u);
925 assert(other);
926 assert(u->manager == other->manager);
927 assert(u->type != _UNIT_TYPE_INVALID);
928
929 other = unit_follow_merge(other);
930
931 if (other == u)
932 return 0;
933
934 if (u->type != other->type)
935 return -EINVAL;
936
937 if (!unit_type_may_alias(u->type)) /* Merging only applies to unit names that support aliases */
938 return -EEXIST;
939
940 if (!IN_SET(other->load_state, UNIT_STUB, UNIT_NOT_FOUND))
941 return -EEXIST;
942
943 if (!streq_ptr(u->instance, other->instance))
944 return -EINVAL;
945
946 if (other->job)
947 return -EEXIST;
948
949 if (other->nop_job)
950 return -EEXIST;
951
952 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
953 return -EEXIST;
954
955 if (other->id)
956 other_id = strdupa(other->id);
957
958 /* Make reservations to ensure merge_dependencies() won't fail */
959 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
960 r = reserve_dependencies(u, other, d);
961 /*
962 * We don't rollback reservations if we fail. We don't have
963 * a way to undo reservations. A reservation is not a leak.
964 */
965 if (r < 0)
966 return r;
967 }
968
969 /* Merge names */
970 r = merge_names(u, other);
971 if (r < 0)
972 return r;
973
974 /* Redirect all references */
975 while (other->refs_by_target)
976 unit_ref_set(other->refs_by_target, other->refs_by_target->source, u);
977
978 /* Merge dependencies */
979 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
980 merge_dependencies(u, other, other_id, d);
981
982 other->load_state = UNIT_MERGED;
983 other->merged_into = u;
984
985 /* If there is still some data attached to the other node, we
986 * don't need it anymore, and can free it. */
987 if (other->load_state != UNIT_STUB)
988 if (UNIT_VTABLE(other)->done)
989 UNIT_VTABLE(other)->done(other);
990
991 unit_add_to_dbus_queue(u);
992 unit_add_to_cleanup_queue(other);
993
994 return 0;
995 }
996
997 int unit_merge_by_name(Unit *u, const char *name) {
998 _cleanup_free_ char *s = NULL;
999 Unit *other;
1000 int r;
1001
1002 /* Either add name to u, or if a unit with name already exists, merge it with u.
1003 * If name is a template, do the same for name@instance, where instance is u's instance. */
1004
1005 assert(u);
1006 assert(name);
1007
1008 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
1009 if (!u->instance)
1010 return -EINVAL;
1011
1012 r = unit_name_replace_instance(name, u->instance, &s);
1013 if (r < 0)
1014 return r;
1015
1016 name = s;
1017 }
1018
1019 other = manager_get_unit(u->manager, name);
1020 if (other)
1021 return unit_merge(u, other);
1022
1023 return unit_add_name(u, name);
1024 }
1025
1026 Unit* unit_follow_merge(Unit *u) {
1027 assert(u);
1028
1029 while (u->load_state == UNIT_MERGED)
1030 assert_se(u = u->merged_into);
1031
1032 return u;
1033 }
1034
1035 int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
1036 int r;
1037
1038 assert(u);
1039 assert(c);
1040
1041 if (c->working_directory && !c->working_directory_missing_ok) {
1042 r = unit_require_mounts_for(u, c->working_directory, UNIT_DEPENDENCY_FILE);
1043 if (r < 0)
1044 return r;
1045 }
1046
1047 if (c->root_directory) {
1048 r = unit_require_mounts_for(u, c->root_directory, UNIT_DEPENDENCY_FILE);
1049 if (r < 0)
1050 return r;
1051 }
1052
1053 if (c->root_image) {
1054 r = unit_require_mounts_for(u, c->root_image, UNIT_DEPENDENCY_FILE);
1055 if (r < 0)
1056 return r;
1057 }
1058
1059 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
1060 if (!u->manager->prefix[dt])
1061 continue;
1062
1063 char **dp;
1064 STRV_FOREACH(dp, c->directories[dt].paths) {
1065 _cleanup_free_ char *p;
1066
1067 p = path_join(u->manager->prefix[dt], *dp);
1068 if (!p)
1069 return -ENOMEM;
1070
1071 r = unit_require_mounts_for(u, p, UNIT_DEPENDENCY_FILE);
1072 if (r < 0)
1073 return r;
1074 }
1075 }
1076
1077 if (!MANAGER_IS_SYSTEM(u->manager))
1078 return 0;
1079
1080 /* For the following three directory types we need write access, and /var/ is possibly on the root
1081 * fs. Hence order after systemd-remount-fs.service, to ensure things are writable. */
1082 if (!strv_isempty(c->directories[EXEC_DIRECTORY_STATE].paths) ||
1083 !strv_isempty(c->directories[EXEC_DIRECTORY_CACHE].paths) ||
1084 !strv_isempty(c->directories[EXEC_DIRECTORY_LOGS].paths)) {
1085 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_REMOUNT_FS_SERVICE, true, UNIT_DEPENDENCY_FILE);
1086 if (r < 0)
1087 return r;
1088 }
1089
1090 if (c->private_tmp) {
1091 const char *p;
1092
1093 FOREACH_STRING(p, "/tmp", "/var/tmp") {
1094 r = unit_require_mounts_for(u, p, UNIT_DEPENDENCY_FILE);
1095 if (r < 0)
1096 return r;
1097 }
1098
1099 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_TMPFILES_SETUP_SERVICE, true, UNIT_DEPENDENCY_FILE);
1100 if (r < 0)
1101 return r;
1102 }
1103
1104 if (c->root_image) {
1105 /* We need to wait for /dev/loopX to appear when doing RootImage=, hence let's add an
1106 * implicit dependency on udev */
1107
1108 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_UDEVD_SERVICE, true, UNIT_DEPENDENCY_FILE);
1109 if (r < 0)
1110 return r;
1111 }
1112
1113 if (!IN_SET(c->std_output,
1114 EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
1115 EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE) &&
1116 !IN_SET(c->std_error,
1117 EXEC_OUTPUT_JOURNAL, EXEC_OUTPUT_JOURNAL_AND_CONSOLE,
1118 EXEC_OUTPUT_KMSG, EXEC_OUTPUT_KMSG_AND_CONSOLE) &&
1119 !c->log_namespace)
1120 return 0;
1121
1122 /* If syslog or kernel logging is requested (or log namespacing is), make sure our own logging daemon
1123 * is run first. */
1124
1125 if (c->log_namespace) {
1126 _cleanup_free_ char *socket_unit = NULL, *varlink_socket_unit = NULL;
1127
1128 r = unit_name_build_from_type("systemd-journald", c->log_namespace, UNIT_SOCKET, &socket_unit);
1129 if (r < 0)
1130 return r;
1131
1132 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, socket_unit, true, UNIT_DEPENDENCY_FILE);
1133 if (r < 0)
1134 return r;
1135
1136 r = unit_name_build_from_type("systemd-journald-varlink", c->log_namespace, UNIT_SOCKET, &varlink_socket_unit);
1137 if (r < 0)
1138 return r;
1139
1140 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, varlink_socket_unit, true, UNIT_DEPENDENCY_FILE);
1141 if (r < 0)
1142 return r;
1143 } else
1144 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, true, UNIT_DEPENDENCY_FILE);
1145 if (r < 0)
1146 return r;
1147
1148 return 0;
1149 }
1150
1151 const char *unit_description(Unit *u) {
1152 assert(u);
1153
1154 if (u->description)
1155 return u->description;
1156
1157 return strna(u->id);
1158 }
1159
1160 const char *unit_status_string(Unit *u) {
1161 assert(u);
1162
1163 if (u->manager->status_unit_format == STATUS_UNIT_FORMAT_NAME && u->id)
1164 return u->id;
1165
1166 return unit_description(u);
1167 }
1168
1169 static void print_unit_dependency_mask(FILE *f, const char *kind, UnitDependencyMask mask, bool *space) {
1170 const struct {
1171 UnitDependencyMask mask;
1172 const char *name;
1173 } table[] = {
1174 { UNIT_DEPENDENCY_FILE, "file" },
1175 { UNIT_DEPENDENCY_IMPLICIT, "implicit" },
1176 { UNIT_DEPENDENCY_DEFAULT, "default" },
1177 { UNIT_DEPENDENCY_UDEV, "udev" },
1178 { UNIT_DEPENDENCY_PATH, "path" },
1179 { UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT, "mountinfo-implicit" },
1180 { UNIT_DEPENDENCY_MOUNTINFO_DEFAULT, "mountinfo-default" },
1181 { UNIT_DEPENDENCY_PROC_SWAP, "proc-swap" },
1182 };
1183
1184 assert(f);
1185 assert(kind);
1186 assert(space);
1187
1188 for (size_t i = 0; i < ELEMENTSOF(table); i++) {
1189
1190 if (mask == 0)
1191 break;
1192
1193 if (FLAGS_SET(mask, table[i].mask)) {
1194 if (*space)
1195 fputc(' ', f);
1196 else
1197 *space = true;
1198
1199 fputs(kind, f);
1200 fputs("-", f);
1201 fputs(table[i].name, f);
1202
1203 mask &= ~table[i].mask;
1204 }
1205 }
1206
1207 assert(mask == 0);
1208 }
1209
1210 void unit_dump(Unit *u, FILE *f, const char *prefix) {
1211 char *t, **j;
1212 const char *prefix2;
1213 char timestamp[5][FORMAT_TIMESTAMP_MAX], timespan[FORMAT_TIMESPAN_MAX];
1214 Unit *following;
1215 _cleanup_set_free_ Set *following_set = NULL;
1216 CGroupMask m;
1217 int r;
1218
1219 assert(u);
1220 assert(u->type >= 0);
1221
1222 prefix = strempty(prefix);
1223 prefix2 = strjoina(prefix, "\t");
1224
1225 fprintf(f,
1226 "%s-> Unit %s:\n",
1227 prefix, u->id);
1228
1229 SET_FOREACH(t, u->aliases)
1230 fprintf(f, "%s\tAlias: %s\n", prefix, t);
1231
1232 fprintf(f,
1233 "%s\tDescription: %s\n"
1234 "%s\tInstance: %s\n"
1235 "%s\tUnit Load State: %s\n"
1236 "%s\tUnit Active State: %s\n"
1237 "%s\tState Change Timestamp: %s\n"
1238 "%s\tInactive Exit Timestamp: %s\n"
1239 "%s\tActive Enter Timestamp: %s\n"
1240 "%s\tActive Exit Timestamp: %s\n"
1241 "%s\tInactive Enter Timestamp: %s\n"
1242 "%s\tMay GC: %s\n"
1243 "%s\tNeed Daemon Reload: %s\n"
1244 "%s\tTransient: %s\n"
1245 "%s\tPerpetual: %s\n"
1246 "%s\tGarbage Collection Mode: %s\n"
1247 "%s\tSlice: %s\n"
1248 "%s\tCGroup: %s\n"
1249 "%s\tCGroup realized: %s\n",
1250 prefix, unit_description(u),
1251 prefix, strna(u->instance),
1252 prefix, unit_load_state_to_string(u->load_state),
1253 prefix, unit_active_state_to_string(unit_active_state(u)),
1254 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->state_change_timestamp.realtime)),
1255 prefix, strna(format_timestamp(timestamp[1], sizeof(timestamp[1]), u->inactive_exit_timestamp.realtime)),
1256 prefix, strna(format_timestamp(timestamp[2], sizeof(timestamp[2]), u->active_enter_timestamp.realtime)),
1257 prefix, strna(format_timestamp(timestamp[3], sizeof(timestamp[3]), u->active_exit_timestamp.realtime)),
1258 prefix, strna(format_timestamp(timestamp[4], sizeof(timestamp[4]), u->inactive_enter_timestamp.realtime)),
1259 prefix, yes_no(unit_may_gc(u)),
1260 prefix, yes_no(unit_need_daemon_reload(u)),
1261 prefix, yes_no(u->transient),
1262 prefix, yes_no(u->perpetual),
1263 prefix, collect_mode_to_string(u->collect_mode),
1264 prefix, strna(unit_slice_name(u)),
1265 prefix, strna(u->cgroup_path),
1266 prefix, yes_no(u->cgroup_realized));
1267
1268 if (u->cgroup_realized_mask != 0) {
1269 _cleanup_free_ char *s = NULL;
1270 (void) cg_mask_to_string(u->cgroup_realized_mask, &s);
1271 fprintf(f, "%s\tCGroup realized mask: %s\n", prefix, strnull(s));
1272 }
1273
1274 if (u->cgroup_enabled_mask != 0) {
1275 _cleanup_free_ char *s = NULL;
1276 (void) cg_mask_to_string(u->cgroup_enabled_mask, &s);
1277 fprintf(f, "%s\tCGroup enabled mask: %s\n", prefix, strnull(s));
1278 }
1279
1280 m = unit_get_own_mask(u);
1281 if (m != 0) {
1282 _cleanup_free_ char *s = NULL;
1283 (void) cg_mask_to_string(m, &s);
1284 fprintf(f, "%s\tCGroup own mask: %s\n", prefix, strnull(s));
1285 }
1286
1287 m = unit_get_members_mask(u);
1288 if (m != 0) {
1289 _cleanup_free_ char *s = NULL;
1290 (void) cg_mask_to_string(m, &s);
1291 fprintf(f, "%s\tCGroup members mask: %s\n", prefix, strnull(s));
1292 }
1293
1294 m = unit_get_delegate_mask(u);
1295 if (m != 0) {
1296 _cleanup_free_ char *s = NULL;
1297 (void) cg_mask_to_string(m, &s);
1298 fprintf(f, "%s\tCGroup delegate mask: %s\n", prefix, strnull(s));
1299 }
1300
1301 if (!sd_id128_is_null(u->invocation_id))
1302 fprintf(f, "%s\tInvocation ID: " SD_ID128_FORMAT_STR "\n",
1303 prefix, SD_ID128_FORMAT_VAL(u->invocation_id));
1304
1305 STRV_FOREACH(j, u->documentation)
1306 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
1307
1308 following = unit_following(u);
1309 if (following)
1310 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
1311
1312 r = unit_following_set(u, &following_set);
1313 if (r >= 0) {
1314 Unit *other;
1315
1316 SET_FOREACH(other, following_set)
1317 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
1318 }
1319
1320 if (u->fragment_path)
1321 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
1322
1323 if (u->source_path)
1324 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
1325
1326 STRV_FOREACH(j, u->dropin_paths)
1327 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
1328
1329 if (u->failure_action != EMERGENCY_ACTION_NONE)
1330 fprintf(f, "%s\tFailure Action: %s\n", prefix, emergency_action_to_string(u->failure_action));
1331 if (u->failure_action_exit_status >= 0)
1332 fprintf(f, "%s\tFailure Action Exit Status: %i\n", prefix, u->failure_action_exit_status);
1333 if (u->success_action != EMERGENCY_ACTION_NONE)
1334 fprintf(f, "%s\tSuccess Action: %s\n", prefix, emergency_action_to_string(u->success_action));
1335 if (u->success_action_exit_status >= 0)
1336 fprintf(f, "%s\tSuccess Action Exit Status: %i\n", prefix, u->success_action_exit_status);
1337
1338 if (u->job_timeout != USEC_INFINITY)
1339 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
1340
1341 if (u->job_timeout_action != EMERGENCY_ACTION_NONE)
1342 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, emergency_action_to_string(u->job_timeout_action));
1343
1344 if (u->job_timeout_reboot_arg)
1345 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
1346
1347 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
1348 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
1349
1350 if (dual_timestamp_is_set(&u->condition_timestamp))
1351 fprintf(f,
1352 "%s\tCondition Timestamp: %s\n"
1353 "%s\tCondition Result: %s\n",
1354 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->condition_timestamp.realtime)),
1355 prefix, yes_no(u->condition_result));
1356
1357 if (dual_timestamp_is_set(&u->assert_timestamp))
1358 fprintf(f,
1359 "%s\tAssert Timestamp: %s\n"
1360 "%s\tAssert Result: %s\n",
1361 prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->assert_timestamp.realtime)),
1362 prefix, yes_no(u->assert_result));
1363
1364 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
1365 UnitDependencyInfo di;
1366 Unit *other;
1367
1368 HASHMAP_FOREACH_KEY(di.data, other, u->dependencies[d]) {
1369 bool space = false;
1370
1371 fprintf(f, "%s\t%s: %s (", prefix, unit_dependency_to_string(d), other->id);
1372
1373 print_unit_dependency_mask(f, "origin", di.origin_mask, &space);
1374 print_unit_dependency_mask(f, "destination", di.destination_mask, &space);
1375
1376 fputs(")\n", f);
1377 }
1378 }
1379
1380 if (!hashmap_isempty(u->requires_mounts_for)) {
1381 UnitDependencyInfo di;
1382 const char *path;
1383
1384 HASHMAP_FOREACH_KEY(di.data, path, u->requires_mounts_for) {
1385 bool space = false;
1386
1387 fprintf(f, "%s\tRequiresMountsFor: %s (", prefix, path);
1388
1389 print_unit_dependency_mask(f, "origin", di.origin_mask, &space);
1390 print_unit_dependency_mask(f, "destination", di.destination_mask, &space);
1391
1392 fputs(")\n", f);
1393 }
1394 }
1395
1396 if (u->load_state == UNIT_LOADED) {
1397
1398 fprintf(f,
1399 "%s\tStopWhenUnneeded: %s\n"
1400 "%s\tRefuseManualStart: %s\n"
1401 "%s\tRefuseManualStop: %s\n"
1402 "%s\tDefaultDependencies: %s\n"
1403 "%s\tOnFailureJobMode: %s\n"
1404 "%s\tIgnoreOnIsolate: %s\n",
1405 prefix, yes_no(u->stop_when_unneeded),
1406 prefix, yes_no(u->refuse_manual_start),
1407 prefix, yes_no(u->refuse_manual_stop),
1408 prefix, yes_no(u->default_dependencies),
1409 prefix, job_mode_to_string(u->on_failure_job_mode),
1410 prefix, yes_no(u->ignore_on_isolate));
1411
1412 if (UNIT_VTABLE(u)->dump)
1413 UNIT_VTABLE(u)->dump(u, f, prefix2);
1414
1415 } else if (u->load_state == UNIT_MERGED)
1416 fprintf(f,
1417 "%s\tMerged into: %s\n",
1418 prefix, u->merged_into->id);
1419 else if (u->load_state == UNIT_ERROR)
1420 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror_safe(u->load_error));
1421
1422 for (const char *n = sd_bus_track_first(u->bus_track); n; n = sd_bus_track_next(u->bus_track))
1423 fprintf(f, "%s\tBus Ref: %s\n", prefix, n);
1424
1425 if (u->job)
1426 job_dump(u->job, f, prefix2);
1427
1428 if (u->nop_job)
1429 job_dump(u->nop_job, f, prefix2);
1430 }
1431
1432 /* Common implementation for multiple backends */
1433 int unit_load_fragment_and_dropin(Unit *u, bool fragment_required) {
1434 int r;
1435
1436 assert(u);
1437
1438 /* Load a .{service,socket,...} file */
1439 r = unit_load_fragment(u);
1440 if (r < 0)
1441 return r;
1442
1443 if (u->load_state == UNIT_STUB) {
1444 if (fragment_required)
1445 return -ENOENT;
1446
1447 u->load_state = UNIT_LOADED;
1448 }
1449
1450 /* Load drop-in directory data. If u is an alias, we might be reloading the
1451 * target unit needlessly. But we cannot be sure which drops-ins have already
1452 * been loaded and which not, at least without doing complicated book-keeping,
1453 * so let's always reread all drop-ins. */
1454 r = unit_load_dropin(unit_follow_merge(u));
1455 if (r < 0)
1456 return r;
1457
1458 if (u->source_path) {
1459 struct stat st;
1460
1461 if (stat(u->source_path, &st) >= 0)
1462 u->source_mtime = timespec_load(&st.st_mtim);
1463 else
1464 u->source_mtime = 0;
1465 }
1466
1467 return 0;
1468 }
1469
1470 void unit_add_to_target_deps_queue(Unit *u) {
1471 Manager *m = u->manager;
1472
1473 assert(u);
1474
1475 if (u->in_target_deps_queue)
1476 return;
1477
1478 LIST_PREPEND(target_deps_queue, m->target_deps_queue, u);
1479 u->in_target_deps_queue = true;
1480 }
1481
1482 int unit_add_default_target_dependency(Unit *u, Unit *target) {
1483 assert(u);
1484 assert(target);
1485
1486 if (target->type != UNIT_TARGET)
1487 return 0;
1488
1489 /* Only add the dependency if both units are loaded, so that
1490 * that loop check below is reliable */
1491 if (u->load_state != UNIT_LOADED ||
1492 target->load_state != UNIT_LOADED)
1493 return 0;
1494
1495 /* If either side wants no automatic dependencies, then let's
1496 * skip this */
1497 if (!u->default_dependencies ||
1498 !target->default_dependencies)
1499 return 0;
1500
1501 /* Don't create loops */
1502 if (hashmap_get(target->dependencies[UNIT_BEFORE], u))
1503 return 0;
1504
1505 return unit_add_dependency(target, UNIT_AFTER, u, true, UNIT_DEPENDENCY_DEFAULT);
1506 }
1507
1508 static int unit_add_slice_dependencies(Unit *u) {
1509 assert(u);
1510
1511 if (!UNIT_HAS_CGROUP_CONTEXT(u))
1512 return 0;
1513
1514 /* Slice units are implicitly ordered against their parent slices (as this relationship is encoded in the
1515 name), while all other units are ordered based on configuration (as in their case Slice= configures the
1516 relationship). */
1517 UnitDependencyMask mask = u->type == UNIT_SLICE ? UNIT_DEPENDENCY_IMPLICIT : UNIT_DEPENDENCY_FILE;
1518
1519 if (UNIT_ISSET(u->slice))
1520 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true, mask);
1521
1522 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
1523 return 0;
1524
1525 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, true, mask);
1526 }
1527
1528 static int unit_add_mount_dependencies(Unit *u) {
1529 UnitDependencyInfo di;
1530 const char *path;
1531 int r;
1532
1533 assert(u);
1534
1535 HASHMAP_FOREACH_KEY(di.data, path, u->requires_mounts_for) {
1536 char prefix[strlen(path) + 1];
1537
1538 PATH_FOREACH_PREFIX_MORE(prefix, path) {
1539 _cleanup_free_ char *p = NULL;
1540 Unit *m;
1541
1542 r = unit_name_from_path(prefix, ".mount", &p);
1543 if (r < 0)
1544 return r;
1545
1546 m = manager_get_unit(u->manager, p);
1547 if (!m) {
1548 /* Make sure to load the mount unit if
1549 * it exists. If so the dependencies
1550 * on this unit will be added later
1551 * during the loading of the mount
1552 * unit. */
1553 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
1554 continue;
1555 }
1556 if (m == u)
1557 continue;
1558
1559 if (m->load_state != UNIT_LOADED)
1560 continue;
1561
1562 r = unit_add_dependency(u, UNIT_AFTER, m, true, di.origin_mask);
1563 if (r < 0)
1564 return r;
1565
1566 if (m->fragment_path) {
1567 r = unit_add_dependency(u, UNIT_REQUIRES, m, true, di.origin_mask);
1568 if (r < 0)
1569 return r;
1570 }
1571 }
1572 }
1573
1574 return 0;
1575 }
1576
1577 static int unit_add_oomd_dependencies(Unit *u) {
1578 CGroupContext *c;
1579 bool wants_oomd;
1580 int r;
1581
1582 assert(u);
1583
1584 if (!u->default_dependencies)
1585 return 0;
1586
1587 c = unit_get_cgroup_context(u);
1588 if (!c)
1589 return 0;
1590
1591 wants_oomd = (c->moom_swap == MANAGED_OOM_KILL || c->moom_mem_pressure == MANAGED_OOM_KILL);
1592 if (!wants_oomd)
1593 return 0;
1594
1595 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, "systemd-oomd.service", true, UNIT_DEPENDENCY_FILE);
1596 if (r < 0)
1597 return r;
1598
1599 return 0;
1600 }
1601
1602 static int unit_add_startup_units(Unit *u) {
1603 CGroupContext *c;
1604
1605 c = unit_get_cgroup_context(u);
1606 if (!c)
1607 return 0;
1608
1609 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1610 c->startup_io_weight == CGROUP_WEIGHT_INVALID &&
1611 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
1612 return 0;
1613
1614 return set_ensure_put(&u->manager->startup_units, NULL, u);
1615 }
1616
1617 int unit_load(Unit *u) {
1618 int r;
1619
1620 assert(u);
1621
1622 if (u->in_load_queue) {
1623 LIST_REMOVE(load_queue, u->manager->load_queue, u);
1624 u->in_load_queue = false;
1625 }
1626
1627 if (u->type == _UNIT_TYPE_INVALID)
1628 return -EINVAL;
1629
1630 if (u->load_state != UNIT_STUB)
1631 return 0;
1632
1633 if (u->transient_file) {
1634 /* Finalize transient file: if this is a transient unit file, as soon as we reach unit_load() the setup
1635 * is complete, hence let's synchronize the unit file we just wrote to disk. */
1636
1637 r = fflush_and_check(u->transient_file);
1638 if (r < 0)
1639 goto fail;
1640
1641 u->transient_file = safe_fclose(u->transient_file);
1642 u->fragment_mtime = now(CLOCK_REALTIME);
1643 }
1644
1645 r = UNIT_VTABLE(u)->load(u);
1646 if (r < 0)
1647 goto fail;
1648
1649 assert(u->load_state != UNIT_STUB);
1650
1651 if (u->load_state == UNIT_LOADED) {
1652 unit_add_to_target_deps_queue(u);
1653
1654 r = unit_add_slice_dependencies(u);
1655 if (r < 0)
1656 goto fail;
1657
1658 r = unit_add_mount_dependencies(u);
1659 if (r < 0)
1660 goto fail;
1661
1662 r = unit_add_oomd_dependencies(u);
1663 if (r < 0)
1664 goto fail;
1665
1666 r = unit_add_startup_units(u);
1667 if (r < 0)
1668 goto fail;
1669
1670 if (u->on_failure_job_mode == JOB_ISOLATE && hashmap_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
1671 r = log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOEXEC),
1672 "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
1673 goto fail;
1674 }
1675
1676 if (u->job_running_timeout != USEC_INFINITY && u->job_running_timeout > u->job_timeout)
1677 log_unit_warning(u, "JobRunningTimeoutSec= is greater than JobTimeoutSec=, it has no effect.");
1678
1679 /* We finished loading, let's ensure our parents recalculate the members mask */
1680 unit_invalidate_cgroup_members_masks(u);
1681 }
1682
1683 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
1684
1685 unit_add_to_dbus_queue(unit_follow_merge(u));
1686 unit_add_to_gc_queue(u);
1687 (void) manager_varlink_send_managed_oom_update(u);
1688
1689 return 0;
1690
1691 fail:
1692 /* We convert ENOEXEC errors to the UNIT_BAD_SETTING load state here. Configuration parsing code
1693 * should hence return ENOEXEC to ensure units are placed in this state after loading. */
1694
1695 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND :
1696 r == -ENOEXEC ? UNIT_BAD_SETTING :
1697 UNIT_ERROR;
1698 u->load_error = r;
1699
1700 /* Record the timestamp on the cache, so that if the cache gets updated between now and the next time
1701 * an attempt is made to load this unit, we know we need to check again. */
1702 if (u->load_state == UNIT_NOT_FOUND)
1703 u->fragment_not_found_timestamp_hash = u->manager->unit_cache_timestamp_hash;
1704
1705 unit_add_to_dbus_queue(u);
1706 unit_add_to_gc_queue(u);
1707
1708 return log_unit_debug_errno(u, r, "Failed to load configuration: %m");
1709 }
1710
1711 _printf_(7, 8)
1712 static int log_unit_internal(void *userdata, int level, int error, const char *file, int line, const char *func, const char *format, ...) {
1713 Unit *u = userdata;
1714 va_list ap;
1715 int r;
1716
1717 va_start(ap, format);
1718 if (u)
1719 r = log_object_internalv(level, error, file, line, func,
1720 u->manager->unit_log_field,
1721 u->id,
1722 u->manager->invocation_log_field,
1723 u->invocation_id_string,
1724 format, ap);
1725 else
1726 r = log_internalv(level, error, file, line, func, format, ap);
1727 va_end(ap);
1728
1729 return r;
1730 }
1731
1732 static bool unit_test_condition(Unit *u) {
1733 _cleanup_strv_free_ char **env = NULL;
1734 int r;
1735
1736 assert(u);
1737
1738 dual_timestamp_get(&u->condition_timestamp);
1739
1740 r = manager_get_effective_environment(u->manager, &env);
1741 if (r < 0) {
1742 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1743 u->condition_result = CONDITION_ERROR;
1744 } else
1745 u->condition_result = condition_test_list(
1746 u->conditions,
1747 env,
1748 condition_type_to_string,
1749 log_unit_internal,
1750 u);
1751
1752 unit_add_to_dbus_queue(u);
1753 return u->condition_result;
1754 }
1755
1756 static bool unit_test_assert(Unit *u) {
1757 _cleanup_strv_free_ char **env = NULL;
1758 int r;
1759
1760 assert(u);
1761
1762 dual_timestamp_get(&u->assert_timestamp);
1763
1764 r = manager_get_effective_environment(u->manager, &env);
1765 if (r < 0) {
1766 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1767 u->assert_result = CONDITION_ERROR;
1768 } else
1769 u->assert_result = condition_test_list(
1770 u->asserts,
1771 env,
1772 assert_type_to_string,
1773 log_unit_internal,
1774 u);
1775
1776 unit_add_to_dbus_queue(u);
1777 return u->assert_result;
1778 }
1779
1780 void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *unit_status_msg_format) {
1781 const char *d;
1782
1783 d = unit_status_string(u);
1784 if (log_get_show_color())
1785 d = strjoina(ANSI_HIGHLIGHT, d, ANSI_NORMAL);
1786
1787 DISABLE_WARNING_FORMAT_NONLITERAL;
1788 manager_status_printf(u->manager, status_type, status, unit_status_msg_format, d);
1789 REENABLE_WARNING;
1790 }
1791
1792 int unit_test_start_limit(Unit *u) {
1793 const char *reason;
1794
1795 assert(u);
1796
1797 if (ratelimit_below(&u->start_ratelimit)) {
1798 u->start_limit_hit = false;
1799 return 0;
1800 }
1801
1802 log_unit_warning(u, "Start request repeated too quickly.");
1803 u->start_limit_hit = true;
1804
1805 reason = strjoina("unit ", u->id, " failed");
1806
1807 emergency_action(u->manager, u->start_limit_action,
1808 EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN,
1809 u->reboot_arg, -1, reason);
1810
1811 return -ECANCELED;
1812 }
1813
1814 bool unit_shall_confirm_spawn(Unit *u) {
1815 assert(u);
1816
1817 if (manager_is_confirm_spawn_disabled(u->manager))
1818 return false;
1819
1820 /* For some reasons units remaining in the same process group
1821 * as PID 1 fail to acquire the console even if it's not used
1822 * by any process. So skip the confirmation question for them. */
1823 return !unit_get_exec_context(u)->same_pgrp;
1824 }
1825
1826 static bool unit_verify_deps(Unit *u) {
1827 Unit *other;
1828 void *v;
1829
1830 assert(u);
1831
1832 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1833 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1834 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1835 * conjunction with After= as for them any such check would make things entirely racy. */
1836
1837 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO]) {
1838
1839 if (!hashmap_contains(u->dependencies[UNIT_AFTER], other))
1840 continue;
1841
1842 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
1843 log_unit_notice(u, "Bound to unit %s, but unit isn't active.", other->id);
1844 return false;
1845 }
1846 }
1847
1848 return true;
1849 }
1850
1851 /* Errors that aren't really errors:
1852 * -EALREADY: Unit is already started.
1853 * -ECOMM: Condition failed
1854 * -EAGAIN: An operation is already in progress. Retry later.
1855 *
1856 * Errors that are real errors:
1857 * -EBADR: This unit type does not support starting.
1858 * -ECANCELED: Start limit hit, too many requests for now
1859 * -EPROTO: Assert failed
1860 * -EINVAL: Unit not loaded
1861 * -EOPNOTSUPP: Unit type not supported
1862 * -ENOLINK: The necessary dependencies are not fulfilled.
1863 * -ESTALE: This unit has been started before and can't be started a second time
1864 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
1865 */
1866 int unit_start(Unit *u) {
1867 UnitActiveState state;
1868 Unit *following;
1869
1870 assert(u);
1871
1872 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1873 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1874 * waiting is finished. */
1875 state = unit_active_state(u);
1876 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1877 return -EALREADY;
1878 if (state == UNIT_MAINTENANCE)
1879 return -EAGAIN;
1880
1881 /* Units that aren't loaded cannot be started */
1882 if (u->load_state != UNIT_LOADED)
1883 return -EINVAL;
1884
1885 /* Refuse starting scope units more than once */
1886 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_enter_timestamp))
1887 return -ESTALE;
1888
1889 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1890 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1891 * recheck the condition in that case. */
1892 if (state != UNIT_ACTIVATING &&
1893 !unit_test_condition(u))
1894 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(ECOMM), "Starting requested but condition failed. Not starting unit.");
1895
1896 /* If the asserts failed, fail the entire job */
1897 if (state != UNIT_ACTIVATING &&
1898 !unit_test_assert(u))
1899 return log_unit_notice_errno(u, SYNTHETIC_ERRNO(EPROTO), "Starting requested but asserts failed.");
1900
1901 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1902 * condition checks, so that we rather return condition check errors (which are usually not
1903 * considered a true failure) than "not supported" errors (which are considered a failure).
1904 */
1905 if (!unit_type_supported(u->type))
1906 return -EOPNOTSUPP;
1907
1908 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1909 * should have taken care of this already, but let's check this here again. After all, our
1910 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
1911 if (!unit_verify_deps(u))
1912 return -ENOLINK;
1913
1914 /* Forward to the main object, if we aren't it. */
1915 following = unit_following(u);
1916 if (following) {
1917 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
1918 return unit_start(following);
1919 }
1920
1921 /* If it is stopped, but we cannot start it, then fail */
1922 if (!UNIT_VTABLE(u)->start)
1923 return -EBADR;
1924
1925 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1926 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1927 * waits for a holdoff timer to elapse before it will start again. */
1928
1929 unit_add_to_dbus_queue(u);
1930 unit_cgroup_freezer_action(u, FREEZER_THAW);
1931
1932 return UNIT_VTABLE(u)->start(u);
1933 }
1934
1935 bool unit_can_start(Unit *u) {
1936 assert(u);
1937
1938 if (u->load_state != UNIT_LOADED)
1939 return false;
1940
1941 if (!unit_type_supported(u->type))
1942 return false;
1943
1944 /* Scope units may be started only once */
1945 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_exit_timestamp))
1946 return false;
1947
1948 return !!UNIT_VTABLE(u)->start;
1949 }
1950
1951 bool unit_can_isolate(Unit *u) {
1952 assert(u);
1953
1954 return unit_can_start(u) &&
1955 u->allow_isolate;
1956 }
1957
1958 /* Errors:
1959 * -EBADR: This unit type does not support stopping.
1960 * -EALREADY: Unit is already stopped.
1961 * -EAGAIN: An operation is already in progress. Retry later.
1962 */
1963 int unit_stop(Unit *u) {
1964 UnitActiveState state;
1965 Unit *following;
1966
1967 assert(u);
1968
1969 state = unit_active_state(u);
1970 if (UNIT_IS_INACTIVE_OR_FAILED(state))
1971 return -EALREADY;
1972
1973 following = unit_following(u);
1974 if (following) {
1975 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
1976 return unit_stop(following);
1977 }
1978
1979 if (!UNIT_VTABLE(u)->stop)
1980 return -EBADR;
1981
1982 unit_add_to_dbus_queue(u);
1983 unit_cgroup_freezer_action(u, FREEZER_THAW);
1984
1985 return UNIT_VTABLE(u)->stop(u);
1986 }
1987
1988 bool unit_can_stop(Unit *u) {
1989 assert(u);
1990
1991 /* Note: if we return true here, it does not mean that the unit may be successfully stopped.
1992 * Extrinsic units follow external state and they may stop following external state changes
1993 * (hence we return true here), but an attempt to do this through the manager will fail. */
1994
1995 if (!unit_type_supported(u->type))
1996 return false;
1997
1998 if (u->perpetual)
1999 return false;
2000
2001 return !!UNIT_VTABLE(u)->stop;
2002 }
2003
2004 /* Errors:
2005 * -EBADR: This unit type does not support reloading.
2006 * -ENOEXEC: Unit is not started.
2007 * -EAGAIN: An operation is already in progress. Retry later.
2008 */
2009 int unit_reload(Unit *u) {
2010 UnitActiveState state;
2011 Unit *following;
2012
2013 assert(u);
2014
2015 if (u->load_state != UNIT_LOADED)
2016 return -EINVAL;
2017
2018 if (!unit_can_reload(u))
2019 return -EBADR;
2020
2021 state = unit_active_state(u);
2022 if (state == UNIT_RELOADING)
2023 return -EAGAIN;
2024
2025 if (state != UNIT_ACTIVE)
2026 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "Unit cannot be reloaded because it is inactive.");
2027
2028 following = unit_following(u);
2029 if (following) {
2030 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
2031 return unit_reload(following);
2032 }
2033
2034 unit_add_to_dbus_queue(u);
2035
2036 if (!UNIT_VTABLE(u)->reload) {
2037 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
2038 unit_notify(u, unit_active_state(u), unit_active_state(u), 0);
2039 return 0;
2040 }
2041
2042 unit_cgroup_freezer_action(u, FREEZER_THAW);
2043
2044 return UNIT_VTABLE(u)->reload(u);
2045 }
2046
2047 bool unit_can_reload(Unit *u) {
2048 assert(u);
2049
2050 if (UNIT_VTABLE(u)->can_reload)
2051 return UNIT_VTABLE(u)->can_reload(u);
2052
2053 if (!hashmap_isempty(u->dependencies[UNIT_PROPAGATES_RELOAD_TO]))
2054 return true;
2055
2056 return UNIT_VTABLE(u)->reload;
2057 }
2058
2059 bool unit_is_unneeded(Unit *u) {
2060 static const UnitDependency deps[] = {
2061 UNIT_REQUIRED_BY,
2062 UNIT_REQUISITE_OF,
2063 UNIT_WANTED_BY,
2064 UNIT_BOUND_BY,
2065 };
2066
2067 assert(u);
2068
2069 if (!u->stop_when_unneeded)
2070 return false;
2071
2072 /* Don't clean up while the unit is transitioning or is even inactive. */
2073 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
2074 return false;
2075 if (u->job)
2076 return false;
2077
2078 for (size_t j = 0; j < ELEMENTSOF(deps); j++) {
2079 Unit *other;
2080 void *v;
2081
2082 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
2083 * restart, then don't clean this one up. */
2084
2085 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]]) {
2086 if (other->job)
2087 return false;
2088
2089 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2090 return false;
2091
2092 if (unit_will_restart(other))
2093 return false;
2094 }
2095 }
2096
2097 return true;
2098 }
2099
2100 static void check_unneeded_dependencies(Unit *u) {
2101
2102 static const UnitDependency deps[] = {
2103 UNIT_REQUIRES,
2104 UNIT_REQUISITE,
2105 UNIT_WANTS,
2106 UNIT_BINDS_TO,
2107 };
2108
2109 assert(u);
2110
2111 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2112
2113 for (size_t j = 0; j < ELEMENTSOF(deps); j++) {
2114 Unit *other;
2115 void *v;
2116
2117 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]])
2118 unit_submit_to_stop_when_unneeded_queue(other);
2119 }
2120 }
2121
2122 static void unit_check_binds_to(Unit *u) {
2123 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2124 bool stop = false;
2125 Unit *other;
2126 void *v;
2127 int r;
2128
2129 assert(u);
2130
2131 if (u->job)
2132 return;
2133
2134 if (unit_active_state(u) != UNIT_ACTIVE)
2135 return;
2136
2137 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO]) {
2138 if (other->job)
2139 continue;
2140
2141 if (!other->coldplugged)
2142 /* We might yet create a job for the other unit… */
2143 continue;
2144
2145 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2146 continue;
2147
2148 stop = true;
2149 break;
2150 }
2151
2152 if (!stop)
2153 return;
2154
2155 /* If stopping a unit fails continuously we might enter a stop
2156 * loop here, hence stop acting on the service being
2157 * unnecessary after a while. */
2158 if (!ratelimit_below(&u->auto_stop_ratelimit)) {
2159 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
2160 return;
2161 }
2162
2163 assert(other);
2164 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
2165
2166 /* A unit we need to run is gone. Sniff. Let's stop this. */
2167 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, NULL, &error, NULL);
2168 if (r < 0)
2169 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
2170 }
2171
2172 static void retroactively_start_dependencies(Unit *u) {
2173 Unit *other;
2174 void *v;
2175
2176 assert(u);
2177 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
2178
2179 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REQUIRES])
2180 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2181 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2182 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
2183
2184 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO])
2185 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2186 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2187 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
2188
2189 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_WANTS])
2190 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2191 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2192 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL, NULL);
2193
2194 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTS])
2195 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2196 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2197
2198 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTED_BY])
2199 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2200 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2201 }
2202
2203 static void retroactively_stop_dependencies(Unit *u) {
2204 Unit *other;
2205 void *v;
2206
2207 assert(u);
2208 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
2209
2210 /* Pull down units which are bound to us recursively if enabled */
2211 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BOUND_BY])
2212 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2213 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2214 }
2215
2216 void unit_start_on_failure(Unit *u) {
2217 Unit *other;
2218 void *v;
2219 int r;
2220
2221 assert(u);
2222
2223 if (hashmap_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
2224 return;
2225
2226 log_unit_info(u, "Triggering OnFailure= dependencies.");
2227
2228 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_ON_FAILURE]) {
2229 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2230
2231 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, &error, NULL);
2232 if (r < 0)
2233 log_unit_warning_errno(u, r, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error, r));
2234 }
2235 }
2236
2237 void unit_trigger_notify(Unit *u) {
2238 Unit *other;
2239 void *v;
2240
2241 assert(u);
2242
2243 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_TRIGGERED_BY])
2244 if (UNIT_VTABLE(other)->trigger_notify)
2245 UNIT_VTABLE(other)->trigger_notify(other, u);
2246 }
2247
2248 static int raise_level(int log_level, bool condition_info, bool condition_notice) {
2249 if (condition_notice && log_level > LOG_NOTICE)
2250 return LOG_NOTICE;
2251 if (condition_info && log_level > LOG_INFO)
2252 return LOG_INFO;
2253 return log_level;
2254 }
2255
2256 static int unit_log_resources(Unit *u) {
2257 struct iovec iovec[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX + _CGROUP_IO_ACCOUNTING_METRIC_MAX + 4];
2258 bool any_traffic = false, have_ip_accounting = false, any_io = false, have_io_accounting = false;
2259 _cleanup_free_ char *igress = NULL, *egress = NULL, *rr = NULL, *wr = NULL;
2260 int log_level = LOG_DEBUG; /* May be raised if resources consumed over a threshold */
2261 size_t n_message_parts = 0, n_iovec = 0;
2262 char* message_parts[1 + 2 + 2 + 1], *t;
2263 nsec_t nsec = NSEC_INFINITY;
2264 int r;
2265 const char* const ip_fields[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
2266 [CGROUP_IP_INGRESS_BYTES] = "IP_METRIC_INGRESS_BYTES",
2267 [CGROUP_IP_INGRESS_PACKETS] = "IP_METRIC_INGRESS_PACKETS",
2268 [CGROUP_IP_EGRESS_BYTES] = "IP_METRIC_EGRESS_BYTES",
2269 [CGROUP_IP_EGRESS_PACKETS] = "IP_METRIC_EGRESS_PACKETS",
2270 };
2271 const char* const io_fields[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
2272 [CGROUP_IO_READ_BYTES] = "IO_METRIC_READ_BYTES",
2273 [CGROUP_IO_WRITE_BYTES] = "IO_METRIC_WRITE_BYTES",
2274 [CGROUP_IO_READ_OPERATIONS] = "IO_METRIC_READ_OPERATIONS",
2275 [CGROUP_IO_WRITE_OPERATIONS] = "IO_METRIC_WRITE_OPERATIONS",
2276 };
2277
2278 assert(u);
2279
2280 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2281 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2282 * information and the complete data in structured fields. */
2283
2284 (void) unit_get_cpu_usage(u, &nsec);
2285 if (nsec != NSEC_INFINITY) {
2286 char buf[FORMAT_TIMESPAN_MAX] = "";
2287
2288 /* Format the CPU time for inclusion in the structured log message */
2289 if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) {
2290 r = log_oom();
2291 goto finish;
2292 }
2293 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2294
2295 /* Format the CPU time for inclusion in the human language message string */
2296 format_timespan(buf, sizeof(buf), nsec / NSEC_PER_USEC, USEC_PER_MSEC);
2297 t = strjoin("consumed ", buf, " CPU time");
2298 if (!t) {
2299 r = log_oom();
2300 goto finish;
2301 }
2302
2303 message_parts[n_message_parts++] = t;
2304
2305 log_level = raise_level(log_level,
2306 nsec > NOTICEWORTHY_CPU_NSEC,
2307 nsec > MENTIONWORTHY_CPU_NSEC);
2308 }
2309
2310 for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
2311 char buf[FORMAT_BYTES_MAX] = "";
2312 uint64_t value = UINT64_MAX;
2313
2314 assert(io_fields[k]);
2315
2316 (void) unit_get_io_accounting(u, k, k > 0, &value);
2317 if (value == UINT64_MAX)
2318 continue;
2319
2320 have_io_accounting = true;
2321 if (value > 0)
2322 any_io = true;
2323
2324 /* Format IO accounting data for inclusion in the structured log message */
2325 if (asprintf(&t, "%s=%" PRIu64, io_fields[k], value) < 0) {
2326 r = log_oom();
2327 goto finish;
2328 }
2329 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2330
2331 /* Format the IO accounting data for inclusion in the human language message string, but only
2332 * for the bytes counters (and not for the operations counters) */
2333 if (k == CGROUP_IO_READ_BYTES) {
2334 assert(!rr);
2335 rr = strjoin("read ", format_bytes(buf, sizeof(buf), value), " from disk");
2336 if (!rr) {
2337 r = log_oom();
2338 goto finish;
2339 }
2340 } else if (k == CGROUP_IO_WRITE_BYTES) {
2341 assert(!wr);
2342 wr = strjoin("written ", format_bytes(buf, sizeof(buf), value), " to disk");
2343 if (!wr) {
2344 r = log_oom();
2345 goto finish;
2346 }
2347 }
2348
2349 if (IN_SET(k, CGROUP_IO_READ_BYTES, CGROUP_IO_WRITE_BYTES))
2350 log_level = raise_level(log_level,
2351 value > MENTIONWORTHY_IO_BYTES,
2352 value > NOTICEWORTHY_IO_BYTES);
2353 }
2354
2355 if (have_io_accounting) {
2356 if (any_io) {
2357 if (rr)
2358 message_parts[n_message_parts++] = TAKE_PTR(rr);
2359 if (wr)
2360 message_parts[n_message_parts++] = TAKE_PTR(wr);
2361
2362 } else {
2363 char *k;
2364
2365 k = strdup("no IO");
2366 if (!k) {
2367 r = log_oom();
2368 goto finish;
2369 }
2370
2371 message_parts[n_message_parts++] = k;
2372 }
2373 }
2374
2375 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
2376 char buf[FORMAT_BYTES_MAX] = "";
2377 uint64_t value = UINT64_MAX;
2378
2379 assert(ip_fields[m]);
2380
2381 (void) unit_get_ip_accounting(u, m, &value);
2382 if (value == UINT64_MAX)
2383 continue;
2384
2385 have_ip_accounting = true;
2386 if (value > 0)
2387 any_traffic = true;
2388
2389 /* Format IP accounting data for inclusion in the structured log message */
2390 if (asprintf(&t, "%s=%" PRIu64, ip_fields[m], value) < 0) {
2391 r = log_oom();
2392 goto finish;
2393 }
2394 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2395
2396 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2397 * bytes counters (and not for the packets counters) */
2398 if (m == CGROUP_IP_INGRESS_BYTES) {
2399 assert(!igress);
2400 igress = strjoin("received ", format_bytes(buf, sizeof(buf), value), " IP traffic");
2401 if (!igress) {
2402 r = log_oom();
2403 goto finish;
2404 }
2405 } else if (m == CGROUP_IP_EGRESS_BYTES) {
2406 assert(!egress);
2407 egress = strjoin("sent ", format_bytes(buf, sizeof(buf), value), " IP traffic");
2408 if (!egress) {
2409 r = log_oom();
2410 goto finish;
2411 }
2412 }
2413
2414 if (IN_SET(m, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2415 log_level = raise_level(log_level,
2416 value > MENTIONWORTHY_IP_BYTES,
2417 value > NOTICEWORTHY_IP_BYTES);
2418 }
2419
2420 if (have_ip_accounting) {
2421 if (any_traffic) {
2422 if (igress)
2423 message_parts[n_message_parts++] = TAKE_PTR(igress);
2424 if (egress)
2425 message_parts[n_message_parts++] = TAKE_PTR(egress);
2426
2427 } else {
2428 char *k;
2429
2430 k = strdup("no IP traffic");
2431 if (!k) {
2432 r = log_oom();
2433 goto finish;
2434 }
2435
2436 message_parts[n_message_parts++] = k;
2437 }
2438 }
2439
2440 /* Is there any accounting data available at all? */
2441 if (n_iovec == 0) {
2442 r = 0;
2443 goto finish;
2444 }
2445
2446 if (n_message_parts == 0)
2447 t = strjoina("MESSAGE=", u->id, ": Completed.");
2448 else {
2449 _cleanup_free_ char *joined;
2450
2451 message_parts[n_message_parts] = NULL;
2452
2453 joined = strv_join(message_parts, ", ");
2454 if (!joined) {
2455 r = log_oom();
2456 goto finish;
2457 }
2458
2459 joined[0] = ascii_toupper(joined[0]);
2460 t = strjoina("MESSAGE=", u->id, ": ", joined, ".");
2461 }
2462
2463 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2464 * and hence don't increase n_iovec for them */
2465 iovec[n_iovec] = IOVEC_MAKE_STRING(t);
2466 iovec[n_iovec + 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR);
2467
2468 t = strjoina(u->manager->unit_log_field, u->id);
2469 iovec[n_iovec + 2] = IOVEC_MAKE_STRING(t);
2470
2471 t = strjoina(u->manager->invocation_log_field, u->invocation_id_string);
2472 iovec[n_iovec + 3] = IOVEC_MAKE_STRING(t);
2473
2474 log_struct_iovec(log_level, iovec, n_iovec + 4);
2475 r = 0;
2476
2477 finish:
2478 for (size_t i = 0; i < n_message_parts; i++)
2479 free(message_parts[i]);
2480
2481 for (size_t i = 0; i < n_iovec; i++)
2482 free(iovec[i].iov_base);
2483
2484 return r;
2485
2486 }
2487
2488 static void unit_update_on_console(Unit *u) {
2489 bool b;
2490
2491 assert(u);
2492
2493 b = unit_needs_console(u);
2494 if (u->on_console == b)
2495 return;
2496
2497 u->on_console = b;
2498 if (b)
2499 manager_ref_console(u->manager);
2500 else
2501 manager_unref_console(u->manager);
2502 }
2503
2504 static void unit_emit_audit_start(Unit *u) {
2505 assert(u);
2506
2507 if (u->type != UNIT_SERVICE)
2508 return;
2509
2510 /* Write audit record if we have just finished starting up */
2511 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, true);
2512 u->in_audit = true;
2513 }
2514
2515 static void unit_emit_audit_stop(Unit *u, UnitActiveState state) {
2516 assert(u);
2517
2518 if (u->type != UNIT_SERVICE)
2519 return;
2520
2521 if (u->in_audit) {
2522 /* Write audit record if we have just finished shutting down */
2523 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, state == UNIT_INACTIVE);
2524 u->in_audit = false;
2525 } else {
2526 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2527 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, state == UNIT_INACTIVE);
2528
2529 if (state == UNIT_INACTIVE)
2530 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, true);
2531 }
2532 }
2533
2534 static bool unit_process_job(Job *j, UnitActiveState ns, UnitNotifyFlags flags) {
2535 bool unexpected = false;
2536 JobResult result;
2537
2538 assert(j);
2539
2540 if (j->state == JOB_WAITING)
2541
2542 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2543 * due to EAGAIN. */
2544 job_add_to_run_queue(j);
2545
2546 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2547 * hence needs to invalidate jobs. */
2548
2549 switch (j->type) {
2550
2551 case JOB_START:
2552 case JOB_VERIFY_ACTIVE:
2553
2554 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
2555 job_finish_and_invalidate(j, JOB_DONE, true, false);
2556 else if (j->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
2557 unexpected = true;
2558
2559 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2560 if (ns == UNIT_FAILED)
2561 result = JOB_FAILED;
2562 else
2563 result = JOB_DONE;
2564
2565 job_finish_and_invalidate(j, result, true, false);
2566 }
2567 }
2568
2569 break;
2570
2571 case JOB_RELOAD:
2572 case JOB_RELOAD_OR_START:
2573 case JOB_TRY_RELOAD:
2574
2575 if (j->state == JOB_RUNNING) {
2576 if (ns == UNIT_ACTIVE)
2577 job_finish_and_invalidate(j, (flags & UNIT_NOTIFY_RELOAD_FAILURE) ? JOB_FAILED : JOB_DONE, true, false);
2578 else if (!IN_SET(ns, UNIT_ACTIVATING, UNIT_RELOADING)) {
2579 unexpected = true;
2580
2581 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2582 job_finish_and_invalidate(j, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
2583 }
2584 }
2585
2586 break;
2587
2588 case JOB_STOP:
2589 case JOB_RESTART:
2590 case JOB_TRY_RESTART:
2591
2592 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2593 job_finish_and_invalidate(j, JOB_DONE, true, false);
2594 else if (j->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
2595 unexpected = true;
2596 job_finish_and_invalidate(j, JOB_FAILED, true, false);
2597 }
2598
2599 break;
2600
2601 default:
2602 assert_not_reached("Job type unknown");
2603 }
2604
2605 return unexpected;
2606 }
2607
2608 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, UnitNotifyFlags flags) {
2609 const char *reason;
2610 Manager *m;
2611
2612 assert(u);
2613 assert(os < _UNIT_ACTIVE_STATE_MAX);
2614 assert(ns < _UNIT_ACTIVE_STATE_MAX);
2615
2616 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2617 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2618 * remounted this function will be called too! */
2619
2620 m = u->manager;
2621
2622 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2623 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2624 unit_add_to_dbus_queue(u);
2625
2626 /* Update systemd-oomd on the property/state change */
2627 if (os != ns) {
2628 /* Always send an update if the unit is going into an inactive state so systemd-oomd knows to stop
2629 * monitoring.
2630 * Also send an update whenever the unit goes active; this is to handle a case where an override file
2631 * sets one of the ManagedOOM*= properties to "kill", then later removes it. systemd-oomd needs to
2632 * know to stop monitoring when the unit changes from "kill" -> "auto" on daemon-reload, but we don't
2633 * have the information on the property. Thus, indiscriminately send an update. */
2634 if (UNIT_IS_INACTIVE_OR_FAILED(ns) || UNIT_IS_ACTIVE_OR_RELOADING(ns))
2635 (void) manager_varlink_send_managed_oom_update(u);
2636 }
2637
2638 /* Update timestamps for state changes */
2639 if (!MANAGER_IS_RELOADING(m)) {
2640 dual_timestamp_get(&u->state_change_timestamp);
2641
2642 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
2643 u->inactive_exit_timestamp = u->state_change_timestamp;
2644 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
2645 u->inactive_enter_timestamp = u->state_change_timestamp;
2646
2647 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
2648 u->active_enter_timestamp = u->state_change_timestamp;
2649 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
2650 u->active_exit_timestamp = u->state_change_timestamp;
2651 }
2652
2653 /* Keep track of failed units */
2654 (void) manager_update_failed_units(m, u, ns == UNIT_FAILED);
2655
2656 /* Make sure the cgroup and state files are always removed when we become inactive */
2657 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2658 unit_prune_cgroup(u);
2659 unit_unlink_state_files(u);
2660 }
2661
2662 unit_update_on_console(u);
2663
2664 if (!MANAGER_IS_RELOADING(m)) {
2665 bool unexpected;
2666
2667 /* Let's propagate state changes to the job */
2668 if (u->job)
2669 unexpected = unit_process_job(u->job, ns, flags);
2670 else
2671 unexpected = true;
2672
2673 /* If this state change happened without being requested by a job, then let's retroactively start or
2674 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2675 * additional jobs just because something is already activated. */
2676
2677 if (unexpected) {
2678 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
2679 retroactively_start_dependencies(u);
2680 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2681 retroactively_stop_dependencies(u);
2682 }
2683
2684 /* stop unneeded units regardless if going down was expected or not */
2685 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2686 check_unneeded_dependencies(u);
2687
2688 if (ns != os && ns == UNIT_FAILED) {
2689 log_unit_debug(u, "Unit entered failed state.");
2690
2691 if (!(flags & UNIT_NOTIFY_WILL_AUTO_RESTART))
2692 unit_start_on_failure(u);
2693 }
2694
2695 if (UNIT_IS_ACTIVE_OR_RELOADING(ns) && !UNIT_IS_ACTIVE_OR_RELOADING(os)) {
2696 /* This unit just finished starting up */
2697
2698 unit_emit_audit_start(u);
2699 manager_send_unit_plymouth(m, u);
2700 }
2701
2702 if (UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os)) {
2703 /* This unit just stopped/failed. */
2704
2705 unit_emit_audit_stop(u, ns);
2706 unit_log_resources(u);
2707 }
2708 }
2709
2710 manager_recheck_journal(m);
2711 manager_recheck_dbus(m);
2712
2713 unit_trigger_notify(u);
2714
2715 if (!MANAGER_IS_RELOADING(m)) {
2716 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2717 unit_submit_to_stop_when_unneeded_queue(u);
2718
2719 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2720 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
2721 * without ever entering started.) */
2722 unit_check_binds_to(u);
2723
2724 if (os != UNIT_FAILED && ns == UNIT_FAILED) {
2725 reason = strjoina("unit ", u->id, " failed");
2726 emergency_action(m, u->failure_action, 0, u->reboot_arg, unit_failure_action_exit_status(u), reason);
2727 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && ns == UNIT_INACTIVE) {
2728 reason = strjoina("unit ", u->id, " succeeded");
2729 emergency_action(m, u->success_action, 0, u->reboot_arg, unit_success_action_exit_status(u), reason);
2730 }
2731 }
2732
2733 unit_add_to_gc_queue(u);
2734 }
2735
2736 int unit_watch_pid(Unit *u, pid_t pid, bool exclusive) {
2737 int r;
2738
2739 assert(u);
2740 assert(pid_is_valid(pid));
2741
2742 /* Watch a specific PID */
2743
2744 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2745 * opportunity to remove any stalled references to this PID as they can be created
2746 * easily (when watching a process which is not our direct child). */
2747 if (exclusive)
2748 manager_unwatch_pid(u->manager, pid);
2749
2750 r = set_ensure_allocated(&u->pids, NULL);
2751 if (r < 0)
2752 return r;
2753
2754 r = hashmap_ensure_allocated(&u->manager->watch_pids, NULL);
2755 if (r < 0)
2756 return r;
2757
2758 /* First try, let's add the unit keyed by "pid". */
2759 r = hashmap_put(u->manager->watch_pids, PID_TO_PTR(pid), u);
2760 if (r == -EEXIST) {
2761 Unit **array;
2762 bool found = false;
2763 size_t n = 0;
2764
2765 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2766 * to an array of Units rather than just a Unit), lists us already. */
2767
2768 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2769 if (array)
2770 for (; array[n]; n++)
2771 if (array[n] == u)
2772 found = true;
2773
2774 if (found) /* Found it already? if so, do nothing */
2775 r = 0;
2776 else {
2777 Unit **new_array;
2778
2779 /* Allocate a new array */
2780 new_array = new(Unit*, n + 2);
2781 if (!new_array)
2782 return -ENOMEM;
2783
2784 memcpy_safe(new_array, array, sizeof(Unit*) * n);
2785 new_array[n] = u;
2786 new_array[n+1] = NULL;
2787
2788 /* Add or replace the old array */
2789 r = hashmap_replace(u->manager->watch_pids, PID_TO_PTR(-pid), new_array);
2790 if (r < 0) {
2791 free(new_array);
2792 return r;
2793 }
2794
2795 free(array);
2796 }
2797 } else if (r < 0)
2798 return r;
2799
2800 r = set_put(u->pids, PID_TO_PTR(pid));
2801 if (r < 0)
2802 return r;
2803
2804 return 0;
2805 }
2806
2807 void unit_unwatch_pid(Unit *u, pid_t pid) {
2808 Unit **array;
2809
2810 assert(u);
2811 assert(pid_is_valid(pid));
2812
2813 /* First let's drop the unit in case it's keyed as "pid". */
2814 (void) hashmap_remove_value(u->manager->watch_pids, PID_TO_PTR(pid), u);
2815
2816 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2817 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2818 if (array) {
2819 /* Let's iterate through the array, dropping our own entry */
2820
2821 size_t m = 0;
2822 for (size_t n = 0; array[n]; n++)
2823 if (array[n] != u)
2824 array[m++] = array[n];
2825 array[m] = NULL;
2826
2827 if (m == 0) {
2828 /* The array is now empty, remove the entire entry */
2829 assert_se(hashmap_remove(u->manager->watch_pids, PID_TO_PTR(-pid)) == array);
2830 free(array);
2831 }
2832 }
2833
2834 (void) set_remove(u->pids, PID_TO_PTR(pid));
2835 }
2836
2837 void unit_unwatch_all_pids(Unit *u) {
2838 assert(u);
2839
2840 while (!set_isempty(u->pids))
2841 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
2842
2843 u->pids = set_free(u->pids);
2844 }
2845
2846 static void unit_tidy_watch_pids(Unit *u) {
2847 pid_t except1, except2;
2848 void *e;
2849
2850 assert(u);
2851
2852 /* Cleans dead PIDs from our list */
2853
2854 except1 = unit_main_pid(u);
2855 except2 = unit_control_pid(u);
2856
2857 SET_FOREACH(e, u->pids) {
2858 pid_t pid = PTR_TO_PID(e);
2859
2860 if (pid == except1 || pid == except2)
2861 continue;
2862
2863 if (!pid_is_unwaited(pid))
2864 unit_unwatch_pid(u, pid);
2865 }
2866 }
2867
2868 static int on_rewatch_pids_event(sd_event_source *s, void *userdata) {
2869 Unit *u = userdata;
2870
2871 assert(s);
2872 assert(u);
2873
2874 unit_tidy_watch_pids(u);
2875 unit_watch_all_pids(u);
2876
2877 /* If the PID set is empty now, then let's finish this off. */
2878 unit_synthesize_cgroup_empty_event(u);
2879
2880 return 0;
2881 }
2882
2883 int unit_enqueue_rewatch_pids(Unit *u) {
2884 int r;
2885
2886 assert(u);
2887
2888 if (!u->cgroup_path)
2889 return -ENOENT;
2890
2891 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2892 if (r < 0)
2893 return r;
2894 if (r > 0) /* On unified we can use proper notifications */
2895 return 0;
2896
2897 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2898 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2899 * involves issuing kill(pid, 0) on all processes we watch. */
2900
2901 if (!u->rewatch_pids_event_source) {
2902 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2903
2904 r = sd_event_add_defer(u->manager->event, &s, on_rewatch_pids_event, u);
2905 if (r < 0)
2906 return log_error_errno(r, "Failed to allocate event source for tidying watched PIDs: %m");
2907
2908 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_IDLE);
2909 if (r < 0)
2910 return log_error_errno(r, "Failed to adjust priority of event source for tidying watched PIDs: %m");
2911
2912 (void) sd_event_source_set_description(s, "tidy-watch-pids");
2913
2914 u->rewatch_pids_event_source = TAKE_PTR(s);
2915 }
2916
2917 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_ONESHOT);
2918 if (r < 0)
2919 return log_error_errno(r, "Failed to enable event source for tidying watched PIDs: %m");
2920
2921 return 0;
2922 }
2923
2924 void unit_dequeue_rewatch_pids(Unit *u) {
2925 int r;
2926 assert(u);
2927
2928 if (!u->rewatch_pids_event_source)
2929 return;
2930
2931 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_OFF);
2932 if (r < 0)
2933 log_warning_errno(r, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2934
2935 u->rewatch_pids_event_source = sd_event_source_unref(u->rewatch_pids_event_source);
2936 }
2937
2938 bool unit_job_is_applicable(Unit *u, JobType j) {
2939 assert(u);
2940 assert(j >= 0 && j < _JOB_TYPE_MAX);
2941
2942 switch (j) {
2943
2944 case JOB_VERIFY_ACTIVE:
2945 case JOB_START:
2946 case JOB_NOP:
2947 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2948 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
2949 * jobs for it. */
2950 return true;
2951
2952 case JOB_STOP:
2953 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2954 * external events), hence it makes no sense to permit enqueuing such a request either. */
2955 return !u->perpetual;
2956
2957 case JOB_RESTART:
2958 case JOB_TRY_RESTART:
2959 return unit_can_stop(u) && unit_can_start(u);
2960
2961 case JOB_RELOAD:
2962 case JOB_TRY_RELOAD:
2963 return unit_can_reload(u);
2964
2965 case JOB_RELOAD_OR_START:
2966 return unit_can_reload(u) && unit_can_start(u);
2967
2968 default:
2969 assert_not_reached("Invalid job type");
2970 }
2971 }
2972
2973 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2974 assert(u);
2975
2976 /* Only warn about some unit types */
2977 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2978 return;
2979
2980 if (streq_ptr(u->id, other))
2981 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2982 else
2983 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
2984 }
2985
2986 static int unit_add_dependency_hashmap(
2987 Hashmap **h,
2988 Unit *other,
2989 UnitDependencyMask origin_mask,
2990 UnitDependencyMask destination_mask) {
2991
2992 UnitDependencyInfo info;
2993 int r;
2994
2995 assert(h);
2996 assert(other);
2997 assert(origin_mask < _UNIT_DEPENDENCY_MASK_FULL);
2998 assert(destination_mask < _UNIT_DEPENDENCY_MASK_FULL);
2999 assert(origin_mask > 0 || destination_mask > 0);
3000
3001 r = hashmap_ensure_allocated(h, NULL);
3002 if (r < 0)
3003 return r;
3004
3005 assert_cc(sizeof(void*) == sizeof(info));
3006
3007 info.data = hashmap_get(*h, other);
3008 if (info.data) {
3009 /* Entry already exists. Add in our mask. */
3010
3011 if (FLAGS_SET(origin_mask, info.origin_mask) &&
3012 FLAGS_SET(destination_mask, info.destination_mask))
3013 return 0; /* NOP */
3014
3015 info.origin_mask |= origin_mask;
3016 info.destination_mask |= destination_mask;
3017
3018 r = hashmap_update(*h, other, info.data);
3019 } else {
3020 info = (UnitDependencyInfo) {
3021 .origin_mask = origin_mask,
3022 .destination_mask = destination_mask,
3023 };
3024
3025 r = hashmap_put(*h, other, info.data);
3026 }
3027 if (r < 0)
3028 return r;
3029
3030 return 1;
3031 }
3032
3033 int unit_add_dependency(
3034 Unit *u,
3035 UnitDependency d,
3036 Unit *other,
3037 bool add_reference,
3038 UnitDependencyMask mask) {
3039
3040 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
3041 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
3042 [UNIT_WANTS] = UNIT_WANTED_BY,
3043 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
3044 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
3045 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
3046 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
3047 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
3048 [UNIT_WANTED_BY] = UNIT_WANTS,
3049 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
3050 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
3051 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
3052 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
3053 [UNIT_BEFORE] = UNIT_AFTER,
3054 [UNIT_AFTER] = UNIT_BEFORE,
3055 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
3056 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
3057 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
3058 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
3059 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
3060 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
3061 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
3062 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
3063 };
3064 Unit *original_u = u, *original_other = other;
3065 int r;
3066 /* Helper to know whether sending a notification is necessary or not:
3067 * if the dependency is already there, no need to notify! */
3068 bool noop = true;
3069
3070 assert(u);
3071 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
3072 assert(other);
3073
3074 u = unit_follow_merge(u);
3075 other = unit_follow_merge(other);
3076
3077 /* We won't allow dependencies on ourselves. We will not
3078 * consider them an error however. */
3079 if (u == other) {
3080 maybe_warn_about_dependency(original_u, original_other->id, d);
3081 return 0;
3082 }
3083
3084 /* Note that ordering a device unit after a unit is permitted since it
3085 * allows to start its job running timeout at a specific time. */
3086 if (d == UNIT_BEFORE && other->type == UNIT_DEVICE) {
3087 log_unit_warning(u, "Dependency Before=%s ignored (.device units cannot be delayed)", other->id);
3088 return 0;
3089 }
3090
3091 if (d == UNIT_ON_FAILURE && !UNIT_VTABLE(u)->can_fail) {
3092 log_unit_warning(u, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other->id, unit_type_to_string(u->type));
3093 return 0;
3094 }
3095
3096 if (d == UNIT_TRIGGERS && !UNIT_VTABLE(u)->can_trigger)
3097 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3098 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(u->type));
3099 if (d == UNIT_TRIGGERED_BY && !UNIT_VTABLE(other)->can_trigger)
3100 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3101 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(other->type));
3102
3103 r = unit_add_dependency_hashmap(u->dependencies + d, other, mask, 0);
3104 if (r < 0)
3105 return r;
3106 else if (r > 0)
3107 noop = false;
3108
3109 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
3110 r = unit_add_dependency_hashmap(other->dependencies + inverse_table[d], u, 0, mask);
3111 if (r < 0)
3112 return r;
3113 else if (r > 0)
3114 noop = false;
3115 }
3116
3117 if (add_reference) {
3118 r = unit_add_dependency_hashmap(u->dependencies + UNIT_REFERENCES, other, mask, 0);
3119 if (r < 0)
3120 return r;
3121 else if (r > 0)
3122 noop = false;
3123
3124 r = unit_add_dependency_hashmap(other->dependencies + UNIT_REFERENCED_BY, u, 0, mask);
3125 if (r < 0)
3126 return r;
3127 else if (r > 0)
3128 noop = false;
3129 }
3130
3131 if (!noop)
3132 unit_add_to_dbus_queue(u);
3133 return 0;
3134 }
3135
3136 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask) {
3137 int r;
3138
3139 assert(u);
3140
3141 r = unit_add_dependency(u, d, other, add_reference, mask);
3142 if (r < 0)
3143 return r;
3144
3145 return unit_add_dependency(u, e, other, add_reference, mask);
3146 }
3147
3148 static int resolve_template(Unit *u, const char *name, char **buf, const char **ret) {
3149 int r;
3150
3151 assert(u);
3152 assert(name);
3153 assert(buf);
3154 assert(ret);
3155
3156 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
3157 *buf = NULL;
3158 *ret = name;
3159 return 0;
3160 }
3161
3162 if (u->instance)
3163 r = unit_name_replace_instance(name, u->instance, buf);
3164 else {
3165 _cleanup_free_ char *i = NULL;
3166
3167 r = unit_name_to_prefix(u->id, &i);
3168 if (r < 0)
3169 return r;
3170
3171 r = unit_name_replace_instance(name, i, buf);
3172 }
3173 if (r < 0)
3174 return r;
3175
3176 *ret = *buf;
3177 return 0;
3178 }
3179
3180 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask) {
3181 _cleanup_free_ char *buf = NULL;
3182 Unit *other;
3183 int r;
3184
3185 assert(u);
3186 assert(name);
3187
3188 r = resolve_template(u, name, &buf, &name);
3189 if (r < 0)
3190 return r;
3191
3192 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3193 if (r < 0)
3194 return r;
3195
3196 return unit_add_dependency(u, d, other, add_reference, mask);
3197 }
3198
3199 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask) {
3200 _cleanup_free_ char *buf = NULL;
3201 Unit *other;
3202 int r;
3203
3204 assert(u);
3205 assert(name);
3206
3207 r = resolve_template(u, name, &buf, &name);
3208 if (r < 0)
3209 return r;
3210
3211 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3212 if (r < 0)
3213 return r;
3214
3215 return unit_add_two_dependencies(u, d, e, other, add_reference, mask);
3216 }
3217
3218 int set_unit_path(const char *p) {
3219 /* This is mostly for debug purposes */
3220 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
3221 return -errno;
3222
3223 return 0;
3224 }
3225
3226 char *unit_dbus_path(Unit *u) {
3227 assert(u);
3228
3229 if (!u->id)
3230 return NULL;
3231
3232 return unit_dbus_path_from_name(u->id);
3233 }
3234
3235 char *unit_dbus_path_invocation_id(Unit *u) {
3236 assert(u);
3237
3238 if (sd_id128_is_null(u->invocation_id))
3239 return NULL;
3240
3241 return unit_dbus_path_from_name(u->invocation_id_string);
3242 }
3243
3244 static int unit_set_invocation_id(Unit *u, sd_id128_t id) {
3245 int r;
3246
3247 assert(u);
3248
3249 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
3250
3251 if (sd_id128_equal(u->invocation_id, id))
3252 return 0;
3253
3254 if (!sd_id128_is_null(u->invocation_id))
3255 (void) hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
3256
3257 if (sd_id128_is_null(id)) {
3258 r = 0;
3259 goto reset;
3260 }
3261
3262 r = hashmap_ensure_allocated(&u->manager->units_by_invocation_id, &id128_hash_ops);
3263 if (r < 0)
3264 goto reset;
3265
3266 u->invocation_id = id;
3267 sd_id128_to_string(id, u->invocation_id_string);
3268
3269 r = hashmap_put(u->manager->units_by_invocation_id, &u->invocation_id, u);
3270 if (r < 0)
3271 goto reset;
3272
3273 return 0;
3274
3275 reset:
3276 u->invocation_id = SD_ID128_NULL;
3277 u->invocation_id_string[0] = 0;
3278 return r;
3279 }
3280
3281 int unit_set_slice(Unit *u, Unit *slice) {
3282 assert(u);
3283 assert(slice);
3284
3285 /* Sets the unit slice if it has not been set before. Is extra
3286 * careful, to only allow this for units that actually have a
3287 * cgroup context. Also, we don't allow to set this for slices
3288 * (since the parent slice is derived from the name). Make
3289 * sure the unit we set is actually a slice. */
3290
3291 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3292 return -EOPNOTSUPP;
3293
3294 if (u->type == UNIT_SLICE)
3295 return -EINVAL;
3296
3297 if (unit_active_state(u) != UNIT_INACTIVE)
3298 return -EBUSY;
3299
3300 if (slice->type != UNIT_SLICE)
3301 return -EINVAL;
3302
3303 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
3304 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
3305 return -EPERM;
3306
3307 if (UNIT_DEREF(u->slice) == slice)
3308 return 0;
3309
3310 /* Disallow slice changes if @u is already bound to cgroups */
3311 if (UNIT_ISSET(u->slice) && u->cgroup_realized)
3312 return -EBUSY;
3313
3314 unit_ref_set(&u->slice, u, slice);
3315 return 1;
3316 }
3317
3318 int unit_set_default_slice(Unit *u) {
3319 const char *slice_name;
3320 Unit *slice;
3321 int r;
3322
3323 assert(u);
3324
3325 if (UNIT_ISSET(u->slice))
3326 return 0;
3327
3328 if (u->instance) {
3329 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
3330
3331 /* Implicitly place all instantiated units in their
3332 * own per-template slice */
3333
3334 r = unit_name_to_prefix(u->id, &prefix);
3335 if (r < 0)
3336 return r;
3337
3338 /* The prefix is already escaped, but it might include
3339 * "-" which has a special meaning for slice units,
3340 * hence escape it here extra. */
3341 escaped = unit_name_escape(prefix);
3342 if (!escaped)
3343 return -ENOMEM;
3344
3345 if (MANAGER_IS_SYSTEM(u->manager))
3346 slice_name = strjoina("system-", escaped, ".slice");
3347 else
3348 slice_name = strjoina("app-", escaped, ".slice");
3349
3350 } else if (unit_is_extrinsic(u))
3351 /* Keep all extrinsic units (e.g. perpetual units and swap and mount units in user mode) in
3352 * the root slice. They don't really belong in one of the subslices. */
3353 slice_name = SPECIAL_ROOT_SLICE;
3354
3355 else if (MANAGER_IS_SYSTEM(u->manager))
3356 slice_name = SPECIAL_SYSTEM_SLICE;
3357 else
3358 slice_name = SPECIAL_APP_SLICE;
3359
3360 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
3361 if (r < 0)
3362 return r;
3363
3364 return unit_set_slice(u, slice);
3365 }
3366
3367 const char *unit_slice_name(Unit *u) {
3368 assert(u);
3369
3370 if (!UNIT_ISSET(u->slice))
3371 return NULL;
3372
3373 return UNIT_DEREF(u->slice)->id;
3374 }
3375
3376 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
3377 _cleanup_free_ char *t = NULL;
3378 int r;
3379
3380 assert(u);
3381 assert(type);
3382 assert(_found);
3383
3384 r = unit_name_change_suffix(u->id, type, &t);
3385 if (r < 0)
3386 return r;
3387 if (unit_has_name(u, t))
3388 return -EINVAL;
3389
3390 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
3391 assert(r < 0 || *_found != u);
3392 return r;
3393 }
3394
3395 static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3396 const char *new_owner;
3397 Unit *u = userdata;
3398 int r;
3399
3400 assert(message);
3401 assert(u);
3402
3403 r = sd_bus_message_read(message, "sss", NULL, NULL, &new_owner);
3404 if (r < 0) {
3405 bus_log_parse_error(r);
3406 return 0;
3407 }
3408
3409 if (UNIT_VTABLE(u)->bus_name_owner_change)
3410 UNIT_VTABLE(u)->bus_name_owner_change(u, empty_to_null(new_owner));
3411
3412 return 0;
3413 }
3414
3415 static int get_name_owner_handler(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3416 const sd_bus_error *e;
3417 const char *new_owner;
3418 Unit *u = userdata;
3419 int r;
3420
3421 assert(message);
3422 assert(u);
3423
3424 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3425
3426 e = sd_bus_message_get_error(message);
3427 if (e) {
3428 if (!sd_bus_error_has_name(e, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3429 log_unit_error(u, "Unexpected error response from GetNameOwner(): %s", e->message);
3430
3431 new_owner = NULL;
3432 } else {
3433 r = sd_bus_message_read(message, "s", &new_owner);
3434 if (r < 0)
3435 return bus_log_parse_error(r);
3436
3437 assert(!isempty(new_owner));
3438 }
3439
3440 if (UNIT_VTABLE(u)->bus_name_owner_change)
3441 UNIT_VTABLE(u)->bus_name_owner_change(u, new_owner);
3442
3443 return 0;
3444 }
3445
3446 int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
3447 const char *match;
3448 int r;
3449
3450 assert(u);
3451 assert(bus);
3452 assert(name);
3453
3454 if (u->match_bus_slot || u->get_name_owner_slot)
3455 return -EBUSY;
3456
3457 match = strjoina("type='signal',"
3458 "sender='org.freedesktop.DBus',"
3459 "path='/org/freedesktop/DBus',"
3460 "interface='org.freedesktop.DBus',"
3461 "member='NameOwnerChanged',"
3462 "arg0='", name, "'");
3463
3464 r = sd_bus_add_match_async(bus, &u->match_bus_slot, match, signal_name_owner_changed, NULL, u);
3465 if (r < 0)
3466 return r;
3467
3468 r = sd_bus_call_method_async(
3469 bus,
3470 &u->get_name_owner_slot,
3471 "org.freedesktop.DBus",
3472 "/org/freedesktop/DBus",
3473 "org.freedesktop.DBus",
3474 "GetNameOwner",
3475 get_name_owner_handler,
3476 u,
3477 "s", name);
3478 if (r < 0) {
3479 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3480 return r;
3481 }
3482
3483 log_unit_debug(u, "Watching D-Bus name '%s'.", name);
3484 return 0;
3485 }
3486
3487 int unit_watch_bus_name(Unit *u, const char *name) {
3488 int r;
3489
3490 assert(u);
3491 assert(name);
3492
3493 /* Watch a specific name on the bus. We only support one unit
3494 * watching each name for now. */
3495
3496 if (u->manager->api_bus) {
3497 /* If the bus is already available, install the match directly.
3498 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
3499 r = unit_install_bus_match(u, u->manager->api_bus, name);
3500 if (r < 0)
3501 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
3502 }
3503
3504 r = hashmap_put(u->manager->watch_bus, name, u);
3505 if (r < 0) {
3506 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3507 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3508 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
3509 }
3510
3511 return 0;
3512 }
3513
3514 void unit_unwatch_bus_name(Unit *u, const char *name) {
3515 assert(u);
3516 assert(name);
3517
3518 (void) hashmap_remove_value(u->manager->watch_bus, name, u);
3519 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3520 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3521 }
3522
3523 bool unit_can_serialize(Unit *u) {
3524 assert(u);
3525
3526 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
3527 }
3528
3529 static int serialize_cgroup_mask(FILE *f, const char *key, CGroupMask mask) {
3530 _cleanup_free_ char *s = NULL;
3531 int r;
3532
3533 assert(f);
3534 assert(key);
3535
3536 if (mask == 0)
3537 return 0;
3538
3539 r = cg_mask_to_string(mask, &s);
3540 if (r < 0)
3541 return log_error_errno(r, "Failed to format cgroup mask: %m");
3542
3543 return serialize_item(f, key, s);
3544 }
3545
3546 static const char *const ip_accounting_metric_field[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
3547 [CGROUP_IP_INGRESS_BYTES] = "ip-accounting-ingress-bytes",
3548 [CGROUP_IP_INGRESS_PACKETS] = "ip-accounting-ingress-packets",
3549 [CGROUP_IP_EGRESS_BYTES] = "ip-accounting-egress-bytes",
3550 [CGROUP_IP_EGRESS_PACKETS] = "ip-accounting-egress-packets",
3551 };
3552
3553 static const char *const io_accounting_metric_field_base[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3554 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-base",
3555 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-base",
3556 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-base",
3557 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-base",
3558 };
3559
3560 static const char *const io_accounting_metric_field_last[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3561 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-last",
3562 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-last",
3563 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-last",
3564 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-last",
3565 };
3566
3567 int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
3568 int r;
3569
3570 assert(u);
3571 assert(f);
3572 assert(fds);
3573
3574 if (unit_can_serialize(u)) {
3575 r = UNIT_VTABLE(u)->serialize(u, f, fds);
3576 if (r < 0)
3577 return r;
3578 }
3579
3580 (void) serialize_dual_timestamp(f, "state-change-timestamp", &u->state_change_timestamp);
3581
3582 (void) serialize_dual_timestamp(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
3583 (void) serialize_dual_timestamp(f, "active-enter-timestamp", &u->active_enter_timestamp);
3584 (void) serialize_dual_timestamp(f, "active-exit-timestamp", &u->active_exit_timestamp);
3585 (void) serialize_dual_timestamp(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
3586
3587 (void) serialize_dual_timestamp(f, "condition-timestamp", &u->condition_timestamp);
3588 (void) serialize_dual_timestamp(f, "assert-timestamp", &u->assert_timestamp);
3589
3590 if (dual_timestamp_is_set(&u->condition_timestamp))
3591 (void) serialize_bool(f, "condition-result", u->condition_result);
3592
3593 if (dual_timestamp_is_set(&u->assert_timestamp))
3594 (void) serialize_bool(f, "assert-result", u->assert_result);
3595
3596 (void) serialize_bool(f, "transient", u->transient);
3597 (void) serialize_bool(f, "in-audit", u->in_audit);
3598
3599 (void) serialize_bool(f, "exported-invocation-id", u->exported_invocation_id);
3600 (void) serialize_bool(f, "exported-log-level-max", u->exported_log_level_max);
3601 (void) serialize_bool(f, "exported-log-extra-fields", u->exported_log_extra_fields);
3602 (void) serialize_bool(f, "exported-log-rate-limit-interval", u->exported_log_ratelimit_interval);
3603 (void) serialize_bool(f, "exported-log-rate-limit-burst", u->exported_log_ratelimit_burst);
3604
3605 (void) serialize_item_format(f, "cpu-usage-base", "%" PRIu64, u->cpu_usage_base);
3606 if (u->cpu_usage_last != NSEC_INFINITY)
3607 (void) serialize_item_format(f, "cpu-usage-last", "%" PRIu64, u->cpu_usage_last);
3608
3609 if (u->managed_oom_kill_last > 0)
3610 (void) serialize_item_format(f, "managed-oom-kill-last", "%" PRIu64, u->managed_oom_kill_last);
3611
3612 if (u->oom_kill_last > 0)
3613 (void) serialize_item_format(f, "oom-kill-last", "%" PRIu64, u->oom_kill_last);
3614
3615 for (CGroupIOAccountingMetric im = 0; im < _CGROUP_IO_ACCOUNTING_METRIC_MAX; im++) {
3616 (void) serialize_item_format(f, io_accounting_metric_field_base[im], "%" PRIu64, u->io_accounting_base[im]);
3617
3618 if (u->io_accounting_last[im] != UINT64_MAX)
3619 (void) serialize_item_format(f, io_accounting_metric_field_last[im], "%" PRIu64, u->io_accounting_last[im]);
3620 }
3621
3622 if (u->cgroup_path)
3623 (void) serialize_item(f, "cgroup", u->cgroup_path);
3624
3625 (void) serialize_bool(f, "cgroup-realized", u->cgroup_realized);
3626 (void) serialize_cgroup_mask(f, "cgroup-realized-mask", u->cgroup_realized_mask);
3627 (void) serialize_cgroup_mask(f, "cgroup-enabled-mask", u->cgroup_enabled_mask);
3628 (void) serialize_cgroup_mask(f, "cgroup-invalidated-mask", u->cgroup_invalidated_mask);
3629
3630 if (uid_is_valid(u->ref_uid))
3631 (void) serialize_item_format(f, "ref-uid", UID_FMT, u->ref_uid);
3632 if (gid_is_valid(u->ref_gid))
3633 (void) serialize_item_format(f, "ref-gid", GID_FMT, u->ref_gid);
3634
3635 if (!sd_id128_is_null(u->invocation_id))
3636 (void) serialize_item_format(f, "invocation-id", SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id));
3637
3638 (void) serialize_item_format(f, "freezer-state", "%s", freezer_state_to_string(unit_freezer_state(u)));
3639
3640 bus_track_serialize(u->bus_track, f, "ref");
3641
3642 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
3643 uint64_t v;
3644
3645 r = unit_get_ip_accounting(u, m, &v);
3646 if (r >= 0)
3647 (void) serialize_item_format(f, ip_accounting_metric_field[m], "%" PRIu64, v);
3648 }
3649
3650 if (serialize_jobs) {
3651 if (u->job) {
3652 fputs("job\n", f);
3653 job_serialize(u->job, f);
3654 }
3655
3656 if (u->nop_job) {
3657 fputs("job\n", f);
3658 job_serialize(u->nop_job, f);
3659 }
3660 }
3661
3662 /* End marker */
3663 fputc('\n', f);
3664 return 0;
3665 }
3666
3667 static int unit_deserialize_job(Unit *u, FILE *f) {
3668 _cleanup_(job_freep) Job *j = NULL;
3669 int r;
3670
3671 assert(u);
3672 assert(f);
3673
3674 j = job_new_raw(u);
3675 if (!j)
3676 return log_oom();
3677
3678 r = job_deserialize(j, f);
3679 if (r < 0)
3680 return r;
3681
3682 r = job_install_deserialized(j);
3683 if (r < 0)
3684 return r;
3685
3686 TAKE_PTR(j);
3687 return 0;
3688 }
3689
3690 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
3691 int r;
3692
3693 assert(u);
3694 assert(f);
3695 assert(fds);
3696
3697 for (;;) {
3698 _cleanup_free_ char *line = NULL;
3699 char *l, *v;
3700 ssize_t m;
3701 size_t k;
3702
3703 r = read_line(f, LONG_LINE_MAX, &line);
3704 if (r < 0)
3705 return log_error_errno(r, "Failed to read serialization line: %m");
3706 if (r == 0) /* eof */
3707 break;
3708
3709 l = strstrip(line);
3710 if (isempty(l)) /* End marker */
3711 break;
3712
3713 k = strcspn(l, "=");
3714
3715 if (l[k] == '=') {
3716 l[k] = 0;
3717 v = l+k+1;
3718 } else
3719 v = l+k;
3720
3721 if (streq(l, "job")) {
3722 if (v[0] == '\0') {
3723 /* New-style serialized job */
3724 r = unit_deserialize_job(u, f);
3725 if (r < 0)
3726 return r;
3727 } else /* Legacy for pre-44 */
3728 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
3729 continue;
3730 } else if (streq(l, "state-change-timestamp")) {
3731 (void) deserialize_dual_timestamp(v, &u->state_change_timestamp);
3732 continue;
3733 } else if (streq(l, "inactive-exit-timestamp")) {
3734 (void) deserialize_dual_timestamp(v, &u->inactive_exit_timestamp);
3735 continue;
3736 } else if (streq(l, "active-enter-timestamp")) {
3737 (void) deserialize_dual_timestamp(v, &u->active_enter_timestamp);
3738 continue;
3739 } else if (streq(l, "active-exit-timestamp")) {
3740 (void) deserialize_dual_timestamp(v, &u->active_exit_timestamp);
3741 continue;
3742 } else if (streq(l, "inactive-enter-timestamp")) {
3743 (void) deserialize_dual_timestamp(v, &u->inactive_enter_timestamp);
3744 continue;
3745 } else if (streq(l, "condition-timestamp")) {
3746 (void) deserialize_dual_timestamp(v, &u->condition_timestamp);
3747 continue;
3748 } else if (streq(l, "assert-timestamp")) {
3749 (void) deserialize_dual_timestamp(v, &u->assert_timestamp);
3750 continue;
3751 } else if (streq(l, "condition-result")) {
3752
3753 r = parse_boolean(v);
3754 if (r < 0)
3755 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
3756 else
3757 u->condition_result = r;
3758
3759 continue;
3760
3761 } else if (streq(l, "assert-result")) {
3762
3763 r = parse_boolean(v);
3764 if (r < 0)
3765 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
3766 else
3767 u->assert_result = r;
3768
3769 continue;
3770
3771 } else if (streq(l, "transient")) {
3772
3773 r = parse_boolean(v);
3774 if (r < 0)
3775 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
3776 else
3777 u->transient = r;
3778
3779 continue;
3780
3781 } else if (streq(l, "in-audit")) {
3782
3783 r = parse_boolean(v);
3784 if (r < 0)
3785 log_unit_debug(u, "Failed to parse in-audit bool %s, ignoring.", v);
3786 else
3787 u->in_audit = r;
3788
3789 continue;
3790
3791 } else if (streq(l, "exported-invocation-id")) {
3792
3793 r = parse_boolean(v);
3794 if (r < 0)
3795 log_unit_debug(u, "Failed to parse exported invocation ID bool %s, ignoring.", v);
3796 else
3797 u->exported_invocation_id = r;
3798
3799 continue;
3800
3801 } else if (streq(l, "exported-log-level-max")) {
3802
3803 r = parse_boolean(v);
3804 if (r < 0)
3805 log_unit_debug(u, "Failed to parse exported log level max bool %s, ignoring.", v);
3806 else
3807 u->exported_log_level_max = r;
3808
3809 continue;
3810
3811 } else if (streq(l, "exported-log-extra-fields")) {
3812
3813 r = parse_boolean(v);
3814 if (r < 0)
3815 log_unit_debug(u, "Failed to parse exported log extra fields bool %s, ignoring.", v);
3816 else
3817 u->exported_log_extra_fields = r;
3818
3819 continue;
3820
3821 } else if (streq(l, "exported-log-rate-limit-interval")) {
3822
3823 r = parse_boolean(v);
3824 if (r < 0)
3825 log_unit_debug(u, "Failed to parse exported log rate limit interval %s, ignoring.", v);
3826 else
3827 u->exported_log_ratelimit_interval = r;
3828
3829 continue;
3830
3831 } else if (streq(l, "exported-log-rate-limit-burst")) {
3832
3833 r = parse_boolean(v);
3834 if (r < 0)
3835 log_unit_debug(u, "Failed to parse exported log rate limit burst %s, ignoring.", v);
3836 else
3837 u->exported_log_ratelimit_burst = r;
3838
3839 continue;
3840
3841 } else if (STR_IN_SET(l, "cpu-usage-base", "cpuacct-usage-base")) {
3842
3843 r = safe_atou64(v, &u->cpu_usage_base);
3844 if (r < 0)
3845 log_unit_debug(u, "Failed to parse CPU usage base %s, ignoring.", v);
3846
3847 continue;
3848
3849 } else if (streq(l, "cpu-usage-last")) {
3850
3851 r = safe_atou64(v, &u->cpu_usage_last);
3852 if (r < 0)
3853 log_unit_debug(u, "Failed to read CPU usage last %s, ignoring.", v);
3854
3855 continue;
3856
3857 } else if (streq(l, "managed-oom-kill-last")) {
3858
3859 r = safe_atou64(v, &u->managed_oom_kill_last);
3860 if (r < 0)
3861 log_unit_debug(u, "Failed to read managed OOM kill last %s, ignoring.", v);
3862
3863 continue;
3864
3865 } else if (streq(l, "oom-kill-last")) {
3866
3867 r = safe_atou64(v, &u->oom_kill_last);
3868 if (r < 0)
3869 log_unit_debug(u, "Failed to read OOM kill last %s, ignoring.", v);
3870
3871 continue;
3872
3873 } else if (streq(l, "cgroup")) {
3874
3875 r = unit_set_cgroup_path(u, v);
3876 if (r < 0)
3877 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
3878
3879 (void) unit_watch_cgroup(u);
3880 (void) unit_watch_cgroup_memory(u);
3881
3882 continue;
3883 } else if (streq(l, "cgroup-realized")) {
3884 int b;
3885
3886 b = parse_boolean(v);
3887 if (b < 0)
3888 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
3889 else
3890 u->cgroup_realized = b;
3891
3892 continue;
3893
3894 } else if (streq(l, "cgroup-realized-mask")) {
3895
3896 r = cg_mask_from_string(v, &u->cgroup_realized_mask);
3897 if (r < 0)
3898 log_unit_debug(u, "Failed to parse cgroup-realized-mask %s, ignoring.", v);
3899 continue;
3900
3901 } else if (streq(l, "cgroup-enabled-mask")) {
3902
3903 r = cg_mask_from_string(v, &u->cgroup_enabled_mask);
3904 if (r < 0)
3905 log_unit_debug(u, "Failed to parse cgroup-enabled-mask %s, ignoring.", v);
3906 continue;
3907
3908 } else if (streq(l, "cgroup-invalidated-mask")) {
3909
3910 r = cg_mask_from_string(v, &u->cgroup_invalidated_mask);
3911 if (r < 0)
3912 log_unit_debug(u, "Failed to parse cgroup-invalidated-mask %s, ignoring.", v);
3913 continue;
3914
3915 } else if (streq(l, "ref-uid")) {
3916 uid_t uid;
3917
3918 r = parse_uid(v, &uid);
3919 if (r < 0)
3920 log_unit_debug(u, "Failed to parse referenced UID %s, ignoring.", v);
3921 else
3922 unit_ref_uid_gid(u, uid, GID_INVALID);
3923
3924 continue;
3925
3926 } else if (streq(l, "ref-gid")) {
3927 gid_t gid;
3928
3929 r = parse_gid(v, &gid);
3930 if (r < 0)
3931 log_unit_debug(u, "Failed to parse referenced GID %s, ignoring.", v);
3932 else
3933 unit_ref_uid_gid(u, UID_INVALID, gid);
3934
3935 continue;
3936
3937 } else if (streq(l, "ref")) {
3938
3939 r = strv_extend(&u->deserialized_refs, v);
3940 if (r < 0)
3941 return log_oom();
3942
3943 continue;
3944 } else if (streq(l, "invocation-id")) {
3945 sd_id128_t id;
3946
3947 r = sd_id128_from_string(v, &id);
3948 if (r < 0)
3949 log_unit_debug(u, "Failed to parse invocation id %s, ignoring.", v);
3950 else {
3951 r = unit_set_invocation_id(u, id);
3952 if (r < 0)
3953 log_unit_warning_errno(u, r, "Failed to set invocation ID for unit: %m");
3954 }
3955
3956 continue;
3957 } else if (streq(l, "freezer-state")) {
3958 FreezerState s;
3959
3960 s = freezer_state_from_string(v);
3961 if (s < 0)
3962 log_unit_debug(u, "Failed to deserialize freezer-state '%s', ignoring.", v);
3963 else
3964 u->freezer_state = s;
3965
3966 continue;
3967 }
3968
3969 /* Check if this is an IP accounting metric serialization field */
3970 m = string_table_lookup(ip_accounting_metric_field, ELEMENTSOF(ip_accounting_metric_field), l);
3971 if (m >= 0) {
3972 uint64_t c;
3973
3974 r = safe_atou64(v, &c);
3975 if (r < 0)
3976 log_unit_debug(u, "Failed to parse IP accounting value %s, ignoring.", v);
3977 else
3978 u->ip_accounting_extra[m] = c;
3979 continue;
3980 }
3981
3982 m = string_table_lookup(io_accounting_metric_field_base, ELEMENTSOF(io_accounting_metric_field_base), l);
3983 if (m >= 0) {
3984 uint64_t c;
3985
3986 r = safe_atou64(v, &c);
3987 if (r < 0)
3988 log_unit_debug(u, "Failed to parse IO accounting base value %s, ignoring.", v);
3989 else
3990 u->io_accounting_base[m] = c;
3991 continue;
3992 }
3993
3994 m = string_table_lookup(io_accounting_metric_field_last, ELEMENTSOF(io_accounting_metric_field_last), l);
3995 if (m >= 0) {
3996 uint64_t c;
3997
3998 r = safe_atou64(v, &c);
3999 if (r < 0)
4000 log_unit_debug(u, "Failed to parse IO accounting last value %s, ignoring.", v);
4001 else
4002 u->io_accounting_last[m] = c;
4003 continue;
4004 }
4005
4006 if (unit_can_serialize(u)) {
4007 r = exec_runtime_deserialize_compat(u, l, v, fds);
4008 if (r < 0) {
4009 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
4010 continue;
4011 }
4012
4013 /* Returns positive if key was handled by the call */
4014 if (r > 0)
4015 continue;
4016
4017 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
4018 if (r < 0)
4019 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
4020 }
4021 }
4022
4023 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
4024 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
4025 * before 228 where the base for timeouts was not persistent across reboots. */
4026
4027 if (!dual_timestamp_is_set(&u->state_change_timestamp))
4028 dual_timestamp_get(&u->state_change_timestamp);
4029
4030 /* Let's make sure that everything that is deserialized also gets any potential new cgroup settings applied
4031 * after we are done. For that we invalidate anything already realized, so that we can realize it again. */
4032 unit_invalidate_cgroup(u, _CGROUP_MASK_ALL);
4033 unit_invalidate_cgroup_bpf(u);
4034
4035 return 0;
4036 }
4037
4038 int unit_deserialize_skip(FILE *f) {
4039 int r;
4040 assert(f);
4041
4042 /* Skip serialized data for this unit. We don't know what it is. */
4043
4044 for (;;) {
4045 _cleanup_free_ char *line = NULL;
4046 char *l;
4047
4048 r = read_line(f, LONG_LINE_MAX, &line);
4049 if (r < 0)
4050 return log_error_errno(r, "Failed to read serialization line: %m");
4051 if (r == 0)
4052 return 0;
4053
4054 l = strstrip(line);
4055
4056 /* End marker */
4057 if (isempty(l))
4058 return 1;
4059 }
4060 }
4061
4062 int unit_add_node_dependency(Unit *u, const char *what, UnitDependency dep, UnitDependencyMask mask) {
4063 _cleanup_free_ char *e = NULL;
4064 Unit *device;
4065 int r;
4066
4067 assert(u);
4068
4069 /* Adds in links to the device node that this unit is based on */
4070 if (isempty(what))
4071 return 0;
4072
4073 if (!is_device_path(what))
4074 return 0;
4075
4076 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
4077 if (!unit_type_supported(UNIT_DEVICE))
4078 return 0;
4079
4080 r = unit_name_from_path(what, ".device", &e);
4081 if (r < 0)
4082 return r;
4083
4084 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
4085 if (r < 0)
4086 return r;
4087
4088 if (dep == UNIT_REQUIRES && device_shall_be_bound_by(device, u))
4089 dep = UNIT_BINDS_TO;
4090
4091 return unit_add_two_dependencies(u, UNIT_AFTER,
4092 MANAGER_IS_SYSTEM(u->manager) ? dep : UNIT_WANTS,
4093 device, true, mask);
4094 }
4095
4096 int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask) {
4097 _cleanup_free_ char *escaped = NULL, *target = NULL;
4098 int r;
4099
4100 assert(u);
4101
4102 if (isempty(what))
4103 return 0;
4104
4105 if (!path_startswith(what, "/dev/"))
4106 return 0;
4107
4108 /* If we don't support devices, then also don't bother with blockdev@.target */
4109 if (!unit_type_supported(UNIT_DEVICE))
4110 return 0;
4111
4112 r = unit_name_path_escape(what, &escaped);
4113 if (r < 0)
4114 return r;
4115
4116 r = unit_name_build("blockdev", escaped, ".target", &target);
4117 if (r < 0)
4118 return r;
4119
4120 return unit_add_dependency_by_name(u, UNIT_AFTER, target, true, mask);
4121 }
4122
4123 int unit_coldplug(Unit *u) {
4124 int r = 0, q;
4125 char **i;
4126 Job *uj;
4127
4128 assert(u);
4129
4130 /* Make sure we don't enter a loop, when coldplugging recursively. */
4131 if (u->coldplugged)
4132 return 0;
4133
4134 u->coldplugged = true;
4135
4136 STRV_FOREACH(i, u->deserialized_refs) {
4137 q = bus_unit_track_add_name(u, *i);
4138 if (q < 0 && r >= 0)
4139 r = q;
4140 }
4141 u->deserialized_refs = strv_free(u->deserialized_refs);
4142
4143 if (UNIT_VTABLE(u)->coldplug) {
4144 q = UNIT_VTABLE(u)->coldplug(u);
4145 if (q < 0 && r >= 0)
4146 r = q;
4147 }
4148
4149 uj = u->job ?: u->nop_job;
4150 if (uj) {
4151 q = job_coldplug(uj);
4152 if (q < 0 && r >= 0)
4153 r = q;
4154 }
4155
4156 return r;
4157 }
4158
4159 void unit_catchup(Unit *u) {
4160 assert(u);
4161
4162 if (UNIT_VTABLE(u)->catchup)
4163 UNIT_VTABLE(u)->catchup(u);
4164 }
4165
4166 static bool fragment_mtime_newer(const char *path, usec_t mtime, bool path_masked) {
4167 struct stat st;
4168
4169 if (!path)
4170 return false;
4171
4172 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
4173 * are never out-of-date. */
4174 if (PATH_STARTSWITH_SET(path, "/proc", "/sys"))
4175 return false;
4176
4177 if (stat(path, &st) < 0)
4178 /* What, cannot access this anymore? */
4179 return true;
4180
4181 if (path_masked)
4182 /* For masked files check if they are still so */
4183 return !null_or_empty(&st);
4184 else
4185 /* For non-empty files check the mtime */
4186 return timespec_load(&st.st_mtim) > mtime;
4187
4188 return false;
4189 }
4190
4191 bool unit_need_daemon_reload(Unit *u) {
4192 _cleanup_strv_free_ char **t = NULL;
4193 char **path;
4194
4195 assert(u);
4196
4197 /* For unit files, we allow masking… */
4198 if (fragment_mtime_newer(u->fragment_path, u->fragment_mtime,
4199 u->load_state == UNIT_MASKED))
4200 return true;
4201
4202 /* Source paths should not be masked… */
4203 if (fragment_mtime_newer(u->source_path, u->source_mtime, false))
4204 return true;
4205
4206 if (u->load_state == UNIT_LOADED)
4207 (void) unit_find_dropin_paths(u, &t);
4208 if (!strv_equal(u->dropin_paths, t))
4209 return true;
4210
4211 /* … any drop-ins that are masked are simply omitted from the list. */
4212 STRV_FOREACH(path, u->dropin_paths)
4213 if (fragment_mtime_newer(*path, u->dropin_mtime, false))
4214 return true;
4215
4216 return false;
4217 }
4218
4219 void unit_reset_failed(Unit *u) {
4220 assert(u);
4221
4222 if (UNIT_VTABLE(u)->reset_failed)
4223 UNIT_VTABLE(u)->reset_failed(u);
4224
4225 ratelimit_reset(&u->start_ratelimit);
4226 u->start_limit_hit = false;
4227 }
4228
4229 Unit *unit_following(Unit *u) {
4230 assert(u);
4231
4232 if (UNIT_VTABLE(u)->following)
4233 return UNIT_VTABLE(u)->following(u);
4234
4235 return NULL;
4236 }
4237
4238 bool unit_stop_pending(Unit *u) {
4239 assert(u);
4240
4241 /* This call does check the current state of the unit. It's
4242 * hence useful to be called from state change calls of the
4243 * unit itself, where the state isn't updated yet. This is
4244 * different from unit_inactive_or_pending() which checks both
4245 * the current state and for a queued job. */
4246
4247 return unit_has_job_type(u, JOB_STOP);
4248 }
4249
4250 bool unit_inactive_or_pending(Unit *u) {
4251 assert(u);
4252
4253 /* Returns true if the unit is inactive or going down */
4254
4255 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
4256 return true;
4257
4258 if (unit_stop_pending(u))
4259 return true;
4260
4261 return false;
4262 }
4263
4264 bool unit_active_or_pending(Unit *u) {
4265 assert(u);
4266
4267 /* Returns true if the unit is active or going up */
4268
4269 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
4270 return true;
4271
4272 if (u->job &&
4273 IN_SET(u->job->type, JOB_START, JOB_RELOAD_OR_START, JOB_RESTART))
4274 return true;
4275
4276 return false;
4277 }
4278
4279 bool unit_will_restart_default(Unit *u) {
4280 assert(u);
4281
4282 return unit_has_job_type(u, JOB_START);
4283 }
4284
4285 bool unit_will_restart(Unit *u) {
4286 assert(u);
4287
4288 if (!UNIT_VTABLE(u)->will_restart)
4289 return false;
4290
4291 return UNIT_VTABLE(u)->will_restart(u);
4292 }
4293
4294 int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
4295 assert(u);
4296 assert(w >= 0 && w < _KILL_WHO_MAX);
4297 assert(SIGNAL_VALID(signo));
4298
4299 if (!UNIT_VTABLE(u)->kill)
4300 return -EOPNOTSUPP;
4301
4302 return UNIT_VTABLE(u)->kill(u, w, signo, error);
4303 }
4304
4305 static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
4306 _cleanup_set_free_ Set *pid_set = NULL;
4307 int r;
4308
4309 pid_set = set_new(NULL);
4310 if (!pid_set)
4311 return NULL;
4312
4313 /* Exclude the main/control pids from being killed via the cgroup */
4314 if (main_pid > 0) {
4315 r = set_put(pid_set, PID_TO_PTR(main_pid));
4316 if (r < 0)
4317 return NULL;
4318 }
4319
4320 if (control_pid > 0) {
4321 r = set_put(pid_set, PID_TO_PTR(control_pid));
4322 if (r < 0)
4323 return NULL;
4324 }
4325
4326 return TAKE_PTR(pid_set);
4327 }
4328
4329 static int kill_common_log(pid_t pid, int signo, void *userdata) {
4330 _cleanup_free_ char *comm = NULL;
4331 Unit *u = userdata;
4332
4333 assert(u);
4334
4335 (void) get_process_comm(pid, &comm);
4336 log_unit_info(u, "Sending signal SIG%s to process " PID_FMT " (%s) on client request.",
4337 signal_to_string(signo), pid, strna(comm));
4338
4339 return 1;
4340 }
4341
4342 int unit_kill_common(
4343 Unit *u,
4344 KillWho who,
4345 int signo,
4346 pid_t main_pid,
4347 pid_t control_pid,
4348 sd_bus_error *error) {
4349
4350 int r = 0;
4351 bool killed = false;
4352
4353 /* This is the common implementation for explicit user-requested killing of unit processes, shared by
4354 * various unit types. Do not confuse with unit_kill_context(), which is what we use when we want to
4355 * stop a service ourselves. */
4356
4357 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
4358 if (main_pid < 0)
4359 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
4360 if (main_pid == 0)
4361 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
4362 }
4363
4364 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
4365 if (control_pid < 0)
4366 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
4367 if (control_pid == 0)
4368 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
4369 }
4370
4371 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
4372 if (control_pid > 0) {
4373 _cleanup_free_ char *comm = NULL;
4374 (void) get_process_comm(control_pid, &comm);
4375
4376 if (kill(control_pid, signo) < 0) {
4377 /* Report this failure both to the logs and to the client */
4378 sd_bus_error_set_errnof(
4379 error, errno,
4380 "Failed to send signal SIG%s to control process " PID_FMT " (%s): %m",
4381 signal_to_string(signo), control_pid, strna(comm));
4382 r = log_unit_warning_errno(
4383 u, errno,
4384 "Failed to send signal SIG%s to control process " PID_FMT " (%s) on client request: %m",
4385 signal_to_string(signo), control_pid, strna(comm));
4386 } else {
4387 log_unit_info(u, "Sent signal SIG%s to control process " PID_FMT " (%s) on client request.",
4388 signal_to_string(signo), control_pid, strna(comm));
4389 killed = true;
4390 }
4391 }
4392
4393 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
4394 if (main_pid > 0) {
4395 _cleanup_free_ char *comm = NULL;
4396 (void) get_process_comm(main_pid, &comm);
4397
4398 if (kill(main_pid, signo) < 0) {
4399 if (r == 0)
4400 sd_bus_error_set_errnof(
4401 error, errno,
4402 "Failed to send signal SIG%s to main process " PID_FMT " (%s): %m",
4403 signal_to_string(signo), main_pid, strna(comm));
4404
4405 r = log_unit_warning_errno(
4406 u, errno,
4407 "Failed to send signal SIG%s to main process " PID_FMT " (%s) on client request: %m",
4408 signal_to_string(signo), main_pid, strna(comm));
4409 } else {
4410 log_unit_info(u, "Sent signal SIG%s to main process " PID_FMT " (%s) on client request.",
4411 signal_to_string(signo), main_pid, strna(comm));
4412 killed = true;
4413 }
4414 }
4415
4416 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
4417 _cleanup_set_free_ Set *pid_set = NULL;
4418 int q;
4419
4420 /* Exclude the main/control pids from being killed via the cgroup */
4421 pid_set = unit_pid_set(main_pid, control_pid);
4422 if (!pid_set)
4423 return log_oom();
4424
4425 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, 0, pid_set, kill_common_log, u);
4426 if (q < 0) {
4427 if (!IN_SET(q, -ESRCH, -ENOENT)) {
4428 if (r == 0)
4429 sd_bus_error_set_errnof(
4430 error, q,
4431 "Failed to send signal SIG%s to auxiliary processes: %m",
4432 signal_to_string(signo));
4433
4434 r = log_unit_warning_errno(
4435 u, q,
4436 "Failed to send signal SIG%s to auxiliary processes on client request: %m",
4437 signal_to_string(signo));
4438 }
4439 } else
4440 killed = true;
4441 }
4442
4443 /* If the "fail" versions of the operation are requested, then complain if the set of processes we killed is empty */
4444 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_MAIN_FAIL))
4445 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No matching processes to kill");
4446
4447 return r;
4448 }
4449
4450 int unit_following_set(Unit *u, Set **s) {
4451 assert(u);
4452 assert(s);
4453
4454 if (UNIT_VTABLE(u)->following_set)
4455 return UNIT_VTABLE(u)->following_set(u, s);
4456
4457 *s = NULL;
4458 return 0;
4459 }
4460
4461 UnitFileState unit_get_unit_file_state(Unit *u) {
4462 int r;
4463
4464 assert(u);
4465
4466 if (u->unit_file_state < 0 && u->fragment_path) {
4467 r = unit_file_get_state(
4468 u->manager->unit_file_scope,
4469 NULL,
4470 u->id,
4471 &u->unit_file_state);
4472 if (r < 0)
4473 u->unit_file_state = UNIT_FILE_BAD;
4474 }
4475
4476 return u->unit_file_state;
4477 }
4478
4479 int unit_get_unit_file_preset(Unit *u) {
4480 assert(u);
4481
4482 if (u->unit_file_preset < 0 && u->fragment_path)
4483 u->unit_file_preset = unit_file_query_preset(
4484 u->manager->unit_file_scope,
4485 NULL,
4486 basename(u->fragment_path),
4487 NULL);
4488
4489 return u->unit_file_preset;
4490 }
4491
4492 Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target) {
4493 assert(ref);
4494 assert(source);
4495 assert(target);
4496
4497 if (ref->target)
4498 unit_ref_unset(ref);
4499
4500 ref->source = source;
4501 ref->target = target;
4502 LIST_PREPEND(refs_by_target, target->refs_by_target, ref);
4503 return target;
4504 }
4505
4506 void unit_ref_unset(UnitRef *ref) {
4507 assert(ref);
4508
4509 if (!ref->target)
4510 return;
4511
4512 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4513 * be unreferenced now. */
4514 unit_add_to_gc_queue(ref->target);
4515
4516 LIST_REMOVE(refs_by_target, ref->target->refs_by_target, ref);
4517 ref->source = ref->target = NULL;
4518 }
4519
4520 static int user_from_unit_name(Unit *u, char **ret) {
4521
4522 static const uint8_t hash_key[] = {
4523 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4524 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4525 };
4526
4527 _cleanup_free_ char *n = NULL;
4528 int r;
4529
4530 r = unit_name_to_prefix(u->id, &n);
4531 if (r < 0)
4532 return r;
4533
4534 if (valid_user_group_name(n, 0)) {
4535 *ret = TAKE_PTR(n);
4536 return 0;
4537 }
4538
4539 /* If we can't use the unit name as a user name, then let's hash it and use that */
4540 if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
4541 return -ENOMEM;
4542
4543 return 0;
4544 }
4545
4546 int unit_patch_contexts(Unit *u) {
4547 CGroupContext *cc;
4548 ExecContext *ec;
4549 int r;
4550
4551 assert(u);
4552
4553 /* Patch in the manager defaults into the exec and cgroup
4554 * contexts, _after_ the rest of the settings have been
4555 * initialized */
4556
4557 ec = unit_get_exec_context(u);
4558 if (ec) {
4559 /* This only copies in the ones that need memory */
4560 for (unsigned i = 0; i < _RLIMIT_MAX; i++)
4561 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
4562 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
4563 if (!ec->rlimit[i])
4564 return -ENOMEM;
4565 }
4566
4567 if (MANAGER_IS_USER(u->manager) &&
4568 !ec->working_directory) {
4569
4570 r = get_home_dir(&ec->working_directory);
4571 if (r < 0)
4572 return r;
4573
4574 /* Allow user services to run, even if the
4575 * home directory is missing */
4576 ec->working_directory_missing_ok = true;
4577 }
4578
4579 if (ec->private_devices)
4580 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
4581
4582 if (ec->protect_kernel_modules)
4583 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
4584
4585 if (ec->protect_kernel_logs)
4586 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
4587
4588 if (ec->protect_clock)
4589 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) | (UINT64_C(1) << CAP_WAKE_ALARM));
4590
4591 if (ec->dynamic_user) {
4592 if (!ec->user) {
4593 r = user_from_unit_name(u, &ec->user);
4594 if (r < 0)
4595 return r;
4596 }
4597
4598 if (!ec->group) {
4599 ec->group = strdup(ec->user);
4600 if (!ec->group)
4601 return -ENOMEM;
4602 }
4603
4604 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4605 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4606 * sandbox. */
4607
4608 ec->private_tmp = true;
4609 ec->remove_ipc = true;
4610 ec->protect_system = PROTECT_SYSTEM_STRICT;
4611 if (ec->protect_home == PROTECT_HOME_NO)
4612 ec->protect_home = PROTECT_HOME_READ_ONLY;
4613
4614 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4615 * them. */
4616 ec->no_new_privileges = true;
4617 ec->restrict_suid_sgid = true;
4618 }
4619 }
4620
4621 cc = unit_get_cgroup_context(u);
4622 if (cc && ec) {
4623
4624 if (ec->private_devices &&
4625 cc->device_policy == CGROUP_DEVICE_POLICY_AUTO)
4626 cc->device_policy = CGROUP_DEVICE_POLICY_CLOSED;
4627
4628 if ((ec->root_image || !LIST_IS_EMPTY(ec->mount_images)) &&
4629 (cc->device_policy != CGROUP_DEVICE_POLICY_AUTO || cc->device_allow)) {
4630 const char *p;
4631
4632 /* When RootImage= or MountImages= is specified, the following devices are touched. */
4633 FOREACH_STRING(p, "/dev/loop-control", "/dev/mapper/control") {
4634 r = cgroup_add_device_allow(cc, p, "rw");
4635 if (r < 0)
4636 return r;
4637 }
4638 FOREACH_STRING(p, "block-loop", "block-blkext", "block-device-mapper") {
4639 r = cgroup_add_device_allow(cc, p, "rwm");
4640 if (r < 0)
4641 return r;
4642 }
4643
4644 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
4645 * Same for mapper and verity. */
4646 FOREACH_STRING(p, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
4647 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, p, true, UNIT_DEPENDENCY_FILE);
4648 if (r < 0)
4649 return r;
4650 }
4651 }
4652
4653 if (ec->protect_clock) {
4654 r = cgroup_add_device_allow(cc, "char-rtc", "r");
4655 if (r < 0)
4656 return r;
4657 }
4658 }
4659
4660 return 0;
4661 }
4662
4663 ExecContext *unit_get_exec_context(Unit *u) {
4664 size_t offset;
4665 assert(u);
4666
4667 if (u->type < 0)
4668 return NULL;
4669
4670 offset = UNIT_VTABLE(u)->exec_context_offset;
4671 if (offset <= 0)
4672 return NULL;
4673
4674 return (ExecContext*) ((uint8_t*) u + offset);
4675 }
4676
4677 KillContext *unit_get_kill_context(Unit *u) {
4678 size_t offset;
4679 assert(u);
4680
4681 if (u->type < 0)
4682 return NULL;
4683
4684 offset = UNIT_VTABLE(u)->kill_context_offset;
4685 if (offset <= 0)
4686 return NULL;
4687
4688 return (KillContext*) ((uint8_t*) u + offset);
4689 }
4690
4691 CGroupContext *unit_get_cgroup_context(Unit *u) {
4692 size_t offset;
4693
4694 if (u->type < 0)
4695 return NULL;
4696
4697 offset = UNIT_VTABLE(u)->cgroup_context_offset;
4698 if (offset <= 0)
4699 return NULL;
4700
4701 return (CGroupContext*) ((uint8_t*) u + offset);
4702 }
4703
4704 ExecRuntime *unit_get_exec_runtime(Unit *u) {
4705 size_t offset;
4706
4707 if (u->type < 0)
4708 return NULL;
4709
4710 offset = UNIT_VTABLE(u)->exec_runtime_offset;
4711 if (offset <= 0)
4712 return NULL;
4713
4714 return *(ExecRuntime**) ((uint8_t*) u + offset);
4715 }
4716
4717 static const char* unit_drop_in_dir(Unit *u, UnitWriteFlags flags) {
4718 assert(u);
4719
4720 if (UNIT_WRITE_FLAGS_NOOP(flags))
4721 return NULL;
4722
4723 if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
4724 return u->manager->lookup_paths.transient;
4725
4726 if (flags & UNIT_PERSISTENT)
4727 return u->manager->lookup_paths.persistent_control;
4728
4729 if (flags & UNIT_RUNTIME)
4730 return u->manager->lookup_paths.runtime_control;
4731
4732 return NULL;
4733 }
4734
4735 char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) {
4736 char *ret = NULL;
4737
4738 if (!s)
4739 return NULL;
4740
4741 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
4742 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
4743 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
4744 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
4745 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
4746 * allocations. */
4747
4748 if (flags & UNIT_ESCAPE_SPECIFIERS) {
4749 ret = specifier_escape(s);
4750 if (!ret)
4751 return NULL;
4752
4753 s = ret;
4754 }
4755
4756 if (flags & UNIT_ESCAPE_C) {
4757 char *a;
4758
4759 a = cescape(s);
4760 free(ret);
4761 if (!a)
4762 return NULL;
4763
4764 ret = a;
4765 }
4766
4767 if (buf) {
4768 *buf = ret;
4769 return ret ?: (char*) s;
4770 }
4771
4772 return ret ?: strdup(s);
4773 }
4774
4775 char* unit_concat_strv(char **l, UnitWriteFlags flags) {
4776 _cleanup_free_ char *result = NULL;
4777 size_t n = 0, allocated = 0;
4778 char **i;
4779
4780 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
4781 * way suitable for ExecStart= stanzas */
4782
4783 STRV_FOREACH(i, l) {
4784 _cleanup_free_ char *buf = NULL;
4785 const char *p;
4786 size_t a;
4787 char *q;
4788
4789 p = unit_escape_setting(*i, flags, &buf);
4790 if (!p)
4791 return NULL;
4792
4793 a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */
4794 if (!GREEDY_REALLOC(result, allocated, n + a + 1))
4795 return NULL;
4796
4797 q = result + n;
4798 if (n > 0)
4799 *(q++) = ' ';
4800
4801 *(q++) = '"';
4802 q = stpcpy(q, p);
4803 *(q++) = '"';
4804
4805 n += a;
4806 }
4807
4808 if (!GREEDY_REALLOC(result, allocated, n + 1))
4809 return NULL;
4810
4811 result[n] = 0;
4812
4813 return TAKE_PTR(result);
4814 }
4815
4816 int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data) {
4817 _cleanup_free_ char *p = NULL, *q = NULL, *escaped = NULL;
4818 const char *dir, *wrapped;
4819 int r;
4820
4821 assert(u);
4822 assert(name);
4823 assert(data);
4824
4825 if (UNIT_WRITE_FLAGS_NOOP(flags))
4826 return 0;
4827
4828 data = unit_escape_setting(data, flags, &escaped);
4829 if (!data)
4830 return -ENOMEM;
4831
4832 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4833 * previous section header is the same */
4834
4835 if (flags & UNIT_PRIVATE) {
4836 if (!UNIT_VTABLE(u)->private_section)
4837 return -EINVAL;
4838
4839 if (!u->transient_file || u->last_section_private < 0)
4840 data = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
4841 else if (u->last_section_private == 0)
4842 data = strjoina("\n[", UNIT_VTABLE(u)->private_section, "]\n", data);
4843 } else {
4844 if (!u->transient_file || u->last_section_private < 0)
4845 data = strjoina("[Unit]\n", data);
4846 else if (u->last_section_private > 0)
4847 data = strjoina("\n[Unit]\n", data);
4848 }
4849
4850 if (u->transient_file) {
4851 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4852 * write to the transient unit file. */
4853 fputs(data, u->transient_file);
4854
4855 if (!endswith(data, "\n"))
4856 fputc('\n', u->transient_file);
4857
4858 /* Remember which section we wrote this entry to */
4859 u->last_section_private = !!(flags & UNIT_PRIVATE);
4860 return 0;
4861 }
4862
4863 dir = unit_drop_in_dir(u, flags);
4864 if (!dir)
4865 return -EINVAL;
4866
4867 wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
4868 "# or an equivalent operation. Do not edit.\n",
4869 data,
4870 "\n");
4871
4872 r = drop_in_file(dir, u->id, 50, name, &p, &q);
4873 if (r < 0)
4874 return r;
4875
4876 (void) mkdir_p_label(p, 0755);
4877
4878 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4879 * recreate the cache after every drop-in we write. */
4880 if (u->manager->unit_path_cache) {
4881 r = set_put_strdup(&u->manager->unit_path_cache, p);
4882 if (r < 0)
4883 return r;
4884 }
4885
4886 r = write_string_file_atomic_label(q, wrapped);
4887 if (r < 0)
4888 return r;
4889
4890 r = strv_push(&u->dropin_paths, q);
4891 if (r < 0)
4892 return r;
4893 q = NULL;
4894
4895 strv_uniq(u->dropin_paths);
4896
4897 u->dropin_mtime = now(CLOCK_REALTIME);
4898
4899 return 0;
4900 }
4901
4902 int unit_write_settingf(Unit *u, UnitWriteFlags flags, const char *name, const char *format, ...) {
4903 _cleanup_free_ char *p = NULL;
4904 va_list ap;
4905 int r;
4906
4907 assert(u);
4908 assert(name);
4909 assert(format);
4910
4911 if (UNIT_WRITE_FLAGS_NOOP(flags))
4912 return 0;
4913
4914 va_start(ap, format);
4915 r = vasprintf(&p, format, ap);
4916 va_end(ap);
4917
4918 if (r < 0)
4919 return -ENOMEM;
4920
4921 return unit_write_setting(u, flags, name, p);
4922 }
4923
4924 int unit_make_transient(Unit *u) {
4925 _cleanup_free_ char *path = NULL;
4926 FILE *f;
4927
4928 assert(u);
4929
4930 if (!UNIT_VTABLE(u)->can_transient)
4931 return -EOPNOTSUPP;
4932
4933 (void) mkdir_p_label(u->manager->lookup_paths.transient, 0755);
4934
4935 path = path_join(u->manager->lookup_paths.transient, u->id);
4936 if (!path)
4937 return -ENOMEM;
4938
4939 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4940 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4941
4942 RUN_WITH_UMASK(0022) {
4943 f = fopen(path, "we");
4944 if (!f)
4945 return -errno;
4946 }
4947
4948 safe_fclose(u->transient_file);
4949 u->transient_file = f;
4950
4951 free_and_replace(u->fragment_path, path);
4952
4953 u->source_path = mfree(u->source_path);
4954 u->dropin_paths = strv_free(u->dropin_paths);
4955 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
4956
4957 u->load_state = UNIT_STUB;
4958 u->load_error = 0;
4959 u->transient = true;
4960
4961 unit_add_to_dbus_queue(u);
4962 unit_add_to_gc_queue(u);
4963
4964 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4965 u->transient_file);
4966
4967 return 0;
4968 }
4969
4970 static int log_kill(pid_t pid, int sig, void *userdata) {
4971 _cleanup_free_ char *comm = NULL;
4972
4973 (void) get_process_comm(pid, &comm);
4974
4975 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4976 only, like for example systemd's own PAM stub process. */
4977 if (comm && comm[0] == '(')
4978 return 0;
4979
4980 log_unit_notice(userdata,
4981 "Killing process " PID_FMT " (%s) with signal SIG%s.",
4982 pid,
4983 strna(comm),
4984 signal_to_string(sig));
4985
4986 return 1;
4987 }
4988
4989 static int operation_to_signal(const KillContext *c, KillOperation k, bool *noteworthy) {
4990 assert(c);
4991
4992 switch (k) {
4993
4994 case KILL_TERMINATE:
4995 case KILL_TERMINATE_AND_LOG:
4996 *noteworthy = false;
4997 return c->kill_signal;
4998
4999 case KILL_RESTART:
5000 *noteworthy = false;
5001 return restart_kill_signal(c);
5002
5003 case KILL_KILL:
5004 *noteworthy = true;
5005 return c->final_kill_signal;
5006
5007 case KILL_WATCHDOG:
5008 *noteworthy = true;
5009 return c->watchdog_signal;
5010
5011 default:
5012 assert_not_reached("KillOperation unknown");
5013 }
5014 }
5015
5016 int unit_kill_context(
5017 Unit *u,
5018 KillContext *c,
5019 KillOperation k,
5020 pid_t main_pid,
5021 pid_t control_pid,
5022 bool main_pid_alien) {
5023
5024 bool wait_for_exit = false, send_sighup;
5025 cg_kill_log_func_t log_func = NULL;
5026 int sig, r;
5027
5028 assert(u);
5029 assert(c);
5030
5031 /* Kill the processes belonging to this unit, in preparation for shutting the unit down. Returns > 0
5032 * if we killed something worth waiting for, 0 otherwise. Do not confuse with unit_kill_common()
5033 * which is used for user-requested killing of unit processes. */
5034
5035 if (c->kill_mode == KILL_NONE)
5036 return 0;
5037
5038 bool noteworthy;
5039 sig = operation_to_signal(c, k, &noteworthy);
5040 if (noteworthy)
5041 log_func = log_kill;
5042
5043 send_sighup =
5044 c->send_sighup &&
5045 IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
5046 sig != SIGHUP;
5047
5048 if (main_pid > 0) {
5049 if (log_func)
5050 log_func(main_pid, sig, u);
5051
5052 r = kill_and_sigcont(main_pid, sig);
5053 if (r < 0 && r != -ESRCH) {
5054 _cleanup_free_ char *comm = NULL;
5055 (void) get_process_comm(main_pid, &comm);
5056
5057 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
5058 } else {
5059 if (!main_pid_alien)
5060 wait_for_exit = true;
5061
5062 if (r != -ESRCH && send_sighup)
5063 (void) kill(main_pid, SIGHUP);
5064 }
5065 }
5066
5067 if (control_pid > 0) {
5068 if (log_func)
5069 log_func(control_pid, sig, u);
5070
5071 r = kill_and_sigcont(control_pid, sig);
5072 if (r < 0 && r != -ESRCH) {
5073 _cleanup_free_ char *comm = NULL;
5074 (void) get_process_comm(control_pid, &comm);
5075
5076 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
5077 } else {
5078 wait_for_exit = true;
5079
5080 if (r != -ESRCH && send_sighup)
5081 (void) kill(control_pid, SIGHUP);
5082 }
5083 }
5084
5085 if (u->cgroup_path &&
5086 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
5087 _cleanup_set_free_ Set *pid_set = NULL;
5088
5089 /* Exclude the main/control pids from being killed via the cgroup */
5090 pid_set = unit_pid_set(main_pid, control_pid);
5091 if (!pid_set)
5092 return -ENOMEM;
5093
5094 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
5095 sig,
5096 CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
5097 pid_set,
5098 log_func, u);
5099 if (r < 0) {
5100 if (!IN_SET(r, -EAGAIN, -ESRCH, -ENOENT))
5101 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
5102
5103 } else if (r > 0) {
5104
5105 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
5106 * we are running in a container or if this is a delegation unit, simply because cgroup
5107 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
5108 * of containers it can be confused easily by left-over directories in the cgroup — which
5109 * however should not exist in non-delegated units. On the unified hierarchy that's different,
5110 * there we get proper events. Hence rely on them. */
5111
5112 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0 ||
5113 (detect_container() == 0 && !unit_cgroup_delegate(u)))
5114 wait_for_exit = true;
5115
5116 if (send_sighup) {
5117 set_free(pid_set);
5118
5119 pid_set = unit_pid_set(main_pid, control_pid);
5120 if (!pid_set)
5121 return -ENOMEM;
5122
5123 (void) cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
5124 SIGHUP,
5125 CGROUP_IGNORE_SELF,
5126 pid_set,
5127 NULL, NULL);
5128 }
5129 }
5130 }
5131
5132 return wait_for_exit;
5133 }
5134
5135 int unit_require_mounts_for(Unit *u, const char *path, UnitDependencyMask mask) {
5136 _cleanup_free_ char *p = NULL;
5137 UnitDependencyInfo di;
5138 int r;
5139
5140 assert(u);
5141 assert(path);
5142
5143 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
5144 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
5145 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
5146 * determine which units to make themselves a dependency of. */
5147
5148 if (!path_is_absolute(path))
5149 return -EINVAL;
5150
5151 r = hashmap_ensure_allocated(&u->requires_mounts_for, &path_hash_ops);
5152 if (r < 0)
5153 return r;
5154
5155 p = strdup(path);
5156 if (!p)
5157 return -ENOMEM;
5158
5159 path = path_simplify(p, true);
5160
5161 if (!path_is_normalized(path))
5162 return -EPERM;
5163
5164 if (hashmap_contains(u->requires_mounts_for, path))
5165 return 0;
5166
5167 di = (UnitDependencyInfo) {
5168 .origin_mask = mask
5169 };
5170
5171 r = hashmap_put(u->requires_mounts_for, path, di.data);
5172 if (r < 0)
5173 return r;
5174 p = NULL;
5175
5176 char prefix[strlen(path) + 1];
5177 PATH_FOREACH_PREFIX_MORE(prefix, path) {
5178 Set *x;
5179
5180 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
5181 if (!x) {
5182 _cleanup_free_ char *q = NULL;
5183
5184 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &path_hash_ops);
5185 if (r < 0)
5186 return r;
5187
5188 q = strdup(prefix);
5189 if (!q)
5190 return -ENOMEM;
5191
5192 x = set_new(NULL);
5193 if (!x)
5194 return -ENOMEM;
5195
5196 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
5197 if (r < 0) {
5198 set_free(x);
5199 return r;
5200 }
5201 q = NULL;
5202 }
5203
5204 r = set_put(x, u);
5205 if (r < 0)
5206 return r;
5207 }
5208
5209 return 0;
5210 }
5211
5212 int unit_setup_exec_runtime(Unit *u) {
5213 ExecRuntime **rt;
5214 size_t offset;
5215 Unit *other;
5216 void *v;
5217 int r;
5218
5219 offset = UNIT_VTABLE(u)->exec_runtime_offset;
5220 assert(offset > 0);
5221
5222 /* Check if there already is an ExecRuntime for this unit? */
5223 rt = (ExecRuntime**) ((uint8_t*) u + offset);
5224 if (*rt)
5225 return 0;
5226
5227 /* Try to get it from somebody else */
5228 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_JOINS_NAMESPACE_OF]) {
5229 r = exec_runtime_acquire(u->manager, NULL, other->id, false, rt);
5230 if (r == 1)
5231 return 1;
5232 }
5233
5234 return exec_runtime_acquire(u->manager, unit_get_exec_context(u), u->id, true, rt);
5235 }
5236
5237 int unit_setup_dynamic_creds(Unit *u) {
5238 ExecContext *ec;
5239 DynamicCreds *dcreds;
5240 size_t offset;
5241
5242 assert(u);
5243
5244 offset = UNIT_VTABLE(u)->dynamic_creds_offset;
5245 assert(offset > 0);
5246 dcreds = (DynamicCreds*) ((uint8_t*) u + offset);
5247
5248 ec = unit_get_exec_context(u);
5249 assert(ec);
5250
5251 if (!ec->dynamic_user)
5252 return 0;
5253
5254 return dynamic_creds_acquire(dcreds, u->manager, ec->user, ec->group);
5255 }
5256
5257 bool unit_type_supported(UnitType t) {
5258 if (_unlikely_(t < 0))
5259 return false;
5260 if (_unlikely_(t >= _UNIT_TYPE_MAX))
5261 return false;
5262
5263 if (!unit_vtable[t]->supported)
5264 return true;
5265
5266 return unit_vtable[t]->supported();
5267 }
5268
5269 void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
5270 int r;
5271
5272 assert(u);
5273 assert(where);
5274
5275 r = dir_is_empty(where);
5276 if (r > 0 || r == -ENOTDIR)
5277 return;
5278 if (r < 0) {
5279 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
5280 return;
5281 }
5282
5283 log_struct(LOG_NOTICE,
5284 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5285 LOG_UNIT_ID(u),
5286 LOG_UNIT_INVOCATION_ID(u),
5287 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
5288 "WHERE=%s", where);
5289 }
5290
5291 int unit_fail_if_noncanonical(Unit *u, const char* where) {
5292 _cleanup_free_ char *canonical_where = NULL;
5293 int r;
5294
5295 assert(u);
5296 assert(where);
5297
5298 r = chase_symlinks(where, NULL, CHASE_NONEXISTENT, &canonical_where, NULL);
5299 if (r < 0) {
5300 log_unit_debug_errno(u, r, "Failed to check %s for symlinks, ignoring: %m", where);
5301 return 0;
5302 }
5303
5304 /* We will happily ignore a trailing slash (or any redundant slashes) */
5305 if (path_equal(where, canonical_where))
5306 return 0;
5307
5308 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
5309 log_struct(LOG_ERR,
5310 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5311 LOG_UNIT_ID(u),
5312 LOG_UNIT_INVOCATION_ID(u),
5313 LOG_UNIT_MESSAGE(u, "Mount path %s is not canonical (contains a symlink).", where),
5314 "WHERE=%s", where);
5315
5316 return -ELOOP;
5317 }
5318
5319 bool unit_is_pristine(Unit *u) {
5320 assert(u);
5321
5322 /* Check if the unit already exists or is already around,
5323 * in a number of different ways. Note that to cater for unit
5324 * types such as slice, we are generally fine with units that
5325 * are marked UNIT_LOADED even though nothing was actually
5326 * loaded, as those unit types don't require a file on disk. */
5327
5328 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
5329 u->fragment_path ||
5330 u->source_path ||
5331 !strv_isempty(u->dropin_paths) ||
5332 u->job ||
5333 u->merged_into);
5334 }
5335
5336 pid_t unit_control_pid(Unit *u) {
5337 assert(u);
5338
5339 if (UNIT_VTABLE(u)->control_pid)
5340 return UNIT_VTABLE(u)->control_pid(u);
5341
5342 return 0;
5343 }
5344
5345 pid_t unit_main_pid(Unit *u) {
5346 assert(u);
5347
5348 if (UNIT_VTABLE(u)->main_pid)
5349 return UNIT_VTABLE(u)->main_pid(u);
5350
5351 return 0;
5352 }
5353
5354 static void unit_unref_uid_internal(
5355 Unit *u,
5356 uid_t *ref_uid,
5357 bool destroy_now,
5358 void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
5359
5360 assert(u);
5361 assert(ref_uid);
5362 assert(_manager_unref_uid);
5363
5364 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5365 * gid_t are actually the same time, with the same validity rules.
5366 *
5367 * Drops a reference to UID/GID from a unit. */
5368
5369 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5370 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5371
5372 if (!uid_is_valid(*ref_uid))
5373 return;
5374
5375 _manager_unref_uid(u->manager, *ref_uid, destroy_now);
5376 *ref_uid = UID_INVALID;
5377 }
5378
5379 static void unit_unref_uid(Unit *u, bool destroy_now) {
5380 unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
5381 }
5382
5383 static void unit_unref_gid(Unit *u, bool destroy_now) {
5384 unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
5385 }
5386
5387 void unit_unref_uid_gid(Unit *u, bool destroy_now) {
5388 assert(u);
5389
5390 unit_unref_uid(u, destroy_now);
5391 unit_unref_gid(u, destroy_now);
5392 }
5393
5394 static int unit_ref_uid_internal(
5395 Unit *u,
5396 uid_t *ref_uid,
5397 uid_t uid,
5398 bool clean_ipc,
5399 int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
5400
5401 int r;
5402
5403 assert(u);
5404 assert(ref_uid);
5405 assert(uid_is_valid(uid));
5406 assert(_manager_ref_uid);
5407
5408 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5409 * are actually the same type, and have the same validity rules.
5410 *
5411 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5412 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5413 * drops to zero. */
5414
5415 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5416 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5417
5418 if (*ref_uid == uid)
5419 return 0;
5420
5421 if (uid_is_valid(*ref_uid)) /* Already set? */
5422 return -EBUSY;
5423
5424 r = _manager_ref_uid(u->manager, uid, clean_ipc);
5425 if (r < 0)
5426 return r;
5427
5428 *ref_uid = uid;
5429 return 1;
5430 }
5431
5432 static int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
5433 return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
5434 }
5435
5436 static int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
5437 return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
5438 }
5439
5440 static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
5441 int r = 0, q = 0;
5442
5443 assert(u);
5444
5445 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5446
5447 if (uid_is_valid(uid)) {
5448 r = unit_ref_uid(u, uid, clean_ipc);
5449 if (r < 0)
5450 return r;
5451 }
5452
5453 if (gid_is_valid(gid)) {
5454 q = unit_ref_gid(u, gid, clean_ipc);
5455 if (q < 0) {
5456 if (r > 0)
5457 unit_unref_uid(u, false);
5458
5459 return q;
5460 }
5461 }
5462
5463 return r > 0 || q > 0;
5464 }
5465
5466 int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
5467 ExecContext *c;
5468 int r;
5469
5470 assert(u);
5471
5472 c = unit_get_exec_context(u);
5473
5474 r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
5475 if (r < 0)
5476 return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5477
5478 return r;
5479 }
5480
5481 void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
5482 int r;
5483
5484 assert(u);
5485
5486 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5487 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5488 * objects when no service references the UID/GID anymore. */
5489
5490 r = unit_ref_uid_gid(u, uid, gid);
5491 if (r > 0)
5492 unit_add_to_dbus_queue(u);
5493 }
5494
5495 int unit_acquire_invocation_id(Unit *u) {
5496 sd_id128_t id;
5497 int r;
5498
5499 assert(u);
5500
5501 r = sd_id128_randomize(&id);
5502 if (r < 0)
5503 return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
5504
5505 r = unit_set_invocation_id(u, id);
5506 if (r < 0)
5507 return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
5508
5509 unit_add_to_dbus_queue(u);
5510 return 0;
5511 }
5512
5513 int unit_set_exec_params(Unit *u, ExecParameters *p) {
5514 int r;
5515
5516 assert(u);
5517 assert(p);
5518
5519 /* Copy parameters from manager */
5520 r = manager_get_effective_environment(u->manager, &p->environment);
5521 if (r < 0)
5522 return r;
5523
5524 p->confirm_spawn = manager_get_confirm_spawn(u->manager);
5525 p->cgroup_supported = u->manager->cgroup_supported;
5526 p->prefix = u->manager->prefix;
5527 SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
5528
5529 /* Copy parameters from unit */
5530 p->cgroup_path = u->cgroup_path;
5531 SET_FLAG(p->flags, EXEC_CGROUP_DELEGATE, unit_cgroup_delegate(u));
5532
5533 p->received_credentials = u->manager->received_credentials;
5534
5535 return 0;
5536 }
5537
5538 int unit_fork_helper_process(Unit *u, const char *name, pid_t *ret) {
5539 int r;
5540
5541 assert(u);
5542 assert(ret);
5543
5544 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5545 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5546
5547 (void) unit_realize_cgroup(u);
5548
5549 r = safe_fork(name, FORK_REOPEN_LOG, ret);
5550 if (r != 0)
5551 return r;
5552
5553 (void) default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
5554 (void) ignore_signals(SIGPIPE, -1);
5555
5556 (void) prctl(PR_SET_PDEATHSIG, SIGTERM);
5557
5558 if (u->cgroup_path) {
5559 r = cg_attach_everywhere(u->manager->cgroup_supported, u->cgroup_path, 0, NULL, NULL);
5560 if (r < 0) {
5561 log_unit_error_errno(u, r, "Failed to join unit cgroup %s: %m", u->cgroup_path);
5562 _exit(EXIT_CGROUP);
5563 }
5564 }
5565
5566 return 0;
5567 }
5568
5569 int unit_fork_and_watch_rm_rf(Unit *u, char **paths, pid_t *ret_pid) {
5570 pid_t pid;
5571 int r;
5572
5573 assert(u);
5574 assert(ret_pid);
5575
5576 r = unit_fork_helper_process(u, "(sd-rmrf)", &pid);
5577 if (r < 0)
5578 return r;
5579 if (r == 0) {
5580 int ret = EXIT_SUCCESS;
5581 char **i;
5582
5583 STRV_FOREACH(i, paths) {
5584 r = rm_rf(*i, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
5585 if (r < 0) {
5586 log_error_errno(r, "Failed to remove '%s': %m", *i);
5587 ret = EXIT_FAILURE;
5588 }
5589 }
5590
5591 _exit(ret);
5592 }
5593
5594 r = unit_watch_pid(u, pid, true);
5595 if (r < 0)
5596 return r;
5597
5598 *ret_pid = pid;
5599 return 0;
5600 }
5601
5602 static void unit_update_dependency_mask(Unit *u, UnitDependency d, Unit *other, UnitDependencyInfo di) {
5603 assert(u);
5604 assert(d >= 0);
5605 assert(d < _UNIT_DEPENDENCY_MAX);
5606 assert(other);
5607
5608 if (di.origin_mask == 0 && di.destination_mask == 0) {
5609 /* No bit set anymore, let's drop the whole entry */
5610 assert_se(hashmap_remove(u->dependencies[d], other));
5611 log_unit_debug(u, "lost dependency %s=%s", unit_dependency_to_string(d), other->id);
5612 } else
5613 /* Mask was reduced, let's update the entry */
5614 assert_se(hashmap_update(u->dependencies[d], other, di.data) == 0);
5615 }
5616
5617 void unit_remove_dependencies(Unit *u, UnitDependencyMask mask) {
5618 assert(u);
5619
5620 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5621
5622 if (mask == 0)
5623 return;
5624
5625 for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
5626 bool done;
5627
5628 do {
5629 UnitDependencyInfo di;
5630 Unit *other;
5631
5632 done = true;
5633
5634 HASHMAP_FOREACH_KEY(di.data, other, u->dependencies[d]) {
5635 if (FLAGS_SET(~mask, di.origin_mask))
5636 continue;
5637 di.origin_mask &= ~mask;
5638 unit_update_dependency_mask(u, d, other, di);
5639
5640 /* We updated the dependency from our unit to the other unit now. But most dependencies
5641 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
5642 * all dependency types on the other unit and delete all those which point to us and
5643 * have the right mask set. */
5644
5645 for (UnitDependency q = 0; q < _UNIT_DEPENDENCY_MAX; q++) {
5646 UnitDependencyInfo dj;
5647
5648 dj.data = hashmap_get(other->dependencies[q], u);
5649 if (FLAGS_SET(~mask, dj.destination_mask))
5650 continue;
5651 dj.destination_mask &= ~mask;
5652
5653 unit_update_dependency_mask(other, q, u, dj);
5654 }
5655
5656 unit_add_to_gc_queue(other);
5657
5658 done = false;
5659 break;
5660 }
5661
5662 } while (!done);
5663 }
5664 }
5665
5666 static int unit_get_invocation_path(Unit *u, char **ret) {
5667 char *p;
5668 int r;
5669
5670 assert(u);
5671 assert(ret);
5672
5673 if (MANAGER_IS_SYSTEM(u->manager))
5674 p = strjoin("/run/systemd/units/invocation:", u->id);
5675 else {
5676 _cleanup_free_ char *user_path = NULL;
5677 r = xdg_user_runtime_dir(&user_path, "/systemd/units/invocation:");
5678 if (r < 0)
5679 return r;
5680 p = strjoin(user_path, u->id);
5681 }
5682
5683 if (!p)
5684 return -ENOMEM;
5685
5686 *ret = p;
5687 return 0;
5688 }
5689
5690 static int unit_export_invocation_id(Unit *u) {
5691 _cleanup_free_ char *p = NULL;
5692 int r;
5693
5694 assert(u);
5695
5696 if (u->exported_invocation_id)
5697 return 0;
5698
5699 if (sd_id128_is_null(u->invocation_id))
5700 return 0;
5701
5702 r = unit_get_invocation_path(u, &p);
5703 if (r < 0)
5704 return log_unit_debug_errno(u, r, "Failed to get invocation path: %m");
5705
5706 r = symlink_atomic_label(u->invocation_id_string, p);
5707 if (r < 0)
5708 return log_unit_debug_errno(u, r, "Failed to create invocation ID symlink %s: %m", p);
5709
5710 u->exported_invocation_id = true;
5711 return 0;
5712 }
5713
5714 static int unit_export_log_level_max(Unit *u, const ExecContext *c) {
5715 const char *p;
5716 char buf[2];
5717 int r;
5718
5719 assert(u);
5720 assert(c);
5721
5722 if (u->exported_log_level_max)
5723 return 0;
5724
5725 if (c->log_level_max < 0)
5726 return 0;
5727
5728 assert(c->log_level_max <= 7);
5729
5730 buf[0] = '0' + c->log_level_max;
5731 buf[1] = 0;
5732
5733 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5734 r = symlink_atomic(buf, p);
5735 if (r < 0)
5736 return log_unit_debug_errno(u, r, "Failed to create maximum log level symlink %s: %m", p);
5737
5738 u->exported_log_level_max = true;
5739 return 0;
5740 }
5741
5742 static int unit_export_log_extra_fields(Unit *u, const ExecContext *c) {
5743 _cleanup_close_ int fd = -1;
5744 struct iovec *iovec;
5745 const char *p;
5746 char *pattern;
5747 le64_t *sizes;
5748 ssize_t n;
5749 int r;
5750
5751 if (u->exported_log_extra_fields)
5752 return 0;
5753
5754 if (c->n_log_extra_fields <= 0)
5755 return 0;
5756
5757 sizes = newa(le64_t, c->n_log_extra_fields);
5758 iovec = newa(struct iovec, c->n_log_extra_fields * 2);
5759
5760 for (size_t i = 0; i < c->n_log_extra_fields; i++) {
5761 sizes[i] = htole64(c->log_extra_fields[i].iov_len);
5762
5763 iovec[i*2] = IOVEC_MAKE(sizes + i, sizeof(le64_t));
5764 iovec[i*2+1] = c->log_extra_fields[i];
5765 }
5766
5767 p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
5768 pattern = strjoina(p, ".XXXXXX");
5769
5770 fd = mkostemp_safe(pattern);
5771 if (fd < 0)
5772 return log_unit_debug_errno(u, fd, "Failed to create extra fields file %s: %m", p);
5773
5774 n = writev(fd, iovec, c->n_log_extra_fields*2);
5775 if (n < 0) {
5776 r = log_unit_debug_errno(u, errno, "Failed to write extra fields: %m");
5777 goto fail;
5778 }
5779
5780 (void) fchmod(fd, 0644);
5781
5782 if (rename(pattern, p) < 0) {
5783 r = log_unit_debug_errno(u, errno, "Failed to rename extra fields file: %m");
5784 goto fail;
5785 }
5786
5787 u->exported_log_extra_fields = true;
5788 return 0;
5789
5790 fail:
5791 (void) unlink(pattern);
5792 return r;
5793 }
5794
5795 static int unit_export_log_ratelimit_interval(Unit *u, const ExecContext *c) {
5796 _cleanup_free_ char *buf = NULL;
5797 const char *p;
5798 int r;
5799
5800 assert(u);
5801 assert(c);
5802
5803 if (u->exported_log_ratelimit_interval)
5804 return 0;
5805
5806 if (c->log_ratelimit_interval_usec == 0)
5807 return 0;
5808
5809 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5810
5811 if (asprintf(&buf, "%" PRIu64, c->log_ratelimit_interval_usec) < 0)
5812 return log_oom();
5813
5814 r = symlink_atomic(buf, p);
5815 if (r < 0)
5816 return log_unit_debug_errno(u, r, "Failed to create log rate limit interval symlink %s: %m", p);
5817
5818 u->exported_log_ratelimit_interval = true;
5819 return 0;
5820 }
5821
5822 static int unit_export_log_ratelimit_burst(Unit *u, const ExecContext *c) {
5823 _cleanup_free_ char *buf = NULL;
5824 const char *p;
5825 int r;
5826
5827 assert(u);
5828 assert(c);
5829
5830 if (u->exported_log_ratelimit_burst)
5831 return 0;
5832
5833 if (c->log_ratelimit_burst == 0)
5834 return 0;
5835
5836 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5837
5838 if (asprintf(&buf, "%u", c->log_ratelimit_burst) < 0)
5839 return log_oom();
5840
5841 r = symlink_atomic(buf, p);
5842 if (r < 0)
5843 return log_unit_debug_errno(u, r, "Failed to create log rate limit burst symlink %s: %m", p);
5844
5845 u->exported_log_ratelimit_burst = true;
5846 return 0;
5847 }
5848
5849 void unit_export_state_files(Unit *u) {
5850 const ExecContext *c;
5851
5852 assert(u);
5853
5854 if (!u->id)
5855 return;
5856
5857 if (MANAGER_IS_TEST_RUN(u->manager))
5858 return;
5859
5860 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5861 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5862 * the IPC system itself and PID 1 also log to the journal.
5863 *
5864 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5865 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5866 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5867 * namespace at least.
5868 *
5869 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5870 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5871 * them with one. */
5872
5873 (void) unit_export_invocation_id(u);
5874
5875 if (!MANAGER_IS_SYSTEM(u->manager))
5876 return;
5877
5878 c = unit_get_exec_context(u);
5879 if (c) {
5880 (void) unit_export_log_level_max(u, c);
5881 (void) unit_export_log_extra_fields(u, c);
5882 (void) unit_export_log_ratelimit_interval(u, c);
5883 (void) unit_export_log_ratelimit_burst(u, c);
5884 }
5885 }
5886
5887 void unit_unlink_state_files(Unit *u) {
5888 const char *p;
5889
5890 assert(u);
5891
5892 if (!u->id)
5893 return;
5894
5895 /* Undoes the effect of unit_export_state() */
5896
5897 if (u->exported_invocation_id) {
5898 _cleanup_free_ char *invocation_path = NULL;
5899 int r = unit_get_invocation_path(u, &invocation_path);
5900 if (r >= 0) {
5901 (void) unlink(invocation_path);
5902 u->exported_invocation_id = false;
5903 }
5904 }
5905
5906 if (!MANAGER_IS_SYSTEM(u->manager))
5907 return;
5908
5909 if (u->exported_log_level_max) {
5910 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5911 (void) unlink(p);
5912
5913 u->exported_log_level_max = false;
5914 }
5915
5916 if (u->exported_log_extra_fields) {
5917 p = strjoina("/run/systemd/units/extra-fields:", u->id);
5918 (void) unlink(p);
5919
5920 u->exported_log_extra_fields = false;
5921 }
5922
5923 if (u->exported_log_ratelimit_interval) {
5924 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5925 (void) unlink(p);
5926
5927 u->exported_log_ratelimit_interval = false;
5928 }
5929
5930 if (u->exported_log_ratelimit_burst) {
5931 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5932 (void) unlink(p);
5933
5934 u->exported_log_ratelimit_burst = false;
5935 }
5936 }
5937
5938 int unit_prepare_exec(Unit *u) {
5939 int r;
5940
5941 assert(u);
5942
5943 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5944 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5945 r = bpf_firewall_load_custom(u);
5946 if (r < 0)
5947 return r;
5948
5949 /* Prepares everything so that we can fork of a process for this unit */
5950
5951 (void) unit_realize_cgroup(u);
5952
5953 if (u->reset_accounting) {
5954 (void) unit_reset_accounting(u);
5955 u->reset_accounting = false;
5956 }
5957
5958 unit_export_state_files(u);
5959
5960 r = unit_setup_exec_runtime(u);
5961 if (r < 0)
5962 return r;
5963
5964 r = unit_setup_dynamic_creds(u);
5965 if (r < 0)
5966 return r;
5967
5968 return 0;
5969 }
5970
5971 static bool ignore_leftover_process(const char *comm) {
5972 return comm && comm[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5973 }
5974
5975 int unit_log_leftover_process_start(pid_t pid, int sig, void *userdata) {
5976 _cleanup_free_ char *comm = NULL;
5977
5978 (void) get_process_comm(pid, &comm);
5979
5980 if (ignore_leftover_process(comm))
5981 return 0;
5982
5983 /* During start we print a warning */
5984
5985 log_unit_warning(userdata,
5986 "Found left-over process " PID_FMT " (%s) in control group while starting unit. Ignoring.\n"
5987 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5988 pid, strna(comm));
5989
5990 return 1;
5991 }
5992
5993 int unit_log_leftover_process_stop(pid_t pid, int sig, void *userdata) {
5994 _cleanup_free_ char *comm = NULL;
5995
5996 (void) get_process_comm(pid, &comm);
5997
5998 if (ignore_leftover_process(comm))
5999 return 0;
6000
6001 /* During stop we only print an informational message */
6002
6003 log_unit_info(userdata,
6004 "Unit process " PID_FMT " (%s) remains running after unit stopped.",
6005 pid, strna(comm));
6006
6007 return 1;
6008 }
6009
6010 int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func) {
6011 assert(u);
6012
6013 (void) unit_pick_cgroup_path(u);
6014
6015 if (!u->cgroup_path)
6016 return 0;
6017
6018 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, 0, 0, NULL, log_func, u);
6019 }
6020
6021 bool unit_needs_console(Unit *u) {
6022 ExecContext *ec;
6023 UnitActiveState state;
6024
6025 assert(u);
6026
6027 state = unit_active_state(u);
6028
6029 if (UNIT_IS_INACTIVE_OR_FAILED(state))
6030 return false;
6031
6032 if (UNIT_VTABLE(u)->needs_console)
6033 return UNIT_VTABLE(u)->needs_console(u);
6034
6035 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
6036 ec = unit_get_exec_context(u);
6037 if (!ec)
6038 return false;
6039
6040 return exec_context_may_touch_console(ec);
6041 }
6042
6043 const char *unit_label_path(const Unit *u) {
6044 const char *p;
6045
6046 assert(u);
6047
6048 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
6049 * when validating access checks. */
6050
6051 p = u->source_path ?: u->fragment_path;
6052 if (!p)
6053 return NULL;
6054
6055 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
6056 if (null_or_empty_path(p) > 0)
6057 return NULL;
6058
6059 return p;
6060 }
6061
6062 int unit_pid_attachable(Unit *u, pid_t pid, sd_bus_error *error) {
6063 int r;
6064
6065 assert(u);
6066
6067 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
6068 * and not a kernel thread either */
6069
6070 /* First, a simple range check */
6071 if (!pid_is_valid(pid))
6072 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process identifier " PID_FMT " is not valid.", pid);
6073
6074 /* Some extra safety check */
6075 if (pid == 1 || pid == getpid_cached())
6076 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a manager process, refusing.", pid);
6077
6078 /* Don't even begin to bother with kernel threads */
6079 r = is_kernel_thread(pid);
6080 if (r == -ESRCH)
6081 return sd_bus_error_setf(error, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN, "Process with ID " PID_FMT " does not exist.", pid);
6082 if (r < 0)
6083 return sd_bus_error_set_errnof(error, r, "Failed to determine whether process " PID_FMT " is a kernel thread: %m", pid);
6084 if (r > 0)
6085 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a kernel thread, refusing.", pid);
6086
6087 return 0;
6088 }
6089
6090 void unit_log_success(Unit *u) {
6091 assert(u);
6092
6093 log_struct(LOG_INFO,
6094 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR,
6095 LOG_UNIT_ID(u),
6096 LOG_UNIT_INVOCATION_ID(u),
6097 LOG_UNIT_MESSAGE(u, "Deactivated successfully."));
6098 }
6099
6100 void unit_log_failure(Unit *u, const char *result) {
6101 assert(u);
6102 assert(result);
6103
6104 log_struct(LOG_WARNING,
6105 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR,
6106 LOG_UNIT_ID(u),
6107 LOG_UNIT_INVOCATION_ID(u),
6108 LOG_UNIT_MESSAGE(u, "Failed with result '%s'.", result),
6109 "UNIT_RESULT=%s", result);
6110 }
6111
6112 void unit_log_skip(Unit *u, const char *result) {
6113 assert(u);
6114 assert(result);
6115
6116 log_struct(LOG_INFO,
6117 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR,
6118 LOG_UNIT_ID(u),
6119 LOG_UNIT_INVOCATION_ID(u),
6120 LOG_UNIT_MESSAGE(u, "Skipped due to '%s'.", result),
6121 "UNIT_RESULT=%s", result);
6122 }
6123
6124 void unit_log_process_exit(
6125 Unit *u,
6126 const char *kind,
6127 const char *command,
6128 bool success,
6129 int code,
6130 int status) {
6131
6132 int level;
6133
6134 assert(u);
6135 assert(kind);
6136
6137 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
6138 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
6139 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
6140 * WARNING. */
6141 if (success)
6142 level = LOG_DEBUG;
6143 else if (code == CLD_EXITED)
6144 level = LOG_NOTICE;
6145 else
6146 level = LOG_WARNING;
6147
6148 log_struct(level,
6149 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR,
6150 LOG_UNIT_MESSAGE(u, "%s exited, code=%s, status=%i/%s",
6151 kind,
6152 sigchld_code_to_string(code), status,
6153 strna(code == CLD_EXITED
6154 ? exit_status_to_string(status, EXIT_STATUS_FULL)
6155 : signal_to_string(status))),
6156 "EXIT_CODE=%s", sigchld_code_to_string(code),
6157 "EXIT_STATUS=%i", status,
6158 "COMMAND=%s", strna(command),
6159 LOG_UNIT_ID(u),
6160 LOG_UNIT_INVOCATION_ID(u));
6161 }
6162
6163 int unit_exit_status(Unit *u) {
6164 assert(u);
6165
6166 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
6167 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
6168 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
6169 * service process has exited abnormally (signal/coredump). */
6170
6171 if (!UNIT_VTABLE(u)->exit_status)
6172 return -EOPNOTSUPP;
6173
6174 return UNIT_VTABLE(u)->exit_status(u);
6175 }
6176
6177 int unit_failure_action_exit_status(Unit *u) {
6178 int r;
6179
6180 assert(u);
6181
6182 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
6183
6184 if (u->failure_action_exit_status >= 0)
6185 return u->failure_action_exit_status;
6186
6187 r = unit_exit_status(u);
6188 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6189 return 255;
6190
6191 return r;
6192 }
6193
6194 int unit_success_action_exit_status(Unit *u) {
6195 int r;
6196
6197 assert(u);
6198
6199 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
6200
6201 if (u->success_action_exit_status >= 0)
6202 return u->success_action_exit_status;
6203
6204 r = unit_exit_status(u);
6205 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6206 return 255;
6207
6208 return r;
6209 }
6210
6211 int unit_test_trigger_loaded(Unit *u) {
6212 Unit *trigger;
6213
6214 /* Tests whether the unit to trigger is loaded */
6215
6216 trigger = UNIT_TRIGGER(u);
6217 if (!trigger)
6218 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6219 "Refusing to start, no unit to trigger.");
6220 if (trigger->load_state != UNIT_LOADED)
6221 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6222 "Refusing to start, unit %s to trigger not loaded.", trigger->id);
6223
6224 return 0;
6225 }
6226
6227 void unit_destroy_runtime_data(Unit *u, const ExecContext *context) {
6228 assert(u);
6229 assert(context);
6230
6231 if (context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO ||
6232 (context->runtime_directory_preserve_mode == EXEC_PRESERVE_RESTART && !unit_will_restart(u)))
6233 exec_context_destroy_runtime_directory(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
6234
6235 exec_context_destroy_credentials(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME], u->id);
6236 }
6237
6238 int unit_clean(Unit *u, ExecCleanMask mask) {
6239 UnitActiveState state;
6240
6241 assert(u);
6242
6243 /* Special return values:
6244 *
6245 * -EOPNOTSUPP → cleaning not supported for this unit type
6246 * -EUNATCH → cleaning not defined for this resource type
6247 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6248 * a job queued or similar
6249 */
6250
6251 if (!UNIT_VTABLE(u)->clean)
6252 return -EOPNOTSUPP;
6253
6254 if (mask == 0)
6255 return -EUNATCH;
6256
6257 if (u->load_state != UNIT_LOADED)
6258 return -EBUSY;
6259
6260 if (u->job)
6261 return -EBUSY;
6262
6263 state = unit_active_state(u);
6264 if (!IN_SET(state, UNIT_INACTIVE))
6265 return -EBUSY;
6266
6267 return UNIT_VTABLE(u)->clean(u, mask);
6268 }
6269
6270 int unit_can_clean(Unit *u, ExecCleanMask *ret) {
6271 assert(u);
6272
6273 if (!UNIT_VTABLE(u)->clean ||
6274 u->load_state != UNIT_LOADED) {
6275 *ret = 0;
6276 return 0;
6277 }
6278
6279 /* When the clean() method is set, can_clean() really should be set too */
6280 assert(UNIT_VTABLE(u)->can_clean);
6281
6282 return UNIT_VTABLE(u)->can_clean(u, ret);
6283 }
6284
6285 bool unit_can_freeze(Unit *u) {
6286 assert(u);
6287
6288 if (UNIT_VTABLE(u)->can_freeze)
6289 return UNIT_VTABLE(u)->can_freeze(u);
6290
6291 return UNIT_VTABLE(u)->freeze;
6292 }
6293
6294 void unit_frozen(Unit *u) {
6295 assert(u);
6296
6297 u->freezer_state = FREEZER_FROZEN;
6298
6299 bus_unit_send_pending_freezer_message(u);
6300 }
6301
6302 void unit_thawed(Unit *u) {
6303 assert(u);
6304
6305 u->freezer_state = FREEZER_RUNNING;
6306
6307 bus_unit_send_pending_freezer_message(u);
6308 }
6309
6310 static int unit_freezer_action(Unit *u, FreezerAction action) {
6311 UnitActiveState s;
6312 int (*method)(Unit*);
6313 int r;
6314
6315 assert(u);
6316 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
6317
6318 method = action == FREEZER_FREEZE ? UNIT_VTABLE(u)->freeze : UNIT_VTABLE(u)->thaw;
6319 if (!method || !cg_freezer_supported())
6320 return -EOPNOTSUPP;
6321
6322 if (u->job)
6323 return -EBUSY;
6324
6325 if (u->load_state != UNIT_LOADED)
6326 return -EHOSTDOWN;
6327
6328 s = unit_active_state(u);
6329 if (s != UNIT_ACTIVE)
6330 return -EHOSTDOWN;
6331
6332 if (IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING))
6333 return -EALREADY;
6334
6335 r = method(u);
6336 if (r <= 0)
6337 return r;
6338
6339 return 1;
6340 }
6341
6342 int unit_freeze(Unit *u) {
6343 return unit_freezer_action(u, FREEZER_FREEZE);
6344 }
6345
6346 int unit_thaw(Unit *u) {
6347 return unit_freezer_action(u, FREEZER_THAW);
6348 }
6349
6350 /* Wrappers around low-level cgroup freezer operations common for service and scope units */
6351 int unit_freeze_vtable_common(Unit *u) {
6352 return unit_cgroup_freezer_action(u, FREEZER_FREEZE);
6353 }
6354
6355 int unit_thaw_vtable_common(Unit *u) {
6356 return unit_cgroup_freezer_action(u, FREEZER_THAW);
6357 }
6358
6359 static const char* const collect_mode_table[_COLLECT_MODE_MAX] = {
6360 [COLLECT_INACTIVE] = "inactive",
6361 [COLLECT_INACTIVE_OR_FAILED] = "inactive-or-failed",
6362 };
6363
6364 DEFINE_STRING_TABLE_LOOKUP(collect_mode, CollectMode);