Debian Codegraph @

src/shared/unit-file.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-id128.h"
4
5 #include "alloc-util.h"
6 #include "chase.h"
7 #include "dirent-util.h"
8 #include "fd-util.h"
9 #include "fs-util.h"
10 #include "glyph-util.h"
11 #include "initrd-util.h"
12 #include "log.h"
13 #include "path-lookup.h"
14 #include "set.h"
15 #include "siphash24.h"
16 #include "special.h"
17 #include "stat-util.h"
18 #include "string-util.h"
19 #include "strv.h"
20 #include "time-util.h"
21 #include "unit-file.h"
22 #include "unit-name.h"
23
24 int unit_symlink_name_compatible(const char *symlink, const char *target, bool instance_propagation) {
25 _cleanup_free_ char *template = NULL;
26 int r, un_type1, un_type2;
27
28 un_type1 = unit_name_classify(symlink);
29
30 /* The straightforward case: the symlink name matches the target and we have a valid unit */
31 if (streq(symlink, target) &&
32 (un_type1 & (UNIT_NAME_PLAIN | UNIT_NAME_INSTANCE)))
33 return 1;
34
35 r = unit_name_template(symlink, &template);
36 if (r == -EINVAL)
37 return 0; /* Not a template */
38 if (r < 0)
39 return r;
40
41 un_type2 = unit_name_classify(target);
42
43 /* An instance name points to a target that is just the template name */
44 if (un_type1 == UNIT_NAME_INSTANCE &&
45 un_type2 == UNIT_NAME_TEMPLATE &&
46 streq(template, target))
47 return 1;
48
49 /* [email protected]/[email protected]: instance will be propagated */
50 if (instance_propagation &&
51 un_type1 == UNIT_NAME_TEMPLATE &&
52 un_type2 == UNIT_NAME_TEMPLATE &&
53 streq(template, target))
54 return 1;
55
56 return 0;
57 }
58
59 int unit_validate_alias_symlink_or_warn(int log_level, const char *filename, const char *target) {
60 _cleanup_free_ char *src = NULL, *dst = NULL;
61 _cleanup_free_ char *src_instance = NULL, *dst_instance = NULL;
62 UnitType src_unit_type, dst_unit_type;
63 UnitNameFlags src_name_type, dst_name_type;
64 int r;
65
66 /* Check if the *alias* symlink is valid. This applies to symlinks like
67 * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
68 * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
69 * unit lookup path.
70 *
71 * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
72 * not allowed to symlink,
73 * -EXDEV if the target filename is not a valid unit name or doesn't match the source,
74 * -ELOOP for an alias to self.
75 */
76
77 r = path_extract_filename(filename, &src);
78 if (r < 0)
79 return r;
80
81 r = path_extract_filename(target, &dst);
82 if (r < 0)
83 return r;
84
85 /* src checks */
86
87 src_name_type = unit_name_to_instance(src, &src_instance);
88 if (src_name_type < 0)
89 return log_full_errno(log_level, src_name_type,
90 "%s: not a valid unit name \"%s\": %m", filename, src);
91
92 src_unit_type = unit_name_to_type(src);
93 assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
94
95 if (!unit_type_may_alias(src_unit_type))
96 return log_full_errno(log_level, SYNTHETIC_ERRNO(EINVAL),
97 "%s: symlinks are not allowed for units of this type, rejecting.",
98 filename);
99
100 if (src_name_type != UNIT_NAME_PLAIN &&
101 !unit_type_may_template(src_unit_type))
102 return log_full_errno(log_level, SYNTHETIC_ERRNO(EINVAL),
103 "%s: templates not allowed for %s units, rejecting.",
104 filename, unit_type_to_string(src_unit_type));
105
106 /* dst checks */
107
108 if (streq(src, dst))
109 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
110 "%s: unit self-alias: %s → %s, ignoring.",
111 filename, src, dst);
112
113 dst_name_type = unit_name_to_instance(dst, &dst_instance);
114 if (dst_name_type < 0)
115 return log_full_errno(log_level, 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_full_errno(log_level, 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_full_errno(log_level, 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_full_errno(log_level, SYNTHETIC_ERRNO(EXDEV),
137 "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
138 filename, dst);
139
140 return 0;
141 }
142
143 #define FOLLOW_MAX 8
144
145 static 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
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. */
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
204 #define HASH_KEY SD_ID128_MAKE(4e,86,1b,e3,39,b3,40,46,98,5d,b8,11,34,8f,c3,c1)
205
206 bool lookup_paths_timestamp_hash_same(const LookupPaths *lp, uint64_t timestamp_hash, uint64_t *ret_new) {
207 struct siphash state;
208
209 siphash24_init(&state, HASH_KEY.bytes);
210
211 STRV_FOREACH(dir, lp->search_path) {
212 struct stat st;
213
214 if (lookup_paths_mtime_exclude(lp, *dir))
215 continue;
216
217 /* Determine the latest lookup path modification time */
218 if (stat(*dir, &st) < 0) {
219 if (errno == ENOENT)
220 continue;
221
222 log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
223 continue;
224 }
225
226 siphash24_compress_usec_t(timespec_load(&st.st_mtim), &state);
227 }
228
229 uint64_t updated = siphash24_finalize(&state);
230 if (ret_new)
231 *ret_new = updated;
232 if (updated != timestamp_hash)
233 log_debug("Modification times have changed, need to update cache.");
234 return updated == timestamp_hash;
235 }
236
237 static int directory_name_is_valid(const char *name) {
238
239 /* Accept a directory whose name is a valid unit file name ending in .wants/, .requires/,
240 * .upholds/ or .d/ */
241
242 FOREACH_STRING(suffix, ".wants", ".requires", ".upholds", ".d") {
243 _cleanup_free_ char *chopped = NULL;
244 const char *e;
245
246 e = endswith(name, suffix);
247 if (!e)
248 continue;
249
250 chopped = strndup(name, e - name);
251 if (!chopped)
252 return log_oom();
253
254 if (unit_name_is_valid(chopped, UNIT_NAME_ANY) ||
255 unit_type_from_string(chopped) >= 0)
256 return true;
257 }
258
259 return false;
260 }
261
262 int unit_file_resolve_symlink(
263 const char *root_dir,
264 char **search_path,
265 const char *dir,
266 int dirfd,
267 const char *filename,
268 bool resolve_destination_target,
269 char **ret_destination) {
270
271 _cleanup_free_ char *target = NULL, *simplified = NULL, *dst = NULL, *_dir = NULL, *_filename = NULL;
272 int r;
273
274 /* This can be called with either dir+dirfd valid and filename just a name,
275 * or !dir && dirfd==AT_FDCWD, and filename being a full path.
276 *
277 * If resolve_destination_target is true, an absolute path will be returned.
278 * If not, an absolute path is returned for linked unit files, and a relative
279 * path otherwise.
280 *
281 * Returns an error, false if this is an alias, true if it's a linked unit file. */
282
283 assert(filename);
284 assert(ret_destination);
285 assert(dir || path_is_absolute(filename));
286 assert(dirfd >= 0 || dirfd == AT_FDCWD);
287
288 r = readlinkat_malloc(dirfd, filename, &target);
289 if (r < 0)
290 return log_warning_errno(r, "Failed to read symlink %s%s%s: %m",
291 dir, dir ? "/" : "", filename);
292
293 if (!dir) {
294 r = path_split_prefix_filename(filename, &_dir, &_filename);
295 if (r < 0)
296 return r;
297 if (r == O_DIRECTORY)
298 return log_warning_errno(SYNTHETIC_ERRNO(EISDIR),
299 "Unexpected path to a directory \"%s\", refusing.", filename);
300
301 /* We validate that the path is absolute above, hence dir must be extractable. */
302 dir = ASSERT_PTR(_dir);
303 filename = _filename;
304 }
305
306 bool is_abs = path_is_absolute(target);
307 if (root_dir || !is_abs) {
308 char *target_abs = path_join(is_abs ? root_dir : dir, target);
309 if (!target_abs)
310 return log_oom();
311
312 free_and_replace(target, target_abs);
313 }
314
315 /* Get rid of "." and ".." components in target path */
316 r = chase(target, root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
317 if (r < 0)
318 return log_warning_errno(r, "Failed to resolve symlink %s/%s pointing to %s: %m",
319 dir, filename, target);
320
321 assert(path_is_absolute(simplified));
322
323 /* Check if the symlink remain inside of our search path.
324 * If yes, it is an alias. Verify that it is valid.
325 *
326 * If no, then this is a linked unit file or mask, and we don't care about the target name
327 * when loading units, and we return the link *source* (resolve_destination_target == false);
328 * When this is called for installation purposes, we want the final destination,
329 * so we return the *target*.
330 */
331 const char *tail = path_startswith_strv(simplified, search_path);
332 if (tail) { /* An alias */
333 _cleanup_free_ char *target_name = NULL;
334
335 r = path_extract_filename(simplified, &target_name);
336 if (r < 0)
337 return r;
338
339 r = unit_validate_alias_symlink_or_warn(LOG_NOTICE, filename, simplified);
340 if (r < 0)
341 return r;
342 if (is_path(tail))
343 log_warning("Suspicious symlink %s/%s %s %s, treating as alias.",
344 dir, filename, glyph(GLYPH_ARROW_RIGHT), simplified);
345
346 dst = resolve_destination_target ? TAKE_PTR(simplified) : TAKE_PTR(target_name);
347
348 } else {
349 log_debug("Linked unit file: %s/%s %s %s", dir, filename, glyph(GLYPH_ARROW_RIGHT), simplified);
350
351 if (resolve_destination_target)
352 dst = TAKE_PTR(simplified);
353 else {
354 dst = path_join(dir, filename);
355 if (!dst)
356 return log_oom();
357 }
358 }
359
360 *ret_destination = TAKE_PTR(dst);
361 return !tail; /* true if linked unit file */
362 }
363
364 int unit_file_build_name_map(
365 const LookupPaths *lp,
366 uint64_t *cache_timestamp_hash,
367 Hashmap **unit_ids_map,
368 Hashmap **unit_names_map,
369 Set **path_cache) {
370
371 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
372 * all aliases (i.e. the entry for a given key is a list of all names which point to this key). The
373 * key is included in the value iff we saw a file or symlink with that name. In other words, if we
374 * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
375 * the unit itself is not loadable.
376 *
377 * At the same, build a cache of paths where to find units. The non-const parameters are for input
378 * and output. Existing contents will be freed before the new contents are stored.
379 */
380
381 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
382 _cleanup_set_free_ Set *paths = NULL;
383 _cleanup_strv_free_ char **expanded_search_path = NULL;
384 uint64_t timestamp_hash;
385 int r;
386
387 /* Before doing anything, check if the timestamp hash that was passed is still valid.
388 * If yes, do nothing. */
389 if (cache_timestamp_hash &&
390 lookup_paths_timestamp_hash_same(lp, *cache_timestamp_hash, &timestamp_hash))
391 return 0;
392
393 /* The timestamp hash is now set based on the mtimes from before when we start reading files.
394 * If anything is modified concurrently, we'll consider the cache outdated. */
395
396 if (path_cache) {
397 paths = set_new(&path_hash_ops_free);
398 if (!paths)
399 return log_oom();
400 }
401
402 /* Go over all our search paths, chase their symlinks and store the result in the
403 * expanded_search_path list.
404 *
405 * This is important for cases where any of the unit directories itself are symlinks into other
406 * directories and would therefore cause all of the unit files to be recognized as linked units.
407 *
408 * This is important for distributions such as NixOS where most paths in /etc/ are symlinks to some
409 * other location on the filesystem (e.g. into /nix/store/).
410 *
411 * Search paths are ordered by priority (highest first), and we need to maintain this order.
412 * If a resolved path is already in the list, we don't need to include.
413 *
414 * Note that we build a list that contains both the original paths and the resolved symlinks:
415 * we need the latter for the case where the directory is symlinked, as described above, and
416 * the former for the case where some unit file alias is a dangling symlink that points to one
417 * of the "original" directories (and can't be followed).
418 */
419 STRV_FOREACH(dir, lp->search_path) {
420 _cleanup_free_ char *resolved_dir = NULL;
421
422 r = strv_extend(&expanded_search_path, *dir);
423 if (r < 0)
424 return log_oom();
425
426 r = chase(*dir, NULL, 0, &resolved_dir, NULL);
427 if (r < 0) {
428 if (r != -ENOENT)
429 log_warning_errno(r, "Failed to resolve symlink %s, ignoring: %m", *dir);
430 continue;
431 }
432
433 if (strv_contains(expanded_search_path, resolved_dir))
434 continue;
435
436 if (strv_consume(&expanded_search_path, TAKE_PTR(resolved_dir)) < 0)
437 return log_oom();
438 }
439
440 STRV_FOREACH(dir, lp->search_path) {
441 _cleanup_closedir_ DIR *d = NULL;
442
443 d = opendir(*dir);
444 if (!d) {
445 if (errno != ENOENT)
446 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
447 continue;
448 }
449
450 FOREACH_DIRENT_ALL(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
451 _unused_ _cleanup_free_ char *_filename_free = NULL;
452 char *filename;
453 _cleanup_free_ char *dst = NULL;
454 bool symlink_to_dir = false;
455
456 /* We only care about valid units and dirs with certain suffixes, let's ignore the
457 * rest. */
458
459 if (de->d_type == DT_REG) {
460
461 /* Accept a regular file whose name is a valid unit file name. */
462 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
463 continue;
464
465 } else if (de->d_type == DT_DIR) {
466
467 if (!paths) /* Skip directories early unless path_cache is requested */
468 continue;
469
470 r = directory_name_is_valid(de->d_name);
471 if (r < 0)
472 return r;
473 if (r == 0)
474 continue;
475
476 } else if (de->d_type == DT_LNK) {
477
478 /* Accept a symlink file whose name is a valid unit file name or
479 * ending in .wants/, .requires/ or .d/. */
480
481 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY)) {
482 _cleanup_free_ char *target = NULL;
483
484 if (!paths) /* Skip symlink to a directory early unless path_cache is requested */
485 continue;
486
487 r = directory_name_is_valid(de->d_name);
488 if (r < 0)
489 return r;
490 if (r == 0)
491 continue;
492
493 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
494 if (r < 0) {
495 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
496 *dir, de->d_name);
497 continue;
498 }
499
500 r = is_dir(target, /* follow= */ true);
501 if (r <= 0)
502 continue;
503
504 symlink_to_dir = true;
505 }
506
507 } else
508 continue;
509
510 filename = path_join(*dir, de->d_name);
511 if (!filename)
512 return log_oom();
513
514 if (paths) {
515 r = set_put(paths, filename);
516 if (r < 0)
517 return log_oom();
518 if (r == 0)
519 _filename_free = filename; /* Make sure we free the filename. */
520 } else
521 _filename_free = filename; /* Make sure we free the filename. */
522
523 if (de->d_type == DT_DIR || (de->d_type == DT_LNK && symlink_to_dir))
524 continue;
525
526 assert(IN_SET(de->d_type, DT_REG, DT_LNK));
527
528 /* search_path is ordered by priority (highest first). If the name is already mapped
529 * to something (incl. itself), it means that we have already seen it, and we should
530 * ignore it here. */
531 if (hashmap_contains(ids, de->d_name))
532 continue;
533
534 if (de->d_type == DT_LNK) {
535 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
536 * limits the number of hops should be used to access the map. */
537
538 r = unit_file_resolve_symlink(lp->root_dir, expanded_search_path,
539 *dir, dirfd(d), de->d_name,
540 /* resolve_destination_target= */ false,
541 &dst);
542 if (r == -ENOMEM)
543 return r;
544 if (r < 0) /* we ignore other errors here */
545 continue;
546
547 } else {
548 dst = TAKE_PTR(_filename_free); /* Grab the copy we made previously, if available. */
549 if (!dst) {
550 dst = strdup(filename);
551 if (!dst)
552 return log_oom();
553 }
554
555 log_debug("%s: normal unit file: %s", __func__, dst);
556 }
557
558 _cleanup_free_ char *key = strdup(de->d_name);
559 if (!key)
560 return log_oom();
561
562 r = hashmap_ensure_put(&ids, &string_hash_ops_free_free, key, dst);
563 if (r < 0)
564 return log_warning_errno(r, "Failed to add entry to hashmap (%s%s%s): %m",
565 de->d_name, glyph(GLYPH_ARROW_RIGHT), dst);
566 key = dst = NULL;
567 }
568 }
569
570 /* Let's also put the names in the reverse db. */
571 const char *dummy, *src;
572 HASHMAP_FOREACH_KEY(dummy, src, ids) {
573 _cleanup_free_ char *inst = NULL, *dst = NULL;
574 const char *dst_path;
575
576 r = unit_ids_map_get(ids, src, &dst_path);
577 if (r < 0)
578 continue;
579
580 if (null_or_empty_path(dst_path) != 0)
581 continue;
582
583 r = path_extract_filename(dst_path, &dst);
584 if (r < 0) {
585 log_debug_errno(r, "Failed to extract file name from %s, ignoring: %m", dst_path);
586 continue;
587 }
588
589 /* If we have an symlink from an instance name to a template name, it is an alias just for
590 * this specific instance, [email protected] ↔ [email protected]. */
591 if (unit_name_is_valid(dst, UNIT_NAME_TEMPLATE)) {
592 UnitNameFlags t = unit_name_to_instance(src, &inst);
593 if (t < 0)
594 return log_error_errno(t, "Failed to extract instance part from %s: %m", src);
595 if (t == UNIT_NAME_INSTANCE) {
596 _cleanup_free_ char *dst_inst = NULL;
597
598 r = unit_name_replace_instance(dst, inst, &dst_inst);
599 if (r < 0) {
600 /* This might happen e.g. if the combined length is too large.
601 * Let's not make too much of a fuss. */
602 log_debug_errno(r, "Failed to build alias name (%s + %s), ignoring: %m",
603 dst, inst);
604 continue;
605 }
606
607 free_and_replace(dst, dst_inst);
608 }
609 }
610
611 r = string_strv_hashmap_put(&names, dst, src);
612 if (r < 0)
613 return log_warning_errno(r, "Failed to add entry to hashmap (%s%s%s): %m",
614 dst, glyph(GLYPH_ARROW_RIGHT), src);
615 }
616
617 if (cache_timestamp_hash)
618 *cache_timestamp_hash = timestamp_hash;
619
620 hashmap_free_and_replace(*unit_ids_map, ids);
621 hashmap_free_and_replace(*unit_names_map, names);
622 if (path_cache)
623 set_free_and_replace(*path_cache, paths);
624
625 return 1;
626 }
627
628 int unit_file_remove_from_name_map(
629 const LookupPaths *lp,
630 uint64_t *cache_timestamp_hash,
631 Hashmap **unit_ids_map,
632 Hashmap **unit_names_map,
633 Set **path_cache,
634 const char *path) {
635
636 int r;
637
638 assert(path);
639
640 /* This assumes the specified path is already removed, and drops the relevant entries from the maps. */
641
642 /* If one of the lookup paths we are monitoring is already changed, let's rebuild the map. Then, the
643 * new map should not contain entries relevant to the specified path. */
644 r = unit_file_build_name_map(lp, cache_timestamp_hash, unit_ids_map, unit_names_map, path_cache);
645 if (r != 0)
646 return r;
647
648 /* If not, drop the relevant entries. */
649
650 _cleanup_free_ char *name = NULL;
651 r = path_extract_filename(path, &name);
652 if (r < 0)
653 return log_warning_errno(r, "Failed to extract file name from '%s': %m", path);
654
655 _unused_ _cleanup_free_ char *key = NULL;
656 free(hashmap_remove2(*unit_ids_map, name, (void**) &key));
657 string_strv_hashmap_remove(*unit_names_map, name, name);
658 free(set_remove(*path_cache, path));
659
660 return 0;
661 }
662
663 static int add_name(
664 const char *unit_name,
665 Set **names,
666 const char *name) {
667 int r;
668
669 assert(names);
670 assert(name);
671
672 r = set_put_strdup(names, name);
673 if (r < 0)
674 return r;
675 if (r > 0 && !streq(unit_name, name))
676 log_debug("Unit %s has alias %s.", unit_name, name);
677 return r;
678 }
679
680 static int add_names(
681 Hashmap *unit_ids_map,
682 Hashmap *unit_name_map,
683 const char *unit_name,
684 const char *fragment_basename, /* Only set when adding additional names based on fragment path */
685 UnitNameFlags name_type,
686 const char *instance,
687 Set **names,
688 const char *name) {
689
690 char **aliases;
691 int r;
692
693 assert(name_type == UNIT_NAME_PLAIN || instance);
694
695 /* The unit has its own name if it's not a template. If we're looking at a fragment, the fragment
696 * name (possibly with instance inserted), is also always one of the unit names. */
697 if (name_type != UNIT_NAME_TEMPLATE) {
698 r = add_name(unit_name, names, name);
699 if (r < 0)
700 return r;
701 }
702
703 /* Add any aliases of the name to the set of names.
704 *
705 * We don't even need to know which fragment we will use. The unit_name_map should return the same
706 * set of names for any of the aliases. */
707 aliases = hashmap_get(unit_name_map, name);
708 STRV_FOREACH(alias, aliases) {
709 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*alias, UNIT_NAME_TEMPLATE)) {
710 _cleanup_free_ char *inst = NULL;
711 const char *inst_fragment = NULL;
712
713 r = unit_name_replace_instance(*alias, instance, &inst);
714 if (r < 0)
715 return log_debug_errno(r, "Cannot build instance name %s + %s: %m",
716 *alias, instance);
717
718 /* Exclude any aliases that point in some other direction.
719 *
720 * See https://github.com/systemd/systemd/pull/13119#discussion_r308145418. */
721 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
722 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
723 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
724
725 if (inst_fragment &&
726 fragment_basename &&
727 !path_equal_filename(inst_fragment, fragment_basename)) {
728 log_debug("Instance %s has fragment %s and is not an alias of %s.",
729 inst, inst_fragment, unit_name);
730 continue;
731 }
732
733 r = add_name(unit_name, names, inst);
734 } else
735 r = add_name(unit_name, names, *alias);
736 if (r < 0)
737 return r;
738 }
739
740 return 0;
741 }
742
743 int unit_file_find_fragment(
744 Hashmap *unit_ids_map,
745 Hashmap *unit_name_map,
746 const char *unit_name,
747 const char **ret_fragment_path,
748 Set **ret_names) {
749
750 const char *fragment = NULL;
751 _cleanup_free_ char *template = NULL, *instance = NULL;
752 _cleanup_set_free_ Set *names = NULL;
753 int r;
754
755 assert(ret_fragment_path);
756
757 /* Finds a fragment path, and returns the set of names:
758 * if we have …/foo.service and …/foo-alias.service→foo.service,
759 * and …/[email protected] and …/[email protected]→[email protected],
760 * and …/[email protected],
761 * this should return:
762 * foo.service → …/foo.service, {foo.service, foo-alias.service},
763 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
764 * [email protected] → …/[email protected], {[email protected], [email protected]},
765 * [email protected] → …/[email protected], {[email protected], [email protected]},
766 * [email protected] → …/[email protected], {[email protected], [email protected]},
767 * [email protected] → …/[email protected], {[email protected], [email protected]},
768 * [email protected] → …/[email protected], {[email protected], [email protected]}.
769 */
770
771 UnitNameFlags name_type = unit_name_to_instance(unit_name, &instance);
772 if (name_type < 0)
773 return name_type;
774
775 if (ret_names) {
776 r = add_names(unit_ids_map, unit_name_map, unit_name, NULL, name_type, instance, &names, unit_name);
777 if (r < 0)
778 return r;
779 }
780
781 /* First try to load fragment under the original name */
782 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
783 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
784 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
785
786 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
787 /* Look for a fragment under the template name */
788
789 r = unit_name_template(unit_name, &template);
790 if (r < 0)
791 return log_debug_errno(r, "Failed to determine template name: %m");
792
793 r = unit_ids_map_get(unit_ids_map, template, &fragment);
794 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
795 return log_debug_errno(r, "Cannot load template %s: %m", template);
796 }
797
798 if (fragment && ret_names) {
799 _cleanup_free_ char *fragment_basename = NULL;
800 r = path_extract_filename(fragment, &fragment_basename);
801 if (r < 0)
802 return r;
803
804 if (!streq(fragment_basename, unit_name)) {
805 /* Add names based on the fragment name to the set of names */
806 r = add_names(unit_ids_map, unit_name_map, unit_name, fragment_basename, name_type, instance, &names, fragment_basename);
807 if (r < 0)
808 return r;
809 }
810 }
811
812 *ret_fragment_path = fragment;
813 if (ret_names)
814 *ret_names = TAKE_PTR(names);
815
816 return 0;
817 }
818
819 static const char * const rlmap[] = {
820 "emergency", SPECIAL_EMERGENCY_TARGET,
821 "-b", SPECIAL_EMERGENCY_TARGET,
822 "rescue", SPECIAL_RESCUE_TARGET,
823 "single", SPECIAL_RESCUE_TARGET,
824 "-s", SPECIAL_RESCUE_TARGET,
825 "s", SPECIAL_RESCUE_TARGET,
826 "S", SPECIAL_RESCUE_TARGET,
827 "1", SPECIAL_RESCUE_TARGET,
828 "2", SPECIAL_MULTI_USER_TARGET,
829 "3", SPECIAL_MULTI_USER_TARGET,
830 "4", SPECIAL_MULTI_USER_TARGET,
831 "5", SPECIAL_GRAPHICAL_TARGET,
832 NULL
833 };
834
835 static const char * const rlmap_initrd[] = {
836 "emergency", SPECIAL_EMERGENCY_TARGET,
837 "rescue", SPECIAL_RESCUE_TARGET,
838 NULL
839 };
840
841 const char* runlevel_to_target(const char *word) {
842 const char * const *rlmap_ptr;
843
844 if (!word)
845 return NULL;
846
847 if (in_initrd()) {
848 word = startswith(word, "rd.");
849 if (!word)
850 return NULL;
851
852 rlmap_ptr = rlmap_initrd;
853 } else
854 rlmap_ptr = rlmap;
855
856 STRV_FOREACH_PAIR(rl, target, rlmap_ptr)
857 if (streq(word, *rl))
858 return *target;
859
860 return NULL;
861 }