]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/unit-file.c
namespace-util: introduce helper for combining unshare() + MS_SLAVE remount
[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 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 **unit_ids_map,
233 Hashmap **unit_names_map,
234 Set **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. The non-const parameters are for input
243 * and output. Existing contents will be freed before the new contents are stored.
244 */
245
246 _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
247 _cleanup_set_free_free_ Set *paths = NULL;
248 char **dir;
249 int r;
250 usec_t mtime = 0;
251
252 /* Before doing anything, check if the mtime that was passed is still valid. If
253 * yes, do nothing. If *cache_time == 0, always build the cache. */
254 if (cache_mtime && *cache_mtime > 0 && lookup_paths_mtime_good(lp, *cache_mtime))
255 return 0;
256
257 if (path_cache) {
258 paths = set_new(&path_hash_ops_free);
259 if (!paths)
260 return log_oom();
261 }
262
263 STRV_FOREACH(dir, (char**) lp->search_path) {
264 struct dirent *de;
265 _cleanup_closedir_ DIR *d = NULL;
266 struct stat st;
267
268 d = opendir(*dir);
269 if (!d) {
270 if (errno != ENOENT)
271 log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
272 continue;
273 }
274
275 /* Determine the latest lookup path modification time */
276 if (fstat(dirfd(d), &st) < 0)
277 return log_error_errno(errno, "Failed to fstat %s: %m", *dir);
278
279 if (!lookup_paths_mtime_exclude(lp, *dir))
280 mtime = MAX(mtime, timespec_load(&st.st_mtim));
281
282 FOREACH_DIRENT_ALL(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
283 char *filename;
284 _cleanup_free_ char *_filename_free = NULL, *simplified = NULL;
285 const char *suffix, *dst = NULL;
286 bool valid_unit_name;
287
288 valid_unit_name = unit_name_is_valid(de->d_name, UNIT_NAME_ANY);
289
290 /* We only care about valid units and dirs with certain suffixes, let's ignore the
291 * rest. */
292 if (!valid_unit_name &&
293 !ENDSWITH_SET(de->d_name, ".wants", ".requires", ".d"))
294 continue;
295
296 filename = path_join(*dir, de->d_name);
297 if (!filename)
298 return log_oom();
299
300 if (paths) {
301 r = set_consume(paths, filename);
302 if (r < 0)
303 return log_oom();
304 /* We will still use filename below. This is safe because we know the set
305 * holds a reference. */
306 } else
307 _filename_free = filename; /* Make sure we free the filename. */
308
309 if (!valid_unit_name)
310 continue;
311 assert_se(suffix = strrchr(de->d_name, '.'));
312
313 /* search_path is ordered by priority (highest first). If the name is already mapped
314 * to something (incl. itself), it means that we have already seen it, and we should
315 * ignore it here. */
316 if (hashmap_contains(ids, de->d_name))
317 continue;
318
319 dirent_ensure_type(d, de);
320 if (de->d_type == DT_LNK) {
321 /* We don't explicitly check for alias loops here. unit_ids_map_get() which
322 * limits the number of hops should be used to access the map. */
323
324 _cleanup_free_ char *target = NULL;
325
326 r = readlinkat_malloc(dirfd(d), de->d_name, &target);
327 if (r < 0) {
328 log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
329 *dir, de->d_name);
330 continue;
331 }
332
333 const bool is_abs = path_is_absolute(target);
334 if (lp->root_dir || !is_abs) {
335 char *target_abs = path_join(is_abs ? lp->root_dir : *dir, target);
336 if (!target_abs)
337 return log_oom();
338
339 free_and_replace(target, target_abs);
340 }
341
342 /* Get rid of "." and ".." components in target path */
343 r = chase_symlinks(target, lp->root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
344 if (r < 0) {
345 log_warning_errno(r, "Failed to resolve symlink %s pointing to %s, ignoring: %m",
346 filename, target);
347 continue;
348 }
349
350 /* Check if the symlink goes outside of our search path.
351 * If yes, it's a linked unit file or mask, and we don't care about the target name.
352 * Let's just store the link destination directly.
353 * If not, let's verify that it's a good symlink. */
354 char *tail = path_startswith_strv(simplified, lp->search_path);
355 if (tail) {
356 bool self_alias;
357
358 dst = basename(simplified);
359 self_alias = streq(dst, de->d_name);
360
361 if (is_path(tail))
362 log_full(self_alias ? LOG_DEBUG : LOG_WARNING,
363 "Suspicious symlink %s→%s, treating as alias.",
364 filename, simplified);
365
366 r = unit_validate_alias_symlink_and_warn(filename, simplified);
367 if (r < 0)
368 continue;
369
370 if (self_alias) {
371 /* A self-alias that has no effect */
372 log_debug("%s: self-alias: %s/%s → %s, ignoring.",
373 __func__, *dir, de->d_name, dst);
374 continue;
375 }
376
377 log_debug("%s: alias: %s/%s → %s", __func__, *dir, de->d_name, dst);
378 } else {
379 dst = simplified;
380
381 log_debug("%s: linked unit file: %s/%s → %s", __func__, *dir, de->d_name, dst);
382 }
383
384 } else {
385 dst = filename;
386 log_debug("%s: normal unit file: %s", __func__, dst);
387 }
388
389 r = hashmap_put_strdup(&ids, de->d_name, dst);
390 if (r < 0)
391 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
392 de->d_name, dst);
393 }
394 }
395
396 /* Let's also put the names in the reverse db. */
397 Iterator it;
398 const char *dummy, *src;
399 HASHMAP_FOREACH_KEY(dummy, src, ids, it) {
400 const char *dst;
401
402 r = unit_ids_map_get(ids, src, &dst);
403 if (r < 0)
404 continue;
405
406 if (null_or_empty_path(dst) != 0)
407 continue;
408
409 /* Do not treat instance symlinks that point to the template as aliases */
410 if (unit_name_is_valid(basename(dst), UNIT_NAME_TEMPLATE) &&
411 unit_name_is_valid(src, UNIT_NAME_INSTANCE))
412 continue;
413
414 r = string_strv_hashmap_put(&names, basename(dst), src);
415 if (r < 0)
416 return log_warning_errno(r, "Failed to add entry to hashmap (%s→%s): %m",
417 basename(dst), src);
418 }
419
420 if (cache_mtime)
421 *cache_mtime = mtime;
422
423 hashmap_free_and_replace(*unit_ids_map, ids);
424 hashmap_free_and_replace(*unit_names_map, names);
425 if (path_cache)
426 set_free_and_replace(*path_cache, paths);
427
428 return 1;
429 }
430
431 int unit_file_find_fragment(
432 Hashmap *unit_ids_map,
433 Hashmap *unit_name_map,
434 const char *unit_name,
435 const char **ret_fragment_path,
436 Set **ret_names) {
437
438 const char *fragment = NULL;
439 _cleanup_free_ char *template = NULL, *instance = NULL;
440 _cleanup_set_free_free_ Set *names = NULL;
441 char **t, **nnn;
442 int r, name_type;
443
444 /* Finds a fragment path, and returns the set of names:
445 * if we have …/foo.service and …/foo-alias.service→foo.service,
446 * and …/foo@.service and …/foo-alias@.service→foo@.service,
447 * and …/foo@inst.service,
448 * this should return:
449 * foo.service → …/foo.service, {foo.service, foo-alias.service},
450 * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
451 * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
452 * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
453 * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
454 * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
455 * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
456 */
457
458 name_type = unit_name_to_instance(unit_name, &instance);
459 if (name_type < 0)
460 return name_type;
461
462 names = set_new(&string_hash_ops);
463 if (!names)
464 return -ENOMEM;
465
466 /* The unit always has its own name if it's not a template. */
467 if (IN_SET(name_type, UNIT_NAME_PLAIN, UNIT_NAME_INSTANCE)) {
468 r = set_put_strdup(&names, unit_name);
469 if (r < 0)
470 return r;
471 }
472
473 /* First try to load fragment under the original name */
474 r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
475 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
476 return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
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 if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*t, UNIT_NAME_TEMPLATE)) {
483 char *inst;
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", *t, instance);
488
489 if (!streq(unit_name, inst))
490 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
491
492 log_info("%s: %s+%s → %s", __func__, *t, instance, inst);
493 r = set_consume(names, inst);
494 } else {
495 if (!streq(unit_name, *t))
496 log_debug("%s: %s has alias %s", __func__, unit_name, *t);
497
498 r = set_put_strdup(&names, *t);
499 }
500 if (r < 0)
501 return r;
502 }
503 }
504
505 if (!fragment && name_type == UNIT_NAME_INSTANCE) {
506 /* Look for a fragment under the template name */
507
508 r = unit_name_template(unit_name, &template);
509 if (r < 0)
510 return log_error_errno(r, "Failed to determine template name: %m");
511
512 r = unit_ids_map_get(unit_ids_map, template, &fragment);
513 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
514 return log_debug_errno(r, "Cannot load template %s: %m", template);
515
516 if (fragment) {
517 /* Add any aliases of the original name to the set of names */
518 nnn = hashmap_get(unit_name_map, basename(fragment));
519 STRV_FOREACH(t, nnn) {
520 _cleanup_free_ char *inst = NULL;
521 const char *inst_fragment = NULL;
522
523 r = unit_name_replace_instance(*t, instance, &inst);
524 if (r < 0)
525 return log_debug_errno(r, "Cannot build instance name %s+%s: %m", template, instance);
526
527 /* Exclude any aliases that point in some other direction. */
528 r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
529 if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
530 return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
531
532 if (inst_fragment &&
533 !streq(basename(inst_fragment), basename(fragment))) {
534 log_debug("Instance %s has fragment %s and is not an alias of %s.",
535 inst, inst_fragment, unit_name);
536 continue;
537 }
538
539 if (!streq(unit_name, inst))
540 log_debug("%s: %s has alias %s", __func__, unit_name, inst);
541 r = set_consume(names, TAKE_PTR(inst));
542 if (r < 0)
543 return r;
544 }
545 }
546 }
547
548 *ret_fragment_path = fragment;
549 *ret_names = TAKE_PTR(names);
550
551 // FIXME: if instance, consider any unit names with different template name
552 return 0;
553 }
554
555 static const char * const rlmap[] = {
556 "emergency", SPECIAL_EMERGENCY_TARGET,
557 "-b", SPECIAL_EMERGENCY_TARGET,
558 "rescue", SPECIAL_RESCUE_TARGET,
559 "single", SPECIAL_RESCUE_TARGET,
560 "-s", SPECIAL_RESCUE_TARGET,
561 "s", SPECIAL_RESCUE_TARGET,
562 "S", SPECIAL_RESCUE_TARGET,
563 "1", SPECIAL_RESCUE_TARGET,
564 "2", SPECIAL_MULTI_USER_TARGET,
565 "3", SPECIAL_MULTI_USER_TARGET,
566 "4", SPECIAL_MULTI_USER_TARGET,
567 "5", SPECIAL_GRAPHICAL_TARGET,
568 NULL
569 };
570
571 static const char * const rlmap_initrd[] = {
572 "emergency", SPECIAL_EMERGENCY_TARGET,
573 "rescue", SPECIAL_RESCUE_TARGET,
574 NULL
575 };
576
577 const char* runlevel_to_target(const char *word) {
578 const char * const *rlmap_ptr;
579 size_t i;
580
581 if (!word)
582 return NULL;
583
584 if (in_initrd()) {
585 word = startswith(word, "rd.");
586 if (!word)
587 return NULL;
588 }
589
590 rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
591
592 for (i = 0; rlmap_ptr[i]; i += 2)
593 if (streq(word, rlmap_ptr[i]))
594 return rlmap_ptr[i+1];
595
596 return NULL;
597 }