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