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