]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/unit-file.c
Merge pull request #15745 from keszybz/one-more-specifier
[thirdparty/systemd.git] / src / shared / unit-file.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "dirent-util.h"
4 #include "fd-util.h"
5 #include "fs-util.h"
6 #include "macro.h"
7 #include "path-lookup.h"
8 #include "set.h"
9 #include "special.h"
10 #include "stat-util.h"
11 #include "string-util.h"
12 #include "strv.h"
13 #include "unit-file.h"
14
15 bool unit_type_may_alias(UnitType type) {
16 return IN_SET(type,
17 UNIT_SERVICE,
18 UNIT_SOCKET,
19 UNIT_TARGET,
20 UNIT_DEVICE,
21 UNIT_TIMER,
22 UNIT_PATH);
23 }
24
25 bool unit_type_may_template(UnitType type) {
26 return IN_SET(type,
27 UNIT_SERVICE,
28 UNIT_SOCKET,
29 UNIT_TARGET,
30 UNIT_TIMER,
31 UNIT_PATH);
32 }
33
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;
37
38 un_type1 = unit_name_classify(symlink);
39
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)))
43 return 1;
44
45 r = unit_name_template(symlink, &template);
46 if (r == -EINVAL)
47 return 0; /* Not a template */
48 if (r < 0)
49 return r;
50
51 un_type2 = unit_name_classify(target);
52
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))
57 return 1;
58
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))
64 return 1;
65
66 return 0;
67 }
68
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;
74
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
78 * unit lookup path.
79 *
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.
83 */
84
85 src = basename(filename);
86 dst = basename(target);
87
88 /* src checks */
89
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);
94
95 src_unit_type = unit_name_to_type(src);
96 assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
97
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.",
101 filename);
102
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));
108
109 /* dst checks */
110
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",
115 filename, dst);
116
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.",
121 filename, dst);
122
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.",
129 filename, dst);
130 }
131
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.",
136 filename, dst);
137
138 return 0;
139 }
140
141 #define FOLLOW_MAX 8
142
143 static int unit_ids_map_get(
144 Hashmap *unit_ids_map,
145 const char *unit_name,
146 const char **ret_fragment_path) {
147
148 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
149 *
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.
152 *
153 * If a symlink target points to an instance name, then we also check for the template. */
154
155 const char *id = NULL;
156 int r;
157
158 for (unsigned n = 0; n < FOLLOW_MAX; n++) {
159 const char *t = hashmap_get(unit_ids_map, id ?: unit_name);
160 if (!t) {
161 _cleanup_free_ char *template = NULL;
162
163 if (!id)
164 return -ENOENT;
165
166 r = unit_name_template(id, &template);
167 if (r == -EINVAL)
168 return -ENXIO; /* we failed to find the symlink target */
169 if (r < 0)
170 return log_error_errno(r, "Failed to determine template name for %s: %m", id);
171
172 t = hashmap_get(unit_ids_map, template);
173 if (!t)
174 return -ENXIO;
175
176 /* We successfully switched from instanced name to a template, let's continue */
177 }
178
179 if (path_is_absolute(t)) {
180 if (ret_fragment_path)
181 *ret_fragment_path = t;
182 return 0;
183 }
184
185 id = t;
186 }
187
188 return -ELOOP;
189 }
190
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. */
193
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);
200 }
201
202 static bool lookup_paths_mtime_good(const LookupPaths *lp, usec_t mtime) {
203 char **dir;
204
205 STRV_FOREACH(dir, (char**) lp->search_path) {
206 struct stat st;
207
208 if (lookup_paths_mtime_exclude(lp, *dir))
209 continue;
210
211 /* Determine the latest lookup path modification time */
212 if (stat(*dir, &st) < 0) {
213 if (errno == ENOENT)
214 continue;
215
216 log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
217 continue;
218 }
219
220 if (timespec_load(&st.st_mtim) > mtime) {
221 log_debug_errno(errno, "Unit dir %s has changed, need to update cache.", *dir);
222 return false;
223 }
224 }
225
226 return true;
227 }
228
229 int unit_file_build_name_map(
230 const LookupPaths *lp,
231 usec_t *cache_mtime,
232 Hashmap **ret_unit_ids_map,
233 Hashmap **ret_unit_names_map,
234 Set **ret_path_cache) {
235
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.
241 *
242 * At the same, build a cache of paths where to find units.
243 */
244
245 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
246 _cleanup_set_free_free_ Set *paths = NULL;
247 char **dir;
248 int r;
249 usec_t mtime = 0;
250
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))
254 return 0;
255
256 if (ret_path_cache) {
257 paths = set_new(&path_hash_ops);
258 if (!paths)
259 return log_oom();
260 }
261
262 STRV_FOREACH(dir, (char**) lp->search_path) {
263 struct dirent *de;
264 _cleanup_closedir_ DIR *d = NULL;
265 struct stat st;
266
267 d = opendir(*dir);
268 if (!d) {
269 if (errno != ENOENT)
270 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
271 continue;
272 }
273
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);
277
278 if (!lookup_paths_mtime_exclude(lp, *dir))
279 mtime = MAX(mtime, timespec_load(&st.st_mtim));
280
281 FOREACH_DIRENT_ALL(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
282 char *filename;
283 _cleanup_free_ char *_filename_free = NULL, *simplified = NULL;
284 const char *suffix, *dst = NULL;
285 bool valid_unit_name;
286
287 valid_unit_name = unit_name_is_valid(de->d_name, UNIT_NAME_ANY);
288
289 /* We only care about valid units and dirs with certain suffixes, let's ignore the
290 * rest. */
291 if (!valid_unit_name &&
292 !ENDSWITH_SET(de->d_name, ".wants", ".requires", ".d"))
293 continue;
294
295 filename = path_join(*dir, de->d_name);
296 if (!filename)
297 return log_oom();
298
299 if (ret_path_cache) {
300 r = set_consume(paths, filename);
301 if (r < 0)
302 return log_oom();
303 /* We will still use filename below. This is safe because we know the set
304 * holds a reference. */
305 } else
306 _filename_free = filename; /* Make sure we free the filename. */
307
308 if (!valid_unit_name)
309 continue;
310 assert_se(suffix = strrchr(de->d_name, '.'));
311
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
314 * ignore it here. */
315 if (hashmap_contains(ids, de->d_name))
316 continue;
317
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. */
322
323 _cleanup_free_ char *target = NULL;
324
325 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
326 if (r < 0) {
327 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
328 *dir, de->d_name);
329 continue;
330 }
331
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);
335 if (!target_abs)
336 return log_oom();
337
338 free_and_replace(target, target_abs);
339 }
340
341 /* Get rid of "." and ".." components in target path */
342 r = chase_symlinks(target, lp->root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
343 if (r < 0) {
344 log_warning_errno(r, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
345 filename, target);
346 continue;
347 }
348
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);
354 if (tail) {
355 bool self_alias;
356
357 dst = basename(simplified);
358 self_alias = streq(dst, de->d_name);
359
360 if (is_path(tail))
361 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
362 "Suspicious symlink %s→%s, treating as alias.",
363 filename, simplified);
364
365 r = unit_validate_alias_symlink_and_warn(filename, simplified);
366 if (r < 0)
367 continue;
368
369 if (self_alias) {
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);
373 continue;
374 }
375
376 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
377 } else {
378 dst = simplified;
379
380 log_debug("%s: linked unit file: %s/%s → %s", __func__, *dir, de->d_name, dst);
381 }
382
383 } else {
384 dst = filename;
385 log_debug("%s: normal unit file: %s", __func__, dst);
386 }
387
388 r = hashmap_put_strdup(&ids, de->d_name, dst);
389 if (r < 0)
390 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
391 de->d_name, dst);
392 }
393 }
394
395 /* Let's also put the names in the reverse db. */
396 Iterator it;
397 const char *dummy, *src;
398 HASHMAP_FOREACH_KEY(dummy, src, ids, it) {
399 const char *dst;
400
401 r = unit_ids_map_get(ids, src, &dst);
402 if (r < 0)
403 continue;
404
405 if (null_or_empty_path(dst) != 0)
406 continue;
407
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))
411 continue;
412
413 r = string_strv_hashmap_put(&names, basename(dst), src);
414 if (r < 0)
415 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
416 basename(dst), src);
417 }
418
419 if (cache_mtime)
420 *cache_mtime = mtime;
421 *ret_unit_ids_map = TAKE_PTR(ids);
422 *ret_unit_names_map = TAKE_PTR(names);
423 if (ret_path_cache)
424 *ret_path_cache = TAKE_PTR(paths);
425
426 return 1;
427 }
428
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,
434 Set **ret_names) {
435
436 const char *fragment = NULL;
437 _cleanup_free_ char *template = NULL, *instance = NULL;
438 _cleanup_set_free_free_ Set *names = NULL;
439 char **t, **nnn;
440 int r, name_type;
441
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}.
454 */
455
456 name_type = unit_name_to_instance(unit_name, &instance);
457 if (name_type < 0)
458 return name_type;
459
460 names = set_new(&string_hash_ops);
461 if (!names)
462 return -ENOMEM;
463
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);
467 if (r < 0)
468 return r;
469 }
470
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);
475
476 if (fragment) {
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)) {
481 char *inst;
482
483 r = unit_name_replace_instance(*t, instance, &inst);
484 if (r < 0)
485 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", *t, instance);
486
487 if (!streq(unit_name, inst))
488 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
489
490 log_info("%s: %s+%s → %s", __func__, *t, instance, inst);
491 r = set_consume(names, inst);
492 } else {
493 if (!streq(unit_name, *t))
494 log_debug("%s: %s has alias %s", __func__, unit_name, *t);
495
496 r = set_put_strdup(&names, *t);
497 }
498 if (r < 0)
499 return r;
500 }
501 }
502
503 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
504 /* Look for a fragment under the template name */
505
506 r = unit_name_template(unit_name, &template);
507 if (r < 0)
508 return log_error_errno(r, "Failed to determine template name: %m");
509
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);
513
514 if (fragment) {
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;
520
521 r = unit_name_replace_instance(*t, instance, &inst);
522 if (r < 0)
523 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", template, instance);
524
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);
529
530 if (inst_fragment &&
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);
534 continue;
535 }
536
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));
540 if (r < 0)
541 return r;
542 }
543 }
544 }
545
546 *ret_fragment_path = fragment;
547 *ret_names = TAKE_PTR(names);
548
549 // FIXME: if instance, consider any unit names with different template name
550 return 0;
551 }
552
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,
566 NULL
567 };
568
569 static const char * const rlmap_initrd[] = {
570 "emergency", SPECIAL_EMERGENCY_TARGET,
571 "rescue", SPECIAL_RESCUE_TARGET,
572 NULL
573 };
574
575 const char* runlevel_to_target(const char *word) {
576 const char * const *rlmap_ptr;
577 size_t i;
578
579 if (!word)
580 return NULL;
581
582 if (in_initrd()) {
583 word = startswith(word, "rd.");
584 if (!word)
585 return NULL;
586 }
587
588 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
589
590 for (i = 0; rlmap_ptr[i]; i += 2)
591 if (streq(word, rlmap_ptr[i]))
592 return rlmap_ptr[i+1];
593
594 return NULL;
595 }