• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 14554080340

19 Apr 2025 11:46AM UTC coverage: 72.101% (-0.03%) from 72.13%
14554080340

push

github

web-flow
Add two new paragraphs to coding style about header files (#37188)

296880 of 411754 relevant lines covered (72.1%)

687547.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.78
/src/shared/unit-file.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include "sd-id128.h"
4

5
#include "chase.h"
6
#include "dirent-util.h"
7
#include "fd-util.h"
8
#include "fs-util.h"
9
#include "initrd-util.h"
10
#include "log.h"
11
#include "macro.h"
12
#include "path-lookup.h"
13
#include "set.h"
14
#include "special.h"
15
#include "stat-util.h"
16
#include "string-util.h"
17
#include "strv.h"
18
#include "unit-file.h"
19

20
int unit_symlink_name_compatible(const char *symlink, const char *target, bool instance_propagation) {
14,399✔
21
        _cleanup_free_ char *template = NULL;
14,399✔
22
        int r, un_type1, un_type2;
14,399✔
23

24
        un_type1 = unit_name_classify(symlink);
14,399✔
25

26
        /* The straightforward case: the symlink name matches the target and we have a valid unit */
27
        if (streq(symlink, target) &&
14,399✔
28
            (un_type1 & (UNIT_NAME_PLAIN | UNIT_NAME_INSTANCE)))
13,601✔
29
                return 1;
30

31
        r = unit_name_template(symlink, &template);
801✔
32
        if (r == -EINVAL)
801✔
33
                return 0; /* Not a template */
34
        if (r < 0)
773✔
35
                return r;
36

37
        un_type2 = unit_name_classify(target);
773✔
38

39
        /* An instance name points to a target that is just the template name */
40
        if (un_type1 == UNIT_NAME_INSTANCE &&
773✔
41
            un_type2 == UNIT_NAME_TEMPLATE &&
773✔
42
            streq(template, target))
740✔
43
                return 1;
44

45
        /* foo@.target.requires/bar@.service: instance will be propagated */
46
        if (instance_propagation &&
38✔
47
            un_type1 == UNIT_NAME_TEMPLATE &&
38✔
48
            un_type2 == UNIT_NAME_TEMPLATE &&
2✔
49
            streq(template, target))
2✔
50
                return 1;
1✔
51

52
        return 0;
53
}
54

55
int unit_validate_alias_symlink_or_warn(int log_level, const char *filename, const char *target) {
11,404✔
56
        _cleanup_free_ char *src = NULL, *dst = NULL;
×
57
        _cleanup_free_ char *src_instance = NULL, *dst_instance = NULL;
11,404✔
58
        UnitType src_unit_type, dst_unit_type;
11,404✔
59
        UnitNameFlags src_name_type, dst_name_type;
11,404✔
60
        int r;
11,404✔
61

62
        /* Check if the *alias* symlink is valid. This applies to symlinks like
63
         * /etc/systemd/system/dbus.service → dbus-broker.service, but not to .wants or .requires symlinks
64
         * and such. Neither does this apply to symlinks which *link* units, i.e. symlinks to outside of the
65
         * unit lookup path.
66
         *
67
         * -EINVAL is returned if the something is wrong with the source filename or the source unit type is
68
         *         not allowed to symlink,
69
         * -EXDEV if the target filename is not a valid unit name or doesn't match the source,
70
         * -ELOOP for an alias to self.
71
         */
72

73
        r = path_extract_filename(filename, &src);
11,404✔
74
        if (r < 0)
11,404✔
75
                return r;
76

77
        r = path_extract_filename(target, &dst);
11,404✔
78
        if (r < 0)
11,404✔
79
                return r;
80

81
        /* src checks */
82

83
        src_name_type = unit_name_to_instance(src, &src_instance);
11,404✔
84
        if (src_name_type < 0)
11,404✔
85
                return log_full_errno(log_level, src_name_type,
×
86
                                      "%s: not a valid unit name \"%s\": %m", filename, src);
87

88
        src_unit_type = unit_name_to_type(src);
11,404✔
89
        assert(src_unit_type >= 0); /* unit_name_to_instance() checked the suffix already */
11,404✔
90

91
        if (!unit_type_may_alias(src_unit_type))
11,404✔
92
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EINVAL),
282✔
93
                                      "%s: symlinks are not allowed for units of this type, rejecting.",
94
                                      filename);
95

96
        if (src_name_type != UNIT_NAME_PLAIN &&
11,122✔
97
            !unit_type_may_template(src_unit_type))
11,122✔
98
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EINVAL),
×
99
                                      "%s: templates not allowed for %s units, rejecting.",
100
                                      filename, unit_type_to_string(src_unit_type));
101

102
        /* dst checks */
103

104
        if (streq(src, dst))
11,122✔
105
                return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1,698✔
