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