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