1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "dirent-util.h"
9 #include "path-lookup.h"
12 #include "stat-util.h"
13 #include "string-util.h"
15 #include "unit-file.h"
17 bool unit_type_may_alias(UnitType type
) {
27 bool unit_type_may_template(UnitType type
) {
36 int unit_symlink_name_compatible(const char *symlink
, const char *target
, bool instance_propagation
) {
37 _cleanup_free_
char *template = NULL
;
38 int r
, un_type1
, un_type2
;
40 un_type1
= unit_name_classify(symlink
);
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
)))
47 r
= unit_name_template(symlink
, &template);
49 return 0; /* Not a template */
53 un_type2
= unit_name_classify(target
);
55 /* An instance name points to a target that is just the template name */
56 if (un_type1
== UNIT_NAME_INSTANCE
&&
57 un_type2
== UNIT_NAME_TEMPLATE
&&
58 streq(template, target
))
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
))
71 int 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
;
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
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.
87 src
= basename(filename
);
88 dst
= basename(target
);
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
);
97 src_unit_type
= unit_name_to_type(src
);
98 assert(src_unit_type
>= 0); /* unit_name_to_instance() checked the suffix already */
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.",
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
));
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",
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.",
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.",
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.",
145 static int unit_ids_map_get(
146 Hashmap
*unit_ids_map
,
147 const char *unit_name
,
148 const char **ret_fragment_path
) {
150 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
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.
155 * If a symlink target points to an instance name, then we also check for the template. */
157 const char *id
= NULL
;
160 for (unsigned n
= 0; n
< FOLLOW_MAX
; n
++) {
161 const char *t
= hashmap_get(unit_ids_map
, id
?: unit_name
);
163 _cleanup_free_
char *template = NULL
;
168 r
= unit_name_template(id
, &template);
170 return -ENXIO
; /* we failed to find the symlink target */
172 return log_error_errno(r
, "Failed to determine template name for %s: %m", id
);
174 t
= hashmap_get(unit_ids_map
, template);
178 /* We successfully switched from instanced name to a template, let's continue */
181 if (path_is_absolute(t
)) {
182 if (ret_fragment_path
)
183 *ret_fragment_path
= t
;
193 static 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. */
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
);
204 #define HASH_KEY SD_ID128_MAKE(4e,86,1b,e3,39,b3,40,46,98,5d,b8,11,34,8f,c3,c1)
206 bool lookup_paths_timestamp_hash_same(const LookupPaths
*lp
, uint64_t timestamp_hash
, uint64_t *ret_new
) {
207 struct siphash state
;
209 siphash24_init(&state
, HASH_KEY
.bytes
);
212 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
215 if (lookup_paths_mtime_exclude(lp
, *dir
))
218 /* Determine the latest lookup path modification time */
219 if (stat(*dir
, &st
) < 0) {
223 log_debug_errno(errno
, "Failed to stat %s, ignoring: %m", *dir
);
227 siphash24_compress_usec_t(timespec_load(&st
.st_mtim
), &state
);
230 uint64_t updated
= siphash24_finalize(&state
);
233 if (updated
!= timestamp_hash
)
234 log_debug("Modification times have changed, need to update cache.");
235 return updated
== timestamp_hash
;
238 int unit_file_build_name_map(
239 const LookupPaths
*lp
,
240 uint64_t *cache_timestamp_hash
,
241 Hashmap
**unit_ids_map
,
242 Hashmap
**unit_names_map
,
245 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
246 * all aliases (i.e. the entry for a given key is a a list of all names which point to this key). The
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.
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.
255 _cleanup_hashmap_free_ Hashmap
*ids
= NULL
, *names
= NULL
;
256 _cleanup_set_free_free_ Set
*paths
= NULL
;
257 uint64_t timestamp_hash
;
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
, ×tamp_hash
))
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. */
271 paths
= set_new(&path_hash_ops_free
);
276 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
278 _cleanup_closedir_
DIR *d
= NULL
;
283 log_warning_errno(errno
, "Failed to open \"%s\", ignoring: %m", *dir
);
287 FOREACH_DIRENT_ALL(de
, d
, log_warning_errno(errno
, "Failed to read \"%s\", ignoring: %m", *dir
)) {
289 _cleanup_free_
char *_filename_free
= NULL
, *simplified
= NULL
;
290 const char *suffix
, *dst
= NULL
;
291 bool valid_unit_name
;
293 valid_unit_name
= unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
);
295 /* We only care about valid units and dirs with certain suffixes, let's ignore the
297 if (!valid_unit_name
&&
298 !ENDSWITH_SET(de
->d_name
, ".wants", ".requires", ".d"))
301 filename
= path_join(*dir
, de
->d_name
);
306 r
= set_consume(paths
, filename
);
309 /* We will still use filename below. This is safe because we know the set
310 * holds a reference. */
312 _filename_free
= filename
; /* Make sure we free the filename. */
314 if (!valid_unit_name
)
316 assert_se(suffix
= strrchr(de
->d_name
, '.'));
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
321 if (hashmap_contains(ids
, de
->d_name
))
324 dirent_ensure_type(d
, de
);
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. */
329 _cleanup_free_
char *target
= NULL
;
331 r
= readlinkat_malloc(dirfd(d
), de
->d_name
, &target
);
333 log_warning_errno(r
, "Failed to read symlink %s/%s, ignoring: %m",
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
);
344 free_and_replace(target
, target_abs
);
347 /* Get rid of "." and ".." components in target path */
348 r
= chase_symlinks(target
, lp
->root_dir
, CHASE_NOFOLLOW
| CHASE_NONEXISTENT
, &simplified
, NULL
);
350 log_warning_errno(r
, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
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.
357 * Let's just store the link destination directly.
358 * If not, let's verify that it's a good symlink. */
359 char *tail
= path_startswith_strv(simplified
, lp
->search_path
);
363 dst
= basename(simplified
);
364 self_alias
= streq(dst
, de
->d_name
);
367 log_full(self_alias
? LOG_DEBUG
: LOG_WARNING
,
368 "Suspicious symlink %s→%s, treating as alias.",
369 filename
, simplified
);
371 r
= unit_validate_alias_symlink_and_warn(filename
, simplified
);
376 /* A self-alias that has no effect */
377 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
378 __func__
, *dir
, de
->d_name
, dst
);
382 log_debug("%s: alias: %s/%s → %s", __func__
, *dir
, de
->d_name
, dst
);
386 log_debug("%s: linked unit file: %s/%s → %s", __func__
, *dir
, de
->d_name
, dst
);
391 log_debug("%s: normal unit file: %s", __func__
, dst
);
394 r
= hashmap_put_strdup(&ids
, de
->d_name
, dst
);
396 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m",
401 /* Let's also put the names in the reverse db. */
403 const char *dummy
, *src
;
404 HASHMAP_FOREACH_KEY(dummy
, src
, ids
, it
) {
407 r
= unit_ids_map_get(ids
, src
, &dst
);
411 if (null_or_empty_path(dst
) != 0)
414 /* Do not treat instance symlinks that point to the template as aliases */
415 if (unit_name_is_valid(basename(dst
), UNIT_NAME_TEMPLATE
) &&
416 unit_name_is_valid(src
, UNIT_NAME_INSTANCE
))
419 r
= string_strv_hashmap_put(&names
, basename(dst
), src
);
421 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m",
425 if (cache_timestamp_hash
)
426 *cache_timestamp_hash
= timestamp_hash
;
428 hashmap_free_and_replace(*unit_ids_map
, ids
);
429 hashmap_free_and_replace(*unit_names_map
, names
);
431 set_free_and_replace(*path_cache
, paths
);
436 int unit_file_find_fragment(
437 Hashmap
*unit_ids_map
,
438 Hashmap
*unit_name_map
,
439 const char *unit_name
,
440 const char **ret_fragment_path
,
443 const char *fragment
= NULL
;
444 _cleanup_free_
char *template = NULL
, *instance
= NULL
;
445 _cleanup_set_free_free_ Set
*names
= NULL
;
449 /* Finds a fragment path, and returns the set of names:
450 * if we have …/foo.service and …/foo-alias.service→foo.service,
451 * and …/foo@.service and …/foo-alias@.service→foo@.service,
452 * and …/foo@inst.service,
453 * this should return:
454 * foo.service → …/foo.service, {foo.service, foo-alias.service},
455 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
456 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
457 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
458 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
459 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
460 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
463 name_type
= unit_name_to_instance(unit_name
, &instance
);
467 names
= set_new(&string_hash_ops
);
471 /* The unit always has its own name if it's not a template. */
472 if (IN_SET(name_type
, UNIT_NAME_PLAIN
, UNIT_NAME_INSTANCE
)) {
473 r
= set_put_strdup(&names
, unit_name
);
478 /* First try to load fragment under the original name */
479 r
= unit_ids_map_get(unit_ids_map
, unit_name
, &fragment
);
480 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
481 return log_debug_errno(r
, "Cannot load unit %s: %m", unit_name
);
484 /* Add any aliases of the original name to the set of names */
485 nnn
= hashmap_get(unit_name_map
, basename(fragment
));
486 STRV_FOREACH(t
, nnn
) {
487 if (name_type
== UNIT_NAME_INSTANCE
&& unit_name_is_valid(*t
, UNIT_NAME_TEMPLATE
)) {
490 r
= unit_name_replace_instance(*t
, instance
, &inst
);
492 return log_debug_errno(r
, "Cannot build instance name %s+%s: %m", *t
, instance
);
494 if (!streq(unit_name
, inst
))
495 log_debug("%s: %s has alias %s", __func__
, unit_name
, inst
);
497 log_info("%s: %s+%s → %s", __func__
, *t
, instance
, inst
);
498 r
= set_consume(names
, inst
);
500 if (!streq(unit_name
, *t
))
501 log_debug("%s: %s has alias %s", __func__
, unit_name
, *t
);
503 r
= set_put_strdup(&names
, *t
);
510 if (!fragment
&& name_type
== UNIT_NAME_INSTANCE
) {
511 /* Look for a fragment under the template name */
513 r
= unit_name_template(unit_name
, &template);
515 return log_error_errno(r
, "Failed to determine template name: %m");
517 r
= unit_ids_map_get(unit_ids_map
, template, &fragment
);
518 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
519 return log_debug_errno(r
, "Cannot load template %s: %m", template);
522 /* Add any aliases of the original name to the set of names */
523 nnn
= hashmap_get(unit_name_map
, basename(fragment
));
524 STRV_FOREACH(t
, nnn
) {
525 _cleanup_free_
char *inst
= NULL
;
526 const char *inst_fragment
= NULL
;
528 r
= unit_name_replace_instance(*t
, instance
, &inst
);
530 return log_debug_errno(r
, "Cannot build instance name %s+%s: %m", template, instance
);
532 /* Exclude any aliases that point in some other direction. */
533 r
= unit_ids_map_get(unit_ids_map
, inst
, &inst_fragment
);
534 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
535 return log_debug_errno(r
, "Cannot find instance fragment %s: %m", inst
);
538 !streq(basename(inst_fragment
), basename(fragment
))) {
539 log_debug("Instance %s has fragment %s and is not an alias of %s.",
540 inst
, inst_fragment
, unit_name
);
544 if (!streq(unit_name
, inst
))
545 log_debug("%s: %s has alias %s", __func__
, unit_name
, inst
);
546 r
= set_consume(names
, TAKE_PTR(inst
));
553 *ret_fragment_path
= fragment
;
554 *ret_names
= TAKE_PTR(names
);
556 // FIXME: if instance, consider any unit names with different template name
560 static const char * const rlmap
[] = {
561 "emergency", SPECIAL_EMERGENCY_TARGET
,
562 "-b", SPECIAL_EMERGENCY_TARGET
,
563 "rescue", SPECIAL_RESCUE_TARGET
,
564 "single", SPECIAL_RESCUE_TARGET
,
565 "-s", SPECIAL_RESCUE_TARGET
,
566 "s", SPECIAL_RESCUE_TARGET
,
567 "S", SPECIAL_RESCUE_TARGET
,
568 "1", SPECIAL_RESCUE_TARGET
,
569 "2", SPECIAL_MULTI_USER_TARGET
,
570 "3", SPECIAL_MULTI_USER_TARGET
,
571 "4", SPECIAL_MULTI_USER_TARGET
,
572 "5", SPECIAL_GRAPHICAL_TARGET
,
576 static const char * const rlmap_initrd
[] = {
577 "emergency", SPECIAL_EMERGENCY_TARGET
,
578 "rescue", SPECIAL_RESCUE_TARGET
,
582 const char* runlevel_to_target(const char *word
) {
583 const char * const *rlmap_ptr
;
590 word
= startswith(word
, "rd.");
595 rlmap_ptr
= in_initrd() ? rlmap_initrd
: rlmap
;
597 for (i
= 0; rlmap_ptr
[i
]; i
+= 2)
598 if (streq(word
, rlmap_ptr
[i
]))
599 return rlmap_ptr
[i
+1];