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