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

systemd / systemd / 22648815823

03 Mar 2026 11:47PM UTC coverage: 72.603% (+0.3%) from 72.342%
22648815823

push

github

yuwata
udevadm: fix --help text for udevadm test-builtin

316021 of 435275 relevant lines covered (72.6%)

1244520.48 hits per line

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

68.85
/src/tmpfiles/tmpfiles.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fcntl.h>
4
#include <fnmatch.h>
5
#include <getopt.h>
6
#include <sys/file.h>
7
#include <sysexits.h>
8
#include <time.h>
9
#include <unistd.h>
10

11
#include "sd-path.h"
12

13
#include "acl-util.h"
14
#include "alloc-util.h"
15
#include "bitfield.h"
16
#include "btrfs-util.h"
17
#include "build.h"
18
#include "capability-util.h"
19
#include "chase.h"
20
#include "chattr-util.h"
21
#include "conf-files.h"
22
#include "constants.h"
23
#include "copy.h"
24
#include "creds-util.h"
25
#include "devnum-util.h"
26
#include "dirent-util.h"
27
#include "dissect-image.h"
28
#include "env-util.h"
29
#include "errno-util.h"
30
#include "escape.h"
31
#include "extract-word.h"
32
#include "fd-util.h"
33
#include "fileio.h"
34
#include "format-util.h"
35
#include "fs-util.h"
36
#include "glob-util.h"
37
#include "hexdecoct.h"
38
#include "image-policy.h"
39
#include "io-util.h"
40
#include "label-util.h"
41
#include "log.h"
42
#include "loop-util.h"
43
#include "main-func.h"
44
#include "mkdir-label.h"
45
#include "mount-util.h"
46
#include "mountpoint-util.h"
47
#include "offline-passwd.h"
48
#include "pager.h"
49
#include "parse-argument.h"
50
#include "parse-util.h"
51
#include "path-lookup.h"
52
#include "path-util.h"
53
#include "pretty-print.h"
54
#include "rlimit-util.h"
55
#include "rm-rf.h"
56
#include "selinux-util.h"
57
#include "set.h"
58
#include "sort-util.h"
59
#include "specifier.h"
60
#include "stat-util.h"
61
#include "string-table.h"
62
#include "string-util.h"
63
#include "strv.h"
64
#include "sysctl-util.h"
65
#include "time-util.h"
66
#include "umask-util.h"
67
#include "user-util.h"
68
#include "verbs.h"
69
#include "virt.h"
70
#include "xattr-util.h"
71

72
/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
73
 * them in the file system. This is intended to be used to create
74
 * properly owned directories beneath /tmp, /var/tmp, /run, which are
75
 * volatile and hence need to be recreated on bootup. */
76

77
typedef enum OperationMask {
78
        OPERATION_CREATE = 1 << 0,
79
        OPERATION_REMOVE = 1 << 1,
80
        OPERATION_CLEAN  = 1 << 2,
81
        OPERATION_PURGE  = 1 << 3,
82
} OperationMask;
83

84
typedef enum ItemType {
85
        /* These ones take file names */
86
        CREATE_FILE                    = 'f',
87
        TRUNCATE_FILE                  = 'F', /* deprecated: use f+ */
88
        CREATE_DIRECTORY               = 'd',
89
        TRUNCATE_DIRECTORY             = 'D',
90
        CREATE_SUBVOLUME               = 'v',
91
        CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
92
        CREATE_SUBVOLUME_NEW_QUOTA     = 'Q',
93
        CREATE_FIFO                    = 'p',
94
        CREATE_SYMLINK                 = 'L',
95
        CREATE_CHAR_DEVICE             = 'c',
96
        CREATE_BLOCK_DEVICE            = 'b',
97
        COPY_FILES                     = 'C',
98

99
        /* These ones take globs */
100
        WRITE_FILE                     = 'w',
101
        EMPTY_DIRECTORY                = 'e',
102
        SET_XATTR                      = 't',
103
        RECURSIVE_SET_XATTR            = 'T',
104
        SET_ACL                        = 'a',
105
        RECURSIVE_SET_ACL              = 'A',
106
        SET_ATTRIBUTE                  = 'h',
107
        RECURSIVE_SET_ATTRIBUTE        = 'H',
108
        IGNORE_PATH                    = 'x',
109
        IGNORE_DIRECTORY_PATH          = 'X',
110
        REMOVE_PATH                    = 'r',
111
        RECURSIVE_REMOVE_PATH          = 'R',
112
        RELABEL_PATH                   = 'z',
113
        RECURSIVE_RELABEL_PATH         = 'Z',
114
        ADJUST_MODE                    = 'm', /* legacy, 'z' is identical to this */
115
} ItemType;
116

117
typedef enum AgeBy {
118
        AGE_BY_ATIME = 1 << 0,
119
        AGE_BY_BTIME = 1 << 1,
120
        AGE_BY_CTIME = 1 << 2,
121
        AGE_BY_MTIME = 1 << 3,
122

123
        /* All file timestamp types are checked by default. */
124
        AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
125
        AGE_BY_DEFAULT_DIR  = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME,
126
} AgeBy;
127

128
typedef struct Item {
129
        ItemType type;
130

131
        char *path;
132
        char *argument;
133
        void *binary_argument;        /* set if binary data, in which case it takes precedence over 'argument' */
134
        size_t binary_argument_size;
135
        char **xattrs;
136
#if HAVE_ACL
137
        acl_t acl_access;
138
        acl_t acl_access_exec;
139
        acl_t acl_default;
140
#endif
141
        uid_t uid;
142
        gid_t gid;
143
        mode_t mode;
144
        usec_t age;
145
        AgeBy age_by_file, age_by_dir;
146

147
        dev_t major_minor;
148
        unsigned attribute_value;
149
        unsigned attribute_mask;
150

151
        bool uid_set:1;
152
        bool gid_set:1;
153
        bool mode_set:1;
154
        bool uid_only_create:1;
155
        bool gid_only_create:1;
156
        bool mode_only_create:1;
157
        bool age_set:1;
158
        bool mask_perms:1;
159
        bool attribute_set:1;
160

161
        bool keep_first_level:1;
162

163
        bool append_or_force:1;
164

165
        bool allow_failure:1;
166

167
        bool try_replace:1;
168

169
        bool purge:1;
170

171
        bool ignore_if_target_missing:1;
172

173
        OperationMask done;
174
} Item;
175

176
typedef struct ItemArray {
177
        Item *items;
178
        size_t n_items;
179

180
        struct ItemArray *parent;
181
        Set *children;
182
} ItemArray;
183

184
typedef enum DirectoryType {
185
        DIRECTORY_RUNTIME,
186
        DIRECTORY_STATE,
187
        DIRECTORY_CACHE,
188
        DIRECTORY_LOGS,
189
        _DIRECTORY_TYPE_MAX,
190
} DirectoryType;
191

192
typedef enum {
193
        CREATION_NORMAL,
194
        CREATION_EXISTING,
195
        CREATION_FORCE,
196
        _CREATION_MODE_MAX,
197
        _CREATION_MODE_INVALID = -EINVAL,
198
} CreationMode;
199

200
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
201
static bool arg_dry_run = false;
202
static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
203
static OperationMask arg_operation = 0;
204
static bool arg_boot = false;
205
static bool arg_graceful = false;
206
static PagerFlags arg_pager_flags = 0;
207
static char **arg_include_prefixes = NULL;
208
static char **arg_exclude_prefixes = NULL;
209
static char *arg_root = NULL;
210
static char *arg_image = NULL;
211
static char *arg_replace = NULL;
212
static ImagePolicy *arg_image_policy = NULL;
213

214
#define MAX_DEPTH 256
215

216
typedef struct Context {
217
        OrderedHashmap *items;
218
        OrderedHashmap *globs;
219
        Set *unix_sockets;
220
        Hashmap *uid_cache;
221
        Hashmap *gid_cache;
222
} Context;
223

224
STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, strv_freep);
711✔
225
STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, strv_freep);
711✔
226
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
711✔
227
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
711✔
228
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
711✔
229

230
static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
231
        [CREATION_NORMAL]   = "Created",
232
        [CREATION_EXISTING] = "Found existing",
233
        [CREATION_FORCE]    = "Created replacement",
234
};
235

236
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
12,296✔
237

238
static void context_done(Context *c) {
711✔
239
        assert(c);
711✔
240

241
        ordered_hashmap_free(c->items);
711✔
242
        ordered_hashmap_free(c->globs);
711✔
243

244
        set_free(c->unix_sockets);
711✔
245

246
        hashmap_free(c->uid_cache);
711✔
247
        hashmap_free(c->gid_cache);
711✔
248
}
711✔
249

250
/* Different kinds of errors that mean that information is not available in the environment. */
251
static bool ERRNO_IS_NEG_NOINFO(intmax_t r) {
95,501✔
252
        return IN_SET(r,
95,501✔
253
                      -EUNATCH,    /* os-release or machine-id missing */
254
                      -ENOMEDIUM,  /* machine-id or another file empty */
255
                      -ENOPKG,     /* machine-id is uninitialized */
256
                      -ENXIO);     /* env var is unset */
257
}
258

259
static int specifier_directory(
606✔
260
                char specifier,
261
                const void *data,
262
                const char *root,
263
                const void *userdata,
264
                char **ret) {
265

266
        struct table_entry {
606✔
267
                uint64_t type;
268
                const char *suffix;
269
        };
270

271
        static const struct table_entry paths_system[] = {
606✔
272
                [DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME            },
273
                [DIRECTORY_STATE] =   { SD_PATH_SYSTEM_STATE_PRIVATE      },
274
                [DIRECTORY_CACHE] =   { SD_PATH_SYSTEM_STATE_CACHE        },
275
                [DIRECTORY_LOGS] =    { SD_PATH_SYSTEM_STATE_LOGS         },
276
        };
277

278
        static const struct table_entry paths_user[] = {
606✔
279
                [DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME              },
280
                [DIRECTORY_STATE] =   { SD_PATH_USER_STATE_PRIVATE        },
281
                [DIRECTORY_CACHE] =   { SD_PATH_USER_STATE_CACHE          },
282
                [DIRECTORY_LOGS] =    { SD_PATH_USER_STATE_PRIVATE, "log" },
283
        };
284

285
        const struct table_entry *paths;
606✔
286
        _cleanup_free_ char *p = NULL;
606✔
287
        unsigned i;
606✔
288
        int r;
606✔
289

290
        assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
606✔
291
        paths = arg_runtime_scope == RUNTIME_SCOPE_USER ? paths_user : paths_system;
606✔
292

293
        i = PTR_TO_UINT(data);
606✔
294
        assert(i < ELEMENTSOF(paths_system));
606✔
295

296
        r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
606✔
297
        if (r < 0)
606✔
298
                return r;
299

300
        if (arg_root) {
606✔
301
                _cleanup_free_ char *j = NULL;
×
302

303
                j = path_join(arg_root, p);
×
304
                if (!j)
×
305
                        return -ENOMEM;
×
306

307
                *ret = TAKE_PTR(j);
×
308
        } else
309
                *ret = TAKE_PTR(p);
606✔
310

311
        return 0;
312
}
313

314
static int log_unresolvable_specifier(const char *filename, unsigned line) {
×
315
        static bool notified = false;
×
316

317
        /* In system mode, this is called when /etc is not fully initialized and some specifiers are
318
         * unresolvable. In user mode, this is called when some variables are not defined. These cases are
319
         * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
320
         * to LOG_DEBUG for the rest.
321
         *
322
         * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
323
         * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
324
         * expectation that machine-id and other files will be populated.
325
         */
326

327
        int log_level = notified || arg_root || running_in_chroot() > 0 ?
×
328
                LOG_DEBUG : LOG_NOTICE;
×
329

330
        log_syntax(NULL,
×
331
                   log_level,
332
                   filename, line, 0,
333
                   "Failed to resolve specifier: %s, skipping.",
334
                   arg_runtime_scope == RUNTIME_SCOPE_USER ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
335

336
        if (!notified)
×
337
                log_full(log_level,
×
338
                         "All rules containing unresolvable specifiers will be skipped.");
339

340
        notified = true;
×
341
        return 0;
×
342
}
343

344
#define log_action(would, doing, fmt, ...)              \
345
        log_full(arg_dry_run ? LOG_INFO : LOG_DEBUG,    \
346
                 fmt,                                   \
347
                 arg_dry_run ? (would) : (doing),       \
348
                 __VA_ARGS__)
349

350
static int user_config_paths(char ***ret) {
202✔
351
        _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
202✔
352
        _cleanup_free_ char *runtime_config = NULL;
202✔
353
        int r;
202✔
354

355
        assert(ret);
202✔
356

357
        /* Combined user-specific and global dirs */
358
        r = user_search_dirs("/user-tmpfiles.d", &config_dirs, &data_dirs);
202✔
359
        if (r < 0)
202✔
360
                return r;
361

362
        r = xdg_user_runtime_dir("/user-tmpfiles.d", &runtime_config);
202✔
363
        if (r < 0 && !ERRNO_IS_NEG_NOINFO(r))
202✔
364
                return r;
365

366
        r = strv_consume(&config_dirs, TAKE_PTR(runtime_config));
202✔
367
        if (r < 0)
202✔
368
                return r;
369

370
        r = strv_extend_strv_consume(&config_dirs, TAKE_PTR(data_dirs), /* filter_duplicates= */ true);
202✔
371
        if (r < 0)
202✔
372
                return r;
373

374
        r = path_strv_make_absolute_cwd(config_dirs);
202✔
375
        if (r < 0)
202✔
376
                return r;
377

378
        *ret = TAKE_PTR(config_dirs);
202✔
379
        return 0;
202✔
380
}
381

382
static bool needs_purge(ItemType t) {
4,479✔
383
        return IN_SET(t,
4,479✔
384
                      CREATE_FILE,
385
                      TRUNCATE_FILE,
386
                      CREATE_DIRECTORY,
387
                      TRUNCATE_DIRECTORY,
388
                      CREATE_SUBVOLUME,
389
                      CREATE_SUBVOLUME_INHERIT_QUOTA,
390
                      CREATE_SUBVOLUME_NEW_QUOTA,
391
                      CREATE_FIFO,
392
                      CREATE_SYMLINK,
393
                      CREATE_CHAR_DEVICE,
394
                      CREATE_BLOCK_DEVICE,
395
                      COPY_FILES,
396
                      WRITE_FILE,
397
                      EMPTY_DIRECTORY);
398
}
399

400
static bool needs_glob(ItemType t) {
25,628✔
401
        return IN_SET(t,
25,628✔
402
                      WRITE_FILE,
403
                      EMPTY_DIRECTORY,
404
                      SET_XATTR,
405
                      RECURSIVE_SET_XATTR,
406
                      SET_ACL,
407
                      RECURSIVE_SET_ACL,
408
                      SET_ATTRIBUTE,
409
                      RECURSIVE_SET_ATTRIBUTE,
410
                      IGNORE_PATH,
411
                      IGNORE_DIRECTORY_PATH,
412
                      REMOVE_PATH,
413
                      RECURSIVE_REMOVE_PATH,
414
                      RELABEL_PATH,
415
                      RECURSIVE_RELABEL_PATH,
416
                      ADJUST_MODE);
417
}
418

419
static bool takes_ownership(ItemType t) {
6,031✔
420
        return IN_SET(t,
6,031✔
421
                      CREATE_FILE,
422
                      TRUNCATE_FILE,
423
                      CREATE_DIRECTORY,
424
                      TRUNCATE_DIRECTORY,
425
                      CREATE_SUBVOLUME,
426
                      CREATE_SUBVOLUME_INHERIT_QUOTA,
427
                      CREATE_SUBVOLUME_NEW_QUOTA,
428
                      CREATE_FIFO,
429
                      CREATE_SYMLINK,
430
                      CREATE_CHAR_DEVICE,
431
                      CREATE_BLOCK_DEVICE,
432
                      COPY_FILES,
433
                      WRITE_FILE,
434
                      EMPTY_DIRECTORY,
435
                      IGNORE_PATH,
436
                      IGNORE_DIRECTORY_PATH,
437
                      REMOVE_PATH,
438
                      RECURSIVE_REMOVE_PATH);
439
}
440

441
static bool supports_ignore_if_target_missing(ItemType t) {
744✔
442
        return t == CREATE_SYMLINK;
744✔
443
}
444

445
static struct Item* find_glob(OrderedHashmap *h, const char *match) {
183✔
446
        ItemArray *j;
183✔
447

448
        ORDERED_HASHMAP_FOREACH(j, h)
294✔
449
                FOREACH_ARRAY(item, j->items, j->n_items)
240✔
450
                        if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
129✔
451
                                return item;
18✔
452
        return NULL;
165✔
453
}
454

455
static int load_unix_sockets(Context *c) {
×
456
        _cleanup_set_free_ Set *sockets = NULL;
×
457
        _cleanup_fclose_ FILE *f = NULL;
×
458
        int r;
×
459

460
        if (c->unix_sockets)
×
461
                return 0;
462

463
        /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
464

465
        f = fopen("/proc/net/unix", "re");
×
466
        if (!f)
×
467
                return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
×
468
                                      "Failed to open %s, ignoring: %m", "/proc/net/unix");
469

470
        /* Skip header */
471
        r = read_line(f, LONG_LINE_MAX, NULL);
×
472
        if (r < 0)
×
473
                return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
×
474
        if (r == 0)
×
475
                return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
×
476

477
        for (;;) {
×
478
                _cleanup_free_ char *line = NULL;
×
479
                char *p;
×
480

481
                r = read_line(f, LONG_LINE_MAX, &line);
×
482
                if (r < 0)
×
483
                        return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
×
484
                if (r == 0) /* EOF */
×
485
                        break;
486

487
                p = strchr(line, ':');
×
488
                if (!p)
×
489
                        continue;
×
490

491
                if (strlen(p) < 37)
×
492
                        continue;
×
493

494
                p += 37;
×
495
                p += strspn(p, WHITESPACE);
×
496
                p += strcspn(p, WHITESPACE); /* skip one more word */
×
497
                p += strspn(p, WHITESPACE);
×
498

499
                if (!path_is_absolute(p))
×
500
                        continue;
×
501

502
                r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
×
503
                if (r < 0)
×
504
                        return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
×
505
        }
506

507
        c->unix_sockets = TAKE_PTR(sockets);
×
508
        return 1;
×
509
}
510

511
static bool unix_socket_alive(Context *c, const char *fn) {
×
512
        assert(c);
×
513
        assert(fn);
×
514

515
        if (load_unix_sockets(c) < 0)
×
516
                return true;     /* We don't know, so assume yes */
517

518
        return set_contains(c->unix_sockets, fn);
×
519
}
520

521
/* Accessors for the argument in binary format */
522
static const void* item_binary_argument(const Item *i) {
1,823✔
523
        assert(i);
1,823✔
524
        return i->binary_argument ?: i->argument;
1,823✔
525
}
526

527
static size_t item_binary_argument_size(const Item *i) {
1,581✔
528
        assert(i);
1,581✔
529
        return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
1,581✔
530
}
531

532
static DIR* xopendirat_nomod(int dirfd, const char *path) {
1,454✔
533
        DIR *dir;
1,454✔
534

535
        dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
1,454✔
536
        if (dir)
1,454✔
537
                return dir;
538

539
        if (!IN_SET(errno, ENOENT, ELOOP))
506✔
540
                log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
11✔
541
        if (!ERRNO_IS_PRIVILEGE(errno))
506✔
542
                return NULL;
543

544
        dir = xopendirat(dirfd, path, O_NOFOLLOW);
×
545
        if (!dir)
×
546
                log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with or without O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
×
547

548
        return dir;
549
}
550

551
static DIR* opendir_nomod(const char *path) {
1,417✔
552
        return xopendirat_nomod(AT_FDCWD, path);
1,417✔
553
}
554

555
static int opendir_and_stat(
547✔
556
                const char *path,
557
                DIR **ret,
558
                struct statx *ret_sx,
559
                bool *ret_mountpoint) {
560

561
        _cleanup_closedir_ DIR *d = NULL;
547✔
562
        struct statx sx;
547✔
563
        int r;
547✔
564

565
        assert(path);
547✔
566
        assert(ret);
547✔
567
        assert(ret_sx);
547✔
568
        assert(ret_mountpoint);
547✔
569

570
        /* Do opendir() and statx() on the directory.
571
         * Return 1 if successful, 0 if file doesn't exist or is not a directory,
572
         * negative errno otherwise.
573
         */
574

575
        d = opendir_nomod(path);
547✔
576
        if (!d) {
547✔
577
                bool ignore = IN_SET(errno, ENOENT, ENOTDIR);
503✔
578
                r = log_full_errno(ignore ? LOG_DEBUG : LOG_ERR,
503✔
579
                                   errno, "Failed to open directory %s: %m", path);
580
                if (!ignore)
503✔
581
                        return r;
582

583
                *ret = NULL;
503✔
584
                *ret_sx = (struct statx) {};
503✔
585
                *ret_mountpoint = false;
503✔
586
                return 0;
503✔
587
        }
588

589
        r = xstatx_full(dirfd(d),
44✔
590
                        /* path= */ NULL,
591
                        AT_EMPTY_PATH,
592
                        /* xstatx_flags= */ 0,
593
                        STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME,
594
                        /* optional_mask= */ 0,
595
                        STATX_ATTR_MOUNT_ROOT,
596
                        &sx);
597
        if (r < 0)
44✔
598
                return log_error_errno(r, "statx(%s) failed: %m", path);
×
599

600
        *ret_mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
44✔
601
        *ret = TAKE_PTR(d);
44✔
602
        *ret_sx = sx;
44✔
603
        return 1;
44✔
604
}
605