106
                                       "%s: unit self-alias: %s → %s, ignoring.",
107
                                       filename, src, dst);
108

109
        dst_name_type = unit_name_to_instance(dst, &dst_instance);
9,424✔
110
        if (dst_name_type < 0)
9,424✔
111
                return log_full_errno(log_level, dst_name_type == -EINVAL ? SYNTHETIC_ERRNO(EXDEV) : dst_name_type,
1✔
112
                                      "%s points to \"%s\" which is not a valid unit name: %m",
113
                                      filename, dst);
114

115
        if (!(dst_name_type == src_name_type ||
9,423✔
116
              (src_name_type == UNIT_NAME_INSTANCE && dst_name_type == UNIT_NAME_TEMPLATE)))
114✔
117
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EXDEV),
13✔
118
                                      "%s: symlink target name type \"%s\" does not match source, rejecting.",
119
                                      filename, dst);
120

121
        if (dst_name_type == UNIT_NAME_INSTANCE) {
9,309✔
122
                assert(src_instance);
13✔
123
                assert(dst_instance);
13✔
124
                if (!streq(src_instance, dst_instance))
13✔
125
                        return log_full_errno(log_level, SYNTHETIC_ERRNO(EXDEV),
4✔
126
                                              "%s: unit symlink target \"%s\" instance name doesn't match, rejecting.",
127
                                              filename, dst);
128
        }
129

130
        dst_unit_type = unit_name_to_type(dst);
9,406✔
131
        if (dst_unit_type != src_unit_type)
9,406✔
132
                return log_full_errno(log_level, SYNTHETIC_ERRNO(EXDEV),
11✔
133
                                      "%s: symlink target \"%s\" has incompatible suffix, rejecting.",
134
                                      filename, dst);
135

136
        return 0;
137
}
138

139
#define FOLLOW_MAX 8
140

141
static int unit_ids_map_get(
346,665✔
142
                Hashmap *unit_ids_map,
143
                const char *unit_name,
144
                const char **ret_fragment_path) {
145

146
        /* Resolve recursively until we hit an absolute path, i.e. a non-aliased unit.
147
         *
148
         * We distinguish the case where unit_name was not found in the hashmap at all, and the case where
149
         * some symlink was broken.
150
         *
151
         * If a symlink target points to an instance name, then we also check for the template. */
152

153
        const char *id = NULL;
346,665✔
154
        int r;
346,665✔
155

156
        for (unsigned n = 0; n < FOLLOW_MAX; n++) {
355,807✔
157
                const char *t = hashmap_get(unit_ids_map, id ?: unit_name);
355,807✔
158
                if (!t) {
355,807✔
159
                        _cleanup_free_ char *template = NULL;
55,417✔
160

161
                        if (!id)
55,417✔
162
                                return -ENOENT;
163

164
                        r = unit_name_template(id, &template);
×
165
                        if (r == -EINVAL)
×
166
                                return -ENXIO; /* we failed to find the symlink target */
167
                        if (r < 0)
×
168
                                return log_error_errno(r, "Failed to determine template name for %s: %m", id);
×
169

170
                        t = hashmap_get(unit_ids_map, template);
×
171
                        if (!t)
×
172
                                return -ENXIO;
173

174
                        /* We successfully switched from instanced name to a template, let's continue */
175
                }
176

177
                if (path_is_absolute(t)) {
300,390✔
178
                        if (ret_fragment_path)
291,248✔
179
                                *ret_fragment_path = t;
291,248✔
180
                        return 0;
291,248✔
181
                }
182

183
                id = t;
9,142✔
184
        }
185

186
        return -ELOOP;
187
}
188

189
static bool lookup_paths_mtime_exclude(const LookupPaths *lp, const char *path) {
1,223,533✔
190
        /* Paths that are under our exclusive control. Users shall not alter those directly. */
191

192
        return streq_ptr(path, lp->generator) ||
1,223,533✔
193
               streq_ptr(path, lp->generator_early) ||
1,144,194✔
194
               streq_ptr(path, lp->generator_late) ||
1,064,855✔
195
               streq_ptr(path, lp->transient) ||
985,516✔
196
               streq_ptr(path, lp->persistent_control) ||
2,129,710✔
197
               streq_ptr(path, lp->runtime_control);
826,838✔
198
}
199

200
#define HASH_KEY SD_ID128_MAKE(4e,86,1b,e3,39,b3,40,46,98,5d,b8,11,34,8f,c3,c1)
201

