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