606
static bool needs_cleanup(
165✔
607
                nsec_t atime,
608
                nsec_t btime,
609
                nsec_t ctime,
610
                nsec_t mtime,
611
                nsec_t cutoff,
612
                const char *sub_path,
613
                AgeBy age_by,
614
                bool is_dir) {
615

616
        if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
165✔
617
                /* Follows spelling in stat(1). */
618
                log_debug("%s \"%s\": modify time %s is too new.",
34✔
619
                          is_dir ? "Directory" : "File",
620
                          sub_path,
621
                          FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
622

623
                return false;
24✔
624
        }
625

626
        if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
141✔
627
                log_debug("%s \"%s\": access time %s is too new.",
117✔
628
                          is_dir ? "Directory" : "File",
629
                          sub_path,
630
                          FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
631

632
                return false;
63✔
633
        }
634

635
        /*
636
         * Note: Unless explicitly specified by the user, "ctime" is ignored
637
         * by default for directories, because we change it when deleting.
638
         */
639
        if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
78✔
640
                log_debug("%s \"%s\": change time %s is too new.",
14✔
641
                          is_dir ? "Directory" : "File",
642
                          sub_path,
643
                          FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
644

645
                return false;
7✔
646
        }
647

648
        if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
71✔
649
                log_debug("%s \"%s\": birth time %s is too new.",
8✔
650
                          is_dir ? "Directory" : "File",
651
                          sub_path,
652
                          FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
653

654
                return false;
5✔
655
        }
656

657
        return true;
658
}
659

660
static int dir_cleanup(
81✔
661
                Context *c,
662
                Item *i,
663
                const char *p,
664
                DIR *d,
665
                nsec_t self_atime_nsec,
666
                nsec_t self_mtime_nsec,
667
                nsec_t cutoff_nsec,
668
                dev_t rootdev_major,
669
                dev_t rootdev_minor,
670
                bool mountpoint,
671
                int maxdepth,
672
                bool keep_this_level,
673
                AgeBy age_by_file,
674
                AgeBy age_by_dir) {
675

676
        bool deleted = false;
81✔
677
        int r = 0;
81✔
678

679
        assert(c);
81✔
680
        assert(i);
81✔
681
        assert(d);
81✔
682

683
        FOREACH_DIRENT_ALL(de, d, break) {
431✔
684
                _cleanup_free_ char *sub_path = NULL;
350✔
685
                nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
350✔
686

687
                if (dot_or_dot_dot(de->d_name))
350✔
688
                        continue;
162✔
689

690
                struct statx sx;
188✔
691
                r = xstatx_full(dirfd(d), de->d_name,
188✔
692
                                AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
693
                                /* xstatx_flags= */ 0,
694
                                STATX_TYPE|STATX_MODE|STATX_UID,
695
                                STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
696
                                STATX_ATTR_MOUNT_ROOT,
697
                                &sx);
698
                if (r == -ENOENT)
188✔
699
                        continue;
×
700
                if (r < 0) {
188✔
701
                        /* FUSE, NFS mounts, SELinux might return EACCES */
702
                        log_full_errno(r == -EACCES ? LOG_DEBUG : LOG_ERR, r,
×
703
                                       "statx(%s/%s) failed: %m", p, de->d_name);
704
                        continue;
×
705
                }
706

707
                if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
188✔
708
                        log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
×
709
                        continue;
×
710
                }
711

712
                atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : 0;
188✔
713
                mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : 0;
188✔
714
                ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : 0;
188✔
715
                btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : 0;
188✔
716

717
                sub_path = path_join(p, de->d_name);
188✔
718
                if (!sub_path) {
188✔
719
                        r = log_oom();
×
720
                        goto finish;
×
721
                }
722

723
                /* Is there an item configured for this path? */
724
                if (ordered_hashmap_get(c->items, sub_path)) {
188✔
725
                        log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
5✔
726
                        continue;
5✔
727
                }
728

729
                if (find_glob(c->globs, sub_path)) {
183✔
730
                        log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
18✔
731
                        continue;
18✔
732
                }
733

734
                if (S_ISDIR(sx.stx_mode)) {
165✔
735
                        _cleanup_closedir_ DIR *sub_dir = NULL;
×
736

737
                        if (mountpoint &&
37✔
738
                            streq(de->d_name, "lost+found") &&
×
739
                            sx.stx_uid == 0) {
×
740
                                log_debug("Ignoring directory \"%s\".", sub_path);
×
741
                                continue;
×
742
                        }
743

744
                        if (maxdepth <= 0)
37✔
745
                                log_warning("Reached max depth on \"%s\".", sub_path);
×
746
                        else {
747
                                int q;
37✔
748

749
                                sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
37✔
750
                                if (!sub_dir) {
37✔
751
                                        if (errno != ENOENT)
×
752
                                                r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
×
753

754
                                        continue;
×
755
                                }
756

757
                                if (!arg_dry_run &&
70✔
758
                                    flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
33✔
759
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path);
×
760
                                        continue;
×
761
                                }
762

763
                                q = dir_cleanup(c, i,
37✔
764
                                                sub_path, sub_dir,
765
                                                atime_nsec, mtime_nsec, cutoff_nsec,
766
                                                rootdev_major, rootdev_minor,
767
                                                false, maxdepth-1, false,
768
                                                age_by_file, age_by_dir);
769
                                if (q < 0)
37✔
770
                                        r = q;
×
771
                        }
772

773
                        /* Note: if you are wondering why we don't support the sticky bit for excluding
774
                         * directories from cleaning like we do it for other file system objects: well, the
775
                         * sticky bit already has a meaning for directories, so we don't want to overload
776
                         * that. */
777

778
                        if (keep_this_level) {
37✔
779
                                log_debug("Keeping directory \"%s\".", sub_path);
×
780
                                continue;
×
781
                        }
782

783
                        /*
784
                         * Check the file timestamps of an entry against the
785
                         * given cutoff time; delete if it is older.
786
                         */
787
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
37✔
788
                                           cutoff_nsec, sub_path, age_by_dir, true))
789
                                continue;
25✔
790

791
                        log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path);
16✔
792
                        if (!arg_dry_run &&
20✔
793
                            unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0 &&
8✔
794
                            !IN_SET(errno, ENOENT, ENOTEMPTY))
×
795
                                r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
×
796

797
                } else {
798
                        _cleanup_close_ int fd = -EBADF; /* This file descriptor is defined here so that the
350✔
799
                                                          * lock that is taken below is only dropped _after_
800
                                                          * the unlink operation has finished. */
801

802
                        /* Skip files for which the sticky bit is set. These are semantics we define, and are
803
                         * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
804
                        if (sx.stx_mode & S_ISVTX) {
128✔
805
                                log_debug("Skipping \"%s\": sticky bit set.", sub_path);
×
806
                                continue;
×
807
                        }
808

809
                        if (mountpoint &&
128✔
810
                            S_ISREG(sx.stx_mode) &&
×
811
                            sx.stx_uid == 0 &&
×
812
                            STR_IN_SET(de->d_name,
×
813
                                       ".journal",
814
                                       "aquota.user",
815
                                       "aquota.group")) {
816
                                log_debug("Skipping \"%s\".", sub_path);
×
817
                                continue;
×
818
                        }
819

820
                        /* Ignore sockets that are listed in /proc/net/unix */
821
                        if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
128✔
822
                                log_debug("Skipping \"%s\": live socket.", sub_path);
×
823
                                continue;
×
824
                        }
825

826
                        /* Ignore device nodes */
827
                        if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
128✔
828
                                log_debug("Skipping \"%s\": a device.", sub_path);
×
829
                                continue;
×
830
                        }
831

832
                        /* Keep files on this level if this was requested */
833
                        if (keep_this_level) {
128✔
834
                                log_debug("Keeping \"%s\".", sub_path);
×
835
                                continue;
×
836
                        }
837

838
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
128✔
839
                                           cutoff_nsec, sub_path, age_by_file, false))
840
                                continue;
74✔
841

842
                        if (!arg_dry_run) {
54✔
843
                                fd = xopenat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME|O_NONBLOCK|O_NOCTTY);
34✔
844
                                if (fd < 0 && !IN_SET(fd, -ENOENT, -ELOOP))
34✔
845
                                        log_warning_errno(fd, "Opening file \"%s\" failed, proceeding without lock: %m", sub_path);
×
846
                                if (fd >= 0 && flock(fd, LOCK_EX|LOCK_NB) < 0 && errno == EAGAIN) {
34✔
847
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", sub_path);
×
848
                                        continue;
×
849
                                }
850
                        }
851

852
                        log_action("Would remove", "Removing", "%s \"%s\"", sub_path);
70✔
853
                        if (!arg_dry_run &&
88✔
854
                            unlinkat(dirfd(d), de->d_name, 0) < 0 &&
34✔
855
                            errno != ENOENT)
×
856
                                r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
×
857

858
                        deleted = true;
54✔
859
                }
860
        }
861

862
finish:
81✔
863
        if (deleted && (self_atime_nsec < NSEC_INFINITY || self_mtime_nsec < NSEC_INFINITY)) {
81✔
864
                struct timespec ts[2];
28✔
865

866
                log_action("Would restore", "Restoring",
37✔
867
                           "%s access and modification time on \"%s\": %s, %s",
868
                           p,
869
                           FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
870
                           FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
871

872
                timespec_store_nsec(ts + 0, self_atime_nsec);
28✔
873
                timespec_store_nsec(ts + 1, self_mtime_nsec);
28✔
874

875
                /* Restore original directory timestamps */
876
                if (!arg_dry_run &&
45✔
877
                    futimens(dirfd(d), ts) < 0)
17✔
878
                        log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
28✔
879
        }
880

881
        return r;
81✔
882
}
883

884
static bool hardlinks_protected(void) {
×
885
        static int cached = -1;
×
886
        int r;
×
887

888
        /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off,
889
         * as that's what the kernel default is.
890
         * Note that we ship 50-default.conf where it is enabled, but better be safe than sorry. */
891

892
        if (cached >= 0)
×
893
                return cached;
×
894

895
        _cleanup_free_ char *value = NULL;
×
896

897
        r = sysctl_read("fs/protected_hardlinks", &value);
×
898
        if (r < 0) {
×
899
                log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
×
900
                return false;
×
901
        }
902

903
        cached = parse_boolean(value);
×
904
        if (cached < 0)
×
905
                log_debug_errno(cached, "Failed to parse fs.protected_hardlinks sysctl, assuming disabled: %m");
×
906
        return cached > 0;
×
907
}
908

909
static bool hardlink_vulnerable(const struct stat *st) {
15,073✔
910
        assert(st);
15,073✔
911

912
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
15,073✔
913
}
914

915
static mode_t process_mask_perms(mode_t mode, mode_t current) {
341✔
916

917
        if ((current & 0111) == 0)
341✔
918
                mode &= ~0111;
238✔
919
        if ((current & 0222) == 0)
341✔
920
                mode &= ~0222;
×
921
        if ((current & 0444) == 0)
341✔
922
                mode &= ~0444;
×
923
        if (!S_ISDIR(current))
341✔
924
                mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
238✔
925

926
        return mode;
341✔
927
}
928

929
static int fd_set_perms(
20,270✔
930
                Context *c,
931
                Item *i,
932
                int fd,
933
                const char *path,
934
                const struct stat *st,
935
                CreationMode creation) {
936

937
        bool do_chown, do_chmod;
20,270✔
938
        struct stat stbuf;
20,270✔
939
        mode_t new_mode;
20,270✔
940
        uid_t new_uid;
20,270✔
941
        gid_t new_gid;
20,270✔
942
        int r;
20,270✔
943

944
        assert(c);
20,270✔
945
        assert(i);
20,270✔
946
        assert(fd >= 0);
20,270✔
947
        assert(path);
20,270✔
948

949
        if (!i->mode_set && !i->uid_set && !i->gid_set)
20,270✔
950
                goto shortcut;
5,989✔
951

952
        if (!st) {
14,281✔
953
                if (fstat(fd, &stbuf) < 0)
2,420✔
954
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
955
                st = &stbuf;
956
        }
957

958
        if (hardlink_vulnerable(st))
14,281✔
959
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
960
                                       "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
961
                                       path);
962
        new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
14,281✔
963
        new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
14,281✔
964

965
        /* Do we need a chown()? */
966
        do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
14,281✔
967

968
        /* Calculate the mode to apply */
969
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
27,945✔
970
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
28,288✔
971
                (st->st_mode & 07777);
274✔
972

973
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
14,281✔
974

975
        if (do_chmod && do_chown) {
14,281✔
976
                /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
977
                 * the new mode. That way there's no time window where the file exists under the old owner
978
                 * with more than the old access modes — and not under the new owner with more than the new
979
                 * access modes either. */
980

981
                if (S_ISLNK(st->st_mode))
751✔
982
                        log_debug("Skipping temporary mode fix for symlink %s.", path);
×
983
                else {
984
                        mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
751✔
985

986
                        if (((m ^ st->st_mode) & 07777) == 0)
751✔
987
                                log_debug("\"%s\" matches temporary mode %o already.", path, m);
740✔
988
                        else {
989
                                log_action("Would temporarily change", "Temporarily changing",
11✔
990
                                           "%s \"%s\" to mode %o", path, m);
991
                                if (!arg_dry_run) {
11✔
992
                                        r = fchmod_opath(fd, m);
11✔
993
                                        if (r < 0)
11✔
994
                                                return log_error_errno(r, "fchmod() of %s failed: %m", path);
×
995
                                }
996
                        }
997
                }
998
        }
999

1000
        if (do_chown) {
14,281✔
1001
                log_action("Would change", "Changing",
2,824✔
1002
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1003

1004
                if (!arg_dry_run &&
2,856✔
1005
                    fchownat(fd, "",
1,427✔
1006
                             new_uid != st->st_uid ? new_uid : UID_INVALID,
1,427✔
1007
                             new_gid != st->st_gid ? new_gid : GID_INVALID,
1,427✔
1008
                             AT_EMPTY_PATH) < 0)
1009
                        return log_error_errno(errno, "fchownat() of %s failed: %m", path);
×
1010
        }
1011

1012
        /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
1013
         * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
1014
        if (do_chmod || do_chown) {
14,281✔
1015
                if (S_ISLNK(st->st_mode))
2,804✔
1016
                        log_debug("Skipping mode fix for symlink %s.", path);
×
1017
                else {
1018
                        log_action("Would change", "Changing", "%s \"%s\" to mode %o", path, new_mode);
5,570✔
1019
                        if (!arg_dry_run) {
2,804✔
1020
                                r = fchmod_opath(fd, new_mode);
2,802✔
1021
                                if (r < 0)
2,802✔
1022
                                        return log_error_errno(r, "fchmod() of %s failed: %m", path);
2✔
1023
                        }
1024
                }
1025
        }
1026

1027
shortcut:
14,279✔
1028
        if (arg_dry_run) {
20,268✔
1029
                log_debug("Would relabel \"%s\"", path);
5✔
1030
                return 0;
5✔
1031
        }
1032

1033
        log_debug("Relabelling \"%s\"", path);
20,263✔
1034
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
20,263✔
1035
}
1036

1037
static int path_open_parent_safe(const char *path, bool allow_failure) {
18,169✔
1038
        _cleanup_free_ char *dn = NULL;
18,169✔
1039
        int r, fd;
18,169✔
1040

1041
        if (!path_is_normalized(path))
18,169✔
1042
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1043
                                      SYNTHETIC_ERRNO(EINVAL),
1044
                                      "Failed to open parent of '%s': path not normalized%s.",
1045
                                      path,
1046
                                      allow_failure ? ", ignoring" : "");
1047

1048
        r = path_extract_directory(path, &dn);
18,169✔
1049
        if (r < 0)
18,169✔
1050
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1051
                                      r,
1052
                                      "Unable to determine parent directory of '%s'%s: %m",
1053
                                      path,
1054
                                      allow_failure ? ", ignoring" : "");
1055

1056
        r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
36,084✔
1057
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
18,169✔
1058
                return r;
1059
        if (r < 0)
18,164✔
1060
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1061
                                      r,
1062
                                      "Failed to open path '%s'%s: %m",
1063
                                      dn,
1064
                                      allow_failure ? ", ignoring" : "");
1065

1066
        return fd;
18,164✔
1067
}
1068

1069
static int path_open_safe(const char *path) {
2,780✔
1070
        int r, fd;
2,780✔
1071

1072
        /* path_open_safe() returns a file descriptor opened with O_PATH after
1073
         * verifying that the path doesn't contain unsafe transitions, except
1074
         * for its final component as the function does not follow symlink. */
1075

1076
        assert(path);
2,780✔
1077

1078
        if (!path_is_normalized(path))
2,780✔
1079
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
×
1080

1081
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
2,780✔
1082
        if (r == -ENOLINK)
2,780✔
1083
                return r; /* Unsafe symlink: already covered by CHASE_WARN */
1084
        if (r < 0)
2,780✔
1085
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
1086
                                      "Failed to open path %s%s: %m", path,
1087
                                      r == -ENOENT ? ", ignoring" : "");
1088

1089
        return fd;
2,780✔
1090
}
1091

1092
static int path_set_perms(
2,275✔
1093
                Context *c,
1094
                Item *i,
1095
                const char *path,
1096
                CreationMode creation) {
1097

1098
        _cleanup_close_ int fd = -EBADF;
2,275✔
1099

1100
        assert(c);
2,275✔
1101
        assert(i);
2,275✔
1102
        assert(path);
2,275✔
1103

1104
        fd = path_open_safe(path);
2,275✔
1105
        if (fd == -ENOENT)
2,275✔
1106
                return 0;
1107
        if (fd < 0)
2,275✔
1108
                return fd;
1109

1110
        return fd_set_perms(c, i, fd, path, /* st= */ NULL, creation);
2,275✔
1111
}
1112

1113
static int parse_xattrs_from_arg(Item *i) {
×
1114
        const char *p;
×
1115
        int r;
×
1116

1117
        assert(i);
×
1118

1119
        assert_se(p = i->argument);
×
1120
        for (;;) {
×
1121
                _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
×
1122

1123
                r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
×
1124
                if (r < 0)
×
1125
                        log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
×
1126
                if (r <= 0)
×
1127
                        break;
1128

1129
                r = split_pair(xattr, "=", &name, &value);
×
1130
                if (r < 0) {
×
1131
                        log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
×
1132
                        continue;
×
1133
                }
1134

1135
                if (isempty(name) || isempty(value)) {
×
1136
                        log_warning("Malformed extended attribute found, ignoring: %s", xattr);
×
1137
                        continue;
×
1138
                }
1139

1140
                if (strv_push_pair(&i->xattrs, name, value) < 0)
×
1141
                        return log_oom();
×
1142

1143
                name = value = NULL;
×
1144
        }
1145

1146
        return 0;
×
1147
}
1148

1149
static int fd_set_xattrs(
×
1150
                Context *c,
1151
                Item *i,
1152
                int fd,
1153
                const char *path,
1154
                const struct stat *st,
1155
                CreationMode creation) {
1156

1157
        int r;
×
1158

1159
        assert(c);
×
1160
        assert(i);
×
1161
        assert(fd >= 0);
×
1162
        assert(path);
×
1163

1164
        STRV_FOREACH_PAIR(name, value, i->xattrs) {
×
1165
                log_action("Would set", "Setting",
×
1166
                           "%s extended attribute '%s=%s' on %s", *name, *value, path);
1167

1168
                if (!arg_dry_run) {
×
1169
                        r = xsetxattr(fd, /* path= */ NULL, AT_EMPTY_PATH, *name, *value);
×
1170
                        if (r < 0)
×
1171
                                return log_error_errno(r, "Failed to set extended attribute %s=%s on '%s': %m",
×
1172
                                                       *name, *value, path);
1173
                }
1174
        }
1175
        return 0;
1176
}
1177

