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