202
bool lookup_paths_timestamp_hash_same(const LookupPaths *lp, uint64_t timestamp_hash, uint64_t *ret_new) {
80,054✔
203
        struct siphash state;
80,054✔
204

205
        siphash24_init(&state, HASH_KEY.bytes);
80,054✔
206

207
        STRV_FOREACH(dir, lp->search_path) {
1,303,587✔
208
                struct stat st;
1,223,533✔
209

210
                if (lookup_paths_mtime_exclude(lp, *dir))
1,223,533✔
211
                        continue;
946,451✔
212

213
                /* Determine the latest lookup path modification time */
214
                if (stat(*dir, &st) < 0) {
747,499✔
215
                        if (errno == ENOENT)
470,417✔
216
                                continue;
470,417✔
217

218
                        log_debug_errno(errno, "Failed to stat %s, ignoring: %m", *dir);
×
219
                        continue;
×
220
                }
221

222
                siphash24_compress_usec_t(timespec_load(&st.st_mtim), &state);
277,082✔
223
        }
224

225
        uint64_t updated = siphash24_finalize(&state);
80,054✔
226
        if (ret_new)
80,054✔
227
                *ret_new = updated;
77,269✔
228
        if (updated != timestamp_hash)
80,054✔
229
                log_debug("Modification times have changed, need to update cache.");
711✔
230
        return updated == timestamp_hash;
80,054✔
231
}
232

233
static int directory_name_is_valid(const char *name) {
25,019✔
234

235
        /* Accept a directory whose name is a valid unit file name ending in .wants/, .requires/,
236
         * .upholds/ or .d/ */
237

238
        FOREACH_STRING(suffix, ".wants", ".requires", ".upholds", ".d") {
67,293✔
239
                _cleanup_free_ char *chopped = NULL;
19,579✔
240
                const char *e;
61,853✔
241

242
                e = endswith(name, suffix);
61,853✔
243
                if (!e)
61,853✔
244
                        continue;
42,274✔
245

246
                chopped = strndup(name, e - name);
19,579✔
247
                if (!chopped)
19,579✔
248
                        return log_oom();
×
249

250
                if (unit_name_is_valid(chopped, UNIT_NAME_ANY) ||
20,095✔
251
                    unit_type_from_string(chopped) >= 0)
516✔
252
                        return true;
253
        }
254

255
        return false;
5,440✔
256
}
257

258
int unit_file_resolve_symlink(
12,356✔
259
                const char *root_dir,
260
                char **search_path,
261
                const char *dir,
262
                int dirfd,
263
                const char *filename,
264
                bool resolve_destination_target,
265
                char **ret_destination) {
266

267
        _cleanup_free_ char *target = NULL, *simplified = NULL, *dst = NULL, *_dir = NULL, *_filename = NULL;
12,356✔
268
        int r;
12,356✔
269

270
        /* This can be called with either dir+dirfd valid and filename just a name,
271
         * or !dir && dirfd==AT_FDCWD, and filename being a full path.
272
         *
273
         * If resolve_destination_target is true, an absolute path will be returned.
274
         * If not, an absolute path is returned for linked unit files, and a relative
275
         * path otherwise.
276
         *
277
         * Returns an error, false if this is an alias, true if it's a linked unit file. */
278

279
        assert(filename);
12,356✔
280
        assert(ret_destination);
12,356✔
281
        assert(dir || path_is_absolute(filename));
12,972✔
282
        assert(dirfd >= 0 || dirfd == AT_FDCWD);
12,356✔
283

284
        r = readlinkat_malloc(dirfd, filename, &target);
12,356✔
285
        if (r < 0)
12,356✔
286
                return log_warning_errno(r, "Failed to read symlink %s%s%s: %m",
×
287
                                         dir, dir ? "/" : "", filename);
288

289
        if (!dir) {
12,356✔
290
                r = path_extract_directory(filename, &_dir);
616✔
291
                if (r < 0)
616✔
292
                        return r;
293
                dir = _dir;
616✔
294

295
                r = path_extract_filename(filename, &_filename);
616✔
296
                if (r < 0)
616✔
297
                        return r;
298
                if (r == O_DIRECTORY)
616✔
299
                        return log_warning_errno(SYNTHETIC_ERRNO(EISDIR),
×
300
                                                 "Unexpected path to a directory \"%s\", refusing.", filename);
301
                filename = _filename;
616✔
302
        }
303

304
        bool is_abs = path_is_absolute(target);
12,356✔
305
        if (root_dir || !is_abs) {
12,356✔
306
                char *target_abs = path_join(is_abs ? root_dir : dir, target);
16,306✔
307
                if (!target_abs)
8,170✔
308
                        return log_oom();
12,356✔
309

310
                free_and_replace(target, target_abs);
8,170✔
311
        }
312

313
        /* Get rid of "." and ".." components in target path */
314
        r = chase(target, root_dir, CHASE_NOFOLLOW | CHASE_NONEXISTENT, &simplified, NULL);
12,356✔
315
        if (r < 0)
12,356✔
316
                return log_warning_errno(r, "Failed to resolve symlink %s/%s pointing to %s: %m",
×
317
                                         dir, filename, target);
318

319
        assert(path_is_absolute(simplified));
12,356✔
320

321
        /* Check if the symlink remain inside of our search path.
322
         * If yes, it is an alias. Verify that it is valid.
323
         *
324
         * If no, then this is a linked unit file or mask, and we don't care about the target name
325
         * when loading units, and we return the link *source* (resolve_destination_target == false);
326
         * When this is called for installation purposes, we want the final destination,
327
         * so we return the *target*.
328
         */
329
        const char *tail = path_startswith_strv(simplified, search_path);
12,356✔
330
        if (tail) {  /* An alias */
12,356✔
331
                _cleanup_free_ char *target_name = NULL;
11,255✔
332

333
                r = path_extract_filename(simplified, &target_name);
11,255✔
334
                if (r < 0)
11,255✔
335
                        return r;
336

337
                r = unit_validate_alias_symlink_or_warn(LOG_NOTICE, filename, simplified);
11,255✔
338
                if (r < 0)
11,255✔
339
                        return r;
340
                if (is_path(tail))
9,277✔
341
                        log_warning("Suspicious symlink %s/%s %s %s, treating as alias.",
×
342
                                    dir, filename, glyph(GLYPH_ARROW_RIGHT), simplified);
343

344
                dst = resolve_destination_target ? TAKE_PTR(simplified) : TAKE_PTR(target_name);
9,277✔
345

346
        } else {
347
                log_debug("Linked unit file: %s/%s %s %s", dir, filename, glyph(GLYPH_ARROW_RIGHT), simplified);
1,101✔
348

349
                if (resolve_destination_target)
1,101✔
350
                        dst = TAKE_PTR(simplified);
166✔
351
                else {
352
                        dst = path_join(dir, filename);
935✔
353
                        if (!dst)
935✔
354
                                return log_oom();
×
355
                }
356
        }
357

358
        *ret_destination = TAKE_PTR(dst);
10,378✔
359
        return !tail;  /* true if linked unit file */
10,378✔
360
}
361