1178
static int path_set_xattrs(
×
1179
                Context *c,
1180
                Item *i,
1181
                const char *path,
1182
                CreationMode creation) {
1183

1184
        _cleanup_close_ int fd = -EBADF;
×
1185

1186
        assert(c);
×
1187
        assert(i);
×
1188
        assert(path);
×
1189

1190
        fd = path_open_safe(path);
×
1191
        if (fd == -ENOENT)
×
1192
                return 0;
1193
        if (fd < 0)
×
1194
                return fd;
1195

1196
        return fd_set_xattrs(c, i, fd, path, /* st= */ NULL, creation);
×
1197
}
1198

1199
static int parse_acls_from_arg(Item *item) {
2,601✔
1200
#if HAVE_ACL
1201
        int r;
2,601✔
1202

1203
        assert(item);
2,601✔
1204

1205
        /* If append_or_force (= modify) is set, we will not modify the acl
1206
         * afterwards, so the mask can be added now if necessary. */
1207

1208
        r = parse_acl(item->argument, &item->acl_access, &item->acl_access_exec,
5,202✔
1209
                      &item->acl_default, !item->append_or_force);
2,601✔
1210
        if (r < 0)
2,601✔
1211
                log_full_errno(arg_graceful && IN_SET(r, -EINVAL, -ENOENT, -ESRCH) ? LOG_DEBUG : LOG_WARNING,
×
1212
                               r, "Failed to parse ACL \"%s\", ignoring: %m", item->argument);
1213
#else
1214
        log_warning("ACLs are not supported, ignoring.");
1215
#endif
1216

1217
        return 0;
2,601✔
1218
}
1219

1220
#if HAVE_ACL
1221
static int parse_acl_cond_exec(
339✔
1222
                const char *path,
1223
                const struct stat *st,
1224
                acl_t cond_exec,
1225
                acl_t access, /* could be empty (NULL) */
1226
                bool append,
1227
                acl_t *ret) {
1228

1229
        acl_entry_t entry;
339✔
1230
        acl_permset_t permset;
339✔
1231
        bool has_exec;
339✔
1232
        int r;
339✔
1233

1234
        assert(path);
339✔
1235
        assert(st);
339✔
1236
        assert(cond_exec);
339✔
1237
        assert(ret);
339✔
1238

1239
        r = dlopen_libacl();
339✔
1240
        if (r < 0)
339✔
1241
                return r;
339✔
1242

1243
        if (!S_ISDIR(st->st_mode)) {
339✔
1244
                _cleanup_(acl_freep) acl_t old = NULL;
236✔
1245

1246
                old = sym_acl_get_file(path, ACL_TYPE_ACCESS);
236✔
1247
                if (!old)
236✔
1248
                        return -errno;
×
1249

1250
                has_exec = false;
236✔
1251

1252
                for (r = sym_acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
236✔
1253
                     r > 0;
932✔
1254
                     r = sym_acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
696✔
1255

1256
                        acl_tag_t tag;
712✔
1257

1258
                        if (sym_acl_get_tag_type(entry, &tag) < 0)
712✔
1259
                                return -errno;
×
1260

1261
                        if (tag == ACL_MASK)
712✔
1262
                                continue;
8✔
1263

1264
                        /* If not appending, skip ACL definitions */
1265
                        if (!append && IN_SET(tag, ACL_USER, ACL_GROUP))
706✔
1266
                                continue;
2✔
1267

1268
                        if (sym_acl_get_permset(entry, &permset) < 0)
704✔
1269
                                return -errno;
×
1270

1271
                        r = sym_acl_get_perm(permset, ACL_EXECUTE);
704✔
1272
                        if (r < 0)
704✔
1273
                                return -errno;
×
1274
                        if (r > 0) {
704✔
1275
                                has_exec = true;
16✔
1276
                                break;
16✔
1277
                        }
1278
                }
1279
                if (r < 0)
236✔
1280
                        return -errno;
×
1281

1282
                /* Check if we're about to set the execute bit in acl_access */
1283
                if (!has_exec && access) {
236✔
1284
                        for (r = sym_acl_get_entry(access, ACL_FIRST_ENTRY, &entry);
×
1285
                             r > 0;
×
1286
                             r = sym_acl_get_entry(access, ACL_NEXT_ENTRY, &entry)) {
×
1287

1288
                                if (sym_acl_get_permset(entry, &permset) < 0)
×
1289
                                        return -errno;
×
1290

1291
                                r = sym_acl_get_perm(permset, ACL_EXECUTE);
×
1292
                                if (r < 0)
×
1293
                                        return -errno;
×
1294
                                if (r > 0) {
×
1295
                                        has_exec = true;
1296
                                        break;
1297
                                }
1298
                        }
1299
                        if (r < 0)
×
1300
                                return -errno;
×
1301
                }
1302
        } else
1303
                has_exec = true;
1304

1305
        _cleanup_(acl_freep) acl_t parsed = access ? sym_acl_dup(access) : sym_acl_init(0);
678✔
1306
        if (!parsed)
339✔
1307
                return -errno;
×
1308

1309
        for (r = sym_acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
339✔
1310
             r > 0;
1,013✔
1311
             r = sym_acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
674✔
1312

1313
                acl_entry_t parsed_entry;
674✔
1314

1315
                if (sym_acl_create_entry(&parsed, &parsed_entry) < 0)
674✔
1316
                        return -errno;
×
1317

1318
                if (sym_acl_copy_entry(parsed_entry, entry) < 0)
674✔
1319
                        return -errno;
×
1320

1321
                /* We substituted 'X' with 'x' in parse_acl(), so drop execute bit here if not applicable. */
1322
                if (!has_exec) {
674✔
1323
                        if (sym_acl_get_permset(parsed_entry, &permset) < 0)
437✔
1324
                                return -errno;
×
1325

1326
                        if (sym_acl_delete_perm(permset, ACL_EXECUTE) < 0)
437✔
1327
                                return -errno;
×
1328
                }
1329
        }
1330
        if (r < 0)
339✔
1331
                return -errno;
×
1332

1333
        if (!append) { /* want_mask = true */
339✔
1334
                r = calc_acl_mask_if_needed(&parsed);
3✔
1335
                if (r < 0)
3✔
1336
                        return r;
1337
        }
1338

1339
        *ret = TAKE_PTR(parsed);
339✔
1340

1341
        return 0;
339✔
1342
}
1343

1344
static int path_set_acl(
1,070✔
1345
                Context *c,
1346
                const char *path,
1347
                const char *pretty,
1348
                acl_type_t type,
1349
                acl_t acl,
1350
                bool modify) {
1351

1352
        _cleanup_(acl_free_charpp) char *t = NULL;
1,070✔
1353
        _cleanup_(acl_freep) acl_t dup = NULL;
1,070✔
1354
        int r;
1,070✔
1355

1356
        assert(c);
1,070✔
1357

1358
        r = dlopen_libacl();
1,070✔
1359
        if (r < 0)
1,070✔
1360
                return r;
1361

1362
        /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1363

1364
        if (modify) {
1,070✔
1365
                r = acls_for_file(path, type, acl, &dup);
1,067✔
1366
                if (r < 0)
1,067✔
1367
                        return r;
1368

1369
                r = calc_acl_mask_if_needed(&dup);
1,067✔
1370
                if (r < 0)
1,067✔
1371
                        return r;
1372
        } else {
1373
                dup = sym_acl_dup(acl);
3✔
1374
                if (!dup)
3✔
1375
                        return -errno;
×
1376

1377
                /* the mask was already added earlier if needed */
1378
        }
1379

1380
        r = add_base_acls_if_needed(&dup, path);
1,070✔
1381
        if (r < 0)
1,070✔
1382
                return r;
1383

1384
        t = sym_acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1,070✔
1385
        log_action("Would set", "Setting",
2,611✔
1386
                   "%s %s ACL %s on %s",
1387
                   type == ACL_TYPE_ACCESS ? "access" : "default",
1388
                   strna(t), pretty);
1389

1390
        if (!arg_dry_run &&
2,139✔
1391
            sym_acl_set_file(path, type, dup) < 0) {
1,069✔
1392
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
1393
                        /* No error if filesystem doesn't support ACLs. Return negative. */
1394
                        return -errno;
×
1395
                else
1396
                        /* Return positive to indicate we already warned */
1397
                        return -log_error_errno(errno,
×
1398
                                                "Setting %s ACL \"%s\" on %s failed: %m",
1399
                                                type == ACL_TYPE_ACCESS ? "access" : "default",
1400
                                                strna(t), pretty);
1401
        }
1402
        return 0;
1403
}
1404
#endif
1405

1406
static int fd_set_acls(
792✔
1407
                Context *c,
1408
                Item *item,
1409
                int fd,
1410
                const char *path,
1411
                const struct stat *st,
1412
                CreationMode creation) {
1413

1414
        int r = 0;
792✔
1415
#if HAVE_ACL
1416
        _cleanup_(acl_freep) acl_t access_with_exec_parsed = NULL;
792✔
1417
        struct stat stbuf;
792✔
1418

1419
        assert(c);
792✔
1420
        assert(item);
792✔
1421
        assert(fd >= 0);
792✔
1422
        assert(path);
792✔
1423

1424
        if (!st) {
792✔
1425
                if (fstat(fd, &stbuf) < 0)
457✔
1426
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1427
                st = &stbuf;
1428
        }
1429

1430
        if (hardlink_vulnerable(st))
792✔
1431
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
1432
                                       "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1433
                                       path);
1434

1435
        if (!inode_type_can_acl(st->st_mode)) {
792✔
1436
                log_debug("Skipping ACL fix for '%s' (inode type does not support ACLs).", path);
×
1437
                return 0;
×
1438
        }
1439

1440
        if (item->acl_access_exec) {
792✔
1441
                r = parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd), st,
339✔
1442
                                        item->acl_access_exec,
1443
                                        item->acl_access,
1444
                                        item->append_or_force,
339✔
1445
                                        &access_with_exec_parsed);
1446
                if (r < 0)
339✔
1447
                        return log_error_errno(r, "Failed to parse conditionalized execute bit for \"%s\": %m", path);
×
1448

1449
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
339✔
1450
        } else if (item->acl_access)
453✔
1451
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
199✔
1452

1453
        /* set only default acls to folders */
1454
        if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
792✔
1455
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
532✔
1456

1457
        if (ERRNO_IS_NOT_SUPPORTED(r)) {
792✔
1458
                log_debug_errno(r, "ACLs not supported by file system at %s", path);
×
1459
                return 0;
×
1460
        }
1461
        if (r > 0)
792✔
1462
                return -r; /* already warned in path_set_acl */
×
1463
        if (r < 0)
792✔
1464
                return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
×
1465
#endif
1466
        return r;
1467
}
1468

1469
static int path_set_acls(
457✔
1470
                Context *c,
1471
                Item *item,
1472
                const char *path,
1473
                CreationMode creation) {
1474

1475
        int r = 0;
457✔
1476
#if HAVE_ACL
1477
        _cleanup_close_ int fd = -EBADF;
457✔
1478

1479
        assert(c);
457✔
1480
        assert(item);
457✔
1481
        assert(path);
457✔
1482

1483
        fd = path_open_safe(path);
457✔
1484
        if (fd == -ENOENT)
457✔
1485
                return 0;
1486
        if (fd < 0)
457✔
1487
                return fd;
1488

1489
        r = fd_set_acls(c, item, fd, path, /* st= */ NULL, creation);
457✔
1490
#endif
1491
        return r;
1492
}
1493

1494
static int parse_attribute_from_arg(Item *item) {
1,113✔
1495
        static const struct {
1,113✔
1496
                char character;
1497
                unsigned value;
1498
        } attributes[] = {
1499
                { 'A', FS_NOATIME_FL },      /* do not update atime */
1500
                { 'S', FS_SYNC_FL },         /* Synchronous updates */
1501
                { 'D', FS_DIRSYNC_FL },      /* dirsync behaviour (directories only) */
1502
                { 'a', FS_APPEND_FL },       /* writes to file may only append */
1503
                { 'c', FS_COMPR_FL },        /* Compress file */
1504
                { 'd', FS_NODUMP_FL },       /* do not dump file */
1505
                { 'e', FS_EXTENT_FL },       /* Extents */
1506
                { 'i', FS_IMMUTABLE_FL },    /* Immutable file */
1507
                { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1508
                { 's', FS_SECRM_FL },        /* Secure deletion */
1509
                { 'u', FS_UNRM_FL },         /* Undelete */
1510
                { 't', FS_NOTAIL_FL },       /* file tail should not be merged */
1511
                { 'T', FS_TOPDIR_FL },       /* Top of directory hierarchies */
1512
                { 'C', FS_NOCOW_FL },        /* Do not cow file */
1513
                { 'P', FS_PROJINHERIT_FL },  /* Inherit the quota project ID */
1514
        };
1515

1516
        enum {
1,113✔
1517
                MODE_ADD,
1518
                MODE_DEL,
1519
                MODE_SET
1520
        } mode = MODE_ADD;
1,113✔
1521

1522
        unsigned value = 0, mask = 0;
1,113✔
1523
        const char *p;
1,113✔
1524

1525
        assert(item);
1,113✔
1526

1527
        p = item->argument;
1,113✔
1528
        if (p) {
1,113✔
1529
                if (*p == '+') {
1,113✔
1530
                        mode = MODE_ADD;
1,113✔
1531
                        p++;
1,113✔
1532
                } else if (*p == '-') {
×
1533
                        mode = MODE_DEL;
×
1534
                        p++;
×
1535
                } else  if (*p == '=') {
×
1536
                        mode = MODE_SET;
×
1537
                        p++;
×
1538
                }
1539
        }
1540

1541
        if (isempty(p) && mode != MODE_SET)
1,113✔
1542
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1543
                                       "Setting file attribute on '%s' needs an attribute specification.",
1544
                                       item->path);
1545

1546
        for (; p && *p ; p++) {
2,226✔
1547
                unsigned i, v;
1548

1549
                for (i = 0; i < ELEMENTSOF(attributes); i++)
15,582✔
1550
                        if (*p == attributes[i].character)
15,582✔
1551
                                break;
1552

1553
                if (i >= ELEMENTSOF(attributes))
1,113✔
1554
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1555
                                               "Unknown file attribute '%c' on '%s'.", *p, item->path);
1556

1557
                v = attributes[i].value;
1,113✔
1558

1559
                SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1,113✔
1560

1561
                mask |= v;
1,113✔
1562
        }
1563

1564
        if (mode == MODE_SET)
1,113✔
1565
                mask |= CHATTR_ALL_FL;
×
1566

1567
        assert(mask != 0);
1,113✔
1568

1569
        item->attribute_mask = mask;
1,113✔
1570
        item->attribute_value = value;
1,113✔
1571
        item->attribute_set = true;
1,113✔
1572

1573
        return 0;
1,113✔
1574
}
1575

1576
static int fd_set_attribute(
48✔
1577
                Context *c,
1578
                Item *item,
1579
                int fd,
1580
                const char *path,
1581
                const struct stat *st,
1582
                CreationMode creation) {
1583

1584
        struct stat stbuf;
48✔
1585
        unsigned f;
48✔
1586
        int r;
48✔
1587

1588
        assert(c);
48✔
1589
        assert(item);
48✔
1590
        assert(fd >= 0);
48✔
1591
        assert(path);
48✔
1592

1593
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1594
                return 0;
48✔
1595

1596
        if (!st) {
48✔
1597
                if (fstat(fd, &stbuf) < 0)
48✔
1598
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1599
                st = &stbuf;
1600
        }
1601

1602
        /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1603
         * drivers, not the file system containing the device node. */
1604
        if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode))
48✔
1605
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1606
                                       "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1607
                                       path);
1608

1609
        f = item->attribute_value & item->attribute_mask;
48✔
1610

1611
        /* Mask away directory-specific flags */
1612
        if (!S_ISDIR(st->st_mode))
48✔
1613
                f &= ~FS_DIRSYNC_FL;
×
1614

1615
        log_action("Would try to set", "Trying to set",
96✔
1616
                   "%s file attributes 0x%08x on %s",
1617
                   f & item->attribute_mask,
1618
                   path);
1619

1620
        if (!arg_dry_run) {
48✔
1621
                _cleanup_close_ int procfs_fd = -EBADF;
48✔
1622

1623
                procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
48✔
1624
                if (procfs_fd < 0)
48✔
1625
                        return log_error_errno(procfs_fd, "Failed to reopen '%s': %m", path);
×
1626

1627
                unsigned previous, current;
48✔
1628
                r = chattr_full(procfs_fd, NULL, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
48✔
1629
                if (r == -ENOANO)
48✔
1630
                        log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
×
1631
                                    "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1632
                                    path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1633
                else if (r < 0)
48✔
1634
                        log_full_errno(ERRNO_IS_IOCTL_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
48✔
1635
                                       "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1636
                                       path, item->attribute_value, item->attribute_mask);
1637
        }
1638

1639
        return 0;
1640
}
1641

1642
static int path_set_attribute(
48✔
1643
                Context *c,
1644
                Item *item,
1645
                const char *path,
1646
                CreationMode creation) {
1647

1648
        _cleanup_close_ int fd = -EBADF;
48✔
1649

1650
        assert(c);
48✔
1651
        assert(item);
48✔
1652

1653
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1654
                return 0;
1655

1656
        fd = path_open_safe(path);
48✔
1657
        if (fd == -ENOENT)
48✔
1658
                return 0;
1659
        if (fd < 0)
48✔
1660
                return fd;
1661

1662
        return fd_set_attribute(c, item, fd, path, /* st= */ NULL, creation);
48✔
1663
}
1664

1665
static int write_argument_data(Item *i, int fd, const char *path) {
272✔
1666
        int r;
272✔
1667

1668
        assert(i);
272✔
1669
        assert(fd >= 0);
272✔
1670
        assert(path);
272✔
1671

1672
        if (item_binary_argument_size(i) == 0)
272✔
1673
                return 0;
1674

1675
        assert(item_binary_argument(i));
264✔
1676

1677
        log_action("Would write", "Writing", "%s to \"%s\"", path);
496✔
1678

1679
        if (!arg_dry_run) {
264✔
1680
                r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i));
261✔
1681
                if (r < 0)
261✔
1682
                        return log_error_errno(r, "Failed to write file \"%s\": %m", path);
×
1683
        }
1684

1685
        return 0;
1686
}
1687

1688
static int write_one_file(Context *c, Item *i, const char *path, CreationMode creation) {
18✔
1689
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
18✔
1690
        _cleanup_free_ char *bn = NULL;
18✔
1691
        int r;
18✔
1692

1693
        assert(c);
18✔
1694
        assert(i);
18✔
1695
        assert(path);
18✔
1696
        assert(i->type == WRITE_FILE);
18✔
1697

1698
        r = path_extract_filename(path, &bn);
18✔
1699
        if (r < 0)
18✔
1700
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1701
        if (r == O_DIRECTORY)
18✔
1702
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1703

1704
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1705
         * can't be changed behind our back. */
1706
        dir_fd = path_open_parent_safe(path, i->allow_failure);
18✔
1707
        if (dir_fd < 0)
18✔
1708
                return dir_fd;
1709

1710
        /* Follow symlinks. Open with O_PATH in dry-run mode to make sure we don't use the path inadvertently. */
1711
        int flags = O_NONBLOCK | O_CLOEXEC | O_WRONLY | O_NOCTTY | i->append_or_force * O_APPEND | arg_dry_run * O_PATH;
18✔
1712
        fd = openat(dir_fd, bn, flags, i->mode);
18✔
1713
        if (fd < 0) {
18✔
1714
                if (errno == ENOENT) {
×
1715
                        log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
×
1716
                        return 0;
×
1717
                }
1718

1719
                if (i->allow_failure)
×
1720
                        return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
×
1721

1722
                return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
×
1723
        }
1724

1725
        /* 'w' is allowed to write into any kind of files. */
1726

1727
        r = write_argument_data(i, fd, path);
18✔
1728
        if (r < 0)
18✔
1729
                return r;
1730

1731
        return fd_set_perms(c, i, fd, path, NULL, creation);
18✔
1732
}
1733

