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