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