1734
static int create_file(
800✔
1735
                Context *c,
1736
                Item *i,
1737
                const char *path) {
1738

1739
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
800✔
1740
        _cleanup_free_ char *bn = NULL;
800✔
1741
        struct stat stbuf, *st = NULL;
800✔
1742
        CreationMode creation;
800✔
1743
        int r = 0;
800✔
1744

1745
        assert(c);
800✔
1746
        assert(i);
800✔
1747
        assert(path);
800✔
1748
        assert(i->type == CREATE_FILE);
800✔
1749

1750
        /* 'f' operates on regular files exclusively. */
1751

1752
        r = path_extract_filename(path, &bn);
800✔
1753
        if (r < 0)
800✔
1754
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1755
        if (r == O_DIRECTORY)
800✔
1756
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1757

1758
        if (arg_dry_run) {
800✔
1759
                log_info("Would create file %s", path);
4✔
1760
                return 0;
4✔
1761

1762
                /* The opening of the directory below would fail if it doesn't exist,
1763
                 * so log and exit before even trying to do that. */
1764
        }
1765

1766
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1767
         * can't be changed behind our back. */
1768
        dir_fd = path_open_parent_safe(path, i->allow_failure);
796✔
1769
        if (dir_fd < 0)
796✔
1770
                return dir_fd;
1771

1772
        WITH_UMASK(0000) {
1,588✔
1773
                mac_selinux_create_file_prepare(path, S_IFREG);
794✔
1774
                fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
794✔
1775
                mac_selinux_create_file_clear();
794✔
1776
        }
1777

1778
        if (fd < 0) {
794✔
1779
                /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1780
                 * returns EROFS only if it needs to create the file. */
1781
                if (fd != -EEXIST)
664✔
1782
                        return log_error_errno(fd, "Failed to create file %s: %m", path);
1✔
1783

1784
                /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1785
                 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1786
                 * fd_set_perms() report the error if the perms need to be modified. */
1787
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
663✔
1788
                if (fd < 0)
663✔
1789
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
×
1790

1791
                if (fstat(fd, &stbuf) < 0)
663✔
1792
                        return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1793

1794
                if (!S_ISREG(stbuf.st_mode))
663✔
1795
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
5✔
1796
                                               "%s exists and is not a regular file.",
1797
                                               path);
1798

1799
                st = &stbuf;
1800
                creation = CREATION_EXISTING;
1801
        } else {
1802
                r = write_argument_data(i, fd, path);
130✔
1803
                if (r < 0)
130✔
1804
                        return r;
1805

1806
                creation = CREATION_NORMAL;
1807
        }
1808

1809
        return fd_set_perms(c, i, fd, path, st, creation);
788✔
1810
}
1811

1812
static int truncate_file(
255✔
1813
                Context *c,
1814
                Item *i,
1815
                const char *path) {
1816

1817
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
255✔
1818
        _cleanup_free_ char *bn = NULL;
255✔
1819
        struct stat stbuf, *st = NULL;
255✔
1820
        CreationMode creation;
255✔
1821
        bool erofs = false;
255✔
1822
        int r = 0;
255✔
1823

1824
        assert(c);
255✔
1825
        assert(i);
255✔
1826
        assert(path);
255✔
1827
        assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
255✔
1828

1829
        /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1830
         * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1831
         * make sure it's a regular one before truncating it. */
1832

1833
        r = path_extract_filename(path, &bn);
255✔
1834
        if (r < 0)
255✔
1835
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1836
        if (r == O_DIRECTORY)
255✔
1837
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
×
1838

1839
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1840
         * can't be changed behind our back. */
1841
        dir_fd = path_open_parent_safe(path, i->allow_failure);
255✔
1842
        if (dir_fd < 0)
255✔
1843
                return dir_fd;
1844

1845
        if (arg_dry_run) {
254✔
1846
                log_info("Would truncate %s", path);
×
1847
                return 0;
×
1848
        }
1849

1850
        creation = CREATION_EXISTING;
254✔
1851
        fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
254✔
1852
        if (fd == -ENOENT) {
230✔
1853
                creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
225✔
1854

1855
                WITH_UMASK(0000) {
450✔
1856
                        mac_selinux_create_file_prepare(path, S_IFREG);
225✔
1857
                        fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
225✔
1858
                        mac_selinux_create_file_clear();
225✔
1859
                }
1860
        }
1861

1862
        if (fd < 0) {
254✔
1863
                if (fd != -EROFS)
6✔
1864
                        return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1✔
1865

1866
                /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1867
                 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1868
                 * fail with EROFS if they try to modify the target file. */
1869

1870
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
5✔
1871
                if (fd < 0) {
5✔
1872
                        if (errno == ENOENT)
1✔
1873
                                return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1✔
1874
                                                       "Cannot create file %s on a read-only file system.",
1875
                                                       path);
1876

1877
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
×
1878
                }
1879

1880
                erofs = true;
1881
                creation = CREATION_EXISTING;
1882
        }
1883

1884
        if (fstat(fd, &stbuf) < 0)
252✔
1885
                return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1886

1887
        if (!S_ISREG(stbuf.st_mode))
252✔
1888
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1889
                                       "%s exists and is not a regular file.",
1890
                                       path);
1891

1892
        if (stbuf.st_size > 0) {
252✔
1893
                if (ftruncate(fd, 0) < 0) {
15✔
1894
                        r = erofs ? -EROFS : -errno;
2✔
1895
                        return log_error_errno(r, "Failed to truncate file %s: %m", path);
2✔
1896
                }
1897
        } else
1898
                st = &stbuf;
1899

1900
        log_debug("\"%s\" has been created.", path);
250✔
1901

1902
        if (item_binary_argument(i)) {
250✔
1903
                r = write_argument_data(i, fd, path);
124✔
1904
                if (r < 0)
124✔
1905
                        return r;
1906
        }
1907

1908
        return fd_set_perms(c, i, fd, path, st, creation);
250✔
1909
}
1910

1911
static int copy_files(Context *c, Item *i) {
3,921✔
1912
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
3,921✔
1913
        _cleanup_free_ char *bn = NULL;
3,921✔
1914
        struct stat st, a;
3,921✔
1915
        int r;
3,921✔
1916

1917
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
7,703✔
1918
        if (arg_dry_run)
3,921✔
1919
                return 0;
1920

1921
        r = path_extract_filename(i->path, &bn);
3,919✔
1922
        if (r < 0)
3,919✔
1923
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
1924

1925
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1926
         * path can't be changed behind our back. */
1927
        dfd = path_open_parent_safe(i->path, i->allow_failure);
3,919✔
1928
        if (dfd < 0)
3,919✔
1929
                return dfd;
1930

1931
        r = copy_tree_at(AT_FDCWD, i->argument,
3,923✔
1932
                         dfd, bn,
1933
                         i->uid_set ? i->uid : UID_INVALID,
3,919✔
1934
                         i->gid_set ? i->gid : GID_INVALID,
3,919✔
1935
                         COPY_REFLINK | ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
3,919✔
1936
                         NULL, NULL);
1937

1938
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
3,919✔
1939
        if (fd < 0) {
3,919✔
1940
                if (r < 0) /* Look at original error first */
×
1941
                        return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
×
1942

1943
                return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
×
1944
        }
1945

1946
        if (fstat(fd, &st) < 0)
3,919✔
1947
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
1948

1949
        if (stat(i->argument, &a) < 0)
3,919✔
1950
                return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
×
1951

1952
        if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
3,919✔
1953
                log_debug("Can't copy to %s, file exists already and is of different type", i->path);
×
1954
                return 0;
×
1955
        }
1956

1957
        return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
3,919✔
1958
}
1959

1960
static int create_directory_or_subvolume(
8,870✔
1961
                const char *path,
1962
                mode_t mode,
1963
                bool subvol,
1964
                bool allow_failure,
1965
                struct stat *ret_st,
1966
                CreationMode *ret_creation) {
1967

1968
        _cleanup_free_ char *bn = NULL;
8,870✔
1969
        _cleanup_close_ int pfd = -EBADF;
8,870✔
1970
        CreationMode creation;
8,870✔
1971
        struct stat st;
8,870✔
1972
        int r, fd;
8,870✔
1973

1974
        assert(path);
8,870✔
1975

1976
        r = path_extract_filename(path, &bn);
8,870✔
1977
        if (r < 0)
8,870✔
1978
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1979

1980
        pfd = path_open_parent_safe(path, allow_failure);
8,870✔
1981
        if (pfd < 0)
8,870✔
1982
                return pfd;
1983

1984
        if (subvol) {
8,868✔
1985
                r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
889✔
1986
                if (r < 0) {
889✔
1987
                        if (r != -ENXIO) /* env var is unset */
889✔
1988
                                log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
×
1989
                        r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
889✔
1990
                }
1991
                if (r == 0)
889✔
1992
                        /* Don't create a subvolume unless the root directory is one, too. We do this under
1993
                         * the assumption that if the root directory is just a plain directory (i.e. very
1994
                         * lightweight), we shouldn't try to split it up into subvolumes (i.e. more
1995
                         * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1996
                         * subvolume set up below their tree only if they specifically set up a btrfs
1997
                         * subvolume for the root dir too. */
1998
                        subvol = false;
1999
                else {
2000
                        log_action("Would create", "Creating", "%s btrfs subvolume %s", path);
×
2001
                        if (!arg_dry_run)
×
2002
                                WITH_UMASK((~mode) & 0777)
×
2003
                                        r = btrfs_subvol_make(pfd, bn);
×
2004
                        else
2005
                                r = 0;
2006
                }
2007
        } else
2008
                r = 0;
2009

2010
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2011
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
17,421✔
2012
                if (!arg_dry_run)
8,868✔
2013
                        WITH_UMASK(0000)
17,736✔
2014
                                r = mkdirat_label(pfd, bn, mode);
8,868✔
2015
        }
2016

2017
        if (arg_dry_run)
8,868✔
2018
                return 0;
2019

2020
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
8,868✔
2021

2022
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
8,868✔
2023
        if (fd < 0) {
8,868✔
2024
                /* We couldn't open it because it is not actually a directory? */
2025
                if (errno == ENOTDIR)
×
2026
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
×
2027

2028
                /* Then look at the original error */
2029
                if (r < 0)
×
2030
                        return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
2031
                                              r,
2032
                                              "Failed to create directory or subvolume \"%s\"%s: %m",
2033
                                              path,
2034
                                              allow_failure ? ", ignoring" : "");
2035

2036
                return log_error_errno(errno, "Failed to open directory/subvolume we just created '%s': %m", path);
×
2037
        }
2038

2039
        if (fstat(fd, &st) < 0)
8,868✔
2040
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2041

2042
        assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
8,868✔
2043

2044
        log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
8,868✔
2045

2046
        if (ret_st)
8,868✔
2047
                *ret_st = st;
8,868✔
2048
        if (ret_creation)
8,868✔
2049
                *ret_creation = creation;
8,868✔
2050

2051
        return fd;
2052
}
2053

2054
static int create_directory(
7,992✔
2055
                Context *c,
2056
                Item *i,
2057
                const char *path) {
2058

2059
        _cleanup_close_ int fd = -EBADF;
7,992✔
2060
        CreationMode creation;
7,992✔
2061
        struct stat st;
7,992✔
2062

2063
        assert(c);
7,992✔
2064
        assert(i);
7,992✔
2065
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
7,992✔
2066

2067
        if (arg_dry_run) {
7,992✔
2068
                log_info("Would create directory %s", path);
11✔
2069
                return 0;
11✔
2070
        }
2071

2072
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
7,981✔
2073
        if (fd == -EEXIST)
7,981✔
2074
                return 0;
2075
        if (fd < 0)
7,981✔
2076
                return fd;
2077

2078
        return fd_set_perms(c, i, fd, path, &st, creation);
7,979✔
2079
}
2080

2081
static int create_subvolume(
889✔
2082
                Context *c,
2083
                Item *i,
2084
                const char *path) {
2085

2086
        _cleanup_close_ int fd = -EBADF;
889✔
2087
        CreationMode creation;
889✔
2088
        struct stat st;
889✔
2089
        int r, q = 0;
889✔
2090

2091
        assert(c);
889✔
2092
        assert(i);
889✔
2093
        assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
889✔
2094

2095
        if (arg_dry_run) {
889✔
2096
                log_info("Would create subvolume %s", path);
×
2097
                return 0;
×
2098
        }
2099

2100
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ true, i->allow_failure, &st, &creation);
889✔
2101
        if (fd == -EEXIST)
889✔
2102
                return 0;
2103
        if (fd < 0)
889✔
2104
                return fd;
2105

2106
        if (creation == CREATION_NORMAL &&
889✔
2107
            IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
3✔
2108
                r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
3✔
2109
                if (r == -ENOTTY)
3✔
2110
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
3✔
2111
                else if (r == -EROFS)
×
2112
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
×
2113
                else if (r == -ENOTCONN)
×
2114
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
×
2115
                else if (r < 0)
×
2116
                        q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
×
2117
                else if (r > 0)
×
2118
                        log_debug("Adjusted quota for subvolume \"%s\".", i->path);
×
2119
                else if (r == 0)
×
2120
                        log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
×
2121
        }
2122

2123
        r = fd_set_perms(c, i, fd, path, &st, creation);
889✔
2124
        if (q < 0) /* prefer the quota change error from above */
889✔
2125
                return q;
×
2126

2127
        return r;
2128
}
2129

2130
static int empty_directory(
5✔
2131
                Context *c,
2132
                Item *i,
2133
                const char *path,
2134
                CreationMode creation) {
2135

2136
        _cleanup_close_ int fd = -EBADF;
5✔
2137
        struct stat st;
5✔
2138
        int r;
5✔
2139

2140
        assert(c);
5✔
2141
        assert(i);
5✔
2142
        assert(i->type == EMPTY_DIRECTORY);
5✔
2143

2144
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
5✔
2145
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
5✔
2146
                return r;
2147
        if (r == -ENOENT) {
5✔
2148
                /* Option "e" operates only on existing objects. Do not print errors about non-existent files
2149
                 * or directories */
2150
                log_debug_errno(r, "Skipping missing directory: %s", path);
×
2151
                return 0;
×
2152
        }
2153
        if (r < 0)
5✔
2154
                return log_error_errno(r, "Failed to open directory '%s': %m", path);
×
2155

2156
        if (fstat(fd, &st) < 0)
5✔
2157
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2158
        if (!S_ISDIR(st.st_mode)) {
5✔
2159
                log_warning("'%s' already exists and is not a directory.", path);
1✔
2160
                return 0;
1✔
2161
        }
2162

2163
        return fd_set_perms(c, i, fd, path, &st, creation);
4✔
2164
}
2165

2166
static int create_device(
2,014✔
2167
                Context *c,
2168
                Item *i,
2169
                mode_t file_type) {
2170

2171
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
2,014✔
2172
        _cleanup_free_ char *bn = NULL;
2,014✔
2173
        CreationMode creation;
2,014✔
2174
        struct stat st;
2,014✔
2175
        int r;
2,014✔
2176

2177
        assert(c);
2,014✔
2178
        assert(i);
2,014✔
2179
        assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
2,014✔
2180
        assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
2,014✔
2181

2182
        r = path_extract_filename(i->path, &bn);
2,014✔
2183
        if (r < 0)
2,014✔
2184
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2185
        if (r == O_DIRECTORY)
2,014✔
2186
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2187
                                       "Cannot open path '%s' for creating device node, is a directory.", i->path);
2188

2189
        if (arg_dry_run) {
2,014✔
2190
                log_info("Would create device node %s", i->path);
4✔
2191
                return 0;
4✔
2192
        }
2193

2194
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2195
         * path can't be changed behind our back. */
2196
        dfd = path_open_parent_safe(i->path, i->allow_failure);
2,010✔
2197
        if (dfd < 0)
2,010✔
2198
                return dfd;
2199

2200
        WITH_UMASK(0000) {
4,020✔
2201
                mac_selinux_create_file_prepare(i->path, file_type);
2,010✔
2202
                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
2,010✔
2203
                mac_selinux_create_file_clear();
2,010✔
2204
        }
2205
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2,010✔
2206

2207
        /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2208
         * order anyway and we hence can ignore the error to create the device node */
2209
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2,010✔
2210
        if (fd < 0) {
2,010✔
2211
                /* OK, so opening the inode failed, let's look at the original error then. */
2212

2213
                if (r < 0) {
×
2214
                        if (ERRNO_IS_PRIVILEGE(r))
×
2215
                                goto handle_privilege;
×
2216

2217
                        return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
×
2218
                }
2219

2220
                return log_error_errno(errno, "Failed to open device node '%s' we just created: %m", i->path);
×
2221
        }
2222

2223
        if (fstat(fd, &st) < 0)
2,010✔
2224
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2225

2226
        if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
2,010✔
2227

2228
                if (i->append_or_force) {
×
2229
                        fd = safe_close(fd);
×
2230

2231
                        WITH_UMASK(0000) {
×
2232
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2233
                                r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
×
2234
                                mac_selinux_create_file_clear();
×
2235
                        }
2236
                        if (ERRNO_IS_PRIVILEGE(r))
×
2237
                                goto handle_privilege;
×
2238
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
×
2239
                                r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
×
2240
                                if (r < 0)
×
2241
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2242

2243
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2244
                                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
×
2245
                                mac_selinux_create_file_clear();
×
2246
                        }
2247
                        if (r < 0)
×
2248
                                return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
×
2249

2250
                        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
×
2251
                        if (fd < 0)
×
2252
                                return log_error_errno(errno, "Failed to open device node we just created '%s': %m", i->path);
×
2253

2254
                        /* Validate type before change ownership below */
2255
                        if (fstat(fd, &st) < 0)
×
2256
                                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2257

2258
                        if (((st.st_mode ^ file_type) & S_IFMT) != 0)
×
2259
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2260
                                                       "Device node we just created is not a device node, refusing.");
2261

2262
                        creation = CREATION_FORCE;
2263
                } else {
2264
                        log_warning("\"%s\" already exists and is not a device node.", i->path);
×
2265
                        return 0;
×
2266
                }
2267
        }
2268

2269
        log_debug("%s %s device node \"%s\" %u:%u.",
4,020✔
2270
                  creation_mode_verb_to_string(creation),
2271
                  i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
2272
                  i->path, major(i->mode), minor(i->mode));
2273

2274
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2,010✔
2275

2276
handle_privilege:
×
2277
        log_debug_errno(r,
2,014✔
2278
                        "We lack permissions, possibly because of cgroup configuration; "
2279
                        "skipping creation of device node '%s'.", i->path);
2280
        return 0;
2281
}
2282

2283
static int create_fifo(Context *c, Item *i) {
4✔
2284
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
4✔
2285
        _cleanup_free_ char *bn = NULL;
4✔
2286
        CreationMode creation;
4✔
2287
        struct stat st;
4✔
2288
        int r;
4✔
2289

2290
        assert(c);
4✔
2291
        assert(i);
4✔
2292
        assert(i->type == CREATE_FIFO);
4✔
2293

2294
        r = path_extract_filename(i->path, &bn);
4✔
2295
        if (r < 0)
4✔
2296
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2297
        if (r == O_DIRECTORY)
4✔
2298
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2299
                                       "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2300

2301
        if (arg_dry_run) {
4✔
2302
                log_info("Would create fifo %s", i->path);
1✔
2303
                return 0;
1✔
2304
        }
2305

2306
        pfd = path_open_parent_safe(i->path, i->allow_failure);
3✔
2307
        if (pfd < 0)
3✔
2308
                return pfd;
2309

2310
        WITH_UMASK(0000) {
6✔
2311
                mac_selinux_create_file_prepare(i->path, S_IFIFO);
3✔
2312
                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
3✔
2313
                mac_selinux_create_file_clear();
3✔
2314
        }
2315

2316
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
3✔
2317

2318
        /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
2319
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
3✔
2320
        if (fd < 0) {
3✔
2321
                if (r < 0)
×
2322
                        return log_error_errno(r, "Failed to create FIFO %s: %m", i->path); /* original error! */
×
2323

2324
                return log_error_errno(errno, "Failed to open FIFO we just created %s: %m", i->path);
×
2325
        }
2326

2327
        if (fstat(fd, &st) < 0)
3✔
2328
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2329

2330
        if (!S_ISFIFO(st.st_mode)) {
3✔
2331

2332
                if (i->append_or_force) {
2✔
2333
                        fd = safe_close(fd);
1✔
2334

2335
                        WITH_UMASK(0000) {
2✔
2336
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
1✔
2337
                                r = mkfifoat_atomic(pfd, bn, i->mode);
1✔
2338
                                mac_selinux_create_file_clear();
1✔
2339
                        }
2340
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1✔
2341
                                r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
×
2342
                                if (r < 0)
×
2343
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2344

2345
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
×
2346
                                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
×
2347
                                mac_selinux_create_file_clear();
×
2348
                        }
2349
                        if (r < 0)
1✔
2350
                                return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
×
2351

2352
                        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1✔
2353
                        if (fd < 0)
1✔
2354
                                return log_error_errno(errno, "Failed to open FIFO we just created '%s': %m", i->path);
×
2355

2356
                        /* Validate type before change ownership below */
2357
                        if (fstat(fd, &st) < 0)
1✔
2358
                                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2359

2360
                        if (!S_ISFIFO(st.st_mode))
1✔
2361
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2362
                                                       "FIFO inode we just created is not a FIFO, refusing.");
2363

2364
                        creation = CREATION_FORCE;
2365
                } else {
2366
                        log_warning("\"%s\" already exists and is not a FIFO.", i->path);
1✔
2367
                        return 0;
1✔
2368
                }
