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