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