]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/unit-file.c
Merge pull request #18863 from keszybz/cmdline-escaping
[thirdparty/systemd.git] / src / basic / unit-file.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-id128.h"
4
5 #include "dirent-util.h"
6 #include "fd-util.h"
7 #include "fs-util.h"
8 #include "macro.h"
9 #include "path-lookup.h"
10 #include "set.h"
11 #include "special.h"
12 #include "stat-util.h"
13 #include "string-util.h"
14 #include "strv.h"
15 #include "unit-file.h"
16
17 bool unit_type_may_alias(UnitType type) {
18 return IN_SET(type,
19 UNIT_SERVICE,
20 UNIT_SOCKET,
21 UNIT_TARGET,
22 UNIT_DEVICE,
23 UNIT_TIMER,
24 UNIT_PATH);
25 }
26
27 bool unit_type_may_template(UnitType type) {
28 return IN_SET(type,
29 UNIT_SERVICE,
30 UNIT_SOCKET,
31 UNIT_TARGET,
32 UNIT_TIMER,
33 UNIT_PATH);
34 }
35
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;
39
40 un_type1 = unit_name_classify(symlink);
41
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)))
45 return 1;
46
47 r = unit_name_template(symlink, &template);
48 if (r == -EINVAL)
49 return 0; /* Not a template */
50 if (r < 0)
51 return r;
52
53 un_type2 = unit_name_classify(target);
54
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))
59 return 1;
60
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))
66 return 1;
67
68 return 0;
69 }
70
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 UnitNameFlags src_name_type, dst_name_type;
76
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
80 * unit lookup path.
81 *
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.
85 */
86
87 src = basename(filename);
88 dst = basename(target);
89
90 /* src checks */
91
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);
96
97 src_unit_type = unit_name_to_type(src);
98 assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
99
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.",
103 filename);
104
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));
110
111 /* dst checks */
112
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",
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_notice_errno(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_notice_errno(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_notice_errno(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 char **dir;
212 STRV_FOREACH(dir, (char**) lp->search_path) {
213 struct stat st;
214
215 if (lookup_paths_mtime_exclude(lp, *dir))
216 continue;
217
218 /* Determine the latest lookup path modification time */
219 if (stat(*dir, &st) < 0) {
220 if (errno == ENOENT)
221 continue;
222
223 log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
224 continue;
225 }
226
227 siphash24_compress_usec_t(timespec_load(&st.st_mtim), &state);
228 }
229
230 uint64_t updated = siphash24_finalize(&state);
231 if (ret_new)
232 *ret_new = updated;
233 if (updated != timestamp_hash)
234 log_debug("Modification times have changed, need to update cache.");
235 return updated == timestamp_hash;
236 }
237
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,
243 Set **path_cache) {
244
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 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.
250 *
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.
253 */
254
255 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
256 _cleanup_set_free_free_ Set *paths = NULL;
257 uint64_t timestamp_hash;
258 char **dir;
259 int r;
260
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, &timestamp_hash))
265 return 0;
266
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. */
269
270 if (path_cache) {
271 paths = set_new(&path_hash_ops_free);
272 if (!paths)
273 return log_oom();
274 }
275
276 STRV_FOREACH(dir, (char**) lp->search_path) {
277 struct dirent *de;
278 _cleanup_closedir_ DIR *d = NULL;
279
280 d = opendir(*dir);
281 if (!d) {
282 if (errno != ENOENT)
283 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
284 continue;
285 }
286
287 FOREACH_DIRENT(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
288 char *filename;
289 _cleanup_free_ char *_filename_free = NULL, *simplified = NULL;
290 const char *suffix, *dst = NULL;
291 bool valid_unit_name;
292
293 valid_unit_name = unit_name_is_valid(de->d_name, UNIT_NAME_ANY);
294
295 /* We only care about valid units and dirs with certain suffixes, let's ignore the
296 * rest. */
297 if (!valid_unit_name &&
298 !ENDSWITH_SET(de->d_name, ".wants", ".requires", ".d"))
299 continue;
300
301 filename = path_join(*dir, de->d_name);
302 if (!filename)
303 return log_oom();
304
305 if (paths) {
306 r = set_consume(paths, filename);
307 if (r < 0)
308 return log_oom();
309 /* We will still use filename below. This is safe because we know the set
310 * holds a reference. */
311 } else
312 _filename_free = filename; /* Make sure we free the filename. */
313
314 if (!valid_unit_name)
315 continue;
316 assert_se(suffix = strrchr(de->d_name, '.'));
317
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
320 * ignore it here. */
321 if (hashmap_contains(ids, de->d_name))
322 continue;
323
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. */
328
329 _cleanup_free_ char *target = NULL;
330
331 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
332 if (r < 0) {
333 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
334 *dir, de->d_name);
335 continue;
336 }
337
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);
341 if (!target_abs)
342 return log_oom();
343
344 free_and_replace(target, target_abs);
345 }
346
347 /* Get rid of "." and ".." components in target path */
348 r = chase_symlinks(target, lp->root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
349 if (r < 0) {
350 log_warning_errno(r, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
351 filename, target);
352 continue;
353 }
354
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 source directly.
358 * If not, let's verify that it's a good symlink. */
359 char *tail = path_startswith_strv(simplified, lp->search_path);
360 if (!tail) {
361 log_debug("%s: linked unit file: %s → %s",
362 __func__, filename, simplified);
363
364 dst = filename;
365 } else {
366
367 bool self_alias;
368
369 dst = basename(simplified);
370 self_alias = streq(dst, de->d_name);
371
372 if (is_path(tail))
373 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
374 "Suspicious symlink %s→%s, treating as alias.",
375 filename, simplified);
376
377 r = unit_validate_alias_symlink_and_warn(filename, simplified);
378 if (r < 0)
379 continue;
380
381 if (self_alias) {
382 /* A self-alias that has no effect */
383 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
384 __func__, *dir, de->d_name, dst);
385 continue;
386 }
387
388 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
389 }
390
391 } else {
392 dst = filename;
393 log_debug("%s: normal unit file: %s", __func__, dst);
394 }
395
396 r = hashmap_put_strdup(&ids, de->d_name, dst);
397 if (r < 0)
398 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
399 de->d_name, dst);
400 }
401 }
402
403 /* Let's also put the names in the reverse db. */
404 const char *dummy, *src;
405 HASHMAP_FOREACH_KEY(dummy, src, ids) {
406 _cleanup_free_ char *inst = NULL, *dst_inst = NULL;
407 const char *dst;
408
409 r = unit_ids_map_get(ids, src, &dst);
410 if (r < 0)
411 continue;
412
413 if (null_or_empty_path(dst) != 0)
414 continue;
415
416 dst = basename(dst);
417
418 /* If we have an symlink from an instance name to a template name, it is an alias just for
419 * this specific instance, foo@id.service ↔ template@id.service. */
420 if (unit_name_is_valid(dst, UNIT_NAME_TEMPLATE)) {
421 UnitNameFlags t = unit_name_to_instance(src, &inst);
422 if (t < 0)
423 return log_error_errno(t, "Failed to extract instance part from %s: %m", src);
424 if (t == UNIT_NAME_INSTANCE) {
425 r = unit_name_replace_instance(dst, inst, &dst_inst);
426 if (r < 0) {
427 /* This might happen e.g. if the combined length is too large.
428 * Let's not make too much of a fuss. */
429 log_debug_errno(r, "Failed to build alias name (%s + %s), ignoring: %m",
430 dst, inst);
431 continue;
432 }
433
434 dst = dst_inst;
435 }
436 }
437
438 r = string_strv_hashmap_put(&names, dst, src);
439 if (r < 0)
440 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m", dst, src);
441 }
442
443 if (cache_timestamp_hash)
444 *cache_timestamp_hash = timestamp_hash;
445
446 hashmap_free_and_replace(*unit_ids_map, ids);
447 hashmap_free_and_replace(*unit_names_map, names);
448 if (path_cache)
449 set_free_and_replace(*path_cache, paths);
450
451 return 1;
452 }
453
454 static int add_name(
455 const char *unit_name,
456 Set **names,
457 const char *name) {
458 int r;
459
460 assert(names);
461 assert(name);
462
463 r = set_put_strdup(names, name);
464 if (r < 0)
465 return r;
466 if (r > 0 && !streq(unit_name, name))
467 log_debug("Unit %s has alias %s.", unit_name, name);
468 return r;
469 }
470
471 static int add_names(
472 Hashmap *unit_ids_map,
473 Hashmap *unit_name_map,
474 const char *unit_name,
475 const char *fragment_basename, /* Only set when adding additional names based on fragment path */
476 UnitNameFlags name_type,
477 const char *instance,
478 Set **names,
479 const char *name) {
480
481 char **aliases, **alias;
482 int r;
483
484 assert(name_type == UNIT_NAME_PLAIN || instance);
485
486 /* The unit has its own name if it's not a template. If we're looking at a fragment, the fragment
487 * name (possibly with instance inserted), is also always one of the unit names. */
488 if (name_type != UNIT_NAME_TEMPLATE) {
489 r = add_name(unit_name, names, name);
490 if (r < 0)
491 return r;
492 }
493
494 /* Add any aliases of the name to the set of names.
495 *
496 * We don't even need to know which fragment we will use. The unit_name_map should return the same
497 * set of names for any of the aliases. */
498 aliases = hashmap_get(unit_name_map, name);
499 STRV_FOREACH(alias, aliases) {
500 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*alias, UNIT_NAME_TEMPLATE)) {
501 _cleanup_free_ char *inst = NULL;
502 const char *inst_fragment = NULL;
503
504 r = unit_name_replace_instance(*alias, instance, &inst);
505 if (r < 0)
506 return log_debug_errno(r, "Cannot build instance name %s + %s: %m",
507 *alias, instance);
508
509 /* Exclude any aliases that point in some other direction.
510 *
511 * See https://github.com/systemd/systemd/pull/13119#discussion_r308145418. */
512 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
513 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
514 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
515
516 if (inst_fragment &&
517 !streq(basename(inst_fragment), fragment_basename)) {
518 log_debug("Instance %s has fragment %s and is not an alias of %s.",
519 inst, inst_fragment, unit_name);
520 continue;
521 }
522
523 r = set_consume(*names, TAKE_PTR(inst));
524 if (r > 0)
525 log_debug("Unit %s has alias %s.", unit_name, inst);
526 } else
527 r = add_name(unit_name, names, *alias);
528
529 if (r < 0)
530 return r;
531 }
532
533 return 0;
534 }
535
536 int unit_file_find_fragment(
537 Hashmap *unit_ids_map,
538 Hashmap *unit_name_map,
539 const char *unit_name,
540 const char **ret_fragment_path,
541 Set **ret_names) {
542
543 const char *fragment = NULL;
544 _cleanup_free_ char *template = NULL, *instance = NULL;
545 _cleanup_set_free_ Set *names = NULL;
546 int r;
547
548 /* Finds a fragment path, and returns the set of names:
549 * if we have …/foo.service and …/foo-alias.service→foo.service,
550 * and …/foo@.service and …/foo-alias@.service→foo@.service,
551 * and …/foo@inst.service,
552 * this should return:
553 * foo.service → …/foo.service, {foo.service, foo-alias.service},
554 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
555 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
556 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
557 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
558 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
559 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
560 */
561
562 UnitNameFlags name_type = unit_name_to_instance(unit_name, &instance);
563 if (name_type < 0)
564 return name_type;
565
566 r = add_names(unit_ids_map, unit_name_map, unit_name, NULL, name_type, instance, &names, unit_name);
567 if (r < 0)
568 return r;
569
570 /* First try to load fragment under the original name */
571 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
572 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
573 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
574
575 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
576 /* Look for a fragment under the template name */
577
578 r = unit_name_template(unit_name, &template);
579 if (r < 0)
580 return log_debug_errno(r, "Failed to determine template name: %m");
581
582 r = unit_ids_map_get(unit_ids_map, template, &fragment);
583 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
584 return log_debug_errno(r, "Cannot load template %s: %m", template);
585 }
586
587 if (fragment) {
588 const char *fragment_basename = basename(fragment);
589
590 if (!streq(fragment_basename, unit_name)) {
591 /* Add names based on the fragment name to the set of names */
592 r = add_names(unit_ids_map, unit_name_map, unit_name, fragment_basename, name_type, instance, &names, fragment_basename);
593 if (r < 0)
594 return r;
595 }
596 }
597
598 *ret_fragment_path = fragment;
599 *ret_names = TAKE_PTR(names);
600
601 return 0;
602 }
603
604 static const char * const rlmap[] = {
605 "emergency", SPECIAL_EMERGENCY_TARGET,
606 "-b", SPECIAL_EMERGENCY_TARGET,
607 "rescue", SPECIAL_RESCUE_TARGET,
608 "single", SPECIAL_RESCUE_TARGET,
609 "-s", SPECIAL_RESCUE_TARGET,
610 "s", SPECIAL_RESCUE_TARGET,
611 "S", SPECIAL_RESCUE_TARGET,
612 "1", SPECIAL_RESCUE_TARGET,
613 "2", SPECIAL_MULTI_USER_TARGET,
614 "3", SPECIAL_MULTI_USER_TARGET,
615 "4", SPECIAL_MULTI_USER_TARGET,
616 "5", SPECIAL_GRAPHICAL_TARGET,
617 NULL
618 };
619
620 static const char * const rlmap_initrd[] = {
621 "emergency", SPECIAL_EMERGENCY_TARGET,
622 "rescue", SPECIAL_RESCUE_TARGET,
623 NULL
624 };
625
626 const char* runlevel_to_target(const char *word) {
627 const char * const *rlmap_ptr;
628
629 if (!word)
630 return NULL;
631
632 if (in_initrd()) {
633 word = startswith(word, "rd.");
634 if (!word)
635 return NULL;
636 }
637
638 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
639
640 for (size_t i = 0; rlmap_ptr[i]; i += 2)
641 if (streq(word, rlmap_ptr[i]))
642 return rlmap_ptr[i+1];
643
644 return NULL;
645 }