]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/unit-file.c
test-unit-file: enable colors
[thirdparty/systemd.git] / src / basic / unit-file.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
5cfa33e0 2
c2911d48
ZJS
3#include "sd-id128.h"
4
e8630e69
ZJS
5#include "dirent-util.h"
6#include "fd-util.h"
7#include "fs-util.h"
5cfa33e0 8#include "macro.h"
e8630e69
ZJS
9#include "path-lookup.h"
10#include "set.h"
da33cba0 11#include "special.h"
e8630e69 12#include "stat-util.h"
7d1e91d1 13#include "string-util.h"
e8630e69 14#include "strv.h"
5cfa33e0
ZJS
15#include "unit-file.h"
16
17bool unit_type_may_alias(UnitType type) {
18 return IN_SET(type,
19 UNIT_SERVICE,
20 UNIT_SOCKET,
21 UNIT_TARGET,
22 UNIT_DEVICE,
23 UNIT_TIMER,
24 UNIT_PATH);
25}
26
27bool unit_type_may_template(UnitType type) {
28 return IN_SET(type,
29 UNIT_SERVICE,
30 UNIT_SOCKET,
31 UNIT_TARGET,
32 UNIT_TIMER,
33 UNIT_PATH);
34}
7d1e91d1 35
1bf15585 36int unit_symlink_name_compatible(const char *symlink, const char *target, bool instance_propagation) {
9a4f9e69 37 _cleanup_free_ char *template = NULL;
1bf15585 38 int r, un_type1, un_type2;
9a4f9e69 39
1bf15585
ZJS
40 un_type1 = unit_name_classify(symlink);
41
42 /* The straightforward case: the symlink name matches the target and we have a valid unit */
43 if (streq(symlink, target) &&
44 (un_type1 & (UNIT_NAME_PLAIN | UNIT_NAME_INSTANCE)))
9a4f9e69
ZJS
45 return 1;
46
47 r = unit_name_template(symlink, &template);
48 if (r == -EINVAL)
49 return 0; /* Not a template */
50 if (r < 0)
51 return r;
52
1bf15585
ZJS
53 un_type2 = unit_name_classify(target);
54
9a4f9e69 55 /* An instance name points to a target that is just the template name */
1bf15585
ZJS
56 if (un_type1 == UNIT_NAME_INSTANCE &&
57 un_type2 == UNIT_NAME_TEMPLATE &&
58 streq(template, target))
59 return 1;
60
61 /* foo@.target.requires/bar@.service: instance will be propagated */
62 if (instance_propagation &&
63 un_type1 == UNIT_NAME_TEMPLATE &&
64 un_type2 == UNIT_NAME_TEMPLATE &&
65 streq(template, target))
66 return 1;
67
68 return 0;
9a4f9e69
ZJS
69}
70
7d1e91d1
ZJS
71int unit_validate_alias_symlink_and_warn(const char *filename, const char *target) {
72 const char *src, *dst;
73 _cleanup_free_ char *src_instance = NULL, *dst_instance = NULL;
74 UnitType src_unit_type, dst_unit_type;
75 int src_name_type, dst_name_type;
76
77 /* Check if the *alias* symlink is valid. This applies to symlinks like
78 * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
79 * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
80 * unit lookup path.
81 *
82 * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
83 * not allowed to symlink,
84 * -EXDEV if the target filename is not a valid unit name or doesn't match the source.
85 */
86
87 src = basename(filename);
88 dst = basename(target);
89
90 /* src checks */
91
92 src_name_type = unit_name_to_instance(src, &src_instance);
93 if (src_name_type < 0)
94 return log_notice_errno(src_name_type,
95 "%s: not a valid unit name \"%s\": %m", filename, src);
96
97 src_unit_type = unit_name_to_type(src);
98 assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
99
100 if (!unit_type_may_alias(src_unit_type))
101 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL),
102 "%s: symlinks are not allowed for units of this type, rejecting.",
103 filename);
104
105 if (src_name_type != UNIT_NAME_PLAIN &&
106 !unit_type_may_template(src_unit_type))
107 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL),
108 "%s: templates not allowed for %s units, rejecting.",
109 filename, unit_type_to_string(src_unit_type));
110
111 /* dst checks */
112
113 dst_name_type = unit_name_to_instance(dst, &dst_instance);
114 if (dst_name_type < 0)
115 return log_notice_errno(dst_name_type == -EINVAL ? SYNTHETIC_ERRNO(EXDEV) : dst_name_type,
116 "%s points to \"%s\" which is not a valid unit name: %m",
117 filename, dst);
118
119 if (!(dst_name_type == src_name_type ||
120 (src_name_type == UNIT_NAME_INSTANCE && dst_name_type == UNIT_NAME_TEMPLATE)))
121 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
122 "%s: symlink target name type \"%s\" does not match source, rejecting.",
123 filename, dst);
124
125 if (dst_name_type == UNIT_NAME_INSTANCE) {
126 assert(src_instance);
127 assert(dst_instance);
128 if (!streq(src_instance, dst_instance))
129 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
130 "%s: unit symlink target \"%s\" instance name doesn't match, rejecting.",
131 filename, dst);
132 }
133
134 dst_unit_type = unit_name_to_type(dst);
135 if (dst_unit_type != src_unit_type)
136 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
137 "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
138 filename, dst);
139
140 return 0;
141}
e8630e69
ZJS
142
143#define FOLLOW_MAX 8
144
145static int unit_ids_map_get(
146 Hashmap *unit_ids_map,
147 const char *unit_name,
148 const char **ret_fragment_path) {
149
150 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
151 *
152 * We distinguish the case where unit_name was not found in the hashmap at all, and the case where
153 * some symlink was broken.
154 *
155 * If a symlink target points to an instance name, then we also check for the template. */
156
157 const char *id = NULL;
158 int r;
159
160 for (unsigned n = 0; n < FOLLOW_MAX; n++) {
161 const char *t = hashmap_get(unit_ids_map, id ?: unit_name);
162 if (!t) {
163 _cleanup_free_ char *template = NULL;
164
165 if (!id)
166 return -ENOENT;
167
168 r = unit_name_template(id, &template);
169 if (r == -EINVAL)
170 return -ENXIO; /* we failed to find the symlink target */
171 if (r < 0)
172 return log_error_errno(r, "Failed to determine template name for %s: %m", id);
173
174 t = hashmap_get(unit_ids_map, template);
175 if (!t)
176 return -ENXIO;
177
178 /* We successfully switched from instanced name to a template, let's continue */
179 }
180
181 if (path_is_absolute(t)) {
182 if (ret_fragment_path)
183 *ret_fragment_path = t;
184 return 0;
185 }
186
187 id = t;
188 }
189
190 return -ELOOP;
191}
192
91e0ee5f
ZJS
193static bool lookup_paths_mtime_exclude(const LookupPaths *lp, const char *path) {
194 /* Paths that are under our exclusive control. Users shall not alter those directly. */
195
196 return streq_ptr(path, lp->generator) ||
197 streq_ptr(path, lp->generator_early) ||
198 streq_ptr(path, lp->generator_late) ||
199 streq_ptr(path, lp->transient) ||
200 streq_ptr(path, lp->persistent_control) ||
201 streq_ptr(path, lp->runtime_control);
202}
203
c2911d48
ZJS
204#define HASH_KEY SD_ID128_MAKE(4e,86,1b,e3,39,b3,40,46,98,5d,b8,11,34,8f,c3,c1)
205
206bool lookup_paths_timestamp_hash_same(const LookupPaths *lp, uint64_t timestamp_hash, uint64_t *ret_new) {
207 struct siphash state;
91e0ee5f 208
c2911d48
ZJS
209 siphash24_init(&state, HASH_KEY.bytes);
210
211 char **dir;
91e0ee5f
ZJS
212 STRV_FOREACH(dir, (char**) lp->search_path) {
213 struct stat st;
214
215 if (lookup_paths_mtime_exclude(lp, *dir))
216 continue;
217
218 /* Determine the latest lookup path modification time */
219 if (stat(*dir, &st) < 0) {
220 if (errno == ENOENT)
221 continue;
222
223 log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
224 continue;
225 }
226
c2911d48 227 siphash24_compress_usec_t(timespec_load(&st.st_mtim), &state);
91e0ee5f
ZJS
228 }
229
c2911d48
ZJS
230 uint64_t updated = siphash24_finalize(&state);
231 if (ret_new)
232 *ret_new = updated;
233 if (updated != timestamp_hash)
234 log_debug("Modification times have changed, need to update cache.");
235 return updated == timestamp_hash;
91e0ee5f
ZJS
236}
237
e8630e69
ZJS
238int unit_file_build_name_map(
239 const LookupPaths *lp,
c2911d48 240 uint64_t *cache_timestamp_hash,
3fb2326f
ZJS
241 Hashmap **unit_ids_map,
242 Hashmap **unit_names_map,
243 Set **path_cache) {
e8630e69
ZJS
244
245 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
fa027117 246 * all aliases (i.e. the entry for a given key is a list of all names which point to this key). The
e8630e69
ZJS
247 * key is included in the value iff we saw a file or symlink with that name. In other words, if we
248 * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
249 * the unit itself is not loadable.
250 *
3fb2326f
ZJS
251 * At the same, build a cache of paths where to find units. The non-const parameters are for input
252 * and output. Existing contents will be freed before the new contents are stored.
e8630e69
ZJS
253 */
254
255 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
256 _cleanup_set_free_free_ Set *paths = NULL;
c2911d48 257 uint64_t timestamp_hash;
e8630e69
ZJS
258 char **dir;
259 int r;
91e0ee5f 260
c2911d48
ZJS
261 /* Before doing anything, check if the timestamp hash that was passed is still valid.
262 * If yes, do nothing. */
263 if (cache_timestamp_hash &&
264 lookup_paths_timestamp_hash_same(lp, *cache_timestamp_hash, &timestamp_hash))
f6067186 265 return 0;
c2911d48
ZJS
266
267 /* The timestamp hash is now set based on the mtimes from before when we start reading files.
268 * If anything is modified concurrently, we'll consider the cache outdated. */
e8630e69 269
3fb2326f
ZJS
270 if (path_cache) {
271 paths = set_new(&path_hash_ops_free);
e8630e69
ZJS
272 if (!paths)
273 return log_oom();
274 }
275
276 STRV_FOREACH(dir, (char**) lp->search_path) {
277 struct dirent *de;
278 _cleanup_closedir_ DIR *d = NULL;
279
280 d = opendir(*dir);
281 if (!d) {
282 if (errno != ENOENT)
283 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
284 continue;
285 }
286
3796bdc5 287 FOREACH_DIRENT(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
e8630e69
ZJS
288 char *filename;
289 _cleanup_free_ char *_filename_free = NULL, *simplified = NULL;
290 const char *suffix, *dst = NULL;
890befcf
ZJS
291 bool valid_unit_name;
292
293 valid_unit_name = unit_name_is_valid(de->d_name, UNIT_NAME_ANY);
294
295 /* We only care about valid units and dirs with certain suffixes, let's ignore the
296 * rest. */
297 if (!valid_unit_name &&
298 !ENDSWITH_SET(de->d_name, ".wants", ".requires", ".d"))
299 continue;
e8630e69
ZJS
300
301 filename = path_join(*dir, de->d_name);
302 if (!filename)
303 return log_oom();
304
3fb2326f 305 if (paths) {
e8630e69
ZJS
306 r = set_consume(paths, filename);
307 if (r < 0)
308 return log_oom();
309 /* We will still use filename below. This is safe because we know the set
310 * holds a reference. */
311 } else
312 _filename_free = filename; /* Make sure we free the filename. */
313
890befcf 314 if (!valid_unit_name)
e8630e69
ZJS
315 continue;
316 assert_se(suffix = strrchr(de->d_name, '.'));
317
318 /* search_path is ordered by priority (highest first). If the name is already mapped
319 * to something (incl. itself), it means that we have already seen it, and we should
320 * ignore it here. */
321 if (hashmap_contains(ids, de->d_name))
322 continue;
323
28e68bb2 324 dirent_ensure_type(d, de);
e8630e69
ZJS
325 if (de->d_type == DT_LNK) {
326 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
327 * limits the number of hops should be used to access the map. */
328
b8239b9c 329 _cleanup_free_ char *target = NULL;
e8630e69
ZJS
330
331 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
332 if (r < 0) {
333 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
334 *dir, de->d_name);
335 continue;
336 }
337
b8239b9c
ZJS
338 const bool is_abs = path_is_absolute(target);
339 if (lp->root_dir || !is_abs) {
340 char *target_abs = path_join(is_abs ? lp->root_dir : *dir, target);
e8630e69
ZJS
341 if (!target_abs)
342 return log_oom();
343
344 free_and_replace(target, target_abs);
345 }
346
347 /* Get rid of "." and ".." components in target path */
a5648b80 348 r = chase_symlinks(target, lp->root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
e8630e69
ZJS
349 if (r < 0) {
350 log_warning_errno(r, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
351 filename, target);
352 continue;
353 }
354
355 /* Check if the symlink goes outside of our search path.
356 * If yes, it's a linked unit file or mask, and we don't care about the target name.
3aa57658 357 * Let's just store the link source directly.
e8630e69
ZJS
358 * If not, let's verify that it's a good symlink. */
359 char *tail = path_startswith_strv(simplified, lp->search_path);
3aa57658
ZJS
360 if (!tail) {
361 log_debug("%s: linked unit file: %s → %s",
362 __func__, filename, simplified);
363
364 dst = filename;
365 } else {
366
e8630e69
ZJS
367 bool self_alias;
368
369 dst = basename(simplified);
370 self_alias = streq(dst, de->d_name);
371
372 if (is_path(tail))
373 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
374 "Suspicious symlink %s→%s, treating as alias.",
375 filename, simplified);
376
377 r = unit_validate_alias_symlink_and_warn(filename, simplified);
378 if (r < 0)
379 continue;
380
381 if (self_alias) {
382 /* A self-alias that has no effect */
383 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
384 __func__, *dir, de->d_name, dst);
385 continue;
386 }
387
388 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
e8630e69
ZJS
389 }
390
391 } else {
392 dst = filename;
393 log_debug("%s: normal unit file: %s", __func__, dst);
394 }
395
396 r = hashmap_put_strdup(&ids, de->d_name, dst);
397 if (r < 0)
398 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
399 de->d_name, dst);
400 }
401 }
402
403 /* Let's also put the names in the reverse db. */
e8630e69 404 const char *dummy, *src;
90e74a66 405 HASHMAP_FOREACH_KEY(dummy, src, ids) {
e8630e69
ZJS
406 const char *dst;
407
408 r = unit_ids_map_get(ids, src, &dst);
409 if (r < 0)
410 continue;
411
412 if (null_or_empty_path(dst) != 0)
413 continue;
414
415 /* Do not treat instance symlinks that point to the template as aliases */
416 if (unit_name_is_valid(basename(dst), UNIT_NAME_TEMPLATE) &&
417 unit_name_is_valid(src, UNIT_NAME_INSTANCE))
418 continue;
419
420 r = string_strv_hashmap_put(&names, basename(dst), src);
421 if (r < 0)
422 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
423 basename(dst), src);
424 }
425
c2911d48
ZJS
426 if (cache_timestamp_hash)
427 *cache_timestamp_hash = timestamp_hash;
3fb2326f
ZJS
428
429 hashmap_free_and_replace(*unit_ids_map, ids);
430 hashmap_free_and_replace(*unit_names_map, names);
431 if (path_cache)
432 set_free_and_replace(*path_cache, paths);
e8630e69 433
91e0ee5f 434 return 1;
e8630e69
ZJS
435}
436
437int unit_file_find_fragment(
438 Hashmap *unit_ids_map,
439 Hashmap *unit_name_map,
440 const char *unit_name,
441 const char **ret_fragment_path,
442 Set **ret_names) {
443
444 const char *fragment = NULL;
445 _cleanup_free_ char *template = NULL, *instance = NULL;
446 _cleanup_set_free_free_ Set *names = NULL;
447 char **t, **nnn;
448 int r, name_type;
449
450 /* Finds a fragment path, and returns the set of names:
451 * if we have …/foo.service and …/foo-alias.service→foo.service,
452 * and …/foo@.service and …/foo-alias@.service→foo@.service,
453 * and …/foo@inst.service,
454 * this should return:
455 * foo.service → …/foo.service, {foo.service, foo-alias.service},
456 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
457 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
458 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
459 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
460 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
461 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
462 */
463
464 name_type = unit_name_to_instance(unit_name, &instance);
465 if (name_type < 0)
466 return name_type;
467
468 names = set_new(&string_hash_ops);
469 if (!names)
470 return -ENOMEM;
471
472 /* The unit always has its own name if it's not a template. */
b208cbe5 473 if (IN_SET(name_type, UNIT_NAME_PLAIN, UNIT_NAME_INSTANCE)) {
be327321 474 r = set_put_strdup(&names, unit_name);
e8630e69
ZJS
475 if (r < 0)
476 return r;
477 }
478
479 /* First try to load fragment under the original name */
480 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
481 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
482 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
483
484 if (fragment) {
485 /* Add any aliases of the original name to the set of names */
486 nnn = hashmap_get(unit_name_map, basename(fragment));
487 STRV_FOREACH(t, nnn) {
b208cbe5 488 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*t, UNIT_NAME_TEMPLATE)) {
e8630e69
ZJS
489 char *inst;
490
491 r = unit_name_replace_instance(*t, instance, &inst);
492 if (r < 0)
b208cbe5 493 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", *t, instance);
e8630e69
ZJS
494
495 if (!streq(unit_name, inst))
496 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
497
498 log_info("%s: %s+%s → %s", __func__, *t, instance, inst);
499 r = set_consume(names, inst);
500 } else {
501 if (!streq(unit_name, *t))
502 log_debug("%s: %s has alias %s", __func__, unit_name, *t);
503
be327321 504 r = set_put_strdup(&names, *t);
e8630e69
ZJS
505 }
506 if (r < 0)
507 return r;
508 }
509 }
510
511 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
512 /* Look for a fragment under the template name */
513
514 r = unit_name_template(unit_name, &template);
515 if (r < 0)
98fac96c 516 return log_debug_errno(r, "Failed to determine template name: %m");
e8630e69
ZJS
517
518 r = unit_ids_map_get(unit_ids_map, template, &fragment);
519 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
771f8aef 520 return log_debug_errno(r, "Cannot load template %s: %m", template);
e8630e69
ZJS
521
522 if (fragment) {
523 /* Add any aliases of the original name to the set of names */
524 nnn = hashmap_get(unit_name_map, basename(fragment));
525 STRV_FOREACH(t, nnn) {
526 _cleanup_free_ char *inst = NULL;
527 const char *inst_fragment = NULL;
528
529 r = unit_name_replace_instance(*t, instance, &inst);
530 if (r < 0)
531 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", template, instance);
532
533 /* Exclude any aliases that point in some other direction. */
534 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
535 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
536 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
537
538 if (inst_fragment &&
539 !streq(basename(inst_fragment), basename(fragment))) {
540 log_debug("Instance %s has fragment %s and is not an alias of %s.",
541 inst, inst_fragment, unit_name);
542 continue;
543 }
544
545 if (!streq(unit_name, inst))
73fdd479 546 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
e8630e69
ZJS
547 r = set_consume(names, TAKE_PTR(inst));
548 if (r < 0)
549 return r;
550 }
551 }
552 }
553
554 *ret_fragment_path = fragment;
555 *ret_names = TAKE_PTR(names);
556
557 // FIXME: if instance, consider any unit names with different template name
558 return 0;
559}
da33cba0
ZJS
560
561static const char * const rlmap[] = {
562 "emergency", SPECIAL_EMERGENCY_TARGET,
563 "-b", SPECIAL_EMERGENCY_TARGET,
564 "rescue", SPECIAL_RESCUE_TARGET,
565 "single", SPECIAL_RESCUE_TARGET,
566 "-s", SPECIAL_RESCUE_TARGET,
567 "s", SPECIAL_RESCUE_TARGET,
568 "S", SPECIAL_RESCUE_TARGET,
569 "1", SPECIAL_RESCUE_TARGET,
570 "2", SPECIAL_MULTI_USER_TARGET,
571 "3", SPECIAL_MULTI_USER_TARGET,
572 "4", SPECIAL_MULTI_USER_TARGET,
573 "5", SPECIAL_GRAPHICAL_TARGET,
574 NULL
575};
576
577static const char * const rlmap_initrd[] = {
578 "emergency", SPECIAL_EMERGENCY_TARGET,
579 "rescue", SPECIAL_RESCUE_TARGET,
580 NULL
581};
582
583const char* runlevel_to_target(const char *word) {
584 const char * const *rlmap_ptr;
da33cba0
ZJS
585
586 if (!word)
587 return NULL;
588
589 if (in_initrd()) {
590 word = startswith(word, "rd.");
591 if (!word)
592 return NULL;
593 }
594
595 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
596
fe96c0f8 597 for (size_t i = 0; rlmap_ptr[i]; i += 2)
da33cba0
ZJS
598 if (streq(word, rlmap_ptr[i]))
599 return rlmap_ptr[i+1];
600
601 return NULL;
602}