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