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