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