2369
        }
2370

2371
        log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
2✔
2372

2373
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2✔
2374
}
2375

2376
static int create_symlink(Context *c, Item *i) {
2,555✔
2377
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
2,555✔
2378
        _cleanup_free_ char *bn = NULL;
2,555✔
2379
        CreationMode creation;
2,555✔
2380
        struct stat st;
2,555✔
2381
        bool good = false;
2,555✔
2382
        int r;
2,555✔
2383

2384
        assert(c);
2,555✔
2385
        assert(i);
2,555✔
2386

2387
        if (i->ignore_if_target_missing) {
2,555✔
2388
                r = chase(i->argument, arg_root, CHASE_SAFE|CHASE_PREFIX_ROOT|CHASE_NOFOLLOW, /* ret_path= */ NULL, /* ret_fd= */ NULL);
256✔
2389
                if (r == -ENOENT) {
256✔
2390
                        /* Silently skip over lines where the source file is missing. */
2391
                        log_debug_errno(r, "Symlink source path '%s/%s' does not exist, skipping line.",
499✔
2392
                                        strempty(arg_root), skip_leading_slash(i->argument));
2393
                        return 0;
255✔
2394
                }
2395
                if (r < 0)
1✔
2396
                        return log_error_errno(r, "Failed to check if symlink source path '%s/%s' exists: %m",
×
2397
                                               strempty(arg_root), skip_leading_slash(i->argument));
2398
        }
2399

2400
        r = path_extract_filename(i->path, &bn);
2,300✔
2401
        if (r < 0)
2,300✔
2402
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2403
        if (r == O_DIRECTORY)
2,300✔
2404
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2405
                                       "Cannot open path '%s' for creating symlink, is a directory.", i->path);
2406

2407
        if (arg_dry_run) {
2,300✔
2408
                log_info("Would create symlink %s -> %s", i->path, i->argument);
2✔
2409
                return 0;
2✔
2410
        }
2411

2412
        pfd = path_open_parent_safe(i->path, i->allow_failure);
2,298✔
2413
        if (pfd < 0)
2,298✔
2414
                return pfd;
2415

2416
        mac_selinux_create_file_prepare(i->path, S_IFLNK);
2,298✔
2417
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
2,298✔
2418
        mac_selinux_create_file_clear();
2,298✔
2419

2420
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2,298✔
2421

2422
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2,298✔
2423
        if (fd < 0) {
2,298✔
2424
                if (r < 0)
×
2425
                        return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
×
2426

2427
                return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
×
2428
        }
2429

2430
        if (fstat(fd, &st) < 0)
2,298✔
2431
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2432

2433
        if (S_ISLNK(st.st_mode)) {
2,298✔
2434
                _cleanup_free_ char *x = NULL;
×
2435

2436
                r = readlinkat_malloc(fd, "", &x);
2,297✔
2437
                if (r < 0)
2,297✔
2438
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
×
2439

2440
                good = streq(x, i->argument);
2,297✔
2441
        } else
2442
                good = false;
2443

2444
        if (!good) {
2,297✔
2445
                if (!i->append_or_force) {
512✔
2446
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
508✔
2447
                        return 0;
508✔
2448
                }
2449

2450
                fd = safe_close(fd);
4✔
2451

2452
                r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
4✔
2453
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
4✔
2454
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
1✔
2455
                        if (r < 0)
1✔
2456
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2457

2458
                        r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
1✔
2459
                }
2460
                if (r < 0)
4✔
2461
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2462

2463
                fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
4✔
2464
                if (fd < 0)
4✔
2465
                        return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
×
2466

2467
                /* Validate type before change ownership below */
2468
                if (fstat(fd, &st) < 0)
4✔
2469
                        return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2470

2471
                if (!S_ISLNK(st.st_mode))
4✔
2472
                        return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
×
2473

2474
                creation = CREATION_FORCE;
2475
        }
2476

2477
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
1,790✔
2478
        return fd_set_perms(c, i, fd, i->path, &st, creation);
1,790✔
2479
}
2480

2481
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2482
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2483

2484
static int item_do(
681✔
2485
                Context *c,
2486
                Item *i,
2487
                int fd,
2488
                const char *path,
2489
                CreationMode creation,
2490
                fdaction_t action) {
2491

2492
        struct stat st;
681✔
2493
        int r;
681✔
2494

2495
        assert(c);
681✔
2496
        assert(i);
681✔
2497
        assert(fd >= 0);
681✔
2498
        assert(path);
681✔
2499
        assert(action);
681✔
2500

2501
        if (fstat(fd, &st) < 0) {
681✔
2502
                r = log_error_errno(errno, "fstat() on file failed: %m");
×
2503
                goto finish;
×
2504
        }
2505

2506
        /* This returns the first error we run into, but nevertheless tries to go on */
2507
        r = action(c, i, fd, path, &st, creation);
681✔
2508

2509
        if (S_ISDIR(st.st_mode)) {
681✔
2510
                _cleanup_closedir_ DIR *d = NULL;
208✔
2511

2512
                /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2513
                 * reading the directory content. */
2514
                d = opendir(FORMAT_PROC_FD_PATH(fd));
208✔
2515
                if (!d) {
208✔
2516
                        RET_GATHER(r, log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd)));
×
2517
                        goto finish;
×
2518
                }
2519

2520
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
1,097✔
2521
                        _cleanup_close_ int de_fd = -EBADF;
889✔
2522
                        _cleanup_free_ char *de_path = NULL;
889✔
2523

2524
                        if (dot_or_dot_dot(de->d_name))
889✔
2525
                                continue;
416✔
2526

2527
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
473✔
2528
                        if (de_fd < 0) {
473✔
2529
                                if (errno != ENOENT)
×
2530
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
×
2531
                                continue;
×
2532
                        }
2533

2534
                        de_path = path_join(path, de->d_name);
473✔
2535
                        if (!de_path) {
473✔
2536
                                r = log_oom();
×
2537
                                goto finish;
×
2538
                        }
2539

2540
                        /* Pass ownership of dirent fd over */
2541
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
473✔
2542
                }
2543
        }
2544

2545
finish:
473✔
2546
        safe_close(fd);
681✔
2547
        return r;
681✔
2548
}
2549

2550
static int glob_item(Context *c, Item *i, action_t action) {
5,967✔
2551
        _cleanup_strv_free_ char **paths = NULL;
5,967✔
2552
        int r;
5,967✔
2553

2554
        assert(c);
5,967✔
2555
        assert(i);
5,967✔
2556
        assert(action);
5,967✔
2557

2558
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
5,967✔
2559
        if (r == -ENOENT)
5,967✔
2560
                return 0;
2561
        if (r < 0)
2,838✔
2562
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2563

2564
        r = 0;
2,838✔
2565
        STRV_FOREACH(fn, paths)
5,683✔
2566
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2567
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
2,845✔
2568

2569
        return r;
2570
}
2571

2572
static int glob_item_recursively(
256✔
2573
                Context *c,
2574
                Item *i,
2575
                fdaction_t action) {
2576

2577
        _cleanup_strv_free_ char **paths = NULL;
256✔
2578
        int r;
256✔
2579

2580
        assert(c);
256✔
2581
        assert(i);
256✔
2582
        assert(action);
256✔
2583

2584
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
256✔
2585
        if (r == -ENOENT)
256✔
2586
                return 0;
2587
        if (r < 0)
208✔
2588
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2589

2590
        r = 0;
208✔
2591
        STRV_FOREACH(fn, paths) {
416✔
2592
                _cleanup_close_ int fd = -EBADF;
208✔
2593

2594
                /* Make sure we won't trigger/follow file object (such as device nodes, automounts, ...)
2595
                 * pointed out by 'fn' with O_PATH. Note, when O_PATH is used, flags other than
2596
                 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2597

2598
                fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
208✔
2599
                if (fd < 0) {
208✔
2600
                        RET_GATHER(r, log_error_errno(errno, "Failed to open '%s': %m", *fn));
×
2601
                        continue;
×
2602
                }
2603

2604
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
208✔
2605
        }
2606

2607
        return r;
2608
}
2609

2610
static int rm_if_wrong_type_safe(
×
2611
                mode_t mode,
2612
                int parent_fd,
2613
                const struct stat *parent_st, /* Only used if follow_links below is true. */
2614
                const char *name,
2615
                int flags) {
2616
        _cleanup_free_ char *parent_name = NULL;
×
2617
        bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
×
2618
        struct stat st;
×
2619
        int r;
×
2620

2621
        assert(name);
×
2622
        assert((mode & ~S_IFMT) == 0);
×
2623
        assert(!follow_links || parent_st);
×
2624
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2625

2626
        if (mode == 0)
×
2627
                return 0;
2628

2629
        if (!filename_is_valid(name))
×
2630
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2631

2632
        r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2633
        if (r < 0) {
×
2634
                (void) fd_get_path(parent_fd, &parent_name);
×
2635
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
2636
                                      "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
2637
        }
2638

2639
        /* Fail before removing anything if this is an unsafe transition. */
2640
        if (follow_links && stat_unsafe_transition(parent_st, &st)) {
×
2641
                (void) fd_get_path(parent_fd, &parent_name);
×
2642
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
×
2643
                                       "Unsafe transition from \"%s\" to \"%s\".", parent_name ?: "...", name);
2644
        }
2645

2646
        if ((st.st_mode & S_IFMT) == mode)
×
2647
                return 0;
2648

2649
        (void) fd_get_path(parent_fd, &parent_name);
×
2650
        log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, parent_name ?: "...", name);
×
2651

2652
        /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2653
         * target, so make sure it is identified as a link and not a directory. */
2654
        if (follow_links) {
×
2655
                r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2656
                if (r < 0)
×
2657
                        return log_error_errno(r, "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
×
2658
        }
2659

2660
        /* Do not remove mount points. */
2661
        r = is_mount_point_at(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
×
2662
        if (r < 0)
×
2663
                (void) log_warning_errno(r, "Failed to check if  \"%s/%s\" is a mount point: %m; continuing.",
×
2664
                                         parent_name ?: "...", name);
2665
        else if (r > 0)
×
2666
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
×
2667
                                "Not removing  \"%s/%s\" because it is a mount point.", parent_name ?: "...", name);
2668

2669
        log_action("Would remove", "Removing", "%s %s/%s", parent_name ?: "...", name);
×
2670
        if (!arg_dry_run) {
×
2671
                if ((st.st_mode & S_IFMT) == S_IFDIR) {
×
2672
                        _cleanup_close_ int child_fd = -EBADF;
×
2673

2674
                        child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
×
2675
                        if (child_fd < 0)
×
2676
                                return log_error_errno(errno, "Failed to open \"%s/%s\": %m", parent_name ?: "...", name);
×
2677

2678
                        r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);
×
2679
                        if (r < 0)
×
2680
                                return log_error_errno(r, "Failed to remove contents of \"%s/%s\": %m", parent_name ?: "...", name);
×
2681

2682
                        r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2683
                } else
2684
                        r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2685
                if (r < 0)
×
2686
                        return log_error_errno(r, "Failed to remove \"%s/%s\": %m", parent_name ?: "...", name);
×
2687
        }
2688

2689
        /* This is covered by the log_notice "Wrong file type...".
2690
         * It is logged earlier because it gives context to other error messages that might follow. */
2691
        return -ENOENT;
2692
}
2693

2694
/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2695
static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
×
2696
        _cleanup_close_ int parent_fd = -EBADF;
×
2697
        struct stat parent_st;
×
2698
        size_t path_len;
×
2699
        int r;
×
2700

2701
        assert(path);
×
2702
        assert((child_mode & ~S_IFMT) == 0);
×
2703

2704
        path_len = strlen(path);
×
2705

2706
        if (!is_path(path))
×
2707
                /* rm_if_wrong_type_safe already logs errors. */
2708
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2709

2710
        if (child_mode != 0 && endswith(path, "/"))
×
2711
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2712
                                "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2713

2714
        /* Get the parent_fd and stat. */
2715
        parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
×
2716
        if (parent_fd < 0)
×
2717
                return log_error_errno(errno, "Failed to open root: %m");
×
2718

2719
        if (fstat(parent_fd, &parent_st) < 0)
×
2720
                return log_error_errno(errno, "Failed to stat root: %m");
×
2721

2722
        /* Check every parent directory in the path, except the last component */
2723
        for (const char *e = path;;) {
×
2724
                _cleanup_close_ int next_fd = -EBADF;
×
2725
                char t[path_len + 1];
×
2726
                const char *s;
×
2727

2728
                /* Find the start of the next path component. */
2729
                s = e + strspn(e, "/");
×
2730
                /* Find the end of the next path component. */
2731
                e = s + strcspn(s, "/");
×
2732

2733
                /* Copy the path component to t so it can be a null terminated string. */
2734
                *mempcpy_typesafe(t, s, e - s) = 0;
×
2735

2736
                /* Is this the last component? If so, then check the type */
2737
                if (*e == 0)
×
2738
                        return rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2739

2740
                r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
×
2741
                /* Remove dangling symlinks. */
2742
                if (r == -ENOENT)
×
2743
                        r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2744
                if (r == -ENOENT) {
×
2745
                        if (!arg_dry_run) {
×
2746
                                WITH_UMASK(0000)
×
2747
                                        r = mkdirat_label(parent_fd, t, 0755);
×
2748
                                if (r < 0) {
×
2749
                                        _cleanup_free_ char *parent_name = NULL;
×
2750

2751
                                        (void) fd_get_path(parent_fd, &parent_name);
×
2752
                                        return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2753
                                }
2754
                        }
2755
                } else if (r < 0)
×
2756
                        /* rm_if_wrong_type_safe already logs errors. */
2757
                        return r;
2758

2759
                next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
×
2760
                if (next_fd < 0) {
×
2761
                        _cleanup_free_ char *parent_name = NULL;
×
2762

2763
                        (void) fd_get_path(parent_fd, &parent_name);
×
2764
                        return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2765
                }
2766
                r = RET_NERRNO(fstat(next_fd, &parent_st));
×
2767
                if (r < 0) {
×
2768
                        _cleanup_free_ char *parent_name = NULL;
×
2769

2770
                        (void) fd_get_path(parent_fd, &parent_name);
×
2771
                        return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2772
                }
2773

2774
                close_and_replace(parent_fd, next_fd);
×
2775
        }
2776
}
2777

2778
static int mkdir_parents_item(Item *i, mode_t child_mode) {
18,430✔
2779
        int r;
18,430✔
2780

2781
        if (i->try_replace) {
18,430✔
2782
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2783
                if (r < 0 && r != -ENOENT)
×
2784
                        return r;
×
2785
        } else
2786
                WITH_UMASK(0000)
36,860✔
2787
                        if (!arg_dry_run)
18,430✔
2788
                                (void) mkdir_parents_label(i->path, 0755);
18,430✔
2789

2790
        return 0;
2791
}
2792

2793
static int create_item(Context *c, Item *i) {
25,510✔
2794
        int r;
25,510✔
2795

2796
        assert(c);
25,510✔
2797
        assert(i);
25,510✔
2798

2799
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
25,510✔
2800

2801
        switch (i->type) {
25,510✔
2802

2803
        case IGNORE_PATH:
2804
        case IGNORE_DIRECTORY_PATH:
2805
        case REMOVE_PATH:
2806
        case RECURSIVE_REMOVE_PATH:
2807
                return 0;
2808

2809
        case TRUNCATE_FILE:
1,055✔
2810
        case CREATE_FILE:
2811
                r = mkdir_parents_item(i, S_IFREG);
1,055✔
2812
                if (r < 0)
1,055✔
2813
                        return r;
2814

2815
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,055✔
2816
                        r = truncate_file(c, i, i->path);
255✔
2817
                else
2818
                        r = create_file(c, i, i->path);
800✔
2819
                if (r < 0)
1,055✔
2820
                        return r;
15✔
2821
                break;
2822

2823
        case COPY_FILES:
3,921✔
2824
                r = mkdir_parents_item(i, 0);
3,921✔
2825
                if (r < 0)
3,921✔
2826
                        return r;
2827

2828
                r = copy_files(c, i);
3,921✔
2829
                if (r < 0)
3,921✔
2830
                        return r;
×
2831
                break;
2832

2833
        case WRITE_FILE:
20✔
2834
                r = glob_item(c, i, write_one_file);
20✔
2835
                if (r < 0)
20✔
2836
                        return r;
×
2837

2838
                break;
2839

2840
        case CREATE_DIRECTORY:
7,992✔
2841
        case TRUNCATE_DIRECTORY:
2842
                r = mkdir_parents_item(i, S_IFDIR);
7,992✔
2843
                if (r < 0)
7,992✔
2844
                        return r;
2845

2846
                r = create_directory(c, i, i->path);
7,992✔
2847
                if (r < 0)
7,992✔
2848
                        return r;
2✔
2849
                break;
2850

2851
        case CREATE_SUBVOLUME:
889✔
2852
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
2853
        case CREATE_SUBVOLUME_NEW_QUOTA:
2854
                r = mkdir_parents_item(i, S_IFDIR);
889✔
2855
                if (r < 0)
889✔
2856
                        return r;
2857

2858
                r = create_subvolume(c, i, i->path);
889✔
2859
                if (r < 0)
889✔
2860
                        return r;
×
2861
                break;
2862

2863
        case EMPTY_DIRECTORY:
4✔
2864
                r = glob_item(c, i, empty_directory);
4✔
2865
                if (r < 0)
4✔
2866
                        return r;
×
2867
                break;
2868

2869
        case CREATE_FIFO:
4✔
2870
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2871
                if (r < 0)
4✔
2872
                        return r;
2873

2874
                r = create_fifo(c, i);
4✔
2875
                if (r < 0)
4✔
2876
                        return r;
×
2877
                break;
2878

2879
        case CREATE_SYMLINK:
2,555✔
2880
                r = mkdir_parents_item(i, S_IFLNK);
2,555✔
2881
                if (r < 0)
2,555✔
2882
                        return r;
2883

2884
                r = create_symlink(c, i);
2,555✔
2885
                if (r < 0)
2,555✔
2886
                        return r;
×
2887

2888
                break;
2889

2890
        case CREATE_BLOCK_DEVICE:
2,014✔
2891
        case CREATE_CHAR_DEVICE:
2892
                if (have_effective_cap(CAP_MKNOD) <= 0) {
2,014✔
2893
                        /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2894
                         * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2895

2896
                        log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
×
2897
                        return 0;
×
2898
                }
2899

2900
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
4,026✔
2901
                if (r < 0)
2,014✔
2902
                        return r;
2903

2904
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
4,026✔
2905
                if (r < 0)
2,014✔
2906
                        return r;
×
2907

2908
                break;
2909

2910
        case ADJUST_MODE:
4,024✔
2911
        case RELABEL_PATH:
2912
                r = glob_item(c, i, path_set_perms);
4,024✔
2913
                if (r < 0)
4,024✔
2914
                        return r;
×
2915
                break;
2916

2917
        case RECURSIVE_RELABEL_PATH:
129✔
2918
                r = glob_item_recursively(c, i, fd_set_perms);
129✔
2919
                if (r < 0)
129✔
2920
                        return r;
×
2921
                break;
2922

2923
        case SET_XATTR:
×
2924
                r = glob_item(c, i, path_set_xattrs);
×
2925
                if (r < 0)
×
2926
                        return r;
×
2927
                break;
2928

2929
        case RECURSIVE_SET_XATTR:
×
2930
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2931
                if (r < 0)
×
2932
                        return r;
×
2933
                break;
2934

2935
        case SET_ACL:
766✔
2936
                r = glob_item(c, i, path_set_acls);
766✔
2937
                if (r < 0)
766✔
2938
                        return r;
×
2939
                break;
2940

2941
        case RECURSIVE_SET_ACL:
127✔
2942
                r = glob_item_recursively(c, i, fd_set_acls);
127✔
2943
                if (r < 0)
127✔
2944
                        return r;
×
2945
                break;
2946

2947
        case SET_ATTRIBUTE:
381✔
2948
                r = glob_item(c, i, path_set_attribute);
381✔
2949
                if (r < 0)
381✔
2950
                        return r;
×
2951
                break;
2952

2953
        case RECURSIVE_SET_ATTRIBUTE:
×
2954
                r = glob_item_recursively(c, i, fd_set_attribute);
×
2955
                if (r < 0)
×
2956
                        return r;
×
2957
                break;
2958
        }
2959

2960
        return 0;
2961
}
2962

