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