]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.c
core: split out functions and definitions from execute.[ch] to credential.[ch]
[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"
602c74cf 23#include "credential.h"
4f5dd394
LP
24#include "dbus-unit.h"
25#include "dbus.h"
26#include "dropin.h"
88e4bfa6 27#include "env-util.h"
4f5dd394
LP
28#include "escape.h"
29#include "execute.h"
6a48d82f 30#include "fd-util.h"
a5c32cff 31#include "fileio-label.h"
ee228be1 32#include "fileio.h"
f97b34a6 33#include "format-util.h"
4b58153d 34#include "id128-util.h"
5cfa33e0 35#include "install.h"
2d3b784d 36#include "io-util.h"
0690160e 37#include "label-util.h"
4f5dd394
LP
38#include "load-dropin.h"
39#include "load-fragment.h"
40#include "log.h"
8c41640a 41#include "logarithm.h"
4f5dd394 42#include "macro.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
47261967
LP
1924 /* Let's hold off running start jobs for mount units when /proc/self/mountinfo monitor is ratelimited. */
1925 if (UNIT_VTABLE(u)->subsystem_ratelimited) {
1926 r = UNIT_VTABLE(u)->subsystem_ratelimited(u->manager);
1927 if (r < 0)
1928 return r;
1929 if (r > 0)
1930 return -EAGAIN;
1931 }
b161bc39 1932
5766aca8
LP
1933 /* If this is already started, then this will succeed. Note that this will even succeed if this unit
1934 * is not startable by the user. This is relied on to detect when we need to wait for units and when
1935 * waiting is finished. */
87f0e418
LP
1936 state = unit_active_state(u);
1937 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1938 return -EALREADY;
380dc8b0
LP
1939 if (state == UNIT_MAINTENANCE)
1940 return -EAGAIN;
87f0e418 1941
6bf0f408
LP
1942 /* Units that aren't loaded cannot be started */
1943 if (u->load_state != UNIT_LOADED)
1944 return -EINVAL;
1945
d4fd1cf2
LP
1946 /* Refuse starting scope units more than once */
1947 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_enter_timestamp))
1948 return -ESTALE;
1949
4e1ac54e 1950 /* If the conditions were unmet, don't do anything at all. If we already are activating this call might
5766aca8
LP
1951 * still be useful to speed up activation in case there is some hold-off time, but we don't want to
1952 * recheck the condition in that case. */
a82e5507 1953 if (state != UNIT_ACTIVATING &&
5af6aa58 1954 !unit_test_condition(u))
4e1ac54e 1955 return log_unit_debug_errno(u, SYNTHETIC_ERRNO(ECOMM), "Starting requested but condition not met. Not starting unit.");
52661efd 1956
59fccdc5
LP
1957 /* If the asserts failed, fail the entire job */
1958 if (state != UNIT_ACTIVATING &&
5766aca8
LP
1959 !unit_test_assert(u))
1960 return log_unit_notice_errno(u, SYNTHETIC_ERRNO(EPROTO), "Starting requested but asserts failed.");
59fccdc5 1961
5766aca8
LP
1962 /* Units of types that aren't supported cannot be started. Note that we do this test only after the
1963 * condition checks, so that we rather return condition check errors (which are usually not
1964 * considered a true failure) than "not supported" errors (which are considered a failure).
d11a7645 1965 */
96cf3ec9 1966 if (!unit_type_supported(u->type))
d11a7645
LP
1967 return -EOPNOTSUPP;
1968
5766aca8
LP
1969 /* Let's make sure that the deps really are in order before we start this. Normally the job engine
1970 * should have taken care of this already, but let's check this here again. After all, our
413e8650 1971 * dependencies might not be in effect anymore, due to a reload or due to an unmet condition. */
631b676b
LP
1972 if (!unit_verify_deps(u))
1973 return -ENOLINK;
1974
92ab323c 1975 /* Forward to the main object, if we aren't it. */
52990c2e
ZJS
1976 following = unit_following(u);
1977 if (following) {
f2341e0a 1978 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
48b92b37 1979 return unit_start(following, details);
92ab323c
LP
1980 }
1981
705578c3
MS
1982 /* Check our ability to start early so that failure conditions don't cause us to enter a busy loop. */
1983 if (UNIT_VTABLE(u)->can_start) {
1984 r = UNIT_VTABLE(u)->can_start(u);
ce2146f5
DDM
1985 if (r < 0)
1986 return r;
1987 }
1988
92ab323c
LP
1989 /* If it is stopped, but we cannot start it, then fail */
1990 if (!UNIT_VTABLE(u)->start)
1991 return -EBADR;
1992
5766aca8
LP
1993 /* We don't suppress calls to ->start() here when we are already starting, to allow this request to
1994 * be used as a "hurry up" call, for example when the unit is in some "auto restart" state where it
1995 * waits for a holdoff timer to elapse before it will start again. */
87f0e418 1996
c1e1601e 1997 unit_add_to_dbus_queue(u);
d9e45bc3 1998 unit_cgroup_freezer_action(u, FREEZER_THAW);
9e58ff9c 1999
48b92b37
LB
2000 if (!u->activation_details) /* Older details object wins */
2001 u->activation_details = activation_details_ref(details);
2002
d1a34ae9 2003 return UNIT_VTABLE(u)->start(u);
87f0e418
LP
2004}
2005
2006bool unit_can_start(Unit *u) {
2007 assert(u);
2008
8ff4d2ab
LP
2009 if (u->load_state != UNIT_LOADED)
2010 return false;
2011
96cf3ec9 2012 if (!unit_type_supported(u->type))
8ff4d2ab
LP
2013 return false;
2014
d4fd1cf2
LP
2015 /* Scope units may be started only once */
2016 if (UNIT_VTABLE(u)->once_only && dual_timestamp_is_set(&u->inactive_exit_timestamp))
2017 return false;
2018
87f0e418
LP
2019 return !!UNIT_VTABLE(u)->start;
2020}
2021
2528a7a6
LP
2022bool unit_can_isolate(Unit *u) {
2023 assert(u);
2024
2025 return unit_can_start(u) &&
ac155bb8 2026 u->allow_isolate;
2528a7a6
LP
2027}
2028
87f0e418
LP
2029/* Errors:
2030 * -EBADR: This unit type does not support stopping.
2031 * -EALREADY: Unit is already stopped.
2032 * -EAGAIN: An operation is already in progress. Retry later.
2033 */
2034int unit_stop(Unit *u) {
2035 UnitActiveState state;
92ab323c 2036 Unit *following;
87f0e418
LP
2037
2038 assert(u);
2039
87f0e418 2040 state = unit_active_state(u);
fdf20a31 2041 if (UNIT_IS_INACTIVE_OR_FAILED(state))
87f0e418
LP
2042 return -EALREADY;
2043
0faacd47
LP
2044 following = unit_following(u);
2045 if (following) {
f2341e0a 2046 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
92ab323c
LP
2047 return unit_stop(following);
2048 }
2049
7898b0cf
LP
2050 if (!UNIT_VTABLE(u)->stop)
2051 return -EBADR;
2052
c1e1601e 2053 unit_add_to_dbus_queue(u);
d9e45bc3 2054 unit_cgroup_freezer_action(u, FREEZER_THAW);
9e58ff9c 2055
d1a34ae9 2056 return UNIT_VTABLE(u)->stop(u);
87f0e418
LP
2057}
2058
f5869324
LP
2059bool unit_can_stop(Unit *u) {
2060 assert(u);
2061
39c79477
ZJS
2062 /* Note: if we return true here, it does not mean that the unit may be successfully stopped.
2063 * Extrinsic units follow external state and they may stop following external state changes
2064 * (hence we return true here), but an attempt to do this through the manager will fail. */
2065
96cf3ec9 2066 if (!unit_type_supported(u->type))
f5869324
LP
2067 return false;
2068
2069 if (u->perpetual)
2070 return false;
2071
2072 return !!UNIT_VTABLE(u)->stop;
2073}
2074
87f0e418
LP
2075/* Errors:
2076 * -EBADR: This unit type does not support reloading.
2077 * -ENOEXEC: Unit is not started.
2078 * -EAGAIN: An operation is already in progress. Retry later.
2079 */
2080int unit_reload(Unit *u) {
2081 UnitActiveState state;
92ab323c 2082 Unit *following;
87f0e418
LP
2083
2084 assert(u);
2085
ac155bb8 2086 if (u->load_state != UNIT_LOADED)
6124958c
LP
2087 return -EINVAL;
2088
87f0e418
LP
2089 if (!unit_can_reload(u))
2090 return -EBADR;
2091
2092 state = unit_active_state(u);
e364ad06 2093 if (state == UNIT_RELOADING)
6255af75 2094 return -EAGAIN;
87f0e418 2095
d85ff944
YW
2096 if (state != UNIT_ACTIVE)
2097 return log_unit_warning_errno(u, SYNTHETIC_ERRNO(ENOEXEC), "Unit cannot be reloaded because it is inactive.");
87f0e418 2098
e48614c4
ZJS
2099 following = unit_following(u);
2100 if (following) {
f2341e0a 2101 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
92ab323c
LP
2102 return unit_reload(following);
2103 }
2104
c1e1601e 2105 unit_add_to_dbus_queue(u);
82a2b6bb 2106
f54bcca5
JR
2107 if (!UNIT_VTABLE(u)->reload) {
2108 /* Unit doesn't have a reload function, but we need to propagate the reload anyway */
96b09de5 2109 unit_notify(u, unit_active_state(u), unit_active_state(u), /* reload_success = */ true);
f54bcca5
JR
2110 return 0;
2111 }
2112
d9e45bc3
MS
2113 unit_cgroup_freezer_action(u, FREEZER_THAW);
2114
d1a34ae9 2115 return UNIT_VTABLE(u)->reload(u);
87f0e418
LP
2116}
2117
2118bool unit_can_reload(Unit *u) {
2119 assert(u);
2120
f54bcca5
JR
2121 if (UNIT_VTABLE(u)->can_reload)
2122 return UNIT_VTABLE(u)->can_reload(u);
87f0e418 2123
15ed3c3a 2124 if (unit_has_dependency(u, UNIT_ATOM_PROPAGATES_RELOAD_TO, NULL))
87f0e418
LP
2125 return true;
2126
f54bcca5 2127 return UNIT_VTABLE(u)->reload;
87f0e418
LP
2128}
2129
a3c1168a 2130bool unit_is_unneeded(Unit *u) {
15ed3c3a 2131 Unit *other;
f3bff0eb
LP
2132 assert(u);
2133
ac155bb8 2134 if (!u->stop_when_unneeded)
a3c1168a 2135 return false;
f3bff0eb 2136
a3c1168a 2137 /* Don't clean up while the unit is transitioning or is even inactive. */
116654d2 2138 if (unit_active_state(u) != UNIT_ACTIVE)
a3c1168a
LP
2139 return false;
2140 if (u->job)
2141 return false;
f3bff0eb 2142
15ed3c3a 2143 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_PINS_STOP_WHEN_UNNEEDED) {
fda09318 2144 /* If a dependent unit has a job queued, is active or transitioning, or is marked for
a3c1168a 2145 * restart, then don't clean this one up. */
b81884e7 2146
15ed3c3a
LP
2147 if (other->job)
2148 return false;
a3c1168a 2149
15ed3c3a
LP
2150 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
2151 return false;
a3c1168a 2152
15ed3c3a
LP
2153 if (unit_will_restart(other))
2154 return false;
bea355da
LP
2155 }
2156
a3c1168a
LP
2157 return true;
2158}
f3bff0eb 2159
0bc488c9
LP
2160bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit) {
2161 Unit *other;
2162
2163 assert(u);
2164
2165 /* Checks if the unit needs to be started because it currently is not running, but some other unit
2166 * that is active declared an Uphold= dependencies on it */
2167
2168 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(u)) || u->job) {
2169 if (ret_culprit)
2170 *ret_culprit = NULL;
2171 return false;
2172 }
2173
2174 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_START_STEADILY) {
2175 if (other->job)
2176 continue;
2177
2178 if (UNIT_IS_ACTIVE_OR_RELOADING(unit_active_state(other))) {
2179 if (ret_culprit)
2180 *ret_culprit = other;
2181 return true;
2182 }
2183 }
2184
2185 if (ret_culprit)
2186 *ret_culprit = NULL;
2187 return false;
2188}
2189
56c59592
LP
2190bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit) {
2191 Unit *other;
2192
2193 assert(u);
2194
2195 /* Checks whether this unit is bound to another unit that is inactive, i.e. whether we should stop
7802194a 2196 * because the other unit is down. */
56c59592
LP
2197
2198 if (unit_active_state(u) != UNIT_ACTIVE || u->job) {
2199 /* Don't clean up while the unit is transitioning or is even inactive. */
2200 if (ret_culprit)
2201 *ret_culprit = NULL;
2202 return false;
2203 }
2204
2205 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_CANNOT_BE_ACTIVE_WITHOUT) {
2206 if (other->job)
2207 continue;
2208
2209 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
3da36106 2210 if (ret_culprit)
56c59592
LP
2211 *ret_culprit = other;
2212
2213 return true;
2214 }
2215 }
2216
2217 if (ret_culprit)
2218 *ret_culprit = NULL;
2219 return false;
2220}
2221
a3c1168a 2222static void check_unneeded_dependencies(Unit *u) {
15ed3c3a 2223 Unit *other;
a3c1168a
LP
2224 assert(u);
2225
2226 /* Add all units this unit depends on to the queue that processes StopWhenUnneeded= behaviour. */
2227
15ed3c3a
LP
2228 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_STOP_WHEN_UNNEEDED_QUEUE)
2229 unit_submit_to_stop_when_unneeded_queue(other);
f3bff0eb
LP
2230}
2231
0bc488c9
LP
2232static void check_uphold_dependencies(Unit *u) {
2233 Unit *other;
2234 assert(u);
2235
2236 /* Add all units this unit depends on to the queue that processes Uphold= behaviour. */
2237
2238 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_START_WHEN_UPHELD_QUEUE)
2239 unit_submit_to_start_when_upheld_queue(other);
2240}
2241
56c59592 2242static void check_bound_by_dependencies(Unit *u) {
ff502445 2243 Unit *other;
ff502445
LP
2244 assert(u);
2245
56c59592 2246 /* Add all units this unit depends on to the queue that processes BindsTo= stop behaviour. */
ff502445 2247
56c59592
LP
2248 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_ADD_CANNOT_BE_ACTIVE_WITHOUT_QUEUE)
2249 unit_submit_to_stop_when_bound_queue(other);
ff502445
LP
2250}
2251
87f0e418 2252static void retroactively_start_dependencies(Unit *u) {
87f0e418
LP
2253 Unit *other;
2254
2255 assert(u);
2256 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
2257
15ed3c3a
LP
2258 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_RETROACTIVE_START_REPLACE) /* Requires= + BindsTo= */
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_REPLACE, NULL, NULL, NULL);
b81884e7 2262
15ed3c3a
LP
2263 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_RETROACTIVE_START_FAIL) /* Wants= */
2264 if (!unit_has_dependency(u, UNIT_ATOM_AFTER, other) &&
b81884e7 2265 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
50cbaba4 2266 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL, NULL);
87f0e418 2267
15ed3c3a 2268 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_RETROACTIVE_STOP_ON_START) /* Conflicts= (and inverse) */
b81884e7 2269 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
50cbaba4 2270 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
87f0e418
LP
2271}
2272
2273static void retroactively_stop_dependencies(Unit *u) {
87f0e418
LP
2274 Unit *other;
2275
2276 assert(u);
2277 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
2278
b81884e7 2279 /* Pull down units which are bound to us recursively if enabled */
15ed3c3a 2280 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_RETROACTIVE_STOP_ON_STOP) /* BoundBy= */
b81884e7 2281 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
50cbaba4 2282 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL, NULL);
cd0504d0
MS
2283}
2284
294446dc
LP
2285void unit_start_on_failure(
2286 Unit *u,
2287 const char *dependency_name,
2288 UnitDependencyAtom atom,
2289 JobMode job_mode) {
2290
82acee14 2291 int n_jobs = -1;
c0daa706 2292 Unit *other;
7f66b026 2293 int r;
c0daa706
LP
2294
2295 assert(u);
294446dc
LP
2296 assert(dependency_name);
2297 assert(IN_SET(atom, UNIT_ATOM_ON_SUCCESS, UNIT_ATOM_ON_FAILURE));
2298
2299 /* Act on OnFailure= and OnSuccess= dependencies */
c0daa706 2300
294446dc 2301 UNIT_FOREACH_DEPENDENCY(other, u, atom) {
7f66b026 2302 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
222ae6a8 2303
82acee14 2304 if (n_jobs < 0) {
294446dc 2305 log_unit_info(u, "Triggering %s dependencies.", dependency_name);
82acee14 2306 n_jobs = 0;
15ed3c3a
LP
2307 }
2308
95c81c55 2309 r = manager_add_job(u->manager, JOB_START, other, job_mode, NULL, &error, NULL);
c1b6628d 2310 if (r < 0)
294446dc
LP
2311 log_unit_warning_errno(
2312 u, r, "Failed to enqueue %s job, ignoring: %s",
2313 dependency_name, bus_error_message(&error, r));
82acee14 2314 n_jobs ++;
222ae6a8 2315 }
294446dc 2316
82acee14 2317 if (n_jobs >= 0)
c0f86d66 2318 log_unit_debug(u, "Triggering %s dependencies done (%i %s).",
82acee14 2319 dependency_name, n_jobs, n_jobs == 1 ? "job" : "jobs");
c0daa706
LP
2320}
2321
3ecaa09b
LP
2322void unit_trigger_notify(Unit *u) {
2323 Unit *other;
3ecaa09b
LP
2324
2325 assert(u);
2326
15ed3c3a 2327 UNIT_FOREACH_DEPENDENCY(other, u, UNIT_ATOM_TRIGGERED_BY)
3ecaa09b
LP
2328 if (UNIT_VTABLE(other)->trigger_notify)
2329 UNIT_VTABLE(other)->trigger_notify(other, u);
2330}
2331
37109b85
ZJS
2332static int raise_level(int log_level, bool condition_info, bool condition_notice) {
2333 if (condition_notice && log_level > LOG_NOTICE)
2334 return LOG_NOTICE;
2335 if (condition_info && log_level > LOG_INFO)
2336 return LOG_INFO;
2337 return log_level;
2338}
2339
915b1d01 2340static int unit_log_resources(Unit *u) {
bc40a20e
LP
2341 struct iovec iovec[1 + _CGROUP_IP_ACCOUNTING_METRIC_MAX + _CGROUP_IO_ACCOUNTING_METRIC_MAX + 4];
2342 bool any_traffic = false, have_ip_accounting = false, any_io = false, have_io_accounting = false;
2343 _cleanup_free_ char *igress = NULL, *egress = NULL, *rr = NULL, *wr = NULL;
162392b7 2344 int log_level = LOG_DEBUG; /* May be raised if resources consumed over a threshold */
915b1d01 2345 size_t n_message_parts = 0, n_iovec = 0;
bc40a20e 2346 char* message_parts[1 + 2 + 2 + 1], *t;
915b1d01 2347 nsec_t nsec = NSEC_INFINITY;
915b1d01
LP
2348 int r;
2349 const char* const ip_fields[_CGROUP_IP_ACCOUNTING_METRIC_MAX] = {
2350 [CGROUP_IP_INGRESS_BYTES] = "IP_METRIC_INGRESS_BYTES",
2351 [CGROUP_IP_INGRESS_PACKETS] = "IP_METRIC_INGRESS_PACKETS",
2352 [CGROUP_IP_EGRESS_BYTES] = "IP_METRIC_EGRESS_BYTES",
2353 [CGROUP_IP_EGRESS_PACKETS] = "IP_METRIC_EGRESS_PACKETS",
2354 };
bc40a20e
LP
2355 const char* const io_fields[_CGROUP_IO_ACCOUNTING_METRIC_MAX] = {
2356 [CGROUP_IO_READ_BYTES] = "IO_METRIC_READ_BYTES",
2357 [CGROUP_IO_WRITE_BYTES] = "IO_METRIC_WRITE_BYTES",
2358 [CGROUP_IO_READ_OPERATIONS] = "IO_METRIC_READ_OPERATIONS",
2359 [CGROUP_IO_WRITE_OPERATIONS] = "IO_METRIC_WRITE_OPERATIONS",
2360 };
915b1d01
LP
2361
2362 assert(u);
2363
2364 /* Invoked whenever a unit enters failed or dead state. Logs information about consumed resources if resource
2365 * accounting was enabled for a unit. It does this in two ways: a friendly human readable string with reduced
2366 * information and the complete data in structured fields. */
2367
2368 (void) unit_get_cpu_usage(u, &nsec);
2369 if (nsec != NSEC_INFINITY) {
915b1d01
LP
2370 /* Format the CPU time for inclusion in the structured log message */
2371 if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) {
2372 r = log_oom();
2373 goto finish;
2374 }
2375 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2376
2377 /* Format the CPU time for inclusion in the human language message string */
5291f26d 2378 t = strjoin("consumed ", FORMAT_TIMESPAN(nsec / NSEC_PER_USEC, USEC_PER_MSEC), " CPU time");
915b1d01
LP
2379 if (!t) {
2380 r = log_oom();
2381 goto finish;
2382 }
2383
2384 message_parts[n_message_parts++] = t;
37109b85
ZJS
2385
2386 log_level = raise_level(log_level,
ef6bb4dd
CG
2387 nsec > MENTIONWORTHY_CPU_NSEC,
2388 nsec > NOTICEWORTHY_CPU_NSEC);
915b1d01
LP
2389 }
2390
bc40a20e 2391 for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
bc40a20e
LP
2392 uint64_t value = UINT64_MAX;
2393
2394 assert(io_fields[k]);
2395
2396 (void) unit_get_io_accounting(u, k, k > 0, &value);
2397 if (value == UINT64_MAX)
2398 continue;
2399
2400 have_io_accounting = true;
2401 if (value > 0)
2402 any_io = true;
2403
2404 /* Format IO accounting data for inclusion in the structured log message */
2405 if (asprintf(&t, "%s=%" PRIu64, io_fields[k], value) < 0) {
2406 r = log_oom();
2407 goto finish;
2408 }
2409 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2410
2411 /* Format the IO accounting data for inclusion in the human language message string, but only
2412 * for the bytes counters (and not for the operations counters) */
2413 if (k == CGROUP_IO_READ_BYTES) {
2414 assert(!rr);
2b59bf51 2415 rr = strjoin("read ", strna(FORMAT_BYTES(value)), " from disk");
bc40a20e
LP
2416 if (!rr) {
2417 r = log_oom();
2418 goto finish;
2419 }
2420 } else if (k == CGROUP_IO_WRITE_BYTES) {
2421 assert(!wr);
2b59bf51 2422 wr = strjoin("written ", strna(FORMAT_BYTES(value)), " to disk");
bc40a20e
LP
2423 if (!wr) {
2424 r = log_oom();
2425 goto finish;
2426 }
2427 }
37109b85
ZJS
2428
2429 if (IN_SET(k, CGROUP_IO_READ_BYTES, CGROUP_IO_WRITE_BYTES))
2430 log_level = raise_level(log_level,
2431 value > MENTIONWORTHY_IO_BYTES,
2432 value > NOTICEWORTHY_IO_BYTES);
bc40a20e
LP
2433 }
2434
2435 if (have_io_accounting) {
2436 if (any_io) {
2437 if (rr)
2438 message_parts[n_message_parts++] = TAKE_PTR(rr);
2439 if (wr)
2440 message_parts[n_message_parts++] = TAKE_PTR(wr);
2441
2442 } else {
2443 char *k;
2444
2445 k = strdup("no IO");
2446 if (!k) {
2447 r = log_oom();
2448 goto finish;
2449 }
2450
2451 message_parts[n_message_parts++] = k;
2452 }
2453 }
2454
12375b95 2455 for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
915b1d01
LP
2456 uint64_t value = UINT64_MAX;
2457
2458 assert(ip_fields[m]);
2459
2460 (void) unit_get_ip_accounting(u, m, &value);
2461 if (value == UINT64_MAX)
2462 continue;
82044702
LP
2463
2464 have_ip_accounting = true;
a87b1faa
LP
2465 if (value > 0)
2466 any_traffic = true;
915b1d01
LP
2467
2468 /* Format IP accounting data for inclusion in the structured log message */
2469 if (asprintf(&t, "%s=%" PRIu64, ip_fields[m], value) < 0) {
2470 r = log_oom();
2471 goto finish;
2472 }
2473 iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
2474
2475 /* Format the IP accounting data for inclusion in the human language message string, but only for the
2476 * bytes counters (and not for the packets counters) */
a87b1faa
LP
2477 if (m == CGROUP_IP_INGRESS_BYTES) {
2478 assert(!igress);
2b59bf51 2479 igress = strjoin("received ", strna(FORMAT_BYTES(value)), " IP traffic");
a87b1faa
LP
2480 if (!igress) {
2481 r = log_oom();
2482 goto finish;
2483 }
2484 } else if (m == CGROUP_IP_EGRESS_BYTES) {
2485 assert(!egress);
2b59bf51 2486 egress = strjoin("sent ", strna(FORMAT_BYTES(value)), " IP traffic");
a87b1faa
LP
2487 if (!egress) {
2488 r = log_oom();
2489 goto finish;
2490 }
2491 }
37109b85
ZJS
2492
2493 if (IN_SET(m, CGROUP_IP_INGRESS_BYTES, CGROUP_IP_EGRESS_BYTES))
2494 log_level = raise_level(log_level,
2495 value > MENTIONWORTHY_IP_BYTES,
2496 value > NOTICEWORTHY_IP_BYTES);
a87b1faa
LP
2497 }
2498
c2503e35
RH
2499 /* This check is here because it is the earliest point following all possible log_level assignments. If
2500 * log_level is assigned anywhere after this point, move this check. */
2501 if (!unit_log_level_test(u, log_level)) {
2502 r = 0;
2503 goto finish;
2504 }
2505
82044702
LP
2506 if (have_ip_accounting) {
2507 if (any_traffic) {
2508 if (igress)
2509 message_parts[n_message_parts++] = TAKE_PTR(igress);
2510 if (egress)
2511 message_parts[n_message_parts++] = TAKE_PTR(egress);
a87b1faa 2512
82044702
LP
2513 } else {
2514 char *k;
915b1d01 2515
82044702
LP
2516 k = strdup("no IP traffic");
2517 if (!k) {
2518 r = log_oom();
2519 goto finish;
2520 }
2521
2522 message_parts[n_message_parts++] = k;
2523 }
915b1d01
LP
2524 }
2525
2526 /* Is there any accounting data available at all? */
2527 if (n_iovec == 0) {
2528 r = 0;
2529 goto finish;
2530 }
2531
2532 if (n_message_parts == 0)
a87b1faa 2533 t = strjoina("MESSAGE=", u->id, ": Completed.");
915b1d01 2534 else {
c2b2df60 2535 _cleanup_free_ char *joined = NULL;
915b1d01
LP
2536
2537 message_parts[n_message_parts] = NULL;
2538
2539 joined = strv_join(message_parts, ", ");
2540 if (!joined) {
2541 r = log_oom();
2542 goto finish;
2543 }
2544
ec9d636b 2545 joined[0] = ascii_toupper(joined[0]);
a87b1faa 2546 t = strjoina("MESSAGE=", u->id, ": ", joined, ".");
915b1d01
LP
2547 }
2548
2549 /* The following four fields we allocate on the stack or are static strings, we hence don't want to free them,
2550 * and hence don't increase n_iovec for them */
2551 iovec[n_iovec] = IOVEC_MAKE_STRING(t);
2552 iovec[n_iovec + 1] = IOVEC_MAKE_STRING("MESSAGE_ID=" SD_MESSAGE_UNIT_RESOURCES_STR);
2553
2554 t = strjoina(u->manager->unit_log_field, u->id);
2555 iovec[n_iovec + 2] = IOVEC_MAKE_STRING(t);
2556
2557 t = strjoina(u->manager->invocation_log_field, u->invocation_id_string);
2558 iovec[n_iovec + 3] = IOVEC_MAKE_STRING(t);
2559
c2503e35 2560 log_unit_struct_iovec(u, log_level, iovec, n_iovec + 4);
915b1d01
LP
2561 r = 0;
2562
2563finish:
12375b95 2564 for (size_t i = 0; i < n_message_parts; i++)
915b1d01
LP
2565 free(message_parts[i]);
2566
12375b95 2567 for (size_t i = 0; i < n_iovec; i++)
915b1d01
LP
2568 free(iovec[i].iov_base);
2569
2570 return r;
2571
2572}
2573
adefcf28
LP
2574static void unit_update_on_console(Unit *u) {
2575 bool b;
2576
2577 assert(u);
2578
2579 b = unit_needs_console(u);
2580 if (u->on_console == b)
2581 return;
2582
2583 u->on_console = b;
2584 if (b)
2585 manager_ref_console(u->manager);
2586 else
2587 manager_unref_console(u->manager);
adefcf28
LP
2588}
2589
6eb65e7c
LP
2590static void unit_emit_audit_start(Unit *u) {
2591 assert(u);
2592
d52b8493 2593 if (UNIT_VTABLE(u)->audit_start_message_type <= 0)
6eb65e7c
LP
2594 return;
2595
2596 /* Write audit record if we have just finished starting up */
d52b8493 2597 manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_start_message_type, /* success= */ true);
6eb65e7c
LP
2598 u->in_audit = true;
2599}
2600
2601static void unit_emit_audit_stop(Unit *u, UnitActiveState state) {
2602 assert(u);
2603
d52b8493 2604 if (UNIT_VTABLE(u)->audit_start_message_type <= 0)
6eb65e7c
LP
2605 return;
2606
2607 if (u->in_audit) {
2608 /* Write audit record if we have just finished shutting down */
d52b8493 2609 manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_stop_message_type, /* success= */ state == UNIT_INACTIVE);
6eb65e7c
LP
2610 u->in_audit = false;
2611 } else {
2612 /* Hmm, if there was no start record written write it now, so that we always have a nice pair */
d52b8493 2613 manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_start_message_type, /* success= */ state == UNIT_INACTIVE);
6eb65e7c
LP
2614
2615 if (state == UNIT_INACTIVE)
d52b8493 2616 manager_send_unit_audit(u->manager, u, UNIT_VTABLE(u)->audit_stop_message_type, /* success= */ true);
6eb65e7c
LP
2617 }
2618}
2619
96b09de5 2620static bool unit_process_job(Job *j, UnitActiveState ns, bool reload_success) {
16c74914 2621 bool unexpected = false;
31cd5f63 2622 JobResult result;
16c74914
LP
2623
2624 assert(j);
2625
2626 if (j->state == JOB_WAITING)
16c74914
LP
2627 /* So we reached a different state for this job. Let's see if we can run it now if it failed previously
2628 * due to EAGAIN. */
2629 job_add_to_run_queue(j);
2630
2631 /* Let's check whether the unit's new state constitutes a finished job, or maybe contradicts a running job and
2632 * hence needs to invalidate jobs. */
2633
2634 switch (j->type) {
2635
2636 case JOB_START:
2637 case JOB_VERIFY_ACTIVE:
2638
2639 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
2640 job_finish_and_invalidate(j, JOB_DONE, true, false);
2641 else if (j->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
2642 unexpected = true;
2643
31cd5f63
AZ
2644 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2645 if (ns == UNIT_FAILED)
2646 result = JOB_FAILED;
31cd5f63
AZ
2647 else
2648 result = JOB_DONE;
2649
2650 job_finish_and_invalidate(j, result, true, false);
2651 }
16c74914
LP
2652 }
2653
2654 break;
2655
2656 case JOB_RELOAD:
2657 case JOB_RELOAD_OR_START:
2658 case JOB_TRY_RELOAD:
2659
2660 if (j->state == JOB_RUNNING) {
2661 if (ns == UNIT_ACTIVE)
96b09de5 2662 job_finish_and_invalidate(j, reload_success ? JOB_DONE : JOB_FAILED, true, false);
16c74914
LP
2663 else if (!IN_SET(ns, UNIT_ACTIVATING, UNIT_RELOADING)) {
2664 unexpected = true;
2665
2666 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2667 job_finish_and_invalidate(j, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true, false);
2668 }
2669 }
2670
2671 break;
2672
2673 case JOB_STOP:
2674 case JOB_RESTART:
2675 case JOB_TRY_RESTART:
2676
2677 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
2678 job_finish_and_invalidate(j, JOB_DONE, true, false);
2679 else if (j->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
2680 unexpected = true;
2681 job_finish_and_invalidate(j, JOB_FAILED, true, false);
2682 }
2683
2684 break;
2685
2686 default:
04499a70 2687 assert_not_reached();
16c74914
LP
2688 }
2689
2690 return unexpected;
2691}
2692
96b09de5 2693void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
429926e9 2694 const char *reason;
8559b3b7 2695 Manager *m;
a096ed36 2696
87f0e418
LP
2697 assert(u);
2698 assert(os < _UNIT_ACTIVE_STATE_MAX);
2699 assert(ns < _UNIT_ACTIVE_STATE_MAX);
87f0e418 2700
8559b3b7
LP
2701 /* Note that this is called for all low-level state changes, even if they might map to the same high-level
2702 * UnitActiveState! That means that ns == os is an expected behavior here. For example: if a mount point is
2703 * remounted this function will be called too! */
87f0e418 2704
546ac4f0
MS
2705 m = u->manager;
2706
3c4832ad
LP
2707 /* Let's enqueue the change signal early. In case this unit has a job associated we want that this unit is in
2708 * the bus queue, so that any job change signal queued will force out the unit change signal first. */
2709 unit_add_to_dbus_queue(u);
2710
e30bbc90
AZ
2711 /* Update systemd-oomd on the property/state change */
2712 if (os != ns) {
2713 /* Always send an update if the unit is going into an inactive state so systemd-oomd knows to stop
2714 * monitoring.
2715 * Also send an update whenever the unit goes active; this is to handle a case where an override file
2716 * sets one of the ManagedOOM*= properties to "kill", then later removes it. systemd-oomd needs to
2717 * know to stop monitoring when the unit changes from "kill" -> "auto" on daemon-reload, but we don't
2718 * have the information on the property. Thus, indiscriminately send an update. */
f561e8c6 2719 if (UNIT_IS_INACTIVE_OR_FAILED(ns) || UNIT_IS_ACTIVE_OR_RELOADING(ns))
e30bbc90
AZ
2720 (void) manager_varlink_send_managed_oom_update(u);
2721 }
2722
f755e3b7 2723 /* Update timestamps for state changes */
2c289ea8 2724 if (!MANAGER_IS_RELOADING(m)) {
a483fb59 2725 dual_timestamp_get(&u->state_change_timestamp);
173e3821 2726
bdbf9951 2727 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 2728 u->inactive_exit_timestamp = u->state_change_timestamp;
bdbf9951 2729 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
a483fb59 2730 u->inactive_enter_timestamp = u->state_change_timestamp;
bdbf9951
LP
2731
2732 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 2733 u->active_enter_timestamp = u->state_change_timestamp;
bdbf9951 2734 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
a483fb59 2735 u->active_exit_timestamp = u->state_change_timestamp;
bdbf9951 2736 }
87f0e418 2737
865cc19a 2738 /* Keep track of failed units */
8724defe 2739 (void) manager_update_failed_units(m, u, ns == UNIT_FAILED);
f755e3b7 2740
d3070fbd
LP
2741 /* Make sure the cgroup and state files are always removed when we become inactive */
2742 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
ff68472a
ZJS
2743 SET_FLAG(u->markers,
2744 (1u << UNIT_MARKER_NEEDS_RELOAD)|(1u << UNIT_MARKER_NEEDS_RESTART),
2745 false);
efdb0237 2746 unit_prune_cgroup(u);
d3070fbd 2747 unit_unlink_state_files(u);
ff68472a
ZJS
2748 } else if (ns != os && ns == UNIT_RELOADING)
2749 SET_FLAG(u->markers, 1u << UNIT_MARKER_NEEDS_RELOAD, false);
fb385181 2750
adefcf28 2751 unit_update_on_console(u);
7ed9f6cd 2752
2c289ea8 2753 if (!MANAGER_IS_RELOADING(m)) {
a1c7334b
LP
2754 bool unexpected;
2755
2756 /* Let's propagate state changes to the job */
2757 if (u->job)
96b09de5 2758 unexpected = unit_process_job(u->job, ns, reload_success);
a1c7334b
LP
2759 else
2760 unexpected = true;
f3bff0eb 2761
a1c7334b
LP
2762 /* If this state change happened without being requested by a job, then let's retroactively start or
2763 * stop dependencies. We skip that step when deserializing, since we don't want to create any
2764 * additional jobs just because something is already activated. */
bdbf9951
LP
2765
2766 if (unexpected) {
2767 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
2768 retroactively_start_dependencies(u);
2769 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
2770 retroactively_stop_dependencies(u);
2771 }
5de9682c 2772
bdbf9951 2773 if (ns != os && ns == UNIT_FAILED) {
ed77d407 2774 log_unit_debug(u, "Unit entered failed state.");
49b34f75 2775 unit_start_on_failure(u, "OnFailure=", UNIT_ATOM_ON_FAILURE, u->on_failure_job_mode);
cd6d0a45 2776 }
e537352b 2777
256f65d0
LP
2778 if (UNIT_IS_ACTIVE_OR_RELOADING(ns) && !UNIT_IS_ACTIVE_OR_RELOADING(os)) {
2779 /* This unit just finished starting up */
3b2775c5 2780
6eb65e7c 2781 unit_emit_audit_start(u);
546ac4f0 2782 manager_send_unit_plymouth(m, u);
256f65d0 2783 }
bdbf9951 2784
256f65d0 2785 if (UNIT_IS_INACTIVE_OR_FAILED(ns) && !UNIT_IS_INACTIVE_OR_FAILED(os)) {
915b1d01 2786 /* This unit just stopped/failed. */
256f65d0 2787
6eb65e7c 2788 unit_emit_audit_stop(u, ns);
915b1d01 2789 unit_log_resources(u);
cd6d0a45 2790 }
294446dc 2791
49b34f75 2792 if (ns == UNIT_INACTIVE && !IN_SET(os, UNIT_FAILED, UNIT_INACTIVE, UNIT_MAINTENANCE))
294446dc 2793 unit_start_on_failure(u, "OnSuccess=", UNIT_ATOM_ON_SUCCESS, u->on_success_job_mode);
f278026d
LP
2794 }
2795
31dc1ca3
LP
2796 manager_recheck_journal(m);
2797 manager_recheck_dbus(m);
e63ebf71 2798
3ecaa09b 2799 unit_trigger_notify(u);
3b2775c5 2800
8724defe 2801 if (!MANAGER_IS_RELOADING(m)) {
429926e9
TR
2802 if (os != UNIT_FAILED && ns == UNIT_FAILED) {
2803 reason = strjoina("unit ", u->id, " failed");
36c4dc08 2804 emergency_action(m, u->failure_action, 0, u->reboot_arg, unit_failure_action_exit_status(u), reason);
429926e9
TR
2805 } else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && ns == UNIT_INACTIVE) {
2806 reason = strjoina("unit ", u->id, " succeeded");
36c4dc08 2807 emergency_action(m, u->success_action, 0, u->reboot_arg, unit_success_action_exit_status(u), reason);
429926e9 2808 }
ff502445
LP
2809 }
2810
99e9af25 2811 /* And now, add the unit or depending units to various queues that will act on the new situation if
48008c1c 2812 * needed. These queues generally check for continuous state changes rather than events (like most of
99e9af25
LP
2813 * the state propagation above), and do work deferred instead of instantly, since they typically
2814 * don't want to run during reloading, and usually involve checking combined state of multiple units
2815 * at once. */
2816
2817 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
2818 /* Stop unneeded units and bound-by units regardless if going down was expected or not */
2819 check_unneeded_dependencies(u);
2820 check_bound_by_dependencies(u);
2821
2822 /* Maybe someone wants us to remain up? */
2823 unit_submit_to_start_when_upheld_queue(u);
2824
2825 /* Maybe the unit should be GC'ed now? */
2826 unit_add_to_gc_queue(u);
6ac62d61
LP
2827
2828 /* Maybe we can release some resources now? */
2829 unit_submit_to_release_resources_queue(u);
99e9af25
LP
2830 }
2831
2832 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
2833 /* Start uphold units regardless if going up was expected or not */
2834 check_uphold_dependencies(u);
2835
2836 /* Maybe we finished startup and are now ready for being stopped because unneeded? */
2837 unit_submit_to_stop_when_unneeded_queue(u);
2838
2839 /* Maybe we finished startup, but something we needed has vanished? Let's die then. (This happens
2840 * when something BindsTo= to a Type=oneshot unit, as these units go directly from starting to
2841 * inactive, without ever entering started.) */
2842 unit_submit_to_stop_when_bound_queue(u);
2843 }
87f0e418
LP
2844}
2845
f75f613d 2846int unit_watch_pid(Unit *u, pid_t pid, bool exclusive) {
62a76913 2847 int r;
a911bb9a 2848
87f0e418 2849 assert(u);
62a76913 2850 assert(pid_is_valid(pid));
87f0e418 2851
62a76913 2852 /* Watch a specific PID */
5ba6985b 2853
f75f613d
FB
2854 /* Caller might be sure that this PID belongs to this unit only. Let's take this
2855 * opportunity to remove any stalled references to this PID as they can be created
2856 * easily (when watching a process which is not our direct child). */
2857 if (exclusive)
2858 manager_unwatch_pid(u->manager, pid);
2859
d5099efc 2860 r = set_ensure_allocated(&u->pids, NULL);
5ba6985b
LP
2861 if (r < 0)
2862 return r;
2863
62a76913 2864 r = hashmap_ensure_allocated(&u->manager->watch_pids, NULL);
a911bb9a
LP
2865 if (r < 0)
2866 return r;
2867
62a76913
LP
2868 /* First try, let's add the unit keyed by "pid". */
2869 r = hashmap_put(u->manager->watch_pids, PID_TO_PTR(pid), u);
2870 if (r == -EEXIST) {
2871 Unit **array;
2872 bool found = false;
2873 size_t n = 0;
05e343b7 2874
62a76913
LP
2875 /* OK, the "pid" key is already assigned to a different unit. Let's see if the "-pid" key (which points
2876 * to an array of Units rather than just a Unit), lists us already. */
a911bb9a 2877
62a76913
LP
2878 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2879 if (array)
2880 for (; array[n]; n++)
2881 if (array[n] == u)
2882 found = true;
a911bb9a 2883
85773a7f 2884 if (!found) {
62a76913
LP
2885 Unit **new_array;
2886
2887 /* Allocate a new array */
2888 new_array = new(Unit*, n + 2);
2889 if (!new_array)
2890 return -ENOMEM;
2891
2892 memcpy_safe(new_array, array, sizeof(Unit*) * n);
2893 new_array[n] = u;
2894 new_array[n+1] = NULL;
2895
2896 /* Add or replace the old array */
2897 r = hashmap_replace(u->manager->watch_pids, PID_TO_PTR(-pid), new_array);
2898 if (r < 0) {
2899 free(new_array);
2900 return r;
2901 }
2902
2903 free(array);
2904 }
2905 } else if (r < 0)
2906 return r;
2907
2908 r = set_put(u->pids, PID_TO_PTR(pid));
2909 if (r < 0)
2910 return r;
2911
2912 return 0;
87f0e418
LP
2913}
2914
2915void unit_unwatch_pid(Unit *u, pid_t pid) {
62a76913
LP
2916 Unit **array;
2917
87f0e418 2918 assert(u);
62a76913
LP
2919 assert(pid_is_valid(pid));
2920
2921 /* First let's drop the unit in case it's keyed as "pid". */
2922 (void) hashmap_remove_value(u->manager->watch_pids, PID_TO_PTR(pid), u);
2923
2924 /* Then, let's also drop the unit, in case it's in the array keyed by -pid */
2925 array = hashmap_get(u->manager->watch_pids, PID_TO_PTR(-pid));
2926 if (array) {
62a76913 2927 /* Let's iterate through the array, dropping our own entry */
12375b95
ZJS
2928
2929 size_t m = 0;
2930 for (size_t n = 0; array[n]; n++)
62a76913
LP
2931 if (array[n] != u)
2932 array[m++] = array[n];
2933 array[m] = NULL;
2934
2935 if (m == 0) {
2936 /* The array is now empty, remove the entire entry */
20c3acfa 2937 assert_se(hashmap_remove(u->manager->watch_pids, PID_TO_PTR(-pid)) == array);
62a76913
LP
2938 free(array);
2939 }
2940 }
87f0e418 2941
fea72cc0 2942 (void) set_remove(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2943}
2944
bd44e61b
LP
2945void unit_unwatch_all_pids(Unit *u) {
2946 assert(u);
2947
2948 while (!set_isempty(u->pids))
fea72cc0 2949 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
bd44e61b 2950
efdb0237 2951 u->pids = set_free(u->pids);
a911bb9a
LP
2952}
2953
50be4f4a
LP
2954static void unit_tidy_watch_pids(Unit *u) {
2955 pid_t except1, except2;
a911bb9a
LP
2956 void *e;
2957
2958 assert(u);
2959
2960 /* Cleans dead PIDs from our list */
2961
50be4f4a
LP
2962 except1 = unit_main_pid(u);
2963 except2 = unit_control_pid(u);
2964
90e74a66 2965 SET_FOREACH(e, u->pids) {
fea72cc0 2966 pid_t pid = PTR_TO_PID(e);
a911bb9a
LP
2967
2968 if (pid == except1 || pid == except2)
2969 continue;
2970
9f5650ae 2971 if (!pid_is_unwaited(pid))
bd44e61b 2972 unit_unwatch_pid(u, pid);
a911bb9a 2973 }
87f0e418
LP
2974}
2975
50be4f4a 2976static int on_rewatch_pids_event(sd_event_source *s, void *userdata) {
99534007 2977 Unit *u = ASSERT_PTR(userdata);
50be4f4a
LP
2978
2979 assert(s);
50be4f4a
LP
2980
2981 unit_tidy_watch_pids(u);
2982 unit_watch_all_pids(u);
2983
2984 /* If the PID set is empty now, then let's finish this off. */
2985 unit_synthesize_cgroup_empty_event(u);
2986
2987 return 0;
2988}
2989
2990int unit_enqueue_rewatch_pids(Unit *u) {
2991 int r;
2992
2993 assert(u);
2994
2995 if (!u->cgroup_path)
2996 return -ENOENT;
2997
2998 r = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
2999 if (r < 0)
3000 return r;
3001 if (r > 0) /* On unified we can use proper notifications */
3002 return 0;
3003
3004 /* Enqueues a low-priority job that will clean up dead PIDs from our list of PIDs to watch and subscribe to new
3005 * PIDs that might have appeared. We do this in a delayed job because the work might be quite slow, as it
3006 * involves issuing kill(pid, 0) on all processes we watch. */
3007
3008 if (!u->rewatch_pids_event_source) {
3009 _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL;
3010
3011 r = sd_event_add_defer(u->manager->event, &s, on_rewatch_pids_event, u);
3012 if (r < 0)
3013 return log_error_errno(r, "Failed to allocate event source for tidying watched PIDs: %m");
3014
3015 r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_IDLE);
3016 if (r < 0)
28b77ab2 3017 return log_error_errno(r, "Failed to adjust priority of event source for tidying watched PIDs: %m");
50be4f4a
LP
3018
3019 (void) sd_event_source_set_description(s, "tidy-watch-pids");
3020
3021 u->rewatch_pids_event_source = TAKE_PTR(s);
3022 }
3023
3024 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_ONESHOT);
3025 if (r < 0)
3026 return log_error_errno(r, "Failed to enable event source for tidying watched PIDs: %m");
3027
3028 return 0;
3029}
3030
3031void unit_dequeue_rewatch_pids(Unit *u) {
3032 int r;
3033 assert(u);
3034
3035 if (!u->rewatch_pids_event_source)
3036 return;
3037
3038 r = sd_event_source_set_enabled(u->rewatch_pids_event_source, SD_EVENT_OFF);
3039 if (r < 0)
3040 log_warning_errno(r, "Failed to disable event source for tidying watched PIDs, ignoring: %m");
3041
5dcadb4c 3042 u->rewatch_pids_event_source = sd_event_source_disable_unref(u->rewatch_pids_event_source);
50be4f4a
LP
3043}
3044
87f0e418
LP
3045bool unit_job_is_applicable(Unit *u, JobType j) {
3046 assert(u);
3047 assert(j >= 0 && j < _JOB_TYPE_MAX);
3048
3049 switch (j) {
3050
3051 case JOB_VERIFY_ACTIVE:
3052 case JOB_START:
e0209d83 3053 case JOB_NOP:
f5869324 3054 /* Note that we don't check unit_can_start() here. That's because .device units and suchlike are not
86b52a39 3055 * startable by us but may appear due to external events, and it thus makes sense to permit enqueuing
f5869324 3056 * jobs for it. */
87f0e418
LP
3057 return true;
3058
f5869324
LP
3059 case JOB_STOP:
3060 /* Similar as above. However, perpetual units can never be stopped (neither explicitly nor due to
86b52a39 3061 * external events), hence it makes no sense to permit enqueuing such a request either. */
f5869324
LP
3062 return !u->perpetual;
3063
87f0e418
LP
3064 case JOB_RESTART:
3065 case JOB_TRY_RESTART:
f5869324 3066 return unit_can_stop(u) && unit_can_start(u);
87f0e418
LP
3067
3068 case JOB_RELOAD:
3282591d 3069 case JOB_TRY_RELOAD:
87f0e418
LP
3070 return unit_can_reload(u);
3071
3072 case JOB_RELOAD_OR_START:
3073 return unit_can_reload(u) && unit_can_start(u);
3074
3075 default:
04499a70 3076 assert_not_reached();
87f0e418
LP
3077 }
3078}
3079
83110824
YW
3080static Hashmap *unit_get_dependency_hashmap_per_type(Unit *u, UnitDependency d) {
3081 Hashmap *deps;
3082
3083 assert(u);
3084 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
3085
3086 deps = hashmap_get(u->dependencies, UNIT_DEPENDENCY_TO_PTR(d));
3087 if (!deps) {
3088 _cleanup_hashmap_free_ Hashmap *h = NULL;
3089
3090 h = hashmap_new(NULL);
3091 if (!h)
3092 return NULL;
3093
3094 if (hashmap_ensure_put(&u->dependencies, NULL, UNIT_DEPENDENCY_TO_PTR(d), h) < 0)
3095 return NULL;
3096
3097 deps = TAKE_PTR(h);
3098 }
3099
3100 return deps;
3101}
3102
3103typedef enum NotifyDependencyFlags {
3104 NOTIFY_DEPENDENCY_UPDATE_FROM = 1 << 0,
3105 NOTIFY_DEPENDENCY_UPDATE_TO = 1 << 1,
3106} NotifyDependencyFlags;
3107
3108static int unit_add_dependency_impl(
eef85c4a
LP
3109 Unit *u,
3110 UnitDependency d,
3111 Unit *other,
eef85c4a 3112 UnitDependencyMask mask) {
87f0e418
LP
3113
3114 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
fb138166
ZJS
3115 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
3116 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
3117 [UNIT_WANTS] = UNIT_WANTED_BY,
3118 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
3119 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
3120 [UNIT_UPHOLDS] = UNIT_UPHELD_BY,
3121 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
3122 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
3123 [UNIT_WANTED_BY] = UNIT_WANTS,
3124 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
3125 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
3126 [UNIT_UPHELD_BY] = UNIT_UPHOLDS,
3127 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
3128 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
3129 [UNIT_BEFORE] = UNIT_AFTER,
3130 [UNIT_AFTER] = UNIT_BEFORE,
3131 [UNIT_ON_SUCCESS] = UNIT_ON_SUCCESS_OF,
3132 [UNIT_ON_SUCCESS_OF] = UNIT_ON_SUCCESS,
3133 [UNIT_ON_FAILURE] = UNIT_ON_FAILURE_OF,
3134 [UNIT_ON_FAILURE_OF] = UNIT_ON_FAILURE,
3135 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
3136 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
3137 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
85e9a101 3138 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
fb138166
ZJS
3139 [UNIT_PROPAGATES_STOP_TO] = UNIT_STOP_PROPAGATED_FROM,
3140 [UNIT_STOP_PROPAGATED_FROM] = UNIT_PROPAGATES_STOP_TO,
3141 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF, /* symmetric! 👓 */
3142 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
3143 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
3144 [UNIT_IN_SLICE] = UNIT_SLICE_OF,
3145 [UNIT_SLICE_OF] = UNIT_IN_SLICE,
87f0e418 3146 };
83110824
YW
3147
3148 Hashmap *u_deps, *other_deps;
3149 UnitDependencyInfo u_info, u_info_old, other_info, other_info_old;
3150 NotifyDependencyFlags flags = 0;
3151 int r;
3152
3153 assert(u);
3154 assert(other);
3155 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
3156 assert(inverse_table[d] >= 0 && inverse_table[d] < _UNIT_DEPENDENCY_MAX);
3157 assert(mask > 0 && mask < _UNIT_DEPENDENCY_MASK_FULL);
3158
3159 /* Ensure the following two hashmaps for each unit exist:
3160 * - the top-level dependency hashmap that maps UnitDependency → Hashmap(Unit* → UnitDependencyInfo),
3161 * - the inner hashmap, that maps Unit* → UnitDependencyInfo, for the specified dependency type. */
3162 u_deps = unit_get_dependency_hashmap_per_type(u, d);
3163 if (!u_deps)
3164 return -ENOMEM;
3165
3166 other_deps = unit_get_dependency_hashmap_per_type(other, inverse_table[d]);
3167 if (!other_deps)
3168 return -ENOMEM;
3169
3170 /* Save the original dependency info. */
3171 u_info.data = u_info_old.data = hashmap_get(u_deps, other);
3172 other_info.data = other_info_old.data = hashmap_get(other_deps, u);
3173
3174 /* Update dependency info. */
3175 u_info.origin_mask |= mask;
3176 other_info.destination_mask |= mask;
3177
3178 /* Save updated dependency info. */
3179 if (u_info.data != u_info_old.data) {
3180 r = hashmap_replace(u_deps, other, u_info.data);
3181 if (r < 0)
3182 return r;
3183
3184 flags = NOTIFY_DEPENDENCY_UPDATE_FROM;
3185 }
3186
3187 if (other_info.data != other_info_old.data) {
3188 r = hashmap_replace(other_deps, u, other_info.data);
3189 if (r < 0) {
3190 if (u_info.data != u_info_old.data) {
3191 /* Restore the old dependency. */
3192 if (u_info_old.data)
3193 (void) hashmap_update(u_deps, other, u_info_old.data);
3194 else
3195 hashmap_remove(u_deps, other);
3196 }
3197 return r;
3198 }
3199
3200 flags |= NOTIFY_DEPENDENCY_UPDATE_TO;
3201 }
3202
3203 return flags;
3204}
3205
3206int unit_add_dependency(
3207 Unit *u,
3208 UnitDependency d,
3209 Unit *other,
3210 bool add_reference,
3211 UnitDependencyMask mask) {
3212
15ed3c3a 3213 UnitDependencyAtom a;
eef85c4a 3214 int r;
15ed3c3a
LP
3215
3216 /* Helper to know whether sending a notification is necessary or not: if the dependency is already
3217 * there, no need to notify! */
83110824 3218 NotifyDependencyFlags notify_flags;
87f0e418
LP
3219
3220 assert(u);
3221 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
87f0e418
LP
3222 assert(other);
3223
9f151f29
LP
3224 u = unit_follow_merge(u);
3225 other = unit_follow_merge(other);
15ed3c3a
LP
3226 a = unit_dependency_to_atom(d);
3227 assert(a >= 0);
9f151f29 3228
15ed3c3a 3229 /* We won't allow dependencies on ourselves. We will not consider them an error however. */
d1fab3fe 3230 if (u == other) {
ed991163
YW
3231 if (unit_should_warn_about_dependency(d))
3232 log_unit_warning(u, "Dependency %s=%s is dropped.",
3233 unit_dependency_to_string(d), u->id);
87f0e418 3234 return 0;
d1fab3fe 3235 }
87f0e418 3236
f14d6810
MG
3237 if (u->manager && FLAGS_SET(u->manager->test_run_flags, MANAGER_TEST_RUN_IGNORE_DEPENDENCIES))
3238 return 0;
3239
15ed3c3a
LP
3240 /* Note that ordering a device unit after a unit is permitted since it allows to start its job
3241 * running timeout at a specific time. */
3242 if (FLAGS_SET(a, UNIT_ATOM_BEFORE) && other->type == UNIT_DEVICE) {
b862c257 3243 log_unit_warning(u, "Dependency Before=%s ignored (.device units cannot be delayed)", other->id);
c80a9a33
LP
3244 return 0;
3245 }
3246
15ed3c3a 3247 if (FLAGS_SET(a, UNIT_ATOM_ON_FAILURE) && !UNIT_VTABLE(u)->can_fail) {
c80a9a33
LP
3248 log_unit_warning(u, "Requested dependency OnFailure=%s ignored (%s units cannot fail).", other->id, unit_type_to_string(u->type));
3249 return 0;
3250 }
3251
15ed3c3a 3252 if (FLAGS_SET(a, UNIT_ATOM_TRIGGERS) && !UNIT_VTABLE(u)->can_trigger)
c80a9a33
LP
3253 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3254 "Requested dependency Triggers=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(u->type));
15ed3c3a 3255 if (FLAGS_SET(a, UNIT_ATOM_TRIGGERED_BY) && !UNIT_VTABLE(other)->can_trigger)
c80a9a33
LP
3256 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3257 "Requested dependency TriggeredBy=%s refused (%s units cannot trigger other units).", other->id, unit_type_to_string(other->type));
3258
d219a2b0
LP
3259 if (FLAGS_SET(a, UNIT_ATOM_IN_SLICE) && other->type != UNIT_SLICE)
3260 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3261 "Requested dependency Slice=%s refused (%s is not a slice unit).", other->id, other->id);
3262 if (FLAGS_SET(a, UNIT_ATOM_SLICE_OF) && u->type != UNIT_SLICE)
3263 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3264 "Requested dependency SliceOf=%s refused (%s is not a slice unit).", other->id, u->id);
3265
3266 if (FLAGS_SET(a, UNIT_ATOM_IN_SLICE) && !UNIT_HAS_CGROUP_CONTEXT(u))
3267 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3268 "Requested dependency Slice=%s refused (%s is not a cgroup unit).", other->id, u->id);
3269
3270 if (FLAGS_SET(a, UNIT_ATOM_SLICE_OF) && !UNIT_HAS_CGROUP_CONTEXT(other))
3271 return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
3272 "Requested dependency SliceOf=%s refused (%s is not a cgroup unit).", other->id, other->id);
3273
83110824 3274 r = unit_add_dependency_impl(u, d, other, mask);
613b411c 3275 if (r < 0)
87f0e418 3276 return r;
83110824 3277 notify_flags = r;
613b411c
LP
3278
3279 if (add_reference) {
83110824 3280 r = unit_add_dependency_impl(u, UNIT_REFERENCES, other, mask);
613b411c 3281 if (r < 0)
701cc384 3282 return r;
83110824 3283 notify_flags |= r;
613b411c 3284 }
87f0e418 3285
83110824 3286 if (FLAGS_SET(notify_flags, NOTIFY_DEPENDENCY_UPDATE_FROM))
5177cb0a 3287 unit_add_to_dbus_queue(u);
83110824 3288 if (FLAGS_SET(notify_flags, NOTIFY_DEPENDENCY_UPDATE_TO))
ac17080c 3289 unit_add_to_dbus_queue(other);
15ed3c3a 3290
83110824 3291 return notify_flags != 0;
87f0e418 3292}
0301abf4 3293
eef85c4a 3294int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask) {
5ee8e988 3295 int r = 0, s = 0;
2c966c03
LP
3296
3297 assert(u);
5ee8e988 3298 assert(d >= 0 || e >= 0);
2c966c03 3299
5ee8e988
LB
3300 if (d >= 0) {
3301 r = unit_add_dependency(u, d, other, add_reference, mask);
3302 if (r < 0)
3303 return r;
3304 }
2c966c03 3305
5ee8e988
LB
3306 if (e >= 0) {
3307 s = unit_add_dependency(u, e, other, add_reference, mask);
3308 if (s < 0)
3309 return s;
3310 }
a8c5a4c6
YW
3311
3312 return r > 0 || s > 0;
2c966c03
LP
3313}
3314
23e8c796 3315static int resolve_template(Unit *u, const char *name, char **buf, const char **ret) {
7410616c 3316 int r;
9e2f7c11
LP
3317
3318 assert(u);
23e8c796 3319 assert(name);
7410616c
LP
3320 assert(buf);
3321 assert(ret);
9e2f7c11 3322
7410616c
LP
3323 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
3324 *buf = NULL;
3325 *ret = name;
3326 return 0;
9e2f7c11
LP
3327 }
3328
ac155bb8 3329 if (u->instance)
7410616c 3330 r = unit_name_replace_instance(name, u->instance, buf);
9e2f7c11 3331 else {
ae018d9b 3332 _cleanup_free_ char *i = NULL;
9e2f7c11 3333
7410616c
LP
3334 r = unit_name_to_prefix(u->id, &i);
3335 if (r < 0)
3336 return r;
9e2f7c11 3337
7410616c 3338 r = unit_name_replace_instance(name, i, buf);
9e2f7c11 3339 }
7410616c
LP
3340 if (r < 0)
3341 return r;
9e2f7c11 3342
7410616c
LP
3343 *ret = *buf;
3344 return 0;
9e2f7c11
LP
3345}
3346
35d8c19a 3347int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask) {
7410616c 3348 _cleanup_free_ char *buf = NULL;
09b6b09f
LP
3349 Unit *other;
3350 int r;
3351
9e2f7c11 3352 assert(u);
35d8c19a 3353 assert(name);
09b6b09f 3354
23e8c796 3355 r = resolve_template(u, name, &buf, &name);
7410616c
LP
3356 if (r < 0)
3357 return r;
09b6b09f 3358
f14d6810
MG
3359 if (u->manager && FLAGS_SET(u->manager->test_run_flags, MANAGER_TEST_RUN_IGNORE_DEPENDENCIES))
3360 return 0;
3361
35d8c19a 3362 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
8afbb8e1
LP
3363 if (r < 0)
3364 return r;
9e2f7c11 3365
eef85c4a 3366 return unit_add_dependency(u, d, other, add_reference, mask);
09b6b09f
LP
3367}
3368
5a724170 3369int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask) {
7410616c 3370 _cleanup_free_ char *buf = NULL;
2c966c03
LP
3371 Unit *other;
3372 int r;
2c966c03
LP
3373
3374 assert(u);
5a724170 3375 assert(name);
2c966c03 3376
23e8c796 3377 r = resolve_template(u, name, &buf, &name);
7410616c
LP
3378 if (r < 0)
3379 return r;
2c966c03 3380
f14d6810
MG
3381 if (u->manager && FLAGS_SET(u->manager->test_run_flags, MANAGER_TEST_RUN_IGNORE_DEPENDENCIES))
3382 return 0;
3383
5a724170 3384 r = manager_load_unit(u->manager, name, NULL, NULL, &other);
3f3cc397 3385 if (r < 0)
68eda4bd 3386 return r;
2c966c03 3387
eef85c4a 3388 return unit_add_two_dependencies(u, d, e, other, add_reference, mask);
2c966c03
LP
3389}
3390
0301abf4 3391int set_unit_path(const char *p) {
0301abf4 3392 /* This is mostly for debug purposes */
7c248223 3393 return RET_NERRNO(setenv("SYSTEMD_UNIT_PATH", p, 1));
0301abf4 3394}
88066b3a 3395
ea430986 3396char *unit_dbus_path(Unit *u) {
ea430986
LP
3397 assert(u);
3398
ac155bb8 3399 if (!u->id)
04ade7d2
LP
3400 return NULL;
3401
48899192 3402 return unit_dbus_path_from_name(u->id);
ea430986
LP
3403}
3404
4b58153d
LP
3405char *unit_dbus_path_invocation_id(Unit *u) {
3406 assert(u);
3407
3408 if (sd_id128_is_null(u->invocation_id))
3409 return NULL;
3410
3411 return unit_dbus_path_from_name(u->invocation_id_string);
3412}
3413
2d3b784d 3414int unit_set_invocation_id(Unit *u, sd_id128_t id) {
db868d45
ZJS
3415 int r;
3416
3417 assert(u);
3418
3419 /* Set the invocation ID for this unit. If we cannot, this will not roll back, but reset the whole thing. */
3420
3421 if (sd_id128_equal(u->invocation_id, id))
3422 return 0;
3423
3424 if (!sd_id128_is_null(u->invocation_id))
3425 (void) hashmap_remove_value(u->manager->units_by_invocation_id, &u->invocation_id, u);
3426
3427 if (sd_id128_is_null(id)) {
3428 r = 0;
3429 goto reset;
3430 }
3431
3432 r = hashmap_ensure_allocated(&u->manager->units_by_invocation_id, &id128_hash_ops);
3433 if (r < 0)
3434 goto reset;
3435
3436 u->invocation_id = id;
3437 sd_id128_to_string(id, u->invocation_id_string);
3438
3439 r = hashmap_put(u->manager->units_by_invocation_id, &u->invocation_id, u);
3440 if (r < 0)
3441 goto reset;
3442
3443 return 0;
3444
3445reset:
3446 u->invocation_id = SD_ID128_NULL;
3447 u->invocation_id_string[0] = 0;
3448 return r;
3449}
3450
899acf5c 3451int unit_set_slice(Unit *u, Unit *slice) {
d219a2b0
LP
3452 int r;
3453
d79200e2
LP
3454 assert(u);
3455 assert(slice);
3456
d219a2b0
LP
3457 /* Sets the unit slice if it has not been set before. Is extra careful, to only allow this for units
3458 * that actually have a cgroup context. Also, we don't allow to set this for slices (since the parent
3459 * slice is derived from the name). Make sure the unit we set is actually a slice. */
d79200e2
LP
3460
3461 if (!UNIT_HAS_CGROUP_CONTEXT(u))
3462 return -EOPNOTSUPP;
3463
3464 if (u->type == UNIT_SLICE)
3465 return -EINVAL;
3466
102ef982
LP
3467 if (unit_active_state(u) != UNIT_INACTIVE)
3468 return -EBUSY;
3469
d79200e2
LP
3470 if (slice->type != UNIT_SLICE)
3471 return -EINVAL;
3472
efdb0237
LP
3473 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
3474 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
3475 return -EPERM;
3476
12f64221 3477 if (UNIT_GET_SLICE(u) == slice)
d79200e2
LP
3478 return 0;
3479
99e66921 3480 /* Disallow slice changes if @u is already bound to cgroups */
12f64221 3481 if (UNIT_GET_SLICE(u) && u->cgroup_realized)
d79200e2
LP
3482 return -EBUSY;
3483
899acf5c
AZ
3484 /* Remove any slices assigned prior; we should only have one UNIT_IN_SLICE dependency */
3485 if (UNIT_GET_SLICE(u))
3486 unit_remove_dependencies(u, UNIT_DEPENDENCY_SLICE_PROPERTY);
3487
3488 r = unit_add_dependency(u, UNIT_IN_SLICE, slice, true, UNIT_DEPENDENCY_SLICE_PROPERTY);
d219a2b0
LP
3489 if (r < 0)
3490 return r;
3491
d79200e2
LP
3492 return 1;
3493}
3494
3495int unit_set_default_slice(Unit *u) {
a8833944 3496 const char *slice_name;
a016b922
LP
3497 Unit *slice;
3498 int r;
3499
3500 assert(u);
3501
f14d6810
MG
3502 if (u->manager && FLAGS_SET(u->manager->test_run_flags, MANAGER_TEST_RUN_IGNORE_DEPENDENCIES))
3503 return 0;
3504
12f64221 3505 if (UNIT_GET_SLICE(u))
a016b922
LP
3506 return 0;
3507
a8833944
LP
3508 if (u->instance) {
3509 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
68eda4bd 3510
a8833944
LP
3511 /* Implicitly place all instantiated units in their
3512 * own per-template slice */
3513
7410616c
LP
3514 r = unit_name_to_prefix(u->id, &prefix);
3515 if (r < 0)
3516 return r;
a8833944
LP
3517
3518 /* The prefix is already escaped, but it might include
3519 * "-" which has a special meaning for slice units,
3520 * hence escape it here extra. */
7410616c 3521 escaped = unit_name_escape(prefix);
a8833944
LP
3522 if (!escaped)
3523 return -ENOMEM;
3524
463d0d15 3525 if (MANAGER_IS_SYSTEM(u->manager))
00e7b3c8 3526 slice_name = strjoina("system-", escaped, ".slice");
a8833944 3527 else
7f3b86a4 3528 slice_name = strjoina("app-", escaped, ".slice");
5ee24fa0
ZJS
3529
3530 } else if (unit_is_extrinsic(u))
3531 /* Keep all extrinsic units (e.g. perpetual units and swap and mount units in user mode) in
3532 * the root slice. They don't really belong in one of the subslices. */
3533 slice_name = SPECIAL_ROOT_SLICE;
3534
3535 else if (MANAGER_IS_SYSTEM(u->manager))
3536 slice_name = SPECIAL_SYSTEM_SLICE;
3537 else
3538 slice_name = SPECIAL_APP_SLICE;
a8833944
LP
3539
3540 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
a016b922
LP
3541 if (r < 0)
3542 return r;
3543
899acf5c 3544 return unit_set_slice(u, slice);
a016b922
LP
3545}
3546
9444b1f2 3547const char *unit_slice_name(Unit *u) {
12f64221 3548 Unit *slice;
9444b1f2
LP
3549 assert(u);
3550
12f64221
LP
3551 slice = UNIT_GET_SLICE(u);
3552 if (!slice)
9444b1f2
LP
3553 return NULL;
3554
12f64221 3555 return slice->id;
9444b1f2
LP
3556}
3557
f6ff8c29 3558int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
78edb35a 3559 _cleanup_free_ char *t = NULL;
f6ff8c29
LP
3560 int r;
3561
3562 assert(u);
3563 assert(type);
3564 assert(_found);
3565
7410616c
LP
3566 r = unit_name_change_suffix(u->id, type, &t);
3567 if (r < 0)
3568 return r;
3569 if (unit_has_name(u, t))
3570 return -EINVAL;
f6ff8c29 3571
ac155bb8 3572 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
9e2f7c11 3573 assert(r < 0 || *_found != u);
f6ff8c29
LP
3574 return r;
3575}
3576
bbc29086 3577static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
fc67a943 3578 const char *new_owner;
99534007 3579 Unit *u = ASSERT_PTR(userdata);
bbc29086
DM
3580 int r;
3581
3582 assert(message);
bbc29086 3583
fc67a943 3584 r = sd_bus_message_read(message, "sss", NULL, NULL, &new_owner);
bbc29086
DM
3585 if (r < 0) {
3586 bus_log_parse_error(r);
3587 return 0;
3588 }
3589
3590 if (UNIT_VTABLE(u)->bus_name_owner_change)
fc67a943 3591 UNIT_VTABLE(u)->bus_name_owner_change(u, empty_to_null(new_owner));
a5a8776a
MJ
3592
3593 return 0;
3594}
3595
3596static int get_name_owner_handler(sd_bus_message *message, void *userdata, sd_bus_error *error) {
3597 const sd_bus_error *e;
3598 const char *new_owner;
99534007 3599 Unit *u = ASSERT_PTR(userdata);
a5a8776a
MJ
3600 int r;
3601
3602 assert(message);
a5a8776a
MJ
3603
3604 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
3605
a5a8776a 3606 e = sd_bus_message_get_error(message);
a5a8776a 3607 if (e) {
91053fc9 3608 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_NAME_HAS_NO_OWNER)) {
33322185
YW
3609 r = sd_bus_error_get_errno(e);
3610 log_unit_error_errno(u, r,
3611 "Unexpected error response from GetNameOwner(): %s",
3612 bus_error_message(e, r));
3613 }
a5a8776a 3614
fc67a943
LP
3615 new_owner = NULL;
3616 } else {
3617 r = sd_bus_message_read(message, "s", &new_owner);
3618 if (r < 0)
3619 return bus_log_parse_error(r);
a5a8776a 3620
fc67a943
LP
3621 assert(!isempty(new_owner));
3622 }
a5a8776a
MJ
3623
3624 if (UNIT_VTABLE(u)->bus_name_owner_change)
fc67a943 3625 UNIT_VTABLE(u)->bus_name_owner_change(u, new_owner);
bbc29086
DM
3626
3627 return 0;
3628}
3629
9806e87d 3630int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
8df433d7 3631 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
9806e87d 3632 const char *match;
8df433d7 3633 usec_t timeout_usec = 0;
a5b07847 3634 int r;
bbc29086 3635
9806e87d
LP
3636 assert(u);
3637 assert(bus);
3638 assert(name);
bbc29086 3639
a5b07847 3640 if (u->match_bus_slot || u->get_name_owner_slot)
bbc29086
DM
3641 return -EBUSY;
3642
8df433d7 3643 /* NameOwnerChanged and GetNameOwner is used to detect when a service finished starting up. The dbus
3644 * call timeout shouldn't be earlier than that. If we couldn't get the start timeout, use the default
3645 * value defined above. */
3646 if (UNIT_VTABLE(u)->get_timeout_start_usec)
3647 timeout_usec = UNIT_VTABLE(u)->get_timeout_start_usec(u);
3648
9806e87d 3649 match = strjoina("type='signal',"
81d62103
ZJS
3650 "sender='org.freedesktop.DBus',"
3651 "path='/org/freedesktop/DBus',"
3652 "interface='org.freedesktop.DBus',"
3653 "member='NameOwnerChanged',"
3654 "arg0='", name, "'");
bbc29086 3655
8df433d7 3656 r = bus_add_match_full(
3657 bus,
3658 &u->match_bus_slot,
3659 true,
3660 match,
3661 signal_name_owner_changed,
3662 NULL,
3663 u,
3664 timeout_usec);
a5a8776a
MJ
3665 if (r < 0)
3666 return r;
3667
8df433d7 3668 r = sd_bus_message_new_method_call(
a5b07847 3669 bus,
8df433d7 3670 &m,
a5b07847
LP
3671 "org.freedesktop.DBus",
3672 "/org/freedesktop/DBus",
3673 "org.freedesktop.DBus",
8df433d7 3674 "GetNameOwner");
3675 if (r < 0)
3676 return r;
3677
3678 r = sd_bus_message_append(m, "s", name);
3679 if (r < 0)
3680 return r;
3681
3682 r = sd_bus_call_async(
3683 bus,
3684 &u->get_name_owner_slot,
3685 m,
a5b07847
LP
3686 get_name_owner_handler,
3687 u,
8df433d7 3688 timeout_usec);
3689
a5b07847
LP
3690 if (r < 0) {
3691 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
3692 return r;
3693 }
3694
3695 log_unit_debug(u, "Watching D-Bus name '%s'.", name);
3696 return 0;
bbc29086
DM
3697}
3698
05e343b7 3699int unit_watch_bus_name(Unit *u, const char *name) {
bbc29086
DM
3700 int r;
3701
05e343b7
LP
3702 assert(u);
3703 assert(name);
3704
3705 /* Watch a specific name on the bus. We only support one unit
3706 * watching each name for now. */
3707
bbc29086
DM
3708 if (u->manager->api_bus) {
3709 /* If the bus is already available, install the match directly.
3710 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
9806e87d 3711 r = unit_install_bus_match(u, u->manager->api_bus, name);
bbc29086 3712 if (r < 0)
8ea823b6 3713 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
bbc29086
DM
3714 }
3715
3716 r = hashmap_put(u->manager->watch_bus, name, u);
3717 if (r < 0) {
3718 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
a5b07847 3719 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
bbc29086
DM
3720 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
3721 }
3722
3723 return 0;
05e343b7
LP
3724}
3725
3726void unit_unwatch_bus_name(Unit *u, const char *name) {
3727 assert(u);
3728 assert(name);
3729
8367fea5 3730 (void) hashmap_remove_value(u->manager->watch_bus, name, u);
bbc29086 3731 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
a5a8776a 3732 u->get_name_owner_slot = sd_bus_slot_unref(u->get_name_owner_slot);
05e343b7
LP
3733}
3734
d336ba9f 3735int unit_add_node_dependency(Unit *u, const char *what, UnitDependency dep, UnitDependencyMask mask) {
68eda4bd 3736 _cleanup_free_ char *e = NULL;
44b0d1fd 3737 Unit *device;
6e2ef85b
LP
3738 int r;
3739
3740 assert(u);
3741
6e2ef85b 3742 /* Adds in links to the device node that this unit is based on */
47bc12e1
LP
3743 if (isempty(what))
3744 return 0;
6e2ef85b 3745
8407a5d0 3746 if (!is_device_path(what))
6e2ef85b
LP
3747 return 0;
3748
44b0d1fd 3749 /* When device units aren't supported (such as in a container), don't create dependencies on them. */
1c2e9646 3750 if (!unit_type_supported(UNIT_DEVICE))
47bc12e1
LP
3751 return 0;
3752
7410616c
LP
3753 r = unit_name_from_path(what, ".device", &e);
3754 if (r < 0)
3755 return r;
6e2ef85b 3756
ac155bb8 3757 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
6e2ef85b
LP
3758 if (r < 0)
3759 return r;
3760
ebc8968b
FB
3761 if (dep == UNIT_REQUIRES && device_shall_be_bound_by(device, u))
3762 dep = UNIT_BINDS_TO;
3763
d336ba9f
FB
3764 return unit_add_two_dependencies(u, UNIT_AFTER,
3765 MANAGER_IS_SYSTEM(u->manager) ? dep : UNIT_WANTS,
3766 device, true, mask);
6e2ef85b 3767}
a16e1123 3768
44b0d1fd
LP
3769int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask) {
3770 _cleanup_free_ char *escaped = NULL, *target = NULL;
3771 int r;
3772
3773 assert(u);
3774
3775 if (isempty(what))
3776 return 0;
3777
3778 if (!path_startswith(what, "/dev/"))
3779 return 0;
3780
3781 /* If we don't support devices, then also don't bother with blockdev@.target */
3782 if (!unit_type_supported(UNIT_DEVICE))
3783 return 0;
3784
3785 r = unit_name_path_escape(what, &escaped);
3786 if (r < 0)
3787 return r;
3788
3789 r = unit_name_build("blockdev", escaped, ".target", &target);
3790 if (r < 0)
3791 return r;
3792
3793 return unit_add_dependency_by_name(u, UNIT_AFTER, target, true, mask);
3794}
3795
be847e82 3796int unit_coldplug(Unit *u) {
05a98afd 3797 int r = 0, q;
cca098b0
LP
3798
3799 assert(u);
3800
f0831ed2 3801 /* Make sure we don't enter a loop, when coldplugging recursively. */
f78f265f
LP
3802 if (u->coldplugged)
3803 return 0;
3804
3805 u->coldplugged = true;
3806
05a98afd
LP
3807 STRV_FOREACH(i, u->deserialized_refs) {
3808 q = bus_unit_track_add_name(u, *i);
3809 if (q < 0 && r >= 0)
3810 r = q;
3811 }
3812 u->deserialized_refs = strv_free(u->deserialized_refs);
cca098b0 3813
05a98afd
LP
3814 if (UNIT_VTABLE(u)->coldplug) {
3815 q = UNIT_VTABLE(u)->coldplug(u);
3816 if (q < 0 && r >= 0)
3817 r = q;
3818 }
5a6158b6 3819
7dbd330c
GL
3820 if (u->job) {
3821 q = job_coldplug(u->job);
3822 if (q < 0 && r >= 0)
3823 r = q;
3824 }
3825 if (u->nop_job) {
3826 q = job_coldplug(u->nop_job);
05a98afd
LP
3827 if (q < 0 && r >= 0)
3828 r = q;
3829 }
cca098b0 3830
05a98afd 3831 return r;
cca098b0
LP
3832}
3833
f0831ed2
LP
3834void unit_catchup(Unit *u) {
3835 assert(u);
3836
3837 if (UNIT_VTABLE(u)->catchup)
3838 UNIT_VTABLE(u)->catchup(u);
869f52f2
DS
3839
3840 unit_cgroup_catchup(u);
f0831ed2
LP
3841}
3842
ba25d39e 3843static bool fragment_mtime_newer(const char *path, usec_t mtime, bool path_masked) {
21b95806
ZJS
3844 struct stat st;
3845
3846 if (!path)
3847 return false;
3848
77969722
LP
3849 /* If the source is some virtual kernel file system, then we assume we watch it anyway, and hence pretend we
3850 * are never out-of-date. */
3851 if (PATH_STARTSWITH_SET(path, "/proc", "/sys"))
3852 return false;
3853
21b95806
ZJS
3854 if (stat(path, &st) < 0)
3855 /* What, cannot access this anymore? */
3856 return true;
3857
ba25d39e
ZJS
3858 if (path_masked)
3859 /* For masked files check if they are still so */
3860 return !null_or_empty(&st);
3861 else
3a8db9fe 3862 /* For non-empty files check the mtime */
87ec20ef 3863 return timespec_load(&st.st_mtim) > mtime;
21b95806
ZJS
3864
3865 return false;
3866}
3867
45fb0699 3868bool unit_need_daemon_reload(Unit *u) {
ae7a7182 3869 _cleanup_strv_free_ char **t = NULL;
1b64d026 3870
45fb0699
LP
3871 assert(u);
3872
ba25d39e
ZJS
3873 /* For unit files, we allow masking… */
3874 if (fragment_mtime_newer(u->fragment_path, u->fragment_mtime,
3875 u->load_state == UNIT_MASKED))
21b95806 3876 return true;
5f4b19f4 3877
ba25d39e
ZJS
3878 /* Source paths should not be masked… */
3879 if (fragment_mtime_newer(u->source_path, u->source_mtime, false))
ab932a62 3880 return true;
ae7a7182 3881
19a44dfe
LR
3882 if (u->load_state == UNIT_LOADED)
3883 (void) unit_find_dropin_paths(u, &t);
ab932a62
LP
3884 if (!strv_equal(u->dropin_paths, t))
3885 return true;
6d10d308 3886
ba25d39e 3887 /* … any drop-ins that are masked are simply omitted from the list. */
ab932a62 3888 STRV_FOREACH(path, u->dropin_paths)
ba25d39e 3889 if (fragment_mtime_newer(*path, u->dropin_mtime, false))
ab932a62 3890 return true;
21b95806 3891
ab932a62 3892 return false;
45fb0699
LP
3893}
3894
fdf20a31 3895void unit_reset_failed(Unit *u) {
5632e374
LP
3896 assert(u);
3897
fdf20a31
MM
3898 if (UNIT_VTABLE(u)->reset_failed)
3899 UNIT_VTABLE(u)->reset_failed(u);
6bf0f408 3900
7bf081a1 3901 ratelimit_reset(&u->start_ratelimit);
6bf0f408 3902 u->start_limit_hit = false;
5632e374
LP
3903}
3904
a7f241db
LP
3905Unit *unit_following(Unit *u) {
3906 assert(u);
3907
3908 if (UNIT_VTABLE(u)->following)
3909 return UNIT_VTABLE(u)->following(u);
3910
3911 return NULL;
3912}
3913
31afa0a4 3914bool unit_stop_pending(Unit *u) {
18ffdfda
LP
3915 assert(u);
3916
31afa0a4
LP
3917 /* This call does check the current state of the unit. It's
3918 * hence useful to be called from state change calls of the
3919 * unit itself, where the state isn't updated yet. This is
3920 * different from unit_inactive_or_pending() which checks both
3921 * the current state and for a queued job. */
18ffdfda 3922
28a2dfe8 3923 return unit_has_job_type(u, JOB_STOP);
31afa0a4
LP
3924}
3925
3926bool unit_inactive_or_pending(Unit *u) {
3927 assert(u);
3928
3929 /* Returns true if the unit is inactive or going down */
18ffdfda 3930
d956ac29
LP
3931 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
3932 return true;
3933
31afa0a4 3934 if (unit_stop_pending(u))
18ffdfda
LP
3935 return true;
3936
3937 return false;
3938}
3939
31afa0a4 3940bool unit_active_or_pending(Unit *u) {
f976f3f6
LP
3941 assert(u);
3942
f60c2665 3943 /* Returns true if the unit is active or going up */
f976f3f6
LP
3944
3945 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
3946 return true;
3947
ac155bb8 3948 if (u->job &&
3742095b 3949 IN_SET(u->job->type, JOB_START, JOB_RELOAD_OR_START, JOB_RESTART))
f976f3f6
LP
3950 return true;
3951
3952 return false;
3953}
3954
52a12341
YW
3955bool unit_will_restart_default(Unit *u) {
3956 assert(u);
3957
28a2dfe8 3958 return unit_has_job_type(u, JOB_START);
52a12341
YW
3959}
3960
deb4e708
MK
3961bool unit_will_restart(Unit *u) {
3962 assert(u);
3963
3964 if (!UNIT_VTABLE(u)->will_restart)
3965 return false;
3966
3967 return UNIT_VTABLE(u)->will_restart(u);
3968}
3969
a721cd00 3970int unit_kill(Unit *u, KillWho w, int signo, int code, int value, sd_bus_error *error) {
8a0867d6
LP
3971 assert(u);
3972 assert(w >= 0 && w < _KILL_WHO_MAX);
6eb7c172 3973 assert(SIGNAL_VALID(signo));
a721cd00 3974 assert(IN_SET(code, SI_USER, SI_QUEUE));
8a0867d6 3975
8a0867d6 3976 if (!UNIT_VTABLE(u)->kill)
15411c0c 3977 return -EOPNOTSUPP;
8a0867d6 3978
a721cd00 3979 return UNIT_VTABLE(u)->kill(u, w, signo, code, value, error);
8a0867d6
LP
3980}
3981
38c41427
NK
3982void unit_notify_cgroup_oom(Unit *u, bool managed_oom) {
3983 assert(u);
3984
3985 if (UNIT_VTABLE(u)->notify_cgroup_oom)
3986 UNIT_VTABLE(u)->notify_cgroup_oom(u, managed_oom);
3987}
3988
82659fd7 3989static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
af4fa99d 3990 _cleanup_set_free_ Set *pid_set = NULL;
82659fd7
LP
3991 int r;
3992
d5099efc 3993 pid_set = set_new(NULL);
82659fd7
LP
3994 if (!pid_set)
3995 return NULL;
3996
3997 /* Exclude the main/control pids from being killed via the cgroup */
3998 if (main_pid > 0) {
fea72cc0 3999 r = set_put(pid_set, PID_TO_PTR(main_pid));
82659fd7 4000 if (r < 0)
95f14a3e 4001 return NULL;
82659fd7
LP
4002 }
4003
4004 if (control_pid > 0) {
fea72cc0 4005 r = set_put(pid_set, PID_TO_PTR(control_pid));
82659fd7 4006 if (r < 0)
95f14a3e 4007 return NULL;
82659fd7
LP
4008 }
4009
95f14a3e 4010 return TAKE_PTR(pid_set);
82659fd7
LP
4011}
4012
d9911002
LP
4013static int kill_common_log(pid_t pid, int signo, void *userdata) {
4014 _cleanup_free_ char *comm = NULL;
99534007 4015 Unit *u = ASSERT_PTR(userdata);
d9911002
LP
4016
4017 (void) get_process_comm(pid, &comm);
4018 log_unit_info(u, "Sending signal SIG%s to process " PID_FMT " (%s) on client request.",
4019 signal_to_string(signo), pid, strna(comm));
4020
4021 return 1;
4022}
4023
a721cd00
LP
4024static int kill_or_sigqueue(pid_t pid, int signo, int code, int value) {
4025 assert(pid > 0);
4026 assert(SIGNAL_VALID(signo));
4027
4028 switch (code) {
4029
4030 case SI_USER:
4031 log_debug("Killing " PID_FMT " with signal SIG%s.", pid, signal_to_string(signo));
4032 return RET_NERRNO(kill(pid, signo));
4033
4034 case SI_QUEUE:
4035 log_debug("Enqueuing value %i to " PID_FMT " on signal SIG%s.", value, pid, signal_to_string(signo));
4036 return RET_NERRNO(sigqueue(pid, signo, (const union sigval) { .sival_int = value }));
4037
4038 default:
4039 assert_not_reached();
4040 }
4041}
4042
d91c34f2
LP
4043int unit_kill_common(
4044 Unit *u,
4045 KillWho who,
4046 int signo,
a721cd00
LP
4047 int code,
4048 int value,
d91c34f2
LP
4049 pid_t main_pid,
4050 pid_t control_pid,
718db961 4051 sd_bus_error *error) {
d91c34f2 4052
ac5e3a50 4053 bool killed = false;
a721cd00 4054 int ret = 0, r;
814cc562 4055
8aff7ac4
LP
4056 /* This is the common implementation for explicit user-requested killing of unit processes, shared by
4057 * various unit types. Do not confuse with unit_kill_context(), which is what we use when we want to
4058 * stop a service ourselves. */
4059
a721cd00
LP
4060 assert(u);
4061 assert(who >= 0);
4062 assert(who < _KILL_WHO_MAX);
4063 assert(SIGNAL_VALID(signo));
4064 assert(IN_SET(code, SI_USER, SI_QUEUE));
4065
ac5e3a50 4066 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
814cc562 4067 if (main_pid < 0)
7358dc02 4068 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
8aff7ac4 4069 if (main_pid == 0)
7358dc02 4070 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
814cc562
MS
4071 }
4072
ac5e3a50 4073 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
814cc562 4074 if (control_pid < 0)
7358dc02 4075 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
8aff7ac4 4076 if (control_pid == 0)
7358dc02 4077 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
814cc562
MS
4078 }
4079
a721cd00
LP
4080 if (control_pid > 0 &&
4081 IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL)) {
4082 _cleanup_free_ char *comm = NULL;
4083 (void) get_process_comm(control_pid, &comm);
d9911002 4084
a721cd00
LP
4085 r = kill_or_sigqueue(control_pid, signo, code, value);
4086 if (r < 0) {
4087 ret = r;
4088
4089 /* Report this failure both to the logs and to the client */
4090 sd_bus_error_set_errnof(
4091 error, r,
4092 "Failed to send signal SIG%s to control process " PID_FMT " (%s): %m",
4093 signal_to_string(signo), control_pid, strna(comm));
4094 log_unit_warning_errno(
4095 u, r,
4096 "Failed to send signal SIG%s to control process " PID_FMT " (%s) on client request: %m",
4097 signal_to_string(signo), control_pid, strna(comm));
4098 } else {
4099 log_unit_info(u, "Sent signal SIG%s to control process " PID_FMT " (%s) on client request.",
4100 signal_to_string(signo), control_pid, strna(comm));
4101 killed = true;
ac5e3a50 4102 }
a721cd00 4103 }
814cc562 4104
a721cd00
LP
4105 if (main_pid > 0 &&
4106 IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL)) {
d9911002 4107
a721cd00
LP
4108 _cleanup_free_ char *comm = NULL;
4109 (void) get_process_comm(main_pid, &comm);
d9911002 4110
a721cd00
LP
4111 r = kill_or_sigqueue(main_pid, signo, code, value);
4112 if (r < 0) {
4113 if (ret == 0) {
4114 ret = r;
4115
4116 sd_bus_error_set_errnof(
4117 error, r,
4118 "Failed to send signal SIG%s to main process " PID_FMT " (%s): %m",
d9911002 4119 signal_to_string(signo), main_pid, strna(comm));
d9911002 4120 }
a721cd00
LP
4121
4122 log_unit_warning_errno(
4123 u, r,
4124 "Failed to send signal SIG%s to main process " PID_FMT " (%s) on client request: %m",
4125 signal_to_string(signo), main_pid, strna(comm));
4126
4127 } else {
4128 log_unit_info(u, "Sent signal SIG%s to main process " PID_FMT " (%s) on client request.",
4129 signal_to_string(signo), main_pid, strna(comm));
4130 killed = true;
ac5e3a50 4131 }
a721cd00 4132 }
814cc562 4133
a721cd00
LP
4134 /* Note: if we shall enqueue rather than kill we won't do this via the cgroup mechanism, since it
4135 * doesn't really make much sense (and given that enqueued values are a relatively expensive
4136 * resource, and we shouldn't allow us to be subjects for such allocation sprees) */
4137 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path && code == SI_USER) {
814cc562 4138 _cleanup_set_free_ Set *pid_set = NULL;
814cc562 4139
82659fd7
LP
4140 /* Exclude the main/control pids from being killed via the cgroup */
4141 pid_set = unit_pid_set(main_pid, control_pid);
814cc562 4142 if (!pid_set)
d9911002
LP
4143 return log_oom();
4144
a721cd00
LP
4145 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, 0, pid_set, kill_common_log, u);
4146 if (r < 0) {
4147 if (!IN_SET(r, -ESRCH, -ENOENT)) {
4148 if (ret == 0) {
4149 ret = r;
4150
d9911002 4151 sd_bus_error_set_errnof(
a721cd00 4152 error, r,
d9911002
LP
4153 "Failed to send signal SIG%s to auxiliary processes: %m",
4154 signal_to_string(signo));
a721cd00 4155 }
d9911002 4156
a721cd00
LP
4157 log_unit_warning_errno(
4158 u, r,
d9911002
LP
4159 "Failed to send signal SIG%s to auxiliary processes on client request: %m",
4160 signal_to_string(signo));
4161 }
4162 } else
ac5e3a50 4163 killed = true;
814cc562
MS
4164 }
4165
2ae0508e 4166 /* If the "fail" versions of the operation are requested, then complain if the set of processes we killed is empty */
a721cd00 4167 if (ret == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_MAIN_FAIL))
2ae0508e 4168 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No matching processes to kill");
ac5e3a50 4169
a721cd00 4170 return ret;
814cc562
MS
4171}
4172
6210e7fc
LP
4173int unit_following_set(Unit *u, Set **s) {
4174 assert(u);
4175 assert(s);
4176
4177 if (UNIT_VTABLE(u)->following_set)
4178 return UNIT_VTABLE(u)->following_set(u, s);
4179
4180 *s = NULL;
4181 return 0;
4182}
4183
a4375746 4184UnitFileState unit_get_unit_file_state(Unit *u) {
0ec0deaa
LP
4185 int r;
4186
a4375746
LP
4187 assert(u);
4188
0ec0deaa
LP
4189 if (u->unit_file_state < 0 && u->fragment_path) {
4190 r = unit_file_get_state(
4870133b 4191 u->manager->runtime_scope,
0ec0deaa 4192 NULL,
9ea3a0e7 4193 u->id,
0ec0deaa
LP
4194 &u->unit_file_state);
4195 if (r < 0)
4196 u->unit_file_state = UNIT_FILE_BAD;
4197 }
a4375746 4198
ac155bb8 4199 return u->unit_file_state;
a4375746
LP
4200}
4201
e77e07f6 4202PresetAction unit_get_unit_file_preset(Unit *u) {
a99626c1
LP
4203 int r;
4204
d2dc52db
LP
4205 assert(u);
4206
a99626c1
LP
4207 if (u->unit_file_preset < 0 && u->fragment_path) {
4208 _cleanup_free_ char *bn = NULL;
4209
4210 r = path_extract_filename(u->fragment_path, &bn);
4211 if (r < 0)
4212 return (u->unit_file_preset = r);
4213
4214 if (r == O_DIRECTORY)
4215 return (u->unit_file_preset = -EISDIR);
4216
d2dc52db 4217 u->unit_file_preset = unit_file_query_preset(
4870133b 4218 u->manager->runtime_scope,
0ec0deaa 4219 NULL,
a99626c1 4220 bn,
8f7b2566 4221 NULL);
a99626c1 4222 }
d2dc52db
LP
4223
4224 return u->unit_file_preset;
4225}
4226
7f7d01ed 4227Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target) {
57020a3a 4228 assert(ref);
7f7d01ed
ZJS
4229 assert(source);
4230 assert(target);
57020a3a 4231
7f7d01ed 4232 if (ref->target)
57020a3a
LP
4233 unit_ref_unset(ref);
4234
7f7d01ed
ZJS
4235 ref->source = source;
4236 ref->target = target;
4237 LIST_PREPEND(refs_by_target, target->refs_by_target, ref);
4238 return target;
57020a3a
LP
4239}
4240
4241void unit_ref_unset(UnitRef *ref) {
4242 assert(ref);
4243
7f7d01ed 4244 if (!ref->target)
57020a3a
LP
4245 return;
4246
b75102e5
LP
4247 /* We are about to drop a reference to the unit, make sure the garbage collection has a look at it as it might
4248 * be unreferenced now. */
7f7d01ed 4249 unit_add_to_gc_queue(ref->target);
b75102e5 4250
7f7d01ed
ZJS
4251 LIST_REMOVE(refs_by_target, ref->target->refs_by_target, ref);
4252 ref->source = ref->target = NULL;
57020a3a
LP
4253}
4254
29206d46
LP
4255static int user_from_unit_name(Unit *u, char **ret) {
4256
4257 static const uint8_t hash_key[] = {
4258 0x58, 0x1a, 0xaf, 0xe6, 0x28, 0x58, 0x4e, 0x96,
4259 0xb4, 0x4e, 0xf5, 0x3b, 0x8c, 0x92, 0x07, 0xec
4260 };
4261
4262 _cleanup_free_ char *n = NULL;
4263 int r;
4264
4265 r = unit_name_to_prefix(u->id, &n);
4266 if (r < 0)
4267 return r;
4268
7a8867ab 4269 if (valid_user_group_name(n, 0)) {
ae2a15bc 4270 *ret = TAKE_PTR(n);
29206d46
LP
4271 return 0;
4272 }
4273
4274 /* If we can't use the unit name as a user name, then let's hash it and use that */
4275 if (asprintf(ret, "_du%016" PRIx64, siphash24(n, strlen(n), hash_key)) < 0)
4276 return -ENOMEM;
4277
4278 return 0;
4279}
4280
598459ce
LP
4281int unit_patch_contexts(Unit *u) {
4282 CGroupContext *cc;
4283 ExecContext *ec;
cba6e062
LP
4284 int r;
4285
e06c73cc 4286 assert(u);
e06c73cc 4287
598459ce
LP
4288 /* Patch in the manager defaults into the exec and cgroup
4289 * contexts, _after_ the rest of the settings have been
4290 * initialized */
085afe36 4291
598459ce
LP
4292 ec = unit_get_exec_context(u);
4293 if (ec) {
4294 /* This only copies in the ones that need memory */
12375b95 4295 for (unsigned i = 0; i < _RLIMIT_MAX; i++)
598459ce
LP
4296 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
4297 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
4298 if (!ec->rlimit[i])
4299 return -ENOMEM;
4300 }
4301
463d0d15 4302 if (MANAGER_IS_USER(u->manager) &&
598459ce
LP
4303 !ec->working_directory) {
4304
4305 r = get_home_dir(&ec->working_directory);
4306 if (r < 0)
4307 return r;
4c08c824
LP
4308
4309 /* Allow user services to run, even if the
4310 * home directory is missing */
4311 ec->working_directory_missing_ok = true;
cba6e062
LP
4312 }
4313
598459ce 4314 if (ec->private_devices)
2cd0a735 4315 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) | (UINT64_C(1) << CAP_SYS_RAWIO));
502d704e
DH
4316
4317 if (ec->protect_kernel_modules)
4318 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
29206d46 4319
84703040
KK
4320 if (ec->protect_kernel_logs)
4321 ec->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
4322
fc64760d
KK
4323 if (ec->protect_clock)
4324 ec->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) | (UINT64_C(1) << CAP_WAKE_ALARM));
4325
29206d46
LP
4326 if (ec->dynamic_user) {
4327 if (!ec->user) {
4328 r = user_from_unit_name(u, &ec->user);
4329 if (r < 0)
4330 return r;
4331 }
4332
4333 if (!ec->group) {
4334 ec->group = strdup(ec->user);
4335 if (!ec->group)
4336 return -ENOMEM;
4337 }
4338
bf65b7e0
LP
4339 /* If the dynamic user option is on, let's make sure that the unit can't leave its
4340 * UID/GID around in the file system or on IPC objects. Hence enforce a strict
4341 * sandbox. */
63bb64a0 4342
29206d46 4343 ec->private_tmp = true;
00d9ef85 4344 ec->remove_ipc = true;
63bb64a0
LP
4345 ec->protect_system = PROTECT_SYSTEM_STRICT;
4346 if (ec->protect_home == PROTECT_HOME_NO)
4347 ec->protect_home = PROTECT_HOME_READ_ONLY;
bf65b7e0
LP
4348
4349 /* Make sure this service can neither benefit from SUID/SGID binaries nor create
4350 * them. */
4351 ec->no_new_privileges = true;
4352 ec->restrict_suid_sgid = true;
29206d46 4353 }
a2ab603c
YW
4354
4355 for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++)
4356 exec_directory_sort(ec->directories + dt);
cba6e062
LP
4357 }
4358
598459ce 4359 cc = unit_get_cgroup_context(u);
fe65e88b 4360 if (cc && ec) {
f513e420 4361
fe65e88b 4362 if (ec->private_devices &&
084870f9
ZJS
4363 cc->device_policy == CGROUP_DEVICE_POLICY_AUTO)
4364 cc->device_policy = CGROUP_DEVICE_POLICY_CLOSED;
fe65e88b 4365
63857bf4
LB
4366 /* Only add these if needed, as they imply that everything else is blocked. */
4367 if (cc->device_policy != CGROUP_DEVICE_POLICY_AUTO || cc->device_allow) {
4368 if (ec->root_image || ec->mount_images) {
4369
4370 /* When RootImage= or MountImages= is specified, the following devices are touched. */
4371 FOREACH_STRING(p, "/dev/loop-control", "/dev/mapper/control") {
4372 r = cgroup_add_device_allow(cc, p, "rw");
4373 if (r < 0)
4374 return r;
4375 }
4376 FOREACH_STRING(p, "block-loop", "block-blkext", "block-device-mapper") {
4377 r = cgroup_add_device_allow(cc, p, "rwm");
4378 if (r < 0)
4379 return r;
4380 }
fe65e88b 4381
63857bf4
LB
4382 /* Make sure "block-loop" can be resolved, i.e. make sure "loop" shows up in /proc/devices.
4383 * Same for mapper and verity. */
4384 FOREACH_STRING(p, "modprobe@loop.service", "modprobe@dm_mod.service", "modprobe@dm_verity.service") {
4385 r = unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_WANTS, p, true, UNIT_DEPENDENCY_FILE);
4386 if (r < 0)
4387 return r;
4388 }
0cffae95 4389 }
867af728 4390
63857bf4
LB
4391 if (ec->protect_clock) {
4392 r = cgroup_add_device_allow(cc, "char-rtc", "r");
0cffae95
LB
4393 if (r < 0)
4394 return r;
4395 }
398dc7d3
LB
4396
4397 /* If there are encrypted credentials we might need to access the TPM. */
50a4217b 4398 if (exec_context_has_encrypted_credentials(ec)) {
df637af4 4399 r = cgroup_add_device_allow(cc, "char-tpm", "rw");
d5902569
AD
4400 if (r < 0)
4401 return r;
4402 }
fe65e88b 4403 }
598459ce 4404 }
f1660f96 4405
cba6e062 4406 return 0;
e06c73cc
LP
4407}
4408
c2503e35 4409ExecContext *unit_get_exec_context(const Unit *u) {
3ef63c31
LP
4410 size_t offset;
4411 assert(u);
4412
598459ce
LP
4413 if (u->type < 0)
4414 return NULL;
4415
3ef63c31
LP
4416 offset = UNIT_VTABLE(u)->exec_context_offset;
4417 if (offset <= 0)
4418 return NULL;
4419
4420 return (ExecContext*) ((uint8_t*) u + offset);
4421}
4422
718db961
LP
4423KillContext *unit_get_kill_context(Unit *u) {
4424 size_t offset;
4425 assert(u);
4426
598459ce
LP
4427 if (u->type < 0)
4428 return NULL;
4429
718db961
LP
4430 offset = UNIT_VTABLE(u)->kill_context_offset;
4431 if (offset <= 0)
4432 return NULL;
4433
4434 return (KillContext*) ((uint8_t*) u + offset);
4435}
4436
4ad49000
LP
4437CGroupContext *unit_get_cgroup_context(Unit *u) {
4438 size_t offset;
4439
598459ce
LP
4440 if (u->type < 0)
4441 return NULL;
4442
4ad49000
LP
4443 offset = UNIT_VTABLE(u)->cgroup_context_offset;
4444 if (offset <= 0)
4445 return NULL;
4446
4447 return (CGroupContext*) ((uint8_t*) u + offset);
4448}
4449
28135da3 4450ExecRuntime *unit_get_exec_runtime(Unit *u) {
613b411c
LP
4451 size_t offset;
4452
598459ce
LP
4453 if (u->type < 0)
4454 return NULL;
4455
613b411c
LP
4456 offset = UNIT_VTABLE(u)->exec_runtime_offset;
4457 if (offset <= 0)
4458 return NULL;
4459
28135da3 4460 return *(ExecRuntime**) ((uint8_t*) u + offset);
613b411c
LP
4461}
4462
2e59b241 4463static const char* unit_drop_in_dir(Unit *u, UnitWriteFlags flags) {
3f5e8115
LP
4464 assert(u);
4465
2e59b241 4466 if (UNIT_WRITE_FLAGS_NOOP(flags))
4f4afc88
LP
4467 return NULL;
4468
39591351
LP
4469 if (u->transient) /* Redirect drop-ins for transient units always into the transient directory. */
4470 return u->manager->lookup_paths.transient;
26d04f86 4471
2e59b241 4472 if (flags & UNIT_PERSISTENT)
4f4afc88 4473 return u->manager->lookup_paths.persistent_control;
26d04f86 4474
2e59b241
LP
4475 if (flags & UNIT_RUNTIME)
4476 return u->manager->lookup_paths.runtime_control;
4477
39591351 4478 return NULL;
71645aca
LP
4479}
4480
68ecb48b
ZJS
4481const char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf) {
4482 assert(s);
8c41640a 4483 assert(popcount(flags & (UNIT_ESCAPE_EXEC_SYNTAX_ENV | UNIT_ESCAPE_EXEC_SYNTAX | UNIT_ESCAPE_C)) <= 1);
68ecb48b 4484 assert(buf);
24536beb
ZJS
4485
4486 _cleanup_free_ char *t = NULL;
2e59b241 4487
68ecb48b
ZJS
4488 /* Returns a string with any escaping done. If no escaping was necessary, *buf is set to NULL, and
4489 * the input pointer is returned as-is. If an allocation was needed, the return buffer pointer is
4490 * written to *buf. This means the return value always contains a properly escaped version, but *buf
4491 * only contains a pointer if an allocation was made. Callers can use this to optimize memory
4492 * allocations. */
2e59b241
LP
4493
4494 if (flags & UNIT_ESCAPE_SPECIFIERS) {
24536beb
ZJS
4495 t = specifier_escape(s);
4496 if (!t)
2e59b241
LP
4497 return NULL;
4498
24536beb 4499 s = t;
2e59b241
LP
4500 }
4501
4a055e5a 4502 /* We either do C-escaping or shell-escaping, to additionally escape characters that we parse for
e7416db1 4503 * ExecStart= and friends, i.e. '$' and quotes. */
24536beb 4504
8c41640a 4505 if (flags & (UNIT_ESCAPE_EXEC_SYNTAX_ENV | UNIT_ESCAPE_EXEC_SYNTAX)) {
e7416db1
ZJS
4506 char *t2;
4507
8c41640a
ZJS
4508 if (flags & UNIT_ESCAPE_EXEC_SYNTAX_ENV) {
4509 t2 = strreplace(s, "$", "$$");
4510 if (!t2)
4511 return NULL;
4512 free_and_replace(t, t2);
4513 }
e7416db1 4514
8c41640a 4515 t2 = shell_escape(t ?: s, "\"");
24536beb
ZJS
4516 if (!t2)
4517 return NULL;
4518 free_and_replace(t, t2);
4519
4520 s = t;
2e59b241 4521
24536beb 4522 } else if (flags & UNIT_ESCAPE_C) {
e7416db1
ZJS
4523 char *t2;
4524
4525 t2 = cescape(s);
24536beb 4526 if (!t2)
2e59b241 4527 return NULL;
24536beb 4528 free_and_replace(t, t2);
2e59b241 4529
24536beb 4530 s = t;
2e59b241
LP
4531 }
4532
68ecb48b
ZJS
4533 *buf = TAKE_PTR(t);
4534 return s;
2e59b241
LP
4535}
4536
4537char* unit_concat_strv(char **l, UnitWriteFlags flags) {
4538 _cleanup_free_ char *result = NULL;
319a4f4b 4539 size_t n = 0;
2e59b241 4540
24536beb
ZJS
4541 /* Takes a list of strings, escapes them, and concatenates them. This may be used to format command
4542 * lines in a way suitable for ExecStart= stanzas. */
2e59b241
LP
4543
4544 STRV_FOREACH(i, l) {
4545 _cleanup_free_ char *buf = NULL;
4546 const char *p;
4547 size_t a;
4548 char *q;
4549
4550 p = unit_escape_setting(*i, flags, &buf);
4551 if (!p)
4552 return NULL;
4553
4554 a = (n > 0) + 1 + strlen(p) + 1; /* separating space + " + entry + " */
319a4f4b 4555 if (!GREEDY_REALLOC(result, n + a + 1))
2e59b241
LP
4556 return NULL;
4557
4558 q = result + n;
4559 if (n > 0)
4560 *(q++) = ' ';
4561
4562 *(q++) = '"';
4563 q = stpcpy(q, p);
4564 *(q++) = '"';
4565
4566 n += a;
4567 }
4568
319a4f4b 4569 if (!GREEDY_REALLOC(result, n + 1))
2e59b241
LP
4570 return NULL;
4571
4572 result[n] = 0;
4573
ae2a15bc 4574 return TAKE_PTR(result);
2e59b241
LP
4575}
4576
4577int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data) {
4578 _cleanup_free_ char *p = NULL, *q = NULL, *escaped = NULL;
2a9a6f8a 4579 const char *dir, *wrapped;
26d04f86 4580 int r;
71645aca
LP
4581
4582 assert(u);
2e59b241
LP
4583 assert(name);
4584 assert(data);
4585
4586 if (UNIT_WRITE_FLAGS_NOOP(flags))
4587 return 0;
4588
4589 data = unit_escape_setting(data, flags, &escaped);
4590 if (!data)
4591 return -ENOMEM;
4592
4593 /* Prefix the section header. If we are writing this out as transient file, then let's suppress this if the
4594 * previous section header is the same */
4595
4596 if (flags & UNIT_PRIVATE) {
4597 if (!UNIT_VTABLE(u)->private_section)
4598 return -EINVAL;
4599
4600 if (!u->transient_file || u->last_section_private < 0)
4601 data = strjoina("[", UNIT_VTABLE(u)->private_section, "]\n", data);
4602 else if (u->last_section_private == 0)
4603 data = strjoina("\n[", UNIT_VTABLE(u)->private_section, "]\n", data);
4604 } else {
4605 if (!u->transient_file || u->last_section_private < 0)
4606 data = strjoina("[Unit]\n", data);
4607 else if (u->last_section_private > 0)
4608 data = strjoina("\n[Unit]\n", data);
4609 }
71645aca 4610
4f4afc88
LP
4611 if (u->transient_file) {
4612 /* When this is a transient unit file in creation, then let's not create a new drop-in but instead
4613 * write to the transient unit file. */
4614 fputs(data, u->transient_file);
4f4afc88 4615
2e59b241
LP
4616 if (!endswith(data, "\n"))
4617 fputc('\n', u->transient_file);
4618
4619 /* Remember which section we wrote this entry to */
4620 u->last_section_private = !!(flags & UNIT_PRIVATE);
8e2af478 4621 return 0;
2e59b241 4622 }
8e2af478 4623
2e59b241 4624 dir = unit_drop_in_dir(u, flags);
39591351
LP
4625 if (!dir)
4626 return -EINVAL;
71645aca 4627
2a9a6f8a 4628 wrapped = strjoina("# This is a drop-in unit file extension, created via \"systemctl set-property\"\n"
3f71dec5 4629 "# or an equivalent operation. Do not edit.\n",
2a9a6f8a
ZJS
4630 data,
4631 "\n");
e20b2a86 4632
815b09d3 4633 r = drop_in_file(dir, u->id, 50, name, &p, &q);
adb76a70
WC
4634 if (r < 0)
4635 return r;
4636
45639f1b 4637 (void) mkdir_p_label(p, 0755);
4dba44a5
ZJS
4638
4639 /* Make sure the drop-in dir is registered in our path cache. This way we don't need to stupidly
4640 * recreate the cache after every drop-in we write. */
4641 if (u->manager->unit_path_cache) {
be327321 4642 r = set_put_strdup(&u->manager->unit_path_cache, p);
4dba44a5
ZJS
4643 if (r < 0)
4644 return r;
4645 }
4646
2a9a6f8a 4647 r = write_string_file_atomic_label(q, wrapped);
adb76a70
WC
4648 if (r < 0)
4649 return r;
4650
815b09d3 4651 r = strv_push(&u->dropin_paths, q);
adb76a70
WC
4652 if (r < 0)
4653 return r;
815b09d3 4654 q = NULL;
adb76a70 4655
adb76a70
WC
4656 strv_uniq(u->dropin_paths);
4657
4658 u->dropin_mtime = now(CLOCK_REALTIME);
4659
4660 return 0;
26d04f86 4661}
71645aca 4662
2e59b241 4663int unit_write_settingf(Unit *u, UnitWriteFlags flags, const char *name, const char *format, ...) {
b9ec9359
LP
4664 _cleanup_free_ char *p = NULL;
4665 va_list ap;
4666 int r;
4667
4668 assert(u);
4669 assert(name);
4670 assert(format);
4671
2e59b241 4672 if (UNIT_WRITE_FLAGS_NOOP(flags))
b9ec9359
LP
4673 return 0;
4674
4675 va_start(ap, format);
4676 r = vasprintf(&p, format, ap);
4677 va_end(ap);
4678
4679 if (r < 0)
4680 return -ENOMEM;
4681
2e59b241 4682 return unit_write_setting(u, flags, name, p);
b9ec9359 4683}
71645aca 4684
c2756a68 4685int unit_make_transient(Unit *u) {
0126c8f3 4686 _cleanup_free_ char *path = NULL;
4f4afc88 4687 FILE *f;
4f4afc88 4688
c2756a68
LP
4689 assert(u);
4690
3f5e8115
LP
4691 if (!UNIT_VTABLE(u)->can_transient)
4692 return -EOPNOTSUPP;
4693
45639f1b
LP
4694 (void) mkdir_p_label(u->manager->lookup_paths.transient, 0755);
4695
657ee2d8 4696 path = path_join(u->manager->lookup_paths.transient, u->id);
4f4afc88
LP
4697 if (!path)
4698 return -ENOMEM;
4699
4700 /* Let's open the file we'll write the transient settings into. This file is kept open as long as we are
4701 * creating the transient, and is closed in unit_load(), as soon as we start loading the file. */
4702
2053593f 4703 WITH_UMASK(0022) {
4f4afc88 4704 f = fopen(path, "we");
0126c8f3 4705 if (!f)
78e334b5 4706 return -errno;
4f4afc88
LP
4707 }
4708
0126c8f3 4709 safe_fclose(u->transient_file);
4f4afc88
LP
4710 u->transient_file = f;
4711
0126c8f3 4712 free_and_replace(u->fragment_path, path);
7c65093a 4713
7c65093a
LP
4714 u->source_path = mfree(u->source_path);
4715 u->dropin_paths = strv_free(u->dropin_paths);
4716 u->fragment_mtime = u->source_mtime = u->dropin_mtime = 0;
4717
4f4afc88
LP
4718 u->load_state = UNIT_STUB;
4719 u->load_error = 0;
4720 u->transient = true;
4721
7c65093a
LP
4722 unit_add_to_dbus_queue(u);
4723 unit_add_to_gc_queue(u);
c2756a68 4724
4f4afc88
LP
4725 fputs("# This is a transient unit file, created programmatically via the systemd API. Do not edit.\n",
4726 u->transient_file);
4727
3f5e8115 4728 return 0;
c2756a68
LP
4729}
4730
c53d2d54 4731static int log_kill(pid_t pid, int sig, void *userdata) {
1d98fef1
LP
4732 _cleanup_free_ char *comm = NULL;
4733
4734 (void) get_process_comm(pid, &comm);
4735
4736 /* Don't log about processes marked with brackets, under the assumption that these are temporary processes
4737 only, like for example systemd's own PAM stub process. */
4738 if (comm && comm[0] == '(')
500cd2e8 4739 /* Although we didn't log anything, as this callback is used in unit_kill_context we must return 1
4740 * here to let the manager know that a process was killed. */
4741 return 1;
1d98fef1
LP
4742
4743 log_unit_notice(userdata,
4744 "Killing process " PID_FMT " (%s) with signal SIG%s.",
4745 pid,
4746 strna(comm),
4747 signal_to_string(sig));
c53d2d54
DB
4748
4749 return 1;
1d98fef1
LP
4750}
4751
efa75d70
LP
4752static int operation_to_signal(
4753 const KillContext *c,
4754 KillOperation k,
4755 bool *ret_noteworthy) {
4756
1d98fef1
LP
4757 assert(c);
4758
4759 switch (k) {
4760
4761 case KILL_TERMINATE:
4762 case KILL_TERMINATE_AND_LOG:
efa75d70 4763 *ret_noteworthy = false;
1d98fef1
LP
4764 return c->kill_signal;
4765
a232ebcc 4766 case KILL_RESTART:
efa75d70 4767 *ret_noteworthy = false;
a232ebcc
ZJS
4768 return restart_kill_signal(c);
4769
1d98fef1 4770 case KILL_KILL:
efa75d70 4771 *ret_noteworthy = true;
fbb48d4c 4772 return c->final_kill_signal;
1d98fef1 4773
c87700a1 4774 case KILL_WATCHDOG:
efa75d70 4775 *ret_noteworthy = true;
c87700a1 4776 return c->watchdog_signal;
1d98fef1
LP
4777
4778 default:
04499a70 4779 assert_not_reached();
1d98fef1
LP
4780 }
4781}
4782
cd2086fe
LP
4783int unit_kill_context(
4784 Unit *u,
4785 KillContext *c,
db2cb23b 4786 KillOperation k,
cd2086fe
LP
4787 pid_t main_pid,
4788 pid_t control_pid,
4789 bool main_pid_alien) {
4790
1d98fef1 4791 bool wait_for_exit = false, send_sighup;
59ec09a8 4792 cg_kill_log_func_t log_func = NULL;
b821a397 4793 int sig, r;
cd2086fe
LP
4794
4795 assert(u);
4796 assert(c);
4797
8aff7ac4
LP
4798 /* Kill the processes belonging to this unit, in preparation for shutting the unit down. Returns > 0
4799 * if we killed something worth waiting for, 0 otherwise. Do not confuse with unit_kill_common()
4800 * which is used for user-requested killing of unit processes. */
1d98fef1 4801
cd2086fe
LP
4802 if (c->kill_mode == KILL_NONE)
4803 return 0;
4804
4ab1670f
ZJS
4805 bool noteworthy;
4806 sig = operation_to_signal(c, k, &noteworthy);
4807 if (noteworthy)
4808 log_func = log_kill;
1d98fef1
LP
4809
4810 send_sighup =
4811 c->send_sighup &&
4812 IN_SET(k, KILL_TERMINATE, KILL_TERMINATE_AND_LOG) &&
4813 sig != SIGHUP;
4814
cd2086fe 4815 if (main_pid > 0) {
1d98fef1
LP
4816 if (log_func)
4817 log_func(main_pid, sig, u);
cd2086fe 4818
1d98fef1 4819 r = kill_and_sigcont(main_pid, sig);
cd2086fe
LP
4820 if (r < 0 && r != -ESRCH) {
4821 _cleanup_free_ char *comm = NULL;
1d98fef1 4822 (void) get_process_comm(main_pid, &comm);
cd2086fe 4823
b821a397 4824 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
82659fd7 4825 } else {
bc6aed7b
LP
4826 if (!main_pid_alien)
4827 wait_for_exit = true;
82659fd7 4828
1d98fef1 4829 if (r != -ESRCH && send_sighup)
d0667321 4830 (void) kill(main_pid, SIGHUP);
82659fd7 4831 }
cd2086fe
LP
4832 }
4833
4834 if (control_pid > 0) {
1d98fef1
LP
4835 if (log_func)
4836 log_func(control_pid, sig, u);
cd2086fe 4837
1d98fef1 4838 r = kill_and_sigcont(control_pid, sig);
cd2086fe
LP
4839 if (r < 0 && r != -ESRCH) {
4840 _cleanup_free_ char *comm = NULL;
1d98fef1 4841 (void) get_process_comm(control_pid, &comm);
cd2086fe 4842
b821a397 4843 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
82659fd7 4844 } else {
cd2086fe 4845 wait_for_exit = true;
82659fd7 4846
1d98fef1 4847 if (r != -ESRCH && send_sighup)
d0667321 4848 (void) kill(control_pid, SIGHUP);
82659fd7 4849 }
cd2086fe
LP
4850 }
4851
b821a397
LP
4852 if (u->cgroup_path &&
4853 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
cd2086fe
LP
4854 _cleanup_set_free_ Set *pid_set = NULL;
4855
82659fd7
LP
4856 /* Exclude the main/control pids from being killed via the cgroup */
4857 pid_set = unit_pid_set(main_pid, control_pid);
cd2086fe
LP
4858 if (!pid_set)
4859 return -ENOMEM;
4860
1d98fef1
LP
4861 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
4862 sig,
4863 CGROUP_SIGCONT|CGROUP_IGNORE_SELF,
4864 pid_set,
4865 log_func, u);
cd2086fe 4866 if (r < 0) {
4c701096 4867 if (!IN_SET(r, -EAGAIN, -ESRCH, -ENOENT))
6178e2f8 4868 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", empty_to_root(u->cgroup_path));
b821a397 4869
82659fd7 4870 } else if (r > 0) {
bc6aed7b 4871
1d9cc876
LP
4872 /* FIXME: For now, on the legacy hierarchy, we will not wait for the cgroup members to die if
4873 * we are running in a container or if this is a delegation unit, simply because cgroup
4874 * notification is unreliable in these cases. It doesn't work at all in containers, and outside
4875 * of containers it can be confused easily by left-over directories in the cgroup — which
4876 * however should not exist in non-delegated units. On the unified hierarchy that's different,
4877 * there we get proper events. Hence rely on them. */
efdb0237 4878
c22800e4 4879 if (cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0 ||
1d9cc876 4880 (detect_container() == 0 && !unit_cgroup_delegate(u)))
e9db43d5 4881 wait_for_exit = true;
58ea275a 4882
1d98fef1 4883 if (send_sighup) {
82659fd7
LP
4884 set_free(pid_set);
4885
4886 pid_set = unit_pid_set(main_pid, control_pid);
4887 if (!pid_set)
4888 return -ENOMEM;
4889
c8aa4b5b
LP
4890 (void) cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path,
4891 SIGHUP,
4892 CGROUP_IGNORE_SELF,
4893 pid_set,
4894 NULL, NULL);
82659fd7
LP
4895 }
4896 }
cd2086fe
LP
4897 }
4898
4899 return wait_for_exit;
4900}
4901
eef85c4a 4902int unit_require_mounts_for(Unit *u, const char *path, UnitDependencyMask mask) {
a57f7e2c
LP
4903 int r;
4904
4905 assert(u);
4906 assert(path);
4907
ac19bdd0
ZJS
4908 /* Registers a unit for requiring a certain path and all its prefixes. We keep a hashtable of these
4909 * paths in the unit (from the path to the UnitDependencyInfo structure indicating how to the
4910 * dependency came to be). However, we build a prefix table for all possible prefixes so that new
4911 * appearing mount units can easily determine which units to make themselves a dependency of. */
a57f7e2c 4912
70b64bd3
ZJS
4913 if (!path_is_absolute(path))
4914 return -EINVAL;
4915
ac19bdd0
ZJS
4916 if (hashmap_contains(u->requires_mounts_for, path)) /* Exit quickly if the path is already covered. */
4917 return 0;
eef85c4a 4918
ac19bdd0 4919 _cleanup_free_ char *p = strdup(path);
a57f7e2c
LP
4920 if (!p)
4921 return -ENOMEM;
4922
ac19bdd0
ZJS
4923 /* Use the canonical form of the path as the stored key. We call path_is_normalized()
4924 * only after simplification, since path_is_normalized() rejects paths with '.'.
4925 * path_is_normalized() also verifies that the path fits in PATH_MAX. */
4ff361cc 4926 path = path_simplify(p);
a57f7e2c 4927
ca8700e9 4928 if (!path_is_normalized(path))
a57f7e2c 4929 return -EPERM;
a57f7e2c 4930
ac19bdd0 4931 UnitDependencyInfo di = {
eef85c4a
LP
4932 .origin_mask = mask
4933 };
4934
ac19bdd0 4935 r = hashmap_ensure_put(&u->requires_mounts_for, &path_hash_ops, p, di.data);
ca8700e9 4936 if (r < 0)
a57f7e2c 4937 return r;
ac19bdd0
ZJS
4938 assert(r > 0);
4939 TAKE_PTR(p); /* path remains a valid pointer to the string stored in the hashmap */
a57f7e2c 4940
4cb06c59 4941 char prefix[strlen(path) + 1];
ca8700e9 4942 PATH_FOREACH_PREFIX_MORE(prefix, path) {
a57f7e2c
LP
4943 Set *x;
4944
4945 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
4946 if (!x) {
ca8700e9 4947 _cleanup_free_ char *q = NULL;
a57f7e2c 4948
548f6937 4949 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &path_hash_ops);
742f41ad
LP
4950 if (r < 0)
4951 return r;
a57f7e2c
LP
4952
4953 q = strdup(prefix);
4954 if (!q)
4955 return -ENOMEM;
4956
d5099efc 4957 x = set_new(NULL);
ca8700e9 4958 if (!x)
a57f7e2c 4959 return -ENOMEM;
a57f7e2c
LP
4960
4961 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
4962 if (r < 0) {
a57f7e2c
LP
4963 set_free(x);
4964 return r;
4965 }
ca8700e9 4966 q = NULL;
a57f7e2c
LP
4967 }
4968
4969 r = set_put(x, u);
4970 if (r < 0)
4971 return r;
4972 }
4973
4974 return 0;
4975}
4976
613b411c 4977int unit_setup_exec_runtime(Unit *u) {
28135da3 4978 _cleanup_(exec_shared_runtime_unrefp) ExecSharedRuntime *esr = NULL;
15220772 4979 _cleanup_(dynamic_creds_unrefp) DynamicCreds *dcreds = NULL;
83123a44 4980 _cleanup_set_free_ Set *units = NULL;
28135da3 4981 ExecRuntime **rt;
15220772 4982 ExecContext *ec;
613b411c 4983 size_t offset;
613b411c 4984 Unit *other;
e8a565cb 4985 int r;
613b411c
LP
4986
4987 offset = UNIT_VTABLE(u)->exec_runtime_offset;
4988 assert(offset > 0);
4989
28135da3
DDM
4990 /* Check if there already is an ExecRuntime for this unit? */
4991 rt = (ExecRuntime**) ((uint8_t*) u + offset);
613b411c
LP
4992 if (*rt)
4993 return 0;
4994
15220772
DDM
4995 ec = unit_get_exec_context(u);
4996 assert(ec);
4997
83123a44
YW
4998 r = unit_get_transitive_dependency_set(u, UNIT_ATOM_JOINS_NAMESPACE_OF, &units);
4999 if (r < 0)
5000 return r;
5001
613b411c 5002 /* Try to get it from somebody else */
83123a44 5003 SET_FOREACH(other, units) {
28135da3
DDM
5004 r = exec_shared_runtime_acquire(u->manager, NULL, other->id, false, &esr);
5005 if (r < 0)
5006 return r;
5007 if (r > 0)
5008 break;
5009 }
5010
5011 if (!esr) {
15220772 5012 r = exec_shared_runtime_acquire(u->manager, ec, u->id, true, &esr);
28135da3
DDM
5013 if (r < 0)
5014 return r;
613b411c
LP
5015 }
5016
15220772
DDM
5017 if (ec->dynamic_user) {
5018 r = dynamic_creds_make(u->manager, ec->user, ec->group, &dcreds);
5019 if (r < 0)
5020 return r;
5021 }
5022
9c0c6701 5023 r = exec_runtime_make(u, ec, esr, dcreds, rt);
28135da3
DDM
5024 if (r < 0)
5025 return r;
5026
5027 TAKE_PTR(esr);
15220772 5028 TAKE_PTR(dcreds);
28135da3
DDM
5029
5030 return r;
613b411c
LP
5031}
5032
1c2e9646 5033bool unit_type_supported(UnitType t) {
88e4bfa6
MS
5034 static int8_t cache[_UNIT_TYPE_MAX] = {}; /* -1: disabled, 1: enabled: 0: don't know */
5035 int r;
5036
1c2e9646
LP
5037 if (_unlikely_(t < 0))
5038 return false;
5039 if (_unlikely_(t >= _UNIT_TYPE_MAX))
5040 return false;
5041
88e4bfa6
MS
5042 if (cache[t] == 0) {
5043 char *e;
5044
5045 e = strjoina("SYSTEMD_SUPPORT_", unit_type_to_string(t));
5046
5047 r = getenv_bool(ascii_strupper(e));
5048 if (r < 0 && r != -ENXIO)
5049 log_debug_errno(r, "Failed to parse $%s, ignoring: %m", e);
5050
5051 cache[t] = r == 0 ? -1 : 1;
5052 }
5053 if (cache[t] < 0)
5054 return false;
5055
1c2e9646
LP
5056 if (!unit_vtable[t]->supported)
5057 return true;
5058
5059 return unit_vtable[t]->supported();
5060}
5061
8b4305c7
LP
5062void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
5063 int r;
5064
5065 assert(u);
5066 assert(where);
5067
c2503e35
RH
5068 if (!unit_log_level_test(u, LOG_NOTICE))
5069 return;
5070
db55bbf2 5071 r = dir_is_empty(where, /* ignore_hidden_or_backup= */ false);
3f602115 5072 if (r > 0 || r == -ENOTDIR)
8b4305c7
LP
5073 return;
5074 if (r < 0) {
5075 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
5076 return;
5077 }
5078
c2503e35
RH
5079 log_unit_struct(u, LOG_NOTICE,
5080 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5081 LOG_UNIT_INVOCATION_ID(u),
5082 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
5083 "WHERE=%s", where);
8b4305c7
LP
5084}
5085
25cd4964 5086int unit_fail_if_noncanonical(Unit *u, const char* where) {
58d9d89b 5087 _cleanup_free_ char *canonical_where = NULL;
8b4305c7
LP
5088 int r;
5089
5090 assert(u);
5091 assert(where);
5092
f461a28d 5093 r = chase(where, NULL, CHASE_NONEXISTENT, &canonical_where, NULL);
8b4305c7 5094 if (r < 0) {
25cd4964 5095 log_unit_debug_errno(u, r, "Failed to check %s for symlinks, ignoring: %m", where);
8b4305c7
LP
5096 return 0;
5097 }
25cd4964
AJ
5098
5099 /* We will happily ignore a trailing slash (or any redundant slashes) */
5100 if (path_equal(where, canonical_where))
8b4305c7
LP
5101 return 0;
5102
25cd4964 5103 /* No need to mention "." or "..", they would already have been rejected by unit_name_from_path() */
c2503e35
RH
5104 log_unit_struct(u, LOG_ERR,
5105 "MESSAGE_ID=" SD_MESSAGE_OVERMOUNTING_STR,
5106 LOG_UNIT_INVOCATION_ID(u),
5107 LOG_UNIT_MESSAGE(u, "Mount path %s is not canonical (contains a symlink).", where),
5108 "WHERE=%s", where);
8b4305c7
LP
5109
5110 return -ELOOP;
5111}
0f13f3bd
LP
5112
5113bool unit_is_pristine(Unit *u) {
5114 assert(u);
5115
1f832446
ZJS
5116 /* Check if the unit already exists or is already around, in a number of different ways. Note that to
5117 * cater for unit types such as slice, we are generally fine with units that are marked UNIT_LOADED
5118 * even though nothing was actually loaded, as those unit types don't require a file on disk.
5119 *
5120 * Note that we don't check for drop-ins here, because we allow drop-ins for transient units
5121 * identically to non-transient units, both unit-specific and hierarchical. E.g. for a-b-c.service:
5122 * service.d/….conf, a-.service.d/….conf, a-b-.service.d/….conf, a-b-c.service.d/….conf.
5123 */
0f13f3bd 5124
b146a734
ZJS
5125 return IN_SET(u->load_state, UNIT_NOT_FOUND, UNIT_LOADED) &&
5126 !u->fragment_path &&
5127 !u->source_path &&
b146a734
ZJS
5128 !u->job &&
5129 !u->merged_into;
0f13f3bd 5130}
291d565a
LP
5131
5132pid_t unit_control_pid(Unit *u) {
5133 assert(u);
5134
5135 if (UNIT_VTABLE(u)->control_pid)
5136 return UNIT_VTABLE(u)->control_pid(u);
5137
5138 return 0;
5139}
5140
5141pid_t unit_main_pid(Unit *u) {
5142 assert(u);
5143
5144 if (UNIT_VTABLE(u)->main_pid)
5145 return UNIT_VTABLE(u)->main_pid(u);
5146
5147 return 0;
5148}
00d9ef85
LP
5149
5150static void unit_unref_uid_internal(
5151 Unit *u,
5152 uid_t *ref_uid,
5153 bool destroy_now,
5154 void (*_manager_unref_uid)(Manager *m, uid_t uid, bool destroy_now)) {
5155
5156 assert(u);
5157 assert(ref_uid);
5158 assert(_manager_unref_uid);
5159
5160 /* Generic implementation of both unit_unref_uid() and unit_unref_gid(), under the assumption that uid_t and
5161 * gid_t are actually the same time, with the same validity rules.
5162 *
5163 * Drops a reference to UID/GID from a unit. */
5164
5165 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5166 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5167
5168 if (!uid_is_valid(*ref_uid))
5169 return;
5170
5171 _manager_unref_uid(u->manager, *ref_uid, destroy_now);
5172 *ref_uid = UID_INVALID;
5173}
5174
b90cf102 5175static void unit_unref_uid(Unit *u, bool destroy_now) {
00d9ef85
LP
5176 unit_unref_uid_internal(u, &u->ref_uid, destroy_now, manager_unref_uid);
5177}
5178
b90cf102 5179static void unit_unref_gid(Unit *u, bool destroy_now) {
00d9ef85
LP
5180 unit_unref_uid_internal(u, (uid_t*) &u->ref_gid, destroy_now, manager_unref_gid);
5181}
5182
b90cf102
LP
5183void unit_unref_uid_gid(Unit *u, bool destroy_now) {
5184 assert(u);
5185
5186 unit_unref_uid(u, destroy_now);
5187 unit_unref_gid(u, destroy_now);
5188}
5189
00d9ef85
LP
5190static int unit_ref_uid_internal(
5191 Unit *u,
5192 uid_t *ref_uid,
5193 uid_t uid,
5194 bool clean_ipc,
5195 int (*_manager_ref_uid)(Manager *m, uid_t uid, bool clean_ipc)) {
5196
5197 int r;
5198
5199 assert(u);
5200 assert(ref_uid);
5201 assert(uid_is_valid(uid));
5202 assert(_manager_ref_uid);
5203
5204 /* Generic implementation of both unit_ref_uid() and unit_ref_guid(), under the assumption that uid_t and gid_t
5205 * are actually the same type, and have the same validity rules.
5206 *
5207 * Adds a reference on a specific UID/GID to this unit. Each unit referencing the same UID/GID maintains a
5208 * reference so that we can destroy the UID/GID's IPC resources as soon as this is requested and the counter
5209 * drops to zero. */
5210
5211 assert_cc(sizeof(uid_t) == sizeof(gid_t));
5212 assert_cc(UID_INVALID == (uid_t) GID_INVALID);
5213
5214 if (*ref_uid == uid)
5215 return 0;
5216
5217 if (uid_is_valid(*ref_uid)) /* Already set? */
5218 return -EBUSY;
5219
5220 r = _manager_ref_uid(u->manager, uid, clean_ipc);
5221 if (r < 0)
5222 return r;
5223
5224 *ref_uid = uid;
5225 return 1;
5226}
5227
b90cf102 5228static int unit_ref_uid(Unit *u, uid_t uid, bool clean_ipc) {
00d9ef85
LP
5229 return unit_ref_uid_internal(u, &u->ref_uid, uid, clean_ipc, manager_ref_uid);
5230}
5231
b90cf102 5232static int unit_ref_gid(Unit *u, gid_t gid, bool clean_ipc) {
00d9ef85
LP
5233 return unit_ref_uid_internal(u, (uid_t*) &u->ref_gid, (uid_t) gid, clean_ipc, manager_ref_gid);
5234}
5235
5236static int unit_ref_uid_gid_internal(Unit *u, uid_t uid, gid_t gid, bool clean_ipc) {
5237 int r = 0, q = 0;
5238
5239 assert(u);
5240
5241 /* Reference both a UID and a GID in one go. Either references both, or neither. */
5242
5243 if (uid_is_valid(uid)) {
5244 r = unit_ref_uid(u, uid, clean_ipc);
5245 if (r < 0)
5246 return r;
5247 }
5248
5249 if (gid_is_valid(gid)) {
5250 q = unit_ref_gid(u, gid, clean_ipc);
5251 if (q < 0) {
5252 if (r > 0)
5253 unit_unref_uid(u, false);
5254
5255 return q;
5256 }
5257 }
5258
5259 return r > 0 || q > 0;
5260}
5261
5262int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid) {
5263 ExecContext *c;
5264 int r;
5265
5266 assert(u);
5267
5268 c = unit_get_exec_context(u);
5269
5270 r = unit_ref_uid_gid_internal(u, uid, gid, c ? c->remove_ipc : false);
5271 if (r < 0)
5272 return log_unit_warning_errno(u, r, "Couldn't add UID/GID reference to unit, proceeding without: %m");
5273
5274 return r;
5275}
5276
00d9ef85
LP
5277void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid) {
5278 int r;
5279
5280 assert(u);
5281
5282 /* This is invoked whenever one of the forked off processes let's us know the UID/GID its user name/group names
5283 * resolved to. We keep track of which UID/GID is currently assigned in order to be able to destroy its IPC
5284 * objects when no service references the UID/GID anymore. */
5285
5286 r = unit_ref_uid_gid(u, uid, gid);
5287 if (r > 0)
37d0b962 5288 unit_add_to_dbus_queue(u);
00d9ef85 5289}
4b58153d 5290
4b58153d
LP
5291int unit_acquire_invocation_id(Unit *u) {
5292 sd_id128_t id;
5293 int r;
5294
5295 assert(u);
5296
5297 r = sd_id128_randomize(&id);
5298 if (r < 0)
5299 return log_unit_error_errno(u, r, "Failed to generate invocation ID for unit: %m");
5300
5301 r = unit_set_invocation_id(u, id);
5302 if (r < 0)
5303 return log_unit_error_errno(u, r, "Failed to set invocation ID for unit: %m");
5304
af92c603 5305 unit_add_to_dbus_queue(u);
4b58153d
LP
5306 return 0;
5307}
f0d47797 5308
1ad6e8b3
LP
5309int unit_set_exec_params(Unit *u, ExecParameters *p) {
5310 int r;
5311
7960b0c7
LP
5312 assert(u);
5313 assert(p);
f0d47797 5314
004c7f16 5315 /* Copy parameters from manager */
1ad6e8b3
LP
5316 r = manager_get_effective_environment(u->manager, &p->environment);
5317 if (r < 0)
5318 return r;
5319
170d978b
LP
5320 p->runtime_scope = u->manager->runtime_scope;
5321
004c7f16
LP
5322 p->confirm_spawn = manager_get_confirm_spawn(u->manager);
5323 p->cgroup_supported = u->manager->cgroup_supported;
5324 p->prefix = u->manager->prefix;
5325 SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
5326
5238e957 5327 /* Copy parameters from unit */
7960b0c7 5328 p->cgroup_path = u->cgroup_path;
1d9cc876 5329 SET_FLAG(p->flags, EXEC_CGROUP_DELEGATE, unit_cgroup_delegate(u));
1ad6e8b3 5330
2ad591a3
LP
5331 p->received_credentials_directory = u->manager->received_credentials_directory;
5332 p->received_encrypted_credentials_directory = u->manager->received_encrypted_credentials_directory;
bb0c0d6f 5333
1ad6e8b3 5334 return 0;
f0d47797 5335}
a79279c7 5336
4c253ed1 5337int unit_fork_helper_process(Unit *u, const char *name, pid_t *ret) {
a79279c7
LP
5338 int r;
5339
5340 assert(u);
5341 assert(ret);
5342
5343 /* Forks off a helper process and makes sure it is a member of the unit's cgroup. Returns == 0 in the child,
5344 * and > 0 in the parent. The pid parameter is always filled in with the child's PID. */
5345
5346 (void) unit_realize_cgroup(u);
5347
54c0ba34 5348 r = safe_fork(name, FORK_REOPEN_LOG|FORK_DEATHSIG, ret);
4c253ed1
LP
5349 if (r != 0)
5350 return r;
a79279c7 5351
9c274488
LP
5352 (void) default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE);
5353 (void) ignore_signals(SIGPIPE);
a79279c7 5354
4c253ed1
LP
5355 if (u->cgroup_path) {
5356 r = cg_attach_everywhere(u->manager->cgroup_supported, u->cgroup_path, 0, NULL, NULL);
5357 if (r < 0) {
6178e2f8 5358 log_unit_error_errno(u, r, "Failed to join unit cgroup %s: %m", empty_to_root(u->cgroup_path));
4c253ed1 5359 _exit(EXIT_CGROUP);
a79279c7 5360 }
a79279c7
LP
5361 }
5362
4c253ed1 5363 return 0;
a79279c7 5364}
c999cf38 5365
810ef318
YW
5366int unit_fork_and_watch_rm_rf(Unit *u, char **paths, pid_t *ret_pid) {
5367 pid_t pid;
5368 int r;
5369
5370 assert(u);
5371 assert(ret_pid);
5372
5373 r = unit_fork_helper_process(u, "(sd-rmrf)", &pid);
5374 if (r < 0)
5375 return r;
5376 if (r == 0) {
5377 int ret = EXIT_SUCCESS;
810ef318
YW
5378
5379 STRV_FOREACH(i, paths) {
5380 r = rm_rf(*i, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
5381 if (r < 0) {
5382 log_error_errno(r, "Failed to remove '%s': %m", *i);
5383 ret = EXIT_FAILURE;
5384 }
5385 }
5386
5387 _exit(ret);
5388 }
5389
5390 r = unit_watch_pid(u, pid, true);
5391 if (r < 0)
5392 return r;
5393
5394 *ret_pid = pid;
5395 return 0;
5396}
5397
15ed3c3a
LP
5398static void unit_update_dependency_mask(Hashmap *deps, Unit *other, UnitDependencyInfo di) {
5399 assert(deps);
c999cf38
LP
5400 assert(other);
5401
15ed3c3a 5402 if (di.origin_mask == 0 && di.destination_mask == 0)
c999cf38 5403 /* No bit set anymore, let's drop the whole entry */
15ed3c3a
LP
5404 assert_se(hashmap_remove(deps, other));
5405 else
c999cf38 5406 /* Mask was reduced, let's update the entry */
15ed3c3a 5407 assert_se(hashmap_update(deps, other, di.data) == 0);
c999cf38
LP
5408}
5409
5410void unit_remove_dependencies(Unit *u, UnitDependencyMask mask) {
15ed3c3a 5411 Hashmap *deps;
c999cf38
LP
5412 assert(u);
5413
5414 /* Removes all dependencies u has on other units marked for ownership by 'mask'. */
5415
5416 if (mask == 0)
5417 return;
5418
15ed3c3a 5419 HASHMAP_FOREACH(deps, u->dependencies) {
c999cf38
LP
5420 bool done;
5421
5422 do {
5423 UnitDependencyInfo di;
5424 Unit *other;
c999cf38
LP
5425
5426 done = true;
5427
15ed3c3a
LP
5428 HASHMAP_FOREACH_KEY(di.data, other, deps) {
5429 Hashmap *other_deps;
5430
1d6cc5d0 5431 if (FLAGS_SET(~mask, di.origin_mask))
c999cf38 5432 continue;
15ed3c3a 5433
c999cf38 5434 di.origin_mask &= ~mask;
15ed3c3a 5435 unit_update_dependency_mask(deps, other, di);
c999cf38 5436
defe63b0
LP
5437 /* We updated the dependency from our unit to the other unit now. But most
5438 * dependencies imply a reverse dependency. Hence, let's delete that one
5439 * too. For that we go through all dependency types on the other unit and
5440 * delete all those which point to us and have the right mask set. */
c999cf38 5441
15ed3c3a 5442 HASHMAP_FOREACH(other_deps, other->dependencies) {
c999cf38
LP
5443 UnitDependencyInfo dj;
5444
15ed3c3a 5445 dj.data = hashmap_get(other_deps, u);
1d6cc5d0 5446 if (FLAGS_SET(~mask, dj.destination_mask))
c999cf38 5447 continue;
c999cf38 5448
15ed3c3a
LP
5449 dj.destination_mask &= ~mask;
5450 unit_update_dependency_mask(other_deps, u, dj);
c999cf38
LP
5451 }
5452
5453 unit_add_to_gc_queue(other);
5454
156ba52b
YW
5455 /* The unit 'other' may not be wanted by the unit 'u'. */
5456 unit_submit_to_stop_when_unneeded_queue(other);
5457
c999cf38
LP
5458 done = false;
5459 break;
5460 }
5461
5462 } while (!done);
5463 }
5464}
d3070fbd 5465
2f8c48b6
AZ
5466static int unit_get_invocation_path(Unit *u, char **ret) {
5467 char *p;
5468 int r;
5469
5470 assert(u);
5471 assert(ret);
5472
5473 if (MANAGER_IS_SYSTEM(u->manager))
5474 p = strjoin("/run/systemd/units/invocation:", u->id);
5475 else {
5476 _cleanup_free_ char *user_path = NULL;
5477 r = xdg_user_runtime_dir(&user_path, "/systemd/units/invocation:");
5478 if (r < 0)
5479 return r;
5480 p = strjoin(user_path, u->id);
5481 }
5482
5483 if (!p)
5484 return -ENOMEM;
5485
5486 *ret = p;
5487 return 0;
5488}
5489
d3070fbd 5490static int unit_export_invocation_id(Unit *u) {
2f8c48b6 5491 _cleanup_free_ char *p = NULL;
d3070fbd
LP
5492 int r;
5493
5494 assert(u);
5495
5496 if (u->exported_invocation_id)
5497 return 0;
5498
5499 if (sd_id128_is_null(u->invocation_id))
5500 return 0;
5501
2f8c48b6
AZ
5502 r = unit_get_invocation_path(u, &p);
5503 if (r < 0)
5504 return log_unit_debug_errno(u, r, "Failed to get invocation path: %m");
5505
a3f5fd96 5506 r = symlink_atomic_label(u->invocation_id_string, p);
d3070fbd
LP
5507 if (r < 0)
5508 return log_unit_debug_errno(u, r, "Failed to create invocation ID symlink %s: %m", p);
5509
5510 u->exported_invocation_id = true;
5511 return 0;
5512}
5513
5514static int unit_export_log_level_max(Unit *u, const ExecContext *c) {
5515 const char *p;
5516 char buf[2];
5517 int r;
5518
5519 assert(u);
5520 assert(c);
5521
5522 if (u->exported_log_level_max)
5523 return 0;
5524
5525 if (c->log_level_max < 0)
5526 return 0;
5527
5528 assert(c->log_level_max <= 7);
5529
5530 buf[0] = '0' + c->log_level_max;
5531 buf[1] = 0;
5532
5533 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5534 r = symlink_atomic(buf, p);
5535 if (r < 0)
5536 return log_unit_debug_errno(u, r, "Failed to create maximum log level symlink %s: %m", p);
5537
5538 u->exported_log_level_max = true;
5539 return 0;
5540}
5541
5542static int unit_export_log_extra_fields(Unit *u, const ExecContext *c) {
254d1313 5543 _cleanup_close_ int fd = -EBADF;
d3070fbd
LP
5544 struct iovec *iovec;
5545 const char *p;
5546 char *pattern;
5547 le64_t *sizes;
5548 ssize_t n;
d3070fbd
LP
5549 int r;
5550
5551 if (u->exported_log_extra_fields)
5552 return 0;
5553
5554 if (c->n_log_extra_fields <= 0)
5555 return 0;
5556
5557 sizes = newa(le64_t, c->n_log_extra_fields);
5558 iovec = newa(struct iovec, c->n_log_extra_fields * 2);
5559
12375b95 5560 for (size_t i = 0; i < c->n_log_extra_fields; i++) {
d3070fbd
LP
5561 sizes[i] = htole64(c->log_extra_fields[i].iov_len);
5562
5563 iovec[i*2] = IOVEC_MAKE(sizes + i, sizeof(le64_t));
5564 iovec[i*2+1] = c->log_extra_fields[i];
5565 }
5566
5567 p = strjoina("/run/systemd/units/log-extra-fields:", u->id);
5568 pattern = strjoina(p, ".XXXXXX");
5569
5570 fd = mkostemp_safe(pattern);
5571 if (fd < 0)
5572 return log_unit_debug_errno(u, fd, "Failed to create extra fields file %s: %m", p);
5573
5574 n = writev(fd, iovec, c->n_log_extra_fields*2);
5575 if (n < 0) {
5576 r = log_unit_debug_errno(u, errno, "Failed to write extra fields: %m");
5577 goto fail;
5578 }
5579
5580 (void) fchmod(fd, 0644);
5581
5582 if (rename(pattern, p) < 0) {
5583 r = log_unit_debug_errno(u, errno, "Failed to rename extra fields file: %m");
5584 goto fail;
5585 }
5586
5587 u->exported_log_extra_fields = true;
5588 return 0;
5589
5590fail:
5591 (void) unlink(pattern);
5592 return r;
5593}
5594
5ac1530e 5595static int unit_export_log_ratelimit_interval(Unit *u, const ExecContext *c) {
90fc172e
AZ
5596 _cleanup_free_ char *buf = NULL;
5597 const char *p;
5598 int r;
5599
5600 assert(u);
5601 assert(c);
5602
5ac1530e 5603 if (u->exported_log_ratelimit_interval)
90fc172e
AZ
5604 return 0;
5605
5ac1530e 5606 if (c->log_ratelimit_interval_usec == 0)
90fc172e
AZ
5607 return 0;
5608
5609 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5610
5ac1530e 5611 if (asprintf(&buf, "%" PRIu64, c->log_ratelimit_interval_usec) < 0)
90fc172e
AZ
5612 return log_oom();
5613
5614 r = symlink_atomic(buf, p);
5615 if (r < 0)
5616 return log_unit_debug_errno(u, r, "Failed to create log rate limit interval symlink %s: %m", p);
5617
5ac1530e 5618 u->exported_log_ratelimit_interval = true;
90fc172e
AZ
5619 return 0;
5620}
5621
5ac1530e 5622static int unit_export_log_ratelimit_burst(Unit *u, const ExecContext *c) {
90fc172e
AZ
5623 _cleanup_free_ char *buf = NULL;
5624 const char *p;
5625 int r;
5626
5627 assert(u);
5628 assert(c);
5629
5ac1530e 5630 if (u->exported_log_ratelimit_burst)
90fc172e
AZ
5631 return 0;
5632
5ac1530e 5633 if (c->log_ratelimit_burst == 0)
90fc172e
AZ
5634 return 0;
5635
5636 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5637
5ac1530e 5638 if (asprintf(&buf, "%u", c->log_ratelimit_burst) < 0)
90fc172e
AZ
5639 return log_oom();
5640
5641 r = symlink_atomic(buf, p);
5642 if (r < 0)
5643 return log_unit_debug_errno(u, r, "Failed to create log rate limit burst symlink %s: %m", p);
5644
5ac1530e 5645 u->exported_log_ratelimit_burst = true;
90fc172e
AZ
5646 return 0;
5647}
5648
d3070fbd
LP
5649void unit_export_state_files(Unit *u) {
5650 const ExecContext *c;
5651
5652 assert(u);
5653
5654 if (!u->id)
5655 return;
5656
638cece4 5657 if (MANAGER_IS_TEST_RUN(u->manager))
8f632531
LP
5658 return;
5659
d3070fbd
LP
5660 /* Exports a couple of unit properties to /run/systemd/units/, so that journald can quickly query this data
5661 * from there. Ideally, journald would use IPC to query this, like everybody else, but that's hard, as long as
5662 * the IPC system itself and PID 1 also log to the journal.
5663 *
5664 * Note that these files really shouldn't be considered API for anyone else, as use a runtime file system as
5665 * IPC replacement is not compatible with today's world of file system namespaces. However, this doesn't really
5666 * apply to communication between the journal and systemd, as we assume that these two daemons live in the same
5667 * namespace at least.
5668 *
5669 * Note that some of the "files" exported here are actually symlinks and not regular files. Symlinks work
5670 * better for storing small bits of data, in particular as we can write them with two system calls, and read
5671 * them with one. */
5672
5673 (void) unit_export_invocation_id(u);
5674
2f8c48b6
AZ
5675 if (!MANAGER_IS_SYSTEM(u->manager))
5676 return;
5677
d3070fbd
LP
5678 c = unit_get_exec_context(u);
5679 if (c) {
5680 (void) unit_export_log_level_max(u, c);
5681 (void) unit_export_log_extra_fields(u, c);
5ac1530e
ZJS
5682 (void) unit_export_log_ratelimit_interval(u, c);
5683 (void) unit_export_log_ratelimit_burst(u, c);
d3070fbd
LP
5684 }
5685}
5686
5687void unit_unlink_state_files(Unit *u) {
5688 const char *p;
5689
5690 assert(u);
5691
5692 if (!u->id)
5693 return;
5694
d3070fbd
LP
5695 /* Undoes the effect of unit_export_state() */
5696
5697 if (u->exported_invocation_id) {
2f8c48b6
AZ
5698 _cleanup_free_ char *invocation_path = NULL;
5699 int r = unit_get_invocation_path(u, &invocation_path);
5700 if (r >= 0) {
5701 (void) unlink(invocation_path);
5702 u->exported_invocation_id = false;
5703 }
d3070fbd
LP
5704 }
5705
2f8c48b6
AZ
5706 if (!MANAGER_IS_SYSTEM(u->manager))
5707 return;
5708
d3070fbd
LP
5709 if (u->exported_log_level_max) {
5710 p = strjoina("/run/systemd/units/log-level-max:", u->id);
5711 (void) unlink(p);
5712
5713 u->exported_log_level_max = false;
5714 }
5715
5716 if (u->exported_log_extra_fields) {
5717 p = strjoina("/run/systemd/units/extra-fields:", u->id);
5718 (void) unlink(p);
5719
5720 u->exported_log_extra_fields = false;
5721 }
90fc172e 5722
5ac1530e 5723 if (u->exported_log_ratelimit_interval) {
90fc172e
AZ
5724 p = strjoina("/run/systemd/units/log-rate-limit-interval:", u->id);
5725 (void) unlink(p);
5726
5ac1530e 5727 u->exported_log_ratelimit_interval = false;
90fc172e
AZ
5728 }
5729
5ac1530e 5730 if (u->exported_log_ratelimit_burst) {
90fc172e
AZ
5731 p = strjoina("/run/systemd/units/log-rate-limit-burst:", u->id);
5732 (void) unlink(p);
5733
5ac1530e 5734 u->exported_log_ratelimit_burst = false;
90fc172e 5735 }
d3070fbd 5736}
5afe510c 5737
3c7416b6
LP
5738int unit_prepare_exec(Unit *u) {
5739 int r;
5740
5741 assert(u);
5742
fab34748
KL
5743 /* Load any custom firewall BPF programs here once to test if they are existing and actually loadable.
5744 * Fail here early since later errors in the call chain unit_realize_cgroup to cgroup_context_apply are ignored. */
5745 r = bpf_firewall_load_custom(u);
5746 if (r < 0)
5747 return r;
5748
3c7416b6
LP
5749 /* Prepares everything so that we can fork of a process for this unit */
5750
5751 (void) unit_realize_cgroup(u);
5752
5753 if (u->reset_accounting) {
9b2559a1 5754 (void) unit_reset_accounting(u);
3c7416b6
LP
5755 u->reset_accounting = false;
5756 }
5757
5758 unit_export_state_files(u);
5759
5760 r = unit_setup_exec_runtime(u);
5761 if (r < 0)
5762 return r;
5763
3c7416b6
LP
5764 return 0;
5765}
5766
4c425434
LP
5767static bool ignore_leftover_process(const char *comm) {
5768 return comm && comm[0] == '('; /* Most likely our own helper process (PAM?), ignore */
5769}
5770
5771int unit_log_leftover_process_start(pid_t pid, int sig, void *userdata) {
a4634b21
LP
5772 _cleanup_free_ char *comm = NULL;
5773
5774 (void) get_process_comm(pid, &comm);
5775
4c425434 5776 if (ignore_leftover_process(comm))
c53d2d54 5777 return 0;
a4634b21 5778
4c425434
LP
5779 /* During start we print a warning */
5780
a4634b21
LP
5781 log_unit_warning(userdata,
5782 "Found left-over process " PID_FMT " (%s) in control group while starting unit. Ignoring.\n"
5783 "This usually indicates unclean termination of a previous run, or service implementation deficiencies.",
5784 pid, strna(comm));
c53d2d54
DB
5785
5786 return 1;
a4634b21
LP
5787}
5788
4c425434
LP
5789int unit_log_leftover_process_stop(pid_t pid, int sig, void *userdata) {
5790 _cleanup_free_ char *comm = NULL;
5791
5792 (void) get_process_comm(pid, &comm);
5793
5794 if (ignore_leftover_process(comm))
5795 return 0;
5796
5797 /* During stop we only print an informational message */
5798
5799 log_unit_info(userdata,
5800 "Unit process " PID_FMT " (%s) remains running after unit stopped.",
5801 pid, strna(comm));
5802
5803 return 1;
5804}
5805
5806int unit_warn_leftover_processes(Unit *u, cg_kill_log_func_t log_func) {
a4634b21
LP
5807 assert(u);
5808
5809 (void) unit_pick_cgroup_path(u);
5810
5811 if (!u->cgroup_path)
c53d2d54 5812 return 0;
a4634b21 5813
4c425434 5814 return cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, 0, 0, NULL, log_func, u);
a4634b21
LP
5815}
5816
bb2c7685
LP
5817bool unit_needs_console(Unit *u) {
5818 ExecContext *ec;
5819 UnitActiveState state;
5820
5821 assert(u);
5822
5823 state = unit_active_state(u);
5824
5825 if (UNIT_IS_INACTIVE_OR_FAILED(state))
5826 return false;
5827
5828 if (UNIT_VTABLE(u)->needs_console)
5829 return UNIT_VTABLE(u)->needs_console(u);
5830
5831 /* If this unit type doesn't implement this call, let's use a generic fallback implementation: */
5832 ec = unit_get_exec_context(u);
5833 if (!ec)
5834 return false;
5835
5836 return exec_context_may_touch_console(ec);
5837}
5838
6592b975
LP
5839int unit_pid_attachable(Unit *u, pid_t pid, sd_bus_error *error) {
5840 int r;
5841
5842 assert(u);
5843
5844 /* Checks whether the specified PID is generally good for attaching, i.e. a valid PID, not our manager itself,
5845 * and not a kernel thread either */
5846
5847 /* First, a simple range check */
5848 if (!pid_is_valid(pid))
5849 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process identifier " PID_FMT " is not valid.", pid);
5850
5851 /* Some extra safety check */
5852 if (pid == 1 || pid == getpid_cached())
3fe91079 5853 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a manager process, refusing.", pid);
6592b975
LP
5854
5855 /* Don't even begin to bother with kernel threads */
5856 r = is_kernel_thread(pid);
5857 if (r == -ESRCH)
5858 return sd_bus_error_setf(error, SD_BUS_ERROR_UNIX_PROCESS_ID_UNKNOWN, "Process with ID " PID_FMT " does not exist.", pid);
5859 if (r < 0)
5860 return sd_bus_error_set_errnof(error, r, "Failed to determine whether process " PID_FMT " is a kernel thread: %m", pid);
5861 if (r > 0)
5862 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Process " PID_FMT " is a kernel thread, refusing.", pid);
5863
5864 return 0;
5865}
5866
523ee2d4
LP
5867void unit_log_success(Unit *u) {
5868 assert(u);
5869
edf2ee22
JM
5870 /* Let's show message "Deactivated successfully" in debug mode (when manager is user) rather than in info mode.
5871 * This message has low information value for regular users and it might be a bit overwhelming on a system with
5872 * a lot of devices. */
5873 log_unit_struct(u,
5874 MANAGER_IS_USER(u->manager) ? LOG_DEBUG : LOG_INFO,
c2503e35
RH
5875 "MESSAGE_ID=" SD_MESSAGE_UNIT_SUCCESS_STR,
5876 LOG_UNIT_INVOCATION_ID(u),
5877 LOG_UNIT_MESSAGE(u, "Deactivated successfully."));
523ee2d4
LP
5878}
5879
7c047d74
LP
5880void unit_log_failure(Unit *u, const char *result) {
5881 assert(u);
5882 assert(result);
5883
c2503e35
RH
5884 log_unit_struct(u, LOG_WARNING,
5885 "MESSAGE_ID=" SD_MESSAGE_UNIT_FAILURE_RESULT_STR,
5886 LOG_UNIT_INVOCATION_ID(u),
5887 LOG_UNIT_MESSAGE(u, "Failed with result '%s'.", result),
5888 "UNIT_RESULT=%s", result);
7c047d74
LP
5889}
5890
31cd5f63
AZ
5891void unit_log_skip(Unit *u, const char *result) {
5892 assert(u);
5893 assert(result);
5894
c2503e35
RH
5895 log_unit_struct(u, LOG_INFO,
5896 "MESSAGE_ID=" SD_MESSAGE_UNIT_SKIPPED_STR,
5897 LOG_UNIT_INVOCATION_ID(u),
5898 LOG_UNIT_MESSAGE(u, "Skipped due to '%s'.", result),
5899 "UNIT_RESULT=%s", result);
31cd5f63
AZ
5900}
5901
91bbd9b7
LP
5902void unit_log_process_exit(
5903 Unit *u,
91bbd9b7
LP
5904 const char *kind,
5905 const char *command,
5cc2cd1c 5906 bool success,
91bbd9b7
LP
5907 int code,
5908 int status) {
5909
5cc2cd1c
ZJS
5910 int level;
5911
91bbd9b7
LP
5912 assert(u);
5913 assert(kind);
5914
5cc2cd1c
ZJS
5915 /* If this is a successful exit, let's log about the exit code on DEBUG level. If this is a failure
5916 * and the process exited on its own via exit(), then let's make this a NOTICE, under the assumption
5917 * that the service already logged the reason at a higher log level on its own. Otherwise, make it a
5918 * WARNING. */
5919 if (success)
5920 level = LOG_DEBUG;
5921 else if (code == CLD_EXITED)
5922 level = LOG_NOTICE;
5923 else
91bbd9b7
LP
5924 level = LOG_WARNING;
5925
c2503e35
RH
5926 log_unit_struct(u, level,
5927 "MESSAGE_ID=" SD_MESSAGE_UNIT_PROCESS_EXIT_STR,
58441bc1 5928 LOG_UNIT_MESSAGE(u, "%s exited, code=%s, status=%i/%s%s",
c2503e35
RH
5929 kind,
5930 sigchld_code_to_string(code), status,
5931 strna(code == CLD_EXITED
5932 ? exit_status_to_string(status, EXIT_STATUS_FULL)
58441bc1
ZJS
5933 : signal_to_string(status)),
5934 success ? " (success)" : ""),
c2503e35
RH
5935 "EXIT_CODE=%s", sigchld_code_to_string(code),
5936 "EXIT_STATUS=%i", status,
5937 "COMMAND=%s", strna(command),
5938 LOG_UNIT_INVOCATION_ID(u));
91bbd9b7
LP
5939}
5940
7af67e9a
LP
5941int unit_exit_status(Unit *u) {
5942 assert(u);
5943
5944 /* Returns the exit status to propagate for the most recent cycle of this unit. Returns a value in the range
5945 * 0…255 if there's something to propagate. EOPNOTSUPP if the concept does not apply to this unit type, ENODATA
5946 * if no data is currently known (for example because the unit hasn't deactivated yet) and EBADE if the main
5947 * service process has exited abnormally (signal/coredump). */
5948
5949 if (!UNIT_VTABLE(u)->exit_status)
5950 return -EOPNOTSUPP;
5951
5952 return UNIT_VTABLE(u)->exit_status(u);
5953}
5954
5955int unit_failure_action_exit_status(Unit *u) {
5956 int r;
5957
5958 assert(u);
5959
5960 /* Returns the exit status to propagate on failure, or an error if there's nothing to propagate */
5961
5962 if (u->failure_action_exit_status >= 0)
5963 return u->failure_action_exit_status;
5964
5965 r = unit_exit_status(u);
5966 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
5967 return 255;
5968
5969 return r;
5970}
5971
5972int unit_success_action_exit_status(Unit *u) {
5973 int r;
5974
5975 assert(u);
5976
5977 /* Returns the exit status to propagate on success, or an error if there's nothing to propagate */
5978
5979 if (u->success_action_exit_status >= 0)
5980 return u->success_action_exit_status;
5981
5982 r = unit_exit_status(u);
5983 if (r == -EBADE) /* Exited, but not cleanly (i.e. by signal or such) */
5984 return 255;
5985
5986 return r;
5987}
5988
a4191c9f
LP
5989int unit_test_trigger_loaded(Unit *u) {
5990 Unit *trigger;
5991
5992 /* Tests whether the unit to trigger is loaded */
5993
5994 trigger = UNIT_TRIGGER(u);
5995 if (!trigger)
e7b9f4d9
ZJS
5996 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
5997 "Refusing to start, no unit to trigger.");
a4191c9f 5998 if (trigger->load_state != UNIT_LOADED)
e7b9f4d9
ZJS
5999 return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
6000 "Refusing to start, unit %s to trigger not loaded.", trigger->id);
a4191c9f
LP
6001
6002 return 0;
6003}
6004
bb0c0d6f
LP
6005void unit_destroy_runtime_data(Unit *u, const ExecContext *context) {
6006 assert(u);
6007 assert(context);
6008
1ba84fef
LP
6009 /* EXEC_PRESERVE_RESTART is handled via unit_release_resources()! */
6010 if (context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
95939aed 6011 exec_context_destroy_runtime_directory(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
bb0c0d6f
LP
6012
6013 exec_context_destroy_credentials(context, u->manager->prefix[EXEC_DIRECTORY_RUNTIME], u->id);
b9f976fb 6014 exec_context_destroy_mount_ns_dir(u);
95939aed
YW
6015}
6016
380dc8b0
LP
6017int unit_clean(Unit *u, ExecCleanMask mask) {
6018 UnitActiveState state;
6019
6020 assert(u);
6021
6022 /* Special return values:
6023 *
6024 * -EOPNOTSUPP → cleaning not supported for this unit type
6025 * -EUNATCH → cleaning not defined for this resource type
6026 * -EBUSY → unit currently can't be cleaned since it's running or not properly loaded, or has
6027 * a job queued or similar
6028 */
6029
6030 if (!UNIT_VTABLE(u)->clean)
6031 return -EOPNOTSUPP;
6032
6033 if (mask == 0)
6034 return -EUNATCH;
6035
6036 if (u->load_state != UNIT_LOADED)
6037 return -EBUSY;
6038
6039 if (u->job)
6040 return -EBUSY;
6041
6042 state = unit_active_state(u);
4f06325c 6043 if (state != UNIT_INACTIVE)
380dc8b0
LP
6044 return -EBUSY;
6045
6046 return UNIT_VTABLE(u)->clean(u, mask);
6047}
6048
6049int unit_can_clean(Unit *u, ExecCleanMask *ret) {
6050 assert(u);
6051
6052 if (!UNIT_VTABLE(u)->clean ||
6053 u->load_state != UNIT_LOADED) {
6054 *ret = 0;
6055 return 0;
6056 }
6057
6058 /* When the clean() method is set, can_clean() really should be set too */
6059 assert(UNIT_VTABLE(u)->can_clean);
6060
6061 return UNIT_VTABLE(u)->can_clean(u, ret);
6062}
6063
d9e45bc3
MS
6064bool unit_can_freeze(Unit *u) {
6065 assert(u);
6066
6067 if (UNIT_VTABLE(u)->can_freeze)
6068 return UNIT_VTABLE(u)->can_freeze(u);
6069
6070 return UNIT_VTABLE(u)->freeze;
6071}
6072
6073void unit_frozen(Unit *u) {
6074 assert(u);
6075
6076 u->freezer_state = FREEZER_FROZEN;
6077
3d19e122 6078 bus_unit_send_pending_freezer_message(u, false);
d9e45bc3
MS
6079}
6080
6081void unit_thawed(Unit *u) {
6082 assert(u);
6083
6084 u->freezer_state = FREEZER_RUNNING;
6085
3d19e122 6086 bus_unit_send_pending_freezer_message(u, false);
d9e45bc3
MS
6087}
6088
6089static int unit_freezer_action(Unit *u, FreezerAction action) {
6090 UnitActiveState s;
6091 int (*method)(Unit*);
6092 int r;
6093
6094 assert(u);
6095 assert(IN_SET(action, FREEZER_FREEZE, FREEZER_THAW));
6096
6097 method = action == FREEZER_FREEZE ? UNIT_VTABLE(u)->freeze : UNIT_VTABLE(u)->thaw;
6098 if (!method || !cg_freezer_supported())
6099 return -EOPNOTSUPP;
6100
6101 if (u->job)
6102 return -EBUSY;
6103
6104 if (u->load_state != UNIT_LOADED)
6105 return -EHOSTDOWN;
6106
6107 s = unit_active_state(u);
6108 if (s != UNIT_ACTIVE)
6109 return -EHOSTDOWN;
6110
3d19e122 6111 if ((IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING) && action == FREEZER_FREEZE) ||
6112 (u->freezer_state == FREEZER_THAWING && action == FREEZER_THAW))
d9e45bc3
MS
6113 return -EALREADY;
6114
6115 r = method(u);
6116 if (r <= 0)
6117 return r;
6118
d171e72e
YW
6119 assert(IN_SET(u->freezer_state, FREEZER_FREEZING, FREEZER_THAWING));
6120
d9e45bc3
MS
6121 return 1;
6122}
6123
6124int unit_freeze(Unit *u) {
6125 return unit_freezer_action(u, FREEZER_FREEZE);
6126}
6127
6128int unit_thaw(Unit *u) {
6129 return unit_freezer_action(u, FREEZER_THAW);
6130}
6131
6132/* Wrappers around low-level cgroup freezer operations common for service and scope units */
6133int unit_freeze_vtable_common(Unit *u) {
6134 return unit_cgroup_freezer_action(u, FREEZER_FREEZE);
6135}
6136
6137int unit_thaw_vtable_common(Unit *u) {
6138 return unit_cgroup_freezer_action(u, FREEZER_THAW);
6139}
6140
6e548561 6141Condition *unit_find_failed_condition(Unit *u) {
03677889 6142 Condition *failed_trigger = NULL;
6e548561
DDM
6143 bool has_succeeded_trigger = false;
6144
6145 if (u->condition_result)
6146 return NULL;
6147
6148 LIST_FOREACH(conditions, c, u->conditions)
6149 if (c->trigger) {
6150 if (c->result == CONDITION_SUCCEEDED)
6151 has_succeeded_trigger = true;
6152 else if (!failed_trigger)
6153 failed_trigger = c;
6154 } else if (c->result != CONDITION_SUCCEEDED)
6155 return c;
6156
6157 return failed_trigger && !has_succeeded_trigger ? failed_trigger : NULL;
6158}
6159
5afe510c
LP
6160static const char* const collect_mode_table[_COLLECT_MODE_MAX] = {
6161 [COLLECT_INACTIVE] = "inactive",
6162 [COLLECT_INACTIVE_OR_FAILED] = "inactive-or-failed",
6163};
6164
6165DEFINE_STRING_TABLE_LOOKUP(collect_mode, CollectMode);
15ed3c3a
LP
6166
6167Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other) {
6168 Unit *i;
6169
6170 assert(u);
6171
6172 /* Checks if the unit has a dependency on 'other' with the specified dependency atom. If 'other' is
6173 * NULL checks if the unit has *any* dependency of that atom. Returns 'other' if found (or if 'other'
6174 * is NULL the first entry found), or NULL if not found. */
6175
6176 UNIT_FOREACH_DEPENDENCY(i, u, atom)
6177 if (!other || other == i)
6178 return i;
6179
6180 return NULL;
6181}
6182
6183int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array) {
6184 _cleanup_free_ Unit **array = NULL;
6185 size_t n = 0;
6186 Unit *other;
6187
6188 assert(u);
6189 assert(ret_array);
6190
6191 /* Gets a list of units matching a specific atom as array. This is useful when iterating through
6192 * dependencies while modifying them: the array is an "atomic snapshot" of sorts, that can be read
48008c1c 6193 * while the dependency table is continuously updated. */
15ed3c3a
LP
6194
6195 UNIT_FOREACH_DEPENDENCY(other, u, atom) {
6196 if (!GREEDY_REALLOC(array, n + 1))
6197 return -ENOMEM;
6198
6199 array[n++] = other;
6200 }
6201
6202 *ret_array = TAKE_PTR(array);
6203
6204 assert(n <= INT_MAX);
6205 return (int) n;
6206}
48b92b37 6207
83123a44
YW
6208int unit_get_transitive_dependency_set(Unit *u, UnitDependencyAtom atom, Set **ret) {
6209 _cleanup_set_free_ Set *units = NULL, *queue = NULL;
6210 Unit *other;
6211 int r;
6212
6213 assert(u);
6214 assert(ret);
6215
6216 /* Similar to unit_get_dependency_array(), but also search the same dependency in other units. */
6217
6218 do {
6219 UNIT_FOREACH_DEPENDENCY(other, u, atom) {
6220 r = set_ensure_put(&units, NULL, other);
6221 if (r < 0)
6222 return r;
6223 if (r == 0)
6224 continue;
6225 r = set_ensure_put(&queue, NULL, other);
6226 if (r < 0)
6227 return r;
6228 }
6229 } while ((u = set_steal_first(queue)));
6230
6231 *ret = TAKE_PTR(units);
6232 return 0;
6233}
6234
48b92b37 6235const ActivationDetailsVTable * const activation_details_vtable[_UNIT_TYPE_MAX] = {
4c420328 6236 [UNIT_PATH] = &activation_details_path_vtable,
c8bc7519 6237 [UNIT_TIMER] = &activation_details_timer_vtable,
48b92b37
LB
6238};
6239
6240ActivationDetails *activation_details_new(Unit *trigger_unit) {
6241 _cleanup_free_ ActivationDetails *details = NULL;
6242
6243 assert(trigger_unit);
6244 assert(trigger_unit->type != _UNIT_TYPE_INVALID);
6245 assert(trigger_unit->id);
6246
6247 details = malloc0(activation_details_vtable[trigger_unit->type]->object_size);
6248 if (!details)
6249 return NULL;
6250
6251 *details = (ActivationDetails) {
6252 .n_ref = 1,
6253 .trigger_unit_type = trigger_unit->type,
6254 };
6255
6256 details->trigger_unit_name = strdup(trigger_unit->id);
6257 if (!details->trigger_unit_name)
6258 return NULL;
6259
6260 if (ACTIVATION_DETAILS_VTABLE(details)->init)
6261 ACTIVATION_DETAILS_VTABLE(details)->init(details, trigger_unit);
6262
6263 return TAKE_PTR(details);
6264}
6265
6266static ActivationDetails *activation_details_free(ActivationDetails *details) {
6267 if (!details)
6268 return NULL;
6269
6270 if (ACTIVATION_DETAILS_VTABLE(details)->done)
6271 ACTIVATION_DETAILS_VTABLE(details)->done(details);
6272
6273 free(details->trigger_unit_name);
6274
6275 return mfree(details);
6276}
6277
6278void activation_details_serialize(ActivationDetails *details, FILE *f) {
6279 if (!details || details->trigger_unit_type == _UNIT_TYPE_INVALID)
6280 return;
6281
6282 (void) serialize_item(f, "activation-details-unit-type", unit_type_to_string(details->trigger_unit_type));
6283 if (details->trigger_unit_name)
6284 (void) serialize_item(f, "activation-details-unit-name", details->trigger_unit_name);
6285 if (ACTIVATION_DETAILS_VTABLE(details)->serialize)
6286 ACTIVATION_DETAILS_VTABLE(details)->serialize(details, f);
6287}
6288
6289int activation_details_deserialize(const char *key, const char *value, ActivationDetails **details) {
e8dba806
FS
6290 int r;
6291
48b92b37
LB
6292 assert(key);
6293 assert(value);
6294 assert(details);
6295
6296 if (!*details) {
6297 UnitType t;
6298
6299 if (!streq(key, "activation-details-unit-type"))
6300 return -EINVAL;
6301
6302 t = unit_type_from_string(value);
210cb8d6
YW
6303 if (t < 0)
6304 return t;
6305
6306 /* The activation details vtable has defined ops only for path and timer units */
6307 if (!activation_details_vtable[t])
48b92b37
LB
6308 return -EINVAL;
6309
6310 *details = malloc0(activation_details_vtable[t]->object_size);
6311 if (!*details)
6312 return -ENOMEM;
6313
6314 **details = (ActivationDetails) {
6315 .n_ref = 1,
6316 .trigger_unit_type = t,
6317 };
6318
6319 return 0;
6320 }
6321
6322 if (streq(key, "activation-details-unit-name")) {
e8dba806
FS
6323 r = free_and_strdup(&(*details)->trigger_unit_name, value);
6324 if (r < 0)
6325 return r;
48b92b37
LB
6326
6327 return 0;
6328 }
6329
6330 if (ACTIVATION_DETAILS_VTABLE(*details)->deserialize)
6331 return ACTIVATION_DETAILS_VTABLE(*details)->deserialize(key, value, details);
6332
6333 return -EINVAL;
6334}
6335
6336int activation_details_append_env(ActivationDetails *details, char ***strv) {
6337 int r = 0;
6338
6339 assert(strv);
6340
6341 if (!details)
6342 return 0;
6343
6344 if (!isempty(details->trigger_unit_name)) {
6345 char *s = strjoin("TRIGGER_UNIT=", details->trigger_unit_name);
6346 if (!s)
6347 return -ENOMEM;
6348
6349 r = strv_consume(strv, TAKE_PTR(s));
6350 if (r < 0)
6351 return r;
6352 }
6353
6354 if (ACTIVATION_DETAILS_VTABLE(details)->append_env) {
6355 r = ACTIVATION_DETAILS_VTABLE(details)->append_env(details, strv);
6356 if (r < 0)
6357 return r;
6358 }
6359
6360 return r + !isempty(details->trigger_unit_name); /* Return the number of variables added to the env block */
6361}
6362
6363int activation_details_append_pair(ActivationDetails *details, char ***strv) {
6364 int r = 0;
6365
6366 assert(strv);
6367
6368 if (!details)
6369 return 0;
6370
6371 if (!isempty(details->trigger_unit_name)) {
6372 r = strv_extend(strv, "trigger_unit");
6373 if (r < 0)
6374 return r;
6375
6376 r = strv_extend(strv, details->trigger_unit_name);
6377 if (r < 0)
6378 return r;
6379 }
6380
6381 if (ACTIVATION_DETAILS_VTABLE(details)->append_env) {
6382 r = ACTIVATION_DETAILS_VTABLE(details)->append_pair(details, strv);
6383 if (r < 0)
6384 return r;
6385 }
6386
6387 return r + !isempty(details->trigger_unit_name); /* Return the number of pairs added to the strv */
6388}
6389
6390DEFINE_TRIVIAL_REF_UNREF_FUNC(ActivationDetails, activation_details, activation_details_free);