2963
static int remove_recursive(
509✔
2964
                Context *c,
2965
                Item *i,
2966
                const char *instance,
2967
                bool remove_instance) {
2968

2969
        _cleanup_closedir_ DIR *d = NULL;
509✔
2970
        struct statx sx;
509✔
2971
        bool mountpoint;
509✔
2972
        int r;
509✔
2973

2974
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
509✔
2975
        if (r < 0)
509✔
2976
                return r;
2977
        if (r == 0) {
509✔
2978
                if (remove_instance) {
499✔
2979
                        log_action("Would remove", "Removing", "%s file \"%s\".", instance);
13✔
2980
                        if (!arg_dry_run &&
14✔
2981
                            remove(instance) < 0 &&
5✔
2982
                            errno != ENOENT)
2✔
2983
                                return log_error_errno(errno, "rm %s: %m", instance);
×
2984
                }
2985
                return 0;
499✔
2986
        }
2987

2988
        r = dir_cleanup(c, i, instance, d,
20✔
2989
                        /* self_atime_nsec= */ NSEC_INFINITY,
2990
                        /* self_mtime_nsec= */ NSEC_INFINITY,
2991
                        /* cutoff_nsec= */ NSEC_INFINITY,
2992
                        sx.stx_dev_major, sx.stx_dev_minor,
10✔
2993
                        mountpoint,
2994
                        MAX_DEPTH,
2995
                        /* keep_this_level= */ false,
2996
                        /* age_by_file= */ 0,
2997
                        /* age_by_dir= */ 0);
2998
        if (r < 0)
10✔
2999
                return r;
3000

3001
        if (remove_instance) {
10✔
3002
                log_action("Would remove", "Removing", "%s directory \"%s\".", instance);
11✔
3003
                if (!arg_dry_run) {
9✔
3004
                        r = RET_NERRNO(rmdir(instance));
512✔
3005
                        if (r < 0) {
3✔
3006
                                bool fatal = !IN_SET(r, -ENOENT, -ENOTEMPTY);
3✔
3007
                                log_full_errno(fatal ? LOG_ERR : LOG_DEBUG, r, "Failed to remove %s: %m", instance);
3✔
3008
                                if (fatal)
3✔
3009
                                        return r;
×
3010
                        }
3011
                }
3012
        }
3013
        return 0;
3014
}
3015

3016
static int purge_item_instance(Context *c, Item *i, const char *instance, CreationMode creation) {
10✔
3017
        return remove_recursive(c, i, instance, /* remove_instance= */ true);
10✔
3018
}
3019

3020
static int purge_item(Context *c, Item *i) {
15✔
3021
        assert(i);
15✔
3022

3023
        if (!needs_purge(i->type))
15✔
3024
                return 0;
3025

3026
        if (!i->purge)
15✔
3027
                return 0;
3028

3029
        log_debug("Running purge action for entry %c %s", (char) i->type, i->path);
10✔
3030

3031
        if (needs_glob(i->type))
10✔
3032
                return glob_item(c, i, purge_item_instance);
×
3033

3034
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3035
}
3036

3037
static int remove_item_instance(
16✔
3038
                Context *c,
3039
                Item *i,
3040
                const char *instance,
3041
                CreationMode creation) {
3042

3043
        assert(c);
16✔
3044
        assert(i);
16✔
3045

3046
        switch (i->type) {
16✔
3047

3048
        case REMOVE_PATH:
3049
                log_action("Would remove", "Removing", "%s \"%s\".", instance);
8✔
3050
                if (!arg_dry_run &&
15✔
3051
                    remove(instance) < 0 &&
7✔
3052
                    errno != ENOENT)
×
3053
                        return log_error_errno(errno, "rm %s: %m", instance);
×
3054

3055
                return 0;
3056

3057
        case RECURSIVE_REMOVE_PATH:
8✔
3058
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3059

3060
        default:
×
3061
                assert_not_reached();
×
3062
        }
3063
}
3064

3065
static int remove_item(Context *c, Item *i) {
19,777✔
3066
        assert(c);
19,777✔
3067
        assert(i);
19,777✔
3068

3069
        log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
19,777✔
3070

3071
        switch (i->type) {
19,777✔
3072

3073
        case TRUNCATE_DIRECTORY:
491✔
3074
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
491✔
3075

3076
        case REMOVE_PATH:
750✔
3077
        case RECURSIVE_REMOVE_PATH:
3078
                return glob_item(c, i, remove_item_instance);
750✔
3079

3080
        default:
3081
                return 0;
3082
        }
3083
}
3084

3085
static char *age_by_to_string(AgeBy ab, bool is_dir) {
44✔
3086
        static const char ab_map[] = { 'a', 'b', 'c', 'm' };
44✔
3087
        size_t j = 0;
44✔
3088
        char *ret;
44✔
3089

3090
        ret = new(char, ELEMENTSOF(ab_map) + 1);
44✔
3091
        if (!ret)
44✔
3092
                return NULL;
3093

3094
        for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
220✔
3095
                if (BIT_SET(ab, i))
176✔
3096
                        ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
110✔
3097

3098
        ret[j] = 0;
44✔
3099
        return ret;
44✔
3100
}
3101

3102
static int clean_item_instance(
57✔
3103
                Context *c,
3104
                Item *i,
3105
                const char* instance,
3106
                CreationMode creation) {
3107

3108
        assert(i);
57✔
3109

3110
        if (!i->age_set)
57✔
3111
                return 0;
57✔
3112

3113
        usec_t n = now(CLOCK_REALTIME);
38✔
3114
        if (n < i->age)
38✔
3115
                return 0;
3116

3117
        usec_t cutoff = n - i->age;
38✔
3118

3119
        _cleanup_closedir_ DIR *d = NULL;
57✔
3120
        struct statx sx;
38✔
3121
        bool mountpoint;
38✔
3122
        int r;
38✔
3123

3124
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
38✔
3125
        if (r <= 0)
38✔
3126
                return r;
3127

3128
        if (DEBUG_LOGGING) {
34✔
3129
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
22✔
3130

3131
                ab_f = age_by_to_string(i->age_by_file, false);
22✔
3132
                if (!ab_f)
22✔
3133
                        return log_oom();
×
3134

3135
                ab_d = age_by_to_string(i->age_by_dir, true);
22✔
3136
                if (!ab_d)
22✔
3137
                        return log_oom();
×
3138

3139
                log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
44✔
3140
                          mountpoint ? "mount point" : "directory",
3141
                          instance,
3142
                          FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
3143
                          ab_f, ab_d);
3144
        }
3145

3146
        return dir_cleanup(c, i, instance, d,
34✔
3147
                           statx_timestamp_load_nsec(&sx.stx_atime),
3148
                           statx_timestamp_load_nsec(&sx.stx_mtime),
3149
                           cutoff * NSEC_PER_USEC,
34✔
3150
                           sx.stx_dev_major, sx.stx_dev_minor,
34✔
3151
                           mountpoint,
3152
                           MAX_DEPTH, i->keep_first_level,
34✔
3153
                           i->age_by_file, i->age_by_dir);
3154
}
3155

3156
static int clean_item(Context *c, Item *i) {
71✔
3157
        assert(c);
71✔
3158
        assert(i);
71✔
3159

3160
        log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
71✔
3161

3162
        switch (i->type) {
71✔
3163

3164
        case CREATE_DIRECTORY:
31✔
3165
        case TRUNCATE_DIRECTORY:
3166
        case CREATE_SUBVOLUME:
3167
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3168
        case CREATE_SUBVOLUME_NEW_QUOTA:
3169
        case COPY_FILES:
3170
                clean_item_instance(c, i, i->path, CREATION_EXISTING);
31✔
3171
                return 0;
31✔
3172

3173
        case EMPTY_DIRECTORY:
22✔
3174
        case IGNORE_PATH:
3175
        case IGNORE_DIRECTORY_PATH:
3176
                return glob_item(c, i, clean_item_instance);
22✔
3177

3178
        default:
3179
                return 0;
3180
        }
3181
}
3182

3183
static int process_item(
82,958✔
3184
                Context *c,
3185
                Item *i,
3186
                OperationMask operation) {
3187

3188
        OperationMask todo;
82,958✔
3189
        _cleanup_free_ char *_path = NULL;
82,958✔
3190
        const char *path;
82,958✔
3191
        int r;
82,958✔
3192

3193
        assert(c);
82,958✔
3194
        assert(i);
82,958✔
3195

3196
        todo = operation & ~i->done;
82,958✔
3197
        if (todo == 0) /* Everything already done? */
82,958✔
3198
                return 0;
3199

3200
        i->done |= operation;
45,373✔
3201

3202
        path = i->path;
45,373✔
3203
        if (string_is_glob(path)) {
45,373✔
3204
                /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3205
                 * for the non-glob part. */
3206

3207
                r = glob_non_glob_prefix(path, &_path);
3,467✔
3208
                if (r < 0 && r != -ENOENT)
3,467✔
3209
                        return log_debug_errno(r, "Failed to deglob path: %m");
×
3210
                if (r >= 0)
3,467✔
3211
                        path = _path;
3,467✔
3212
        }
3213

3214
        r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
45,373✔
3215
        if (r == -EREMOTE) {
45,373✔
3216
                log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
×
3217
                return 0;
×
3218
        }
3219
        if (r < 0)
45,373✔
3220
                log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
×
3221

3222
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
45,373✔
3223
        /* Failure can only be tolerated for create */
3224
        if (i->allow_failure)
45,373✔
3225
                r = 0;
996✔
3226

3227
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
45,373✔
3228
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
45,373✔
3229
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
45,373✔
3230

3231
        return r;
3232
}
3233

3234
static int process_item_array(
76,583✔
3235
                Context *c,
3236
                ItemArray *array,
3237
                OperationMask operation) {
3238

3239
        int r = 0;
76,583✔
3240

3241
        assert(c);
76,583✔
3242
        assert(array);
76,583✔
3243

3244
        /* Create any parent first. */
3245
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
76,583✔
3246
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
17,780✔
3247

3248
        /* Clean up all children first */
3249
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
76,583✔
3250
                ItemArray *cc;
6,573✔
3251

3252
                SET_FOREACH(cc, array->children)
22,625✔
3253
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
16,052✔
3254
        }
3255

3256
        FOREACH_ARRAY(item, array->items, array->n_items)
159,541✔
3257
                RET_GATHER(r, process_item(c, item, operation));
82,958✔
3258

3259
        return r;
76,583✔
3260
}
3261

3262
static void item_free_contents(Item *i) {
94,684✔
3263
        assert(i);
94,684✔
3264
        free(i->path);
94,684✔
3265
        free(i->argument);
94,684✔
3266
        free(i->binary_argument);
94,684✔
3267
        strv_free(i->xattrs);
94,684✔
3268

3269
#if HAVE_ACL
3270
        if (i->acl_access)
94,684✔
3271
                sym_acl_free(i->acl_access);
1,484✔
3272

3273
        if (i->acl_access_exec)
94,684✔
3274
                sym_acl_free(i->acl_access_exec);
375✔
3275

3276
        if (i->acl_default)
94,684✔
3277
                sym_acl_free(i->acl_default);
2,226✔
3278
#endif
3279
}
94,684✔
3280

3281
static ItemArray* item_array_free(ItemArray *a) {
24,213✔
3282
        if (!a)
24,213✔
3283
                return NULL;
3284

3285
        FOREACH_ARRAY(item, a->items, a->n_items)
49,828✔
3286
                item_free_contents(item);
25,615✔
3287

3288
        set_free(a->children);
24,213✔
3289
        free(a->items);
24,213✔
3290
        return mfree(a);
24,213✔
3291
}
3292

3293
static int item_compare(const Item *a, const Item *b) {
1,920✔
3294
        /* Make sure that the ownership taking item is put first, so
3295
         * that we first create the node, and then can adjust it */
3296

3297
        if (takes_ownership(a->type) && !takes_ownership(b->type))
1,920✔
3298
                return -1;
3299
        if (!takes_ownership(a->type) && takes_ownership(b->type))
1,920✔
3300
                return 1;
3301

3302
        return CMP(a->type, b->type);
1,920✔
3303
}
3304

3305
static bool item_compatible(const Item *a, const Item *b) {
1,667✔
3306
        assert(a);
1,667✔
3307
        assert(b);
1,667✔
3308
        assert(streq(a->path, b->path));
1,667✔
3309

3310
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,667✔
3311
                /* check if the items are the same */
3312
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
524✔
3313
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
505✔
3314

3315
                        a->uid_set == b->uid_set &&
505✔
3316
                        a->uid == b->uid &&
505✔
3317
                        a->uid_only_create == b->uid_only_create &&
505✔
3318

3319
                        a->gid_set == b->gid_set &&
505✔
3320
                        a->gid == b->gid &&
505✔
3321
                        a->gid_only_create == b->gid_only_create &&
505✔
3322

3323
                        a->mode_set == b->mode_set &&
505✔
3324
                        a->mode == b->mode &&
505✔
3325
                        a->mode_only_create == b->mode_only_create &&
505✔
3326

3327
                        a->age_set == b->age_set &&
505✔
3328
                        a->age == b->age &&
505✔
3329

3330
                        a->age_by_file == b->age_by_file &&
505✔
3331
                        a->age_by_dir == b->age_by_dir &&
505✔
3332

3333
                        a->mask_perms == b->mask_perms &&
505✔
3334

3335
                        a->keep_first_level == b->keep_first_level &&
1,553✔
3336

3337
                        a->major_minor == b->major_minor;
505✔
3338

3339
        return true;
3340
}
3341

3342
static bool should_include_path(const char *path) {
68,978✔
3343
        STRV_FOREACH(prefix, arg_exclude_prefixes)
88,987✔
3344
                if (path_startswith(path, *prefix)) {
22,447✔
3345
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,438✔
3346
                                  path, *prefix);
3347
                        return false;
2,438✔
3348
                }
3349

3350
        STRV_FOREACH(prefix, arg_include_prefixes)
106,558✔
3351
                if (path_startswith(path, *prefix)) {
44,894✔
3352
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
4,876✔
3353
                        return true;
4,876✔
3354
                }
3355

3356
        /* no matches, so we should include this path only if we have no allow list at all */
3357
        if (strv_isempty(arg_include_prefixes))
61,664✔
3358
                return true;
3359

3360
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
40,018✔
3361
        return false;
3362
}
3363

3364
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
26,522✔
3365
        int r;
26,522✔
3366

3367
        assert(i);
26,522✔
3368

3369
        if (!i->argument)
26,522✔
3370
                return 0;
3371

3372
        switch (i->type) {
7,058✔
3373
        case COPY_FILES:
3,769✔
3374
        case CREATE_SYMLINK:
3375
        case CREATE_FILE:
3376
        case TRUNCATE_FILE:
3377
        case WRITE_FILE: {
3378
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
3,769✔
3379
                ssize_t l;
3,769✔
3380

3381
                l = cunescape(i->argument, 0, &unescaped);
3,769✔
3382
                if (l < 0)
3,769✔
3383
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3384

3385
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
3,769✔
3386
                if (r < 0)
3,769✔
3387
                        return r;
3388

3389
                return free_and_replace(i->argument, resolved);
3,769✔
3390
        }
3391
        case SET_XATTR:
×
3392
        case RECURSIVE_SET_XATTR:
3393
                STRV_FOREACH(xattr, i->xattrs) {
×
3394
                        _cleanup_free_ char *resolved = NULL;
×
3395

3396
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3397
                        if (r < 0)
×
3398
                                return r;
×
3399

3400
                        free_and_replace(*xattr, resolved);
×
3401
                }
3402
                return 0;
3403

3404
        default:
3405
                return 0;
3406
        }
3407
}
3408

3409
static int patch_var_run(const char *fname, unsigned line, char **path) {
68,979✔
3410
        const char *k;
68,979✔
3411
        char *n;
68,979✔
3412

3413
        assert(path);
68,979✔
3414
        assert(*path);
68,979✔
3415

3416
        /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges
3417
         * lines in some cases and detects conflicts in others. If files/directories are specified through
3418
         * two equivalent lines this is problematic as neither case will be detected. Ideally we'd detect
3419
         * these cases by resolving symlinks early, but that's precisely not what we can do here as this code
3420
         * very likely is running very early on, at a time where the paths in question are not available yet,
3421
         * or even more importantly, our own tmpfiles rules might create the paths that are intermediary to
3422
         * the listed paths. We can't really cover the generic case, but the least we can do is cover the
3423
         * specific case of /var/run vs. /run, as /var/run is a legacy name for /run only, and we explicitly
3424
         * document that and require that on systemd systems the former is a symlink to the latter. Moreover
3425
         * files below this path are by far the primary use case for tmpfiles.d/. */
3426

3427
        k = path_startswith(*path, "/var/run/");
68,979✔
3428
        if (isempty(k)) /* Don't complain about paths other than under /var/run,
68,979✔
3429
                         * and not about /var/run itself either. */
3430
                return 0;
68,979✔
3431

3432
        n = path_join("/run", k);
×
3433
        if (!n)
×
3434
                return log_oom();
×
3435

3436
        /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation
3437
         * automatically, hence there's no immediate need for action by the user. However, in the interest of
3438
         * making things less confusing to the user, let's still inform the user that these snippets should
3439
         * really be updated. */
3440
        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
×
3441
                   "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3442
                   *path, n);
3443

3444
        free_and_replace(*path, n);
×
3445

3446
        return 0;
×
3447
}
3448

3449
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
9,163✔
3450
        int r;
9,163✔
3451

3452
        assert(user);
9,163✔
3453
        assert(ret_uid);
9,163✔
3454

3455
        /* First: parse as numeric UID string */
3456
        r = parse_uid(user, ret_uid);
9,163✔
3457
        if (r >= 0)
9,163✔
3458
                return r;
3459

3460
        /* Second: pass to NSS if we are running "online" */
3461
        if (!arg_root)
9,149✔
3462
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
9,149✔
3463

3464
        /* Third, synthesize "root" unconditionally */
3465
        if (streq(user, "root")) {
×
3466
                *ret_uid = 0;
×
3467
                return 0;
×
3468
        }
3469

3470
        /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3471
        return name_to_uid_offline(arg_root, user, ret_uid, cache);
×
3472
}
3473

3474
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
10,657✔
3475
        int r;
10,657✔
3476

3477
        assert(group);
10,657✔
3478
        assert(ret_gid);
10,657✔
3479

3480
        /* First: parse as numeric GID string */
3481
        r = parse_gid(group, ret_gid);
10,657✔
3482
        if (r >= 0)
10,657✔
3483
                return r;
3484

3485
        /* Second: pass to NSS if we are running "online" */
3486
        if (!arg_root)
10,643✔
3487
                return get_group_creds(&group, ret_gid, 0);
10,643✔
3488

3489
        /* Third, synthesize "root" unconditionally */
3490
        if (streq(group, "root")) {
×
3491
                *ret_gid = 0;
×
3492
                return 0;
×
3493
        }
3494

3495
        /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3496
        return name_to_gid_offline(arg_root, group, ret_gid, cache);
×
3497
}
3498

3499
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
155✔
3500
        AgeBy ab_f = 0, ab_d = 0;
155✔
3501

3502
        static const struct {
155✔
3503
                char age_by_chr;
3504
                AgeBy age_by_flag;
3505
        } age_by_types[] = {
3506
                { 'a', AGE_BY_ATIME },
3507
                { 'b', AGE_BY_BTIME },
3508
                { 'c', AGE_BY_CTIME },
3509
                { 'm', AGE_BY_MTIME },
3510
        };
3511

3512
        assert(age_by_str);
155✔
3513
        assert(item);
155✔
3514

3515
        if (isempty(age_by_str))
155✔
3516
                return -EINVAL;
3517

3518
        for (const char *s = age_by_str; *s != 0; s++) {
329✔
3519
                size_t i;
180✔
3520

3521
                /* Ignore whitespace. */
3522
                if (strchr(WHITESPACE, *s))
180✔
3523
                        continue;
11✔
3524

3525
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
231✔
3526
                        /* Check lower-case for files, upper-case for directories. */
3527
                        if (*s == age_by_types[i].age_by_chr) {
228✔
3528
                                ab_f |= age_by_types[i].age_by_flag;
156✔
3529
                                break;
156✔
3530
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3531
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3532
                                break;
10✔
3533
                        }
3534
                }
3535

3536
                /* Invalid character. */
3537
                if (i >= ELEMENTSOF(age_by_types))
3538
                        return -EINVAL;
3539
        }
3540

3541
        /* No match. */
3542
        if (ab_f == 0 && ab_d == 0)
149✔
3543
                return -EINVAL;
3544

3545
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
148✔
3546
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
148✔
3547

3548
        return 0;
148✔
3549
}
3550

3551
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
1,405✔
3552
        assert(existing);
1,405✔
3553
        assert(i);
1,405✔
3554

3555
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
3,069✔
3556
                if (item_compatible(e, i))
1,667✔
3557
                        continue;
1,648✔
3558

3559
                /* Only multiple 'w+' lines for the same path are allowed. */
