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