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