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