]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/unit.c
core: also log about left-over processes during unit stop
[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 _cleanup_strv_free_ char **env = NULL;
1709 int r;
1710
1711 assert(u);
1712
1713 dual_timestamp_get(&u->condition_timestamp);
1714
1715 r = manager_get_effective_environment(u->manager, &env);
1716 if (r < 0) {
1717 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1718 u->condition_result = CONDITION_ERROR;
1719 } else
1720 u->condition_result = condition_test_list(
1721 u->conditions,
1722 env,
1723 condition_type_to_string,
1724 log_unit_internal,
1725 u);
1726
1727 unit_add_to_dbus_queue(u);
1728 return u->condition_result;
1729 }
1730
1731 static bool unit_test_assert(Unit *u) {
1732 _cleanup_strv_free_ char **env = NULL;
1733 int r;
1734
1735 assert(u);
1736
1737 dual_timestamp_get(&u->assert_timestamp);
1738
1739 r = manager_get_effective_environment(u->manager, &env);
1740 if (r < 0) {
1741 log_unit_error_errno(u, r, "Failed to determine effective environment: %m");
1742 u->assert_result = CONDITION_ERROR;
1743 } else
1744 u->assert_result = condition_test_list(
1745 u->asserts,
1746 env,
1747 assert_type_to_string,
1748 log_unit_internal,
1749 u);
1750
1751 unit_add_to_dbus_queue(u);
1752 return u->assert_result;
1753 }
1754
1755 void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *unit_status_msg_format) {
1756 const char *d;
1757
1758 d = unit_status_string(u);
1759 if (log_get_show_color())
1760 d = strjoina(ANSI_HIGHLIGHT, d, ANSI_NORMAL);
1761
1762 DISABLE_WARNING_FORMAT_NONLITERAL;
1763 manager_status_printf(u->manager, status_type, status, unit_status_msg_format, d);
1764 REENABLE_WARNING;
1765 }
1766
1767 int unit_test_start_limit(Unit *u) {
1768 const char *reason;
1769
1770 assert(u);
1771
1772 if (ratelimit_below(&u->start_ratelimit)) {
1773 u->start_limit_hit = false;
1774 return 0;
1775 }
1776
1777 log_unit_warning(u, "Start request repeated too quickly.");
1778 u->start_limit_hit = true;
1779
1780 reason = strjoina("unit ", u->id, " failed");
1781
1782 emergency_action(u->manager, u->start_limit_action,
1783 EMERGENCY_ACTION_IS_WATCHDOG|EMERGENCY_ACTION_WARN,
1784 u->reboot_arg, -1, reason);
1785
1786 return -ECANCELED;
1787 }
1788
1789 bool unit_shall_confirm_spawn(Unit *u) {
1790 assert(u);
1791
1792 if (manager_is_confirm_spawn_disabled(u->manager))
1793 return false;
1794
1795 /* For some reasons units remaining in the same process group
1796 * as PID 1 fail to acquire the console even if it's not used
1797 * by any process. So skip the confirmation question for them. */
1798 return !unit_get_exec_context(u)->same_pgrp;
1799 }
1800
1801 static bool unit_verify_deps(Unit *u) {
1802 Unit *other;
1803 Iterator j;
1804 void *v;
1805
1806 assert(u);
1807
1808 /* Checks whether all BindsTo= dependencies of this unit are fulfilled — if they are also combined with
1809 * After=. We do not check Requires= or Requisite= here as they only should have an effect on the job
1810 * processing, but do not have any effect afterwards. We don't check BindsTo= dependencies that are not used in
1811 * conjunction with After= as for them any such check would make things entirely racy. */
1812
1813 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO], j) {
1814
1815 if (!hashmap_contains(u->dependencies[UNIT_AFTER], other))
1816 continue;
1817
1818 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
1819 log_unit_notice(u, "Bound to unit %s, but unit isn't active.", other->id);
1820 return false;
1821 }
1822 }
1823
1824 return true;
1825 }
1826
1827 /* Errors that aren't really errors:
1828 * -EALREADY: Unit is already started.
1829 * -ECOMM: Condition failed
1830 * -EAGAIN: An operation is already in progress. Retry later.
1831 *
1832 * Errors that are real errors:
1833 * -EBADR: This unit type does not support starting.
1834 * -ECANCELED: Start limit hit, too many requests for now
1835 * -EPROTO: Assert failed
1836 * -EINVAL: Unit not loaded
1837 * -EOPNOTSUPP: Unit type not supported
1838 * -ENOLINK: The necessary dependencies are not fulfilled.
1839 * -ESTALE: This unit has been started before and can't be started a second time
1840 * -ENOENT: This is a triggering unit and unit to trigger is not loaded
1841 */
1842 int unit_start(Unit *u) {
1843 UnitActiveState state;
1844 Unit *following;
1845
1846 assert(u);
1847
1848 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1849 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1850 * waiting is finished. */
1851 state = unit_active_state(u);
1852 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1853 return -EALREADY;
1854 if (state == UNIT_MAINTENANCE)
1855 return -EAGAIN;
1856
1857 /* Units that aren't loaded cannot be started */
1858 if (u->load_state != UNIT_LOADED)
1859 return -EINVAL;
1860
1861 /* Refuse starting scope units more than once */
1862 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_enter_timestamp))
1863 return -ESTALE;
1864
1865 /* If the conditions failed, don't do anything at all. If we already are activating this call might
1866 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1867 * recheck the condition in that case. */
1868 if (state != UNIT_ACTIVATING &&
1869 !unit_test_condition(u))
1870 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(ECOMM), "Starting requested but condition failed. Not starting unit.");
1871
1872 /* If the asserts failed, fail the entire job */
1873 if (state != UNIT_ACTIVATING &&
1874 !unit_test_assert(u))
1875 return log_unit_notice_errno(u, SYNTHETIC_ERRNO(EPROTO), "Starting requested but asserts failed.");
1876
1877 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1878 * condition checks, so that we rather return condition check errors (which are usually not
1879 * considered a true failure) than "not supported" errors (which are considered a failure).
1880 */
1881 if (!unit_type_supported(u->type))
1882 return -EOPNOTSUPP;
1883
1884 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1885 * should have taken care of this already, but let's check this here again. After all, our
1886 * dependencies might not be in effect anymore, due to a reload or due to a failed condition. */
1887 if (!unit_verify_deps(u))
1888 return -ENOLINK;
1889
1890 /* Forward to the main object, if we aren't it. */
1891 following = unit_following(u);
1892 if (following) {
1893 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
1894 return unit_start(following);
1895 }
1896
1897 /* If it is stopped, but we cannot start it, then fail */
1898 if (!UNIT_VTABLE(u)->start)
1899 return -EBADR;
1900
1901 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1902 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1903 * waits for a holdoff timer to elapse before it will start again. */
1904
1905 unit_add_to_dbus_queue(u);
1906 unit_cgroup_freezer_action(u, FREEZER_THAW);
1907
1908 return UNIT_VTABLE(u)->start(u);
1909 }
1910
1911 bool unit_can_start(Unit *u) {
1912 assert(u);
1913
1914 if (u->load_state != UNIT_LOADED)
1915 return false;
1916
1917 if (!unit_type_supported(u->type))
1918 return false;
1919
1920 /* Scope units may be started only once */
1921 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_exit_timestamp))
1922 return false;
1923
1924 return !!UNIT_VTABLE(u)->start;
1925 }
1926
1927 bool unit_can_isolate(Unit *u) {
1928 assert(u);
1929
1930 return unit_can_start(u) &&
1931 u->allow_isolate;
1932 }
1933
1934 /* Errors:
1935 * -EBADR: This unit type does not support stopping.
1936 * -EALREADY: Unit is already stopped.
1937 * -EAGAIN: An operation is already in progress. Retry later.
1938 */
1939 int unit_stop(Unit *u) {
1940 UnitActiveState state;
1941 Unit *following;
1942
1943 assert(u);
1944
1945 state = unit_active_state(u);
1946 if (UNIT_IS_INACTIVE_OR_FAILED(state))
1947 return -EALREADY;
1948
1949 following = unit_following(u);
1950 if (following) {
1951 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
1952 return unit_stop(following);
1953 }
1954
1955 if (!UNIT_VTABLE(u)->stop)
1956 return -EBADR;
1957
1958 unit_add_to_dbus_queue(u);
1959 unit_cgroup_freezer_action(u, FREEZER_THAW);
1960
1961 return UNIT_VTABLE(u)->stop(u);
1962 }
1963
1964 bool unit_can_stop(Unit *u) {
1965 assert(u);
1966
1967 if (!unit_type_supported(u->type))
1968 return false;
1969
1970 if (u->perpetual)
1971 return false;
1972
1973 return !!UNIT_VTABLE(u)->stop;
1974 }
1975
1976 /* Errors:
1977 * -EBADR: This unit type does not support reloading.
1978 * -ENOEXEC: Unit is not started.
1979 * -EAGAIN: An operation is already in progress. Retry later.
1980 */
1981 int unit_reload(Unit *u) {
1982 UnitActiveState state;
1983 Unit *following;
1984
1985 assert(u);
1986
1987 if (u->load_state != UNIT_LOADED)
1988 return -EINVAL;
1989
1990 if (!unit_can_reload(u))
1991 return -EBADR;
1992
1993 state = unit_active_state(u);
1994 if (state == UNIT_RELOADING)
1995 return -EAGAIN;
1996
1997 if (state != UNIT_ACTIVE) {
1998 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
1999 return -ENOEXEC;
2000 }
2001
2002 following = unit_following(u);
2003 if (following) {
2004 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
2005 return unit_reload(following);
2006 }
2007
2008 unit_add_to_dbus_queue(u);
2009
2010 if (!UNIT_VTABLE(u)->reload) {
2011 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
2012 unit_notify(u, unit_active_state(u), unit_active_state(u), 0);
2013 return 0;
2014 }
2015
2016 unit_cgroup_freezer_action(u, FREEZER_THAW);
2017
2018 return UNIT_VTABLE(u)->reload(u);
2019 }
2020
2021 bool unit_can_reload(Unit *u) {
2022 assert(u);
2023
2024 if (UNIT_VTABLE(u)->can_reload)
2025 return UNIT_VTABLE(u)->can_reload(u);
2026
2027 if (!hashmap_isempty(u->dependencies[UNIT_PROPAGATES_RELOAD_TO]))
2028 return true;
2029
2030 return UNIT_VTABLE(u)->reload;
2031 }
2032
2033 bool unit_is_unneeded(Unit *u) {
2034 static const UnitDependency deps[] = {
2035 UNIT_REQUIRED_BY,
2036 UNIT_REQUISITE_OF,
2037 UNIT_WANTED_BY,
2038 UNIT_BOUND_BY,
2039 };
2040 size_t j;
2041
2042 assert(u);
2043
2044 if (!u->stop_when_unneeded)
2045 return false;
2046
2047 /* Don't clean up while the unit is transitioning or is even inactive. */
2048 if (!UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(u)))
2049 return false;
2050 if (u->job)
2051 return false;
2052
2053 for (j = 0; j < ELEMENTSOF(deps); j++) {
2054 Unit *other;
2055 Iterator i;
2056 void *v;
2057
2058 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
2059 * restart, then don't clean this one up. */
2060
2061 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]], i) {
2062 if (other->job)
2063 return false;
2064
2065 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2066 return false;
2067
2068 if (unit_will_restart(other))
2069 return false;
2070 }
2071 }
2072
2073 return true;
2074 }
2075
2076 static void check_unneeded_dependencies(Unit *u) {
2077
2078 static const UnitDependency deps[] = {
2079 UNIT_REQUIRES,
2080 UNIT_REQUISITE,
2081 UNIT_WANTS,
2082 UNIT_BINDS_TO,
2083 };
2084 size_t j;
2085
2086 assert(u);
2087
2088 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2089
2090 for (j = 0; j < ELEMENTSOF(deps); j++) {
2091 Unit *other;
2092 Iterator i;
2093 void *v;
2094
2095 HASHMAP_FOREACH_KEY(v, other, u->dependencies[deps[j]], i)
2096 unit_submit_to_stop_when_unneeded_queue(other);
2097 }
2098 }
2099
2100 static void unit_check_binds_to(Unit *u) {
2101 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2102 bool stop = false;
2103 Unit *other;
2104 Iterator i;
2105 void *v;
2106 int r;
2107
2108 assert(u);
2109
2110 if (u->job)
2111 return;
2112
2113 if (unit_active_state(u) != UNIT_ACTIVE)
2114 return;
2115
2116 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO], i) {
2117 if (other->job)
2118 continue;
2119
2120 if (!other->coldplugged)
2121 /* We might yet create a job for the other unit… */
2122 continue;
2123
2124 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2125 continue;
2126
2127 stop = true;
2128 break;
2129 }
2130
2131 if (!stop)
2132 return;
2133
2134 /* If stopping a unit fails continuously we might enter a stop
2135 * loop here, hence stop acting on the service being
2136 * unnecessary after a while. */
2137 if (!ratelimit_below(&u->auto_stop_ratelimit)) {
2138 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
2139 return;
2140 }
2141
2142 assert(other);
2143 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
2144
2145 /* A unit we need to run is gone. Sniff. Let's stop this. */
2146 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, NULL, &error, NULL);
2147 if (r < 0)
2148 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
2149 }
2150
2151 static void retroactively_start_dependencies(Unit *u) {
2152 Iterator i;
2153 Unit *other;
2154 void *v;
2155
2156 assert(u);
2157 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
2158
2159 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_REQUIRES], i)
2160 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2161 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2162 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
2163
2164 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BINDS_TO], i)
2165 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2166 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2167 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL, NULL);
2168
2169 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_WANTS], i)
2170 if (!hashmap_get(u->dependencies[UNIT_AFTER], other) &&
2171 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
2172 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL, NULL);
2173
2174 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTS], i)
2175 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2176 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2177
2178 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_CONFLICTED_BY], i)
2179 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2180 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2181 }
2182
2183 static void retroactively_stop_dependencies(Unit *u) {
2184 Unit *other;
2185 Iterator i;
2186 void *v;
2187
2188 assert(u);
2189 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
2190
2191 /* Pull down units which are bound to us recursively if enabled */
2192 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_BOUND_BY], i)
2193 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
2194 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
2195 }
2196
2197 void unit_start_on_failure(Unit *u) {
2198 Unit *other;
2199 Iterator i;
2200 void *v;
2201 int r;
2202
2203 assert(u);
2204
2205 if (hashmap_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
2206 return;
2207
2208 log_unit_info(u, "Triggering OnFailure= dependencies.");
2209
2210 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_ON_FAILURE], i) {
2211 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2212
2213 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, &error, NULL);
2214 if (r < 0)
2215 log_unit_warning_errno(u, r, "Failed to enqueue OnFailure= job, ignoring: %s", bus_error_message(&error, r));
2216 }
2217 }
2218
2219 void unit_trigger_notify(Unit *u) {
2220 Unit *other;
2221 Iterator i;
2222 void *v;
2223
2224 assert(u);
2225
2226 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_TRIGGERED_BY], i)
2227 if (UNIT_VTABLE(other)->trigger_notify)
2228 UNIT_VTABLE(other)->trigger_notify(other, u);
2229 }
2230
2231 static int raise_level(int log_level, bool condition_info, bool condition_notice) {
2232 if (condition_notice && log_level > LOG_NOTICE)
2233 return LOG_NOTICE;
2234 if (condition_info && log_level > LOG_INFO)
2235 return LOG_INFO;
2236 return log_level;
2237 }
2238
2239 static int unit_log_resources(Unit *u) {
2240 struct iovec iovec[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX + _CGROUP_IO_ACCOUNTING_METRIC_MAX + 4];
2241 bool any_traffic = false, have_ip_accounting = false, any_io = false, have_io_accounting = false;
2242 _cleanup_free_ char *igress = NULL, *egress = NULL, *rr = NULL, *wr = NULL;
2243 int log_level = LOG_DEBUG; /* May be raised if resources consumed over a threshold */
2244 size_t n_message_parts = 0, n_iovec = 0;
2245 char* message_parts[1 + 2 + 2 + 1], *t;
2246 nsec_t nsec = NSEC_INFINITY;
2247 CGroupIPAccountingMetric m;
2248 size_t i;
2249 int r;
2250 const char* const ip_fields[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
2251 [CGROUP_IP_INGRESS_BYTES] = "IP_METRIC_INGRESS_BYTES",
2252 [CGROUP_IP_INGRESS_PACKETS] = "IP_METRIC_INGRESS_PACKETS",
2253 [CGROUP_IP_EGRESS_BYTES] = "IP_METRIC_EGRESS_BYTES",
2254 [CGROUP_IP_EGRESS_PACKETS] = "IP_METRIC_EGRESS_PACKETS",
2255 };
2256 const char* const io_fields[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
2257 [CGROUP_IO_READ_BYTES] = "IO_METRIC_READ_BYTES",
2258 [CGROUP_IO_WRITE_BYTES] = "IO_METRIC_WRITE_BYTES",
2259 [CGROUP_IO_READ_OPERATIONS] = "IO_METRIC_READ_OPERATIONS",
2260 [CGROUP_IO_WRITE_OPERATIONS] = "IO_METRIC_WRITE_OPERATIONS",
2261 };
2262
2263 assert(u);
2264
2265 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2266 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2267 * information and the complete data in structured fields. */
2268
2269 (void) unit_get_cpu_usage(u, &nsec);
2270 if (nsec != NSEC_INFINITY) {
2271 char buf[FORMAT_TIMESPAN_MAX] = "";
2272
2273 /* Format the CPU time for inclusion in the structured log message */
2274 if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) {
2275 r = log_oom();
2276 goto finish;
2277 }
2278 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2279
2280 /* Format the CPU time for inclusion in the human language message string */
2281 format_timespan(buf, sizeof(buf), nsec / NSEC_PER_USEC, USEC_PER_MSEC);
2282 t = strjoin("consumed ", buf, " CPU time");
2283 if (!t) {
2284 r = log_oom();
2285 goto finish;
2286 }
2287
2288 message_parts[n_message_parts++] = t;
2289
2290 log_level = raise_level(log_level,
2291 nsec > NOTICEWORTHY_CPU_NSEC,
2292 nsec > MENTIONWORTHY_CPU_NSEC);
2293 }
2294
2295 for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
2296 char buf[FORMAT_BYTES_MAX] = "";
2297 uint64_t value = UINT64_MAX;
2298
2299 assert(io_fields[k]);
2300
2301 (void) unit_get_io_accounting(u, k, k > 0, &value);
2302 if (value == UINT64_MAX)
2303 continue;
2304
2305 have_io_accounting = true;
2306 if (value > 0)
2307 any_io = true;
2308
2309 /* Format IO accounting data for inclusion in the structured log message */
2310 if (asprintf(&t, "%s=%" PRIu64, io_fields[k], value) < 0) {
2311 r = log_oom();
2312 goto finish;
2313 }
2314 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2315
2316 /* Format the IO accounting data for inclusion in the human language message string, but only
2317 * for the bytes counters (and not for the operations counters) */
2318 if (k == CGROUP_IO_READ_BYTES) {
2319 assert(!rr);
2320 rr = strjoin("read ", format_bytes(buf, sizeof(buf), value), " from disk");
2321 if (!rr) {
2322 r = log_oom();
2323 goto finish;
2324 }
2325 } else if (k == CGROUP_IO_WRITE_BYTES) {
2326 assert(!wr);
2327 wr = strjoin("written ", format_bytes(buf, sizeof(buf), value), " to disk");
2328 if (!wr) {
2329 r = log_oom();
2330 goto finish;
2331 }
2332 }
2333
2334 if (IN_SET(k, CGROUP_IO_READ_BYTES, CGROUP_IO_WRITE_BYTES))
2335 log_level = raise_level(log_level,
2336 value > MENTIONWORTHY_IO_BYTES,
2337 value > NOTICEWORTHY_IO_BYTES);
2338 }
2339
2340 if (have_io_accounting) {
2341 if (any_io) {
2342 if (rr)
2343 message_parts[n_message_parts++] = TAKE_PTR(rr);
2344 if (wr)
2345 message_parts[n_message_parts++] = TAKE_PTR(wr);
2346
2347 } else {
2348 char *k;
2349
2350 k = strdup("no IO");
2351 if (!k) {
2352 r = log_oom();
2353 goto finish;
2354 }
2355
2356 message_parts[n_message_parts++] = k;
2357 }
2358 }
2359
2360 for (m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
2361 char buf[FORMAT_BYTES_MAX] = "";
2362 uint64_t value = UINT64_MAX;
2363
2364 assert(ip_fields[m]);
2365
2366 (void) unit_get_ip_accounting(u, m, &value);
2367 if (value == UINT64_MAX)
2368 continue;
2369
2370 have_ip_accounting = true;
2371 if (value > 0)
2372 any_traffic = true;
2373
2374 /* Format IP accounting data for inclusion in the structured log message */
2375 if (asprintf(&t, "%s=%" PRIu64, ip_fields[m], value) < 0) {
2376 r = log_oom();
2377 goto finish;
2378 }
2379 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2380
2381 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2382 * bytes counters (and not for the packets counters) */
2383 if (m == CGROUP_IP_INGRESS_BYTES) {
2384 assert(!igress);
2385 igress = strjoin("received ", format_bytes(buf, sizeof(buf), value), " IP traffic");
2386 if (!igress) {
2387 r = log_oom();
2388 goto finish;
2389 }
2390 } else if (m == CGROUP_IP_EGRESS_BYTES) {
2391 assert(!egress);
2392 egress = strjoin("sent ", format_bytes(buf, sizeof(buf), value), " IP traffic");
2393 if (!egress) {
2394 r = log_oom();
2395 goto finish;
2396 }
2397 }
2398
2399 if (IN_SET(m, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2400 log_level = raise_level(log_level,
2401 value > MENTIONWORTHY_IP_BYTES,
2402 value > NOTICEWORTHY_IP_BYTES);
2403 }
2404
2405 if (have_ip_accounting) {
2406 if (any_traffic) {
2407 if (igress)
2408 message_parts[n_message_parts++] = TAKE_PTR(igress);
2409 if (egress)
2410 message_parts[n_message_parts++] = TAKE_PTR(egress);
2411
2412 } else {
2413 char *k;
2414
2415 k = strdup("no IP traffic");
2416 if (!k) {
2417 r = log_oom();
2418 goto finish;
2419 }
2420
2421 message_parts[n_message_parts++] = k;
2422 }
2423 }
2424
2425 /* Is there any accounting data available at all? */
2426 if (n_iovec == 0) {
2427 r = 0;
2428 goto finish;
2429 }
2430
2431 if (n_message_parts == 0)
2432 t = strjoina("MESSAGE=", u->id, ": Completed.");
2433 else {
2434 _cleanup_free_ char *joined;
2435
2436 message_parts[n_message_parts] = NULL;
2437
2438 joined = strv_join(message_parts, ", ");
2439 if (!joined) {
2440 r = log_oom();
2441 goto finish;
2442 }
2443
2444 joined[0] = ascii_toupper(joined[0]);
2445 t = strjoina("MESSAGE=", u->id, ": ", joined, ".");
2446 }
2447
2448 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2449 * and hence don't increase n_iovec for them */
2450 iovec[n_iovec] = IOVEC_MAKE_STRING(t);
2451 iovec[n_iovec + 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR);
2452
2453 t = strjoina(u->manager->unit_log_field, u->id);
2454 iovec[n_iovec + 2] = IOVEC_MAKE_STRING(t);
2455
2456 t = strjoina(u->manager->invocation_log_field, u->invocation_id_string);
2457 iovec[n_iovec + 3] = IOVEC_MAKE_STRING(t);
2458
2459 log_struct_iovec(log_level, iovec, n_iovec + 4);
2460 r = 0;
2461
2462 finish:
2463 for (i = 0; i < n_message_parts; i++)
2464 free(message_parts[i]);
2465
2466 for (i = 0; i < n_iovec; i++)
2467 free(iovec[i].iov_base);
2468
2469 return r;
2470
2471 }
2472
2473 static void unit_update_on_console(Unit *u) {
2474 bool b;
2475
2476 assert(u);
2477
2478 b = unit_needs_console(u);
2479 if (u->on_console == b)
2480 return;
2481
2482 u->on_console = b;
2483 if (b)
2484 manager_ref_console(u->manager);
2485 else
2486 manager_unref_console(u->manager);
2487 }
2488
2489 static void unit_emit_audit_start(Unit *u) {
2490 assert(u);
2491
2492 if (u->type != UNIT_SERVICE)
2493 return;
2494
2495 /* Write audit record if we have just finished starting up */
2496 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, true);
2497 u->in_audit = true;
2498 }
2499
2500 static void unit_emit_audit_stop(Unit *u, UnitActiveState state) {
2501 assert(u);
2502
2503 if (u->type != UNIT_SERVICE)
2504 return;
2505
2506 if (u->in_audit) {
2507 /* Write audit record if we have just finished shutting down */
2508 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, state == UNIT_INACTIVE);
2509 u->in_audit = false;
2510 } else {
2511 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
2512 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_START, state == UNIT_INACTIVE);
2513
2514 if (state == UNIT_INACTIVE)
2515 manager_send_unit_audit(u->manager, u, AUDIT_SERVICE_STOP, true);
2516 }
2517 }
2518
2519 static bool unit_process_job(Job *j, UnitActiveState ns, UnitNotifyFlags flags) {
2520 bool unexpected = false;
2521 JobResult result;
2522
2523 assert(j);
2524
2525 if (j->state == JOB_WAITING)
2526
2527 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2528 * due to EAGAIN. */
2529 job_add_to_run_queue(j);
2530
2531 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2532 * hence needs to invalidate jobs. */
2533
2534 switch (j->type) {
2535
2536 case JOB_START:
2537 case JOB_VERIFY_ACTIVE:
2538
2539 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
2540 job_finish_and_invalidate(j, JOB_DONE, true, false);
2541 else if (j->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
2542 unexpected = true;
2543
2544 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2545 if (ns == UNIT_FAILED)
2546 result = JOB_FAILED;
2547 else if (FLAGS_SET(flags, UNIT_NOTIFY_SKIP_CONDITION))
2548 result = JOB_SKIPPED;
2549 else
2550 result = JOB_DONE;
2551
2552 job_finish_and_invalidate(j, result, true, false);
2553 }
2554 }
2555
2556 break;
2557
2558 case JOB_RELOAD:
2559 case JOB_RELOAD_OR_START:
2560 case JOB_TRY_RELOAD:
2561
2562 if (j->state == JOB_RUNNING) {
2563 if (ns == UNIT_ACTIVE)
2564 job_finish_and_invalidate(j, (flags & UNIT_NOTIFY_RELOAD_FAILURE) ? JOB_FAILED : JOB_DONE, true, false);
2565 else if (!IN_SET(ns, UNIT_ACTIVATING, UNIT_RELOADING)) {
2566 unexpected = true;
2567
2568 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2569 job_finish_and_invalidate(j, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
2570 }
2571 }
2572
2573 break;
2574
2575 case JOB_STOP:
2576 case JOB_RESTART:
2577 case JOB_TRY_RESTART:
2578
2579 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2580 job_finish_and_invalidate(j, JOB_DONE, true, false);
2581 else if (j->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
2582 unexpected = true;
2583 job_finish_and_invalidate(j, JOB_FAILED, true, false);
2584 }
2585
2586 break;
2587
2588 default:
2589 assert_not_reached("Job type unknown");
2590 }
2591
2592 return unexpected;
2593 }
2594
2595 void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, UnitNotifyFlags flags) {
2596 const char *reason;
2597 Manager *m;
2598
2599 assert(u);
2600 assert(os < _UNIT_ACTIVE_STATE_MAX);
2601 assert(ns < _UNIT_ACTIVE_STATE_MAX);
2602
2603 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2604 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2605 * remounted this function will be called too! */
2606
2607 m = u->manager;
2608
2609 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2610 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2611 unit_add_to_dbus_queue(u);
2612
2613 /* Update timestamps for state changes */
2614 if (!MANAGER_IS_RELOADING(m)) {
2615 dual_timestamp_get(&u->state_change_timestamp);
2616
2617 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
2618 u->inactive_exit_timestamp = u->state_change_timestamp;
2619 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
2620 u->inactive_enter_timestamp = u->state_change_timestamp;
2621
2622 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
2623 u->active_enter_timestamp = u->state_change_timestamp;
2624 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
2625 u->active_exit_timestamp = u->state_change_timestamp;
2626 }
2627
2628 /* Keep track of failed units */
2629 (void) manager_update_failed_units(m, u, ns == UNIT_FAILED);
2630
2631 /* Make sure the cgroup and state files are always removed when we become inactive */
2632 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2633 unit_prune_cgroup(u);
2634 unit_unlink_state_files(u);
2635 }
2636
2637 unit_update_on_console(u);
2638
2639 if (!MANAGER_IS_RELOADING(m)) {
2640 bool unexpected;
2641
2642 /* Let's propagate state changes to the job */
2643 if (u->job)
2644 unexpected = unit_process_job(u->job, ns, flags);
2645 else
2646 unexpected = true;
2647
2648 /* If this state change happened without being requested by a job, then let's retroactively start or
2649 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2650 * additional jobs just because something is already activated. */
2651
2652 if (unexpected) {
2653 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
2654 retroactively_start_dependencies(u);
2655 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2656 retroactively_stop_dependencies(u);
2657 }
2658
2659 /* stop unneeded units regardless if going down was expected or not */
2660 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2661 check_unneeded_dependencies(u);
2662
2663 if (ns != os && ns == UNIT_FAILED) {
2664 log_unit_debug(u, "Unit entered failed state.");
2665
2666 if (!(flags & UNIT_NOTIFY_WILL_AUTO_RESTART))
2667 unit_start_on_failure(u);
2668 }
2669
2670 if (UNIT_IS_ACTIVE_OR_RELOADING(ns) && !UNIT_IS_ACTIVE_OR_RELOADING(os)) {
2671 /* This unit just finished starting up */
2672
2673 unit_emit_audit_start(u);
2674 manager_send_unit_plymouth(m, u);
2675 }
2676
2677 if (UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os)) {
2678 /* This unit just stopped/failed. */
2679
2680 unit_emit_audit_stop(u, ns);
2681 unit_log_resources(u);
2682 }
2683 }
2684
2685 manager_recheck_journal(m);
2686 manager_recheck_dbus(m);
2687
2688 unit_trigger_notify(u);
2689
2690 if (!MANAGER_IS_RELOADING(m)) {
2691 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2692 unit_submit_to_stop_when_unneeded_queue(u);
2693
2694 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens when
2695 * something BindsTo= to a Type=oneshot unit, as these units go directly from starting to inactive,
2696 * without ever entering started.) */
2697 unit_check_binds_to(u);
2698
2699 if (os != UNIT_FAILED && ns == UNIT_FAILED) {
2700 reason = strjoina("unit ", u->id, " failed");
2701 emergency_action(m, u->failure_action, 0, u->reboot_arg, unit_failure_action_exit_status(u), reason);
2702 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && ns == UNIT_INACTIVE) {
2703 reason = strjoina("unit ", u->id, " succeeded");
2704 emergency_action(m, u->success_action, 0, u->reboot_arg, unit_success_action_exit_status(u), reason);
2705 }
2706 }
2707
2708 unit_add_to_gc_queue(u);
2709 }
2710
2711 int unit_watch_pid(Unit *u, pid_t pid, bool exclusive) {
2712 int r;
2713
2714 assert(u);
2715 assert(pid_is_valid(pid));
2716
2717 /* Watch a specific PID */
2718
2719 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2720 * opportunity to remove any stalled references to this PID as they can be created
2721 * easily (when watching a process which is not our direct child). */
2722 if (exclusive)
2723 manager_unwatch_pid(u->manager, pid);
2724
2725 r = set_ensure_allocated(&u->pids, NULL);
2726 if (r < 0)
2727 return r;
2728
2729 r = hashmap_ensure_allocated(&u->manager->watch_pids, NULL);
2730 if (r < 0)
2731 return r;
2732
2733 /* First try, let's add the unit keyed by "pid". */
2734 r = hashmap_put(u->manager->watch_pids, PID_TO_PTR(pid), u);
2735 if (r == -EEXIST) {
2736 Unit **array;
2737 bool found = false;
2738 size_t n = 0;
2739
2740 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2741 * to an array of Units rather than just a Unit), lists us already. */
2742
2743 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2744 if (array)
2745 for (; array[n]; n++)
2746 if (array[n] == u)
2747 found = true;
2748
2749 if (found) /* Found it already? if so, do nothing */
2750 r = 0;
2751 else {
2752 Unit **new_array;
2753
2754 /* Allocate a new array */
2755 new_array = new(Unit*, n + 2);
2756 if (!new_array)
2757 return -ENOMEM;
2758
2759 memcpy_safe(new_array, array, sizeof(Unit*) * n);
2760 new_array[n] = u;
2761 new_array[n+1] = NULL;
2762
2763 /* Add or replace the old array */
2764 r = hashmap_replace(u->manager->watch_pids, PID_TO_PTR(-pid), new_array);
2765 if (r < 0) {
2766 free(new_array);
2767 return r;
2768 }
2769
2770 free(array);
2771 }
2772 } else if (r < 0)
2773 return r;
2774
2775 r = set_put(u->pids, PID_TO_PTR(pid));
2776 if (r < 0)
2777 return r;
2778
2779 return 0;
2780 }
2781
2782 void unit_unwatch_pid(Unit *u, pid_t pid) {
2783 Unit **array;
2784
2785 assert(u);
2786 assert(pid_is_valid(pid));
2787
2788 /* First let's drop the unit in case it's keyed as "pid". */
2789 (void) hashmap_remove_value(u->manager->watch_pids, PID_TO_PTR(pid), u);
2790
2791 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2792 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2793 if (array) {
2794 size_t n, m = 0;
2795
2796 /* Let's iterate through the array, dropping our own entry */
2797 for (n = 0; array[n]; n++)
2798 if (array[n] != u)
2799 array[m++] = array[n];
2800 array[m] = NULL;
2801
2802 if (m == 0) {
2803 /* The array is now empty, remove the entire entry */
2804 assert_se(hashmap_remove(u->manager->watch_pids, PID_TO_PTR(-pid)) == array);
2805 free(array);
2806 }
2807 }
2808
2809 (void) set_remove(u->pids, PID_TO_PTR(pid));
2810 }
2811
2812 void unit_unwatch_all_pids(Unit *u) {
2813 assert(u);
2814
2815 while (!set_isempty(u->pids))
2816 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
2817
2818 u->pids = set_free(u->pids);
2819 }
2820
2821 static void unit_tidy_watch_pids(Unit *u) {
2822 pid_t except1, except2;
2823 Iterator i;
2824 void *e;
2825
2826 assert(u);
2827
2828 /* Cleans dead PIDs from our list */
2829
2830 except1 = unit_main_pid(u);
2831 except2 = unit_control_pid(u);
2832
2833 SET_FOREACH(e, u->pids, i) {
2834 pid_t pid = PTR_TO_PID(e);
2835
2836 if (pid == except1 || pid == except2)
2837 continue;
2838
2839 if (!pid_is_unwaited(pid))
2840 unit_unwatch_pid(u, pid);
2841 }
2842 }
2843
2844 static int on_rewatch_pids_event(sd_event_source *s, void *userdata) {
2845 Unit *u = userdata;
2846
2847 assert(s);
2848 assert(u);
2849
2850 unit_tidy_watch_pids(u);
2851 unit_watch_all_pids(u);
2852
2853 /* If the PID set is empty now, then let's finish this off. */
2854 unit_synthesize_cgroup_empty_event(u);
2855
2856 return 0;
2857 }
2858
2859 int unit_enqueue_rewatch_pids(Unit *u) {
2860 int r;
2861
2862 assert(u);
2863
2864 if (!u->cgroup_path)
2865 return -ENOENT;
2866
2867 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2868 if (r < 0)
2869 return r;
2870 if (r > 0) /* On unified we can use proper notifications */
2871 return 0;
2872
2873 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
2874 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
2875 * involves issuing kill(pid, 0) on all processes we watch. */
2876
2877 if (!u->rewatch_pids_event_source) {
2878 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
2879
2880 r = sd_event_add_defer(u->manager->event, &s, on_rewatch_pids_event, u);
2881 if (r < 0)
2882 return log_error_errno(r, "Failed to allocate event source for tidying watched PIDs: %m");
2883
2884 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_IDLE);
2885 if (r < 0)
2886 return log_error_errno(r, "Failed to adjust priority of event source for tidying watched PIDs: %m");
2887
2888 (void) sd_event_source_set_description(s, "tidy-watch-pids");
2889
2890 u->rewatch_pids_event_source = TAKE_PTR(s);
2891 }
2892
2893 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_ONESHOT);
2894 if (r < 0)
2895 return log_error_errno(r, "Failed to enable event source for tidying watched PIDs: %m");
2896
2897 return 0;
2898 }
2899
2900 void unit_dequeue_rewatch_pids(Unit *u) {
2901 int r;
2902 assert(u);
2903
2904 if (!u->rewatch_pids_event_source)
2905 return;
2906
2907 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_OFF);
2908 if (r < 0)
2909 log_warning_errno(r, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
2910
2911 u->rewatch_pids_event_source = sd_event_source_unref(u->rewatch_pids_event_source);
2912 }
2913
2914 bool unit_job_is_applicable(Unit *u, JobType j) {
2915 assert(u);
2916 assert(j >= 0 && j < _JOB_TYPE_MAX);
2917
2918 switch (j) {
2919
2920 case JOB_VERIFY_ACTIVE:
2921 case JOB_START:
2922 case JOB_NOP:
2923 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
2924 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
2925 * jobs for it. */
2926 return true;
2927
2928 case JOB_STOP:
2929 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
2930 * external events), hence it makes no sense to permit enqueuing such a request either. */
2931 return !u->perpetual;
2932
2933 case JOB_RESTART:
2934 case JOB_TRY_RESTART:
2935 return unit_can_stop(u) && unit_can_start(u);
2936
2937 case JOB_RELOAD:
2938 case JOB_TRY_RELOAD:
2939 return unit_can_reload(u);
2940
2941 case JOB_RELOAD_OR_START:
2942 return unit_can_reload(u) && unit_can_start(u);
2943
2944 default:
2945 assert_not_reached("Invalid job type");
2946 }
2947 }
2948
2949 static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2950 assert(u);
2951
2952 /* Only warn about some unit types */
2953 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2954 return;
2955
2956 if (streq_ptr(u->id, other))
2957 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2958 else
2959 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
2960 }
2961
2962 static int unit_add_dependency_hashmap(
2963 Hashmap **h,
2964 Unit *other,
2965 UnitDependencyMask origin_mask,
2966 UnitDependencyMask destination_mask) {
2967
2968 UnitDependencyInfo info;
2969 int r;
2970
2971 assert(h);
2972 assert(other);
2973 assert(origin_mask < _UNIT_DEPENDENCY_MASK_FULL);
2974 assert(destination_mask < _UNIT_DEPENDENCY_MASK_FULL);
2975 assert(origin_mask > 0 || destination_mask > 0);
2976
2977 r = hashmap_ensure_allocated(h, NULL);
2978 if (r < 0)
2979 return r;
2980
2981 assert_cc(sizeof(void*) == sizeof(info));
2982
2983 info.data = hashmap_get(*h, other);
2984 if (info.data) {
2985 /* Entry already exists. Add in our mask. */
2986
2987 if (FLAGS_SET(origin_mask, info.origin_mask) &&
2988 FLAGS_SET(destination_mask, info.destination_mask))
2989 return 0; /* NOP */
2990
2991 info.origin_mask |= origin_mask;
2992 info.destination_mask |= destination_mask;
2993
2994 r = hashmap_update(*h, other, info.data);
2995 } else {
2996 info = (UnitDependencyInfo) {
2997 .origin_mask = origin_mask,
2998 .destination_mask = destination_mask,
2999 };
3000
3001 r = hashmap_put(*h, other, info.data);
3002 }
3003 if (r < 0)
3004 return r;
3005
3006 return 1;
3007 }
3008
3009 int unit_add_dependency(
3010 Unit *u,
3011 UnitDependency d,
3012 Unit *other,
3013 bool add_reference,
3014 UnitDependencyMask mask) {
3015
3016 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
3017 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
3018 [UNIT_WANTS] = UNIT_WANTED_BY,
3019 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
3020 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
3021 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
3022 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
3023 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
3024 [UNIT_WANTED_BY] = UNIT_WANTS,
3025 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
3026 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
3027 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
3028 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
3029 [UNIT_BEFORE] = UNIT_AFTER,
3030 [UNIT_AFTER] = UNIT_BEFORE,
3031 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
3032 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
3033 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
3034 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
3035 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
3036 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
3037 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
3038 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
3039 };
3040 Unit *original_u = u, *original_other = other;
3041 int r;
3042
3043 assert(u);
3044 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
3045 assert(other);
3046
3047 u = unit_follow_merge(u);
3048 other = unit_follow_merge(other);
3049
3050 /* We won't allow dependencies on ourselves. We will not
3051 * consider them an error however. */
3052 if (u == other) {
3053 maybe_warn_about_dependency(original_u, original_other->id, d);
3054 return 0;
3055 }
3056
3057 /* Note that ordering a device unit after a unit is permitted since it
3058 * allows to start its job running timeout at a specific time. */
3059 if (d == UNIT_BEFORE && other->type == UNIT_DEVICE) {
3060 log_unit_warning(u, "Dependency Before=%s ignored (.device units cannot be delayed)", other->id);
3061 return 0;
3062 }
3063
3064 if (d == UNIT_ON_FAILURE && !UNIT_VTABLE(u)->can_fail) {
3065 log_unit_warning(u, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other->id, unit_type_to_string(u->type));
3066 return 0;
3067 }
3068
3069 if (d == UNIT_TRIGGERS && !UNIT_VTABLE(u)->can_trigger)
3070 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3071 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(u->type));
3072 if (d == UNIT_TRIGGERED_BY && !UNIT_VTABLE(other)->can_trigger)
3073 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3074 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(other->type));
3075
3076 r = unit_add_dependency_hashmap(u->dependencies + d, other, mask, 0);
3077 if (r < 0)
3078 return r;
3079
3080 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
3081 r = unit_add_dependency_hashmap(other->dependencies + inverse_table[d], u, 0, mask);
3082 if (r < 0)
3083 return r;
3084 }
3085
3086 if (add_reference) {
3087 r = unit_add_dependency_hashmap(u->dependencies + UNIT_REFERENCES, other, mask, 0);
3088 if (r < 0)
3089 return r;
3090
3091 r = unit_add_dependency_hashmap(other->dependencies + UNIT_REFERENCED_BY, u, 0, mask);
3092 if (r < 0)
3093 return r;
3094 }
3095
3096 unit_add_to_dbus_queue(u);
3097 return 0;
3098 }
3099
3100 int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask) {
3101 int r;
3102
3103 assert(u);
3104
3105 r = unit_add_dependency(u, d, other, add_reference, mask);
3106 if (r < 0)
3107 return r;
3108
3109 return unit_add_dependency(u, e, other, add_reference, mask);
3110 }
3111
3112 static int resolve_template(Unit *u, const char *name, char **buf, const char **ret) {
3113 int r;
3114
3115 assert(u);
3116 assert(name);
3117 assert(buf);
3118 assert(ret);
3119
3120 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
3121 *buf = NULL;
3122 *ret = name;
3123 return 0;
3124 }
3125
3126 if (u->instance)
3127 r = unit_name_replace_instance(name, u->instance, buf);
3128 else {
3129 _cleanup_free_ char *i = NULL;
3130
3131 r = unit_name_to_prefix(u->id, &i);
3132 if (r < 0)
3133 return r;
3134
3135 r = unit_name_replace_instance(name, i, buf);
3136 }
3137 if (r < 0)
3138 return r;
3139
3140 *ret = *buf;
3141 return 0;
3142 }
3143
3144 int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask) {
3145 _cleanup_free_ char *buf = NULL;
3146 Unit *other;
3147 int r;
3148
3149 assert(u);
3150 assert(name);
3151
3152 r = resolve_template(u, name, &buf, &name);
3153 if (r < 0)
3154 return r;
3155
3156 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3157 if (r < 0)
3158 return r;
3159
3160 return unit_add_dependency(u, d, other, add_reference, mask);
3161 }
3162
3163 int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask) {
3164 _cleanup_free_ char *buf = NULL;
3165 Unit *other;
3166 int r;
3167
3168 assert(u);
3169 assert(name);
3170
3171 r = resolve_template(u, name, &buf, &name);
3172 if (r < 0)
3173 return r;
3174
3175 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3176 if (r < 0)
3177 return r;
3178
3179 return unit_add_two_dependencies(u, d, e, other, add_reference, mask);
3180 }
3181
3182 int set_unit_path(const char *p) {
3183 /* This is mostly for debug purposes */
3184 if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
3185 return -errno;
3186
3187 return 0;
3188 }
3189
3190 char *unit_dbus_path(Unit *u) {
3191 assert(u);
3192
3193 if (!u->id)
3194 return NULL;
3195
3196 return unit_dbus_path_from_name(u->id);
3197 }
3198
3199 char *unit_dbus_path_invocation_id(Unit *u) {
3200 assert(u);
3201
3202 if (sd_id128_is_null(u->invocation_id))
3203 return NULL;
3204
3205 return unit_dbus_path_from_name(u->invocation_id_string);
3206 }
3207
3208 int unit_set_slice(Unit *u, Unit *slice) {
3209 assert(u);
3210 assert(slice);
3211
3212 /* Sets the unit slice if it has not been set before. Is extra
3213 * careful, to only allow this for units that actually have a
3214 * cgroup context. Also, we don't allow to set this for slices
3215 * (since the parent slice is derived from the name). Make
3216 * sure the unit we set is actually a slice. */
3217
3218 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3219 return -EOPNOTSUPP;
3220
3221 if (u->type == UNIT_SLICE)
3222 return -EINVAL;
3223
3224 if (unit_active_state(u) != UNIT_INACTIVE)
3225 return -EBUSY;
3226
3227 if (slice->type != UNIT_SLICE)
3228 return -EINVAL;
3229
3230 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
3231 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
3232 return -EPERM;
3233
3234 if (UNIT_DEREF(u->slice) == slice)
3235 return 0;
3236
3237 /* Disallow slice changes if @u is already bound to cgroups */
3238 if (UNIT_ISSET(u->slice) && u->cgroup_realized)
3239 return -EBUSY;
3240
3241 unit_ref_set(&u->slice, u, slice);
3242 return 1;
3243 }
3244
3245 int unit_set_default_slice(Unit *u) {
3246 const char *slice_name;
3247 Unit *slice;
3248 int r;
3249
3250 assert(u);
3251
3252 if (UNIT_ISSET(u->slice))
3253 return 0;
3254
3255 if (u->instance) {
3256 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
3257
3258 /* Implicitly place all instantiated units in their
3259 * own per-template slice */
3260
3261 r = unit_name_to_prefix(u->id, &prefix);
3262 if (r < 0)
3263 return r;
3264
3265 /* The prefix is already escaped, but it might include
3266 * "-" which has a special meaning for slice units,
3267 * hence escape it here extra. */
3268 escaped = unit_name_escape(prefix);
3269 if (!escaped)
3270 return -ENOMEM;
3271
3272 if (MANAGER_IS_SYSTEM(u->manager))
3273 slice_name = strjoina("system-", escaped, ".slice");
3274 else
3275 slice_name = strjoina(escaped, ".slice");
3276 } else
3277 slice_name =
3278 MANAGER_IS_SYSTEM(u->manager) && !unit_has_name(u, SPECIAL_INIT_SCOPE)
3279 ? SPECIAL_SYSTEM_SLICE
3280 : SPECIAL_ROOT_SLICE;
3281
3282 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
3283 if (r < 0)
3284 return r;
3285
3286 return unit_set_slice(u, slice);
3287 }
3288
3289 const char *unit_slice_name(Unit *u) {
3290 assert(u);
3291
3292 if (!UNIT_ISSET(u->slice))
3293 return NULL;
3294
3295 return UNIT_DEREF(u->slice)->id;
3296 }
3297
3298 int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
3299 _cleanup_free_ char *t = NULL;
3300 int r;
3301
3302 assert(u);
3303 assert(type);
3304 assert(_found);
3305
3306 r = unit_name_change_suffix(u->id, type, &t);
3307 if (r < 0)
3308 return r;
3309 if (unit_has_name(u, t))
3310 return -EINVAL;
3311
3312 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
3313 assert(r < 0 || *_found != u);
3314 return r;
3315 }
3316
3317 static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3318 const char *new_owner;
3319 Unit *u = userdata;
3320 int r;
3321
3322 assert(message);
3323 assert(u);
3324
3325 r = sd_bus_message_read(message, "sss", NULL, NULL, &new_owner);
3326 if (r < 0) {
3327 bus_log_parse_error(r);
3328 return 0;
3329 }
3330
3331 if (UNIT_VTABLE(u)->bus_name_owner_change)
3332 UNIT_VTABLE(u)->bus_name_owner_change(u, empty_to_null(new_owner));
3333
3334 return 0;
3335 }
3336
3337 static int get_name_owner_handler(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3338 const sd_bus_error *e;
3339 const char *new_owner;
3340 Unit *u = userdata;
3341 int r;
3342
3343 assert(message);
3344 assert(u);
3345
3346 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3347
3348 e = sd_bus_message_get_error(message);
3349 if (e) {
3350 if (!sd_bus_error_has_name(e, "org.freedesktop.DBus.Error.NameHasNoOwner"))
3351 log_unit_error(u, "Unexpected error response from GetNameOwner(): %s", e->message);
3352
3353 new_owner = NULL;
3354 } else {
3355 r = sd_bus_message_read(message, "s", &new_owner);
3356 if (r < 0)
3357 return bus_log_parse_error(r);
3358
3359 assert(!isempty(new_owner));
3360 }
3361
3362 if (UNIT_VTABLE(u)->bus_name_owner_change)
3363 UNIT_VTABLE(u)->bus_name_owner_change(u, new_owner);
3364
3365 return 0;
3366 }
3367
3368 int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
3369 const char *match;
3370 int r;
3371
3372 assert(u);
3373 assert(bus);
3374 assert(name);
3375
3376 if (u->match_bus_slot || u->get_name_owner_slot)
3377 return -EBUSY;
3378
3379 match = strjoina("type='signal',"
3380 "sender='org.freedesktop.DBus',"
3381 "path='/org/freedesktop/DBus',"
3382 "interface='org.freedesktop.DBus',"
3383 "member='NameOwnerChanged',"
3384 "arg0='", name, "'");
3385
3386 r = sd_bus_add_match_async(bus, &u->match_bus_slot, match, signal_name_owner_changed, NULL, u);
3387 if (r < 0)
3388 return r;
3389
3390 r = sd_bus_call_method_async(
3391 bus,
3392 &u->get_name_owner_slot,
3393 "org.freedesktop.DBus",
3394 "/org/freedesktop/DBus",
3395 "org.freedesktop.DBus",
3396 "GetNameOwner",
3397 get_name_owner_handler,
3398 u,
3399 "s", name);
3400 if (r < 0) {
3401 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3402 return r;
3403 }
3404
3405 log_unit_debug(u, "Watching D-Bus name '%s'.", name);
3406 return 0;
3407 }
3408
3409 int unit_watch_bus_name(Unit *u, const char *name) {
3410 int r;
3411
3412 assert(u);
3413 assert(name);
3414
3415 /* Watch a specific name on the bus. We only support one unit
3416 * watching each name for now. */
3417
3418 if (u->manager->api_bus) {
3419 /* If the bus is already available, install the match directly.
3420 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
3421 r = unit_install_bus_match(u, u->manager->api_bus, name);
3422 if (r < 0)
3423 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
3424 }
3425
3426 r = hashmap_put(u->manager->watch_bus, name, u);
3427 if (r < 0) {
3428 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3429 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3430 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
3431 }
3432
3433 return 0;
3434 }
3435
3436 void unit_unwatch_bus_name(Unit *u, const char *name) {
3437 assert(u);
3438 assert(name);
3439
3440 (void) hashmap_remove_value(u->manager->watch_bus, name, u);
3441 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3442 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3443 }
3444
3445 bool unit_can_serialize(Unit *u) {
3446 assert(u);
3447
3448 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
3449 }
3450
3451 static int serialize_cgroup_mask(FILE *f, const char *key, CGroupMask mask) {
3452 _cleanup_free_ char *s = NULL;
3453 int r;
3454
3455 assert(f);
3456 assert(key);
3457
3458 if (mask == 0)
3459 return 0;
3460
3461 r = cg_mask_to_string(mask, &s);
3462 if (r < 0)
3463 return log_error_errno(r, "Failed to format cgroup mask: %m");
3464
3465 return serialize_item(f, key, s);
3466 }
3467
3468 static const char *const ip_accounting_metric_field[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
3469 [CGROUP_IP_INGRESS_BYTES] = "ip-accounting-ingress-bytes",
3470 [CGROUP_IP_INGRESS_PACKETS] = "ip-accounting-ingress-packets",
3471 [CGROUP_IP_EGRESS_BYTES] = "ip-accounting-egress-bytes",
3472 [CGROUP_IP_EGRESS_PACKETS] = "ip-accounting-egress-packets",
3473 };
3474
3475 static const char *const io_accounting_metric_field_base[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3476 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-base",
3477 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-base",
3478 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-base",
3479 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-base",
3480 };
3481
3482 static const char *const io_accounting_metric_field_last[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
3483 [CGROUP_IO_READ_BYTES] = "io-accounting-read-bytes-last",
3484 [CGROUP_IO_WRITE_BYTES] = "io-accounting-write-bytes-last",
3485 [CGROUP_IO_READ_OPERATIONS] = "io-accounting-read-operations-last",
3486 [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-last",
3487 };
3488
3489 int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
3490 CGroupIPAccountingMetric m;
3491 int r;
3492
3493 assert(u);
3494 assert(f);
3495 assert(fds);
3496
3497 if (unit_can_serialize(u)) {
3498 r = UNIT_VTABLE(u)->serialize(u, f, fds);
3499 if (r < 0)
3500 return r;
3501 }
3502
3503 (void) serialize_dual_timestamp(f, "state-change-timestamp", &u->state_change_timestamp);
3504
3505 (void) serialize_dual_timestamp(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
3506 (void) serialize_dual_timestamp(f, "active-enter-timestamp", &u->active_enter_timestamp);
3507 (void) serialize_dual_timestamp(f, "active-exit-timestamp", &u->active_exit_timestamp);
3508 (void) serialize_dual_timestamp(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
3509
3510 (void) serialize_dual_timestamp(f, "condition-timestamp", &u->condition_timestamp);
3511 (void) serialize_dual_timestamp(f, "assert-timestamp", &u->assert_timestamp);
3512
3513 if (dual_timestamp_is_set(&u->condition_timestamp))
3514 (void) serialize_bool(f, "condition-result", u->condition_result);
3515
3516 if (dual_timestamp_is_set(&u->assert_timestamp))
3517 (void) serialize_bool(f, "assert-result", u->assert_result);
3518
3519 (void) serialize_bool(f, "transient", u->transient);
3520 (void) serialize_bool(f, "in-audit", u->in_audit);
3521
3522 (void) serialize_bool(f, "exported-invocation-id", u->exported_invocation_id);
3523 (void) serialize_bool(f, "exported-log-level-max", u->exported_log_level_max);
3524 (void) serialize_bool(f, "exported-log-extra-fields", u->exported_log_extra_fields);
3525 (void) serialize_bool(f, "exported-log-rate-limit-interval", u->exported_log_ratelimit_interval);
3526 (void) serialize_bool(f, "exported-log-rate-limit-burst", u->exported_log_ratelimit_burst);
3527
3528 (void) serialize_item_format(f, "cpu-usage-base", "%" PRIu64, u->cpu_usage_base);
3529 if (u->cpu_usage_last != NSEC_INFINITY)
3530 (void) serialize_item_format(f, "cpu-usage-last", "%" PRIu64, u->cpu_usage_last);
3531
3532 if (u->oom_kill_last > 0)
3533 (void) serialize_item_format(f, "oom-kill-last", "%" PRIu64, u->oom_kill_last);
3534
3535 for (CGroupIOAccountingMetric im = 0; im < _CGROUP_IO_ACCOUNTING_METRIC_MAX; im++) {
3536 (void) serialize_item_format(f, io_accounting_metric_field_base[im], "%" PRIu64, u->io_accounting_base[im]);
3537
3538 if (u->io_accounting_last[im] != UINT64_MAX)
3539 (void) serialize_item_format(f, io_accounting_metric_field_last[im], "%" PRIu64, u->io_accounting_last[im]);
3540 }
3541
3542 if (u->cgroup_path)
3543 (void) serialize_item(f, "cgroup", u->cgroup_path);
3544
3545 (void) serialize_bool(f, "cgroup-realized", u->cgroup_realized);
3546 (void) serialize_cgroup_mask(f, "cgroup-realized-mask", u->cgroup_realized_mask);
3547 (void) serialize_cgroup_mask(f, "cgroup-enabled-mask", u->cgroup_enabled_mask);
3548 (void) serialize_cgroup_mask(f, "cgroup-invalidated-mask", u->cgroup_invalidated_mask);
3549
3550 if (uid_is_valid(u->ref_uid))
3551 (void) serialize_item_format(f, "ref-uid", UID_FMT, u->ref_uid);
3552 if (gid_is_valid(u->ref_gid))
3553 (void) serialize_item_format(f, "ref-gid", GID_FMT, u->ref_gid);
3554
3555 if (!sd_id128_is_null(u->invocation_id))
3556 (void) serialize_item_format(f, "invocation-id", SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id));
3557
3558 (void) serialize_item_format(f, "freezer-state", "%s", freezer_state_to_string(unit_freezer_state(u)));
3559
3560 bus_track_serialize(u->bus_track, f, "ref");
3561
3562 for (m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
3563 uint64_t v;
3564
3565 r = unit_get_ip_accounting(u, m, &v);
3566 if (r >= 0)
3567 (void) serialize_item_format(f, ip_accounting_metric_field[m], "%" PRIu64, v);
3568 }
3569
3570 if (serialize_jobs) {
3571 if (u->job) {
3572 fputs("job\n", f);
3573 job_serialize(u->job, f);
3574 }
3575
3576 if (u->nop_job) {
3577 fputs("job\n", f);
3578 job_serialize(u->nop_job, f);
3579 }
3580 }
3581
3582 /* End marker */
3583 fputc('\n', f);
3584 return 0;
3585 }
3586
3587 static int unit_deserialize_job(Unit *u, FILE *f) {
3588 _cleanup_(job_freep) Job *j = NULL;
3589 int r;
3590
3591 assert(u);
3592 assert(f);
3593
3594 j = job_new_raw(u);
3595 if (!j)
3596 return log_oom();
3597
3598 r = job_deserialize(j, f);
3599 if (r < 0)
3600 return r;
3601
3602 r = job_install_deserialized(j);
3603 if (r < 0)
3604 return r;
3605
3606 TAKE_PTR(j);
3607 return 0;
3608 }
3609
3610 int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
3611 int r;
3612
3613 assert(u);
3614 assert(f);
3615 assert(fds);
3616
3617 for (;;) {
3618 _cleanup_free_ char *line = NULL;
3619 char *l, *v;
3620 ssize_t m;
3621 size_t k;
3622
3623 r = read_line(f, LONG_LINE_MAX, &line);
3624 if (r < 0)
3625 return log_error_errno(r, "Failed to read serialization line: %m");
3626 if (r == 0) /* eof */
3627 break;
3628
3629 l = strstrip(line);
3630 if (isempty(l)) /* End marker */
3631 break;
3632
3633 k = strcspn(l, "=");
3634
3635 if (l[k] == '=') {
3636 l[k] = 0;
3637 v = l+k+1;
3638 } else
3639 v = l+k;
3640
3641 if (streq(l, "job")) {
3642 if (v[0] == '\0') {
3643 /* New-style serialized job */
3644 r = unit_deserialize_job(u, f);
3645 if (r < 0)
3646 return r;
3647 } else /* Legacy for pre-44 */
3648 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
3649 continue;
3650 } else if (streq(l, "state-change-timestamp")) {
3651 (void) deserialize_dual_timestamp(v, &u->state_change_timestamp);
3652 continue;
3653 } else if (streq(l, "inactive-exit-timestamp")) {
3654 (void) deserialize_dual_timestamp(v, &u->inactive_exit_timestamp);
3655 continue;
3656 } else if (streq(l, "active-enter-timestamp")) {
3657 (void) deserialize_dual_timestamp(v, &u->active_enter_timestamp);
3658 continue;
3659 } else if (streq(l, "active-exit-timestamp")) {
3660 (void) deserialize_dual_timestamp(v, &u->active_exit_timestamp);
3661 continue;
3662 } else if (streq(l, "inactive-enter-timestamp")) {
3663 (void) deserialize_dual_timestamp(v, &u->inactive_enter_timestamp);
3664 continue;
3665 } else if (streq(l, "condition-timestamp")) {
3666 (void) deserialize_dual_timestamp(v, &u->condition_timestamp);
3667 continue;
3668 } else if (streq(l, "assert-timestamp")) {
3669 (void) deserialize_dual_timestamp(v, &u->assert_timestamp);
3670 continue;
3671 } else if (streq(l, "condition-result")) {
3672
3673 r = parse_boolean(v);
3674 if (r < 0)
3675 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
3676 else
3677 u->condition_result = r;
3678
3679 continue;
3680
3681 } else if (streq(l, "assert-result")) {
3682
3683 r = parse_boolean(v);
3684 if (r < 0)
3685 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
3686 else
3687 u->assert_result = r;
3688
3689 continue;
3690
3691 } else if (streq(l, "transient")) {
3692
3693 r = parse_boolean(v);
3694 if (r < 0)
3695 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
3696 else
3697 u->transient = r;
3698
3699 continue;
3700
3701 } else if (streq(l, "in-audit")) {
3702
3703 r = parse_boolean(v);
3704 if (r < 0)
3705 log_unit_debug(u, "Failed to parse in-audit bool %s, ignoring.", v);
3706 else
3707 u->in_audit = r;
3708
3709 continue;
3710
3711 } else if (streq(l, "exported-invocation-id")) {
3712
3713 r = parse_boolean(v);
3714 if (r < 0)
3715 log_unit_debug(u, "Failed to parse exported invocation ID bool %s, ignoring.", v);
3716 else
3717 u->exported_invocation_id = r;
3718
3719 continue;
3720
3721 } else if (streq(l, "exported-log-level-max")) {
3722
3723 r = parse_boolean(v);
3724 if (r < 0)
3725 log_unit_debug(u, "Failed to parse exported log level max bool %s, ignoring.", v);
3726 else
3727 u->exported_log_level_max = r;
3728
3729 continue;
3730
3731 } else if (streq(l, "exported-log-extra-fields")) {
3732
3733 r = parse_boolean(v);
3734 if (r < 0)
3735 log_unit_debug(u, "Failed to parse exported log extra fields bool %s, ignoring.", v);
3736 else
3737 u->exported_log_extra_fields = r;
3738
3739 continue;
3740
3741 } else if (streq(l, "exported-log-rate-limit-interval")) {
3742
3743 r = parse_boolean(v);
3744 if (r < 0)
3745 log_unit_debug(u, "Failed to parse exported log rate limit interval %s, ignoring.", v);
3746 else
3747 u->exported_log_ratelimit_interval = r;
3748
3749 continue;
3750
3751 } else if (streq(l, "exported-log-rate-limit-burst")) {
3752
3753 r = parse_boolean(v);
3754 if (r < 0)
3755 log_unit_debug(u, "Failed to parse exported log rate limit burst %s, ignoring.", v);
3756 else
3757 u->exported_log_ratelimit_burst = r;
3758
3759 continue;
3760
3761 } else if (STR_IN_SET(l, "cpu-usage-base", "cpuacct-usage-base")) {
3762
3763 r = safe_atou64(v, &u->cpu_usage_base);
3764 if (r < 0)
3765 log_unit_debug(u, "Failed to parse CPU usage base %s, ignoring.", v);
3766
3767 continue;
3768
3769 } else if (streq(l, "cpu-usage-last")) {
3770
3771 r = safe_atou64(v, &u->cpu_usage_last);
3772 if (r < 0)
3773 log_unit_debug(u, "Failed to read CPU usage last %s, ignoring.", v);
3774
3775 continue;
3776
3777 } else if (streq(l, "oom-kill-last")) {
3778
3779 r = safe_atou64(v, &u->oom_kill_last);
3780 if (r < 0)
3781 log_unit_debug(u, "Failed to read OOM kill last %s, ignoring.", v);
3782
3783 continue;
3784
3785 } else if (streq(l, "cgroup")) {
3786
3787 r = unit_set_cgroup_path(u, v);
3788 if (r < 0)
3789 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
3790
3791 (void) unit_watch_cgroup(u);
3792 (void) unit_watch_cgroup_memory(u);
3793
3794 continue;
3795 } else if (streq(l, "cgroup-realized")) {
3796 int b;
3797
3798 b = parse_boolean(v);
3799 if (b < 0)
3800 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
3801 else
3802 u->cgroup_realized = b;
3803
3804 continue;
3805
3806 } else if (streq(l, "cgroup-realized-mask")) {
3807
3808 r = cg_mask_from_string(v, &u->cgroup_realized_mask);
3809 if (r < 0)
3810 log_unit_debug(u, "Failed to parse cgroup-realized-mask %s, ignoring.", v);
3811 continue;
3812
3813 } else if (streq(l, "cgroup-enabled-mask")) {
3814
3815 r = cg_mask_from_string(v, &u->cgroup_enabled_mask);
3816 if (r < 0)
3817 log_unit_debug(u, "Failed to parse cgroup-enabled-mask %s, ignoring.", v);
3818 continue;
3819
3820 } else if (streq(l, "cgroup-invalidated-mask")) {
3821
3822 r = cg_mask_from_string(v, &u->cgroup_invalidated_mask);
3823 if (r < 0)
3824 log_unit_debug(u, "Failed to parse cgroup-invalidated-mask %s, ignoring.", v);
3825 continue;
3826
3827 } else if (streq(l, "ref-uid")) {
3828 uid_t uid;
3829
3830 r = parse_uid(v, &uid);
3831 if (r < 0)
3832 log_unit_debug(u, "Failed to parse referenced UID %s, ignoring.", v);
3833 else
3834 unit_ref_uid_gid(u, uid, GID_INVALID);
3835
3836 continue;
3837
3838 } else if (streq(l, "ref-gid")) {
3839 gid_t gid;
3840
3841 r = parse_gid(v, &gid);
3842 if (r < 0)
3843 log_unit_debug(u, "Failed to parse referenced GID %s, ignoring.", v);
3844 else
3845 unit_ref_uid_gid(u, UID_INVALID, gid);
3846
3847 continue;
3848
3849 } else if (streq(l, "ref")) {
3850
3851 r = strv_extend(&u->deserialized_refs, v);
3852 if (r < 0)
3853 return log_oom();
3854
3855 continue;
3856 } else if (streq(l, "invocation-id")) {
3857 sd_id128_t id;
3858
3859 r = sd_id128_from_string(v, &id);
3860 if (r < 0)
3861 log_unit_debug(u, "Failed to parse invocation id %s, ignoring.", v);
3862 else {
3863 r = unit_set_invocation_id(u, id);
3864 if (r < 0)
3865 log_unit_warning_errno(u, r, "Failed to set invocation ID for unit: %m");
3866 }
3867
3868 continue;
3869 } else if (streq(l, "freezer-state")) {
3870 FreezerState s;
3871
3872 s = freezer_state_from_string(v);
3873 if (s < 0)
3874 log_unit_debug(u, "Failed to deserialize freezer-state '%s', ignoring.", v);
3875 else
3876 u->freezer_state = s;
3877
3878 continue;
3879 }
3880
3881 /* Check if this is an IP accounting metric serialization field */
3882 m = string_table_lookup(ip_accounting_metric_field, ELEMENTSOF(ip_accounting_metric_field), l);
3883 if (m >= 0) {
3884 uint64_t c;
3885
3886 r = safe_atou64(v, &c);
3887 if (r < 0)
3888 log_unit_debug(u, "Failed to parse IP accounting value %s, ignoring.", v);
3889 else
3890 u->ip_accounting_extra[m] = c;
3891 continue;
3892 }
3893
3894 m = string_table_lookup(io_accounting_metric_field_base, ELEMENTSOF(io_accounting_metric_field_base), l);
3895 if (m >= 0) {
3896 uint64_t c;
3897
3898 r = safe_atou64(v, &c);
3899 if (r < 0)
3900 log_unit_debug(u, "Failed to parse IO accounting base value %s, ignoring.", v);
3901 else
3902 u->io_accounting_base[m] = c;
3903 continue;
3904 }
3905
3906 m = string_table_lookup(io_accounting_metric_field_last, ELEMENTSOF(io_accounting_metric_field_last), l);
3907 if (m >= 0) {
3908 uint64_t c;
3909
3910 r = safe_atou64(v, &c);
3911 if (r < 0)
3912 log_unit_debug(u, "Failed to parse IO accounting last value %s, ignoring.", v);
3913 else
3914 u->io_accounting_last[m] = c;
3915 continue;
3916 }
3917
3918 if (unit_can_serialize(u)) {
3919 r = exec_runtime_deserialize_compat(u, l, v, fds);
3920 if (r < 0) {
3921 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
3922 continue;
3923 }
3924
3925 /* Returns positive if key was handled by the call */
3926 if (r > 0)
3927 continue;
3928
3929 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
3930 if (r < 0)
3931 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
3932 }
3933 }
3934
3935 /* Versions before 228 did not carry a state change timestamp. In this case, take the current time. This is
3936 * useful, so that timeouts based on this timestamp don't trigger too early, and is in-line with the logic from
3937 * before 228 where the base for timeouts was not persistent across reboots. */
3938
3939 if (!dual_timestamp_is_set(&u->state_change_timestamp))
3940 dual_timestamp_get(&u->state_change_timestamp);
3941
3942 /* Let's make sure that everything that is deserialized also gets any potential new cgroup settings applied
3943 * after we are done. For that we invalidate anything already realized, so that we can realize it again. */
3944 unit_invalidate_cgroup(u, _CGROUP_MASK_ALL);
3945 unit_invalidate_cgroup_bpf(u);
3946
3947 return 0;
3948 }
3949
3950 int unit_deserialize_skip(FILE *f) {
3951 int r;
3952 assert(f);
3953
3954 /* Skip serialized data for this unit. We don't know what it is. */
3955
3956 for (;;) {
3957 _cleanup_free_ char *line = NULL;
3958 char *l;
3959
3960 r = read_line(f, LONG_LINE_MAX, &line);
3961 if (r < 0)
3962 return log_error_errno(r, "Failed to read serialization line: %m");
3963 if (r == 0)
3964 return 0;
3965
3966 l = strstrip(line);
3967
3968 /* End marker */
3969 if (isempty(l))
3970 return 1;
3971 }
3972 }
3973
3974 int unit_add_node_dependency(Unit *u, const char *what, UnitDependency dep, UnitDependencyMask mask) {
3975 _cleanup_free_ char *e = NULL;
3976 Unit *device;
3977 int r;
3978
3979 assert(u);
3980
3981 /* Adds in links to the device node that this unit is based on */
3982 if (isempty(what))
3983 return 0;
3984
3985 if (!is_device_path(what))
3986 return 0;
3987
3988 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
3989 if (!unit_type_supported(UNIT_DEVICE))
3990 return 0;
3991
3992 r = unit_name_from_path(what, ".device", &e);
3993 if (r < 0)
3994 return r;
3995
3996 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
3997 if (r < 0)
3998 return r;
3999
4000 if (dep == UNIT_REQUIRES && device_shall_be_bound_by(device, u))
4001 dep = UNIT_BINDS_TO;
4002
4003 return unit_add_two_dependencies(u, UNIT_AFTER,
4004 MANAGER_IS_SYSTEM(u->manager) ? dep : UNIT_WANTS,
4005 device, true, mask);
4006 }
4007
4008 int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask) {
4009 _cleanup_free_ char *escaped = NULL, *target = NULL;
4010 int r;
4011
4012 assert(u);
4013
4014 if (isempty(what))
4015 return 0;
4016
4017 if (!path_startswith(what, "/dev/"))
4018 return 0;
4019
4020 /* If we don't support devices, then also don't bother with blockdev@.target */
4021 if (!unit_type_supported(UNIT_DEVICE))
4022 return 0;
4023
4024 r = unit_name_path_escape(what, &escaped);
4025 if (r < 0)
4026 return r;
4027
4028 r = unit_name_build("blockdev", escaped, ".target", &target);
4029 if (r < 0)
4030 return r;
4031
4032 return unit_add_dependency_by_name(u, UNIT_AFTER, target, true, mask);
4033 }
4034
4035 int unit_coldplug(Unit *u) {
4036 int r = 0, q;
4037 char **i;
4038 Job *uj;
4039
4040 assert(u);
4041
4042 /* Make sure we don't enter a loop, when coldplugging recursively. */
4043 if (u->coldplugged)
4044 return 0;
4045
4046 u->coldplugged = true;
4047
4048 STRV_FOREACH(i, u->deserialized_refs) {
4049 q = bus_unit_track_add_name(u, *i);
4050 if (q < 0 && r >= 0)
4051 r = q;
4052 }
4053 u->deserialized_refs = strv_free(u->deserialized_refs);
4054
4055 if (UNIT_VTABLE(u)->coldplug) {
4056 q = UNIT_VTABLE(u)->coldplug(u);
4057 if (q < 0 && r >= 0)
4058 r = q;
4059 }
4060
4061 uj = u->job ?: u->nop_job;
4062 if (uj) {
4063 q = job_coldplug(uj);
4064 if (q < 0 && r >= 0)
4065 r = q;
4066 }
4067
4068 return r;
4069 }
4070
4071 void unit_catchup(Unit *u) {
4072 assert(u);
4073
4074 if (UNIT_VTABLE(u)->catchup)
4075 UNIT_VTABLE(u)->catchup(u);
4076 }
4077
4078 static bool fragment_mtime_newer(const char *path, usec_t mtime, bool path_masked) {
4079 struct stat st;
4080
4081 if (!path)
4082 return false;
4083
4084 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
4085 * are never out-of-date. */
4086 if (PATH_STARTSWITH_SET(path, "/proc", "/sys"))
4087 return false;
4088
4089 if (stat(path, &st) < 0)
4090 /* What, cannot access this anymore? */
4091 return true;
4092
4093 if (path_masked)
4094 /* For masked files check if they are still so */
4095 return !null_or_empty(&st);
4096 else
4097 /* For non-empty files check the mtime */
4098 return timespec_load(&st.st_mtim) > mtime;
4099
4100 return false;
4101 }
4102
4103 bool unit_need_daemon_reload(Unit *u) {
4104 _cleanup_strv_free_ char **t = NULL;
4105 char **path;
4106
4107 assert(u);
4108
4109 /* For unit files, we allow masking… */
4110 if (fragment_mtime_newer(u->fragment_path, u->fragment_mtime,
4111 u->load_state == UNIT_MASKED))
4112 return true;
4113
4114 /* Source paths should not be masked… */
4115 if (fragment_mtime_newer(u->source_path, u->source_mtime, false))
4116 return true;
4117
4118 if (u->load_state == UNIT_LOADED)
4119 (void) unit_find_dropin_paths(u, &t);
4120 if (!strv_equal(u->dropin_paths, t))
4121 return true;
4122
4123 /* … any drop-ins that are masked are simply omitted from the list. */
4124 STRV_FOREACH(path, u->dropin_paths)
4125 if (fragment_mtime_newer(*path, u->dropin_mtime, false))
4126 return true;
4127
4128 return false;
4129 }
4130
4131 void unit_reset_failed(Unit *u) {
4132 assert(u);
4133
4134 if (UNIT_VTABLE(u)->reset_failed)
4135 UNIT_VTABLE(u)->reset_failed(u);
4136
4137 ratelimit_reset(&u->start_ratelimit);
4138 u->start_limit_hit = false;
4139 }
4140
4141 Unit *unit_following(Unit *u) {
4142 assert(u);
4143
4144 if (UNIT_VTABLE(u)->following)
4145 return UNIT_VTABLE(u)->following(u);
4146
4147 return NULL;
4148 }
4149
4150 bool unit_stop_pending(Unit *u) {
4151 assert(u);
4152
4153 /* This call does check the current state of the unit. It's
4154 * hence useful to be called from state change calls of the
4155 * unit itself, where the state isn't updated yet. This is
4156 * different from unit_inactive_or_pending() which checks both
4157 * the current state and for a queued job. */
4158
4159 return unit_has_job_type(u, JOB_STOP);
4160 }
4161
4162 bool unit_inactive_or_pending(Unit *u) {
4163 assert(u);
4164
4165 /* Returns true if the unit is inactive or going down */
4166
4167 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
4168 return true;
4169
4170 if (unit_stop_pending(u))
4171 return true;
4172
4173 return false;
4174 }
4175
4176 bool unit_active_or_pending(Unit *u) {
4177 assert(u);
4178
4179 /* Returns true if the unit is active or going up */
4180
4181 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
4182 return true;
4183
4184 if (u->job &&
4185 IN_SET(u->job->type, JOB_START, JOB_RELOAD_OR_START, JOB_RESTART))
4186 return true;
4187
4188 return false;
4189 }
4190
4191 bool unit_will_restart_default(Unit *u) {
4192 assert(u);
4193
4194 return unit_has_job_type(u, JOB_START);
4195 }
4196
4197 bool unit_will_restart(Unit *u) {
4198 assert(u);
4199
4200 if (!UNIT_VTABLE(u)->will_restart)
4201 return false;
4202
4203 return UNIT_VTABLE(u)->will_restart(u);
4204 }
4205
4206 int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
4207 assert(u);
4208 assert(w >= 0 && w < _KILL_WHO_MAX);
4209 assert(SIGNAL_VALID(signo));
4210
4211 if (!UNIT_VTABLE(u)->kill)
4212 return -EOPNOTSUPP;
4213
4214 return UNIT_VTABLE(u)->kill(u, w, signo, error);
4215 }
4216
4217 static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
4218 _cleanup_set_free_ Set *pid_set = NULL;
4219 int r;
4220
4221 pid_set = set_new(NULL);
4222 if (!pid_set)
4223 return NULL;
4224
4225 /* Exclude the main/control pids from being killed via the cgroup */
4226 if (main_pid > 0) {
4227 r = set_put(pid_set, PID_TO_PTR(main_pid));
4228 if (r < 0)
4229 return NULL;
4230 }
4231
4232 if (control_pid > 0) {
4233 r = set_put(pid_set, PID_TO_PTR(control_pid));
4234 if (r < 0)
4235 return NULL;
4236 }
4237
4238 return TAKE_PTR(pid_set);
4239 }
4240
4241 int unit_kill_common(
4242 Unit *u,
4243 KillWho who,
4244 int signo,
4245 pid_t main_pid,
4246 pid_t control_pid,
4247 sd_bus_error *error) {
4248
4249 int r = 0;
4250 bool killed = false;
4251
4252 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
4253 if (main_pid < 0)
4254 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
4255 else if (main_pid == 0)
4256 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
4257 }
4258
4259 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
4260 if (control_pid < 0)
4261 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
4262 else if (control_pid == 0)
4263 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
4264 }
4265
4266 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
4267 if (control_pid > 0) {
4268 if (kill(control_pid, signo) < 0)
4269 r = -errno;
4270 else
4271 killed = true;
4272 }
4273
4274 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
4275 if (main_pid > 0) {
4276 if (kill(main_pid, signo) < 0)
4277 r = -errno;
4278 else
4279 killed = true;
4280 }
4281
4282 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
4283 _cleanup_set_free_ Set *pid_set = NULL;
4284 int q;
4285
4286 /* Exclude the main/control pids from being killed via the cgroup */
4287 pid_set = unit_pid_set(main_pid, control_pid);
4288 if (!pid_set)
4289 return -ENOMEM;
4290
4291 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, 0, pid_set, NULL, NULL);
4292 if (q < 0 && !IN_SET(q, -EAGAIN, -ESRCH, -ENOENT))
4293 r = q;
4294 else
4295 killed = true;
4296 }
4297
4298 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL))
4299 return -ESRCH;
4300
4301 return r;
4302 }
4303
4304 int unit_following_set(Unit *u, Set **s) {
4305 assert(u);
4306 assert(s);
4307
4308 if (UNIT_VTABLE(u)->following_set)
4309 return UNIT_VTABLE(u)->following_set(u, s);
4310
4311 *s = NULL;
4312 return 0;
4313 }
4314
4315 UnitFileState unit_get_unit_file_state(Unit *u) {
4316 int r;
4317
4318 assert(u);
4319
4320 if (u->unit_file_state < 0 && u->fragment_path) {
4321 r = unit_file_get_state(
4322 u->manager->unit_file_scope,
4323 NULL,
4324 u->id,
4325 &u->unit_file_state);
4326 if (r < 0)
4327 u->unit_file_state = UNIT_FILE_BAD;
4328 }
4329
4330 return u->unit_file_state;
4331 }
4332
4333 int unit_get_unit_file_preset(Unit *u) {
4334 assert(u);
4335
4336 if (u->unit_file_preset < 0 && u->fragment_path)
4337 u->unit_file_preset = unit_file_query_preset(
4338 u->manager->unit_file_scope,
4339 NULL,
4340 basename(u->fragment_path),
4341 NULL);
4342
4343 return u->unit_file_preset;
4344 }
4345
4346 Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target) {
4347 assert(ref);
4348 assert(source);
4349 assert(target);
4350
4351 if (ref->target)
4352 unit_ref_unset(ref);
4353
4354 ref->source = source;
4355 ref->target = target;
4356 LIST_PREPEND(refs_by_target, target->refs_by_target, ref);
4357 return target;
4358 }
4359
4360 void unit_ref_unset(UnitRef *ref) {
4361 assert(ref);
4362
4363 if (!ref->target)
4364 return;
4365
4366 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4367 * be unreferenced now. */
4368 unit_add_to_gc_queue(ref->target);
4369
4370 LIST_REMOVE(refs_by_target, ref->target->refs_by_target, ref);
4371 ref->source = ref->target = NULL;
4372 }
4373
4374 static int user_from_unit_name(Unit *u, char **ret) {
4375
4376 static const uint8_t hash_key[] = {
4377 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4378 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4379 };
4380
4381 _cleanup_free_ char *n = NULL;
4382 int r;
4383
4384 r = unit_name_to_prefix(u->id, &n);
4385 if (r < 0)
4386 return r;
4387
4388 if (valid_user_group_name(n, 0)) {
4389 *ret = TAKE_PTR(n);
4390 return 0;
4391 }
4392
4393 /* If we can't use the unit name as a user name, then let's hash it and use that */
4394 if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
4395 return -ENOMEM;
4396
4397 return 0;
4398 }
4399
4400 int unit_patch_contexts(Unit *u) {
4401 CGroupContext *cc;
4402 ExecContext *ec;
4403 unsigned i;
4404 int r;
4405
4406 assert(u);
4407
4408 /* Patch in the manager defaults into the exec and cgroup
4409 * contexts, _after_ the rest of the settings have been
4410 * initialized */
4411
4412 ec = unit_get_exec_context(u);
4413 if (ec) {
4414 /* This only copies in the ones that need memory */
4415 for (i = 0; i < _RLIMIT_MAX; i++)
4416 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
4417 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
4418 if (!ec->rlimit[i])
4419 return -ENOMEM;
4420 }
4421
4422 if (MANAGER_IS_USER(u->manager) &&
4423 !ec->working_directory) {
4424
4425 r = get_home_dir(&ec->working_directory);
4426 if (r < 0)
4427 return r;
4428
4429 /* Allow user services to run, even if the
4430 * home directory is missing */
4431 ec->working_directory_missing_ok = true;
4432 }
4433
4434 if (ec->private_devices)
4435 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
4436
4437 if (ec->protect_kernel_modules)
4438 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
4439
4440 if (ec->protect_kernel_logs)
4441 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
4442
4443 if (ec->protect_clock)
4444 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) | (UINT64_C(1) << CAP_WAKE_ALARM));
4445
4446 if (ec->dynamic_user) {
4447 if (!ec->user) {
4448 r = user_from_unit_name(u, &ec->user);
4449 if (r < 0)
4450 return r;
4451 }
4452
4453 if (!ec->group) {
4454 ec->group = strdup(ec->user);
4455 if (!ec->group)
4456 return -ENOMEM;
4457 }
4458
4459 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4460 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4461 * sandbox. */
4462
4463 ec->private_tmp = true;
4464 ec->remove_ipc = true;
4465 ec->protect_system = PROTECT_SYSTEM_STRICT;
4466 if (ec->protect_home == PROTECT_HOME_NO)
4467 ec->protect_home = PROTECT_HOME_READ_ONLY;
4468
4469 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4470 * them. */
4471 ec->no_new_privileges = true;
4472 ec->restrict_suid_sgid = true;
4473 }
4474 }
4475
4476 cc = unit_get_cgroup_context(u);
4477 if (cc && ec) {
4478
4479 if (ec->private_devices &&
4480 cc->device_policy == CGROUP_DEVICE_POLICY_AUTO)
4481 cc->device_policy = CGROUP_DEVICE_POLICY_CLOSED;
4482
4483 if (ec->root_image &&
4484 (cc->device_policy != CGROUP_DEVICE_POLICY_AUTO || cc->device_allow)) {
4485
4486 /* When RootImage= is specified, the following devices are touched. */
4487 r = cgroup_add_device_allow(cc, "/dev/loop-control", "rw");
4488 if (r < 0)
4489 return r;
4490
4491 r = cgroup_add_device_allow(cc, "block-loop", "rwm");
4492 if (r < 0)
4493 return r;
4494
4495 r = cgroup_add_device_allow(cc, "block-blkext", "rwm");
4496 if (r < 0)
4497 return r;
4498
4499 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices */
4500 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, "modprobe@loop.service", true, UNIT_DEPENDENCY_FILE);
4501 if (r < 0)
4502 return r;
4503 }
4504
4505 if (ec->protect_clock) {
4506 r = cgroup_add_device_allow(cc, "char-rtc", "r");
4507 if (r < 0)
4508 return r;
4509 }
4510 }
4511
4512 return 0;
4513 }
4514
4515 ExecContext *unit_get_exec_context(Unit *u) {
4516 size_t offset;
4517 assert(u);
4518
4519 if (u->type < 0)
4520 return NULL;
4521
4522 offset = UNIT_VTABLE(u)->exec_context_offset;
4523 if (offset <= 0)
4524 return NULL;
4525
4526 return (ExecContext*) ((uint8_t*) u + offset);
4527 }
4528
4529 KillContext *unit_get_kill_context(Unit *u) {
4530 size_t offset;
4531 assert(u);
4532
4533 if (u->type < 0)
4534 return NULL;
4535
4536 offset = UNIT_VTABLE(u)->kill_context_offset;
4537 if (offset <= 0)
4538 return NULL;
4539
4540 return (KillContext*) ((uint8_t*) u + offset);
4541 }
4542
4543 CGroupContext *unit_get_cgroup_context(Unit *u) {
4544 size_t offset;
4545
4546 if (u->type < 0)
4547 return NULL;
4548
4549 offset = UNIT_VTABLE(u)->cgroup_context_offset;
4550 if (offset <= 0)
4551 return NULL;
4552
4553 return (CGroupContext*) ((uint8_t*) u + offset);
4554 }
4555
4556 ExecRuntime *unit_get_exec_runtime(Unit *u) {
4557 size_t offset;
4558
4559 if (u->type < 0)
4560 return NULL;
4561
4562 offset = UNIT_VTABLE(u)->exec_runtime_offset;
4563 if (offset <= 0)
4564 return NULL;
4565
4566 return *(ExecRuntime**) ((uint8_t*) u + offset);
4567 }
4568
4569 static const char* unit_drop_in_dir(Unit *u, UnitWriteFlags flags) {
4570 assert(u);
4571
4572 if (UNIT_WRITE_FLAGS_NOOP(flags))
4573 return NULL;
4574
4575 if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
4576 return u->manager->lookup_paths.transient;
4577
4578 if (flags & UNIT_PERSISTENT)
4579 return u->manager->lookup_paths.persistent_control;
4580
4581 if (flags & UNIT_RUNTIME)
4582 return u->manager->lookup_paths.runtime_control;
4583
4584 return NULL;
4585 }
4586
4587 char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) {
4588 char *ret = NULL;
4589
4590 if (!s)
4591 return NULL;
4592
4593 /* Escapes the input string as requested. Returns the escaped string. If 'buf' is specified then the allocated
4594 * return buffer pointer is also written to *buf, except if no escaping was necessary, in which case *buf is
4595 * set to NULL, and the input pointer is returned as-is. This means the return value always contains a properly
4596 * escaped version, but *buf when passed only contains a pointer if an allocation was necessary. If *buf is
4597 * not specified, then the return value always needs to be freed. Callers can use this to optimize memory
4598 * allocations. */
4599
4600 if (flags & UNIT_ESCAPE_SPECIFIERS) {
4601 ret = specifier_escape(s);
4602 if (!ret)
4603 return NULL;
4604
4605 s = ret;
4606 }
4607
4608 if (flags & UNIT_ESCAPE_C) {
4609 char *a;
4610
4611 a = cescape(s);
4612 free(ret);
4613 if (!a)
4614 return NULL;
4615
4616 ret = a;
4617 }
4618
4619 if (buf) {
4620 *buf = ret;
4621 return ret ?: (char*) s;
4622 }
4623
4624 return ret ?: strdup(s);
4625 }
4626
4627 char* unit_concat_strv(char **l, UnitWriteFlags flags) {
4628 _cleanup_free_ char *result = NULL;
4629 size_t n = 0, allocated = 0;
4630 char **i;
4631
4632 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command lines in a
4633 * way suitable for ExecStart= stanzas */
4634
4635 STRV_FOREACH(i, l) {
4636 _cleanup_free_ char *buf = NULL;
4637 const char *p;
4638 size_t a;
4639 char *q;
4640
4641 p = unit_escape_setting(*i, flags, &buf);
4642 if (!p)
4643 return NULL;
4644
4645 a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */
4646 if (!GREEDY_REALLOC(result, allocated, n + a + 1))
4647 return NULL;
4648
4649 q = result + n;
4650 if (n > 0)
4651 *(q++) = ' ';
4652
4653 *(q++) = '"';
4654 q = stpcpy(q, p);
4655 *(q++) = '"';
4656
4657 n += a;
4658 }
4659
4660 if (!GREEDY_REALLOC(result, allocated, n + 1))
4661 return NULL;
4662
4663 result[n] = 0;
4664
4665 return TAKE_PTR(result);
4666 }
4667
4668 int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data) {
4669 _cleanup_free_ char *p = NULL, *q = NULL, *escaped = NULL;
4670 const char *dir, *wrapped;
4671 int r;
4672
4673 assert(u);
4674 assert(name);
4675 assert(data);
4676
4677 if (UNIT_WRITE_FLAGS_NOOP(flags))
4678 return 0;
4679
4680 data = unit_escape_setting(data, flags, &escaped);
4681 if (!data)
4682 return -ENOMEM;
4683
4684 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4685 * previous section header is the same */
4686
4687 if (flags & UNIT_PRIVATE) {
4688 if (!UNIT_VTABLE(u)->private_section)
4689 return -EINVAL;
4690
4691 if (!u->transient_file || u->last_section_private < 0)
4692 data = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
4693 else if (u->last_section_private == 0)
4694 data = strjoina("\n[", UNIT_VTABLE(u)->private_section, "]\n", data);
4695 } else {
4696 if (!u->transient_file || u->last_section_private < 0)
4697 data = strjoina("[Unit]\n", data);
4698 else if (u->last_section_private > 0)
4699 data = strjoina("\n[Unit]\n", data);
4700 }
4701
4702 if (u->transient_file) {
4703 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4704 * write to the transient unit file. */
4705 fputs(data, u->transient_file);
4706
4707 if (!endswith(data, "\n"))
4708 fputc('\n', u->transient_file);
4709
4710 /* Remember which section we wrote this entry to */
4711 u->last_section_private = !!(flags & UNIT_PRIVATE);
4712 return 0;
4713 }
4714
4715 dir = unit_drop_in_dir(u, flags);
4716 if (!dir)
4717 return -EINVAL;
4718
4719 wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
4720 "# or an equivalent operation. Do not edit.\n",
4721 data,
4722 "\n");
4723
4724 r = drop_in_file(dir, u->id, 50, name, &p, &q);
4725 if (r < 0)
4726 return r;
4727
4728 (void) mkdir_p_label(p, 0755);
4729
4730 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4731 * recreate the cache after every drop-in we write. */
4732 if (u->manager->unit_path_cache) {
4733 r = set_put_strdup(&u->manager->unit_path_cache, p);
4734 if (r < 0)
4735 return r;
4736 }
4737
4738 r = write_string_file_atomic_label(q, wrapped);
4739 if (r < 0)
4740 return r;
4741
4742 r = strv_push(&u->dropin_paths, q);
4743 if (r < 0)
4744 return r;
4745 q = NULL;
4746
4747 strv_uniq(u->dropin_paths);
4748
4749 u->dropin_mtime = now(CLOCK_REALTIME);
4750
4751 return 0;
4752 }
4753
4754 int unit_write_settingf(Unit *u, UnitWriteFlags flags, const char *name, const char *format, ...) {
4755 _cleanup_free_ char *p = NULL;
4756 va_list ap;
4757 int r;
4758
4759 assert(u);
4760 assert(name);
4761 assert(format);
4762
4763 if (UNIT_WRITE_FLAGS_NOOP(flags))
4764 return 0;
4765
4766 va_start(ap, format);
4767 r = vasprintf(&p, format, ap);
4768 va_end(ap);
4769
4770 if (r < 0)
4771 return -ENOMEM;
4772
4773 return unit_write_setting(u, flags, name, p);
4774 }
4775
4776 int unit_make_transient(Unit *u) {
4777 _cleanup_free_ char *path = NULL;
4778 FILE *f;
4779
4780 assert(u);
4781
4782 if (!UNIT_VTABLE(u)->can_transient)
4783 return -EOPNOTSUPP;
4784
4785 (void) mkdir_p_label(u->manager->lookup_paths.transient, 0755);
4786
4787 path = path_join(u->manager->lookup_paths.transient, u->id);
4788 if (!path)
4789 return -ENOMEM;
4790
4791 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4792 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4793
4794 RUN_WITH_UMASK(0022) {
4795 f = fopen(path, "we");
4796 if (!f)
4797 return -errno;
4798 }
4799
4800 safe_fclose(u->transient_file);
4801 u->transient_file = f;
4802
4803 free_and_replace(u->fragment_path, path);
4804
4805 u->source_path = mfree(u->source_path);
4806 u->dropin_paths = strv_free(u->dropin_paths);
4807 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
4808
4809 u->load_state = UNIT_STUB;
4810 u->load_error = 0;
4811 u->transient = true;
4812
4813 unit_add_to_dbus_queue(u);
4814 unit_add_to_gc_queue(u);
4815
4816 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4817 u->transient_file);
4818
4819 return 0;
4820 }
4821
4822 static int log_kill(pid_t pid, int sig, void *userdata) {
4823 _cleanup_free_ char *comm = NULL;
4824
4825 (void) get_process_comm(pid, &comm);
4826
4827 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4828 only, like for example systemd's own PAM stub process. */
4829 if (comm && comm[0] == '(')
4830 return 0;
4831
4832 log_unit_notice(userdata,
4833 "Killing process " PID_FMT " (%s) with signal SIG%s.",
4834 pid,
4835 strna(comm),
4836 signal_to_string(sig));
4837
4838 return 1;
4839 }
4840
4841 static int operation_to_signal(const KillContext *c, KillOperation k, bool *noteworthy) {
4842 assert(c);
4843
4844 switch (k) {
4845
4846 case KILL_TERMINATE:
4847 case KILL_TERMINATE_AND_LOG:
4848 *noteworthy = false;
4849 return c->kill_signal;
4850
4851 case KILL_RESTART:
4852 *noteworthy = false;
4853 return restart_kill_signal(c);
4854
4855 case KILL_KILL:
4856 *noteworthy = true;
4857 return c->final_kill_signal;
4858
4859 case KILL_WATCHDOG:
4860 *noteworthy = true;
4861 return c->watchdog_signal;
4862
4863 default:
4864 assert_not_reached("KillOperation unknown");
4865 }
4866 }
4867
4868 int unit_kill_context(
4869 Unit *u,
4870 KillContext *c,
4871 KillOperation k,
4872 pid_t main_pid,
4873 pid_t control_pid,
4874 bool main_pid_alien) {
4875
4876 bool wait_for_exit = false, send_sighup;
4877 cg_kill_log_func_t log_func = NULL;
4878 int sig, r;
4879
4880 assert(u);
4881 assert(c);
4882
4883 /* Kill the processes belonging to this unit, in preparation for shutting the unit down.
4884 * Returns > 0 if we killed something worth waiting for, 0 otherwise. */
4885
4886 if (c->kill_mode == KILL_NONE)
4887 return 0;
4888
4889 bool noteworthy;
4890 sig = operation_to_signal(c, k, &noteworthy);
4891 if (noteworthy)
4892 log_func = log_kill;
4893
4894 send_sighup =
4895 c->send_sighup &&
4896 IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
4897 sig != SIGHUP;
4898
4899 if (main_pid > 0) {
4900 if (log_func)
4901 log_func(main_pid, sig, u);
4902
4903 r = kill_and_sigcont(main_pid, sig);
4904 if (r < 0 && r != -ESRCH) {
4905 _cleanup_free_ char *comm = NULL;
4906 (void) get_process_comm(main_pid, &comm);
4907
4908 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
4909 } else {
4910 if (!main_pid_alien)
4911 wait_for_exit = true;
4912
4913 if (r != -ESRCH && send_sighup)
4914 (void) kill(main_pid, SIGHUP);
4915 }
4916 }
4917
4918 if (control_pid > 0) {
4919 if (log_func)
4920 log_func(control_pid, sig, u);
4921
4922 r = kill_and_sigcont(control_pid, sig);
4923 if (r < 0 && r != -ESRCH) {
4924 _cleanup_free_ char *comm = NULL;
4925 (void) get_process_comm(control_pid, &comm);
4926
4927 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
4928 } else {
4929 wait_for_exit = true;
4930
4931 if (r != -ESRCH && send_sighup)
4932 (void) kill(control_pid, SIGHUP);
4933 }
4934 }
4935
4936 if (u->cgroup_path &&
4937 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
4938 _cleanup_set_free_ Set *pid_set = NULL;
4939
4940 /* Exclude the main/control pids from being killed via the cgroup */
4941 pid_set = unit_pid_set(main_pid, control_pid);
4942 if (!pid_set)
4943 return -ENOMEM;
4944
4945 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
4946 sig,
4947 CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
4948 pid_set,
4949 log_func, u);
4950 if (r < 0) {
4951 if (!IN_SET(r, -EAGAIN, -ESRCH, -ENOENT))
4952 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
4953
4954 } else if (r > 0) {
4955
4956 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
4957 * we are running in a container or if this is a delegation unit, simply because cgroup
4958 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
4959 * of containers it can be confused easily by left-over directories in the cgroup — which
4960 * however should not exist in non-delegated units. On the unified hierarchy that's different,
4961 * there we get proper events. Hence rely on them. */
4962
4963 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0 ||
4964 (detect_container() == 0 && !unit_cgroup_delegate(u)))
4965 wait_for_exit = true;
4966
4967 if (send_sighup) {
4968 set_free(pid_set);
4969
4970 pid_set = unit_pid_set(main_pid, control_pid);
4971 if (!pid_set)
4972 return -ENOMEM;
4973
4974 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
4975 SIGHUP,
4976 CGROUP_IGNORE_SELF,
4977 pid_set,
4978 NULL, NULL);
4979 }
4980 }
4981 }
4982
4983 return wait_for_exit;
4984 }
4985
4986 int unit_require_mounts_for(Unit *u, const char *path, UnitDependencyMask mask) {
4987 _cleanup_free_ char *p = NULL;
4988 UnitDependencyInfo di;
4989 int r;
4990
4991 assert(u);
4992 assert(path);
4993
4994 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these paths in
4995 * the unit (from the path to the UnitDependencyInfo structure indicating how to the dependency came to
4996 * be). However, we build a prefix table for all possible prefixes so that new appearing mount units can easily
4997 * determine which units to make themselves a dependency of. */
4998
4999 if (!path_is_absolute(path))
5000 return -EINVAL;
5001
5002 r = hashmap_ensure_allocated(&u->requires_mounts_for, &path_hash_ops);
5003 if (r < 0)
5004 return r;
5005
5006 p = strdup(path);
5007 if (!p)
5008 return -ENOMEM;
5009
5010 path = path_simplify(p, true);
5011
5012 if (!path_is_normalized(path))
5013 return -EPERM;
5014
5015 if (hashmap_contains(u->requires_mounts_for, path))
5016 return 0;
5017
5018 di = (UnitDependencyInfo) {
5019 .origin_mask = mask
5020 };
5021
5022 r = hashmap_put(u->requires_mounts_for, path, di.data);
5023 if (r < 0)
5024 return r;
5025 p = NULL;
5026
5027 char prefix[strlen(path) + 1];
5028 PATH_FOREACH_PREFIX_MORE(prefix, path) {
5029 Set *x;
5030
5031 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
5032 if (!x) {
5033 _cleanup_free_ char *q = NULL;
5034
5035 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &path_hash_ops);
5036 if (r < 0)
5037 return r;
5038
5039 q = strdup(prefix);
5040 if (!q)
5041 return -ENOMEM;
5042
5043 x = set_new(NULL);
5044 if (!x)
5045 return -ENOMEM;
5046
5047 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
5048 if (r < 0) {
5049 set_free(x);
5050 return r;
5051 }
5052 q = NULL;
5053 }
5054
5055 r = set_put(x, u);
5056 if (r < 0)
5057 return r;
5058 }
5059
5060 return 0;
5061 }
5062
5063 int unit_setup_exec_runtime(Unit *u) {
5064 ExecRuntime **rt;
5065 size_t offset;
5066 Unit *other;
5067 Iterator i;
5068 void *v;
5069 int r;
5070
5071 offset = UNIT_VTABLE(u)->exec_runtime_offset;
5072 assert(offset > 0);
5073
5074 /* Check if there already is an ExecRuntime for this unit? */
5075 rt = (ExecRuntime**) ((uint8_t*) u + offset);
5076 if (*rt)
5077 return 0;
5078
5079 /* Try to get it from somebody else */
5080 HASHMAP_FOREACH_KEY(v, other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
5081 r = exec_runtime_acquire(u->manager, NULL, other->id, false, rt);
5082 if (r == 1)
5083 return 1;
5084 }
5085
5086 return exec_runtime_acquire(u->manager, unit_get_exec_context(u), u->id, true, rt);
5087 }
5088
5089 int unit_setup_dynamic_creds(Unit *u) {
5090 ExecContext *ec;
5091 DynamicCreds *dcreds;
5092 size_t offset;
5093
5094 assert(u);
5095
5096 offset = UNIT_VTABLE(u)->dynamic_creds_offset;
5097 assert(offset > 0);
5098 dcreds = (DynamicCreds*) ((uint8_t*) u + offset);
5099
5100 ec = unit_get_exec_context(u);
5101 assert(ec);
5102
5103 if (!ec->dynamic_user)
5104 return 0;
5105
5106 return dynamic_creds_acquire(dcreds, u->manager, ec->user, ec->group);
5107 }
5108
5109 bool unit_type_supported(UnitType t) {
5110 if (_unlikely_(t < 0))
5111 return false;
5112 if (_unlikely_(t >= _UNIT_TYPE_MAX))
5113 return false;
5114
5115 if (!unit_vtable[t]->supported)
5116 return true;
5117
5118 return unit_vtable[t]->supported();
5119 }
5120
5121 void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
5122 int r;
5123
5124 assert(u);
5125 assert(where);
5126
5127 r = dir_is_empty(where);
5128 if (r > 0 || r == -ENOTDIR)
5129 return;
5130 if (r < 0) {
5131 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
5132 return;
5133 }
5134
5135 log_struct(LOG_NOTICE,
5136 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5137 LOG_UNIT_ID(u),
5138 LOG_UNIT_INVOCATION_ID(u),
5139 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
5140 "WHERE=%s", where);
5141 }
5142
5143 int unit_fail_if_noncanonical(Unit *u, const char* where) {
5144 _cleanup_free_ char *canonical_where = NULL;
5145 int r;
5146
5147 assert(u);
5148 assert(where);
5149
5150 r = chase_symlinks(where, NULL, CHASE_NONEXISTENT, &canonical_where, NULL);
5151 if (r < 0) {
5152 log_unit_debug_errno(u, r, "Failed to check %s for symlinks, ignoring: %m", where);
5153 return 0;
5154 }
5155
5156 /* We will happily ignore a trailing slash (or any redundant slashes) */
5157 if (path_equal(where, canonical_where))
5158 return 0;
5159
5160 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
5161 log_struct(LOG_ERR,
5162 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5163 LOG_UNIT_ID(u),
5164 LOG_UNIT_INVOCATION_ID(u),
5165 LOG_UNIT_MESSAGE(u, "Mount path %s is not canonical (contains a symlink).", where),
5166 "WHERE=%s", where);
5167
5168 return -ELOOP;
5169 }
5170
5171 bool unit_is_pristine(Unit *u) {
5172 assert(u);
5173
5174 /* Check if the unit already exists or is already around,
5175 * in a number of different ways. Note that to cater for unit
5176 * types such as slice, we are generally fine with units that
5177 * are marked UNIT_LOADED even though nothing was actually
5178 * loaded, as those unit types don't require a file on disk. */
5179
5180 return !(!IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) ||
5181 u->fragment_path ||
5182 u->source_path ||
5183 !strv_isempty(u->dropin_paths) ||
5184 u->job ||
5185 u->merged_into);
5186 }
5187
5188 pid_t unit_control_pid(Unit *u) {
5189 assert(u);
5190
5191 if (UNIT_VTABLE(u)->control_pid)
5192 return UNIT_VTABLE(u)->control_pid(u);
5193
5194 return 0;
5195 }
5196
5197 pid_t unit_main_pid(Unit *u) {
5198 assert(u);
5199
5200 if (UNIT_VTABLE(u)->main_pid)
5201 return UNIT_VTABLE(u)->main_pid(u);
5202
5203 return 0;
5204 }
5205
5206 static void unit_unref_uid_internal(
5207 Unit *u,
5208 uid_t *ref_uid,
5209 bool destroy_now,
5210 void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
5211
5212 assert(u);
5213 assert(ref_uid);
5214 assert(_manager_unref_uid);
5215
5216 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5217 * gid_t are actually the same time, with the same validity rules.
5218 *
5219 * Drops a reference to UID/GID from a unit. */
5220
5221 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5222 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5223
5224 if (!uid_is_valid(*ref_uid))
5225 return;
5226
5227 _manager_unref_uid(u->manager, *ref_uid, destroy_now);
5228 *ref_uid = UID_INVALID;
5229 }
5230
5231 static void unit_unref_uid(Unit *u, bool destroy_now) {
5232 unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
5233 }
5234
5235 static void unit_unref_gid(Unit *u, bool destroy_now) {
5236 unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
5237 }
5238
5239 void unit_unref_uid_gid(Unit *u, bool destroy_now) {
5240 assert(u);
5241
5242 unit_unref_uid(u, destroy_now);
5243 unit_unref_gid(u, destroy_now);
5244 }
5245
5246 static int unit_ref_uid_internal(
5247 Unit *u,
5248 uid_t *ref_uid,
5249 uid_t uid,
5250 bool clean_ipc,
5251 int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
5252
5253 int r;
5254
5255 assert(u);
5256 assert(ref_uid);
5257 assert(uid_is_valid(uid));
5258 assert(_manager_ref_uid);
5259
5260 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5261 * are actually the same type, and have the same validity rules.
5262 *
5263 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5264 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5265 * drops to zero. */
5266
5267 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5268 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5269
5270 if (*ref_uid == uid)
5271 return 0;
5272
5273 if (uid_is_valid(*ref_uid)) /* Already set? */
5274 return -EBUSY;
5275
5276 r = _manager_ref_uid(u->manager, uid, clean_ipc);
5277 if (r < 0)
5278 return r;
5279
5280 *ref_uid = uid;
5281 return 1;
5282 }
5283
5284 static int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
5285 return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
5286 }
5287
5288 static int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
5289 return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
5290 }
5291
5292 static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
5293 int r = 0, q = 0;
5294
5295 assert(u);
5296
5297 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5298
5299 if (uid_is_valid(uid)) {
5300 r = unit_ref_uid(u, uid, clean_ipc);
5301 if (r < 0)
5302 return r;
5303 }
5304
5305 if (gid_is_valid(gid)) {
5306 q = unit_ref_gid(u, gid, clean_ipc);
5307 if (q < 0) {
5308 if (r > 0)
5309 unit_unref_uid(u, false);
5310
5311 return q;
5312 }
5313 }
5314
5315 return r > 0 || q > 0;
5316 }
5317
5318 int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
5319 ExecContext *c;
5320 int r;
5321
5322 assert(u);
5323
5324 c = unit_get_exec_context(u);
5325
5326 r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
5327 if (r < 0)
5328 return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5329
5330 return r;
5331 }
5332
5333 void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
5334 int r;
5335
5336 assert(u);
5337
5338 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5339 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5340 * objects when no service references the UID/GID anymore. */
5341
5342 r = unit_ref_uid_gid(u, uid, gid);
5343 if (r > 0)
5344 unit_add_to_dbus_queue(u);
5345 }
5346
5347 int unit_set_invocation_id(Unit *u, sd_id128_t id) {
5348 int r;
5349
5350 assert(u);
5351
5352 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
5353
5354 if (sd_id128_equal(u->invocation_id, id))
5355 return 0;
5356
5357 if (!sd_id128_is_null(u->invocation_id))
5358 (void) hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
5359
5360 if (sd_id128_is_null(id)) {
5361 r = 0;
5362 goto reset;
5363 }
5364
5365 r = hashmap_ensure_allocated(&u->manager->units_by_invocation_id, &id128_hash_ops);
5366 if (r < 0)
5367 goto reset;
5368
5369 u->invocation_id = id;
5370 sd_id128_to_string(id, u->invocation_id_string);
5371
5372 r = hashmap_put(u->manager->units_by_invocation_id, &u->invocation_id, u);
5373 if (r < 0)
5374 goto reset;
5375
5376 return 0;
5377
5378 reset:
5379 u->invocation_id = SD_ID128_NULL;
5380 u->invocation_id_string[0] = 0;
5381 return r;
5382 }
5383
5384 int unit_acquire_invocation_id(Unit *u) {
5385 sd_id128_t id;
5386 int r;
5387
5388 assert(u);
5389
5390 r = sd_id128_randomize(&id);
5391 if (r < 0)
5392 return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
5393
5394 r = unit_set_invocation_id(u, id);
5395 if (r < 0)
5396 return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
5397
5398 unit_add_to_dbus_queue(u);
5399 return 0;
5400 }
5401
5402 int unit_set_exec_params(Unit *u, ExecParameters *p) {
5403 int r;
5404
5405 assert(u);
5406 assert(p);
5407
5408 /* Copy parameters from manager */
5409 r = manager_get_effective_environment(u->manager, &p->environment);
5410 if (r < 0)
5411 return r;
5412
5413 p->confirm_spawn = manager_get_confirm_spawn(u->manager);
5414 p->cgroup_supported = u->manager->cgroup_supported;
5415 p->prefix = u->manager->prefix;
5416 SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
5417
5418 /* Copy parameters from unit */
5419 p->cgroup_path = u->cgroup_path;
5420 SET_FLAG(p->flags, EXEC_CGROUP_DELEGATE, unit_cgroup_delegate(u));
5421
5422 return 0;
5423 }
5424
5425 int unit_fork_helper_process(Unit *u, const char *name, pid_t *ret) {
5426 int r;
5427
5428 assert(u);
5429 assert(ret);
5430
5431 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5432 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5433
5434 (void) unit_realize_cgroup(u);
5435
5436 r = safe_fork(name, FORK_REOPEN_LOG, ret);
5437 if (r != 0)
5438 return r;
5439
5440 (void) default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
5441 (void) ignore_signals(SIGPIPE, -1);
5442
5443 (void) prctl(PR_SET_PDEATHSIG, SIGTERM);
5444
5445 if (u->cgroup_path) {
5446 r = cg_attach_everywhere(u->manager->cgroup_supported, u->cgroup_path, 0, NULL, NULL);
5447 if (r < 0) {
5448 log_unit_error_errno(u, r, "Failed to join unit cgroup %s: %m", u->cgroup_path);
5449 _exit(EXIT_CGROUP);
5450 }
5451 }
5452
5453 return 0;
5454 }
5455
5456 int unit_fork_and_watch_rm_rf(Unit *u, char **paths, pid_t *ret_pid) {
5457 pid_t pid;
5458 int r;
5459
5460 assert(u);
5461 assert(ret_pid);
5462
5463 r = unit_fork_helper_process(u, "(sd-rmrf)", &pid);
5464 if (r < 0)
5465 return r;
5466 if (r == 0) {
5467 int ret = EXIT_SUCCESS;
5468 char **i;
5469
5470 STRV_FOREACH(i, paths) {
5471 r = rm_rf(*i, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
5472 if (r < 0) {
5473 log_error_errno(r, "Failed to remove '%s': %m", *i);
5474 ret = EXIT_FAILURE;
5475 }
5476 }
5477
5478 _exit(ret);
5479 }
5480
5481 r = unit_watch_pid(u, pid, true);
5482 if (r < 0)
5483 return r;
5484
5485 *ret_pid = pid;
5486 return 0;
5487 }
5488
5489 static void unit_update_dependency_mask(Unit *u, UnitDependency d, Unit *other, UnitDependencyInfo di) {
5490 assert(u);
5491 assert(d >= 0);
5492 assert(d < _UNIT_DEPENDENCY_MAX);
5493 assert(other);
5494
5495 if (di.origin_mask == 0 && di.destination_mask == 0) {
5496 /* No bit set anymore, let's drop the whole entry */
5497 assert_se(hashmap_remove(u->dependencies[d], other));
5498 log_unit_debug(u, "lost dependency %s=%s", unit_dependency_to_string(d), other->id);
5499 } else
5500 /* Mask was reduced, let's update the entry */
5501 assert_se(hashmap_update(u->dependencies[d], other, di.data) == 0);
5502 }
5503
5504 void unit_remove_dependencies(Unit *u, UnitDependencyMask mask) {
5505 UnitDependency d;
5506
5507 assert(u);
5508
5509 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5510
5511 if (mask == 0)
5512 return;
5513
5514 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
5515 bool done;
5516
5517 do {
5518 UnitDependencyInfo di;
5519 Unit *other;
5520 Iterator i;
5521
5522 done = true;
5523
5524 HASHMAP_FOREACH_KEY(di.data, other, u->dependencies[d], i) {
5525 UnitDependency q;
5526
5527 if ((di.origin_mask & ~mask) == di.origin_mask)
5528 continue;
5529 di.origin_mask &= ~mask;
5530 unit_update_dependency_mask(u, d, other, di);
5531
5532 /* We updated the dependency from our unit to the other unit now. But most dependencies
5533 * imply a reverse dependency. Hence, let's delete that one too. For that we go through
5534 * all dependency types on the other unit and delete all those which point to us and
5535 * have the right mask set. */
5536
5537 for (q = 0; q < _UNIT_DEPENDENCY_MAX; q++) {
5538 UnitDependencyInfo dj;
5539
5540 dj.data = hashmap_get(other->dependencies[q], u);
5541 if ((dj.destination_mask & ~mask) == dj.destination_mask)
5542 continue;
5543 dj.destination_mask &= ~mask;
5544
5545 unit_update_dependency_mask(other, q, u, dj);
5546 }
5547
5548 unit_add_to_gc_queue(other);
5549
5550 done = false;
5551 break;
5552 }
5553
5554 } while (!done);
5555 }
5556 }
5557
5558 static int unit_get_invocation_path(Unit *u, char **ret) {
5559 char *p;
5560 int r;
5561
5562 assert(u);
5563 assert(ret);
5564
5565 if (MANAGER_IS_SYSTEM(u->manager))
5566 p = strjoin("/run/systemd/units/invocation:", u->id);
5567 else {
5568 _cleanup_free_ char *user_path = NULL;
5569 r = xdg_user_runtime_dir(&user_path, "/systemd/units/invocation:");
5570 if (r < 0)
5571 return r;
5572 p = strjoin(user_path, u->id);
5573 }
5574
5575 if (!p)
5576 return -ENOMEM;
5577
5578 *ret = p;
5579 return 0;
5580 }
5581
5582 static int unit_export_invocation_id(Unit *u) {
5583 _cleanup_free_ char *p = NULL;
5584 int r;
5585
5586 assert(u);
5587
5588 if (u->exported_invocation_id)
5589 return 0;
5590
5591 if (sd_id128_is_null(u->invocation_id))
5592 return 0;
5593
5594 r = unit_get_invocation_path(u, &p);
5595 if (r < 0)
5596 return log_unit_debug_errno(u, r, "Failed to get invocation path: %m");
5597
5598 r = symlink_atomic(u->invocation_id_string, p);
5599 if (r < 0)
5600 return log_unit_debug_errno(u, r, "Failed to create invocation ID symlink %s: %m", p);
5601
5602 u->exported_invocation_id = true;
5603 return 0;
5604 }
5605
5606 static int unit_export_log_level_max(Unit *u, const ExecContext *c) {
5607 const char *p;
5608 char buf[2];
5609 int r;
5610
5611 assert(u);
5612 assert(c);
5613
5614 if (u->exported_log_level_max)
5615 return 0;
5616
5617 if (c->log_level_max < 0)
5618 return 0;
5619
5620 assert(c->log_level_max <= 7);
5621
5622 buf[0] = '0' + c->log_level_max;
5623 buf[1] = 0;
5624
5625 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5626 r = symlink_atomic(buf, p);
5627 if (r < 0)
5628 return log_unit_debug_errno(u, r, "Failed to create maximum log level symlink %s: %m", p);
5629
5630 u->exported_log_level_max = true;
5631 return 0;
5632 }
5633
5634 static int unit_export_log_extra_fields(Unit *u, const ExecContext *c) {
5635 _cleanup_close_ int fd = -1;
5636 struct iovec *iovec;
5637 const char *p;
5638 char *pattern;
5639 le64_t *sizes;
5640 ssize_t n;
5641 size_t i;
5642 int r;
5643
5644 if (u->exported_log_extra_fields)
5645 return 0;
5646
5647 if (c->n_log_extra_fields <= 0)
5648 return 0;
5649
5650 sizes = newa(le64_t, c->n_log_extra_fields);
5651 iovec = newa(struct iovec, c->n_log_extra_fields * 2);
5652
5653 for (i = 0; i < c->n_log_extra_fields; i++) {
5654 sizes[i] = htole64(c->log_extra_fields[i].iov_len);
5655
5656 iovec[i*2] = IOVEC_MAKE(sizes + i, sizeof(le64_t));
5657 iovec[i*2+1] = c->log_extra_fields[i];
5658 }
5659
5660 p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
5661 pattern = strjoina(p, ".XXXXXX");
5662
5663 fd = mkostemp_safe(pattern);
5664 if (fd < 0)
5665 return log_unit_debug_errno(u, fd, "Failed to create extra fields file %s: %m", p);
5666
5667 n = writev(fd, iovec, c->n_log_extra_fields*2);
5668 if (n < 0) {
5669 r = log_unit_debug_errno(u, errno, "Failed to write extra fields: %m");
5670 goto fail;
5671 }
5672
5673 (void) fchmod(fd, 0644);
5674
5675 if (rename(pattern, p) < 0) {
5676 r = log_unit_debug_errno(u, errno, "Failed to rename extra fields file: %m");
5677 goto fail;
5678 }
5679
5680 u->exported_log_extra_fields = true;
5681 return 0;
5682
5683 fail:
5684 (void) unlink(pattern);
5685 return r;
5686 }
5687
5688 static int unit_export_log_ratelimit_interval(Unit *u, const ExecContext *c) {
5689 _cleanup_free_ char *buf = NULL;
5690 const char *p;
5691 int r;
5692
5693 assert(u);
5694 assert(c);
5695
5696 if (u->exported_log_ratelimit_interval)
5697 return 0;
5698
5699 if (c->log_ratelimit_interval_usec == 0)
5700 return 0;
5701
5702 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5703
5704 if (asprintf(&buf, "%" PRIu64, c->log_ratelimit_interval_usec) < 0)
5705 return log_oom();
5706
5707 r = symlink_atomic(buf, p);
5708 if (r < 0)
5709 return log_unit_debug_errno(u, r, "Failed to create log rate limit interval symlink %s: %m", p);
5710
5711 u->exported_log_ratelimit_interval = true;
5712 return 0;
5713 }
5714
5715 static int unit_export_log_ratelimit_burst(Unit *u, const ExecContext *c) {
5716 _cleanup_free_ char *buf = NULL;
5717 const char *p;
5718 int r;
5719
5720 assert(u);
5721 assert(c);
5722
5723 if (u->exported_log_ratelimit_burst)
5724 return 0;
5725
5726 if (c->log_ratelimit_burst == 0)
5727 return 0;
5728
5729 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5730
5731 if (asprintf(&buf, "%u", c->log_ratelimit_burst) < 0)
5732 return log_oom();
5733
5734 r = symlink_atomic(buf, p);
5735 if (r < 0)
5736 return log_unit_debug_errno(u, r, "Failed to create log rate limit burst symlink %s: %m", p);
5737
5738 u->exported_log_ratelimit_burst = true;
5739 return 0;
5740 }
5741
5742 void unit_export_state_files(Unit *u) {
5743 const ExecContext *c;
5744
5745 assert(u);
5746
5747 if (!u->id)
5748 return;
5749
5750 if (MANAGER_IS_TEST_RUN(u->manager))
5751 return;
5752
5753 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5754 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5755 * the IPC system itself and PID 1 also log to the journal.
5756 *
5757 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5758 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5759 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5760 * namespace at least.
5761 *
5762 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5763 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5764 * them with one. */
5765
5766 (void) unit_export_invocation_id(u);
5767
5768 if (!MANAGER_IS_SYSTEM(u->manager))
5769 return;
5770
5771 c = unit_get_exec_context(u);
5772 if (c) {
5773 (void) unit_export_log_level_max(u, c);
5774 (void) unit_export_log_extra_fields(u, c);
5775 (void) unit_export_log_ratelimit_interval(u, c);
5776 (void) unit_export_log_ratelimit_burst(u, c);
5777 }
5778 }
5779
5780 void unit_unlink_state_files(Unit *u) {
5781 const char *p;
5782
5783 assert(u);
5784
5785 if (!u->id)
5786 return;
5787
5788 /* Undoes the effect of unit_export_state() */
5789
5790 if (u->exported_invocation_id) {
5791 _cleanup_free_ char *invocation_path = NULL;
5792 int r = unit_get_invocation_path(u, &invocation_path);
5793 if (r >= 0) {
5794 (void) unlink(invocation_path);
5795 u->exported_invocation_id = false;
5796 }
5797 }
5798
5799 if (!MANAGER_IS_SYSTEM(u->manager))
5800 return;
5801
5802 if (u->exported_log_level_max) {
5803 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5804 (void) unlink(p);
5805
5806 u->exported_log_level_max = false;
5807 }
5808
5809 if (u->exported_log_extra_fields) {
5810 p = strjoina("/run/systemd/units/extra-fields:", u->id);
5811 (void) unlink(p);
5812
5813 u->exported_log_extra_fields = false;
5814 }
5815
5816 if (u->exported_log_ratelimit_interval) {
5817 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5818 (void) unlink(p);
5819
5820 u->exported_log_ratelimit_interval = false;
5821 }
5822
5823 if (u->exported_log_ratelimit_burst) {
5824 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5825 (void) unlink(p);
5826
5827 u->exported_log_ratelimit_burst = false;
5828 }
5829 }
5830
5831 int unit_prepare_exec(Unit *u) {
5832 int r;
5833
5834 assert(u);
5835
5836 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5837 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5838 r = bpf_firewall_load_custom(u);
5839 if (r < 0)
5840 return r;
5841
5842 /* Prepares everything so that we can fork of a process for this unit */
5843
5844 (void) unit_realize_cgroup(u);
5845
5846 if (u->reset_accounting) {
5847 (void) unit_reset_accounting(u);
5848 u->reset_accounting = false;
5849 }
5850
5851 unit_export_state_files(u);
5852
5853 r = unit_setup_exec_runtime(u);
5854 if (r < 0)
5855 return r;
5856
5857 r = unit_setup_dynamic_creds(u);
5858 if (r < 0)
5859 return r;
5860
5861 return 0;
5862 }
5863
5864 static bool ignore_leftover_process(const char *comm) {
5865 return comm && comm[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5866 }
5867
5868 int unit_log_leftover_process_start(pid_t pid, int sig, void *userdata) {
5869 _cleanup_free_ char *comm = NULL;
5870
5871 (void) get_process_comm(pid, &comm);
5872
5873 if (ignore_leftover_process(comm))
5874 return 0;
5875
5876 /* During start we print a warning */
5877
5878 log_unit_warning(userdata,
5879 "Found left-over process " PID_FMT " (%s) in control group while starting unit. Ignoring.\n"
5880 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5881 pid, strna(comm));
5882
5883 return 1;
5884 }
5885
5886 int unit_log_leftover_process_stop(pid_t pid, int sig, void *userdata) {
5887 _cleanup_free_ char *comm = NULL;
5888
5889 (void) get_process_comm(pid, &comm);
5890
5891 if (ignore_leftover_process(comm))
5892 return 0;
5893
5894 /* During stop we only print an informational message */
5895
5896 log_unit_info(userdata,
5897 "Unit process " PID_FMT " (%s) remains running after unit stopped.",
5898 pid, strna(comm));
5899
5900 return 1;
5901 }
5902
5903 int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func) {
5904 assert(u);
5905
5906 (void) unit_pick_cgroup_path(u);
5907
5908 if (!u->cgroup_path)
5909 return 0;
5910
5911 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, 0, 0, NULL, log_func, u);
5912 }
5913
5914 bool unit_needs_console(Unit *u) {
5915 ExecContext *ec;
5916 UnitActiveState state;
5917
5918 assert(u);
5919
5920 state = unit_active_state(u);
5921
5922 if (UNIT_IS_INACTIVE_OR_FAILED(state))
5923 return false;
5924
5925 if (UNIT_VTABLE(u)->needs_console)
5926 return UNIT_VTABLE(u)->needs_console(u);
5927
5928 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
5929 ec = unit_get_exec_context(u);
5930 if (!ec)
5931 return false;
5932
5933 return exec_context_may_touch_console(ec);
5934 }
5935
5936 const char *unit_label_path(const Unit *u) {
5937 const char *p;
5938
5939 assert(u);
5940
5941 /* Returns the file system path to use for MAC access decisions, i.e. the file to read the SELinux label off
5942 * when validating access checks. */
5943
5944 p = u->source_path ?: u->fragment_path;
5945 if (!p)
5946 return NULL;
5947
5948 /* If a unit is masked, then don't read the SELinux label of /dev/null, as that really makes no sense */
5949 if (path_equal(p, "/dev/null"))
5950 return NULL;
5951
5952 return p;
5953 }
5954
5955 int unit_pid_attachable(Unit *u, pid_t pid, sd_bus_error *error) {
5956 int r;
5957
5958 assert(u);
5959
5960 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
5961 * and not a kernel thread either */
5962
5963 /* First, a simple range check */
5964 if (!pid_is_valid(pid))
5965 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process identifier " PID_FMT " is not valid.", pid);
5966
5967 /* Some extra safety check */
5968 if (pid == 1 || pid == getpid_cached())
5969 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a manager process, refusing.", pid);
5970
5971 /* Don't even begin to bother with kernel threads */
5972 r = is_kernel_thread(pid);
5973 if (r == -ESRCH)
5974 return sd_bus_error_setf(error, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN, "Process with ID " PID_FMT " does not exist.", pid);
5975 if (r < 0)
5976 return sd_bus_error_set_errnof(error, r, "Failed to determine whether process " PID_FMT " is a kernel thread: %m", pid);
5977 if (r > 0)
5978 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a kernel thread, refusing.", pid);
5979
5980 return 0;
5981 }
5982
5983 void unit_log_success(Unit *u) {
5984 assert(u);
5985
5986 log_struct(LOG_INFO,
5987 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR,
5988 LOG_UNIT_ID(u),
5989 LOG_UNIT_INVOCATION_ID(u),
5990 LOG_UNIT_MESSAGE(u, "Succeeded."));
5991 }
5992
5993 void unit_log_failure(Unit *u, const char *result) {
5994 assert(u);
5995 assert(result);
5996
5997 log_struct(LOG_WARNING,
5998 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR,
5999 LOG_UNIT_ID(u),
6000 LOG_UNIT_INVOCATION_ID(u),
6001 LOG_UNIT_MESSAGE(u, "Failed with result '%s'.", result),
6002 "UNIT_RESULT=%s", result);
6003 }
6004
6005 void unit_log_skip(Unit *u, const char *result) {
6006 assert(u);
6007 assert(result);
6008
6009 log_struct(LOG_INFO,
6010 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR,
6011 LOG_UNIT_ID(u),
6012 LOG_UNIT_INVOCATION_ID(u),
6013 LOG_UNIT_MESSAGE(u, "Skipped due to '%s'.", result),
6014 "UNIT_RESULT=%s", result);
6015 }
6016
6017 void unit_log_process_exit(
6018 Unit *u,
6019 const char *kind,
6020 const char *command,
6021 bool success,
6022 int code,
6023 int status) {
6024
6025 int level;
6026
6027 assert(u);
6028 assert(kind);
6029
6030 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
6031 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
6032 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
6033 * WARNING. */
6034 if (success)
6035 level = LOG_DEBUG;
6036 else if (code == CLD_EXITED)
6037 level = LOG_NOTICE;
6038 else
6039 level = LOG_WARNING;
6040
6041 log_struct(level,
6042 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR,
6043 LOG_UNIT_MESSAGE(u, "%s exited, code=%s, status=%i/%s",
6044 kind,
6045 sigchld_code_to_string(code), status,
6046 strna(code == CLD_EXITED
6047 ? exit_status_to_string(status, EXIT_STATUS_FULL)
6048 : signal_to_string(status))),
6049 "EXIT_CODE=%s", sigchld_code_to_string(code),
6050 "EXIT_STATUS=%i", status,
6051 "COMMAND=%s", strna(command),
6052 LOG_UNIT_ID(u),
6053 LOG_UNIT_INVOCATION_ID(u));
6054 }
6055
6056 int unit_exit_status(Unit *u) {
6057 assert(u);
6058
6059 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
6060 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
6061 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
6062 * service process has exited abnormally (signal/coredump). */
6063
6064 if (!UNIT_VTABLE(u)->exit_status)
6065 return -EOPNOTSUPP;
6066
6067 return UNIT_VTABLE(u)->exit_status(u);
6068 }
6069
6070 int unit_failure_action_exit_status(Unit *u) {
6071 int r;
6072
6073 assert(u);
6074
6075 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
6076
6077 if (u->failure_action_exit_status >= 0)
6078 return u->failure_action_exit_status;
6079
6080 r = unit_exit_status(u);
6081 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6082 return 255;
6083
6084 return r;
6085 }
6086
6087 int unit_success_action_exit_status(Unit *u) {
6088 int r;
6089
6090 assert(u);
6091
6092 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
6093
6094 if (u->success_action_exit_status >= 0)
6095 return u->success_action_exit_status;
6096
6097 r = unit_exit_status(u);
6098 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
6099 return 255;
6100
6101 return r;
6102 }
6103
6104 int unit_test_trigger_loaded(Unit *u) {
6105 Unit *trigger;
6106
6107 /* Tests whether the unit to trigger is loaded */
6108
6109 trigger = UNIT_TRIGGER(u);
6110 if (!trigger)
6111 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6112 "Refusing to start, no unit to trigger.");
6113 if (trigger->load_state != UNIT_LOADED)
6114 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6115 "Refusing to start, unit %s to trigger not loaded.", trigger->id);
6116
6117 return 0;
6118 }
6119
6120 void unit_destroy_runtime_directory(Unit *u, const ExecContext *context) {
6121 if (context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO ||
6122 (context->runtime_directory_preserve_mode == EXEC_PRESERVE_RESTART && !unit_will_restart(u)))
6123 exec_context_destroy_runtime_directory(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
6124 }
6125
6126 int unit_clean(Unit *u, ExecCleanMask mask) {
6127 UnitActiveState state;
6128
6129 assert(u);
6130
6131 /* Special return values:
6132 *
6133 * -EOPNOTSUPP → cleaning not supported for this unit type
6134 * -EUNATCH → cleaning not defined for this resource type
6135 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6136 * a job queued or similar
6137 */
6138
6139 if (!UNIT_VTABLE(u)->clean)
6140 return -EOPNOTSUPP;
6141
6142 if (mask == 0)
6143 return -EUNATCH;
6144
6145 if (u->load_state != UNIT_LOADED)
6146 return -EBUSY;
6147
6148 if (u->job)
6149 return -EBUSY;
6150
6151 state = unit_active_state(u);
6152 if (!IN_SET(state, UNIT_INACTIVE))
6153 return -EBUSY;
6154
6155 return UNIT_VTABLE(u)->clean(u, mask);
6156 }
6157
6158 int unit_can_clean(Unit *u, ExecCleanMask *ret) {
6159 assert(u);
6160
6161 if (!UNIT_VTABLE(u)->clean ||
6162 u->load_state != UNIT_LOADED) {
6163 *ret = 0;
6164 return 0;
6165 }
6166
6167 /* When the clean() method is set, can_clean() really should be set too */
6168 assert(UNIT_VTABLE(u)->can_clean);
6169
6170 return UNIT_VTABLE(u)->can_clean(u, ret);
6171 }
6172
6173 bool unit_can_freeze(Unit *u) {
6174 assert(u);
6175
6176 if (UNIT_VTABLE(u)->can_freeze)
6177 return UNIT_VTABLE(u)->can_freeze(u);
6178
6179 return UNIT_VTABLE(u)->freeze;
6180 }
6181
6182 void unit_frozen(Unit *u) {
6183 assert(u);
6184
6185 u->freezer_state = FREEZER_FROZEN;
6186
6187 bus_unit_send_pending_freezer_message(u);
6188 }
6189
6190 void unit_thawed(Unit *u) {
6191 assert(u);
6192
6193 u->freezer_state = FREEZER_RUNNING;
6194
6195 bus_unit_send_pending_freezer_message(u);
6196 }
6197
6198 static int unit_freezer_action(Unit *u, FreezerAction action) {
6199 UnitActiveState s;
6200 int (*method)(Unit*);
6201 int r;
6202
6203 assert(u);
6204 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
6205
6206 method = action == FREEZER_FREEZE ? UNIT_VTABLE(u)->freeze : UNIT_VTABLE(u)->thaw;
6207 if (!method || !cg_freezer_supported())
6208 return -EOPNOTSUPP;
6209
6210 if (u->job)
6211 return -EBUSY;
6212
6213 if (u->load_state != UNIT_LOADED)
6214 return -EHOSTDOWN;
6215
6216 s = unit_active_state(u);
6217 if (s != UNIT_ACTIVE)
6218 return -EHOSTDOWN;
6219
6220 if (IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING))
6221 return -EALREADY;
6222
6223 r = method(u);
6224 if (r <= 0)
6225 return r;
6226
6227 return 1;
6228 }
6229
6230 int unit_freeze(Unit *u) {
6231 return unit_freezer_action(u, FREEZER_FREEZE);
6232 }
6233
6234 int unit_thaw(Unit *u) {
6235 return unit_freezer_action(u, FREEZER_THAW);
6236 }
6237
6238 /* Wrappers around low-level cgroup freezer operations common for service and scope units */
6239 int unit_freeze_vtable_common(Unit *u) {
6240 return unit_cgroup_freezer_action(u, FREEZER_FREEZE);
6241 }
6242
6243 int unit_thaw_vtable_common(Unit *u) {
6244 return unit_cgroup_freezer_action(u, FREEZER_THAW);
6245 }
6246
6247 static const char* const collect_mode_table[_COLLECT_MODE_MAX] = {
6248 [COLLECT_INACTIVE] = "inactive",
6249 [COLLECT_INACTIVE_OR_FAILED] = "inactive-or-failed",
6250 };
6251
6252 DEFINE_STRING_TABLE_LOOKUP(collect_mode, CollectMode);