]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/unit-file.c
basic/fs-util: change CHASE_OPEN flag into a separate output parameter
[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_validate_alias_symlink_and_warn(const char *filename, const char *target) {
35 const char *src, *dst;
36 _cleanup_free_ char *src_instance = NULL, *dst_instance = NULL;
37 UnitType src_unit_type, dst_unit_type;
38 int src_name_type, dst_name_type;
39
40 /* Check if the *alias* symlink is valid. This applies to symlinks like
41 * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
42 * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
43 * unit lookup path.
44 *
45 * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
46 * not allowed to symlink,
47 * -EXDEV if the target filename is not a valid unit name or doesn't match the source.
48 */
49
50 src = basename(filename);
51 dst = basename(target);
52
53 /* src checks */
54
55 src_name_type = unit_name_to_instance(src, &src_instance);
56 if (src_name_type < 0)
57 return log_notice_errno(src_name_type,
58 "%s: not a valid unit name \"%s\": %m", filename, src);
59
60 src_unit_type = unit_name_to_type(src);
61 assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
62
63 if (!unit_type_may_alias(src_unit_type))
64 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL),
65 "%s: symlinks are not allowed for units of this type, rejecting.",
66 filename);
67
68 if (src_name_type != UNIT_NAME_PLAIN &&
69 !unit_type_may_template(src_unit_type))
70 return log_notice_errno(SYNTHETIC_ERRNO(EINVAL),
71 "%s: templates not allowed for %s units, rejecting.",
72 filename, unit_type_to_string(src_unit_type));
73
74 /* dst checks */
75
76 dst_name_type = unit_name_to_instance(dst, &dst_instance);
77 if (dst_name_type < 0)
78 return log_notice_errno(dst_name_type == -EINVAL ? SYNTHETIC_ERRNO(EXDEV) : dst_name_type,
79 "%s points to \"%s\" which is not a valid unit name: %m",
80 filename, dst);
81
82 if (!(dst_name_type == src_name_type ||
83 (src_name_type == UNIT_NAME_INSTANCE && dst_name_type == UNIT_NAME_TEMPLATE)))
84 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
85 "%s: symlink target name type \"%s\" does not match source, rejecting.",
86 filename, dst);
87
88 if (dst_name_type == UNIT_NAME_INSTANCE) {
89 assert(src_instance);
90 assert(dst_instance);
91 if (!streq(src_instance, dst_instance))
92 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
93 "%s: unit symlink target \"%s\" instance name doesn't match, rejecting.",
94 filename, dst);
95 }
96
97 dst_unit_type = unit_name_to_type(dst);
98 if (dst_unit_type != src_unit_type)
99 return log_notice_errno(SYNTHETIC_ERRNO(EXDEV),
100 "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
101 filename, dst);
102
103 return 0;
104 }
105
106 #define FOLLOW_MAX 8
107
108 static int unit_ids_map_get(
109 Hashmap *unit_ids_map,
110 const char *unit_name,
111 const char **ret_fragment_path) {
112
113 /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
114 *
115 * We distinguish the case where unit_name was not found in the hashmap at all, and the case where
116 * some symlink was broken.
117 *
118 * If a symlink target points to an instance name, then we also check for the template. */
119
120 const char *id = NULL;
121 int r;
122
123 for (unsigned n = 0; n < FOLLOW_MAX; n++) {
124 const char *t = hashmap_get(unit_ids_map, id ?: unit_name);
125 if (!t) {
126 _cleanup_free_ char *template = NULL;
127
128 if (!id)
129 return -ENOENT;
130
131 r = unit_name_template(id, &template);
132 if (r == -EINVAL)
133 return -ENXIO; /* we failed to find the symlink target */
134 if (r < 0)
135 return log_error_errno(r, "Failed to determine template name for %s: %m", id);
136
137 t = hashmap_get(unit_ids_map, template);
138 if (!t)
139 return -ENXIO;
140
141 /* We successfully switched from instanced name to a template, let's continue */
142 }
143
144 if (path_is_absolute(t)) {
145 if (ret_fragment_path)
146 *ret_fragment_path = t;
147 return 0;
148 }
149
150 id = t;
151 }
152
153 return -ELOOP;
154 }
155
156 static bool lookup_paths_mtime_exclude(const LookupPaths *lp, const char *path) {
157 /* Paths that are under our exclusive control. Users shall not alter those directly. */
158
159 return streq_ptr(path, lp->generator) ||
160 streq_ptr(path, lp->generator_early) ||
161 streq_ptr(path, lp->generator_late) ||
162 streq_ptr(path, lp->transient) ||
163 streq_ptr(path, lp->persistent_control) ||
164 streq_ptr(path, lp->runtime_control);
165 }
166
167 static bool lookup_paths_mtime_good(const LookupPaths *lp, usec_t mtime) {
168 char **dir;
169
170 STRV_FOREACH(dir, (char**) lp->search_path) {
171 struct stat st;
172
173 if (lookup_paths_mtime_exclude(lp, *dir))
174 continue;
175
176 /* Determine the latest lookup path modification time */
177 if (stat(*dir, &st) < 0) {
178 if (errno == ENOENT)
179 continue;
180
181 log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
182 continue;
183 }
184
185 if (timespec_load(&st.st_mtim) > mtime) {
186 log_debug_errno(errno, "Unit dir %s has changed, need to update cache.", *dir);
187 return false;
188 }
189 }
190
191 return true;
192 }
193
194 int unit_file_build_name_map(
195 const LookupPaths *lp,
196 usec_t *cache_mtime,
197 Hashmap **ret_unit_ids_map,
198 Hashmap **ret_unit_names_map,
199 Set **ret_path_cache) {
200
201 /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
202 * all aliases (i.e. the entry for a given key is a a list of all names which point to this key). The
203 * key is included in the value iff we saw a file or symlink with that name. In other words, if we
204 * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
205 * the unit itself is not loadable.
206 *
207 * At the same, build a cache of paths where to find units.
208 */
209
210 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
211 _cleanup_set_free_free_ Set *paths = NULL;
212 char **dir;
213 int r;
214 usec_t mtime = 0;
215
216 /* Before doing anything, check if the mtime that was passed is still valid. If
217 * yes, do nothing. If *cache_time == 0, always build the cache. */
218 if (cache_mtime && *cache_mtime > 0 && lookup_paths_mtime_good(lp, *cache_mtime))
219 return 0;
220
221 if (ret_path_cache) {
222 paths = set_new(&path_hash_ops);
223 if (!paths)
224 return log_oom();
225 }
226
227 STRV_FOREACH(dir, (char**) lp->search_path) {
228 struct dirent *de;
229 _cleanup_closedir_ DIR *d = NULL;
230 struct stat st;
231
232 d = opendir(*dir);
233 if (!d) {
234 if (errno != ENOENT)
235 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
236 continue;
237 }
238
239 /* Determine the latest lookup path modification time */
240 if (fstat(dirfd(d), &st) < 0)
241 return log_error_errno(errno, "Failed to fstat %s: %m", *dir);
242
243 if (!lookup_paths_mtime_exclude(lp, *dir))
244 mtime = MAX(mtime, timespec_load(&st.st_mtim));
245
246 FOREACH_DIRENT_ALL(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
247 char *filename;
248 _cleanup_free_ char *_filename_free = NULL, *simplified = NULL;
249 const char *suffix, *dst = NULL;
250 bool valid_unit_name;
251
252 valid_unit_name = unit_name_is_valid(de->d_name, UNIT_NAME_ANY);
253
254 /* We only care about valid units and dirs with certain suffixes, let's ignore the
255 * rest. */
256 if (!valid_unit_name &&
257 !ENDSWITH_SET(de->d_name, ".wants", ".requires", ".d"))
258 continue;
259
260 filename = path_join(*dir, de->d_name);
261 if (!filename)
262 return log_oom();
263
264 if (ret_path_cache) {
265 r = set_consume(paths, filename);
266 if (r < 0)
267 return log_oom();
268 /* We will still use filename below. This is safe because we know the set
269 * holds a reference. */
270 } else
271 _filename_free = filename; /* Make sure we free the filename. */
272
273 if (!valid_unit_name)
274 continue;
275 assert_se(suffix = strrchr(de->d_name, '.'));
276
277 /* search_path is ordered by priority (highest first). If the name is already mapped
278 * to something (incl. itself), it means that we have already seen it, and we should
279 * ignore it here. */
280 if (hashmap_contains(ids, de->d_name))
281 continue;
282
283 dirent_ensure_type(d, de);
284 if (de->d_type == DT_LNK) {
285 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
286 * limits the number of hops should be used to access the map. */
287
288 _cleanup_free_ char *target = NULL, *target_abs = NULL;
289
290 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
291 if (r < 0) {
292 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
293 *dir, de->d_name);
294 continue;
295 }
296
297 if (!path_is_absolute(target)) {
298 target_abs = path_join(*dir, target);
299 if (!target_abs)
300 return log_oom();
301
302 free_and_replace(target, target_abs);
303 }
304
305 /* Get rid of "." and ".." components in target path */
306 r = chase_symlinks(target, lp->root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
307 if (r < 0) {
308 log_warning_errno(r, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
309 filename, target);
310 continue;
311 }
312
313 /* Check if the symlink goes outside of our search path.
314 * If yes, it's a linked unit file or mask, and we don't care about the target name.
315 * Let's just store the link destination directly.
316 * If not, let's verify that it's a good symlink. */
317 char *tail = path_startswith_strv(simplified, lp->search_path);
318 if (tail) {
319 bool self_alias;
320
321 dst = basename(simplified);
322 self_alias = streq(dst, de->d_name);
323
324 if (is_path(tail))
325 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
326 "Suspicious symlink %s→%s, treating as alias.",
327 filename, simplified);
328
329 r = unit_validate_alias_symlink_and_warn(filename, simplified);
330 if (r < 0)
331 continue;
332
333 if (self_alias) {
334 /* A self-alias that has no effect */
335 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
336 __func__, *dir, de->d_name, dst);
337 continue;
338 }
339
340 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
341 } else {
342 dst = simplified;
343
344 log_debug("%s: linked unit file: %s/%s → %s", __func__, *dir, de->d_name, dst);
345 }
346
347 } else {
348 dst = filename;
349 log_debug("%s: normal unit file: %s", __func__, dst);
350 }
351
352 r = hashmap_put_strdup(&ids, de->d_name, dst);
353 if (r < 0)
354 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
355 de->d_name, dst);
356 }
357 }
358
359 /* Let's also put the names in the reverse db. */
360 Iterator it;
361 const char *dummy, *src;
362 HASHMAP_FOREACH_KEY(dummy, src, ids, it) {
363 const char *dst;
364
365 r = unit_ids_map_get(ids, src, &dst);
366 if (r < 0)
367 continue;
368
369 if (null_or_empty_path(dst) != 0)
370 continue;
371
372 /* Do not treat instance symlinks that point to the template as aliases */
373 if (unit_name_is_valid(basename(dst), UNIT_NAME_TEMPLATE) &&
374 unit_name_is_valid(src, UNIT_NAME_INSTANCE))
375 continue;
376
377 r = string_strv_hashmap_put(&names, basename(dst), src);
378 if (r < 0)
379 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
380 basename(dst), src);
381 }
382
383 if (cache_mtime)
384 *cache_mtime = mtime;
385 *ret_unit_ids_map = TAKE_PTR(ids);
386 *ret_unit_names_map = TAKE_PTR(names);
387 if (ret_path_cache)
388 *ret_path_cache = TAKE_PTR(paths);
389
390 return 1;
391 }
392
393 int unit_file_find_fragment(
394 Hashmap *unit_ids_map,
395 Hashmap *unit_name_map,
396 const char *unit_name,
397 const char **ret_fragment_path,
398 Set **ret_names) {
399
400 const char *fragment = NULL;
401 _cleanup_free_ char *template = NULL, *instance = NULL;
402 _cleanup_set_free_free_ Set *names = NULL;
403 char **t, **nnn;
404 int r, name_type;
405
406 /* Finds a fragment path, and returns the set of names:
407 * if we have …/foo.service and …/foo-alias.service→foo.service,
408 * and …/foo@.service and …/foo-alias@.service→foo@.service,
409 * and …/foo@inst.service,
410 * this should return:
411 * foo.service → …/foo.service, {foo.service, foo-alias.service},
412 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
413 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
414 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
415 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
416 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
417 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
418 */
419
420 name_type = unit_name_to_instance(unit_name, &instance);
421 if (name_type < 0)
422 return name_type;
423
424 names = set_new(&string_hash_ops);
425 if (!names)
426 return -ENOMEM;
427
428 /* The unit always has its own name if it's not a template. */
429 if (IN_SET(name_type, UNIT_NAME_PLAIN, UNIT_NAME_INSTANCE)) {
430 r = set_put_strdup(names, unit_name);
431 if (r < 0)
432 return r;
433 }
434
435 /* First try to load fragment under the original name */
436 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
437 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
438 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
439
440 if (fragment) {
441 /* Add any aliases of the original name to the set of names */
442 nnn = hashmap_get(unit_name_map, basename(fragment));
443 STRV_FOREACH(t, nnn) {
444 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*t, UNIT_NAME_TEMPLATE)) {
445 char *inst;
446
447 r = unit_name_replace_instance(*t, instance, &inst);
448 if (r < 0)
449 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", *t, instance);
450
451 if (!streq(unit_name, inst))
452 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
453
454 log_info("%s: %s+%s → %s", __func__, *t, instance, inst);
455 r = set_consume(names, inst);
456 } else {
457 if (!streq(unit_name, *t))
458 log_debug("%s: %s has alias %s", __func__, unit_name, *t);
459
460 r = set_put_strdup(names, *t);
461 }
462 if (r < 0)
463 return r;
464 }
465 }
466
467 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
468 /* Look for a fragment under the template name */
469
470 r = unit_name_template(unit_name, &template);
471 if (r < 0)
472 return log_error_errno(r, "Failed to determine template name: %m");
473
474 r = unit_ids_map_get(unit_ids_map, template, &fragment);
475 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
476 return log_debug_errno(r, "Cannot load template %s: %m", template);
477
478 if (fragment) {
479 /* Add any aliases of the original name to the set of names */
480 nnn = hashmap_get(unit_name_map, basename(fragment));
481 STRV_FOREACH(t, nnn) {
482 _cleanup_free_ char *inst = NULL;
483 const char *inst_fragment = NULL;
484
485 r = unit_name_replace_instance(*t, instance, &inst);
486 if (r < 0)
487 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", template, instance);
488
489 /* Exclude any aliases that point in some other direction. */
490 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
491 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
492 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
493
494 if (inst_fragment &&
495 !streq(basename(inst_fragment), basename(fragment))) {
496 log_debug("Instance %s has fragment %s and is not an alias of %s.",
497 inst, inst_fragment, unit_name);
498 continue;
499 }
500
501 if (!streq(unit_name, inst))
502 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
503 r = set_consume(names, TAKE_PTR(inst));
504 if (r < 0)
505 return r;
506 }
507 }
508 }
509
510 *ret_fragment_path = fragment;
511 *ret_names = TAKE_PTR(names);
512
513 // FIXME: if instance, consider any unit names with different template name
514 return 0;
515 }
516
517 static const char * const rlmap[] = {
518 "emergency", SPECIAL_EMERGENCY_TARGET,
519 "-b", SPECIAL_EMERGENCY_TARGET,
520 "rescue", SPECIAL_RESCUE_TARGET,
521 "single", SPECIAL_RESCUE_TARGET,
522 "-s", SPECIAL_RESCUE_TARGET,
523 "s", SPECIAL_RESCUE_TARGET,
524 "S", SPECIAL_RESCUE_TARGET,
525 "1", SPECIAL_RESCUE_TARGET,
526 "2", SPECIAL_MULTI_USER_TARGET,
527 "3", SPECIAL_MULTI_USER_TARGET,
528 "4", SPECIAL_MULTI_USER_TARGET,
529 "5", SPECIAL_GRAPHICAL_TARGET,
530 NULL
531 };
532
533 static const char * const rlmap_initrd[] = {
534 "emergency", SPECIAL_EMERGENCY_TARGET,
535 "rescue", SPECIAL_RESCUE_TARGET,
536 NULL
537 };
538
539 const char* runlevel_to_target(const char *word) {
540 const char * const *rlmap_ptr;
541 size_t i;
542
543 if (!word)
544 return NULL;
545
546 if (in_initrd()) {
547 word = startswith(word, "rd.");
548 if (!word)
549 return NULL;
550 }
551
552 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
553
554 for (i = 0; rlmap_ptr[i]; i += 2)
555 if (streq(word, rlmap_ptr[i]))
556 return rlmap_ptr[i+1];
557
558 return NULL;
559 }