362
int unit_file_build_name_map(
77,282✔
363
                const LookupPaths *lp,
364
                uint64_t *cache_timestamp_hash,
365
                Hashmap **unit_ids_map,
366
                Hashmap **unit_names_map,
367
                Set **path_cache) {
368

369
        /* Build two mappings: any name → main unit (i.e. the end result of symlink resolution), unit name →
370
         * all aliases (i.e. the entry for a given key is a list of all names which point to this key). The
371
         * key is included in the value iff we saw a file or symlink with that name. In other words, if we
372
         * have a key, but it is not present in the value for itself, there was an alias pointing to it, but
373
         * the unit itself is not loadable.
374
         *
375
         * At the same, build a cache of paths where to find units. The non-const parameters are for input
376
         * and output. Existing contents will be freed before the new contents are stored.
377
         */
378

379
        _cleanup_hashmap_free_ Hashmap *ids = NULL, *names = NULL;
77,282✔
380
        _cleanup_set_free_ Set *paths = NULL;
77,282✔
381
        _cleanup_strv_free_ char **expanded_search_path = NULL;
×
382
        uint64_t timestamp_hash;
77,282✔
383
        int r;
77,282✔
384

385
        /* Before doing anything, check if the timestamp hash that was passed is still valid.
386
         * If yes, do nothing. */
387
        if (cache_timestamp_hash &&
154,551✔
388
            lookup_paths_timestamp_hash_same(lp, *cache_timestamp_hash, &timestamp_hash))
77,269✔
389
                return 0;
390

391
        /* The timestamp hash is now set based on the mtimes from before when we start reading files.
392
         * If anything is modified concurrently, we'll consider the cache outdated. */
393

394
        if (path_cache) {
724✔
395
                paths = set_new(&path_hash_ops_free);
712✔
396
                if (!paths)
712✔
397
                        return log_oom();
×
398
        }
399

400
        /* Go over all our search paths, chase their symlinks and store the result in the
401
         * expanded_search_path list.
402
         *
403
         * This is important for cases where any of the unit directories itself are symlinks into other
404
         * directories and would therefore cause all of the unit files to be recognized as linked units.
405
         *
406
         * This is important for distributions such as NixOS where most paths in /etc/ are symlinks to some
407
         * other location on the filesystem (e.g.  into /nix/store/).
408
         *
409
         * Search paths are ordered by priority (highest first), and we need to maintain this order.
410
         * If a resolved path is already in the list, we don't need to include.
411
         *
412
         * Note that we build a list that contains both the original paths and the resolved symlinks:
413
         * we need the latter for the case where the directory is symlinked, as described above, and
414
         * the former for the case where some unit file alias is a dangling symlink that points to one
415
         * of the "original" directories (and can't be followed).
416
         */
417
        STRV_FOREACH(dir, lp->search_path) {
10,434✔
418
                _cleanup_free_ char *resolved_dir = NULL;
9,710✔
419

420
                r = strv_extend(&expanded_search_path, *dir);
9,710✔
421
                if (r < 0)
9,710✔
422
                        return log_oom();
×
423

424
                r = chase(*dir, NULL, 0, &resolved_dir, NULL);
9,710✔
425
                if (r < 0) {
9,710✔
426
                        if (r != -ENOENT)
7,080✔
427
                                log_warning_errno(r, "Failed to resolve symlink %s, ignoring: %m", *dir);
×
428
                        continue;
7,080✔
429
                }
430

431
                if (strv_contains(expanded_search_path, resolved_dir))
2,630✔
432
                        continue;
2,627✔
433

434
                if (strv_consume(&expanded_search_path, TAKE_PTR(resolved_dir)) < 0)
3✔
435
                        return log_oom();
×
436
        }
437

438
        STRV_FOREACH(dir, lp->search_path) {
10,434✔
439
                _cleanup_closedir_ DIR *d = NULL;
86,992✔
440

441
                d = opendir(*dir);
9,710✔
442
                if (!d) {
9,710✔
443
                        if (errno != ENOENT)
7,080✔
444
                                log_warning_errno(errno, "Failed to open \"%s\", ignoring: %m", *dir);
×
445
                        continue;
7,080✔
446
                }
447

448
                FOREACH_DIRENT_ALL(de, d, log_warning_errno(errno, "Failed to read \"%s\", ignoring: %m", *dir)) {
360,172✔
449
                        _unused_ _cleanup_free_ char *_filename_free = NULL;
264,214✔
450
                        char *filename;
357,542✔
451
                        _cleanup_free_ char *dst = NULL;
93,328✔
452
                        bool symlink_to_dir = false;
357,542✔
453

454
                        /* We only care about valid units and dirs with certain suffixes, let's ignore the
455
                         * rest. */
456

457
                        if (de->d_type == DT_REG) {
357,542✔
458

459
                                /* Accept a regular file whose name is a valid unit file name. */
460
                                if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
318,698✔
461
                                        continue;
62,336✔
462

463
                        } else if (de->d_type == DT_DIR) {
38,844✔
464

465
                                if (!paths) /* Skip directories early unless path_cache is requested */
25,547✔
466
                                        continue;
528✔
467

468
                                r = directory_name_is_valid(de->d_name);
25,019✔
469
                                if (r < 0)
25,019✔
470
                                        return r;
471
                                if (r == 0)
25,019✔
472
                                        continue;
5,440✔
473

474
                        } else if (de->d_type == DT_LNK) {
13,297✔
475

476
                                /* Accept a symlink file whose name is a valid unit file name or
477
                                 * ending in .wants/, .requires/ or .d/. */
478

479
                                if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY)) {
13,297✔
480
                                        _cleanup_free_ char *target = NULL;
×
481

482
                                        if (!paths) /* Skip symlink to a directory early unless path_cache is requested */
×
483
                                                continue;
×
484

485
                                        r = directory_name_is_valid(de->d_name);
×
486
                                        if (r < 0)
×
487
                                                return r;
×
488
                                        if (r == 0)
×
489
                                                continue;
×
490

491
                                        r = readlinkat_malloc(dirfd(d), de->d_name, &target);
×
492
                                        if (r < 0) {
×
493
                                                log_warning_errno(r, "Failed to read symlink %s/%s, ignoring: %m",
×
494
                                                                  *dir, de->d_name);
495
                                                continue;
×
496
                                        }
497

498
                                        r = is_dir(target, /* follow = */ true);
×
499
                                        if (r <= 0)
×
500
                                                continue;
×
501

502
                                        symlink_to_dir = true;
×
503
                                }
504

505
                        } else
506
                                continue;
×
507

508
                        filename = path_join(*dir, de->d_name);
289,238✔
509
                        if (!filename)
289,238✔
510
                                return log_oom();
×
511

512
                        if (paths) {
289,238✔
513
                                r = set_put(paths, filename);
284,898✔
514
                                if (r < 0)
284,898✔
515
                                        return log_oom();
×
516
                                if (r == 0)
284,898✔
517
                                        _filename_free = filename; /* Make sure we free the filename. */
×
518
                        } else
519
                                _filename_free = filename; /* Make sure we free the filename. */
520

521
                        if (de->d_type == DT_DIR || (de->d_type == DT_LNK && symlink_to_dir))
289,238✔
522
                                continue;
19,579✔
523

524
                        assert(IN_SET(de->d_type, DT_REG, DT_LNK));
269,659✔
525

526
                        /* search_path is ordered by priority (highest first). If the name is already mapped
527
                         * to something (incl. itself), it means that we have already seen it, and we should
528
                         * ignore it here. */
529
                        if (hashmap_contains(ids, de->d_name))
269,659✔
530
                                continue;
3,468✔
531

532
                        if (de->d_type == DT_LNK) {
266,191✔
533
                                /* We don't explicitly check for alias loops here. unit_ids_map_get() which
534
                                 * limits the number of hops should be used to access the map. */
535

536
                                r = unit_file_resolve_symlink(lp->root_dir, expanded_search_path,
11,740✔
537
                                                              *dir, dirfd(d), de->d_name,
538
                                                              /* resolve_destination_target= */ false,
539
                                                              &dst);
540
                                if (r == -ENOMEM)
11,740✔
541
                                        return r;
542
                                if (r < 0)  /* we ignore other errors here */
11,740✔
543
                                        continue;
1,977✔
544

545
                        } else {
546
                                dst = TAKE_PTR(_filename_free); /* Grab the copy we made previously, if available. */
254,451✔
547
                                if (!dst) {
254,451✔
548
                                        dst = strdup(filename);
250,385✔
549
                                        if (!dst)
250,385✔
550
                                                return log_oom();
×
551
                                }
552

553
                                log_debug("%s: normal unit file: %s", __func__, dst);
254,451✔
554
                        }
555

556
                        _cleanup_free_ char *key = strdup(de->d_name);
264,214✔
557
                        if (!key)
264,214✔
558
                                return log_oom();
×
559

560
                        r = hashmap_ensure_put(&ids, &string_hash_ops_free_free, key, dst);
264,214✔
561
                        if (r < 0)
264,214✔
562
                                return log_warning_errno(r, "Failed to add entry to hashmap (%s%s%s): %m",
×
563
                                                         de->d_name, glyph(GLYPH_ARROW_RIGHT), dst);
564
                        key = dst = NULL;
264,214✔
565
                }
