1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #include "dirent-util.h"
7 #include "path-lookup.h"
10 #include "stat-util.h"
11 #include "string-util.h"
13 #include "unit-file.h"
15 bool unit_type_may_alias(UnitType type
) {
25 bool unit_type_may_template(UnitType type
) {
34 int unit_symlink_name_compatible(const char *symlink
, const char *target
, bool instance_propagation
) {
35 _cleanup_free_
char *template = NULL
;
36 int r
, un_type1
, un_type2
;
38 un_type1
= unit_name_classify(symlink
);
40 /* The straightforward case: the symlink name matches the target and we have a valid unit */
41 if (streq(symlink
, target
) &&
42 (un_type1
& (UNIT_NAME_PLAIN
| UNIT_NAME_INSTANCE
)))
45 r
= unit_name_template(symlink
, &template);
47 return 0; /* Not a template */
51 un_type2
= unit_name_classify(target
);
53 /* An instance name points to a target that is just the template name */
54 if (un_type1
== UNIT_NAME_INSTANCE
&&
55 un_type2
== UNIT_NAME_TEMPLATE
&&
56 streq(template, target
))
59 /* foo@.target.requires/bar@.service: instance will be propagated */
60 if (instance_propagation
&&
61 un_type1
== UNIT_NAME_TEMPLATE
&&
62 un_type2
== UNIT_NAME_TEMPLATE
&&
63 streq(template, target
))
69 int unit_validate_alias_symlink_and_warn(const char *filename
, const char *target
) {
70 const char *src
, *dst
;
71 _cleanup_free_
char *src_instance
= NULL
, *dst_instance
= NULL
;
72 UnitType src_unit_type
, dst_unit_type
;
73 int src_name_type
, dst_name_type
;
75 /* Check if the *alias* symlink is valid. This applies to symlinks like
76 * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
77 * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
80 * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
81 * not allowed to symlink,
82 * -EXDEV if the target filename is not a valid unit name or doesn't match the source.
85 src
= basename(filename
);
86 dst
= basename(target
);
90 src_name_type
= unit_name_to_instance(src
, &src_instance
);
91 if (src_name_type
< 0)
92 return log_notice_errno(src_name_type
,
93 "%s: not a valid unit name \"%s\": %m", filename
, src
);
95 src_unit_type
= unit_name_to_type(src
);
96 assert(src_unit_type
>= 0); /* unit_name_to_instance() checked the suffix already */
98 if (!unit_type_may_alias(src_unit_type
))
99 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL
),
100 "%s: symlinks are not allowed for units of this type, rejecting.",
103 if (src_name_type
!= UNIT_NAME_PLAIN
&&
104 !unit_type_may_template(src_unit_type
))
105 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL
),
106 "%s: templates not allowed for %s units, rejecting.",
107 filename
, unit_type_to_string(src_unit_type
));
111 dst_name_type
= unit_name_to_instance(dst
, &dst_instance
);
112 if (dst_name_type
< 0)
113 return log_notice_errno(dst_name_type
== -EINVAL
? SYNTHETIC_ERRNO(EXDEV
) : dst_name_type
,
114 "%s points to \"%s\" which is not a valid unit name: %m",
117 if (!(dst_name_type
== src_name_type
||
118 (src_name_type
== UNIT_NAME_INSTANCE
&& dst_name_type
== UNIT_NAME_TEMPLATE
)))
119 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
120 "%s: symlink target name type \"%s\" does not match source, rejecting.",
123 if (dst_name_type
== UNIT_NAME_INSTANCE
) {
124 assert(src_instance
);
125 assert(dst_instance
);
126 if (!streq(src_instance
, dst_instance
))
127 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
128 "%s: unit symlink target \"%s\" instance name doesn't match, rejecting.",
132 dst_unit_type
= unit_name_to_type(dst
);
133 if (dst_unit_type
!= src_unit_type
)
134 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV
),
135 "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
143 static int unit_ids_map_get(
144 Hashmap
*unit_ids_map
,
145 const char *unit_name
,
146 const char **ret_fragment_path
) {
148 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
150 * We distinguish the case where unit_name was not found in the hashmap at all, and the case where
151 * some symlink was broken.
153 * If a symlink target points to an instance name, then we also check for the template. */
155 const char *id
= NULL
;
158 for (unsigned n
= 0; n
< FOLLOW_MAX
; n
++) {
159 const char *t
= hashmap_get(unit_ids_map
, id
?: unit_name
);
161 _cleanup_free_
char *template = NULL
;
166 r
= unit_name_template(id
, &template);
168 return -ENXIO
; /* we failed to find the symlink target */
170 return log_error_errno(r
, "Failed to determine template name for %s: %m", id
);
172 t
= hashmap_get(unit_ids_map
, template);
176 /* We successfully switched from instanced name to a template, let's continue */
179 if (path_is_absolute(t
)) {
180 if (ret_fragment_path
)
181 *ret_fragment_path
= t
;
191 static bool lookup_paths_mtime_exclude(const LookupPaths
*lp
, const char *path
) {
192 /* Paths that are under our exclusive control. Users shall not alter those directly. */
194 return streq_ptr(path
, lp
->generator
) ||
195 streq_ptr(path
, lp
->generator_early
) ||
196 streq_ptr(path
, lp
->generator_late
) ||
197 streq_ptr(path
, lp
->transient
) ||
198 streq_ptr(path
, lp
->persistent_control
) ||
199 streq_ptr(path
, lp
->runtime_control
);
202 static bool lookup_paths_mtime_good(const LookupPaths
*lp
, usec_t mtime
) {
205 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
208 if (lookup_paths_mtime_exclude(lp
, *dir
))
211 /* Determine the latest lookup path modification time */
212 if (stat(*dir
, &st
) < 0) {
216 log_debug_errno(errno
, "Failed to stat %s, ignoring: %m", *dir
);
220 if (timespec_load(&st
.st_mtim
) > mtime
) {
221 log_debug_errno(errno
, "Unit dir %s has changed, need to update cache.", *dir
);
229 int unit_file_build_name_map(
230 const LookupPaths
*lp
,
232 Hashmap
**ret_unit_ids_map
,
233 Hashmap
**ret_unit_names_map
,
234 Set
**ret_path_cache
) {
236 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
237 * all aliases (i.e. the entry for a given key is a a list of all names which point to this key). The
238 * key is included in the value iff we saw a file or symlink with that name. In other words, if we
239 * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
240 * the unit itself is not loadable.
242 * At the same, build a cache of paths where to find units.
245 _cleanup_hashmap_free_ Hashmap
*ids
= NULL
, *names
= NULL
;
246 _cleanup_set_free_free_ Set
*paths
= NULL
;
251 /* Before doing anything, check if the mtime that was passed is still valid. If
252 * yes, do nothing. If *cache_time == 0, always build the cache. */
253 if (cache_mtime
&& *cache_mtime
> 0 && lookup_paths_mtime_good(lp
, *cache_mtime
))
256 if (ret_path_cache
) {
257 paths
= set_new(&path_hash_ops
);
262 STRV_FOREACH(dir
, (char**) lp
->search_path
) {
264 _cleanup_closedir_
DIR *d
= NULL
;
270 log_warning_errno(errno
, "Failed to open \"%s\", ignoring: %m", *dir
);
274 /* Determine the latest lookup path modification time */
275 if (fstat(dirfd(d
), &st
) < 0)
276 return log_error_errno(errno
, "Failed to fstat %s: %m", *dir
);
278 if (!lookup_paths_mtime_exclude(lp
, *dir
))
279 mtime
= MAX(mtime
, timespec_load(&st
.st_mtim
));
281 FOREACH_DIRENT_ALL(de
, d
, log_warning_errno(errno
, "Failed to read \"%s\", ignoring: %m", *dir
)) {
283 _cleanup_free_
char *_filename_free
= NULL
, *simplified
= NULL
;
284 const char *suffix
, *dst
= NULL
;
285 bool valid_unit_name
;
287 valid_unit_name
= unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
);
289 /* We only care about valid units and dirs with certain suffixes, let's ignore the
291 if (!valid_unit_name
&&
292 !ENDSWITH_SET(de
->d_name
, ".wants", ".requires", ".d"))
295 filename
= path_join(*dir
, de
->d_name
);
299 if (ret_path_cache
) {
300 r
= set_consume(paths
, filename
);
303 /* We will still use filename below. This is safe because we know the set
304 * holds a reference. */
306 _filename_free
= filename
; /* Make sure we free the filename. */
308 if (!valid_unit_name
)
310 assert_se(suffix
= strrchr(de
->d_name
, '.'));
312 /* search_path is ordered by priority (highest first). If the name is already mapped
313 * to something (incl. itself), it means that we have already seen it, and we should
315 if (hashmap_contains(ids
, de
->d_name
))
318 dirent_ensure_type(d
, de
);
319 if (de
->d_type
== DT_LNK
) {
320 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
321 * limits the number of hops should be used to access the map. */
323 _cleanup_free_
char *target
= NULL
;
325 r
= readlinkat_malloc(dirfd(d
), de
->d_name
, &target
);
327 log_warning_errno(r
, "Failed to read symlink %s/%s, ignoring: %m",
332 const bool is_abs
= path_is_absolute(target
);
333 if (lp
->root_dir
|| !is_abs
) {
334 char *target_abs
= path_join(is_abs
? lp
->root_dir
: *dir
, target
);
338 free_and_replace(target
, target_abs
);
341 /* Get rid of "." and ".." components in target path */
342 r
= chase_symlinks(target
, lp
->root_dir
, CHASE_NOFOLLOW
| CHASE_NONEXISTENT
, &simplified
, NULL
);
344 log_warning_errno(r
, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
349 /* Check if the symlink goes outside of our search path.
350 * If yes, it's a linked unit file or mask, and we don't care about the target name.
351 * Let's just store the link destination directly.
352 * If not, let's verify that it's a good symlink. */
353 char *tail
= path_startswith_strv(simplified
, lp
->search_path
);
357 dst
= basename(simplified
);
358 self_alias
= streq(dst
, de
->d_name
);
361 log_full(self_alias
? LOG_DEBUG
: LOG_WARNING
,
362 "Suspicious symlink %s→%s, treating as alias.",
363 filename
, simplified
);
365 r
= unit_validate_alias_symlink_and_warn(filename
, simplified
);
370 /* A self-alias that has no effect */
371 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
372 __func__
, *dir
, de
->d_name
, dst
);
376 log_debug("%s: alias: %s/%s → %s", __func__
, *dir
, de
->d_name
, dst
);
380 log_debug("%s: linked unit file: %s/%s → %s", __func__
, *dir
, de
->d_name
, dst
);
385 log_debug("%s: normal unit file: %s", __func__
, dst
);
388 r
= hashmap_put_strdup(&ids
, de
->d_name
, dst
);
390 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m",
395 /* Let's also put the names in the reverse db. */
397 const char *dummy
, *src
;
398 HASHMAP_FOREACH_KEY(dummy
, src
, ids
, it
) {
401 r
= unit_ids_map_get(ids
, src
, &dst
);
405 if (null_or_empty_path(dst
) != 0)
408 /* Do not treat instance symlinks that point to the template as aliases */
409 if (unit_name_is_valid(basename(dst
), UNIT_NAME_TEMPLATE
) &&
410 unit_name_is_valid(src
, UNIT_NAME_INSTANCE
))
413 r
= string_strv_hashmap_put(&names
, basename(dst
), src
);
415 return log_warning_errno(r
, "Failed to add entry to hashmap (%s→%s): %m",
420 *cache_mtime
= mtime
;
421 *ret_unit_ids_map
= TAKE_PTR(ids
);
422 *ret_unit_names_map
= TAKE_PTR(names
);
424 *ret_path_cache
= TAKE_PTR(paths
);
429 int unit_file_find_fragment(
430 Hashmap
*unit_ids_map
,
431 Hashmap
*unit_name_map
,
432 const char *unit_name
,
433 const char **ret_fragment_path
,
436 const char *fragment
= NULL
;
437 _cleanup_free_
char *template = NULL
, *instance
= NULL
;
438 _cleanup_set_free_free_ Set
*names
= NULL
;
442 /* Finds a fragment path, and returns the set of names:
443 * if we have …/foo.service and …/foo-alias.service→foo.service,
444 * and …/foo@.service and …/foo-alias@.service→foo@.service,
445 * and …/foo@inst.service,
446 * this should return:
447 * foo.service → …/foo.service, {foo.service, foo-alias.service},
448 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
449 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
450 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
451 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
452 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
453 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
456 name_type
= unit_name_to_instance(unit_name
, &instance
);
460 names
= set_new(&string_hash_ops
);
464 /* The unit always has its own name if it's not a template. */
465 if (IN_SET(name_type
, UNIT_NAME_PLAIN
, UNIT_NAME_INSTANCE
)) {
466 r
= set_put_strdup(&names
, unit_name
);
471 /* First try to load fragment under the original name */
472 r
= unit_ids_map_get(unit_ids_map
, unit_name
, &fragment
);
473 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
474 return log_debug_errno(r
, "Cannot load unit %s: %m", unit_name
);
477 /* Add any aliases of the original name to the set of names */
478 nnn
= hashmap_get(unit_name_map
, basename(fragment
));
479 STRV_FOREACH(t
, nnn
) {
480 if (name_type
== UNIT_NAME_INSTANCE
&& unit_name_is_valid(*t
, UNIT_NAME_TEMPLATE
)) {
483 r
= unit_name_replace_instance(*t
, instance
, &inst
);
485 return log_debug_errno(r
, "Cannot build instance name %s+%s: %m", *t
, instance
);
487 if (!streq(unit_name
, inst
))
488 log_debug("%s: %s has alias %s", __func__
, unit_name
, inst
);
490 log_info("%s: %s+%s → %s", __func__
, *t
, instance
, inst
);
491 r
= set_consume(names
, inst
);
493 if (!streq(unit_name
, *t
))
494 log_debug("%s: %s has alias %s", __func__
, unit_name
, *t
);
496 r
= set_put_strdup(&names
, *t
);
503 if (!fragment
&& name_type
== UNIT_NAME_INSTANCE
) {
504 /* Look for a fragment under the template name */
506 r
= unit_name_template(unit_name
, &template);
508 return log_error_errno(r
, "Failed to determine template name: %m");
510 r
= unit_ids_map_get(unit_ids_map
, template, &fragment
);
511 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
512 return log_debug_errno(r
, "Cannot load template %s: %m", template);
515 /* Add any aliases of the original name to the set of names */
516 nnn
= hashmap_get(unit_name_map
, basename(fragment
));
517 STRV_FOREACH(t
, nnn
) {
518 _cleanup_free_
char *inst
= NULL
;
519 const char *inst_fragment
= NULL
;
521 r
= unit_name_replace_instance(*t
, instance
, &inst
);
523 return log_debug_errno(r
, "Cannot build instance name %s+%s: %m", template, instance
);
525 /* Exclude any aliases that point in some other direction. */
526 r
= unit_ids_map_get(unit_ids_map
, inst
, &inst_fragment
);
527 if (r
< 0 && !IN_SET(r
, -ENOENT
, -ENXIO
))
528 return log_debug_errno(r
, "Cannot find instance fragment %s: %m", inst
);
531 !streq(basename(inst_fragment
), basename(fragment
))) {
532 log_debug("Instance %s has fragment %s and is not an alias of %s.",
533 inst
, inst_fragment
, unit_name
);
537 if (!streq(unit_name
, inst
))
538 log_debug("%s: %s has alias %s", __func__
, unit_name
, inst
);
539 r
= set_consume(names
, TAKE_PTR(inst
));
546 *ret_fragment_path
= fragment
;
547 *ret_names
= TAKE_PTR(names
);
549 // FIXME: if instance, consider any unit names with different template name
553 static const char * const rlmap
[] = {
554 "emergency", SPECIAL_EMERGENCY_TARGET
,
555 "-b", SPECIAL_EMERGENCY_TARGET
,
556 "rescue", SPECIAL_RESCUE_TARGET
,
557 "single", SPECIAL_RESCUE_TARGET
,
558 "-s", SPECIAL_RESCUE_TARGET
,
559 "s", SPECIAL_RESCUE_TARGET
,
560 "S", SPECIAL_RESCUE_TARGET
,
561 "1", SPECIAL_RESCUE_TARGET
,
562 "2", SPECIAL_MULTI_USER_TARGET
,
563 "3", SPECIAL_MULTI_USER_TARGET
,
564 "4", SPECIAL_MULTI_USER_TARGET
,
565 "5", SPECIAL_GRAPHICAL_TARGET
,
569 static const char * const rlmap_initrd
[] = {
570 "emergency", SPECIAL_EMERGENCY_TARGET
,
571 "rescue", SPECIAL_RESCUE_TARGET
,
575 const char* runlevel_to_target(const char *word
) {
576 const char * const *rlmap_ptr
;
583 word
= startswith(word
, "rd.");
588 rlmap_ptr
= in_initrd() ? rlmap_initrd
: rlmap
;
590 for (i
= 0; rlmap_ptr
[i
]; i
+= 2)
591 if (streq(word
, rlmap_ptr
[i
]))
592 return rlmap_ptr
[i
+1];