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