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