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