1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
5 #include "chase-symlinks.h"
6 #include "dirent-util.h"
10 #include "path-lookup.h"
13 #include "stat-util.h"
14 #include "string-util.h"
16 #include "unit-file.h"
18 bool unit_type_may_alias(UnitType type
) {
28 bool unit_type_may_template(UnitType type
) {
37 int unit_symlink_name_compatible(const char *symlink
, const char *target
, bool instance_propagation
) {
38 _cleanup_free_
char *template = NULL
;
39 int r
, un_type1
, un_type2
;
41 un_type1
= unit_name_classify(symlink
);
43 /* The straightforward case: the symlink name matches the target and we have a valid unit */
44 if (streq(symlink
, target
) &&
45 (un_type1
& (UNIT_NAME_PLAIN
| UNIT_NAME_INSTANCE
)))
48 r
= unit_name_template(symlink
, &template);
50 return 0; /* Not a template */
54 un_type2
= unit_name_classify(target
);
56 /* An instance name points to a target that is just the template name */
57 if (un_type1
== UNIT_NAME_INSTANCE
&&
58 un_type2
== UNIT_NAME_TEMPLATE
&&
59 streq(template, target
))
62 /* foo@.target.requires/bar@.service: instance will be propagated */
63 if (instance_propagation
&&
64 un_type1
== UNIT_NAME_TEMPLATE
&&
65 un_type2
== UNIT_NAME_TEMPLATE
&&
66 streq(template, target
))
72 int unit_validate_alias_symlink_and_warn(const char *filename
, const char *target
) {
73 const char *src
, *dst
;
74 _cleanup_free_
char *src_instance
= NULL
, *dst_instance
= NULL
;
75 UnitType src_unit_type
, dst_unit_type
;
76 UnitNameFlags src_name_type
, dst_name_type
;
78 /* Check if the *alias* symlink is valid. This applies to symlinks like
79 * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
80 * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
83 * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
84 * not allowed to symlink,
85 * -EXDEV if the target filename is not a valid unit name or doesn't match the source.
88 src
= basename(filename
);
89 dst
= basename(target
);
93 src_name_type
= unit_name_to_instance(src
, &src_instance
);
94 if (src_name_type
< 0)
95 return log_notice_errno(src_name_type
,
96 "%s: not a valid unit name \"%s\": %m", filename
, src
);
98 src_unit_type
= unit_name_to_type(src
);
99 assert(src_unit_type
>= 0); /* unit_name_to_instance() checked the suffix already */
101 if (!unit_type_may_alias(src_unit_type
))
102 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL
),
103 "%s: symlinks are not allowed for units of this type, rejecting.",
106 if (src_name_type
!= UNIT_NAME_PLAIN
&&
107 !unit_type_may_template(src_unit_type
))
108 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL
),
109 "%s: templates not allowed for %s units, rejecting.",
110 filename
, unit_type_to_string(src_unit_type
));
114 dst_name_type
= unit_name_to_instance(dst
, &dst_instance
);
115 if (dst_name_type
< 0)
116 return log_notice_errno(dst_name_type
== -EINVAL
? SYNTHETIC_ERRNO(EXDEV
) : dst_name_type
,
117 "%s points to \"%s\" which is not a valid unit name: %m",
120 if (!(dst_name_type
== src_name_type
||
121 (src_name_type
== UNIT_NAME_INSTANCE
&& dst_name_type
== UNIT_NAME_TEMPLATE
)))
122 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
123 "%s: symlink target name type \"%s\" does not match source, rejecting.",
126 if (dst_name_type
== UNIT_NAME_INSTANCE
) {
127 assert(src_instance
);
128 assert(dst_instance
);
129 if (!streq(src_instance
, dst_instance
))
130 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
131 "%s: unit symlink target \"%s\" instance name doesn't match, rejecting.",
135 dst_unit_type
= unit_name_to_type(dst
);
136 if (dst_unit_type
!= src_unit_type
)
137 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
138 "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
146 static int unit_ids_map_get(
147 Hashmap
*unit_ids_map
,
148 const char *unit_name
,
149 const char **ret_fragment_path
) {
151 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
153 * We distinguish the case where unit_name was not found in the hashmap at all, and the case where
154 * some symlink was broken.
156 * If a symlink target points to an instance name, then we also check for the template. */
158 const char *id
= NULL
;
161 for (unsigned n
= 0; n
< FOLLOW_MAX
; n
++) {
162 const char *t
= hashmap_get(unit_ids_map
, id
?: unit_name
);
164 _cleanup_free_
char *template = NULL
;
169 r
= unit_name_template(id
, &template);
171 return -ENXIO
; /* we failed to find the symlink target */
173 return log_error_errno(r
, "Failed to determine template name for %s: %m", id
);
175 t
= hashmap_get(unit_ids_map
, template);
179 /* We successfully switched from instanced name to a template, let's continue */
182 if (path_is_absolute(t
)) {
183 if (ret_fragment_path
)
184 *ret_fragment_path
= t
;
194 static bool lookup_paths_mtime_exclude(const LookupPaths
*lp
, const char *path
) {
195 /* Paths that are under our exclusive control. Users shall not alter those directly. */
197 return streq_ptr(path
, lp
->generator
) ||
198 streq_ptr(path
, lp
->generator_early
) ||
199 streq_ptr(path
, lp
->generator_late
) ||
200 streq_ptr(path
, lp
->transient
) ||
201 streq_ptr(path
, lp
->persistent_control
) ||
202 streq_ptr(path
, lp
->runtime_control
);
205 #define HASH_KEY SD_ID128_MAKE(4e,86,1b,e3,39,b3,40,46,98,5d,b8,11,34,8f,c3,c1)
207 bool lookup_paths_timestamp_hash_same(const LookupPaths
*lp
, uint64_t timestamp_hash
, uint64_t *ret_new
) {
208 struct siphash state
;
210 siphash24_init(&state
, HASH_KEY
.bytes
);
213 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
216 if (lookup_paths_mtime_exclude(lp
, *dir
))
219 /* Determine the latest lookup path modification time */
220 if (stat(*dir
, &st
) < 0) {
224 log_debug_errno(errno
, "Failed to stat %s, ignoring: %m", *dir
);
228 siphash24_compress_usec_t(timespec_load(&st
.st_mtim
), &state
);
231 uint64_t updated
= siphash24_finalize(&state
);
234 if (updated
!= timestamp_hash
)
235 log_debug("Modification times have changed, need to update cache.");
236 return updated
== timestamp_hash
;
239 int unit_file_build_name_map(
240 const LookupPaths
*lp
,
241 uint64_t *cache_timestamp_hash
,
242 Hashmap
**unit_ids_map
,
243 Hashmap
**unit_names_map
,
246 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
247 * all aliases (i.e. the entry for a given key is a list of all names which point to this key). The
248 * key is included in the value iff we saw a file or symlink with that name. In other words, if we
249 * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
250 * the unit itself is not loadable.
252 * At the same, build a cache of paths where to find units. The non-const parameters are for input
253 * and output. Existing contents will be freed before the new contents are stored.
256 _cleanup_hashmap_free_ Hashmap
*ids
= NULL
, *names
= NULL
;
257 _cleanup_set_free_free_ Set
*paths
= NULL
;
258 uint64_t timestamp_hash
;
262 /* Before doing anything, check if the timestamp hash that was passed is still valid.
263 * If yes, do nothing. */
264 if (cache_timestamp_hash
&&
265 lookup_paths_timestamp_hash_same(lp
, *cache_timestamp_hash
, ×tamp_hash
))
268 /* The timestamp hash is now set based on the mtimes from before when we start reading files.
269 * If anything is modified concurrently, we'll consider the cache outdated. */
272 paths
= set_new(&path_hash_ops_free
);
277 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
278 _cleanup_closedir_
DIR *d
= NULL
;
284 log_warning_errno(errno
, "Failed to open \"%s\", ignoring: %m", *dir
);
288 FOREACH_DIRENT_ALL(de
, d
, log_warning_errno(errno
, "Failed to read \"%s\", ignoring: %m", *dir
)) {
289 _unused_ _cleanup_free_
char *_filename_free
= NULL
;
290 _cleanup_free_
char *simplified
= NULL
;
291 const char *dst
= NULL
;
294 /* We only care about valid units and dirs with certain suffixes, let's ignore the
297 if (IN_SET(de
->d_type
, DT_REG
, DT_LNK
)) {
299 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
302 /* Accept a regular file or symlink whose name is a valid unit file name. */
304 } else if (de
->d_type
== DT_DIR
) {
305 bool valid_dir_name
= false;
308 /* Also accept a directory whose name is a valid unit file name ending in
309 * .wants/, .requires/ or .d/ */
311 if (!paths
) /* Skip directories early unless path_cache is requested */
314 FOREACH_STRING(suffix
, ".wants", ".requires", ".d") {
315 _cleanup_free_
char *chopped
= NULL
;
318 e
= endswith(de
->d_name
, suffix
);
322 chopped
= strndup(de
->d_name
, e
- de
->d_name
);
326 if (unit_name_is_valid(chopped
, UNIT_NAME_ANY
) ||
327 unit_type_from_string(chopped
) >= 0) {
328 valid_dir_name
= true;
338 filename
= path_join(*dir
, de
->d_name
);
343 r
= set_put(paths
, filename
);
347 _filename_free
= filename
; /* Make sure we free the filename. */
349 _filename_free
= filename
; /* Make sure we free the filename. */
351 if (!IN_SET(de
->d_type
, DT_REG
, DT_LNK
))
354 /* search_path is ordered by priority (highest first). If the name is already mapped
355 * to something (incl. itself), it means that we have already seen it, and we should
357 if (hashmap_contains(ids
, de
->d_name
))
360 if (de
->d_type
== DT_LNK
) {
361 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
362 * limits the number of hops should be used to access the map. */
364 _cleanup_free_
char *target
= NULL
;
366 r
= readlinkat_malloc(dirfd(d
), de
->d_name
, &target
);
368 log_warning_errno(r
, "Failed to read symlink %s/%s, ignoring: %m",
373 const bool is_abs
= path_is_absolute(target
);
374 if (lp
->root_dir
|| !is_abs
) {
375 char *target_abs
= path_join(is_abs
? lp
->root_dir
: *dir
, target
);
379 free_and_replace(target
, target_abs
);
382 /* Get rid of "." and ".." components in target path */
383 r
= chase_symlinks(target
, lp
->root_dir
, CHASE_NOFOLLOW
| CHASE_NONEXISTENT
, &simplified
, NULL
);
385 log_warning_errno(r
, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
390 /* Check if the symlink goes outside of our search path.
391 * If yes, it's a linked unit file or mask, and we don't care about the target name.
392 * Let's just store the link source directly.
393 * If not, let's verify that it's a good symlink. */
394 char *tail
= path_startswith_strv(simplified
, lp
->search_path
);
396 log_debug("%s: linked unit file: %s → %s",
397 __func__
, filename
, simplified
);
404 dst
= basename(simplified
);
405 self_alias
= streq(dst
, de
->d_name
);
408 log_full(self_alias
? LOG_DEBUG
: LOG_WARNING
,
409 "Suspicious symlink %s→%s, treating as alias.",
410 filename
, simplified
);
412 r
= unit_validate_alias_symlink_and_warn(filename
, simplified
);
417 /* A self-alias that has no effect */
418 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
419 __func__
, *dir
, de
->d_name
, dst
);
423 log_debug("%s: alias: %s/%s → %s", __func__
, *dir
, de
->d_name
, dst
);
428 log_debug("%s: normal unit file: %s", __func__
, dst
);
431 r
= hashmap_put_strdup(&ids
, de
->d_name
, dst
);
433 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m",
438 /* Let's also put the names in the reverse db. */
439 const char *dummy
, *src
;
440 HASHMAP_FOREACH_KEY(dummy
, src
, ids
) {
441 _cleanup_free_
char *inst
= NULL
, *dst_inst
= NULL
;
444 r
= unit_ids_map_get(ids
, src
, &dst
);
448 if (null_or_empty_path(dst
) != 0)
453 /* If we have an symlink from an instance name to a template name, it is an alias just for
454 * this specific instance, foo@id.service ↔ template@id.service. */
455 if (unit_name_is_valid(dst
, UNIT_NAME_TEMPLATE
)) {
456 UnitNameFlags t
= unit_name_to_instance(src
, &inst
);
458 return log_error_errno(t
, "Failed to extract instance part from %s: %m", src
);
459 if (t
== UNIT_NAME_INSTANCE
) {
460 r
= unit_name_replace_instance(dst
, inst
, &dst_inst
);
462 /* This might happen e.g. if the combined length is too large.
463 * Let's not make too much of a fuss. */
464 log_debug_errno(r
, "Failed to build alias name (%s + %s), ignoring: %m",
473 r
= string_strv_hashmap_put(&names
, dst
, src
);
475 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m", dst
, src
);
478 if (cache_timestamp_hash
)
479 *cache_timestamp_hash
= timestamp_hash
;
481 hashmap_free_and_replace(*unit_ids_map
, ids
);
482 hashmap_free_and_replace(*unit_names_map
, names
);
484 set_free_and_replace(*path_cache
, paths
);
490 const char *unit_name
,
498 r
= set_put_strdup(names
, name
);
501 if (r
> 0 && !streq(unit_name
, name
))
502 log_debug("Unit %s has alias %s.", unit_name
, name
);
506 static int add_names(
507 Hashmap
*unit_ids_map
,
508 Hashmap
*unit_name_map
,
509 const char *unit_name
,
510 const char *fragment_basename
, /* Only set when adding additional names based on fragment path */
511 UnitNameFlags name_type
,
512 const char *instance
,
516 char **aliases
, **alias
;
519 assert(name_type
== UNIT_NAME_PLAIN
|| instance
);
521 /* The unit has its own name if it's not a template. If we're looking at a fragment, the fragment
522 * name (possibly with instance inserted), is also always one of the unit names. */
523 if (name_type
!= UNIT_NAME_TEMPLATE
) {
524 r
= add_name(unit_name
, names
, name
);
529 /* Add any aliases of the name to the set of names.
531 * We don't even need to know which fragment we will use. The unit_name_map should return the same
532 * set of names for any of the aliases. */
533 aliases
= hashmap_get(unit_name_map
, name
);
534 STRV_FOREACH(alias
, aliases
) {
535 if (name_type
== UNIT_NAME_INSTANCE
&& unit_name_is_valid(*alias
, UNIT_NAME_TEMPLATE
)) {
536 _cleanup_free_
char *inst
= NULL
;
537 const char *inst_fragment
= NULL
;
539 r
= unit_name_replace_instance(*alias
, instance
, &inst
);
541 return log_debug_errno(r
, "Cannot build instance name %s + %s: %m",
544 /* Exclude any aliases that point in some other direction.
546 * See https://github.com/systemd/systemd/pull/13119#discussion_r308145418. */
547 r
= unit_ids_map_get(unit_ids_map
, inst
, &inst_fragment
);
548 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
549 return log_debug_errno(r
, "Cannot find instance fragment %s: %m", inst
);
552 !streq(basename(inst_fragment
), fragment_basename
)) {
553 log_debug("Instance %s has fragment %s and is not an alias of %s.",
554 inst
, inst_fragment
, unit_name
);
558 r
= set_consume(*names
, TAKE_PTR(inst
));
560 log_debug("Unit %s has alias %s.", unit_name
, inst
);
562 r
= add_name(unit_name
, names
, *alias
);
571 int unit_file_find_fragment(
572 Hashmap
*unit_ids_map
,
573 Hashmap
*unit_name_map
,
574 const char *unit_name
,
575 const char **ret_fragment_path
,
578 const char *fragment
= NULL
;
579 _cleanup_free_
char *template = NULL
, *instance
= NULL
;
580 _cleanup_set_free_ Set
*names
= NULL
;
583 /* Finds a fragment path, and returns the set of names:
584 * if we have …/foo.service and …/foo-alias.service→foo.service,
585 * and …/foo@.service and …/foo-alias@.service→foo@.service,
586 * and …/foo@inst.service,
587 * this should return:
588 * foo.service → …/foo.service, {foo.service, foo-alias.service},
589 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
590 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
591 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
592 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
593 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
594 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
597 UnitNameFlags name_type
= unit_name_to_instance(unit_name
, &instance
);
601 r
= add_names(unit_ids_map
, unit_name_map
, unit_name
, NULL
, name_type
, instance
, &names
, unit_name
);
605 /* First try to load fragment under the original name */
606 r
= unit_ids_map_get(unit_ids_map
, unit_name
, &fragment
);
607 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
608 return log_debug_errno(r
, "Cannot load unit %s: %m", unit_name
);
610 if (!fragment
&& name_type
== UNIT_NAME_INSTANCE
) {
611 /* Look for a fragment under the template name */
613 r
= unit_name_template(unit_name
, &template);
615 return log_debug_errno(r
, "Failed to determine template name: %m");
617 r
= unit_ids_map_get(unit_ids_map
, template, &fragment
);
618 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
619 return log_debug_errno(r
, "Cannot load template %s: %m", template);
623 const char *fragment_basename
= basename(fragment
);
625 if (!streq(fragment_basename
, unit_name
)) {
626 /* Add names based on the fragment name to the set of names */
627 r
= add_names(unit_ids_map
, unit_name_map
, unit_name
, fragment_basename
, name_type
, instance
, &names
, fragment_basename
);
633 *ret_fragment_path
= fragment
;
634 *ret_names
= TAKE_PTR(names
);
639 static const char * const rlmap
[] = {
640 "emergency", SPECIAL_EMERGENCY_TARGET
,
641 "-b", SPECIAL_EMERGENCY_TARGET
,
642 "rescue", SPECIAL_RESCUE_TARGET
,
643 "single", SPECIAL_RESCUE_TARGET
,
644 "-s", SPECIAL_RESCUE_TARGET
,
645 "s", SPECIAL_RESCUE_TARGET
,
646 "S", SPECIAL_RESCUE_TARGET
,
647 "1", SPECIAL_RESCUE_TARGET
,
648 "2", SPECIAL_MULTI_USER_TARGET
,
649 "3", SPECIAL_MULTI_USER_TARGET
,
650 "4", SPECIAL_MULTI_USER_TARGET
,
651 "5", SPECIAL_GRAPHICAL_TARGET
,
655 static const char * const rlmap_initrd
[] = {
656 "emergency", SPECIAL_EMERGENCY_TARGET
,
657 "rescue", SPECIAL_RESCUE_TARGET
,
661 const char* runlevel_to_target(const char *word
) {
662 const char * const *rlmap_ptr
;
668 word
= startswith(word
, "rd.");
673 rlmap_ptr
= in_initrd() ? rlmap_initrd
: rlmap
;
675 for (size_t i
= 0; rlmap_ptr
[i
]; i
+= 2)
676 if (streq(word
, rlmap_ptr
[i
]))
677 return rlmap_ptr
[i
+1];