566
        }
567

568
        /* Let's also put the names in the reverse db. */
569
        const char *dummy, *src;
724✔
570
        HASHMAP_FOREACH_KEY(dummy, src, ids) {
264,938✔
571
                _cleanup_free_ char *inst = NULL, *dst_inst = NULL;
264,214✔
572
                const char *dst;
264,214✔
573

574
                r = unit_ids_map_get(ids, src, &dst);
264,214✔
575
                if (r < 0)
264,214✔
576
                        continue;
×
577

578
                if (null_or_empty_path(dst) != 0)
264,214✔
579
                        continue;
927✔
580

581
                dst = basename(dst);
263,287✔
582

583
                /* If we have an symlink from an instance name to a template name, it is an alias just for
584
                 * this specific instance, foo@id.service ↔ template@id.service. */
585
                if (unit_name_is_valid(dst, UNIT_NAME_TEMPLATE)) {
263,287✔
586
                        UnitNameFlags t = unit_name_to_instance(src, &inst);
34,653✔
587
                        if (t < 0)
34,653✔
588
                                return log_error_errno(t, "Failed to extract instance part from %s: %m", src);
×
589
                        if (t == UNIT_NAME_INSTANCE) {
34,653✔
590
                                r = unit_name_replace_instance(dst, inst, &dst_inst);
90✔
591
                                if (r < 0) {
90✔
592
                                        /* This might happen e.g. if the combined length is too large.
593
                                         * Let's not make too much of a fuss. */
594
                                        log_debug_errno(r, "Failed to build alias name (%s + %s), ignoring: %m",
×
595
                                                        dst, inst);
596
                                        continue;
×
597
                                }
598

599
                                dst = dst_inst;
90✔
600
                        }
601
                }
602

603
                r = string_strv_hashmap_put(&names, dst, src);
263,287✔
604
                if (r < 0)
263,287✔
605
                        return log_warning_errno(r, "Failed to add entry to hashmap (%s%s%s): %m",
×
606
                                                 dst, glyph(GLYPH_ARROW_RIGHT), src);
607
        }
