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