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