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