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