3560
                if (e->type != WRITE_FILE || !e->append_or_force ||
19✔
3561
                    i->type != WRITE_FILE || !i->append_or_force)
16✔
3562
                        return true;
3563
        }
3564

3565
        return false;
3566
}
3567

3568
static int parse_line(
69,069✔
3569
                const char *fname,
3570
                unsigned line,
3571
                const char *buffer,
3572
                bool *invalid_config,
3573
                void *context) {
3574

3575
        Context *c = ASSERT_PTR(context);
69,069✔
3576
        _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
69,069✔
3577
        _cleanup_(item_free_contents) Item i = {
×
3578
                /* The "age-by" argument considers all file timestamp types by default. */
3579
                .age_by_file = AGE_BY_DEFAULT_FILE,
3580
                .age_by_dir = AGE_BY_DEFAULT_DIR,
3581
        };
3582
        ItemArray *existing;
69,069✔
3583
        OrderedHashmap *h;
69,069✔
3584
        bool append_or_force = false, boot = false, allow_failure = false, try_replace = false,
69,069✔
3585
                unbase64 = false, from_cred = false, missing_user_or_group = false, purge = false,
69,069✔
3586
                ignore_if_target_missing = false;
69,069✔
3587
        int r;
69,069✔
3588

3589
        assert(fname);
69,069✔
3590
        assert(line >= 1);
69,069✔
3591
        assert(buffer);
69,069✔
3592

3593
        const Specifier specifier_table[] = {
69,069✔
3594
                { 'h', specifier_user_home,       NULL },
3595

3596
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3597
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3598
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3599
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3600

3601
                COMMON_SYSTEM_SPECIFIERS,
3602
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
69,069✔
3603
                COMMON_TMP_SPECIFIERS,
3604
                {}
3605
        };
3606

3607
        r = extract_many_words(
69,069✔
3608
                        &buffer,
3609
                        NULL,
3610
                        EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE,
3611
                        &action,
3612
                        &path,
3613
                        &mode,
3614
                        &user,
3615
                        &group,
3616
                        &age);
3617
        if (r < 0) {
69,069✔
3618
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3619
                        /* invalid quoting and such or an unknown specifier */
3620
                        *invalid_config = true;
×
3621
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
×
3622
        } else if (r < 2) {
69,069✔
3623
                *invalid_config = true;
×
3624
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
×
3625
        }
3626

3627
        if (!empty_or_dash(buffer)) {
69,069✔
3628
                i.argument = strdup(buffer);
16,859✔
3629
                if (!i.argument)
16,859✔
3630
                        return log_oom();
×
3631
        }
3632

3633
        if (isempty(action)) {
69,069✔
3634
                *invalid_config = true;
×
3635
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3636
                                  "Command too short '%s'.", action);
3637
        }
3638

3639
        for (int pos = 1; action[pos]; pos++)
90,672✔
3640
                if (action[pos] == '!' && !boot)
21,603✔
3641
                        boot = true;
3642
                else if (action[pos] == '+' && !append_or_force)
11,910✔
3643
                        append_or_force = true;
3644
                else if (action[pos] == '-' && !allow_failure)
8,176✔
3645
                        allow_failure = true;
3646
                else if (action[pos] == '=' && !try_replace)
6,692✔
3647
                        try_replace = true;
3648
                else if (action[pos] == '~' && !unbase64)
6,692✔
3649
                        unbase64 = true;
3650
                else if (action[pos] == '^' && !from_cred)
6,692✔
3651
                        from_cred = true;
3652
                else if (action[pos] == '$' && !purge)
5,208✔
3653
                        purge = true;
3654
                else if (action[pos] == '?' && !ignore_if_target_missing)
744✔
3655
                        ignore_if_target_missing = true;
3656
                else {
3657
                        *invalid_config = true;
×
3658
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3659
                                          "Unknown modifiers in command: %s", action);
3660
                }
3661

3662
        if (boot && !arg_boot) {
69,069✔
3663
                log_syntax(NULL, LOG_DEBUG, fname, line, 0,
90✔
3664
                           "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3665
                return 0;
90✔
3666
        }
3667

3668
        i.type = action[0];
68,979✔
3669
        i.append_or_force = append_or_force;
68,979✔
3670
        i.allow_failure = allow_failure;
68,979✔
3671
        i.try_replace = try_replace;
68,979✔
3672
        i.purge = purge;
68,979✔
3673
        i.ignore_if_target_missing = ignore_if_target_missing;
68,979✔
3674

3675
        r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
68,979✔
3676
        if (ERRNO_IS_NEG_NOINFO(r))
68,979✔
3677
                return log_unresolvable_specifier(fname, line);
×
3678
        if (r < 0) {
68,979✔
3679
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3680
                        *invalid_config = true;
×
3681
                return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3682
                                  "Failed to replace specifiers in '%s': %m", path);
3683
        }
3684

3685
        r = patch_var_run(fname, line, &i.path);
68,979✔
3686
        if (r < 0)
68,979✔
3687
                return r;
3688

3689
        if (!path_is_absolute(i.path)) {
68,979✔
3690
                *invalid_config = true;
×
3691
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3692
                                  "Path '%s' not absolute.", i.path);
3693
        }
3694

3695
        path_simplify(i.path);
68,979✔
3696

3697
        switch (i.type) {
68,979✔
3698

3699
        case CREATE_DIRECTORY:
38,402✔
3700
        case CREATE_SUBVOLUME:
3701
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3702
        case CREATE_SUBVOLUME_NEW_QUOTA:
3703
        case EMPTY_DIRECTORY:
3704
        case TRUNCATE_DIRECTORY:
3705
        case CREATE_FIFO:
3706
        case IGNORE_PATH:
3707
        case IGNORE_DIRECTORY_PATH:
3708
        case REMOVE_PATH:
3709
        case RECURSIVE_REMOVE_PATH:
3710
        case ADJUST_MODE:
3711
        case RELABEL_PATH:
3712
        case RECURSIVE_RELABEL_PATH:
3713
                if (i.argument)
38,402✔
3714
                        log_syntax(NULL, LOG_WARNING, fname, line, 0,
1✔
3715
                                   "%c lines don't take argument fields, ignoring.", (char) i.type);
3716
                break;
3717

3718
        case CREATE_FILE:
3719
        case TRUNCATE_FILE:
3720
                break;
3721

3722
        case CREATE_SYMLINK:
6,720✔
3723
                if (unbase64) {
6,720✔
3724
                        *invalid_config = true;
×
3725
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3726
                                          "base64 decoding not supported for symlink targets.");
3727
                }
3728
                break;
3729

3730
        case WRITE_FILE:
21✔
3731
                if (!i.argument) {
21✔
3732
                        *invalid_config = true;
1✔
3733
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1✔
3734
                                          "Write file requires argument.");
3735
                }
3736
                break;
3737

3738
        case COPY_FILES:
12,970✔
3739
                if (unbase64) {
12,970✔
3740
                        *invalid_config = true;
×
3741
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3742
                                          "base64 decoding not supported for copy sources.");
3743
                }
3744
                break;
3745

3746
        case CREATE_CHAR_DEVICE:
3,019✔
3747
        case CREATE_BLOCK_DEVICE:
3748
                if (unbase64) {
3,019✔
3749
                        *invalid_config = true;
×
3750
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3751
                                          "base64 decoding not supported for device node creation.");
3752
                }
3753

3754
                if (!i.argument) {
3,019✔
3755
                        *invalid_config = true;
×
3756
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3757
                                          "Device file requires argument.");
3758
                }
3759

3760
                r = parse_devnum(i.argument, &i.major_minor);
3,019✔
3761
                if (r < 0) {
3,019✔
3762
                        *invalid_config = true;
×
3763
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3764
                                          "Can't parse device file major/minor '%s'.", i.argument);
3765
                }
3766

3767
                break;
3768

3769
        case SET_XATTR:
×
3770
        case RECURSIVE_SET_XATTR:
3771
                if (unbase64) {
×
3772
                        *invalid_config = true;
×
3773
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3774
                                          "base64 decoding not supported for extended attributes.");
3775
                }
3776
                if (!i.argument) {
×
3777
                        *invalid_config = true;
×
3778
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3779
                                          "Set extended attribute requires argument.");
3780
                }
3781
                r = parse_xattrs_from_arg(&i);
×
3782
                if (r < 0)
×
3783
                        return r;
3784
                break;
3785

3786
        case SET_ACL:
2,601✔
3787
        case RECURSIVE_SET_ACL:
3788
                if (unbase64) {
2,601✔
3789
                        *invalid_config = true;
×
3790
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3791
                                          "base64 decoding not supported for ACLs.");
3792
                }
3793
                if (!i.argument) {
2,601✔
3794
                        *invalid_config = true;
×
3795
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3796
                                          "Set ACLs requires argument.");
3797
                }
3798
                r = parse_acls_from_arg(&i);
2,601✔
3799
                if (r < 0)
2,601✔
3800
                        return r;
3801
                break;
3802

3803
        case SET_ATTRIBUTE:
1,113✔
3804
        case RECURSIVE_SET_ATTRIBUTE:
3805
                if (unbase64) {
1,113✔
3806
                        *invalid_config = true;
×
3807
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3808
                                          "base64 decoding not supported for file attributes.");
3809
                }
3810
                if (!i.argument) {
1,113✔
3811
                        *invalid_config = true;
×
3812
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3813
                                          "Set file attribute requires argument.");
3814
                }
3815
                r = parse_attribute_from_arg(&i);
1,113✔
3816
                if (IN_SET(r, -EINVAL, -EBADSLT))
1,113✔
3817
                        *invalid_config = true;
×
3818
                if (r < 0)
1,113✔
3819
                        return r;
3820
                break;
3821

3822
        default:
×
3823
                *invalid_config = true;
×
3824
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3825
                                  "Unknown command type '%c'.", (char) i.type);
3826
        }
3827

3828
        if (i.purge && !needs_purge(i.type)) {
68,978✔
3829
                *invalid_config = true;
×
3830
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3831
                                  "Purge flag '$' combined with line type '%c' which does not support purging.", (char) i.type);
3832
        }
3833

3834
        if (i.ignore_if_target_missing && !supports_ignore_if_target_missing(i.type)) {
68,978✔
3835
                *invalid_config = true;
×
3836
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3837
                                  "Modifier '?' combined with line type '%c' which does not support this modifier.", (char) i.type);
3838
        }
3839

3840
        if (!should_include_path(i.path))
68,978✔
3841
                return 0;
3842

3843
        if (!unbase64) {
26,522✔
3844
                /* Do specifier expansion except if base64 mode is enabled */
3845
                r = specifier_expansion_from_arg(specifier_table, &i);
26,522✔
3846
                if (ERRNO_IS_NEG_NOINFO(r))
26,522✔
3847
                        return log_unresolvable_specifier(fname, line);
×
3848
                if (r < 0) {
26,522✔
3849
                        if (IN_SET(r, -EINVAL, -EBADSLT))
×
3850
                                *invalid_config = true;
×
3851
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3852
                                          "Failed to substitute specifiers in argument: %m");
3853
                }
3854
        }
3855

3856
        switch (i.type) {
26,522✔
3857
        case CREATE_SYMLINK:
2,572✔
3858
                if (!i.argument) {
2,572✔
3859
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3860
                        if (!i.argument)
2✔
3861
                                return log_oom();
×
3862
                }
3863

3864
                break;
3865

3866
        case COPY_FILES:
4,430✔
3867
                if (!i.argument) {
4,430✔
3868
                        i.argument = path_join("/usr/share/factory", i.path);
3,913✔
3869
                        if (!i.argument)
3,913✔
3870
                                return log_oom();
×
3871
                } else if (!path_is_absolute(i.argument)) {
517✔
3872
                        *invalid_config = true;
×
3873
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3874
                                          "Source path '%s' is not absolute.", i.argument);
3875

3876
                }
3877

3878
                if (!empty_or_root(arg_root)) {
4,430✔
3879
                        char *p;
1✔
3880

3881
                        p = path_join(arg_root, i.argument);
1✔
3882
                        if (!p)
1✔
3883
                                return log_oom();
×
3884
                        free_and_replace(i.argument, p);
1✔
3885
                }
3886

3887
                path_simplify(i.argument);
4,430✔
3888

3889
                if (access_nofollow(i.argument, F_OK) == -ENOENT) {
4,430✔
3890
                        /* Silently skip over lines where the source file is missing. */
3891
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
509✔
3892
                                   "Copy source path '%s' does not exist, skipping line.", i.argument);
3893
                        return 0;
509✔
3894
                }
3895

3896
                break;
3897

3898
        default:
26,013✔
3899
                ;
26,013✔
3900
        }
3901

3902
        if (from_cred) {
26,013✔
3903
                if (!i.argument)
508✔
3904
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3905
                                          "Reading from credential requested, but no credential name specified.");
3906
                if (!credential_name_valid(i.argument))
508✔
3907
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3908
                                          "Credential name not valid: %s", i.argument);
3909

3910
                r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
508✔
3911
                if (IN_SET(r, -ENXIO, -ENOENT)) {
508✔
3912
                        /* Silently skip over lines that have no credentials passed */
3913
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
386✔
3914
                                   "Credential '%s' not specified, skipping line.", i.argument);
3915
                        return 0;
386✔
3916
                }
3917
                if (r < 0)
122✔
3918
                        return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
×
3919
        }
3920

3921
        /* If base64 decoding is requested, do so now */
3922
        if (unbase64 && item_binary_argument(&i)) {
25,627✔
3923
                _cleanup_free_ void *data = NULL;
×
3924
                size_t data_size = 0;
×
3925

3926
                r = unbase64mem_full(item_binary_argument(&i), item_binary_argument_size(&i), /* secure= */ false,
×
3927
                                     &data, &data_size);
3928
                if (r < 0)
×
3929
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to base64 decode specified argument '%s': %m", i.argument);
×
3930

3931
                free_and_replace(i.binary_argument, data);
×
3932
                i.binary_argument_size = data_size;
×
3933
        }
3934

3935
        if (!empty_or_root(arg_root)) {
25,627✔
3936
                char *p;
14✔
3937

3938
                p = path_join(arg_root, i.path);
14✔
3939
                if (!p)
14✔
3940
                        return log_oom();
69,069✔
3941
                free_and_replace(i.path, p);
14✔
3942
        }
3943

3944
        if (!empty_or_dash(user)) {
25,627✔
3945
                const char *u;
9,163✔
3946

3947
                u = startswith(user, ":");
9,163✔
3948
                if (u)
9,163✔
3949
                        i.uid_only_create = true;
4✔
3950
                else
3951
                        u = user;
3952

3953
                r = find_uid(u, &i.uid, &c->uid_cache);
9,163✔
3954
                if (r == -ESRCH && arg_graceful) {
9,163✔
3955
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3956
                                   "%s: user '%s' not found, not adjusting ownership.", i.path, u);
3957
                        missing_user_or_group = true;
3958
                } else if (r < 0) {
9,163✔
3959
                        *invalid_config = true;
×
3960
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3961
                                          "Failed to resolve user '%s': %s", u, STRERROR_USER(r));
3962
                } else
3963
                        i.uid_set = true;
9,163✔
3964
        }
3965

3966
        if (!empty_or_dash(group)) {
25,627✔
3967
                const char *g;
10,657✔
3968

3969
                g = startswith(group, ":");
10,657✔
3970
                if (g)
10,657✔
3971
                        i.gid_only_create = true;
380✔
3972
                else
3973
                        g = group;
3974

3975
                r = find_gid(g, &i.gid, &c->gid_cache);
10,657✔
3976
                if (r == -ESRCH && arg_graceful) {
10,657✔
3977
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3978
                                   "%s: group '%s' not found, not adjusting ownership.", i.path, g);
3979
                        missing_user_or_group = true;
3980
                } else if (r < 0) {
10,657✔
3981
                        *invalid_config = true;
×
3982
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3983
                                          "Failed to resolve group '%s': %s", g, STRERROR_GROUP(r));
3984
                } else
3985
                        i.gid_set = true;
10,657✔
3986
        }
3987

3988
        if (!empty_or_dash(mode)) {
25,627✔
3989
                const char *mm;
3990
                unsigned m;
3991

3992
                for (mm = mode;; mm++)
507✔
3993
                        if (*mm == '~')
16,348✔
3994
                                i.mask_perms = true;
127✔
3995
                        else if (*mm == ':')
16,221✔
3996
                                i.mode_only_create = true;
380✔
3997
                        else
3998
                                break;
3999

4000
                r = parse_mode(mm, &m);
15,841✔
4001
                if (r < 0) {
15,841✔
4002
                        *invalid_config = true;
×
4003
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
×
4004
                }
4005

4006
                i.mode = m;
15,841✔
4007
                i.mode_set = true;
15,841✔
4008
        } else
4009
                i.mode = IN_SET(i.type,
9,786✔
4010
                                CREATE_DIRECTORY,
4011
                                TRUNCATE_DIRECTORY,
4012
                                CREATE_SUBVOLUME,
4013
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4014
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4015

4016
        if (missing_user_or_group && (i.mode & ~0777) != 0) {
25,627✔
4017
                /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
4018
                mode_t adjusted = i.mode & 0777;
×
4019
                log_syntax(NULL, LOG_INFO, fname, line, 0,
×
4020
                           "Changing mode 0%o to 0%o because of changed ownership.", i.mode, adjusted);
4021
                i.mode = adjusted;
×
4022
        }
4023

4024
        if (!empty_or_dash(age)) {
25,627✔
4025
                const char *a = age;
1,290✔
4026
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,290✔
4027

4028
                if (*a == '~') {
1,290✔
4029
                        i.keep_first_level = true;
×
4030
                        a++;
×
4031
                }
4032

4033
                /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
4034
                r = split_pair(a, ":", &age_by, &seconds);
1,290✔
4035
                if (r == -ENOMEM)
1,290✔
4036
                        return log_oom();
×
4037
                if (r < 0 && r != -EINVAL)
1,290✔
4038
                        return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
×
4039
                if (r >= 0) {
1,290✔
4040
                        /* We found a ":", parse the "age-by" part. */
4041
                        r = parse_age_by_from_arg(age_by, &i);
155✔
4042
                        if (r == -ENOMEM)
155✔
4043
                                return log_oom();
×
4044
                        if (r < 0) {
155✔
4045
                                *invalid_config = true;
7✔
4046
                                return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
7✔
4047
                        }
4048

4049
                        /* For parsing the "age" part, after the ":". */
4050
                        a = seconds;
148✔
4051
                }
4052

4053
                r = parse_sec(a, &i.age);
1,283✔
4054
                if (r < 0) {
1,283✔
4055
                        *invalid_config = true;
2✔
4056
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
2✔
4057
                }
4058

4059
                i.age_set = true;
1,281✔
4060
        }
4061

4062
        h = needs_glob(i.type) ? c->globs : c->items;
25,618✔
4063

4064
        existing = ordered_hashmap_get(h, i.path);
25,618✔
4065
        if (existing) {
25,618✔
4066
                if (is_duplicated_item(existing, &i)) {
1,405✔
4067
                        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3✔
4068
                                   "Duplicate line for path \"%s\", ignoring.", i.path);
4069
                        return 0;
3✔
4070
                }
4071
        } else {
4072
                existing = new0(ItemArray, 1);
24,213✔
4073
                if (!existing)
24,213✔
4074
                        return log_oom();
×
4075

4076
                r = ordered_hashmap_put(h, i.path, existing);
24,213✔
4077
                if (r < 0) {
24,213✔
4078
                        free(existing);
×
4079
                        return log_oom();
×
4080
                }
4081
        }
4082

4083
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
25,615✔
4084
                return log_oom();
×
4085

4086
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
25,615✔
4087

4088
        /* Sort item array, to enforce stable ordering of application */
4089
        typesafe_qsort(existing->items, existing->n_items, item_compare);
25,615✔
4090

4091
        return 0;
4092
}
4093

4094
static int cat_config(char **config_dirs, char **args) {
×
4095
        _cleanup_strv_free_ char **files = NULL;
×
4096
        int r;
×
4097

4098
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4099
        if (r < 0)
×
4100
                return r;
4101

4102
        pager_open(arg_pager_flags);
×
4103

4104
        return cat_files(NULL, files, arg_cat_flags);
×
4105
}
4106

4107
static int exclude_default_prefixes(void) {
×
4108
        int r;
×
4109

4110
        /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
4111
         * combination with --root= where we probably don't want to apply stuff to these dirs as they are
4112
         * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
4113
         * all kinds of files created/adjusted underneath these mount points. */
4114

4115
        r = strv_extend_many(
×
4116
                        &arg_exclude_prefixes,
4117
                        "/dev",
4118
                        "/proc",
4119
                        "/run",
4120
                        "/sys");
4121
        if (r < 0)
×
4122
                return log_oom();
×
4123

4124
        strv_uniq(arg_exclude_prefixes);
×
4125
        return 0;
×
4126
}
4127

