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