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