4128
static int help(void) {
×
4129
        _cleanup_free_ char *link = NULL;
×
4130
        int r;
×
4131

4132
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4133
        if (r < 0)
×
4134
                return log_oom();
×
4135

4136
        printf("%1$s COMMAND [OPTIONS...] [CONFIGURATION FILE...]\n"
×
4137
               "\n%2$sCreate, delete, and clean up files and directories.%4$s\n"
4138
               "\n%3$sCommands:%4$s\n"
4139
               "     --create               Create and adjust files and directories\n"
4140
               "     --clean                Clean up files and directories\n"
4141
               "     --remove               Remove files and directories marked for removal\n"
4142
               "     --purge                Delete files and directories marked for creation in\n"
4143
               "                            specified configuration files (careful!)\n"
4144
               "     --cat-config           Show configuration files\n"
4145
               "     --tldr                 Show non-comment parts of configuration files\n"
4146
               "  -h --help                 Show this help\n"
4147
               "     --version              Show package version\n"
4148
               "\n%3$sOptions:%4$s\n"
4149
               "     --user                 Execute user configuration\n"
4150
               "     --boot                 Execute actions only safe at boot\n"
4151
               "     --graceful             Quietly ignore unknown users or groups\n"
4152
               "     --prefix=PATH          Only apply rules with the specified prefix\n"
4153
               "     --exclude-prefix=PATH  Ignore rules with the specified prefix\n"
4154
               "  -E                        Ignore rules prefixed with /dev, /proc, /run, /sys\n"
4155
               "     --root=PATH            Operate on an alternate filesystem root\n"
4156
               "     --image=PATH           Operate on disk image as filesystem root\n"
4157
               "     --image-policy=POLICY  Specify disk image dissection policy\n"
4158
               "     --replace=PATH         Treat arguments as replacement for PATH\n"
4159
               "     --dry-run              Just print what would be done\n"
4160
               "     --no-pager             Do not pipe output into a pager\n"
4161
               "\nSee the %5$s for details.\n",
4162
               program_invocation_short_name,
4163
               ansi_highlight(),
4164
               ansi_underline(),
4165
               ansi_normal(),
4166
               link);
4167

4168
        return 0;
4169
}
4170

4171
static int parse_argv(int argc, char *argv[]) {
711✔
4172
        enum {
711✔
4173
                ARG_VERSION = 0x100,
4174
                ARG_CAT_CONFIG,
4175
                ARG_TLDR,
4176
                ARG_USER,
4177
                ARG_CREATE,
4178
                ARG_CLEAN,
4179
                ARG_REMOVE,
4180
                ARG_PURGE,
4181
                ARG_BOOT,
4182
                ARG_GRACEFUL,
4183
                ARG_PREFIX,
4184
                ARG_EXCLUDE_PREFIX,
4185
                ARG_ROOT,
4186
                ARG_IMAGE,
4187
                ARG_IMAGE_POLICY,
4188
                ARG_REPLACE,
4189
                ARG_DRY_RUN,
4190
                ARG_NO_PAGER,
4191
        };
4192

4193
        static const struct option options[] = {
711✔
4194
                { "help",           no_argument,         NULL, 'h'                },
4195
                { "user",           no_argument,         NULL, ARG_USER           },
4196
                { "version",        no_argument,         NULL, ARG_VERSION        },
4197
                { "cat-config",     no_argument,         NULL, ARG_CAT_CONFIG     },
4198
                { "tldr",           no_argument,         NULL, ARG_TLDR           },
4199
                { "create",         no_argument,         NULL, ARG_CREATE         },
4200
                { "clean",          no_argument,         NULL, ARG_CLEAN          },
4201
                { "remove",         no_argument,         NULL, ARG_REMOVE         },
4202
                { "purge",          no_argument,         NULL, ARG_PURGE          },
4203
                { "boot",           no_argument,         NULL, ARG_BOOT           },
4204
                { "graceful",       no_argument,         NULL, ARG_GRACEFUL       },
4205
                { "prefix",         required_argument,   NULL, ARG_PREFIX         },
4206
                { "exclude-prefix", required_argument,   NULL, ARG_EXCLUDE_PREFIX },
4207
                { "root",           required_argument,   NULL, ARG_ROOT           },
4208
                { "image",          required_argument,   NULL, ARG_IMAGE          },
4209
                { "image-policy",   required_argument,   NULL, ARG_IMAGE_POLICY   },
4210
                { "replace",        required_argument,   NULL, ARG_REPLACE        },
4211
                { "dry-run",        no_argument,         NULL, ARG_DRY_RUN        },
4212
                { "no-pager",       no_argument,         NULL, ARG_NO_PAGER       },
4213
                {}
4214
        };
4215

4216
        int c, r;
711✔
4217

4218
        assert(argc >= 0);
711✔
4219
        assert(argv);
711✔
4220

4221
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3,033✔
4222

4223
                switch (c) {
2,322✔
4224

4225
                case 'h':
×
4226
                        return help();
×
4227

4228
                case ARG_VERSION:
×
4229
                        return version();
×
4230

4231
                case ARG_CAT_CONFIG:
×
4232
                        arg_cat_flags = CAT_CONFIG_ON;
×
4233
                        break;
×
4234

4235
                case ARG_TLDR:
×
4236
                        arg_cat_flags = CAT_TLDR;
×
4237
                        break;
×
4238

4239
                case ARG_USER:
202✔
4240
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
202✔
4241
                        break;
202✔
4242

4243
                case ARG_CREATE:
657✔
4244
                        arg_operation |= OPERATION_CREATE;
657✔
4245
                        break;
657✔
4246

4247
                case ARG_CLEAN:
41✔
4248
                        arg_operation |= OPERATION_CLEAN;
41✔
4249
                        break;
41✔
4250

4251
                case ARG_REMOVE:
331✔
4252
                        arg_operation |= OPERATION_REMOVE;
331✔
4253
                        break;
331✔
4254

4255
                case ARG_BOOT:
561✔
4256
                        arg_boot = true;
561✔
4257
                        break;
561✔
4258

4259
                case ARG_PURGE:
5✔
4260
                        arg_operation |= OPERATION_PURGE;
5✔
4261
                        break;
5✔
4262

4263
                case ARG_GRACEFUL:
122✔
4264
                        arg_graceful = true;
122✔
4265
                        break;
122✔
4266

4267
                case ARG_PREFIX:
244✔
4268
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
244✔
4269
                                return log_oom();
×
4270
                        break;
4271

4272
                case ARG_EXCLUDE_PREFIX:
122✔
4273
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
122✔
4274
                                return log_oom();
×
4275
                        break;
4276

4277
                case ARG_ROOT:
8✔
4278
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
8✔
4279
                        if (r < 0)
8✔
4280
                                return r;
4281
                        break;
4282

4283
                case ARG_IMAGE:
×
4284
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
4285
                        if (r < 0)
×
4286
                                return r;
4287

4288
                        /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4289
                        _fallthrough_;
×
4290

4291
                case 'E':
4292
                        r = exclude_default_prefixes();
×
4293
                        if (r < 0)
×
4294
                                return r;
4295

4296
                        break;
4297

4298
                case ARG_IMAGE_POLICY:
×
4299
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4300
                        if (r < 0)
×
4301
                                return r;
4302
                        break;
4303

4304
                case ARG_REPLACE:
×
4305
                        if (!path_is_absolute(optarg))
×
4306
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4307
                                                       "The argument to --replace= must be an absolute path.");
4308
                        if (!endswith(optarg, ".conf"))
×
4309
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4310
                                                       "The argument to --replace= must have the extension '.conf'.");
4311

4312
                        arg_replace = optarg;
×
4313
                        break;
×
4314

4315
                case ARG_DRY_RUN:
29✔
4316
                        arg_dry_run = true;
29✔
4317
                        break;
29✔
4318

4319
                case ARG_NO_PAGER:
×
4320
                        arg_pager_flags |= PAGER_DISABLE;
×
4321
                        break;
×
4322

4323
                case '?':
4324
                        return -EINVAL;
4325

4326
                default:
×
4327
                        assert_not_reached();
×
4328
                }
4329

4330
        if (arg_operation == 0 && arg_cat_flags == CAT_CONFIG_OFF)
711✔
4331
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4332
                                       "You need to specify at least one of --clean, --create, --remove, or --purge.");
4333

4334
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
711✔
4335
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4336
                                       "Refusing --purge without specification of a configuration file.");
4337

4338
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
711✔
4339
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4340
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4341

4342
        if (arg_replace && optind >= argc)
711✔
4343
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4344
                                       "When --replace= is given, some configuration items must be specified.");
4345

4346
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
711✔
4347
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4348
                                       "Combination of --user and --root= is not supported.");
4349

4350
        if (arg_image && arg_root)
711✔
4351
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4352
                                       "Please specify either --root= or --image=, the combination of both is not supported.");
4353

4354
        return 1;
4355
}
4356

4357
static int read_config_file(
16,129✔
4358
                Context *c,
4359
                char **config_dirs,
4360
                const char *fn,
4361
                bool ignore_enoent,
4362
                bool *invalid_config) {
4363

4364
        ItemArray *ia;
16,129✔
4365
        int r = 0;
16,129✔
4366

4367
        assert(c);
16,129✔
4368
        assert(fn);
16,129✔
4369

4370
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
16,129✔
4371
                           parse_line, c, ignore_enoent, invalid_config);
4372
        if (r <= 0)
16,129✔
4373
                return r;
16,129✔
4374

4375
        /* we have to determine age parameter for each entry of type X */
4376
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
108,213✔
4377
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
190,267✔
4378
                        ItemArray *ja;
97,820✔
4379
                        Item *candidate_item = NULL;
97,820✔
4380

4381
                        if (i->type != IGNORE_DIRECTORY_PATH)
97,820✔
4382
                                continue;
96,022✔
4383

4384
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
182,310✔
4385
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
366,230✔
4386
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
185,718✔
4387
                                                             TRUNCATE_DIRECTORY,
4388
                                                             CREATE_SUBVOLUME,
4389
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4390
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4391
                                                continue;
94,086✔
4392

4393
                                        if (path_equal(j->path, i->path)) {
91,632✔
4394
                                                candidate_item = j;
4395
                                                break;
4396
                                        }
4397

4398
                                        if (candidate_item
91,632✔
4399
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
7,791✔
4400
                                            : path_startswith(i->path, j->path) != NULL)
83,841✔
4401
                                                candidate_item = j;
4402
                                }
4403

4404
                        if (candidate_item && candidate_item->age_set) {
1,798✔
4405
                                i->age = candidate_item->age;
1,284✔
4406
                                i->age_set = true;
1,284✔
4407
                        }
4408
                }
4409

4410
        return r;
15,766✔
4411
}
4412

4413
static int parse_arguments(
138✔
4414
                Context *c,
4415
                char **config_dirs,
4416
                char **args,
4417
                bool *invalid_config) {
4418
        int r;
138✔
4419

4420
        assert(c);
138✔
4421

4422
        STRV_FOREACH(arg, args) {
276✔
4423
                r = read_config_file(c, config_dirs, *arg, false, invalid_config);
138✔
4424
                if (r < 0)
138✔
4425
                        return r;
4426
        }
4427

4428
        return 0;
4429
}
4430

4431
static int read_config_files(
573✔
4432
                Context *c,
4433
                char **config_dirs,
4434
                char **args,
4435
                bool *invalid_config) {
4436

4437
        _cleanup_strv_free_ char **files = NULL;
×
4438
        _cleanup_free_ char *p = NULL;
573✔
4439
        int r;
573✔
4440

4441
        assert(c);
573✔
4442

4443
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
573✔
4444
        if (r < 0)
573✔
4445
                return r;
4446

4447
        STRV_FOREACH(f, files)
16,198✔
4448
                if (p && path_equal(*f, p)) {
15,625✔
4449
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4450

4451
                        r = parse_arguments(c, config_dirs, args, invalid_config);
×
4452
                        if (r < 0)
×
4453
                                return r;
4454
                } else
4455
                        /* Just warn, ignore result otherwise.
4456
                         * read_config_file() has some debug output, so no need to print anything. */
4457
                        (void) read_config_file(c, config_dirs, *f, true, invalid_config);
15,625✔
4458

4459
        return 0;
4460
}
4461

4462
static int read_credential_lines(Context *c, bool *invalid_config) {
711✔
4463
        _cleanup_free_ char *j = NULL;
711✔
4464
        const char *d;
711✔
4465
        int r;
711✔
4466

4467
        assert(c);
711✔
4468

4469
        r = get_credentials_dir(&d);
711✔
4470
        if (r == -ENXIO)
711✔
4471
                return 0;
4472
        if (r < 0)
366✔
4473
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4474

4475
        j = path_join(d, "tmpfiles.extra");
366✔
4476
        if (!j)
366✔
4477
                return log_oom();
×
4478

4479
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
366✔
4480
        return 0;
4481
}
4482

4483
static int link_parent(Context *c, ItemArray *a) {
24,213✔
4484
        const char *path;
24,213✔
4485
        char *prefix;
24,213✔
4486
        int r;
24,213✔
4487

4488
        assert(c);
24,213✔
4489
        assert(a);
24,213✔
4490

4491
        /* Finds the closest "parent" item array for the specified item array. Then registers the specified
4492
         * item array as child of it, and fills the parent in, linking them both ways. This allows us to
4493
         * later create parents before their children, and clean up/remove children before their parents.
4494
         */
4495

4496
        if (a->n_items <= 0)
24,213✔
4497
                return 0;
4498

4499
        path = a->items[0].path;
24,213✔
4500
        prefix = newa(char, strlen(path) + 1);
24,213✔
4501
        PATH_FOREACH_PREFIX(prefix, path) {
82,195✔
4502
                ItemArray *j;
43,876✔
4503

4504
                j = ordered_hashmap_get(c->items, prefix);
43,876✔
4505
                if (!j)
43,876✔
4506
                        j = ordered_hashmap_get(c->globs, prefix);
34,539✔
4507
                if (j) {
34,539✔
4508
                        r = set_ensure_put(&j->children, NULL, a);
10,107✔
4509
                        if (r < 0)
10,107✔
4510
                                return log_oom();
×
4511

4512
                        a->parent = j;
10,107✔
4513
                        return 1;
10,107✔
4514
                }
4515
        }
4516

4517
        return 0;
4518
}
4519

4520
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
24,213✔
4521
                                              ItemArray, item_array_free);
4522

4523
static int run(int argc, char *argv[]) {
711✔
4524
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
711✔
4525
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
711✔
4526
        _cleanup_strv_free_ char **config_dirs = NULL;
711✔
4527
        _cleanup_(context_done) Context c = {};
×
4528
        bool invalid_config = false;
711✔
4529
        ItemArray *a;
711✔
4530
        enum {
711✔
4531
                PHASE_PURGE,
4532
                PHASE_REMOVE_AND_CLEAN,
4533
                PHASE_CREATE,
4534
                _PHASE_MAX
4535
        } phase;
4536
        int r;
711✔
4537

4538
        r = parse_argv(argc, argv);
711✔
4539
        if (r <= 0)
711✔
4540
                return r;
4541

4542
        log_setup();
711✔
4543

4544
        /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4545
         * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4546
         * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4547
         * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4548
         * and output a nice and friendly warning. */
4549
        if (proc_mounted() == 0)
711✔
4550
                return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
×
4551
                                       "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4552
                                       "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4553

4554
        /* Descending down file system trees might take a lot of fds */
4555
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
711✔
4556

4557
        switch (arg_runtime_scope) {
711✔
4558

4559
        case RUNTIME_SCOPE_USER:
202✔
4560
                r = user_config_paths(&config_dirs);
202✔
4561
                if (r < 0)
202✔
4562
                        return log_error_errno(r, "Failed to initialize configuration directory list: %m");
×
4563
                break;
4564

4565
        case RUNTIME_SCOPE_SYSTEM:
509✔
4566
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
509✔
4567
                if (!config_dirs)
509✔
4568
                        return log_oom();
×
4569
                break;
4570

4571
        default:
×
4572
                assert_not_reached();
×
4573
        }
4574

4575
        if (DEBUG_LOGGING) {
711✔
4576
                _cleanup_free_ char *t = NULL;
599✔
4577

4578
                STRV_FOREACH(i, config_dirs) {
3,399✔
4579
                        _cleanup_free_ char *j = NULL;
2,800✔
4580

4581
                        j = path_join(arg_root, *i);
2,800✔
4582
                        if (!j)
2,800✔
4583
                                return log_oom();
×
4584

4585
                        if (!strextend(&t, "\n\t", j))
2,800✔
4586
                                return log_oom();
×
4587
                }
4588

4589
                log_debug("Looking for configuration files in (higher priority first):%s", t);
599✔
4590
        }
4591

4592
        if (arg_cat_flags != CAT_CONFIG_OFF)
711✔
4593
                return cat_config(config_dirs, argv + optind);
×
4594

4595
        if (should_bypass("SYSTEMD_TMPFILES"))
711✔
4596
                return 0;
4597

4598
        umask(0022);
711✔
4599

4600
        r = mac_init();
711✔
4601
        if (r < 0)
711✔
4602
                return r;
4603

4604
        if (arg_image) {
711✔
4605
                assert(!arg_root);
×
4606

4607
                r = mount_image_privately_interactively(
×
4608
                                arg_image,
4609
                                arg_image_policy,
4610
                                DISSECT_IMAGE_GENERIC_ROOT |
4611
                                DISSECT_IMAGE_REQUIRE_ROOT |
4612
                                DISSECT_IMAGE_VALIDATE_OS |
4613
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
4614
                                DISSECT_IMAGE_FSCK |
4615
                                DISSECT_IMAGE_GROWFS |
4616
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
4617
                                &mounted_dir,
4618
                                /* ret_dir_fd= */ NULL,
4619
                                &loop_device);
4620
                if (r < 0)
×
4621
                        return r;
4622

4623
                arg_root = strdup(mounted_dir);
×
4624
                if (!arg_root)
×
4625
                        return log_oom();
×
4626
        }
4627

4628
        c.items = ordered_hashmap_new(&item_array_hash_ops);
711✔
4629
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
711✔
4630
        if (!c.items || !c.globs)
711✔
4631
                return log_oom();
×
4632

4633
        /* If command line arguments are specified along with --replace=, read all configuration files and
4634
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4635
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
4636
         * read configuration and execute it. */
4637
        if (arg_replace || optind >= argc)
711✔
4638
                r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
573✔
4639
        else
4640
                r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
138✔
4641
        if (r < 0)
711✔
4642
                return r;
4643

4644
        r = read_credential_lines(&c, &invalid_config);
711✔
4645
        if (r < 0)
711✔
4646
                return r;
4647

4648
        /* Let's now link up all child/parent relationships */
4649
        ORDERED_HASHMAP_FOREACH(a, c.items) {
18,697✔
4650
                r = link_parent(&c, a);
17,986✔
4651
                if (r < 0)
17,986✔
4652
                        return r;
×
4653
        }
4654
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
6,938✔
4655
                r = link_parent(&c, a);
6,227✔
4656
                if (r < 0)
6,227✔
4657
                        return r;
×
4658
        }
4659

4660
        /* If multiple operations are requested, let's first run the remove/clean operations, and only then
4661
         * the create operations. i.e. that we first clean out the platform we then build on. */
4662
        for (phase = 0; phase < _PHASE_MAX; phase++) {
2,844✔
4663
                OperationMask op;
2,133✔
4664

4665
                if (phase == PHASE_PURGE)
2,133✔
4666
                        op = arg_operation & OPERATION_PURGE;
711✔
4667
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,422✔
4668
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
711✔
4669
                else if (phase == PHASE_CREATE)
711✔
4670
                        op = arg_operation & OPERATION_CREATE;
711✔
4671
                else
4672
                        assert_not_reached();
×
4673

4674
                if (op == 0) /* Nothing requested in this phase */
2,133✔
4675
                        continue;
1,099✔
4676

4677
                /* The non-globbing ones usually create things, hence we apply them first */
4678
                ORDERED_HASHMAP_FOREACH(a, c.items)
33,772✔
4679
                        RET_GATHER(r, process_item_array(&c, a, op));
32,738✔
4680

4681
                /* The globbing ones usually alter things, hence we apply them second. */
4682
                ORDERED_HASHMAP_FOREACH(a, c.globs)
11,047✔
4683
                        RET_GATHER(r, process_item_array(&c, a, op));
10,013✔
4684
        }
4685

4686
        if (ERRNO_IS_NEG_RESOURCE(r))
1,422✔
4687
                return r;
4688
        if (invalid_config)
711✔
4689
                return EX_DATAERR;
4690
        if (r < 0)
701✔
4691
                return EX_CANTCREAT;
15✔
4692
        return 0;
4693
}
4694

4695
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
711✔
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