608

609
        if (cache_timestamp_hash)
724✔
610
                *cache_timestamp_hash = timestamp_hash;
711✔
611

612
        hashmap_free_and_replace(*unit_ids_map, ids);
724✔
613
        hashmap_free_and_replace(*unit_names_map, names);
724✔
614
        if (path_cache)
724✔
615
                set_free_and_replace(*path_cache, paths);
712✔
616

617
        return 1;
618
}
619

620
int unit_file_remove_from_name_map(
126✔
621
                const LookupPaths *lp,
622
                uint64_t *cache_timestamp_hash,
623
                Hashmap **unit_ids_map,
624
                Hashmap **unit_names_map,
625
                Set **path_cache,
626
                const char *path) {
627

628
        int r;
126✔
629

630
        assert(path);
126✔
631

632
        /* This assumes the specified path is already removed, and drops the relevant entries from the maps. */
633

634
        /* If one of the lookup paths we are monitoring is already changed, let's rebuild the map. Then, the
635
         * new map should not contain entries relevant to the specified path. */
636
        r = unit_file_build_name_map(lp, cache_timestamp_hash, unit_ids_map, unit_names_map, path_cache);
126✔
637
        if (r != 0)
126✔
638
                return r;
126✔
639

640
        /* If not, drop the relevant entries. */
641

642
        _cleanup_free_ char *name = NULL;
126✔
643
        r = path_extract_filename(path, &name);
126✔
644
        if (r < 0)
126✔
645
                return log_warning_errno(r, "Failed to extract file name from '%s': %m", path);
×
646

647
        _unused_ _cleanup_free_ char *key = NULL;
126✔
648
        free(hashmap_remove2(*unit_ids_map, name, (void**) &key));
126✔
649
        string_strv_hashmap_remove(*unit_names_map, name, name);
126✔
650
        free(set_remove(*path_cache, path));
126✔
651

652
        return 0;
126✔
653
}
654

