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