]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/unit-file.c
tree-wide: define iterator inside of the macro
[thirdparty/systemd.git] / src / shared / unit-file.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
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 int 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 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_ALL(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 destination 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 bool self_alias;
362
363 dst = basename(simplified);
364 self_alias = streq(dst, de->d_name);
365
366 if (is_path(tail))
367 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
368 "Suspicious symlink %s→%s, treating as alias.",
369 filename, simplified);
370
371 r = unit_validate_alias_symlink_and_warn(filename, simplified);
372 if (r < 0)
373 continue;
374
375 if (self_alias) {
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);
379 continue;
380 }
381
382 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
383 } else {
384 dst = simplified;
385
386 log_debug("%s: linked unit file: %s/%s → %s", __func__, *dir, de->d_name, dst);
387 }
388
389 } else {
390 dst = filename;
391 log_debug("%s: normal unit file: %s", __func__, dst);
392 }
393
394 r = hashmap_put_strdup(&ids, de->d_name, dst);
395 if (r < 0)
396 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
397 de->d_name, dst);
398 }
399 }
400
401 /* Let's also put the names in the reverse db. */
402 const char *dummy, *src;
403 HASHMAP_FOREACH_KEY(dummy, src, ids) {
404 const char *dst;
405
406 r = unit_ids_map_get(ids, src, &dst);
407 if (r < 0)
408 continue;
409
410 if (null_or_empty_path(dst) != 0)
411 continue;
412
413 /* Do not treat instance symlinks that point to the template as aliases */
414 if (unit_name_is_valid(basename(dst), UNIT_NAME_TEMPLATE) &&
415 unit_name_is_valid(src, UNIT_NAME_INSTANCE))
416 continue;
417
418 r = string_strv_hashmap_put(&names, basename(dst), src);
419 if (r < 0)
420 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
421 basename(dst), src);
422 }
423
424 if (cache_timestamp_hash)
425 *cache_timestamp_hash = timestamp_hash;
426
427 hashmap_free_and_replace(*unit_ids_map, ids);
428 hashmap_free_and_replace(*unit_names_map, names);
429 if (path_cache)
430 set_free_and_replace(*path_cache, paths);
431
432 return 1;
433 }
434
435 int unit_file_find_fragment(
436 Hashmap *unit_ids_map,
437 Hashmap *unit_name_map,
438 const char *unit_name,
439 const char **ret_fragment_path,
440 Set **ret_names) {
441
442 const char *fragment = NULL;
443 _cleanup_free_ char *template = NULL, *instance = NULL;
444 _cleanup_set_free_free_ Set *names = NULL;
445 char **t, **nnn;
446 int r, name_type;
447
448 /* Finds a fragment path, and returns the set of names:
449 * if we have …/foo.service and …/foo-alias.service→foo.service,
450 * and …/foo@.service and …/foo-alias@.service→foo@.service,
451 * and …/foo@inst.service,
452 * this should return:
453 * foo.service → …/foo.service, {foo.service, foo-alias.service},
454 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
455 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
456 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
457 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
458 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
459 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
460 */
461
462 name_type = unit_name_to_instance(unit_name, &instance);
463 if (name_type < 0)
464 return name_type;
465
466 names = set_new(&string_hash_ops);
467 if (!names)
468 return -ENOMEM;
469
470 /* The unit always has its own name if it's not a template. */
471 if (IN_SET(name_type, UNIT_NAME_PLAIN, UNIT_NAME_INSTANCE)) {
472 r = set_put_strdup(&names, unit_name);
473 if (r < 0)
474 return r;
475 }
476
477 /* First try to load fragment under the original name */
478 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
479 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
480 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
481
482 if (fragment) {
483 /* Add any aliases of the original name to the set of names */
484 nnn = hashmap_get(unit_name_map, basename(fragment));
485 STRV_FOREACH(t, nnn) {
486 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*t, UNIT_NAME_TEMPLATE)) {
487 char *inst;
488
489 r = unit_name_replace_instance(*t, instance, &inst);
490 if (r < 0)
491 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", *t, instance);
492
493 if (!streq(unit_name, inst))
494 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
495
496 log_info("%s: %s+%s → %s", __func__, *t, instance, inst);
497 r = set_consume(names, inst);
498 } else {
499 if (!streq(unit_name, *t))
500 log_debug("%s: %s has alias %s", __func__, unit_name, *t);
501
502 r = set_put_strdup(&names, *t);
503 }
504 if (r < 0)
505 return r;
506 }
507 }
508
509 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
510 /* Look for a fragment under the template name */
511
512 r = unit_name_template(unit_name, &template);
513 if (r < 0)
514 return log_error_errno(r, "Failed to determine template name: %m");
515
516 r = unit_ids_map_get(unit_ids_map, template, &fragment);
517 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
518 return log_debug_errno(r, "Cannot load template %s: %m", template);
519
520 if (fragment) {
521 /* Add any aliases of the original name to the set of names */
522 nnn = hashmap_get(unit_name_map, basename(fragment));
523 STRV_FOREACH(t, nnn) {
524 _cleanup_free_ char *inst = NULL;
525 const char *inst_fragment = NULL;
526
527 r = unit_name_replace_instance(*t, instance, &inst);
528 if (r < 0)
529 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", template, instance);
530
531 /* Exclude any aliases that point in some other direction. */
532 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
533 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
534 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
535
536 if (inst_fragment &&
537 !streq(basename(inst_fragment), basename(fragment))) {
538 log_debug("Instance %s has fragment %s and is not an alias of %s.",
539 inst, inst_fragment, unit_name);
540 continue;
541 }
542
543 if (!streq(unit_name, inst))
544 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
545 r = set_consume(names, TAKE_PTR(inst));
546 if (r < 0)
547 return r;
548 }
549 }
550 }
551
552 *ret_fragment_path = fragment;
553 *ret_names = TAKE_PTR(names);
554
555 // FIXME: if instance, consider any unit names with different template name
556 return 0;
557 }
558
559 static const char * const rlmap[] = {
560 "emergency", SPECIAL_EMERGENCY_TARGET,
561 "-b", SPECIAL_EMERGENCY_TARGET,
562 "rescue", SPECIAL_RESCUE_TARGET,
563 "single", SPECIAL_RESCUE_TARGET,
564 "-s", SPECIAL_RESCUE_TARGET,
565 "s", SPECIAL_RESCUE_TARGET,
566 "S", SPECIAL_RESCUE_TARGET,
567 "1", SPECIAL_RESCUE_TARGET,
568 "2", SPECIAL_MULTI_USER_TARGET,
569 "3", SPECIAL_MULTI_USER_TARGET,
570 "4", SPECIAL_MULTI_USER_TARGET,
571 "5", SPECIAL_GRAPHICAL_TARGET,
572 NULL
573 };
574
575 static const char * const rlmap_initrd[] = {
576 "emergency", SPECIAL_EMERGENCY_TARGET,
577 "rescue", SPECIAL_RESCUE_TARGET,
578 NULL
579 };
580
581 const char* runlevel_to_target(const char *word) {
582 const char * const *rlmap_ptr;
583 size_t i;
584
585 if (!word)
586 return NULL;
587
588 if (in_initrd()) {
589 word = startswith(word, "rd.");
590 if (!word)
591 return NULL;
592 }
593
594 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
595
596 for (i = 0; rlmap_ptr[i]; i += 2)
597 if (streq(word, rlmap_ptr[i]))
598 return rlmap_ptr[i+1];
599
600 return NULL;
601 }