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