655
static int add_name(
108,364✔
656
                const char *unit_name,
657
                Set **names,
658
                const char *name) {
659
        int r;
108,364✔
660

661
        assert(names);
108,364✔
662
        assert(name);
108,364✔
663

664
        r = set_put_strdup(names, name);
108,364✔
665
        if (r < 0)
108,364✔
666
                return r;
667
        if (r > 0 && !streq(unit_name, name))
108,364✔
668
                log_debug("Unit %s has alias %s.", unit_name, name);
3,931✔
669
        return r;
670
}
671

672
static int add_names(
79,906✔
673
                Hashmap *unit_ids_map,
674
                Hashmap *unit_name_map,
675
                const char *unit_name,
676
                const char *fragment_basename,  /* Only set when adding additional names based on fragment path */
677
                UnitNameFlags name_type,
678
                const char *instance,
679
                Set **names,
680
                const char *name) {
681

682
        char **aliases;
79,906✔
683
        int r;
79,906✔
684

685
        assert(name_type == UNIT_NAME_PLAIN || instance);
79,906✔
686

687
        /* The unit has its own name if it's not a template. If we're looking at a fragment, the fragment
688
         * name (possibly with instance inserted), is also always one of the unit names. */
689
        if (name_type != UNIT_NAME_TEMPLATE) {
79,906✔
690
                r = add_name(unit_name, names, name);
79,901✔
691
                if (r < 0)
79,901✔
692
                        return r;
693
        }
694

695
        /* Add any aliases of the name to the set of names.
696
         *
697
         * We don't even need to know which fragment we will use. The unit_name_map should return the same
698
         * set of names for any of the aliases. */
699
        aliases = hashmap_get(unit_name_map, name);
79,906✔
700
        STRV_FOREACH(alias, aliases) {
108,369✔
701
                if (name_type == UNIT_NAME_INSTANCE && unit_name_is_valid(*alias, UNIT_NAME_TEMPLATE)) {
28,463✔
702
                        _cleanup_free_ char *inst = NULL;
2,606✔
703
                        const char *inst_fragment = NULL;
2,606✔
704

705
                        r = unit_name_replace_instance(*alias, instance, &inst);
2,606✔
706
                        if (r < 0)
2,606✔
707
                                return log_debug_errno(r, "Cannot build instance name %s + %s: %m",
×
708
                                                       *alias, instance);
709

710
                        /* Exclude any aliases that point in some other direction.
711
                         *
712
                         * See https://github.com/systemd/systemd/pull/13119#discussion_r308145418. */
713
                        r = unit_ids_map_get(unit_ids_map, inst, &inst_fragment);
2,606✔
714
                        if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
2,606✔
715
                                return log_debug_errno(r, "Cannot find instance fragment %s: %m", inst);
×
716

717
                        if (inst_fragment &&
2,606✔
718
                            fragment_basename &&
×
719
                            !path_equal_filename(inst_fragment, fragment_basename)) {
×
720
                                log_debug("Instance %s has fragment %s and is not an alias of %s.",
×
721
                                          inst, inst_fragment, unit_name);
722
                                continue;
×
723
                        }
724

725
                        r = add_name(unit_name, names, inst);
2,606✔
726
                } else
727
                        r = add_name(unit_name, names, *alias);
25,857✔
728
                if (r < 0)
28,463✔
729
                        return r;
730
        }
731

732
        return 0;
733
}
734

