]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/unit.c
util: move string_is_safe() to string-util.[ch]
[thirdparty/systemd.git] / src / core / unit.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
87f0e418 2
a7334b09
LP
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
87f0e418 22#include <errno.h>
0301abf4 23#include <stdlib.h>
4f5dd394 24#include <string.h>
45fb0699 25#include <sys/stat.h>
4f5dd394 26#include <unistd.h>
87f0e418 27
718db961
LP
28#include "sd-id128.h"
29#include "sd-messages.h"
4f5dd394
LP
30
31#include "bus-common-errors.h"
32#include "bus-util.h"
c6c18be3 33#include "cgroup-util.h"
4f5dd394
LP
34#include "dbus-unit.h"
35#include "dbus.h"
36#include "dropin.h"
37#include "escape.h"
38#include "execute.h"
a5c32cff 39#include "fileio-label.h"
6482f626 40#include "formats-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"
e9db43d5 51#include "special.h"
07630cea 52#include "string-util.h"
4f5dd394
LP
53#include "strv.h"
54#include "unit-name.h"
e9db43d5 55#include "unit.h"
b1d4f8e1
LP
56#include "user-util.h"
57#include "virt.h"
87f0e418
LP
58
59const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
60 [UNIT_SERVICE] = &service_vtable,
87f0e418 61 [UNIT_SOCKET] = &socket_vtable,
e821075a 62 [UNIT_BUSNAME] = &busname_vtable,
87f0e418 63 [UNIT_TARGET] = &target_vtable,
e821075a 64 [UNIT_SNAPSHOT] = &snapshot_vtable,
87f0e418
LP
65 [UNIT_DEVICE] = &device_vtable,
66 [UNIT_MOUNT] = &mount_vtable,
67 [UNIT_AUTOMOUNT] = &automount_vtable,
01f78473 68 [UNIT_SWAP] = &swap_vtable,
e821075a 69 [UNIT_TIMER] = &timer_vtable,
a016b922 70 [UNIT_PATH] = &path_vtable,
6c12b52e
LP
71 [UNIT_SLICE] = &slice_vtable,
72 [UNIT_SCOPE] = &scope_vtable
87f0e418
LP
73};
74
f2341e0a 75static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
d1fab3fe 76
7d17cfbc 77Unit *unit_new(Manager *m, size_t size) {
87f0e418
LP
78 Unit *u;
79
80 assert(m);
ac155bb8 81 assert(size >= sizeof(Unit));
87f0e418 82
7d17cfbc
MS
83 u = malloc0(size);
84 if (!u)
87f0e418
LP
85 return NULL;
86
d5099efc 87 u->names = set_new(&string_hash_ops);
ac155bb8 88 if (!u->names) {
87f0e418
LP
89 free(u);
90 return NULL;
91 }
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;
87f0e418 100
67bfdc97 101 RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16);
bea355da 102
87f0e418
LP
103 return u;
104}
105
f278026d
LP
106bool unit_has_name(Unit *u, const char *name) {
107 assert(u);
108 assert(name);
109
ac155bb8 110 return !!set_get(u->names, (char*) name);
f278026d
LP
111}
112
598459ce
LP
113static void unit_init(Unit *u) {
114 CGroupContext *cc;
115 ExecContext *ec;
116 KillContext *kc;
117
118 assert(u);
119 assert(u->manager);
120 assert(u->type >= 0);
121
122 cc = unit_get_cgroup_context(u);
123 if (cc) {
124 cgroup_context_init(cc);
125
126 /* Copy in the manager defaults into the cgroup
127 * context, _before_ the rest of the settings have
128 * been initialized */
129
130 cc->cpu_accounting = u->manager->default_cpu_accounting;
131 cc->blockio_accounting = u->manager->default_blockio_accounting;
132 cc->memory_accounting = u->manager->default_memory_accounting;
03a7b521 133 cc->tasks_accounting = u->manager->default_tasks_accounting;
598459ce
LP
134 }
135
136 ec = unit_get_exec_context(u);
137 if (ec)
138 exec_context_init(ec);
139
140 kc = unit_get_kill_context(u);
141 if (kc)
142 kill_context_init(kc);
143
144 if (UNIT_VTABLE(u)->init)
145 UNIT_VTABLE(u)->init(u);
146}
147
87f0e418 148int unit_add_name(Unit *u, const char *text) {
598459ce 149 _cleanup_free_ char *s = NULL, *i = NULL;
87f0e418 150 UnitType t;
87f0e418
LP
151 int r;
152
153 assert(u);
154 assert(text);
155
7410616c 156 if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
598459ce 157
ac155bb8 158 if (!u->instance)
9e2f7c11 159 return -EINVAL;
87f0e418 160
7410616c
LP
161 r = unit_name_replace_instance(text, u->instance, &s);
162 if (r < 0)
163 return r;
164 } else {
9e2f7c11 165 s = strdup(text);
7410616c
LP
166 if (!s)
167 return -ENOMEM;
168 }
87f0e418 169
7410616c
LP
170 if (set_contains(u->names, s))
171 return 0;
172 if (hashmap_contains(u->manager->units, s))
173 return -EEXIST;
174
175 if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
598459ce 176 return -EINVAL;
e537352b 177
7410616c
LP
178 t = unit_name_to_type(s);
179 if (t < 0)
180 return -EINVAL;
87f0e418 181
598459ce
LP
182 if (u->type != _UNIT_TYPE_INVALID && t != u->type)
183 return -EINVAL;
87f0e418 184
e48614c4
ZJS
185 r = unit_name_to_instance(s, &i);
186 if (r < 0)
598459ce 187 return r;
87f0e418 188
598459ce
LP
189 if (i && unit_vtable[t]->no_instances)
190 return -EINVAL;
9e2f7c11 191
276c3e78 192 /* Ensure that this unit is either instanced or not instanced,
7410616c
LP
193 * but not both. Note that we do allow names with different
194 * instance names however! */
598459ce
LP
195 if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i)
196 return -EINVAL;
9e2f7c11 197
7410616c 198 if (unit_vtable[t]->no_alias && !set_isempty(u->names))
598459ce 199 return -EEXIST;
9e2f7c11 200
598459ce
LP
201 if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
202 return -E2BIG;
4f0f902f 203
e48614c4 204 r = set_put(u->names, s);
7410616c 205 if (r < 0)
598459ce 206 return r;
7410616c 207 assert(r > 0);
87f0e418 208
e48614c4
ZJS
209 r = hashmap_put(u->manager->units, s, u);
210 if (r < 0) {
7410616c 211 (void) set_remove(u->names, s);
598459ce 212 return r;
87f0e418
LP
213 }
214
ac155bb8 215 if (u->type == _UNIT_TYPE_INVALID) {
ac155bb8
MS
216 u->type = t;
217 u->id = s;
218 u->instance = i;
9e2f7c11 219
71fda00f 220 LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
e537352b 221
598459ce 222 unit_init(u);
87f0e418 223
598459ce
LP
224 i = NULL;
225 }
9e2f7c11 226
598459ce 227 s = NULL;
9e2f7c11 228
598459ce
LP
229 unit_add_to_dbus_queue(u);
230 return 0;
87f0e418
LP
231}
232
0ae97ec1 233int unit_choose_id(Unit *u, const char *name) {
68eda4bd 234 _cleanup_free_ char *t = NULL;
598459ce 235 char *s, *i;
276c3e78 236 int r;
0ae97ec1
LP
237
238 assert(u);
239 assert(name);
240
7410616c 241 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
9e2f7c11 242
ac155bb8 243 if (!u->instance)
9e2f7c11
LP
244 return -EINVAL;
245
7410616c
LP
246 r = unit_name_replace_instance(name, u->instance, &t);
247 if (r < 0)
248 return r;
9e2f7c11
LP
249
250 name = t;
251 }
252
0ae97ec1 253 /* Selects one of the names of this unit as the id */
ac155bb8 254 s = set_get(u->names, (char*) name);
9e2f7c11 255 if (!s)
0ae97ec1
LP
256 return -ENOENT;
257
7410616c 258 /* Determine the new instance from the new id */
e48614c4
ZJS
259 r = unit_name_to_instance(s, &i);
260 if (r < 0)
276c3e78
LP
261 return r;
262
ac155bb8 263 u->id = s;
276c3e78 264
ac155bb8
MS
265 free(u->instance);
266 u->instance = i;
276c3e78 267
c1e1601e 268 unit_add_to_dbus_queue(u);
9e2f7c11 269
0ae97ec1
LP
270 return 0;
271}
272
f50e0a01
LP
273int unit_set_description(Unit *u, const char *description) {
274 char *s;
275
276 assert(u);
277
8aec412f
LP
278 if (isempty(description))
279 s = NULL;
280 else {
281 s = strdup(description);
282 if (!s)
283 return -ENOMEM;
284 }
f50e0a01 285
ac155bb8
MS
286 free(u->description);
287 u->description = s;
c1e1601e
LP
288
289 unit_add_to_dbus_queue(u);
f50e0a01
LP
290 return 0;
291}
292
701cc384 293bool unit_check_gc(Unit *u) {
a354329f 294 UnitActiveState state;
701cc384
LP
295 assert(u);
296
a354329f 297 if (u->job)
701cc384
LP
298 return true;
299
a354329f 300 if (u->nop_job)
6c073082
LP
301 return true;
302
a354329f
LP
303 state = unit_active_state(u);
304
305 /* If the unit is inactive and failed and no job is queued for
306 * it, then release its runtime resources */
307 if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
308 UNIT_VTABLE(u)->release_resources)
309 UNIT_VTABLE(u)->release_resources(u);
310
311 /* But we keep the unit object around for longer when it is
312 * referenced or configured to not be gc'ed */
313 if (state != UNIT_INACTIVE)
701cc384
LP
314 return true;
315
a354329f 316 if (UNIT_VTABLE(u)->no_gc)
e0209d83
MS
317 return true;
318
a354329f 319 if (u->no_gc)
701cc384
LP
320 return true;
321
9d576438
LP
322 if (u->refs)
323 return true;
324
701cc384
LP
325 if (UNIT_VTABLE(u)->check_gc)
326 if (UNIT_VTABLE(u)->check_gc(u))
327 return true;
328
329 return false;
330}
331
87f0e418
LP
332void unit_add_to_load_queue(Unit *u) {
333 assert(u);
ac155bb8 334 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 335
ac155bb8 336 if (u->load_state != UNIT_STUB || u->in_load_queue)
87f0e418
LP
337 return;
338
71fda00f 339 LIST_PREPEND(load_queue, u->manager->load_queue, u);
ac155bb8 340 u->in_load_queue = true;
87f0e418
LP
341}
342
23a177ef
LP
343void unit_add_to_cleanup_queue(Unit *u) {
344 assert(u);
345
ac155bb8 346 if (u->in_cleanup_queue)
23a177ef
LP
347 return;
348
71fda00f 349 LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
ac155bb8 350 u->in_cleanup_queue = true;
23a177ef
LP
351}
352
701cc384
LP
353void unit_add_to_gc_queue(Unit *u) {
354 assert(u);
355
ac155bb8 356 if (u->in_gc_queue || u->in_cleanup_queue)
701cc384
LP
357 return;
358
359 if (unit_check_gc(u))
360 return;
361
71fda00f 362 LIST_PREPEND(gc_queue, u->manager->gc_queue, u);
ac155bb8 363 u->in_gc_queue = true;
701cc384 364
ac155bb8 365 u->manager->n_in_gc_queue ++;
701cc384
LP
366}
367
c1e1601e
LP
368void unit_add_to_dbus_queue(Unit *u) {
369 assert(u);
ac155bb8 370 assert(u->type != _UNIT_TYPE_INVALID);
c1e1601e 371
ac155bb8 372 if (u->load_state == UNIT_STUB || u->in_dbus_queue)
c1e1601e
LP
373 return;
374
a567261a 375 /* Shortcut things if nobody cares */
8f8f05a9
LP
376 if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
377 set_isempty(u->manager->private_buses)) {
ac155bb8 378 u->sent_dbus_new_signal = true;
94b6dfa2
LP
379 return;
380 }
381
71fda00f 382 LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
ac155bb8 383 u->in_dbus_queue = true;
c1e1601e
LP
384}
385
87f0e418
LP
386static void bidi_set_free(Unit *u, Set *s) {
387 Iterator i;
388 Unit *other;
389
390 assert(u);
391
392 /* Frees the set and makes sure we are dropped from the
393 * inverse pointers */
394
395 SET_FOREACH(other, s, i) {
396 UnitDependency d;
397
398 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 399 set_remove(other->dependencies[d], u);
701cc384
LP
400
401 unit_add_to_gc_queue(other);
87f0e418
LP
402 }
403
404 set_free(s);
405}
406
c2756a68
LP
407static void unit_remove_transient(Unit *u) {
408 char **i;
409
410 assert(u);
411
412 if (!u->transient)
413 return;
414
415 if (u->fragment_path)
3f5e8115 416 (void) unlink(u->fragment_path);
c2756a68
LP
417
418 STRV_FOREACH(i, u->dropin_paths) {
419 _cleanup_free_ char *p = NULL;
c2756a68 420
3f5e8115 421 (void) unlink(*i);
c2756a68 422
5f311f8c
LP
423 p = dirname_malloc(*i);
424 if (p)
3f5e8115 425 (void) rmdir(p);
c2756a68
LP
426 }
427}
428
a57f7e2c
LP
429static void unit_free_requires_mounts_for(Unit *u) {
430 char **j;
431
432 STRV_FOREACH(j, u->requires_mounts_for) {
433 char s[strlen(*j) + 1];
434
435 PATH_FOREACH_PREFIX_MORE(s, *j) {
436 char *y;
437 Set *x;
438
439 x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
440 if (!x)
441 continue;
442
443 set_remove(x, u);
444
445 if (set_isempty(x)) {
446 hashmap_remove(u->manager->units_requiring_mounts_for, y);
447 free(y);
448 set_free(x);
449 }
450 }
451 }
452
6796073e 453 u->requires_mounts_for = strv_free(u->requires_mounts_for);
a57f7e2c
LP
454}
455
598459ce
LP
456static void unit_done(Unit *u) {
457 ExecContext *ec;
458 CGroupContext *cc;
32ee7d33 459 int r;
598459ce
LP
460
461 assert(u);
462
463 if (u->type < 0)
464 return;
465
466 if (UNIT_VTABLE(u)->done)
467 UNIT_VTABLE(u)->done(u);
468
469 ec = unit_get_exec_context(u);
470 if (ec)
471 exec_context_done(ec);
472
473 cc = unit_get_cgroup_context(u);
474 if (cc)
475 cgroup_context_done(cc);
32ee7d33
DM
476
477 r = unit_remove_from_netclass_cgroup(u);
478 if (r < 0)
479 log_warning_errno(r, "Unable to remove unit from netclass group: %m");
598459ce
LP
480}
481
87f0e418
LP
482void unit_free(Unit *u) {
483 UnitDependency d;
484 Iterator i;
485 char *t;
486
487 assert(u);
488
c2756a68
LP
489 if (u->manager->n_reloading <= 0)
490 unit_remove_transient(u);
491
c1e1601e
LP
492 bus_unit_send_removed_signal(u);
493
598459ce 494 unit_done(u);
a013b84b 495
cf9fd508
DM
496 sd_bus_slot_unref(u->match_bus_slot);
497
a57f7e2c
LP
498 unit_free_requires_mounts_for(u);
499
ac155bb8
MS
500 SET_FOREACH(t, u->names, i)
501 hashmap_remove_value(u->manager->units, t, u);
87f0e418 502
97e7d748
MS
503 if (u->job) {
504 Job *j = u->job;
505 job_uninstall(j);
506 job_free(j);
507 }
964e0949 508
e0209d83
MS
509 if (u->nop_job) {
510 Job *j = u->nop_job;
511 job_uninstall(j);
512 job_free(j);
513 }
514
964e0949 515 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
ac155bb8 516 bidi_set_free(u, u->dependencies[d]);
964e0949 517
ac155bb8 518 if (u->type != _UNIT_TYPE_INVALID)
71fda00f 519 LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
ef734fd6 520
ac155bb8 521 if (u->in_load_queue)
71fda00f 522 LIST_REMOVE(load_queue, u->manager->load_queue, u);
87f0e418 523
ac155bb8 524 if (u->in_dbus_queue)
71fda00f 525 LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
c1e1601e 526
ac155bb8 527 if (u->in_cleanup_queue)
71fda00f 528 LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
23a177ef 529
ac155bb8 530 if (u->in_gc_queue) {
71fda00f 531 LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
ac155bb8 532 u->manager->n_in_gc_queue--;
701cc384
LP
533 }
534
4ad49000 535 if (u->in_cgroup_queue)
71fda00f 536 LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
87f0e418 537
efdb0237 538 unit_release_cgroup(u);
72673e86 539
5269eb6b 540 (void) manager_update_failed_units(u->manager, u, false);
db785129 541 set_remove(u->manager->startup_units, u);
f755e3b7 542
ac155bb8 543 free(u->description);
49dbfa7b 544 strv_free(u->documentation);
ac155bb8 545 free(u->fragment_path);
1b64d026 546 free(u->source_path);
ae7a7182 547 strv_free(u->dropin_paths);
ac155bb8 548 free(u->instance);
87f0e418 549
f189ab18
LP
550 free(u->job_timeout_reboot_arg);
551
ac155bb8 552 set_free_free(u->names);
87f0e418 553
a911bb9a
LP
554 unit_unwatch_all_pids(u);
555
ac155bb8 556 condition_free_list(u->conditions);
59fccdc5 557 condition_free_list(u->asserts);
52661efd 558
702a2d8f
LP
559 unit_ref_unset(&u->slice);
560
ac155bb8
MS
561 while (u->refs)
562 unit_ref_unset(u->refs);
57020a3a 563
87f0e418
LP
564 free(u);
565}
566
567UnitActiveState unit_active_state(Unit *u) {
568 assert(u);
569
ac155bb8 570 if (u->load_state == UNIT_MERGED)
6124958c
LP
571 return unit_active_state(unit_follow_merge(u));
572
573 /* After a reload it might happen that a unit is not correctly
574 * loaded but still has a process around. That's why we won't
fdf20a31 575 * shortcut failed loading to UNIT_INACTIVE_FAILED. */
87f0e418
LP
576
577 return UNIT_VTABLE(u)->active_state(u);
578}
579
10a94420
LP
580const char* unit_sub_state_to_string(Unit *u) {
581 assert(u);
582
583 return UNIT_VTABLE(u)->sub_state_to_string(u);
584}
585
7c0b05e5
MS
586static int complete_move(Set **s, Set **other) {
587 int r;
588
23a177ef
LP
589 assert(s);
590 assert(other);
87f0e418 591
23a177ef 592 if (!*other)
7c0b05e5 593 return 0;
87f0e418 594
7c0b05e5
MS
595 if (*s) {
596 r = set_move(*s, *other);
597 if (r < 0)
598 return r;
599 } else {
23a177ef
LP
600 *s = *other;
601 *other = NULL;
602 }
7c0b05e5
MS
603
604 return 0;
23a177ef 605}
87f0e418 606
7c0b05e5 607static int merge_names(Unit *u, Unit *other) {
23a177ef
LP
608 char *t;
609 Iterator i;
7c0b05e5 610 int r;
87f0e418 611
23a177ef
LP
612 assert(u);
613 assert(other);
614
7c0b05e5
MS
615 r = complete_move(&u->names, &other->names);
616 if (r < 0)
617 return r;
23a177ef 618
ac155bb8
MS
619 set_free_free(other->names);
620 other->names = NULL;
621 other->id = NULL;
23a177ef 622
ac155bb8
MS
623 SET_FOREACH(t, u->names, i)
624 assert_se(hashmap_replace(u->manager->units, t, u) == 0);
7c0b05e5
MS
625
626 return 0;
87f0e418
LP
627}
628
09a65f92
MS
629static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
630 unsigned n_reserve;
631
632 assert(u);
633 assert(other);
634 assert(d < _UNIT_DEPENDENCY_MAX);
635
636 /*
637 * If u does not have this dependency set allocated, there is no need
f131770b 638 * to reserve anything. In that case other's set will be transferred
09a65f92
MS
639 * as a whole to u by complete_move().
640 */
641 if (!u->dependencies[d])
642 return 0;
643
644 /* merge_dependencies() will skip a u-on-u dependency */
645 n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
646
647 return set_reserve(u->dependencies[d], n_reserve);
648}
649
d1fab3fe 650static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
23a177ef
LP
651 Iterator i;
652 Unit *back;
87f0e418 653 int r;
23a177ef
LP
654
655 assert(u);
656 assert(other);
657 assert(d < _UNIT_DEPENDENCY_MAX);
658
83a95334 659 /* Fix backwards pointers */
ac155bb8 660 SET_FOREACH(back, other->dependencies[d], i) {
23a177ef
LP
661 UnitDependency k;
662
e48614c4 663 for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
e66047ff
ZJS
664 /* Do not add dependencies between u and itself */
665 if (back == u) {
d1fab3fe 666 if (set_remove(back->dependencies[k], other))
f2341e0a 667 maybe_warn_about_dependency(u, other_id, k);
e66047ff
ZJS
668 } else {
669 r = set_remove_and_put(back->dependencies[k], other, u);
670 if (r == -EEXIST)
671 set_remove(back->dependencies[k], other);
672 else
673 assert(r >= 0 || r == -ENOENT);
674 }
e48614c4 675 }
23a177ef
LP
676 }
677
e66047ff 678 /* Also do not move dependencies on u to itself */
d1fab3fe
ZJS
679 back = set_remove(other->dependencies[d], u);
680 if (back)
f2341e0a 681 maybe_warn_about_dependency(u, other_id, d);
e66047ff 682
7c0b05e5
MS
683 /* The move cannot fail. The caller must have performed a reservation. */
684 assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
23a177ef 685
525d3cc7 686 other->dependencies[d] = set_free(other->dependencies[d]);
23a177ef
LP
687}
688
689int unit_merge(Unit *u, Unit *other) {
87f0e418 690 UnitDependency d;
d1fab3fe 691 const char *other_id = NULL;
09a65f92 692 int r;
87f0e418
LP
693
694 assert(u);
695 assert(other);
ac155bb8
MS
696 assert(u->manager == other->manager);
697 assert(u->type != _UNIT_TYPE_INVALID);
87f0e418 698
cc916967
LP
699 other = unit_follow_merge(other);
700
23a177ef
LP
701 if (other == u)
702 return 0;
703
ac155bb8 704 if (u->type != other->type)
9e2f7c11
LP
705 return -EINVAL;
706
ac155bb8 707 if (!u->instance != !other->instance)
87f0e418
LP
708 return -EINVAL;
709
ac155bb8 710 if (other->load_state != UNIT_STUB &&
c2756a68 711 other->load_state != UNIT_NOT_FOUND)
23a177ef 712 return -EEXIST;
87f0e418 713
ac155bb8 714 if (other->job)
819e213f
LP
715 return -EEXIST;
716
e0209d83
MS
717 if (other->nop_job)
718 return -EEXIST;
719
fdf20a31 720 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
819e213f
LP
721 return -EEXIST;
722
d1fab3fe
ZJS
723 if (other->id)
724 other_id = strdupa(other->id);
725
09a65f92
MS
726 /* Make reservations to ensure merge_dependencies() won't fail */
727 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
728 r = reserve_dependencies(u, other, d);
729 /*
730 * We don't rollback reservations if we fail. We don't have
731 * a way to undo reservations. A reservation is not a leak.
732 */
733 if (r < 0)
734 return r;
735 }
736
87f0e418 737 /* Merge names */
7c0b05e5
MS
738 r = merge_names(u, other);
739 if (r < 0)
740 return r;
87f0e418 741
57020a3a 742 /* Redirect all references */
ac155bb8
MS
743 while (other->refs)
744 unit_ref_set(other->refs, u);
57020a3a 745
87f0e418
LP
746 /* Merge dependencies */
747 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
d1fab3fe 748 merge_dependencies(u, other, other_id, d);
87f0e418 749
ac155bb8
MS
750 other->load_state = UNIT_MERGED;
751 other->merged_into = u;
23a177ef 752
3616a49c
LP
753 /* If there is still some data attached to the other node, we
754 * don't need it anymore, and can free it. */
ac155bb8 755 if (other->load_state != UNIT_STUB)
3616a49c
LP
756 if (UNIT_VTABLE(other)->done)
757 UNIT_VTABLE(other)->done(other);
758
759 unit_add_to_dbus_queue(u);
23a177ef
LP
760 unit_add_to_cleanup_queue(other);
761
762 return 0;
763}
764
765int unit_merge_by_name(Unit *u, const char *name) {
766 Unit *other;
9e2f7c11 767 int r;
68eda4bd 768 _cleanup_free_ char *s = NULL;
23a177ef
LP
769
770 assert(u);
771 assert(name);
772
7410616c 773 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
ac155bb8 774 if (!u->instance)
9e2f7c11
LP
775 return -EINVAL;
776
7410616c
LP
777 r = unit_name_replace_instance(name, u->instance, &s);
778 if (r < 0)
779 return r;
9e2f7c11
LP
780
781 name = s;
782 }
783
c2756a68 784 other = manager_get_unit(u->manager, name);
7410616c
LP
785 if (other)
786 return unit_merge(u, other);
23a177ef 787
7410616c 788 return unit_add_name(u, name);
23a177ef
LP
789}
790
791Unit* unit_follow_merge(Unit *u) {
792 assert(u);
793
ac155bb8
MS
794 while (u->load_state == UNIT_MERGED)
795 assert_se(u = u->merged_into);
23a177ef
LP
796
797 return u;
798}
799
800int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
801 int r;
802
803 assert(u);
804 assert(c);
805
36be24c8
ZJS
806 if (c->working_directory) {
807 r = unit_require_mounts_for(u, c->working_directory);
808 if (r < 0)
809 return r;
810 }
811
812 if (c->root_directory) {
813 r = unit_require_mounts_for(u, c->root_directory);
814 if (r < 0)
815 return r;
816 }
817
b2c23da8 818 if (u->manager->running_as != MANAGER_SYSTEM)
b46a529c
LP
819 return 0;
820
821 if (c->private_tmp) {
822 r = unit_require_mounts_for(u, "/tmp");
823 if (r < 0)
824 return r;
825
826 r = unit_require_mounts_for(u, "/var/tmp");
827 if (r < 0)
828 return r;
829 }
830
ecc6e2b8
LP
831 if (c->std_output != EXEC_OUTPUT_KMSG &&
832 c->std_output != EXEC_OUTPUT_SYSLOG &&
706343f4 833 c->std_output != EXEC_OUTPUT_JOURNAL &&
28dbc1e8
LP
834 c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
835 c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
706343f4 836 c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
ecc6e2b8 837 c->std_error != EXEC_OUTPUT_KMSG &&
085c98af 838 c->std_error != EXEC_OUTPUT_SYSLOG &&
706343f4 839 c->std_error != EXEC_OUTPUT_JOURNAL &&
085c98af 840 c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
706343f4 841 c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
28dbc1e8 842 c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
23a177ef
LP
843 return 0;
844
845 /* If syslog or kernel logging is requested, make sure our own
846 * logging daemon is run first. */
847
b46a529c
LP
848 r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
849 if (r < 0)
850 return r;
23a177ef 851
87f0e418
LP
852 return 0;
853}
854
87f0e418
LP
855const char *unit_description(Unit *u) {
856 assert(u);
857
ac155bb8
MS
858 if (u->description)
859 return u->description;
87f0e418 860
ac155bb8 861 return strna(u->id);
87f0e418
LP
862}
863
864void unit_dump(Unit *u, FILE *f, const char *prefix) {
49dbfa7b 865 char *t, **j;
87f0e418
LP
866 UnitDependency d;
867 Iterator i;
47be870b 868 const char *prefix2;
173e3821
LP
869 char
870 timestamp1[FORMAT_TIMESTAMP_MAX],
871 timestamp2[FORMAT_TIMESTAMP_MAX],
872 timestamp3[FORMAT_TIMESTAMP_MAX],
faf919f1
LP
873 timestamp4[FORMAT_TIMESTAMP_MAX],
874 timespan[FORMAT_TIMESPAN_MAX];
a7f241db 875 Unit *following;
eeaedb7c
LP
876 _cleanup_set_free_ Set *following_set = NULL;
877 int r;
87f0e418
LP
878
879 assert(u);
ac155bb8 880 assert(u->type >= 0);
87f0e418 881
4c940960 882 prefix = strempty(prefix);
63c372cb 883 prefix2 = strjoina(prefix, "\t");
87f0e418
LP
884
885 fprintf(f,
40d50879 886 "%s-> Unit %s:\n"
87f0e418 887 "%s\tDescription: %s\n"
9e2f7c11 888 "%s\tInstance: %s\n"
87f0e418 889 "%s\tUnit Load State: %s\n"
2fad8195 890 "%s\tUnit Active State: %s\n"
173e3821 891 "%s\tInactive Exit Timestamp: %s\n"
2fad8195 892 "%s\tActive Enter Timestamp: %s\n"
701cc384 893 "%s\tActive Exit Timestamp: %s\n"
173e3821 894 "%s\tInactive Enter Timestamp: %s\n"
45fb0699 895 "%s\tGC Check Good: %s\n"
9444b1f2 896 "%s\tNeed Daemon Reload: %s\n"
c2756a68 897 "%s\tTransient: %s\n"
4ad49000
LP
898 "%s\tSlice: %s\n"
899 "%s\tCGroup: %s\n"
900 "%s\tCGroup realized: %s\n"
6414b7c9
DS
901 "%s\tCGroup mask: 0x%x\n"
902 "%s\tCGroup members mask: 0x%x\n",
ac155bb8 903 prefix, u->id,
87f0e418 904 prefix, unit_description(u),
ac155bb8
MS
905 prefix, strna(u->instance),
906 prefix, unit_load_state_to_string(u->load_state),
2fad8195 907 prefix, unit_active_state_to_string(unit_active_state(u)),
ac155bb8
MS
908 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
909 prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
910 prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
911 prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
45fb0699 912 prefix, yes_no(unit_check_gc(u)),
9444b1f2 913 prefix, yes_no(unit_need_daemon_reload(u)),
c2756a68 914 prefix, yes_no(u->transient),
4ad49000
LP
915 prefix, strna(unit_slice_name(u)),
916 prefix, strna(u->cgroup_path),
917 prefix, yes_no(u->cgroup_realized),
bc432dc7 918 prefix, u->cgroup_realized_mask,
6414b7c9 919 prefix, u->cgroup_members_mask);
0301abf4 920
ac155bb8 921 SET_FOREACH(t, u->names, i)
87f0e418
LP
922 fprintf(f, "%s\tName: %s\n", prefix, t);
923
49dbfa7b
LP
924 STRV_FOREACH(j, u->documentation)
925 fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
926
eeaedb7c
LP
927 following = unit_following(u);
928 if (following)
ac155bb8 929 fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
8fe914ec 930
eeaedb7c
LP
931 r = unit_following_set(u, &following_set);
932 if (r >= 0) {
933 Unit *other;
934
935 SET_FOREACH(other, following_set, i)
936 fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
937 }
938
ac155bb8
MS
939 if (u->fragment_path)
940 fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
23a177ef 941
1b64d026
LP
942 if (u->source_path)
943 fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
944
ae7a7182 945 STRV_FOREACH(j, u->dropin_paths)
2875e22b 946 fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
ae7a7182 947
ac155bb8 948 if (u->job_timeout > 0)
2fa4092c 949 fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
faf919f1 950
f189ab18
LP
951 if (u->job_timeout_action != FAILURE_ACTION_NONE)
952 fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
953
954 if (u->job_timeout_reboot_arg)
955 fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
956
59fccdc5
LP
957 condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
958 condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
52661efd 959
ac155bb8 960 if (dual_timestamp_is_set(&u->condition_timestamp))
2791a8f8
LP
961 fprintf(f,
962 "%s\tCondition Timestamp: %s\n"
963 "%s\tCondition Result: %s\n",
ac155bb8
MS
964 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
965 prefix, yes_no(u->condition_result));
2791a8f8 966
59fccdc5
LP
967 if (dual_timestamp_is_set(&u->assert_timestamp))
968 fprintf(f,
969 "%s\tAssert Timestamp: %s\n"
970 "%s\tAssert Result: %s\n",
971 prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
972 prefix, yes_no(u->assert_result));
973
87f0e418
LP
974 for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
975 Unit *other;
976
ac155bb8
MS
977 SET_FOREACH(other, u->dependencies[d], i)
978 fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
87f0e418
LP
979 }
980
7c8fa05c 981 if (!strv_isempty(u->requires_mounts_for)) {
7c8fa05c
LP
982 fprintf(f,
983 "%s\tRequiresMountsFor:", prefix);
984
985 STRV_FOREACH(j, u->requires_mounts_for)
986 fprintf(f, " %s", *j);
987
988 fputs("\n", f);
989 }
990
ac155bb8 991 if (u->load_state == UNIT_LOADED) {
ab1f0633 992
b0650475 993 fprintf(f,
a40eb732 994 "%s\tStopWhenUnneeded: %s\n"
b5e9dba8
LP
995 "%s\tRefuseManualStart: %s\n"
996 "%s\tRefuseManualStop: %s\n"
222ae6a8 997 "%s\tDefaultDependencies: %s\n"
d420282b 998 "%s\tOnFailureJobMode: %s\n"
7a6000a6
LP
999 "%s\tIgnoreOnIsolate: %s\n"
1000 "%s\tIgnoreOnSnapshot: %s\n",
ac155bb8
MS
1001 prefix, yes_no(u->stop_when_unneeded),
1002 prefix, yes_no(u->refuse_manual_start),
1003 prefix, yes_no(u->refuse_manual_stop),
1004 prefix, yes_no(u->default_dependencies),
d420282b 1005 prefix, job_mode_to_string(u->on_failure_job_mode),
ac155bb8
MS
1006 prefix, yes_no(u->ignore_on_isolate),
1007 prefix, yes_no(u->ignore_on_snapshot));
1008
23a177ef
LP
1009 if (UNIT_VTABLE(u)->dump)
1010 UNIT_VTABLE(u)->dump(u, f, prefix2);
b0650475 1011
ac155bb8 1012 } else if (u->load_state == UNIT_MERGED)
b0650475
LP
1013 fprintf(f,
1014 "%s\tMerged into: %s\n",
ac155bb8
MS
1015 prefix, u->merged_into->id);
1016 else if (u->load_state == UNIT_ERROR)
1017 fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
8821a00f 1018
87f0e418 1019
ac155bb8
MS
1020 if (u->job)
1021 job_dump(u->job, f, prefix2);
87f0e418 1022
e0209d83
MS
1023 if (u->nop_job)
1024 job_dump(u->nop_job, f, prefix2);
1025
87f0e418
LP
1026}
1027
1028/* Common implementation for multiple backends */
e537352b 1029int unit_load_fragment_and_dropin(Unit *u) {
23a177ef
LP
1030 int r;
1031
1032 assert(u);
23a177ef 1033
e48614c4 1034 /* Load a .{service,socket,...} file */
4ad49000
LP
1035 r = unit_load_fragment(u);
1036 if (r < 0)
23a177ef
LP
1037 return r;
1038
ac155bb8 1039 if (u->load_state == UNIT_STUB)
23a177ef
LP
1040 return -ENOENT;
1041
1042 /* Load drop-in directory data */
4ad49000
LP
1043 r = unit_load_dropin(unit_follow_merge(u));
1044 if (r < 0)
23a177ef
LP
1045 return r;
1046
1047 return 0;
1048}
1049
1050/* Common implementation for multiple backends */
e537352b 1051int unit_load_fragment_and_dropin_optional(Unit *u) {
23a177ef 1052 int r;
87f0e418
LP
1053
1054 assert(u);
1055
23a177ef
LP
1056 /* Same as unit_load_fragment_and_dropin(), but whether
1057 * something can be loaded or not doesn't matter. */
1058
1059 /* Load a .service file */
4ad49000
LP
1060 r = unit_load_fragment(u);
1061 if (r < 0)
87f0e418
LP
1062 return r;
1063
ac155bb8
MS
1064 if (u->load_state == UNIT_STUB)
1065 u->load_state = UNIT_LOADED;
d46de8a1 1066
87f0e418 1067 /* Load drop-in directory data */
4ad49000
LP
1068 r = unit_load_dropin(unit_follow_merge(u));
1069 if (r < 0)
87f0e418
LP
1070 return r;
1071
23a177ef 1072 return 0;
87f0e418
LP
1073}
1074
bba34eed 1075int unit_add_default_target_dependency(Unit *u, Unit *target) {
98bc2000
LP
1076 assert(u);
1077 assert(target);
1078
ac155bb8 1079 if (target->type != UNIT_TARGET)
98bc2000
LP
1080 return 0;
1081
35b8ca3a 1082 /* Only add the dependency if both units are loaded, so that
bba34eed 1083 * that loop check below is reliable */
ac155bb8
MS
1084 if (u->load_state != UNIT_LOADED ||
1085 target->load_state != UNIT_LOADED)
bba34eed
LP
1086 return 0;
1087
21256a2b
LP
1088 /* If either side wants no automatic dependencies, then let's
1089 * skip this */
ac155bb8
MS
1090 if (!u->default_dependencies ||
1091 !target->default_dependencies)
21256a2b
LP
1092 return 0;
1093
98bc2000 1094 /* Don't create loops */
ac155bb8 1095 if (set_get(target->dependencies[UNIT_BEFORE], u))
98bc2000
LP
1096 return 0;
1097
1098 return unit_add_dependency(target, UNIT_AFTER, u, true);
1099}
1100
e954c9cf 1101static int unit_add_target_dependencies(Unit *u) {
a016b922 1102
21256a2b
LP
1103 static const UnitDependency deps[] = {
1104 UNIT_REQUIRED_BY,
1105 UNIT_REQUIRED_BY_OVERRIDABLE,
be7d9ff7
LP
1106 UNIT_REQUISITE_OF,
1107 UNIT_REQUISITE_OF_OVERRIDABLE,
21256a2b
LP
1108 UNIT_WANTED_BY,
1109 UNIT_BOUND_BY
1110 };
1111
bba34eed 1112 Unit *target;
98bc2000 1113 Iterator i;
21256a2b 1114 unsigned k;
db57f3c6 1115 int r = 0;
98bc2000
LP
1116
1117 assert(u);
1118
21256a2b 1119 for (k = 0; k < ELEMENTSOF(deps); k++)
a016b922
LP
1120 SET_FOREACH(target, u->dependencies[deps[k]], i) {
1121 r = unit_add_default_target_dependency(u, target);
1122 if (r < 0)
21256a2b 1123 return r;
a016b922
LP
1124 }
1125
e954c9cf
LP
1126 return r;
1127}
4ad49000 1128
e954c9cf
LP
1129static int unit_add_slice_dependencies(Unit *u) {
1130 assert(u);
b81884e7 1131
35b7ff80 1132 if (!UNIT_HAS_CGROUP_CONTEXT(u))
e954c9cf
LP
1133 return 0;
1134
1135 if (UNIT_ISSET(u->slice))
8c8da0e0 1136 return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
e954c9cf 1137
8c8da0e0 1138 if (unit_has_name(u, SPECIAL_ROOT_SLICE))
d1fab3fe
ZJS
1139 return 0;
1140
8c8da0e0 1141 return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
98bc2000
LP
1142}
1143
e954c9cf 1144static int unit_add_mount_dependencies(Unit *u) {
9588bc32
LP
1145 char **i;
1146 int r;
1147
1148 assert(u);
1149
1150 STRV_FOREACH(i, u->requires_mounts_for) {
1151 char prefix[strlen(*i) + 1];
1152
1153 PATH_FOREACH_PREFIX_MORE(prefix, *i) {
c7c89abb 1154 _cleanup_free_ char *p = NULL;
9588bc32
LP
1155 Unit *m;
1156
c7c89abb 1157 r = unit_name_from_path(prefix, ".mount", &p);
9588bc32
LP
1158 if (r < 0)
1159 return r;
c7c89abb
FB
1160
1161 m = manager_get_unit(u->manager, p);
1162 if (!m) {
1163 /* Make sure to load the mount unit if
1164 * it exists. If so the dependencies
1165 * on this unit will be added later
1166 * during the loading of the mount
1167 * unit. */
1168 (void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
9588bc32 1169 continue;
c7c89abb 1170 }
9588bc32
LP
1171 if (m == u)
1172 continue;
1173
1174 if (m->load_state != UNIT_LOADED)
1175 continue;
1176
1177 r = unit_add_dependency(u, UNIT_AFTER, m, true);
1178 if (r < 0)
1179 return r;
1180
1181 if (m->fragment_path) {
1182 r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
1183 if (r < 0)
1184 return r;
1185 }
1186 }
1187 }
1188
1189 return 0;
1190}
1191
95ae05c0
WC
1192static int unit_add_startup_units(Unit *u) {
1193 CGroupContext *c;
5269eb6b 1194 int r;
95ae05c0
WC
1195
1196 c = unit_get_cgroup_context(u);
db785129
LP
1197 if (!c)
1198 return 0;
1199
d53d9474
LP
1200 if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
1201 c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
db785129
LP
1202 return 0;
1203
5269eb6b
LP
1204 r = set_ensure_allocated(&u->manager->startup_units, NULL);
1205 if (r < 0)
1206 return r;
1207
756c09e6 1208 return set_put(u->manager->startup_units, u);
95ae05c0
WC
1209}
1210
87f0e418
LP
1211int unit_load(Unit *u) {
1212 int r;
1213
1214 assert(u);
1215
ac155bb8 1216 if (u->in_load_queue) {
71fda00f 1217 LIST_REMOVE(load_queue, u->manager->load_queue, u);
ac155bb8 1218 u->in_load_queue = false;
87f0e418
LP
1219 }
1220
ac155bb8 1221 if (u->type == _UNIT_TYPE_INVALID)
e537352b
LP
1222 return -EINVAL;
1223
ac155bb8 1224 if (u->load_state != UNIT_STUB)
87f0e418
LP
1225 return 0;
1226
c2756a68
LP
1227 if (UNIT_VTABLE(u)->load) {
1228 r = UNIT_VTABLE(u)->load(u);
1229 if (r < 0)
87f0e418 1230 goto fail;
c2756a68 1231 }
23a177ef 1232
ac155bb8 1233 if (u->load_state == UNIT_STUB) {
23a177ef
LP
1234 r = -ENOENT;
1235 goto fail;
1236 }
1237
7c8fa05c 1238 if (u->load_state == UNIT_LOADED) {
c2756a68 1239
e954c9cf
LP
1240 r = unit_add_target_dependencies(u);
1241 if (r < 0)
1242 goto fail;
1243
1244 r = unit_add_slice_dependencies(u);
1245 if (r < 0)
1246 goto fail;
c2756a68 1247
e954c9cf 1248 r = unit_add_mount_dependencies(u);
7c8fa05c 1249 if (r < 0)
c2756a68 1250 goto fail;
7c8fa05c 1251
95ae05c0
WC
1252 r = unit_add_startup_units(u);
1253 if (r < 0)
1254 goto fail;
1255
bc432dc7 1256 if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
f2341e0a 1257 log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
c2756a68
LP
1258 r = -EINVAL;
1259 goto fail;
1260 }
bc432dc7
LP
1261
1262 unit_update_cgroup_members_masks(u);
32ee7d33
DM
1263
1264 /* If we are reloading, we need to wait for the deserializer
1265 * to restore the net_cls ids that have been set previously */
1266 if (u->manager->n_reloading <= 0) {
1267 r = unit_add_to_netclass_cgroup(u);
1268 if (r < 0)
1269 return r;
1270 }
f68319bb
LP
1271 }
1272
ac155bb8 1273 assert((u->load_state != UNIT_MERGED) == !u->merged_into);
23a177ef
LP
1274
1275 unit_add_to_dbus_queue(unit_follow_merge(u));
701cc384 1276 unit_add_to_gc_queue(u);
87f0e418 1277
87f0e418
LP
1278 return 0;
1279
1280fail:
c2756a68 1281 u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
ac155bb8 1282 u->load_error = r;
c1e1601e 1283 unit_add_to_dbus_queue(u);
9a46fc3b 1284 unit_add_to_gc_queue(u);
23a177ef 1285
f2341e0a 1286 log_unit_debug_errno(u, r, "Failed to load configuration: %m");
23a177ef 1287
87f0e418
LP
1288 return r;
1289}
1290
49365733
LP
1291static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
1292 Condition *c;
1293 int triggered = -1;
1294
1295 assert(u);
1296 assert(to_string);
1297
1298 /* If the condition list is empty, then it is true */
1299 if (!first)
1300 return true;
1301
1302 /* Otherwise, if all of the non-trigger conditions apply and
1303 * if any of the trigger conditions apply (unless there are
1304 * none) we return true */
1305 LIST_FOREACH(conditions, c, first) {
1306 int r;
1307
1308 r = condition_test(c);
1309 if (r < 0)
f2341e0a
LP
1310 log_unit_warning(u,
1311 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
49365733
LP
1312 to_string(c->type),
1313 c->trigger ? "|" : "",
1314 c->negate ? "!" : "",
f2341e0a 1315 c->parameter);
49365733 1316 else
f2341e0a
LP
1317 log_unit_debug(u,
1318 "%s=%s%s%s %s.",
49365733
LP
1319 to_string(c->type),
1320 c->trigger ? "|" : "",
1321 c->negate ? "!" : "",
1322 c->parameter,
f2341e0a 1323 condition_result_to_string(c->result));
49365733
LP
1324
1325 if (!c->trigger && r <= 0)
1326 return false;
1327
1328 if (c->trigger && triggered <= 0)
1329 triggered = r > 0;
1330 }
1331
1332 return triggered != 0;
1333}
1334
9588bc32 1335static bool unit_condition_test(Unit *u) {
90bbc946
LP
1336 assert(u);
1337
ac155bb8 1338 dual_timestamp_get(&u->condition_timestamp);
49365733 1339 u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
90bbc946 1340
ac155bb8 1341 return u->condition_result;
90bbc946
LP
1342}
1343
59fccdc5
LP
1344static bool unit_assert_test(Unit *u) {
1345 assert(u);
1346
1347 dual_timestamp_get(&u->assert_timestamp);
49365733 1348 u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
59fccdc5
LP
1349
1350 return u->assert_result;
1351}
1352
44a6b1b6 1353_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
877d54e9 1354 const char *format;
a85ca902 1355 const UnitStatusMessageFormats *format_table;
877d54e9
LP
1356
1357 assert(u);
b5bf308b 1358 assert(t == JOB_START || t == JOB_STOP || t == JOB_RELOAD);
877d54e9 1359
b5bf308b 1360 if (t != JOB_RELOAD) {
a85ca902
MS
1361 format_table = &UNIT_VTABLE(u)->status_message_formats;
1362 if (format_table) {
1363 format = format_table->starting_stopping[t == JOB_STOP];
1364 if (format)
1365 return format;
1366 }
1367 }
877d54e9
LP
1368
1369 /* Return generic strings */
1370 if (t == JOB_START)
1371 return "Starting %s.";
1372 else if (t == JOB_STOP)
1373 return "Stopping %s.";
b5bf308b 1374 else
877d54e9 1375 return "Reloading %s.";
877d54e9
LP
1376}
1377
1378static void unit_status_print_starting_stopping(Unit *u, JobType t) {
1379 const char *format;
1380
1381 assert(u);
1382
877d54e9 1383 format = unit_get_status_message_format(u, t);
c6918296 1384
bcfce235 1385 DISABLE_WARNING_FORMAT_NONLITERAL;
49b1d377 1386 unit_status_printf(u, "", format);
bcfce235 1387 REENABLE_WARNING;
c6918296
MS
1388}
1389
877d54e9
LP
1390static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
1391 const char *format;
1392 char buf[LINE_MAX];
1393 sd_id128_t mid;
1394
1395 assert(u);
1396
1397 if (t != JOB_START && t != JOB_STOP && t != JOB_RELOAD)
1398 return;
1399
81270860
LP
1400 if (log_on_console())
1401 return;
1402
877d54e9
LP
1403 /* We log status messages for all units and all operations. */
1404
a85ca902 1405 format = unit_get_status_message_format(u, t);
877d54e9 1406
bcfce235 1407 DISABLE_WARNING_FORMAT_NONLITERAL;
877d54e9 1408 snprintf(buf, sizeof(buf), format, unit_description(u));
bcfce235 1409 REENABLE_WARNING;
877d54e9
LP
1410
1411 mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
1412 t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
1413 SD_MESSAGE_UNIT_RELOADING;
1414
f2341e0a
LP
1415 /* Note that we deliberately use LOG_MESSAGE() instead of
1416 * LOG_UNIT_MESSAGE() here, since this is supposed to mimic
1417 * closely what is written to screen using the status output,
1418 * which is supposed the highest level, friendliest output
1419 * possible, which means we should avoid the low-level unit
1420 * name. */
1421 log_struct(LOG_INFO,
1422 LOG_MESSAGE_ID(mid),
1423 LOG_UNIT_ID(u),
1424 LOG_MESSAGE("%s", buf),
1425 NULL);
877d54e9 1426}
877d54e9 1427
d1a34ae9
MS
1428void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
1429
1430 unit_status_log_starting_stopping_reloading(u, t);
1431
1432 /* Reload status messages have traditionally not been printed to console. */
1433 if (t != JOB_RELOAD)
1434 unit_status_print_starting_stopping(u, t);
1435}
1436
87f0e418 1437/* Errors:
d5159713
LP
1438 * -EBADR: This unit type does not support starting.
1439 * -EALREADY: Unit is already started.
1440 * -EAGAIN: An operation is already in progress. Retry later.
1441 * -ECANCELED: Too many requests for now.
59fccdc5 1442 * -EPROTO: Assert failed
87f0e418
LP
1443 */
1444int unit_start(Unit *u) {
1445 UnitActiveState state;
92ab323c 1446 Unit *following;
87f0e418
LP
1447
1448 assert(u);
1449
8ff4d2ab 1450 /* Units that aren't loaded cannot be started */
ac155bb8 1451 if (u->load_state != UNIT_LOADED)
6124958c
LP
1452 return -EINVAL;
1453
a82e5507
LP
1454 /* If this is already started, then this will succeed. Note
1455 * that this will even succeed if this unit is not startable
1456 * by the user. This is relied on to detect when we need to
1457 * wait for units and when waiting is finished. */
87f0e418
LP
1458 state = unit_active_state(u);
1459 if (UNIT_IS_ACTIVE_OR_RELOADING(state))
1460 return -EALREADY;
1461
a82e5507
LP
1462 /* If the conditions failed, don't do anything at all. If we
1463 * already are activating this call might still be useful to
1464 * speed up activation in case there is some hold-off time,
1465 * but we don't want to recheck the condition in that case. */
1466 if (state != UNIT_ACTIVATING &&
1467 !unit_condition_test(u)) {
f2341e0a 1468 log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
52661efd
LP
1469 return -EALREADY;
1470 }
1471
59fccdc5
LP
1472 /* If the asserts failed, fail the entire job */
1473 if (state != UNIT_ACTIVATING &&
1474 !unit_assert_test(u)) {
f2341e0a 1475 log_unit_notice(u, "Starting requested but asserts failed.");
59fccdc5
LP
1476 return -EPROTO;
1477 }
1478
d11a7645
LP
1479 /* Units of types that aren't supported cannot be
1480 * started. Note that we do this test only after the condition
1481 * checks, so that we rather return condition check errors
1482 * (which are usually not considered a true failure) than "not
1483 * supported" errors (which are considered a failure).
1484 */
1485 if (!unit_supported(u))
1486 return -EOPNOTSUPP;
1487
92ab323c 1488 /* Forward to the main object, if we aren't it. */
52990c2e
ZJS
1489 following = unit_following(u);
1490 if (following) {
f2341e0a 1491 log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
92ab323c
LP
1492 return unit_start(following);
1493 }
1494
1495 /* If it is stopped, but we cannot start it, then fail */
1496 if (!UNIT_VTABLE(u)->start)
1497 return -EBADR;
1498
87f0e418
LP
1499 /* We don't suppress calls to ->start() here when we are
1500 * already starting, to allow this request to be used as a
1501 * "hurry up" call, for example when the unit is in some "auto
1502 * restart" state where it waits for a holdoff timer to elapse
1503 * before it will start again. */
1504
c1e1601e 1505 unit_add_to_dbus_queue(u);
9e58ff9c 1506
d1a34ae9 1507 return UNIT_VTABLE(u)->start(u);
87f0e418
LP
1508}
1509
1510bool unit_can_start(Unit *u) {
1511 assert(u);
1512
8ff4d2ab
LP
1513 if (u->load_state != UNIT_LOADED)
1514 return false;
1515
1516 if (!unit_supported(u))
1517 return false;
1518
87f0e418
LP
1519 return !!UNIT_VTABLE(u)->start;
1520}
1521
2528a7a6
LP
1522bool unit_can_isolate(Unit *u) {
1523 assert(u);
1524
1525 return unit_can_start(u) &&
ac155bb8 1526 u->allow_isolate;
2528a7a6
LP
1527}
1528
87f0e418
LP
1529/* Errors:
1530 * -EBADR: This unit type does not support stopping.
1531 * -EALREADY: Unit is already stopped.
1532 * -EAGAIN: An operation is already in progress. Retry later.
1533 */
1534int unit_stop(Unit *u) {
1535 UnitActiveState state;
92ab323c 1536 Unit *following;
87f0e418
LP
1537
1538 assert(u);
1539
87f0e418 1540 state = unit_active_state(u);
fdf20a31 1541 if (UNIT_IS_INACTIVE_OR_FAILED(state))
87f0e418
LP
1542 return -EALREADY;
1543
0faacd47
LP
1544 following = unit_following(u);
1545 if (following) {
f2341e0a 1546 log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
92ab323c
LP
1547 return unit_stop(following);
1548 }
1549
7898b0cf
LP
1550 if (!UNIT_VTABLE(u)->stop)
1551 return -EBADR;
1552
c1e1601e 1553 unit_add_to_dbus_queue(u);
9e58ff9c 1554
d1a34ae9 1555 return UNIT_VTABLE(u)->stop(u);
87f0e418
LP
1556}
1557
1558/* Errors:
1559 * -EBADR: This unit type does not support reloading.
1560 * -ENOEXEC: Unit is not started.
1561 * -EAGAIN: An operation is already in progress. Retry later.
1562 */
1563int unit_reload(Unit *u) {
1564 UnitActiveState state;
92ab323c 1565 Unit *following;
87f0e418
LP
1566
1567 assert(u);
1568
ac155bb8 1569 if (u->load_state != UNIT_LOADED)
6124958c
LP
1570 return -EINVAL;
1571
87f0e418
LP
1572 if (!unit_can_reload(u))
1573 return -EBADR;
1574
1575 state = unit_active_state(u);
e364ad06 1576 if (state == UNIT_RELOADING)
87f0e418
LP
1577 return -EALREADY;
1578
6a371e23 1579 if (state != UNIT_ACTIVE) {
f2341e0a 1580 log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
87f0e418 1581 return -ENOEXEC;
6a371e23 1582 }
87f0e418 1583
e48614c4
ZJS
1584 following = unit_following(u);
1585 if (following) {
f2341e0a 1586 log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
92ab323c
LP
1587 return unit_reload(following);
1588 }
1589
c1e1601e 1590 unit_add_to_dbus_queue(u);
82a2b6bb 1591
d1a34ae9 1592 return UNIT_VTABLE(u)->reload(u);
87f0e418
LP
1593}
1594
1595bool unit_can_reload(Unit *u) {
1596 assert(u);
1597
1598 if (!UNIT_VTABLE(u)->reload)
1599 return false;
1600
1601 if (!UNIT_VTABLE(u)->can_reload)
1602 return true;
1603
1604 return UNIT_VTABLE(u)->can_reload(u);
1605}
1606
b4a16b7b 1607static void unit_check_unneeded(Unit *u) {
be7d9ff7
LP
1608
1609 static const UnitDependency needed_dependencies[] = {
1610 UNIT_REQUIRED_BY,
1611 UNIT_REQUIRED_BY_OVERRIDABLE,
084918ba 1612 UNIT_REQUISITE_OF,
be7d9ff7
LP
1613 UNIT_REQUISITE_OF_OVERRIDABLE,
1614 UNIT_WANTED_BY,
1615 UNIT_BOUND_BY,
1616 };
1617
f3bff0eb 1618 Unit *other;
be7d9ff7
LP
1619 Iterator i;
1620 unsigned j;
1621 int r;
f3bff0eb
LP
1622
1623 assert(u);
1624
1625 /* If this service shall be shut down when unneeded then do
1626 * so. */
1627
ac155bb8 1628 if (!u->stop_when_unneeded)
f3bff0eb
LP
1629 return;
1630
1631 if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
1632 return;
1633
be7d9ff7 1634 for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
f3b85044 1635 SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
be7d9ff7
LP
1636 if (unit_active_or_pending(other))
1637 return;
b81884e7 1638
bea355da
LP
1639 /* If stopping a unit fails continously we might enter a stop
1640 * loop here, hence stop acting on the service being
1641 * unnecessary after a while. */
67bfdc97 1642 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
bea355da
LP
1643 log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
1644 return;
1645 }
1646
f2341e0a 1647 log_unit_info(u, "Unit not needed anymore. Stopping.");
f3bff0eb
LP
1648
1649 /* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
be7d9ff7
LP
1650 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1651 if (r < 0)
1652 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %m");
f3bff0eb
LP
1653}
1654
ff502445
LP
1655static void unit_check_binds_to(Unit *u) {
1656 bool stop = false;
1657 Unit *other;
1658 Iterator i;
67bfdc97 1659 int r;
ff502445
LP
1660
1661 assert(u);
1662
1663 if (u->job)
1664 return;
1665
1666 if (unit_active_state(u) != UNIT_ACTIVE)
1667 return;
1668
1669 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
1670 if (other->job)
1671 continue;
1672
1673 if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
1674 continue;
1675
1676 stop = true;
98f738b6 1677 break;
ff502445
LP
1678 }
1679
1680 if (!stop)
1681 return;
1682
67bfdc97
LP
1683 /* If stopping a unit fails continously we might enter a stop
1684 * loop here, hence stop acting on the service being
1685 * unnecessary after a while. */
1686 if (!ratelimit_test(&u->auto_stop_ratelimit)) {
1687 log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
1688 return;
1689 }
1690
98f738b6 1691 assert(other);
f2341e0a 1692 log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
ff502445
LP
1693
1694 /* A unit we need to run is gone. Sniff. Let's stop this. */
67bfdc97
LP
1695 r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, true, NULL, NULL);
1696 if (r < 0)
1697 log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %m");
ff502445
LP
1698}
1699
87f0e418
LP
1700static void retroactively_start_dependencies(Unit *u) {
1701 Iterator i;
1702 Unit *other;
1703
1704 assert(u);
1705 assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
1706
ac155bb8
MS
1707 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
1708 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1709 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
ac155bb8 1710 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
b81884e7 1711
7f2cddae 1712 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
ac155bb8 1713 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1714 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
ac155bb8 1715 manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, true, NULL, NULL);
87f0e418 1716
ac155bb8
MS
1717 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
1718 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1719 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
ac155bb8 1720 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
87f0e418 1721
ac155bb8
MS
1722 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
1723 if (!set_get(u->dependencies[UNIT_AFTER], other) &&
b81884e7 1724 !UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
ac155bb8 1725 manager_add_job(u->manager, JOB_START, other, JOB_FAIL, false, NULL, NULL);
87f0e418 1726
ac155bb8 1727 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
b81884e7 1728 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
ac155bb8 1729 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
69dd2852 1730
ac155bb8 1731 SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
b81884e7 1732 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
ac155bb8 1733 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
87f0e418
LP
1734}
1735
1736static void retroactively_stop_dependencies(Unit *u) {
1737 Iterator i;
1738 Unit *other;
1739
1740 assert(u);
1741 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
1742
b81884e7 1743 /* Pull down units which are bound to us recursively if enabled */
ac155bb8 1744 SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
b81884e7 1745 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
ac155bb8 1746 manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, true, NULL, NULL);
cd0504d0
MS
1747}
1748
1749static void check_unneeded_dependencies(Unit *u) {
1750 Iterator i;
1751 Unit *other;
1752
1753 assert(u);
1754 assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
f3bff0eb
LP
1755
1756 /* Garbage collect services that might not be needed anymore, if enabled */
ac155bb8 1757 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
87f0e418 1758 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1759 unit_check_unneeded(other);
ac155bb8 1760 SET_FOREACH(other, u->dependencies[UNIT_REQUIRES_OVERRIDABLE], i)
f3bff0eb 1761 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1762 unit_check_unneeded(other);
ac155bb8 1763 SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
f3bff0eb 1764 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1765 unit_check_unneeded(other);
ac155bb8 1766 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
f3bff0eb 1767 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1768 unit_check_unneeded(other);
ac155bb8 1769 SET_FOREACH(other, u->dependencies[UNIT_REQUISITE_OVERRIDABLE], i)
f3bff0eb 1770 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
b4a16b7b 1771 unit_check_unneeded(other);
7f2cddae 1772 SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
b81884e7
LP
1773 if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
1774 unit_check_unneeded(other);
87f0e418
LP
1775}
1776
3ecaa09b 1777void unit_start_on_failure(Unit *u) {
c0daa706
LP
1778 Unit *other;
1779 Iterator i;
1780
1781 assert(u);
1782
ac155bb8 1783 if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
222ae6a8
LP
1784 return;
1785
f2341e0a 1786 log_unit_info(u, "Triggering OnFailure= dependencies.");
222ae6a8 1787
ac155bb8 1788 SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
222ae6a8
LP
1789 int r;
1790
d420282b 1791 r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, true, NULL, NULL);
c1b6628d 1792 if (r < 0)
f2341e0a 1793 log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
222ae6a8 1794 }
c0daa706
LP
1795}
1796
3ecaa09b
LP
1797void unit_trigger_notify(Unit *u) {
1798 Unit *other;
1799 Iterator i;
1800
1801 assert(u);
1802
1803 SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
1804 if (UNIT_VTABLE(other)->trigger_notify)
1805 UNIT_VTABLE(other)->trigger_notify(other, u);
1806}
1807
e2f3b44c 1808void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
546ac4f0 1809 Manager *m;
7e6e7b06 1810 bool unexpected;
a096ed36 1811
87f0e418
LP
1812 assert(u);
1813 assert(os < _UNIT_ACTIVE_STATE_MAX);
1814 assert(ns < _UNIT_ACTIVE_STATE_MAX);
87f0e418 1815
8e471ccd
LP
1816 /* Note that this is called for all low-level state changes,
1817 * even if they might map to the same high-level
865cc19a 1818 * UnitActiveState! That means that ns == os is an expected
c5315881 1819 * behavior here. For example: if a mount point is remounted
cd6d0a45 1820 * this function will be called too! */
87f0e418 1821
546ac4f0
MS
1822 m = u->manager;
1823
f755e3b7 1824 /* Update timestamps for state changes */
546ac4f0 1825 if (m->n_reloading <= 0) {
bdbf9951 1826 dual_timestamp ts;
173e3821 1827
bdbf9951 1828 dual_timestamp_get(&ts);
173e3821 1829
bdbf9951 1830 if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
ac155bb8 1831 u->inactive_exit_timestamp = ts;
bdbf9951 1832 else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
ac155bb8 1833 u->inactive_enter_timestamp = ts;
bdbf9951
LP
1834
1835 if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
ac155bb8 1836 u->active_enter_timestamp = ts;
bdbf9951 1837 else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
ac155bb8 1838 u->active_exit_timestamp = ts;
bdbf9951 1839 }
87f0e418 1840
865cc19a 1841 /* Keep track of failed units */
5269eb6b 1842 (void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
f755e3b7
LP
1843
1844 /* Make sure the cgroup is always removed when we become inactive */
fdf20a31 1845 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
efdb0237 1846 unit_prune_cgroup(u);
fb385181 1847
9cd86184 1848 /* Note that this doesn't apply to RemainAfterExit services exiting
6f285378 1849 * successfully, since there's no change of state in that case. Which is
9cd86184 1850 * why it is handled in service_set_state() */
7ed9f6cd 1851 if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
b33918c2
LP
1852 ExecContext *ec;
1853
1854 ec = unit_get_exec_context(u);
7ed9f6cd 1855 if (ec && exec_context_may_touch_console(ec)) {
31a7eb86
ZJS
1856 if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
1857 m->n_on_console --;
1858
1859 if (m->n_on_console == 0)
1860 /* unset no_console_output flag, since the console is free */
2f38577f 1861 m->no_console_output = false;
31a7eb86
ZJS
1862 } else
1863 m->n_on_console ++;
7ed9f6cd
MS
1864 }
1865 }
1866
ac155bb8 1867 if (u->job) {
7e6e7b06 1868 unexpected = false;
87f0e418 1869
ac155bb8 1870 if (u->job->state == JOB_WAITING)
87f0e418
LP
1871
1872 /* So we reached a different state for this
1873 * job. Let's see if we can run it now if it
1874 * failed previously due to EAGAIN. */
ac155bb8 1875 job_add_to_run_queue(u->job);
87f0e418 1876
b410e6b9 1877 /* Let's check whether this state change constitutes a
35b8ca3a 1878 * finished job, or maybe contradicts a running job and
b410e6b9 1879 * hence needs to invalidate jobs. */
87f0e418 1880
ac155bb8 1881 switch (u->job->type) {
87f0e418 1882
b410e6b9
LP
1883 case JOB_START:
1884 case JOB_VERIFY_ACTIVE:
87f0e418 1885
b410e6b9 1886 if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
5273510e 1887 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1888 else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
b410e6b9 1889 unexpected = true;
41b02ec7 1890
fdf20a31 1891 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1892 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
b410e6b9 1893 }
87f0e418 1894
b410e6b9 1895 break;
87f0e418 1896
b410e6b9
LP
1897 case JOB_RELOAD:
1898 case JOB_RELOAD_OR_START:
87f0e418 1899
ac155bb8 1900 if (u->job->state == JOB_RUNNING) {
a096ed36 1901 if (ns == UNIT_ACTIVE)
5273510e 1902 job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
032ff4af 1903 else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
a096ed36 1904 unexpected = true;
41b02ec7 1905
fdf20a31 1906 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1907 job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
a096ed36 1908 }
b410e6b9 1909 }
87f0e418 1910
b410e6b9 1911 break;
87f0e418 1912
b410e6b9
LP
1913 case JOB_STOP:
1914 case JOB_RESTART:
1915 case JOB_TRY_RESTART:
87f0e418 1916
fdf20a31 1917 if (UNIT_IS_INACTIVE_OR_FAILED(ns))
5273510e 1918 job_finish_and_invalidate(u->job, JOB_DONE, true);
ac155bb8 1919 else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
b410e6b9 1920 unexpected = true;
5273510e 1921 job_finish_and_invalidate(u->job, JOB_FAILED, true);
b410e6b9 1922 }
87f0e418 1923
b410e6b9 1924 break;
87f0e418 1925
b410e6b9
LP
1926 default:
1927 assert_not_reached("Job type unknown");
87f0e418 1928 }
87f0e418 1929
7e6e7b06
LP
1930 } else
1931 unexpected = true;
1932
546ac4f0 1933 if (m->n_reloading <= 0) {
f3bff0eb 1934
bdbf9951
LP
1935 /* If this state change happened without being
1936 * requested by a job, then let's retroactively start
1937 * or stop dependencies. We skip that step when
1938 * deserializing, since we don't want to create any
1939 * additional jobs just because something is already
1940 * activated. */
1941
1942 if (unexpected) {
1943 if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
1944 retroactively_start_dependencies(u);
1945 else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
1946 retroactively_stop_dependencies(u);
1947 }
5de9682c 1948
cd0504d0 1949 /* stop unneeded units regardless if going down was expected or not */
b33918c2 1950 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
cd0504d0
MS
1951 check_unneeded_dependencies(u);
1952
bdbf9951 1953 if (ns != os && ns == UNIT_FAILED) {
f2341e0a 1954 log_unit_notice(u, "Unit entered failed state.");
3ecaa09b 1955 unit_start_on_failure(u);
cd6d0a45 1956 }
3b2775c5 1957 }
e537352b 1958
3b2775c5
LP
1959 /* Some names are special */
1960 if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
1961
1962 if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
865cc19a 1963 /* The bus might have just become available,
3b2775c5
LP
1964 * hence try to connect to it, if we aren't
1965 * yet connected. */
546ac4f0 1966 bus_init(m, true);
3b2775c5 1967
ac155bb8 1968 if (u->type == UNIT_SERVICE &&
3b2775c5 1969 !UNIT_IS_ACTIVE_OR_RELOADING(os) &&
546ac4f0 1970 m->n_reloading <= 0) {
3b2775c5 1971 /* Write audit record if we have just finished starting up */
546ac4f0 1972 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
ac155bb8 1973 u->in_audit = true;
3b2775c5 1974 }
e983b760 1975
3b2775c5 1976 if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
546ac4f0 1977 manager_send_unit_plymouth(m, u);
bdbf9951 1978
3b2775c5 1979 } else {
bdbf9951 1980
3b2775c5
LP
1981 /* We don't care about D-Bus here, since we'll get an
1982 * asynchronous notification for it anyway. */
cd6d0a45 1983
ac155bb8 1984 if (u->type == UNIT_SERVICE &&
3b2775c5
LP
1985 UNIT_IS_INACTIVE_OR_FAILED(ns) &&
1986 !UNIT_IS_INACTIVE_OR_FAILED(os) &&
546ac4f0 1987 m->n_reloading <= 0) {
4927fcae 1988
3b2775c5
LP
1989 /* Hmm, if there was no start record written
1990 * write it now, so that we always have a nice
1991 * pair */
ac155bb8 1992 if (!u->in_audit) {
546ac4f0 1993 manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
cd6d0a45 1994
3b2775c5 1995 if (ns == UNIT_INACTIVE)
546ac4f0 1996 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
3b2775c5
LP
1997 } else
1998 /* Write audit record if we have just finished shutting down */
546ac4f0 1999 manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
bdbf9951 2000
ac155bb8 2001 u->in_audit = false;
cd6d0a45 2002 }
f278026d
LP
2003 }
2004
546ac4f0 2005 manager_recheck_journal(m);
3ecaa09b 2006 unit_trigger_notify(u);
3b2775c5 2007
ff502445
LP
2008 if (u->manager->n_reloading <= 0) {
2009 /* Maybe we finished startup and are now ready for
2010 * being stopped because unneeded? */
bf6dcfa6 2011 unit_check_unneeded(u);
c1e1601e 2012
ff502445
LP
2013 /* Maybe we finished startup, but something we needed
2014 * has vanished? Let's die then. (This happens when
2015 * something BindsTo= to a Type=oneshot unit, as these
2016 * units go directly from starting to inactive,
2017 * without ever entering started.) */
2018 unit_check_binds_to(u);
2019 }
2020
c1e1601e 2021 unit_add_to_dbus_queue(u);
701cc384 2022 unit_add_to_gc_queue(u);
87f0e418
LP
2023}
2024
87f0e418 2025int unit_watch_pid(Unit *u, pid_t pid) {
a911bb9a
LP
2026 int q, r;
2027
87f0e418
LP
2028 assert(u);
2029 assert(pid >= 1);
2030
5ba6985b
LP
2031 /* Watch a specific PID. We only support one or two units
2032 * watching each PID for now, not more. */
2033
d5099efc 2034 r = set_ensure_allocated(&u->pids, NULL);
5ba6985b
LP
2035 if (r < 0)
2036 return r;
2037
d5099efc 2038 r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
a911bb9a
LP
2039 if (r < 0)
2040 return r;
2041
fea72cc0 2042 r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
5ba6985b 2043 if (r == -EEXIST) {
d5099efc 2044 r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
5ba6985b
LP
2045 if (r < 0)
2046 return r;
05e343b7 2047
fea72cc0 2048 r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
5ba6985b 2049 }
a911bb9a 2050
fea72cc0 2051 q = set_put(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2052 if (q < 0)
2053 return q;
2054
2055 return r;
87f0e418
LP
2056}
2057
2058void unit_unwatch_pid(Unit *u, pid_t pid) {
2059 assert(u);
2060 assert(pid >= 1);
2061
fea72cc0
LP
2062 (void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
2063 (void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
2064 (void) set_remove(u->pids, PID_TO_PTR(pid));
a911bb9a
LP
2065}
2066
bd44e61b
LP
2067void unit_unwatch_all_pids(Unit *u) {
2068 assert(u);
2069
2070 while (!set_isempty(u->pids))
fea72cc0 2071 unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
bd44e61b 2072
efdb0237 2073 u->pids = set_free(u->pids);
a911bb9a
LP
2074}
2075
2076void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
2077 Iterator i;
2078 void *e;
2079
2080 assert(u);
2081
2082 /* Cleans dead PIDs from our list */
2083
2084 SET_FOREACH(e, u->pids, i) {
fea72cc0 2085 pid_t pid = PTR_TO_PID(e);
a911bb9a
LP
2086
2087 if (pid == except1 || pid == except2)
2088 continue;
2089
9f5650ae 2090 if (!pid_is_unwaited(pid))
bd44e61b 2091 unit_unwatch_pid(u, pid);
a911bb9a 2092 }
87f0e418
LP
2093}
2094
87f0e418
LP
2095bool unit_job_is_applicable(Unit *u, JobType j) {
2096 assert(u);
2097 assert(j >= 0 && j < _JOB_TYPE_MAX);
2098
2099 switch (j) {
2100
2101 case JOB_VERIFY_ACTIVE:
2102 case JOB_START:
57339f47 2103 case JOB_STOP:
e0209d83 2104 case JOB_NOP:
87f0e418
LP
2105 return true;
2106
87f0e418
LP
2107 case JOB_RESTART:
2108 case JOB_TRY_RESTART:
2109 return unit_can_start(u);
2110
2111 case JOB_RELOAD:
2112 return unit_can_reload(u);
2113
2114 case JOB_RELOAD_OR_START:
2115 return unit_can_reload(u) && unit_can_start(u);
2116
2117 default:
2118 assert_not_reached("Invalid job type");
2119 }
2120}
2121
f2341e0a
LP
2122static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
2123 assert(u);
d1fab3fe 2124
f2341e0a
LP
2125 /* Only warn about some unit types */
2126 if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
2127 return;
3f3cc397 2128
f2341e0a
LP
2129 if (streq_ptr(u->id, other))
2130 log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
2131 else
2132 log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
d1fab3fe
ZJS
2133}
2134
701cc384 2135int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
87f0e418
LP
2136
2137 static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
2138 [UNIT_REQUIRES] = UNIT_REQUIRED_BY,
9e2f7c11 2139 [UNIT_REQUIRES_OVERRIDABLE] = UNIT_REQUIRED_BY_OVERRIDABLE,
87f0e418 2140 [UNIT_WANTS] = UNIT_WANTED_BY,
be7d9ff7
LP
2141 [UNIT_REQUISITE] = UNIT_REQUISITE_OF,
2142 [UNIT_REQUISITE_OVERRIDABLE] = UNIT_REQUISITE_OF_OVERRIDABLE,
7f2cddae 2143 [UNIT_BINDS_TO] = UNIT_BOUND_BY,
60649f17 2144 [UNIT_PART_OF] = UNIT_CONSISTS_OF,
be7d9ff7
LP
2145 [UNIT_REQUIRED_BY] = UNIT_REQUIRES,
2146 [UNIT_REQUIRED_BY_OVERRIDABLE] = UNIT_REQUIRES_OVERRIDABLE,
2147 [UNIT_REQUISITE_OF] = UNIT_REQUISITE,
2148 [UNIT_REQUISITE_OF_OVERRIDABLE] = UNIT_REQUISITE_OVERRIDABLE,
2149 [UNIT_WANTED_BY] = UNIT_WANTS,
7f2cddae 2150 [UNIT_BOUND_BY] = UNIT_BINDS_TO,
60649f17 2151 [UNIT_CONSISTS_OF] = UNIT_PART_OF,
69dd2852
LP
2152 [UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
2153 [UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
87f0e418 2154 [UNIT_BEFORE] = UNIT_AFTER,
701cc384 2155 [UNIT_AFTER] = UNIT_BEFORE,
5de9682c 2156 [UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
701cc384 2157 [UNIT_REFERENCES] = UNIT_REFERENCED_BY,
57020a3a
LP
2158 [UNIT_REFERENCED_BY] = UNIT_REFERENCES,
2159 [UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
4dcc1cb4 2160 [UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
7f2cddae 2161 [UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
85e9a101 2162 [UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
613b411c 2163 [UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
87f0e418 2164 };
701cc384 2165 int r, q = 0, v = 0, w = 0;
d1fab3fe 2166 Unit *orig_u = u, *orig_other = other;
87f0e418
LP
2167
2168 assert(u);
2169 assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
87f0e418
LP
2170 assert(other);
2171
9f151f29
LP
2172 u = unit_follow_merge(u);
2173 other = unit_follow_merge(other);
2174
87f0e418
LP
2175 /* We won't allow dependencies on ourselves. We will not
2176 * consider them an error however. */
d1fab3fe 2177 if (u == other) {
f2341e0a 2178 maybe_warn_about_dependency(orig_u, orig_other->id, d);
87f0e418 2179 return 0;
d1fab3fe 2180 }
87f0e418 2181
d5099efc 2182 r = set_ensure_allocated(&u->dependencies[d], NULL);
613b411c 2183 if (r < 0)
87f0e418
LP
2184 return r;
2185
613b411c 2186 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
d5099efc 2187 r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
613b411c
LP
2188 if (r < 0)
2189 return r;
2190 }
2191
2192 if (add_reference) {
d5099efc 2193 r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
613b411c 2194 if (r < 0)
5de9682c
LP
2195 return r;
2196
d5099efc 2197 r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
613b411c 2198 if (r < 0)
701cc384 2199 return r;
613b411c 2200 }
87f0e418 2201
613b411c
LP
2202 q = set_put(u->dependencies[d], other);
2203 if (q < 0)
701cc384 2204 return q;
87f0e418 2205
613b411c
LP
2206 if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
2207 v = set_put(other->dependencies[inverse_table[d]], u);
2208 if (v < 0) {
5de9682c
LP
2209 r = v;
2210 goto fail;
2211 }
613b411c 2212 }
701cc384
LP
2213
2214 if (add_reference) {
613b411c
LP
2215 w = set_put(u->dependencies[UNIT_REFERENCES], other);
2216 if (w < 0) {
701cc384
LP
2217 r = w;
2218 goto fail;
2219 }
2220
613b411c
LP
2221 r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
2222 if (r < 0)
701cc384 2223 goto fail;
87f0e418
LP
2224 }
2225
c1e1601e 2226 unit_add_to_dbus_queue(u);
87f0e418 2227 return 0;
701cc384
LP
2228
2229fail:
2230 if (q > 0)
ac155bb8 2231 set_remove(u->dependencies[d], other);
701cc384
LP
2232
2233 if (v > 0)
ac155bb8 2234 set_remove(other->dependencies[inverse_table[d]], u);
701cc384
LP
2235
2236 if (w > 0)
ac155bb8 2237 set_remove(u->dependencies[UNIT_REFERENCES], other);
701cc384
LP
2238
2239 return r;
87f0e418 2240}
0301abf4 2241
2c966c03
LP
2242int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
2243 int r;
2244
2245 assert(u);
2246
3f3cc397
LP
2247 r = unit_add_dependency(u, d, other, add_reference);
2248 if (r < 0)
2c966c03
LP
2249 return r;
2250
7410616c 2251 return unit_add_dependency(u, e, other, add_reference);
2c966c03
LP
2252}
2253
7410616c
LP
2254static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
2255 int r;
9e2f7c11
LP
2256
2257 assert(u);
2258 assert(name || path);
7410616c
LP
2259 assert(buf);
2260 assert(ret);
9e2f7c11
LP
2261
2262 if (!name)
2b6bf07d 2263 name = basename(path);
9e2f7c11 2264
7410616c
LP
2265 if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
2266 *buf = NULL;
2267 *ret = name;
2268 return 0;
9e2f7c11
LP
2269 }
2270
ac155bb8 2271 if (u->instance)
7410616c 2272 r = unit_name_replace_instance(name, u->instance, buf);
9e2f7c11 2273 else {
ae018d9b 2274 _cleanup_free_ char *i = NULL;
9e2f7c11 2275
7410616c
LP
2276 r = unit_name_to_prefix(u->id, &i);
2277 if (r < 0)
2278 return r;
9e2f7c11 2279
7410616c 2280 r = unit_name_replace_instance(name, i, buf);
9e2f7c11 2281 }
7410616c
LP
2282 if (r < 0)
2283 return r;
9e2f7c11 2284
7410616c
LP
2285 *ret = *buf;
2286 return 0;
9e2f7c11
LP
2287}
2288
701cc384 2289int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
7410616c 2290 _cleanup_free_ char *buf = NULL;
09b6b09f
LP
2291 Unit *other;
2292 int r;
2293
9e2f7c11
LP
2294 assert(u);
2295 assert(name || path);
09b6b09f 2296
7410616c
LP
2297 r = resolve_template(u, name, path, &buf, &name);
2298 if (r < 0)
2299 return r;
09b6b09f 2300
8afbb8e1
LP
2301 r = manager_load_unit(u->manager, name, path, NULL, &other);
2302 if (r < 0)
2303 return r;
9e2f7c11 2304
8afbb8e1 2305 return unit_add_dependency(u, d, other, add_reference);
09b6b09f
LP
2306}
2307
2c966c03 2308int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
7410616c 2309 _cleanup_free_ char *buf = NULL;
2c966c03
LP
2310 Unit *other;
2311 int r;
2c966c03
LP
2312
2313 assert(u);
2314 assert(name || path);
2315
7410616c
LP
2316 r = resolve_template(u, name, path, &buf, &name);
2317 if (r < 0)
2318 return r;
2c966c03 2319
3f3cc397
LP
2320 r = manager_load_unit(u->manager, name, path, NULL, &other);
2321 if (r < 0)
68eda4bd 2322 return r;
2c966c03 2323
3f3cc397 2324 return unit_add_two_dependencies(u, d, e, other, add_reference);
2c966c03
LP
2325}
2326
0301abf4 2327int set_unit_path(const char *p) {
0301abf4 2328 /* This is mostly for debug purposes */
cf7d80a5 2329 if (setenv("SYSTEMD_UNIT_PATH", p, 0) < 0)
26d04f86 2330 return -errno;
0301abf4
LP
2331
2332 return 0;
2333}
88066b3a 2334
ea430986 2335char *unit_dbus_path(Unit *u) {
ea430986
LP
2336 assert(u);
2337
ac155bb8 2338 if (!u->id)
04ade7d2
LP
2339 return NULL;
2340
48899192 2341 return unit_dbus_path_from_name(u->id);
ea430986
LP
2342}
2343
d79200e2
LP
2344int unit_set_slice(Unit *u, Unit *slice) {
2345 assert(u);
2346 assert(slice);
2347
2348 /* Sets the unit slice if it has not been set before. Is extra
2349 * careful, to only allow this for units that actually have a
2350 * cgroup context. Also, we don't allow to set this for slices
2351 * (since the parent slice is derived from the name). Make
2352 * sure the unit we set is actually a slice. */
2353
2354 if (!UNIT_HAS_CGROUP_CONTEXT(u))
2355 return -EOPNOTSUPP;
2356
2357 if (u->type == UNIT_SLICE)
2358 return -EINVAL;
2359
102ef982
LP
2360 if (unit_active_state(u) != UNIT_INACTIVE)
2361 return -EBUSY;
2362
d79200e2
LP
2363 if (slice->type != UNIT_SLICE)
2364 return -EINVAL;
2365
efdb0237
LP
2366 if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
2367 !unit_has_name(slice, SPECIAL_ROOT_SLICE))
2368 return -EPERM;
2369
d79200e2
LP
2370 if (UNIT_DEREF(u->slice) == slice)
2371 return 0;
2372
2373 if (UNIT_ISSET(u->slice))
2374 return -EBUSY;
2375
2376 unit_ref_set(&u->slice, slice);
2377 return 1;
2378}
2379
2380int unit_set_default_slice(Unit *u) {
a8833944
LP
2381 _cleanup_free_ char *b = NULL;
2382 const char *slice_name;
a016b922
LP
2383 Unit *slice;
2384 int r;
2385
2386 assert(u);
2387
9444b1f2 2388 if (UNIT_ISSET(u->slice))
a016b922
LP
2389 return 0;
2390
a8833944
LP
2391 if (u->instance) {
2392 _cleanup_free_ char *prefix = NULL, *escaped = NULL;
68eda4bd 2393
a8833944
LP
2394 /* Implicitly place all instantiated units in their
2395 * own per-template slice */
2396
7410616c
LP
2397 r = unit_name_to_prefix(u->id, &prefix);
2398 if (r < 0)
2399 return r;
a8833944
LP
2400
2401 /* The prefix is already escaped, but it might include
2402 * "-" which has a special meaning for slice units,
2403 * hence escape it here extra. */
7410616c 2404 escaped = unit_name_escape(prefix);
a8833944
LP
2405 if (!escaped)
2406 return -ENOMEM;
2407
b2c23da8 2408 if (u->manager->running_as == MANAGER_SYSTEM)
a8833944
LP
2409 b = strjoin("system-", escaped, ".slice", NULL);
2410 else
2411 b = strappend(escaped, ".slice");
2412 if (!b)
2413 return -ENOMEM;
2414
2415 slice_name = b;
2416 } else
2417 slice_name =
efdb0237 2418 u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
a8833944
LP
2419 ? SPECIAL_SYSTEM_SLICE
2420 : SPECIAL_ROOT_SLICE;
2421
2422 r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
a016b922
LP
2423 if (r < 0)
2424 return r;
2425
d79200e2 2426 return unit_set_slice(u, slice);
a016b922
LP
2427}
2428
9444b1f2
LP
2429const char *unit_slice_name(Unit *u) {
2430 assert(u);
2431
2432 if (!UNIT_ISSET(u->slice))
2433 return NULL;
2434
2435 return UNIT_DEREF(u->slice)->id;
2436}
2437
f6ff8c29 2438int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
78edb35a 2439 _cleanup_free_ char *t = NULL;
f6ff8c29
LP
2440 int r;
2441
2442 assert(u);
2443 assert(type);
2444 assert(_found);
2445
7410616c
LP
2446 r = unit_name_change_suffix(u->id, type, &t);
2447 if (r < 0)
2448 return r;
2449 if (unit_has_name(u, t))
2450 return -EINVAL;
f6ff8c29 2451
ac155bb8 2452 r = manager_load_unit(u->manager, t, NULL, NULL, _found);
9e2f7c11 2453 assert(r < 0 || *_found != u);
f6ff8c29
LP
2454 return r;
2455}
2456
bbc29086
DM
2457static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
2458 const char *name, *old_owner, *new_owner;
2459 Unit *u = userdata;
2460 int r;
2461
2462 assert(message);
2463 assert(u);
2464
2465 r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
2466 if (r < 0) {
2467 bus_log_parse_error(r);
2468 return 0;
2469 }
2470
2471 if (UNIT_VTABLE(u)->bus_name_owner_change)
2472 UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
2473
2474 return 0;
2475}
2476
9806e87d
LP
2477int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
2478 const char *match;
bbc29086 2479
9806e87d
LP
2480 assert(u);
2481 assert(bus);
2482 assert(name);
bbc29086
DM
2483
2484 if (u->match_bus_slot)
2485 return -EBUSY;
2486
9806e87d 2487 match = strjoina("type='signal',"
bbc29086
DM
2488 "sender='org.freedesktop.DBus',"
2489 "path='/org/freedesktop/DBus',"
2490 "interface='org.freedesktop.DBus',"
2491 "member='NameOwnerChanged',"
9806e87d 2492 "arg0='", name, "'",
bbc29086 2493 NULL);
bbc29086
DM
2494
2495 return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
2496}
2497
05e343b7 2498int unit_watch_bus_name(Unit *u, const char *name) {
bbc29086
DM
2499 int r;
2500
05e343b7
LP
2501 assert(u);
2502 assert(name);
2503
2504 /* Watch a specific name on the bus. We only support one unit
2505 * watching each name for now. */
2506
bbc29086
DM
2507 if (u->manager->api_bus) {
2508 /* If the bus is already available, install the match directly.
2509 * Otherwise, just put the name in the list. bus_setup_api() will take care later. */
9806e87d 2510 r = unit_install_bus_match(u, u->manager->api_bus, name);
bbc29086
DM
2511 if (r < 0)
2512 return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal: %m");
2513 }
2514
2515 r = hashmap_put(u->manager->watch_bus, name, u);
2516 if (r < 0) {
2517 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
2518 return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
2519 }
2520
2521 return 0;
05e343b7
LP
2522}
2523
2524void unit_unwatch_bus_name(Unit *u, const char *name) {
2525 assert(u);
2526 assert(name);
2527
ac155bb8 2528 hashmap_remove_value(u->manager->watch_bus, name, u);
bbc29086 2529 u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
05e343b7
LP
2530}
2531
a16e1123
LP
2532bool unit_can_serialize(Unit *u) {
2533 assert(u);
2534
2535 return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
2536}
2537
6b78f9b4 2538int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
a16e1123
LP
2539 int r;
2540
2541 assert(u);
2542 assert(f);
2543 assert(fds);
2544
9bdb98c5
LP
2545 if (unit_can_serialize(u)) {
2546 ExecRuntime *rt;
a16e1123 2547
9bdb98c5 2548 r = UNIT_VTABLE(u)->serialize(u, f, fds);
613b411c
LP
2549 if (r < 0)
2550 return r;
9bdb98c5
LP
2551
2552 rt = unit_get_exec_runtime(u);
2553 if (rt) {
f2341e0a 2554 r = exec_runtime_serialize(u, rt, f, fds);
9bdb98c5
LP
2555 if (r < 0)
2556 return r;
2557 }
e0209d83
MS
2558 }
2559
ac155bb8
MS
2560 dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
2561 dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
2562 dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
2563 dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
2564 dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
59fccdc5 2565 dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
2791a8f8 2566
ac155bb8
MS
2567 if (dual_timestamp_is_set(&u->condition_timestamp))
2568 unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
10717a1a 2569
59fccdc5
LP
2570 if (dual_timestamp_is_set(&u->assert_timestamp))
2571 unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
2572
c2756a68 2573 unit_serialize_item(u, f, "transient", yes_no(u->transient));
5ad096b3 2574 unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
c2756a68
LP
2575
2576 if (u->cgroup_path)
2577 unit_serialize_item(u, f, "cgroup", u->cgroup_path);
de1d4f9b 2578 unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
c2756a68 2579
32ee7d33
DM
2580 if (u->cgroup_netclass_id)
2581 unit_serialize_item_format(u, f, "netclass-id", "%" PRIu32, u->cgroup_netclass_id);
2582
613b411c
LP
2583 if (serialize_jobs) {
2584 if (u->job) {
2585 fprintf(f, "job\n");
2586 job_serialize(u->job, f, fds);
2587 }
2588
2589 if (u->nop_job) {
2590 fprintf(f, "job\n");
2591 job_serialize(u->nop_job, f, fds);
2592 }
2593 }
2594
a16e1123
LP
2595 /* End marker */
2596 fputc('\n', f);
2597 return 0;
2598}
2599
a34ceba6
LP
2600int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
2601 assert(u);
2602 assert(f);
2603 assert(key);
2604
2605 if (!value)
2606 return 0;
2607
2608 fputs(key, f);
2609 fputc('=', f);
2610 fputs(value, f);
2611 fputc('\n', f);
2612
2613 return 1;
2614}
2615
2616int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
2617 _cleanup_free_ char *c = NULL;
2618
2619 assert(u);
2620 assert(f);
2621 assert(key);
2622
2623 if (!value)
2624 return 0;
2625
2626 c = cescape(value);
2627 if (!c)
2628 return -ENOMEM;
2629
2630 fputs(key, f);
2631 fputc('=', f);
2632 fputs(c, f);
2633 fputc('\n', f);
2634
2635 return 1;
2636}
2637
2638int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
2639 int copy;
2640
2641 assert(u);
2642 assert(f);
2643 assert(key);
2644
2645 if (fd < 0)
2646 return 0;
2647
2648 copy = fdset_put_dup(fds, fd);
2649 if (copy < 0)
2650 return copy;
2651
2652 fprintf(f, "%s=%i\n", key, copy);
2653 return 1;
2654}
2655
a16e1123
LP
2656void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
2657 va_list ap;
2658
2659 assert(u);
2660 assert(f);
2661 assert(key);
2662 assert(format);
2663
2664 fputs(key, f);
2665 fputc('=', f);
2666
2667 va_start(ap, format);
2668 vfprintf(f, format, ap);
2669 va_end(ap);
2670
2671 fputc('\n', f);
2672}
2673
a16e1123 2674int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
28b99ccd 2675 ExecRuntime **rt = NULL;
9bdb98c5 2676 size_t offset;
a16e1123
LP
2677 int r;
2678
2679 assert(u);
2680 assert(f);
2681 assert(fds);
2682
613b411c
LP
2683 offset = UNIT_VTABLE(u)->exec_runtime_offset;
2684 if (offset > 0)
2685 rt = (ExecRuntime**) ((uint8_t*) u + offset);
2686
a16e1123 2687 for (;;) {
20c03b7b 2688 char line[LINE_MAX], *l, *v;
a16e1123
LP
2689 size_t k;
2690
2691 if (!fgets(line, sizeof(line), f)) {
2692 if (feof(f))
2693 return 0;
2694 return -errno;
2695 }
2696
10f8e83c 2697 char_array_0(line);
a16e1123
LP
2698 l = strstrip(line);
2699
2700 /* End marker */
e911de99 2701 if (isempty(l))
a16e1123
LP
2702 return 0;
2703
2704 k = strcspn(l, "=");
2705
2706 if (l[k] == '=') {
2707 l[k] = 0;
2708 v = l+k+1;
2709 } else
2710 v = l+k;
2711
cca098b0 2712 if (streq(l, "job")) {
39a18c60
MS
2713 if (v[0] == '\0') {
2714 /* new-style serialized job */
9c3349e2
LP
2715 Job *j;
2716
2717 j = job_new_raw(u);
39a18c60 2718 if (!j)
e911de99 2719 return log_oom();
39a18c60
MS
2720
2721 r = job_deserialize(j, f, fds);
2722 if (r < 0) {
2723 job_free(j);
2724 return r;
2725 }
cca098b0 2726
39a18c60
MS
2727 r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
2728 if (r < 0) {
2729 job_free(j);
2730 return r;
2731 }
e0209d83
MS
2732
2733 r = job_install_deserialized(j);
2734 if (r < 0) {
2735 hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
2736 job_free(j);
2737 return r;
2738 }
ed10fa8c
LP
2739 } else /* legacy for pre-44 */
2740 log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
cca098b0 2741 continue;
8aaf019b 2742 } else if (streq(l, "inactive-exit-timestamp")) {
ac155bb8 2743 dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
8aaf019b
LP
2744 continue;
2745 } else if (streq(l, "active-enter-timestamp")) {
ac155bb8 2746 dual_timestamp_deserialize(v, &u->active_enter_timestamp);
8aaf019b
LP
2747 continue;
2748 } else if (streq(l, "active-exit-timestamp")) {
ac155bb8 2749 dual_timestamp_deserialize(v, &u->active_exit_timestamp);
8aaf019b
LP
2750 continue;
2751 } else if (streq(l, "inactive-enter-timestamp")) {
ac155bb8 2752 dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
8aaf019b 2753 continue;
2791a8f8 2754 } else if (streq(l, "condition-timestamp")) {
ac155bb8 2755 dual_timestamp_deserialize(v, &u->condition_timestamp);
2791a8f8 2756 continue;
59fccdc5
LP
2757 } else if (streq(l, "assert-timestamp")) {
2758 dual_timestamp_deserialize(v, &u->assert_timestamp);
2759 continue;
2791a8f8 2760 } else if (streq(l, "condition-result")) {
2791a8f8 2761
e911de99
LP
2762 r = parse_boolean(v);
2763 if (r < 0)
f2341e0a 2764 log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
2791a8f8 2765 else
e911de99 2766 u->condition_result = r;
efbac6d2
LP
2767
2768 continue;
c2756a68 2769
59fccdc5 2770 } else if (streq(l, "assert-result")) {
59fccdc5 2771
e911de99
LP
2772 r = parse_boolean(v);
2773 if (r < 0)
f2341e0a 2774 log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
59fccdc5 2775 else
e911de99 2776 u->assert_result = r;
59fccdc5
LP
2777
2778 continue;
2779
c2756a68 2780 } else if (streq(l, "transient")) {
c2756a68 2781
e911de99
LP
2782 r = parse_boolean(v);
2783 if (r < 0)
f2341e0a 2784 log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
c2756a68 2785 else
e911de99 2786 u->transient = r;
c2756a68
LP
2787
2788 continue;
e911de99 2789
5ad096b3
LP
2790 } else if (streq(l, "cpuacct-usage-base")) {
2791
2792 r = safe_atou64(v, &u->cpuacct_usage_base);
2793 if (r < 0)
f2341e0a 2794 log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
5ad096b3 2795
0f908397 2796 continue;
4e595329 2797
e911de99 2798 } else if (streq(l, "cgroup")) {
72673e86 2799
e911de99
LP
2800 r = unit_set_cgroup_path(u, v);
2801 if (r < 0)
f2341e0a 2802 log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
4e595329 2803
efdb0237
LP
2804 (void) unit_watch_cgroup(u);
2805
de1d4f9b
WF
2806 continue;
2807 } else if (streq(l, "cgroup-realized")) {
2808 int b;
2809
2810 b = parse_boolean(v);
2811 if (b < 0)
2812 log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
2813 else
2814 u->cgroup_realized = b;
2815
32ee7d33
DM
2816 continue;
2817 } else if (streq(l, "netclass-id")) {
2818 r = safe_atou32(v, &u->cgroup_netclass_id);
2819 if (r < 0)
2820 log_unit_debug(u, "Failed to parse netclass ID %s, ignoring.", v);
2821 else {
2822 r = unit_add_to_netclass_cgroup(u);
2823 if (r < 0)
2824 log_unit_debug_errno(u, r, "Failed to add unit to netclass cgroup, ignoring: %m");
2825 }
2826
c2756a68 2827 continue;
8aaf019b 2828 }
cca098b0 2829
9bdb98c5
LP
2830 if (unit_can_serialize(u)) {
2831 if (rt) {
f2341e0a 2832 r = exec_runtime_deserialize_item(u, rt, l, v, fds);
e911de99 2833 if (r < 0) {
f2341e0a 2834 log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
e911de99
LP
2835 continue;
2836 }
2837
2838 /* Returns positive if key was handled by the call */
9bdb98c5
LP
2839 if (r > 0)
2840 continue;
2841 }
2842
2843 r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
613b411c 2844 if (r < 0)
f2341e0a 2845 log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
613b411c 2846 }
a16e1123
LP
2847 }
2848}
2849
6e2ef85b
LP
2850int unit_add_node_link(Unit *u, const char *what, bool wants) {
2851 Unit *device;
68eda4bd 2852 _cleanup_free_ char *e = NULL;
6e2ef85b
LP
2853 int r;
2854
2855 assert(u);
2856
6e2ef85b 2857 /* Adds in links to the device node that this unit is based on */
47bc12e1
LP
2858 if (isempty(what))
2859 return 0;
6e2ef85b 2860
8407a5d0 2861 if (!is_device_path(what))
6e2ef85b
LP
2862 return 0;
2863
47bc12e1
LP
2864 /* When device units aren't supported (such as in a
2865 * container), don't create dependencies on them. */
1c2e9646 2866 if (!unit_type_supported(UNIT_DEVICE))
47bc12e1
LP
2867 return 0;
2868
7410616c
LP
2869 r = unit_name_from_path(what, ".device", &e);
2870 if (r < 0)
2871 return r;
6e2ef85b 2872
ac155bb8 2873 r = manager_load_unit(u->manager, e, NULL, NULL, &device);
6e2ef85b
LP
2874 if (r < 0)
2875 return r;
2876
b2c23da8 2877 r = unit_add_two_dependencies(u, UNIT_AFTER, u->manager->running_as == MANAGER_SYSTEM ? UNIT_BINDS_TO : UNIT_WANTS, device, true);
faa368e3 2878 if (r < 0)
6e2ef85b
LP
2879 return r;
2880
faa368e3
LP
2881 if (wants) {
2882 r = unit_add_dependency(device, UNIT_WANTS, u, false);
2883 if (r < 0)
6e2ef85b 2884 return r;
faa368e3 2885 }
6e2ef85b
LP
2886
2887 return 0;
2888}
a16e1123 2889
be847e82 2890int unit_coldplug(Unit *u) {
cca098b0
LP
2891 int r;
2892
2893 assert(u);
2894
f78f265f
LP
2895 /* Make sure we don't enter a loop, when coldplugging
2896 * recursively. */
2897 if (u->coldplugged)
2898 return 0;
2899
2900 u->coldplugged = true;
2901
f78f265f
LP
2902 if (UNIT_VTABLE(u)->coldplug) {
2903 r = UNIT_VTABLE(u)->coldplug(u);
2904 if (r < 0)
2905 return r;
2906 }
cca098b0 2907
39a18c60
MS
2908 if (u->job) {
2909 r = job_coldplug(u->job);
2910 if (r < 0)
2911 return r;
be847e82 2912 }
cca098b0
LP
2913
2914 return 0;
2915}
2916
49b1d377 2917void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
bcfce235 2918 DISABLE_WARNING_FORMAT_NONLITERAL;
127d5fd1
ZJS
2919 manager_status_printf(u->manager, STATUS_TYPE_NORMAL,
2920 status, unit_status_msg_format, unit_description(u));
bcfce235 2921 REENABLE_WARNING;
49b1d377
MS
2922}
2923
45fb0699 2924bool unit_need_daemon_reload(Unit *u) {
ae7a7182
OS
2925 _cleanup_strv_free_ char **t = NULL;
2926 char **path;
1b64d026 2927 struct stat st;
ae7a7182 2928 unsigned loaded_cnt, current_cnt;
1b64d026 2929
45fb0699
LP
2930 assert(u);
2931
ac155bb8 2932 if (u->fragment_path) {
5f4b19f4 2933 zero(st);
ac155bb8 2934 if (stat(u->fragment_path, &st) < 0)
5f4b19f4
LP
2935 /* What, cannot access this anymore? */
2936 return true;
45fb0699 2937
ac155bb8
MS
2938 if (u->fragment_mtime > 0 &&
2939 timespec_load(&st.st_mtim) != u->fragment_mtime)
5f4b19f4
LP
2940 return true;
2941 }
2942
1b64d026
LP
2943 if (u->source_path) {
2944 zero(st);
2945 if (stat(u->source_path, &st) < 0)
2946 return true;
2947
2948 if (u->source_mtime > 0 &&
2949 timespec_load(&st.st_mtim) != u->source_mtime)
2950 return true;
2951 }
5f4b19f4 2952
1a7f1b38 2953 (void) unit_find_dropin_paths(u, &t);
ae7a7182
OS
2954 loaded_cnt = strv_length(t);
2955 current_cnt = strv_length(u->dropin_paths);
2956
2957 if (loaded_cnt == current_cnt) {
2958 if (loaded_cnt == 0)
2959 return false;
2960
2961 if (strv_overlap(u->dropin_paths, t)) {
2962 STRV_FOREACH(path, u->dropin_paths) {
2963 zero(st);
2964 if (stat(*path, &st) < 0)
2965 return true;
2966
2967 if (u->dropin_mtime > 0 &&
2968 timespec_load(&st.st_mtim) > u->dropin_mtime)
2969 return true;
2970 }
2971
2972 return false;
2973 } else
2974 return true;
2975 } else
2976 return true;
45fb0699
LP
2977}
2978
fdf20a31 2979void unit_reset_failed(Unit *u) {
5632e374
LP
2980 assert(u);
2981
fdf20a31
MM
2982 if (UNIT_VTABLE(u)->reset_failed)
2983 UNIT_VTABLE(u)->reset_failed(u);
5632e374
LP
2984}
2985
a7f241db
LP
2986Unit *unit_following(Unit *u) {
2987 assert(u);
2988
2989 if (UNIT_VTABLE(u)->following)
2990 return UNIT_VTABLE(u)->following(u);
2991
2992 return NULL;
2993}
2994
31afa0a4 2995bool unit_stop_pending(Unit *u) {
18ffdfda
LP
2996 assert(u);
2997
31afa0a4
LP
2998 /* This call does check the current state of the unit. It's
2999 * hence useful to be called from state change calls of the
3000 * unit itself, where the state isn't updated yet. This is
3001 * different from unit_inactive_or_pending() which checks both
3002 * the current state and for a queued job. */
18ffdfda 3003
31afa0a4
LP
3004 return u->job && u->job->type == JOB_STOP;
3005}
3006
3007bool unit_inactive_or_pending(Unit *u) {
3008 assert(u);
3009
3010 /* Returns true if the unit is inactive or going down */
18ffdfda 3011
d956ac29
LP
3012 if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
3013 return true;
3014
31afa0a4 3015 if (unit_stop_pending(u))
18ffdfda
LP
3016 return true;
3017
3018 return false;
3019}
3020
31afa0a4 3021bool unit_active_or_pending(Unit *u) {
f976f3f6
LP
3022 assert(u);
3023
f60c2665 3024 /* Returns true if the unit is active or going up */
f976f3f6
LP
3025
3026 if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
3027 return true;
3028
ac155bb8
MS
3029 if (u->job &&
3030 (u->job->type == JOB_START ||
3031 u->job->type == JOB_RELOAD_OR_START ||
3032 u->job->type == JOB_RESTART))
f976f3f6
LP
3033 return true;
3034
3035 return false;
3036}
3037
718db961 3038int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
8a0867d6
LP
3039 assert(u);
3040 assert(w >= 0 && w < _KILL_WHO_MAX);
8a0867d6
LP
3041 assert(signo > 0);
3042 assert(signo < _NSIG);
3043
8a0867d6 3044 if (!UNIT_VTABLE(u)->kill)
15411c0c 3045 return -EOPNOTSUPP;
8a0867d6 3046
c74f17d9 3047 return UNIT_VTABLE(u)->kill(u, w, signo, error);
8a0867d6
LP
3048}
3049
82659fd7
LP
3050static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
3051 Set *pid_set;
3052 int r;
3053
d5099efc 3054 pid_set = set_new(NULL);
82659fd7
LP
3055 if (!pid_set)
3056 return NULL;
3057
3058 /* Exclude the main/control pids from being killed via the cgroup */
3059 if (main_pid > 0) {
fea72cc0 3060 r = set_put(pid_set, PID_TO_PTR(main_pid));
82659fd7
LP
3061 if (r < 0)
3062 goto fail;
3063 }
3064
3065 if (control_pid > 0) {
fea72cc0 3066 r = set_put(pid_set, PID_TO_PTR(control_pid));
82659fd7
LP
3067 if (r < 0)
3068 goto fail;
3069 }
3070
3071 return pid_set;
3072
3073fail:
3074 set_free(pid_set);
3075 return NULL;
3076}
3077
d91c34f2
LP
3078int unit_kill_common(
3079 Unit *u,
3080 KillWho who,
3081 int signo,
3082 pid_t main_pid,
3083 pid_t control_pid,
718db961 3084 sd_bus_error *error) {
d91c34f2 3085
814cc562 3086 int r = 0;
ac5e3a50 3087 bool killed = false;
814cc562 3088
ac5e3a50 3089 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
814cc562 3090 if (main_pid < 0)
7358dc02 3091 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
52f448c3 3092 else if (main_pid == 0)
7358dc02 3093 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
814cc562
MS
3094 }
3095
ac5e3a50 3096 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
814cc562 3097 if (control_pid < 0)
7358dc02 3098 return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
52f448c3 3099 else if (control_pid == 0)
7358dc02 3100 return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
814cc562
MS
3101 }
3102
ac5e3a50
JS
3103 if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
3104 if (control_pid > 0) {
814cc562
MS
3105 if (kill(control_pid, signo) < 0)
3106 r = -errno;
ac5e3a50
JS
3107 else
3108 killed = true;
3109 }
814cc562 3110
ac5e3a50
JS
3111 if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
3112 if (main_pid > 0) {
814cc562
MS
3113 if (kill(main_pid, signo) < 0)
3114 r = -errno;
ac5e3a50
JS
3115 else
3116 killed = true;
3117 }
814cc562 3118
ac5e3a50 3119 if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
814cc562
MS
3120 _cleanup_set_free_ Set *pid_set = NULL;
3121 int q;
3122
82659fd7
LP
3123 /* Exclude the main/control pids from being killed via the cgroup */
3124 pid_set = unit_pid_set(main_pid, control_pid);
814cc562
MS
3125 if (!pid_set)
3126 return -ENOMEM;
3127
d0667321 3128 q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set);
814cc562
MS
3129 if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
3130 r = q;
ac5e3a50
JS
3131 else
3132 killed = true;
814cc562
MS
3133 }
3134
ac5e3a50
JS
3135 if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_ALL_FAIL))
3136 return -ESRCH;
3137
814cc562
MS
3138 return r;
3139}
3140
6210e7fc
LP
3141int unit_following_set(Unit *u, Set **s) {
3142 assert(u);
3143 assert(s);
3144
3145 if (UNIT_VTABLE(u)->following_set)
3146 return UNIT_VTABLE(u)->following_set(u, s);
3147
3148 *s = NULL;
3149 return 0;
3150}
3151
a4375746
LP
3152UnitFileState unit_get_unit_file_state(Unit *u) {
3153 assert(u);
3154
ac155bb8
MS
3155 if (u->unit_file_state < 0 && u->fragment_path)
3156 u->unit_file_state = unit_file_get_state(
b2c23da8 3157 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2b6bf07d 3158 NULL, basename(u->fragment_path));
a4375746 3159
ac155bb8 3160 return u->unit_file_state;
a4375746
LP
3161}
3162
d2dc52db
LP
3163int unit_get_unit_file_preset(Unit *u) {
3164 assert(u);
3165
3166 if (u->unit_file_preset < 0 && u->fragment_path)
3167 u->unit_file_preset = unit_file_query_preset(
b2c23da8 3168 u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
d2dc52db
LP
3169 NULL, basename(u->fragment_path));
3170
3171 return u->unit_file_preset;
3172}
3173
57020a3a
LP
3174Unit* unit_ref_set(UnitRef *ref, Unit *u) {
3175 assert(ref);
3176 assert(u);
3177
3178 if (ref->unit)
3179 unit_ref_unset(ref);
3180
3181 ref->unit = u;
71fda00f 3182 LIST_PREPEND(refs, u->refs, ref);
57020a3a
LP
3183 return u;
3184}
3185
3186void unit_ref_unset(UnitRef *ref) {
3187 assert(ref);
3188
3189 if (!ref->unit)
3190 return;
3191
71fda00f 3192 LIST_REMOVE(refs, ref->unit->refs, ref);
57020a3a
LP
3193 ref->unit = NULL;
3194}
3195
598459ce
LP
3196int unit_patch_contexts(Unit *u) {
3197 CGroupContext *cc;
3198 ExecContext *ec;
cba6e062
LP
3199 unsigned i;
3200 int r;
3201
e06c73cc 3202 assert(u);
e06c73cc 3203
598459ce
LP
3204 /* Patch in the manager defaults into the exec and cgroup
3205 * contexts, _after_ the rest of the settings have been
3206 * initialized */
085afe36 3207
598459ce
LP
3208 ec = unit_get_exec_context(u);
3209 if (ec) {
3210 /* This only copies in the ones that need memory */
3211 for (i = 0; i < _RLIMIT_MAX; i++)
3212 if (u->manager->rlimit[i] && !ec->rlimit[i]) {
3213 ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
3214 if (!ec->rlimit[i])
3215 return -ENOMEM;
3216 }
3217
b2c23da8 3218 if (u->manager->running_as == MANAGER_USER &&
598459ce
LP
3219 !ec->working_directory) {
3220
3221 r = get_home_dir(&ec->working_directory);
3222 if (r < 0)
3223 return r;
4c08c824
LP
3224
3225 /* Allow user services to run, even if the
3226 * home directory is missing */
3227 ec->working_directory_missing_ok = true;
cba6e062
LP
3228 }
3229
b2c23da8 3230 if (u->manager->running_as == MANAGER_USER &&
598459ce
LP
3231 (ec->syscall_whitelist ||
3232 !set_isempty(ec->syscall_filter) ||
3233 !set_isempty(ec->syscall_archs) ||
3234 ec->address_families_whitelist ||
3235 !set_isempty(ec->address_families)))
3236 ec->no_new_privileges = true;
e06c73cc 3237
598459ce
LP
3238 if (ec->private_devices)
3239 ec->capability_bounding_set_drop |= (uint64_t) 1ULL << (uint64_t) CAP_MKNOD;
cba6e062
LP
3240 }
3241
598459ce
LP
3242 cc = unit_get_cgroup_context(u);
3243 if (cc) {
f513e420 3244
598459ce
LP
3245 if (ec &&
3246 ec->private_devices &&
3247 cc->device_policy == CGROUP_AUTO)
3248 cc->device_policy = CGROUP_CLOSED;
3249 }
f1660f96 3250
cba6e062 3251 return 0;
e06c73cc
LP
3252}
3253
3ef63c31
LP
3254ExecContext *unit_get_exec_context(Unit *u) {
3255 size_t offset;
3256 assert(u);
3257
598459ce
LP
3258 if (u->type < 0)
3259 return NULL;
3260
3ef63c31
LP
3261 offset = UNIT_VTABLE(u)->exec_context_offset;
3262 if (offset <= 0)
3263 return NULL;
3264
3265 return (ExecContext*) ((uint8_t*) u + offset);
3266}
3267
718db961
LP
3268KillContext *unit_get_kill_context(Unit *u) {
3269 size_t offset;
3270 assert(u);
3271
598459ce
LP
3272 if (u->type < 0)
3273 return NULL;
3274
718db961
LP
3275 offset = UNIT_VTABLE(u)->kill_context_offset;
3276 if (offset <= 0)
3277 return NULL;
3278
3279 return (KillContext*) ((uint8_t*) u + offset);
3280}
3281
4ad49000
LP
3282CGroupContext *unit_get_cgroup_context(Unit *u) {
3283 size_t offset;
3284
598459ce
LP
3285 if (u->type < 0)
3286 return NULL;
3287
4ad49000
LP
3288 offset = UNIT_VTABLE(u)->cgroup_context_offset;
3289 if (offset <= 0)
3290 return NULL;
3291
3292 return (CGroupContext*) ((uint8_t*) u + offset);
3293}
3294
613b411c
LP
3295ExecRuntime *unit_get_exec_runtime(Unit *u) {
3296 size_t offset;
3297
598459ce
LP
3298 if (u->type < 0)
3299 return NULL;
3300
613b411c
LP
3301 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3302 if (offset <= 0)
3303 return NULL;
3304
3305 return *(ExecRuntime**) ((uint8_t*) u + offset);
3306}
3307
29686440 3308static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) {
3f5e8115
LP
3309 assert(u);
3310
b2c23da8 3311 if (u->manager->running_as == MANAGER_USER) {
29686440 3312 int r;
26d04f86 3313
718880ba
SA
3314 if (mode == UNIT_PERSISTENT && !transient)
3315 r = user_config_home(dir);
3316 else
4d5dec23 3317 r = user_runtime_dir(dir);
26d04f86
LP
3318 if (r == 0)
3319 return -ENOENT;
3f5e8115 3320
29686440
ZJS
3321 return r;
3322 }
26d04f86 3323
29686440
ZJS
3324 if (mode == UNIT_PERSISTENT && !transient)
3325 *dir = strdup("/etc/systemd/system");
8e2af478 3326 else
29686440
ZJS
3327 *dir = strdup("/run/systemd/system");
3328 if (!*dir)
71645aca
LP
3329 return -ENOMEM;
3330
26d04f86 3331 return 0;
71645aca
LP
3332}
3333
8e2af478 3334int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
29686440 3335
adb76a70 3336 _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL;
26d04f86 3337 int r;
71645aca
LP
3338
3339 assert(u);
3340
6d235724 3341 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
8e2af478
LP
3342 return 0;
3343
29686440 3344 r = unit_drop_in_dir(u, mode, u->transient, &dir);
26d04f86
LP
3345 if (r < 0)
3346 return r;
71645aca 3347
adb76a70
WC
3348 r = write_drop_in(dir, u->id, 50, name, data);
3349 if (r < 0)
3350 return r;
3351
3352 r = drop_in_file(dir, u->id, 50, name, &p, &q);
3353 if (r < 0)
3354 return r;
3355
3356 r = strv_extend(&u->dropin_paths, q);
3357 if (r < 0)
3358 return r;
3359
3360 strv_sort(u->dropin_paths);
3361 strv_uniq(u->dropin_paths);
3362
3363 u->dropin_mtime = now(CLOCK_REALTIME);
3364
3365 return 0;
26d04f86 3366}
71645aca 3367
b9ec9359
LP
3368int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3369 _cleanup_free_ char *p = NULL;
3370 va_list ap;
3371 int r;
3372
3373 assert(u);
3374 assert(name);
3375 assert(format);
3376
6d235724 3377 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3378 return 0;
3379
3380 va_start(ap, format);
3381 r = vasprintf(&p, format, ap);
3382 va_end(ap);
3383
3384 if (r < 0)
3385 return -ENOMEM;
3386
3387 return unit_write_drop_in(u, mode, name, p);
3388}
3389
3390int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
b42defe3
LP
3391 _cleanup_free_ char *ndata = NULL;
3392
3393 assert(u);
3394 assert(name);
3395 assert(data);
3396
3397 if (!UNIT_VTABLE(u)->private_section)
3398 return -EINVAL;
3399
6d235724 3400 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3401 return 0;
3402
b42defe3
LP
3403 ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL);
3404 if (!ndata)
3405 return -ENOMEM;
3406
3407 return unit_write_drop_in(u, mode, name, ndata);
3408}
3409
b9ec9359
LP
3410int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
3411 _cleanup_free_ char *p = NULL;
3412 va_list ap;
3413 int r;
3414
3415 assert(u);
3416 assert(name);
3417 assert(format);
3418
6d235724 3419 if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
b9ec9359
LP
3420 return 0;
3421
3422 va_start(ap, format);
3423 r = vasprintf(&p, format, ap);
3424 va_end(ap);
3425
3426 if (r < 0)
3427 return -ENOMEM;
3428
3429 return unit_write_drop_in_private(u, mode, name, p);
3430}
71645aca 3431
c2756a68 3432int unit_make_transient(Unit *u) {
c2756a68
LP
3433 assert(u);
3434
3f5e8115
LP
3435 if (!UNIT_VTABLE(u)->can_transient)
3436 return -EOPNOTSUPP;
3437
c2756a68
LP
3438 u->load_state = UNIT_STUB;
3439 u->load_error = 0;
3440 u->transient = true;
3f5e8115 3441 u->fragment_path = mfree(u->fragment_path);
c2756a68 3442
3f5e8115 3443 return 0;
c2756a68
LP
3444}
3445
cd2086fe
LP
3446int unit_kill_context(
3447 Unit *u,
3448 KillContext *c,
db2cb23b 3449 KillOperation k,
cd2086fe
LP
3450 pid_t main_pid,
3451 pid_t control_pid,
3452 bool main_pid_alien) {
3453
b821a397
LP
3454 bool wait_for_exit = false;
3455 int sig, r;
cd2086fe
LP
3456
3457 assert(u);
3458 assert(c);
3459
3460 if (c->kill_mode == KILL_NONE)
3461 return 0;
3462
db2cb23b
UTL
3463 switch (k) {
3464 case KILL_KILL:
3465 sig = SIGKILL;
3466 break;
3467 case KILL_ABORT:
3468 sig = SIGABRT;
3469 break;
3470 case KILL_TERMINATE:
3471 sig = c->kill_signal;
3472 break;
3473 default:
3474 assert_not_reached("KillOperation unknown");
3475 }
cd2086fe
LP
3476
3477 if (main_pid > 0) {
3478 r = kill_and_sigcont(main_pid, sig);
3479
3480 if (r < 0 && r != -ESRCH) {
3481 _cleanup_free_ char *comm = NULL;
3482 get_process_comm(main_pid, &comm);
3483
b821a397 3484 log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
82659fd7 3485 } else {
bc6aed7b
LP
3486 if (!main_pid_alien)
3487 wait_for_exit = true;
82659fd7 3488
d0667321
LP
3489 if (c->send_sighup && k == KILL_TERMINATE)
3490 (void) kill(main_pid, SIGHUP);
82659fd7 3491 }
cd2086fe
LP
3492 }
3493
3494 if (control_pid > 0) {
3495 r = kill_and_sigcont(control_pid, sig);
3496
3497 if (r < 0 && r != -ESRCH) {
3498 _cleanup_free_ char *comm = NULL;
3499 get_process_comm(control_pid, &comm);
3500
b821a397 3501 log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
82659fd7 3502 } else {
cd2086fe 3503 wait_for_exit = true;
82659fd7 3504
d0667321
LP
3505 if (c->send_sighup && k == KILL_TERMINATE)
3506 (void) kill(control_pid, SIGHUP);
82659fd7 3507 }
cd2086fe
LP
3508 }
3509
b821a397
LP
3510 if (u->cgroup_path &&
3511 (c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
cd2086fe
LP
3512 _cleanup_set_free_ Set *pid_set = NULL;
3513
82659fd7
LP
3514 /* Exclude the main/control pids from being killed via the cgroup */
3515 pid_set = unit_pid_set(main_pid, control_pid);
cd2086fe
LP
3516 if (!pid_set)
3517 return -ENOMEM;
3518
d0667321 3519 r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set);
cd2086fe
LP
3520 if (r < 0) {
3521 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
b821a397
LP
3522 log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
3523
82659fd7 3524 } else if (r > 0) {
bc6aed7b 3525
efdb0237
LP
3526 /* FIXME: For now, on the legacy hierarchy, we
3527 * will not wait for the cgroup members to die
3528 * if we are running in a container or if this
3529 * is a delegation unit, simply because cgroup
3530 * notification is unreliable in these
3531 * cases. It doesn't work at all in
3532 * containers, and outside of containers it
3533 * can be confused easily by left-over
3534 * directories in the cgroup -- which however
3535 * should not exist in non-delegated units. On
3536 * the unified hierarchy that's different,
3537 * there we get proper events. Hence rely on
3538 * them.*/
3539
3540 if (cg_unified() > 0 ||
75f86906 3541 (detect_container() == 0 && !unit_cgroup_delegate(u)))
e9db43d5 3542 wait_for_exit = true;
58ea275a 3543
db2cb23b 3544 if (c->send_sighup && k != KILL_KILL) {
82659fd7
LP
3545 set_free(pid_set);
3546
3547 pid_set = unit_pid_set(main_pid, control_pid);
3548 if (!pid_set)
3549 return -ENOMEM;
3550
8190da36 3551 cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set);
82659fd7
LP
3552 }
3553 }
cd2086fe
LP
3554 }
3555
3556 return wait_for_exit;
3557}
3558
a57f7e2c
LP
3559int unit_require_mounts_for(Unit *u, const char *path) {
3560 char prefix[strlen(path) + 1], *p;
3561 int r;
3562
3563 assert(u);
3564 assert(path);
3565
3566 /* Registers a unit for requiring a certain path and all its
3567 * prefixes. We keep a simple array of these paths in the
3568 * unit, since its usually short. However, we build a prefix
3569 * table for all possible prefixes so that new appearing mount
3570 * units can easily determine which units to make themselves a
3571 * dependency of. */
3572
70b64bd3
ZJS
3573 if (!path_is_absolute(path))
3574 return -EINVAL;
3575
a57f7e2c
LP
3576 p = strdup(path);
3577 if (!p)
3578 return -ENOMEM;
3579
3580 path_kill_slashes(p);
3581
a57f7e2c
LP
3582 if (!path_is_safe(p)) {
3583 free(p);
3584 return -EPERM;
3585 }
3586
3587 if (strv_contains(u->requires_mounts_for, p)) {
3588 free(p);
3589 return 0;
3590 }
3591
6e18964d
ZJS
3592 r = strv_consume(&u->requires_mounts_for, p);
3593 if (r < 0)
a57f7e2c 3594 return r;
a57f7e2c
LP
3595
3596 PATH_FOREACH_PREFIX_MORE(prefix, p) {
3597 Set *x;
3598
3599 x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
3600 if (!x) {
3601 char *q;
3602
742f41ad
LP
3603 r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
3604 if (r < 0)
3605 return r;
a57f7e2c
LP
3606
3607 q = strdup(prefix);
3608 if (!q)
3609 return -ENOMEM;
3610
d5099efc 3611 x = set_new(NULL);
a57f7e2c
LP
3612 if (!x) {
3613 free(q);
3614 return -ENOMEM;
3615 }
3616
3617 r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
3618 if (r < 0) {
3619 free(q);
3620 set_free(x);
3621 return r;
3622 }
3623 }
3624
3625 r = set_put(x, u);
3626 if (r < 0)
3627 return r;
3628 }
3629
3630 return 0;
3631}
3632
613b411c
LP
3633int unit_setup_exec_runtime(Unit *u) {
3634 ExecRuntime **rt;
3635 size_t offset;
3636 Iterator i;
3637 Unit *other;
3638
3639 offset = UNIT_VTABLE(u)->exec_runtime_offset;
3640 assert(offset > 0);
3641
06b643e7 3642 /* Check if there already is an ExecRuntime for this unit? */
613b411c
LP
3643 rt = (ExecRuntime**) ((uint8_t*) u + offset);
3644 if (*rt)
3645 return 0;
3646
3647 /* Try to get it from somebody else */
3648 SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
3649
3650 *rt = unit_get_exec_runtime(other);
3651 if (*rt) {
3652 exec_runtime_ref(*rt);
3653 return 0;
3654 }
3655 }
3656
3657 return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
3658}
3659
1c2e9646
LP
3660bool unit_type_supported(UnitType t) {
3661 if (_unlikely_(t < 0))
3662 return false;
3663 if (_unlikely_(t >= _UNIT_TYPE_MAX))
3664 return false;
3665
3666 if (!unit_vtable[t]->supported)
3667 return true;
3668
3669 return unit_vtable[t]->supported();
3670}
3671
8b4305c7
LP
3672void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
3673 int r;
3674
3675 assert(u);
3676 assert(where);
3677
3678 r = dir_is_empty(where);
3679 if (r > 0)
3680 return;
3681 if (r < 0) {
3682 log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
3683 return;
3684 }
3685
3686 log_struct(LOG_NOTICE,
3687 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3688 LOG_UNIT_ID(u),
3689 LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
3690 "WHERE=%s", where,
3691 NULL);
3692}
3693
3694int unit_fail_if_symlink(Unit *u, const char* where) {
3695 int r;
3696
3697 assert(u);
3698 assert(where);
3699
3700 r = is_symlink(where);
3701 if (r < 0) {
3702 log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
3703 return 0;
3704 }
3705 if (r == 0)
3706 return 0;
3707
3708 log_struct(LOG_ERR,
3709 LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
3710 LOG_UNIT_ID(u),
3711 LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
3712 "WHERE=%s", where,
3713 NULL);
3714
3715 return -ELOOP;
3716}