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