735
int unit_file_find_fragment(
77,155✔
736
                Hashmap *unit_ids_map,
737
                Hashmap *unit_name_map,
738
                const char *unit_name,
739
                const char **ret_fragment_path,
740
                Set **ret_names) {
741

742
        const char *fragment = NULL;
77,155✔
743
        _cleanup_free_ char *template = NULL, *instance = NULL;
77,155✔
744
        _cleanup_set_free_ Set *names = NULL;
77,155✔
745
        int r;
77,155✔
746

747
        /* Finds a fragment path, and returns the set of names:
748
         * if we have …/foo.service and …/foo-alias.service→foo.service,
749
         * and …/foo@.service and …/foo-alias@.service→foo@.service,
750
         * and …/foo@inst.service,
751
         * this should return:
752
         * foo.service → …/foo.service, {foo.service, foo-alias.service},
753
         * foo-alias.service → …/foo.service, {foo.service, foo-alias.service},
754
         * foo@.service → …/foo@.service, {foo@.service, foo-alias@.service},
755
         * foo-alias@.service → …/foo@.service, {foo@.service, foo-alias@.service},
756
         * foo@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
757
         * foo-alias@bar.service → …/foo@.service, {foo@bar.service, foo-alias@bar.service},
758
         * foo-alias@inst.service → …/foo@inst.service, {foo@inst.service, foo-alias@inst.service}.
759
         */
760

761
        UnitNameFlags name_type = unit_name_to_instance(unit_name, &instance);
77,155✔
762
        if (name_type < 0)
77,155✔
763
                return name_type;
764

765
        if (ret_names) {
77,155✔
766
                r = add_names(unit_ids_map, unit_name_map, unit_name, NULL, name_type, instance, &names, unit_name);
77,145✔
767
                if (r < 0)
77,145✔
768
                        return r;
769
        }
770

771
        /* First try to load fragment under the original name */
772
        r = unit_ids_map_get(unit_ids_map, unit_name, &fragment);
77,155✔
773
        if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
77,155✔
774
                return log_debug_errno(r, "Cannot load unit %s: %m", unit_name);
×
775

776
        if (!fragment && name_type == UNIT_NAME_INSTANCE) {
77,155✔
777
                /* Look for a fragment under the template name */
778

779
                r = unit_name_template(unit_name, &template);
2,690✔
780
                if (r < 0)
2,690✔
781
                        return log_debug_errno(r, "Failed to determine template name: %m");
×
782

783
                r = unit_ids_map_get(unit_ids_map, template, &fragment);
2,690✔
784
                if (r < 0 && !IN_SET(r, -ENOENT, -ENXIO))
2,690✔
785
                        return log_debug_errno(r, "Cannot load template %s: %m", template);
×
786
        }
787

788
        if (fragment && ret_names) {
77,155✔
789
                _cleanup_free_ char *fragment_basename = NULL;
27,025✔
790
                r = path_extract_filename(fragment, &fragment_basename);
27,025✔
791
                if (r < 0)
27,025✔
792
                        return r;
793

794
                if (!streq(fragment_basename, unit_name)) {
27,025✔
795
                        /* Add names based on the fragment name to the set of names */
796
                        r = add_names(unit_ids_map, unit_name_map, unit_name, fragment_basename, name_type, instance, &names, fragment_basename);
2,761✔
797
                        if (r < 0)
2,761✔
798
                                return r;
799
                }
800
        }
801

802
        *ret_fragment_path = fragment;
77,155✔
803
        if (ret_names)
77,155✔
804
                *ret_names = TAKE_PTR(names);
77,145✔
805

806
        return 0;
807
}
808

809
static const char * const rlmap[] = {
810
        "emergency", SPECIAL_EMERGENCY_TARGET,
811
        "-b",        SPECIAL_EMERGENCY_TARGET,
812
        "rescue",    SPECIAL_RESCUE_TARGET,
813
        "single",    SPECIAL_RESCUE_TARGET,
814
        "-s",        SPECIAL_RESCUE_TARGET,
815
        "s",         SPECIAL_RESCUE_TARGET,
816
        "S",         SPECIAL_RESCUE_TARGET,
817
        "1",         SPECIAL_RESCUE_TARGET,
818
        "2",         SPECIAL_MULTI_USER_TARGET,
819
        "3",         SPECIAL_MULTI_USER_TARGET,
820
        "4",         SPECIAL_MULTI_USER_TARGET,
821
        "5",         SPECIAL_GRAPHICAL_TARGET,
822
        NULL
823
};
824

825
static const char * const rlmap_initrd[] = {
826
        "emergency", SPECIAL_EMERGENCY_TARGET,
827
        "rescue",    SPECIAL_RESCUE_TARGET,
828
        NULL
829
};
830

831
const char* runlevel_to_target(const char *word) {
204✔
832
        const char * const *rlmap_ptr;
204✔
833

834
        if (!word)
204✔
835
                return NULL;
836

837
        if (in_initrd()) {
202✔
838
                word = startswith(word, "rd.");
22✔
839
                if (!word)
22✔
840
                        return NULL;
841
        }
842

843
        rlmap_ptr = in_initrd() ? rlmap_initrd : rlmap;
182✔
844

845
        for (size_t i = 0; rlmap_ptr[i]; i += 2)
2,339✔
846
                if (streq(word, rlmap_ptr[i]))
2,160✔
847
                        return rlmap_ptr[i+1];
3✔
848

849
        return NULL;
850
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc