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