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