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