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

systemd / systemd / 17389502517

01 Sep 2025 09:06AM UTC coverage: 72.214% (+0.03%) from 72.187%
17389502517

push

github

bluca
NEWS: mention ACLs by "uaccess" is always set by udevd

Follow-up for c960ca2be (#36444).
Prompted by https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1112660.

302438 of 418806 relevant lines covered (72.21%)

649140.06 hits per line

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

67.47
/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);
689✔
225
STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, strv_freep);
689✔
226
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
689✔
227
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
689✔
228
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
689✔
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);
10,483✔
237

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

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

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

246
        hashmap_free(c->uid_cache);
689✔
247
        hashmap_free(c->gid_cache);
689✔
248
}
689✔
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) {
89,157✔
252
        return IN_SET(r,
89,157✔
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(
×
260
                char specifier,
261
                const void *data,
262
                const char *root,
263
                const void *userdata,
264
                char **ret) {
265

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

271
        static const struct table_entry paths_system[] = {
×
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[] = {
×
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;
×
286
        _cleanup_free_ char *p = NULL;
×
287
        unsigned i;
×
288
        int r;
×
289

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

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

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

300
        if (arg_root) {
×
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);
×
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) {
186✔
351
        _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
186✔
352
        _cleanup_free_ char *runtime_config = NULL;
186✔
353
        int r;
186✔
354

355
        assert(ret);
186✔
356

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

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

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

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

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

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

382
static bool needs_purge(ItemType t) {
4,407✔
383
        return IN_SET(t,
4,407✔
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) {
23,677✔
401
        return IN_SET(t,
23,677✔
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) {
5,921✔
420
        return IN_SET(t,
5,921✔
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) {
2✔
442
        return t == CREATE_SYMLINK;
2✔
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,789✔
523
        assert(i);
1,789✔
524
        return i->binary_argument ?: i->argument;
1,789✔
525
}
526

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

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

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

539
        if (!IN_SET(errno, ENOENT, ELOOP))
498✔
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))
498✔
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,520✔
552
        return xopendirat_nomod(AT_FDCWD, path);
1,520✔
553
}
554

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

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

565
        assert(path);
539✔
566
        assert(ret);
539✔
567
        assert(ret_sx);
539✔
568
        assert(ret_mountpoint);
539✔
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);
539✔
576
        if (!d) {
539✔
577
                bool ignore = IN_SET(errno, ENOENT, ENOTDIR);
495✔
578
                r = log_full_errno(ignore ? LOG_DEBUG : LOG_ERR,
495✔
579
                                   errno, "Failed to open directory %s: %m", path);
580
                if (!ignore)
495✔
581
                        return r;
582

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

589
        if (statx(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx1) < 0)
44✔
590
                return log_error_errno(errno, "statx(%s) failed: %m", path);
×
591

592
        if (FLAGS_SET(sx1.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
44✔
593
                *ret_mountpoint = FLAGS_SET(sx1.stx_attributes, STATX_ATTR_MOUNT_ROOT);
44✔
594
        else {
595
                struct statx sx2;
×
596
                if (statx(dirfd(d), "..", 0, STATX_INO, &sx2) < 0)
×
597
                        return log_error_errno(errno, "statx(%s/..) failed: %m", path);
×
598

599
                *ret_mountpoint = !statx_mount_same(&sx1, &sx2);
×
600
        }
601

602
        *ret = TAKE_PTR(d);
44✔
603
        *ret_sx = sx1;
44✔
604
        return 1;
44✔
605
}
606

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

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

624
                return false;
24✔
625
        }
626

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

633
                return false;
63✔
634
        }
635

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

646
                return false;
7✔
647
        }
648

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

655
                return false;
5✔
656
        }
657

658
        return true;
659
}
660

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

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

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

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

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

691
                /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
692
                 * explicitly where we are looking at a mount point, for free as side information. Determining
693
                 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
694
                 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
695
                 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
696
                 * while on older kernels's well do traditional st_dev based detection of mount points.
697
                 *
698
                 * Using statx() for detecting mount points also has the benefit that we handle weird file
699
                 * systems such as overlayfs better where each file is originating from a different
700
                 * st_dev. */
701

702
                struct statx sx;
188✔
703
                if (statx(dirfd(d), de->d_name,
188✔
704
                          AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
705
                          STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
706
                          &sx) < 0) {
707
                        if (errno == ENOENT)
×
708
                                continue;
×
709

710
                        /* FUSE, NFS mounts, SELinux might return EACCES */
711
                        log_full_errno(errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
×
712
                                       "statx(%s/%s) failed: %m", p, de->d_name);
713
                        continue;
×
714
                }
715

716
                if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) {
188✔
717
                        /* Yay, we have the mount point API, use it */
718
                        if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
188✔
719
                                log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
×
720
                                continue;
×
721
                        }
722
                } else {
723
                        /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
724
                         * back to traditional stx_dev checking. */
725
                        if (sx.stx_dev_major != rootdev_major ||
×
726
                            sx.stx_dev_minor != rootdev_minor) {
×
727
                                log_debug("Ignoring \"%s/%s\": different filesystem.", p, de->d_name);
×
728
                                continue;
×
729
                        }
730

731
                        /* Try to detect bind mounts of the same filesystem instance; they do not differ in
732
                         * device major/minors. This type of query is not supported on all kernels or
733
                         * filesystem types though. */
734
                        if (S_ISDIR(sx.stx_mode)) {
×
735
                                int q;
×
736

737
                                q = is_mount_point_at(dirfd(d), de->d_name, 0);
×
738
                                if (q < 0)
×
739
                                        log_debug_errno(q, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p, de->d_name);
×
740
                                else if (q > 0) {
×
741
                                        log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p, de->d_name);
×
742
                                        continue;
×
743
                                }
744
                        }
745
                }
746

747
                atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : 0;
188✔
748
                mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : 0;
188✔
749
                ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : 0;
188✔
750
                btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : 0;
188✔
751

752
                sub_path = path_join(p, de->d_name);
188✔
753
                if (!sub_path) {
188✔
754
                        r = log_oom();
×
755
                        goto finish;
×
756
                }
757

758
                /* Is there an item configured for this path? */
759
                if (ordered_hashmap_get(c->items, sub_path)) {
188✔
760
                        log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
5✔
761
                        continue;
5✔
762
                }
763

764
                if (find_glob(c->globs, sub_path)) {
183✔
765
                        log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
18✔
766
                        continue;
18✔
767
                }
768

769
                if (S_ISDIR(sx.stx_mode)) {
165✔
770
                        _cleanup_closedir_ DIR *sub_dir = NULL;
×
771

772
                        if (mountpoint &&
37✔
773
                            streq(de->d_name, "lost+found") &&
×
774
                            sx.stx_uid == 0) {
×
775
                                log_debug("Ignoring directory \"%s\".", sub_path);
×
776
                                continue;
×
777
                        }
778

779
                        if (maxdepth <= 0)
37✔
780
                                log_warning("Reached max depth on \"%s\".", sub_path);
×
781
                        else {
782
                                int q;
37✔
783

784
                                sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
37✔
785
                                if (!sub_dir) {
37✔
786
                                        if (errno != ENOENT)
×
787
                                                r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
×
788

789
                                        continue;
×
790
                                }
791

792
                                if (!arg_dry_run &&
70✔
793
                                    flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
33✔
794
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path);
×
795
                                        continue;
×
796
                                }
797

798
                                q = dir_cleanup(c, i,
37✔
799
                                                sub_path, sub_dir,
800
                                                atime_nsec, mtime_nsec, cutoff_nsec,
801
                                                rootdev_major, rootdev_minor,
802
                                                false, maxdepth-1, false,
803
                                                age_by_file, age_by_dir);
804
                                if (q < 0)
37✔
805
                                        r = q;
×
806
                        }
807

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

813
                        if (keep_this_level) {
37✔
814
                                log_debug("Keeping directory \"%s\".", sub_path);
×
815
                                continue;
×
816
                        }
817

818
                        /*
819
                         * Check the file timestamps of an entry against the
820
                         * given cutoff time; delete if it is older.
821
                         */
822
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
37✔
823
                                           cutoff_nsec, sub_path, age_by_dir, true))
824
                                continue;
25✔
825

826
                        log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path);
16✔
827
                        if (!arg_dry_run &&
20✔
828
                            unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0 &&
8✔
829
                            !IN_SET(errno, ENOENT, ENOTEMPTY))
×
830
                                r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
×
831

832
                } else {
833
                        _cleanup_close_ int fd = -EBADF; /* This file descriptor is defined here so that the
350✔
834
                                                          * lock that is taken below is only dropped _after_
835
                                                          * the unlink operation has finished. */
836

837
                        /* Skip files for which the sticky bit is set. These are semantics we define, and are
838
                         * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
839
                        if (sx.stx_mode & S_ISVTX) {
128✔
840
                                log_debug("Skipping \"%s\": sticky bit set.", sub_path);
×
841
                                continue;
×
842
                        }
843

844
                        if (mountpoint &&
128✔
845
                            S_ISREG(sx.stx_mode) &&
×
846
                            sx.stx_uid == 0 &&
×
847
                            STR_IN_SET(de->d_name,
×
848
                                       ".journal",
849
                                       "aquota.user",
850
                                       "aquota.group")) {
851
                                log_debug("Skipping \"%s\".", sub_path);
×
852
                                continue;
×
853
                        }
854

855
                        /* Ignore sockets that are listed in /proc/net/unix */
856
                        if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
128✔
857
                                log_debug("Skipping \"%s\": live socket.", sub_path);
×
858
                                continue;
×
859
                        }
860

861
                        /* Ignore device nodes */
862
                        if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
128✔
863
                                log_debug("Skipping \"%s\": a device.", sub_path);
×
864
                                continue;
×
865
                        }
866

867
                        /* Keep files on this level if this was requested */
868
                        if (keep_this_level) {
128✔
869
                                log_debug("Keeping \"%s\".", sub_path);
×
870
                                continue;
×
871
                        }
872

873
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
128✔
874
                                           cutoff_nsec, sub_path, age_by_file, false))
875
                                continue;
74✔
876

877
                        if (!arg_dry_run) {
54✔
878
                                fd = xopenat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME|O_NONBLOCK|O_NOCTTY);
34✔
879
                                if (fd < 0 && !IN_SET(fd, -ENOENT, -ELOOP))
34✔
880
                                        log_warning_errno(fd, "Opening file \"%s\" failed, proceeding without lock: %m", sub_path);
×
881
                                if (fd >= 0 && flock(fd, LOCK_EX|LOCK_NB) < 0 && errno == EAGAIN) {
34✔
882
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", sub_path);
×
883
                                        continue;
×
884
                                }
885
                        }
886

887
                        log_action("Would remove", "Removing", "%s \"%s\"", sub_path);
70✔
888
                        if (!arg_dry_run &&
88✔
889
                            unlinkat(dirfd(d), de->d_name, 0) < 0 &&
34✔
890
                            errno != ENOENT)
×
891
                                r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
×
892

893
                        deleted = true;
54✔
894
                }
895
        }
896

897
finish:
81✔
898
        if (deleted && (self_atime_nsec < NSEC_INFINITY || self_mtime_nsec < NSEC_INFINITY)) {
81✔
899
                struct timespec ts[2];
28✔
900

901
                log_action("Would restore", "Restoring",
37✔
902
                           "%s access and modification time on \"%s\": %s, %s",
903
                           p,
904
                           FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
905
                           FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
906

907
                timespec_store_nsec(ts + 0, self_atime_nsec);
28✔
908
                timespec_store_nsec(ts + 1, self_mtime_nsec);
28✔
909

910
                /* Restore original directory timestamps */
911
                if (!arg_dry_run &&
45✔
912
                    futimens(dirfd(d), ts) < 0)
17✔
913
                        log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
28✔
914
        }
915

916
        return r;
81✔
917
}
918

919
static bool hardlinks_protected(void) {
×
920
        static int cached = -1;
×
921
        int r;
×
922

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

927
        if (cached >= 0)
×
928
                return cached;
×
929

930
        _cleanup_free_ char *value = NULL;
×
931

932
        r = sysctl_read("fs/protected_hardlinks", &value);
×
933
        if (r < 0) {
×
934
                log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
×
935
                return false;
×
936
        }
937

938
        cached = parse_boolean(value);
×
939
        if (cached < 0)
×
940
                log_debug_errno(cached, "Failed to parse fs.protected_hardlinks sysctl, assuming disabled: %m");
×
941
        return cached > 0;
×
942
}
943

944
static bool hardlink_vulnerable(const struct stat *st) {
14,686✔
945
        assert(st);
14,686✔
946

947
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
14,686✔
948
}
949

950
static mode_t process_mask_perms(mode_t mode, mode_t current) {
282✔
951

952
        if ((current & 0111) == 0)
282✔
953
                mode &= ~0111;
181✔
954
        if ((current & 0222) == 0)
282✔
955
                mode &= ~0222;
×
956
        if ((current & 0444) == 0)
282✔
957
                mode &= ~0444;
×
958
        if (!S_ISDIR(current))
282✔
959
                mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
181✔
960

961
        return mode;
282✔
962
}
963

964
static int fd_set_perms(
19,097✔
965
                Context *c,
966
                Item *i,
967
                int fd,
968
                const char *path,
969
                const struct stat *st,
970
                CreationMode creation) {
971

972
        bool do_chown, do_chmod;
19,097✔
973
        struct stat stbuf;
19,097✔
974
        mode_t new_mode;
19,097✔
975
        uid_t new_uid;
19,097✔
976
        gid_t new_gid;
19,097✔
977
        int r;
19,097✔
978

979
        assert(c);
19,097✔
980
        assert(i);
19,097✔
981
        assert(fd >= 0);
19,097✔
982
        assert(path);
19,097✔
983

984
        if (!i->mode_set && !i->uid_set && !i->gid_set)
19,097✔
985
                goto shortcut;
5,136✔
986

987
        if (!st) {
13,961✔
988
                if (fstat(fd, &stbuf) < 0)
3,236✔
989
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
990
                st = &stbuf;
991
        }
992

993
        if (hardlink_vulnerable(st))
13,961✔
994
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
995
                                       "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
996
                                       path);
997
        new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
13,961✔
998
        new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
13,961✔
999

1000
        /* Do we need a chown()? */
1001
        do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
13,961✔
1002

1003
        /* Calculate the mode to apply */
1004
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
27,369✔
1005
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
27,653✔
1006
                (st->st_mode & 07777);
269✔
1007

1008
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
13,961✔
1009

1010
        if (do_chmod && do_chown) {
13,961✔
1011
                /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
1012
                 * the new mode. That way there's no time window where the file exists under the old owner
1013
                 * with more than the old access modes — and not under the new owner with more than the new
1014
                 * access modes either. */
1015

1016
                if (S_ISLNK(st->st_mode))
728✔
1017
                        log_debug("Skipping temporary mode fix for symlink %s.", path);
×
1018
                else {
1019
                        mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
728✔
1020

1021
                        if (((m ^ st->st_mode) & 07777) == 0)
728✔
1022
                                log_debug("\"%s\" matches temporary mode %o already.", path, m);
717✔
1023
                        else {
1024
                                log_action("Would temporarily change", "Temporarily changing",
11✔
1025
                                           "%s \"%s\" to mode %o", path, m);
1026
                                if (!arg_dry_run) {
11✔
1027
                                        r = fchmod_opath(fd, m);
11✔
1028
                                        if (r < 0)
11✔
1029
                                                return log_error_errno(r, "fchmod() of %s failed: %m", path);
×
1030
                                }
1031
                        }
1032
                }
1033
        }
1034

1035
        if (do_chown) {
13,961✔
1036
                log_action("Would change", "Changing",
2,818✔
1037
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1038

1039
                if (!arg_dry_run &&
2,850✔
1040
                    fchownat(fd, "",
1,424✔
1041
                             new_uid != st->st_uid ? new_uid : UID_INVALID,
1,424✔
1042
                             new_gid != st->st_gid ? new_gid : GID_INVALID,
1,424✔
1043
                             AT_EMPTY_PATH) < 0)
1044
                        return log_error_errno(errno, "fchownat() of %s failed: %m", path);
×
1045
        }
1046

1047
        /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
1048
         * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
1049
        if (do_chmod || do_chown) {
13,961✔
1050
                if (S_ISLNK(st->st_mode))
2,748✔
1051
                        log_debug("Skipping mode fix for symlink %s.", path);
×
1052
                else {
1053
                        log_action("Would change", "Changing", "%s \"%s\" to mode %o", path, new_mode);
5,458✔
1054
                        if (!arg_dry_run) {
2,748✔
1055
                                r = fchmod_opath(fd, new_mode);
2,746✔
1056
                                if (r < 0)
2,746✔
1057
                                        return log_error_errno(r, "fchmod() of %s failed: %m", path);
2✔
1058
                        }
1059
                }
1060
        }
1061

1062
shortcut:
13,959✔
1063
        if (arg_dry_run) {
19,095✔
1064
                log_debug("Would relabel \"%s\"", path);
5✔
1065
                return 0;
5✔
1066
        }
1067

1068
        log_debug("Relabelling \"%s\"", path);
19,090✔
1069
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
19,090✔
1070
}
1071

1072
static int path_open_parent_safe(const char *path, bool allow_failure) {
16,230✔
1073
        _cleanup_free_ char *dn = NULL;
16,230✔
1074
        int r, fd;
16,230✔
1075

1076
        if (!path_is_normalized(path))
16,230✔
1077
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1078
                                      SYNTHETIC_ERRNO(EINVAL),
1079
                                      "Failed to open parent of '%s': path not normalized%s.",
1080
                                      path,
1081
                                      allow_failure ? ", ignoring" : "");
1082

1083
        r = path_extract_directory(path, &dn);
16,230✔
1084
        if (r < 0)
16,230✔
1085
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1086
                                      r,
1087
                                      "Unable to determine parent directory of '%s'%s: %m",
1088
                                      path,
1089
                                      allow_failure ? ", ignoring" : "");
1090

1091
        r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
32,210✔
1092
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
16,230✔
1093
                return r;
1094
        if (r < 0)
16,225✔
1095
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1096
                                      r,
1097
                                      "Failed to open path '%s'%s: %m",
1098
                                      dn,
1099
                                      allow_failure ? ", ignoring" : "");
1100

1101
        return fd;
16,225✔
1102
}
1103

1104
static int path_open_safe(const char *path) {
3,591✔
1105
        int r, fd;
3,591✔
1106

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

1111
        assert(path);
3,591✔
1112

1113
        if (!path_is_normalized(path))
3,591✔
1114
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
×
1115

1116
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
3,591✔
1117
        if (r == -ENOLINK)
3,591✔
1118
                return r; /* Unsafe symlink: already covered by CHASE_WARN */
1119
        if (r < 0)
3,591✔
1120
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
1121
                                      "Failed to open path %s%s: %m", path,
1122
                                      r == -ENOENT ? ", ignoring" : "");
1123

1124
        return fd;
3,591✔
1125
}
1126

1127
static int path_set_perms(
3,092✔
1128
                Context *c,
1129
                Item *i,
1130
                const char *path,
1131
                CreationMode creation) {
1132

1133
        _cleanup_close_ int fd = -EBADF;
3,092✔
1134

1135
        assert(c);
3,092✔
1136
        assert(i);
3,092✔
1137
        assert(path);
3,092✔
1138

1139
        fd = path_open_safe(path);
3,092✔
1140
        if (fd == -ENOENT)
3,092✔
1141
                return 0;
1142
        if (fd < 0)
3,092✔
1143
                return fd;
1144

1145
        return fd_set_perms(c, i, fd, path, /* st= */ NULL, creation);
3,092✔
1146
}
1147

1148
static int parse_xattrs_from_arg(Item *i) {
×
1149
        const char *p;
×
1150
        int r;
×
1151

1152
        assert(i);
×
1153

1154
        assert_se(p = i->argument);
×
1155
        for (;;) {
×
1156
                _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
×
1157

1158
                r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
×
1159
                if (r < 0)
×
1160
                        log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
×
1161
                if (r <= 0)
×
1162
                        break;
1163

1164
                r = split_pair(xattr, "=", &name, &value);
×
1165
                if (r < 0) {
×
1166
                        log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
×
1167
                        continue;
×
1168
                }
1169

1170
                if (isempty(name) || isempty(value)) {
×
1171
                        log_warning("Malformed extended attribute found, ignoring: %s", xattr);
×
1172
                        continue;
×
1173
                }
1174

1175
                if (strv_push_pair(&i->xattrs, name, value) < 0)
×
1176
                        return log_oom();
×
1177

1178
                name = value = NULL;
×
1179
        }
1180

1181
        return 0;
×
1182
}
1183

1184
static int fd_set_xattrs(
×
1185
                Context *c,
1186
                Item *i,
1187
                int fd,
1188
                const char *path,
1189
                const struct stat *st,
1190
                CreationMode creation) {
1191

1192
        int r;
×
1193

1194
        assert(c);
×
1195
        assert(i);
×
1196
        assert(fd >= 0);
×
1197
        assert(path);
×
1198

1199
        STRV_FOREACH_PAIR(name, value, i->xattrs) {
×
1200
                log_action("Would set", "Setting",
×
1201
                           "%s extended attribute '%s=%s' on %s", *name, *value, path);
1202

1203
                if (!arg_dry_run) {
×
1204
                        r = xsetxattr(fd, /* path = */ NULL, AT_EMPTY_PATH, *name, *value);
×
1205
                        if (r < 0)
×
1206
                                return log_error_errno(r, "Failed to set extended attribute %s=%s on '%s': %m",
×
1207
                                                       *name, *value, path);
1208
                }
1209
        }
1210
        return 0;
1211
}
1212

1213
static int path_set_xattrs(
×
1214
                Context *c,
1215
                Item *i,
1216
                const char *path,
1217
                CreationMode creation) {
1218

1219
        _cleanup_close_ int fd = -EBADF;
×
1220

1221
        assert(c);
×
1222
        assert(i);
×
1223
        assert(path);
×
1224

1225
        fd = path_open_safe(path);
×
1226
        if (fd == -ENOENT)
×
1227
                return 0;
1228
        if (fd < 0)
×
1229
                return fd;
1230

1231
        return fd_set_xattrs(c, i, fd, path, /* st = */ NULL, creation);
×
1232
}
1233

1234
static int parse_acls_from_arg(Item *item) {
2,559✔
1235
#if HAVE_ACL
1236
        int r;
2,559✔
1237

1238
        assert(item);
2,559✔
1239

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

1243
        r = parse_acl(item->argument, &item->acl_access, &item->acl_access_exec,
5,118✔
1244
                      &item->acl_default, !item->append_or_force);
2,559✔
1245
        if (r < 0)
2,559✔
1246
                log_full_errno(arg_graceful && IN_SET(r, -EINVAL, -ENOENT, -ESRCH) ? LOG_DEBUG : LOG_WARNING,
×
1247
                               r, "Failed to parse ACL \"%s\", ignoring: %m", item->argument);
1248
#else
1249
        log_warning("ACLs are not supported, ignoring.");
1250
#endif
1251

1252
        return 0;
2,559✔
1253
}
1254

1255
#if HAVE_ACL
1256
static int parse_acl_cond_exec(
278✔
1257
                const char *path,
1258
                const struct stat *st,
1259
                acl_t cond_exec,
1260
                acl_t access, /* could be empty (NULL) */
1261
                bool append,
1262
                acl_t *ret) {
1263

1264
        acl_entry_t entry;
278✔
1265
        acl_permset_t permset;
278✔
1266
        bool has_exec;
278✔
1267
        int r;
278✔
1268

1269
        assert(path);
278✔
1270
        assert(st);
278✔
1271
        assert(cond_exec);
278✔
1272
        assert(ret);
278✔
1273

1274
        if (!S_ISDIR(st->st_mode)) {
278✔
1275
                _cleanup_(acl_freep) acl_t old = NULL;
×
1276

1277
                old = acl_get_file(path, ACL_TYPE_ACCESS);
177✔
1278
                if (!old)
177✔
1279
                        return -errno;
×
1280

1281
                has_exec = false;
177✔
1282

1283
                for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
177✔
1284
                     r > 0;
702✔
1285
                     r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
525✔
1286

1287
                        acl_tag_t tag;
538✔
1288

1289
                        if (acl_get_tag_type(entry, &tag) < 0)
538✔
1290
                                return -errno;
×
1291

1292
                        if (tag == ACL_MASK)
538✔
1293
                                continue;
8✔
1294

1295
                        /* If not appending, skip ACL definitions */
1296
                        if (!append && IN_SET(tag, ACL_USER, ACL_GROUP))
532✔
1297
                                continue;
2✔
1298

1299
                        if (acl_get_permset(entry, &permset) < 0)
530✔
1300
                                return -errno;
×
1301

1302
                        r = acl_get_perm(permset, ACL_EXECUTE);
530✔
1303
                        if (r < 0)
530✔
1304
                                return -errno;
×
1305
                        if (r > 0) {
530✔
1306
                                has_exec = true;
13✔
1307
                                break;
13✔
1308
                        }
1309
                }
1310
                if (r < 0)
177✔
1311
                        return -errno;
×
1312

1313
                /* Check if we're about to set the execute bit in acl_access */
1314
                if (!has_exec && access) {
177✔
1315
                        for (r = acl_get_entry(access, ACL_FIRST_ENTRY, &entry);
×
1316
                             r > 0;
×
1317
                             r = acl_get_entry(access, ACL_NEXT_ENTRY, &entry)) {
×
1318

1319
                                if (acl_get_permset(entry, &permset) < 0)
×
1320
                                        return -errno;
×
1321

1322
                                r = acl_get_perm(permset, ACL_EXECUTE);
×
1323
                                if (r < 0)
×
1324
                                        return -errno;
×
1325
                                if (r > 0) {
×
1326
                                        has_exec = true;
1327
                                        break;
1328
                                }
1329
                        }
1330
                        if (r < 0)
×
1331
                                return -errno;
×
1332
                }
1333
        } else
1334
                has_exec = true;
1335

1336
        _cleanup_(acl_freep) acl_t parsed = access ? acl_dup(access) : acl_init(0);
556✔
1337
        if (!parsed)
278✔
1338
                return -errno;
×
1339

1340
        for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
278✔
1341
             r > 0;
830✔
1342
             r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
552✔
1343

1344
                acl_entry_t parsed_entry;
552✔
1345

1346
                if (acl_create_entry(&parsed, &parsed_entry) < 0)
552✔
1347
                        return -errno;
×
1348

1349
                if (acl_copy_entry(parsed_entry, entry) < 0)
552✔
1350
                        return -errno;
×
1351

1352
                /* We substituted 'X' with 'x' in parse_acl(), so drop execute bit here if not applicable. */
1353
                if (!has_exec) {
552✔
1354
                        if (acl_get_permset(parsed_entry, &permset) < 0)
325✔
1355
                                return -errno;
×
1356

1357
                        if (acl_delete_perm(permset, ACL_EXECUTE) < 0)
325✔
1358
                                return -errno;
×
1359
                }
1360
        }
1361
        if (r < 0)
278✔
1362
                return -errno;
×
1363

1364
        if (!append) { /* want_mask = true */
278✔
1365
                r = calc_acl_mask_if_needed(&parsed);
3✔
1366
                if (r < 0)
3✔
1367
                        return r;
1368
        }
1369

1370
        *ret = TAKE_PTR(parsed);
278✔
1371

1372
        return 0;
278✔
1373
}
1374

1375
static int path_set_acl(
999✔
1376
                Context *c,
1377
                const char *path,
1378
                const char *pretty,
1379
                acl_type_t type,
1380
                acl_t acl,
1381
                bool modify) {
1382

1383
        _cleanup_(acl_free_charpp) char *t = NULL;
999✔
1384
        _cleanup_(acl_freep) acl_t dup = NULL;
999✔
1385
        int r;
999✔
1386

1387
        assert(c);
999✔
1388

1389
        /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1390

1391
        if (modify) {
999✔
1392
                r = acls_for_file(path, type, acl, &dup);
996✔
1393
                if (r < 0)
996✔
1394
                        return r;
1395

1396
                r = calc_acl_mask_if_needed(&dup);
996✔
1397
                if (r < 0)
996✔
1398
                        return r;
1399
        } else {
1400
                dup = acl_dup(acl);
3✔
1401
                if (!dup)
3✔
1402
                        return -errno;
×
1403

1404
                /* the mask was already added earlier if needed */
1405
        }
1406

1407
        r = add_base_acls_if_needed(&dup, path);
999✔
1408
        if (r < 0)
999✔
1409
                return r;
1410

1411
        t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
999✔
1412
        log_action("Would set", "Setting",
2,462✔
1413
                   "%s %s ACL %s on %s",
1414
                   type == ACL_TYPE_ACCESS ? "access" : "default",
1415
                   strna(t), pretty);
1416

1417
        if (!arg_dry_run &&
1,997✔
1418
            acl_set_file(path, type, dup) < 0) {
998✔
1419
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
1420
                        /* No error if filesystem doesn't support ACLs. Return negative. */
1421
                        return -errno;
×
1422
                else
1423
                        /* Return positive to indicate we already warned */
1424
                        return -log_error_errno(errno,
×
1425
                                                "Setting %s ACL \"%s\" on %s failed: %m",
1426
                                                type == ACL_TYPE_ACCESS ? "access" : "default",
1427
                                                strna(t), pretty);
1428
        }
1429
        return 0;
1430
}
1431
#endif
1432

1433
static int fd_set_acls(
725✔
1434
                Context *c,
1435
                Item *item,
1436
                int fd,
1437
                const char *path,
1438
                const struct stat *st,
1439
                CreationMode creation) {
1440

1441
        int r = 0;
725✔
1442
#if HAVE_ACL
1443
        _cleanup_(acl_freep) acl_t access_with_exec_parsed = NULL;
725✔
1444
        struct stat stbuf;
725✔
1445

1446
        assert(c);
725✔
1447
        assert(item);
725✔
1448
        assert(fd >= 0);
725✔
1449
        assert(path);
725✔
1450

1451
        if (!st) {
725✔
1452
                if (fstat(fd, &stbuf) < 0)
451✔
1453
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1454
                st = &stbuf;
1455
        }
1456

1457
        if (hardlink_vulnerable(st))
725✔
1458
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
1459
                                       "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1460
                                       path);
1461

1462
        if (S_ISLNK(st->st_mode)) {
725✔
1463
                log_debug("Skipping ACL fix for symlink %s.", path);
×
1464
                return 0;
×
1465
        }
1466

1467
        if (item->acl_access_exec) {
725✔
1468
                r = parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd), st,
278✔
1469
                                        item->acl_access_exec,
1470
                                        item->acl_access,
1471
                                        item->append_or_force,
278✔
1472
                                        &access_with_exec_parsed);
1473
                if (r < 0)
278✔
1474
                        return log_error_errno(r, "Failed to parse conditionalized execute bit for \"%s\": %m", path);
×
1475

1476
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
278✔
1477
        } else if (item->acl_access)
447✔
1478
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
197✔
1479

1480
        /* set only default acls to folders */
1481
        if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
725✔
1482
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
524✔
1483

1484
        if (ERRNO_IS_NOT_SUPPORTED(r)) {
725✔
1485
                log_debug_errno(r, "ACLs not supported by file system at %s", path);
×
1486
                return 0;
×
1487
        }
1488
        if (r > 0)
725✔
1489
                return -r; /* already warned in path_set_acl */
×
1490
        if (r < 0)
725✔
1491
                return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
×
1492
#endif
1493
        return r;
1494
}
1495

1496
static int path_set_acls(
451✔
1497
                Context *c,
1498
                Item *item,
1499
                const char *path,
1500
                CreationMode creation) {
1501

1502
        int r = 0;
451✔
1503
#if HAVE_ACL
1504
        _cleanup_close_ int fd = -EBADF;
451✔
1505

1506
        assert(c);
451✔
1507
        assert(item);
451✔
1508
        assert(path);
451✔
1509

1510
        fd = path_open_safe(path);
451✔
1511
        if (fd == -ENOENT)
451✔
1512
                return 0;
1513
        if (fd < 0)
451✔
1514
                return fd;
1515

1516
        r = fd_set_acls(c, item, fd, path, /* st= */ NULL, creation);
451✔
1517
#endif
1518
        return r;
1519
}
1520

1521
static int parse_attribute_from_arg(Item *item) {
1,095✔
1522
        static const struct {
1,095✔
1523
                char character;
1524
                unsigned value;
1525
        } attributes[] = {
1526
                { 'A', FS_NOATIME_FL },      /* do not update atime */
1527
                { 'S', FS_SYNC_FL },         /* Synchronous updates */
1528
                { 'D', FS_DIRSYNC_FL },      /* dirsync behaviour (directories only) */
1529
                { 'a', FS_APPEND_FL },       /* writes to file may only append */
1530
                { 'c', FS_COMPR_FL },        /* Compress file */
1531
                { 'd', FS_NODUMP_FL },       /* do not dump file */
1532
                { 'e', FS_EXTENT_FL },       /* Extents */
1533
                { 'i', FS_IMMUTABLE_FL },    /* Immutable file */
1534
                { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1535
                { 's', FS_SECRM_FL },        /* Secure deletion */
1536
                { 'u', FS_UNRM_FL },         /* Undelete */
1537
                { 't', FS_NOTAIL_FL },       /* file tail should not be merged */
1538
                { 'T', FS_TOPDIR_FL },       /* Top of directory hierarchies */
1539
                { 'C', FS_NOCOW_FL },        /* Do not cow file */
1540
                { 'P', FS_PROJINHERIT_FL },  /* Inherit the quota project ID */
1541
        };
1542

1543
        enum {
1,095✔
1544
                MODE_ADD,
1545
                MODE_DEL,
1546
                MODE_SET
1547
        } mode = MODE_ADD;
1,095✔
1548

1549
        unsigned value = 0, mask = 0;
1,095✔
1550
        const char *p;
1,095✔
1551

1552
        assert(item);
1,095✔
1553

1554
        p = item->argument;
1,095✔
1555
        if (p) {
1,095✔
1556
                if (*p == '+') {
1,095✔
1557
                        mode = MODE_ADD;
1,095✔
1558
                        p++;
1,095✔
1559
                } else if (*p == '-') {
×
1560
                        mode = MODE_DEL;
×
1561
                        p++;
×
1562
                } else  if (*p == '=') {
×
1563
                        mode = MODE_SET;
×
1564
                        p++;
×
1565
                }
1566
        }
1567

1568
        if (isempty(p) && mode != MODE_SET)
1,095✔
1569
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1570
                                       "Setting file attribute on '%s' needs an attribute specification.",
1571
                                       item->path);
1572

1573
        for (; p && *p ; p++) {
2,190✔
1574
                unsigned i, v;
1575

1576
                for (i = 0; i < ELEMENTSOF(attributes); i++)
15,330✔
1577
                        if (*p == attributes[i].character)
15,330✔
1578
                                break;
1579

1580
                if (i >= ELEMENTSOF(attributes))
1,095✔
1581
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1582
                                               "Unknown file attribute '%c' on '%s'.", *p, item->path);
1583

1584
                v = attributes[i].value;
1,095✔
1585

1586
                SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1,095✔
1587

1588
                mask |= v;
1,095✔
1589
        }
1590

1591
        if (mode == MODE_SET)
1,095✔
1592
                mask |= CHATTR_ALL_FL;
×
1593

1594
        assert(mask != 0);
1,095✔
1595

1596
        item->attribute_mask = mask;
1,095✔
1597
        item->attribute_value = value;
1,095✔
1598
        item->attribute_set = true;
1,095✔
1599

1600
        return 0;
1,095✔
1601
}
1602

1603
static int fd_set_attribute(
48✔
1604
                Context *c,
1605
                Item *item,
1606
                int fd,
1607
                const char *path,
1608
                const struct stat *st,
1609
                CreationMode creation) {
1610

1611
        struct stat stbuf;
48✔
1612
        unsigned f;
48✔
1613
        int r;
48✔
1614

1615
        assert(c);
48✔
1616
        assert(item);
48✔
1617
        assert(fd >= 0);
48✔
1618
        assert(path);
48✔
1619

1620
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1621
                return 0;
48✔
1622

1623
        if (!st) {
48✔
1624
                if (fstat(fd, &stbuf) < 0)
48✔
1625
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1626
                st = &stbuf;
1627
        }
1628

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

1636
        f = item->attribute_value & item->attribute_mask;
48✔
1637

1638
        /* Mask away directory-specific flags */
1639
        if (!S_ISDIR(st->st_mode))
48✔
1640
                f &= ~FS_DIRSYNC_FL;
×
1641

1642
        log_action("Would try to set", "Trying to set",
96✔
1643
                   "%s file attributes 0x%08x on %s",
1644
                   f & item->attribute_mask,
1645
                   path);
1646

1647
        if (!arg_dry_run) {
48✔
1648
                _cleanup_close_ int procfs_fd = -EBADF;
48✔
1649

1650
                procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
48✔
1651
                if (procfs_fd < 0)
48✔
1652
                        return log_error_errno(procfs_fd, "Failed to reopen '%s': %m", path);
×
1653

1654
                unsigned previous, current;
48✔
1655
                r = chattr_full(procfs_fd, NULL, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
48✔
1656
                if (r == -ENOANO)
48✔
1657
                        log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
×
1658
                                    "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1659
                                    path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1660
                else if (r < 0)
48✔
1661
                        log_full_errno(ERRNO_IS_IOCTL_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
48✔
1662
                                       "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1663
                                       path, item->attribute_value, item->attribute_mask);
1664
        }
1665

1666
        return 0;
1667
}
1668

1669
static int path_set_attribute(
48✔
1670
                Context *c,
1671
                Item *item,
1672
                const char *path,
1673
                CreationMode creation) {
1674

1675
        _cleanup_close_ int fd = -EBADF;
48✔
1676

1677
        assert(c);
48✔
1678
        assert(item);
48✔
1679

1680
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1681
                return 0;
1682

1683
        fd = path_open_safe(path);
48✔
1684
        if (fd == -ENOENT)
48✔
1685
                return 0;
1686
        if (fd < 0)
48✔
1687
                return fd;
1688

1689
        return fd_set_attribute(c, item, fd, path, /* st= */ NULL, creation);
48✔
1690
}
1691

1692
static int write_argument_data(Item *i, int fd, const char *path) {
269✔
1693
        int r;
269✔
1694

1695
        assert(i);
269✔
1696
        assert(fd >= 0);
269✔
1697
        assert(path);
269✔
1698

1699
        if (item_binary_argument_size(i) == 0)
269✔
1700
                return 0;
1701

1702
        assert(item_binary_argument(i));
261✔
1703

1704
        log_action("Would write", "Writing", "%s to \"%s\"", path);
490✔
1705

1706
        if (!arg_dry_run) {
261✔
1707
                r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i));
258✔
1708
                if (r < 0)
258✔
1709
                        return log_error_errno(r, "Failed to write file \"%s\": %m", path);
×
1710
        }
1711

1712
        return 0;
1713
}
1714

1715
static int write_one_file(Context *c, Item *i, const char *path, CreationMode creation) {
18✔
1716
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
18✔
1717
        _cleanup_free_ char *bn = NULL;
18✔
1718
        int r;
18✔
1719

1720
        assert(c);
18✔
1721
        assert(i);
18✔
1722
        assert(path);
18✔
1723
        assert(i->type == WRITE_FILE);
18✔
1724

1725
        r = path_extract_filename(path, &bn);
18✔
1726
        if (r < 0)
18✔
1727
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1728
        if (r == O_DIRECTORY)
18✔
1729
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1730

1731
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1732
         * can't be changed behind our back. */
1733
        dir_fd = path_open_parent_safe(path, i->allow_failure);
18✔
1734
        if (dir_fd < 0)
18✔
1735
                return dir_fd;
1736

1737
        /* Follow symlinks. Open with O_PATH in dry-run mode to make sure we don't use the path inadvertently. */
1738
        int flags = O_NONBLOCK | O_CLOEXEC | O_WRONLY | O_NOCTTY | i->append_or_force * O_APPEND | arg_dry_run * O_PATH;
18✔
1739
        fd = openat(dir_fd, bn, flags, i->mode);
18✔
1740
        if (fd < 0) {
18✔
1741
                if (errno == ENOENT) {
×
1742
                        log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
×
1743
                        return 0;
×
1744
                }
1745

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

1749
                return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
×
1750
        }
1751

1752
        /* 'w' is allowed to write into any kind of files. */
1753

1754
        r = write_argument_data(i, fd, path);
18✔
1755
        if (r < 0)
18✔
1756
                return r;
1757

1758
        return fd_set_perms(c, i, fd, path, NULL, creation);
18✔
1759
}
1760

1761
static int create_file(
788✔
1762
                Context *c,
1763
                Item *i,
1764
                const char *path) {
1765

1766
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
788✔
1767
        _cleanup_free_ char *bn = NULL;
788✔
1768
        struct stat stbuf, *st = NULL;
788✔
1769
        CreationMode creation;
788✔
1770
        int r = 0;
788✔
1771

1772
        assert(c);
788✔
1773
        assert(i);
788✔
1774
        assert(path);
788✔
1775
        assert(i->type == CREATE_FILE);
788✔
1776

1777
        /* 'f' operates on regular files exclusively. */
1778

1779
        r = path_extract_filename(path, &bn);
788✔
1780
        if (r < 0)
788✔
1781
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1782
        if (r == O_DIRECTORY)
788✔
1783
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1784

1785
        if (arg_dry_run) {
788✔
1786
                log_info("Would create file %s", path);
4✔
1787
                return 0;
4✔
1788

1789
                /* The opening of the directory below would fail if it doesn't exist,
1790
                 * so log and exit before even trying to do that. */
1791
        }
1792

1793
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1794
         * can't be changed behind our back. */
1795
        dir_fd = path_open_parent_safe(path, i->allow_failure);
784✔
1796
        if (dir_fd < 0)
784✔
1797
                return dir_fd;
1798

1799
        WITH_UMASK(0000) {
1,564✔
1800
                mac_selinux_create_file_prepare(path, S_IFREG);
782✔
1801
                fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
782✔
1802
                mac_selinux_create_file_clear();
782✔
1803
        }
1804

1805
        if (fd < 0) {
782✔
1806
                /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1807
                 * returns EROFS only if it needs to create the file. */
1808
                if (fd != -EEXIST)
653✔
1809
                        return log_error_errno(fd, "Failed to create file %s: %m", path);
1✔
1810

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

1818
                if (fstat(fd, &stbuf) < 0)
652✔
1819
                        return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1820

1821
                if (!S_ISREG(stbuf.st_mode))
652✔
1822
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
5✔
1823
                                               "%s exists and is not a regular file.",
1824
                                               path);
1825

1826
                st = &stbuf;
1827
                creation = CREATION_EXISTING;
1828
        } else {
1829
                r = write_argument_data(i, fd, path);
129✔
1830
                if (r < 0)
129✔
1831
                        return r;
1832

1833
                creation = CREATION_NORMAL;
1834
        }
1835

1836
        return fd_set_perms(c, i, fd, path, st, creation);
776✔
1837
}
1838

1839
static int truncate_file(
251✔
1840
                Context *c,
1841
                Item *i,
1842
                const char *path) {
1843

1844
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
251✔
1845
        _cleanup_free_ char *bn = NULL;
251✔
1846
        struct stat stbuf, *st = NULL;
251✔
1847
        CreationMode creation;
251✔
1848
        bool erofs = false;
251✔
1849
        int r = 0;
251✔
1850

1851
        assert(c);
251✔
1852
        assert(i);
251✔
1853
        assert(path);
251✔
1854
        assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
251✔
1855

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

1860
        r = path_extract_filename(path, &bn);
251✔
1861
        if (r < 0)
251✔
1862
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1863
        if (r == O_DIRECTORY)
251✔
1864
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
×
1865

1866
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1867
         * can't be changed behind our back. */
1868
        dir_fd = path_open_parent_safe(path, i->allow_failure);
251✔
1869
        if (dir_fd < 0)
251✔
1870
                return dir_fd;
1871

1872
        if (arg_dry_run) {
250✔
1873
                log_info("Would truncate %s", path);
×
1874
                return 0;
×
1875
        }
1876

1877
        creation = CREATION_EXISTING;
250✔
1878
        fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
250✔
1879
        if (fd == -ENOENT) {
226✔
1880
                creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
221✔
1881

1882
                WITH_UMASK(0000) {
442✔
1883
                        mac_selinux_create_file_prepare(path, S_IFREG);
221✔
1884
                        fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
221✔
1885
                        mac_selinux_create_file_clear();
221✔
1886
                }
1887
        }
1888

1889
        if (fd < 0) {
250✔
1890
                if (fd != -EROFS)
6✔
1891
                        return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1✔
1892

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

1897
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
5✔
1898
                if (fd < 0) {
5✔
1899
                        if (errno == ENOENT)
1✔
1900
                                return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1✔
1901
                                                       "Cannot create file %s on a read-only file system.",
1902
                                                       path);
1903

1904
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
×
1905
                }
1906

1907
                erofs = true;
1908
                creation = CREATION_EXISTING;
1909
        }
1910

1911
        if (fstat(fd, &stbuf) < 0)
248✔
1912
                return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1913

1914
        if (!S_ISREG(stbuf.st_mode))
248✔
1915
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1916
                                       "%s exists and is not a regular file.",
1917
                                       path);
1918

1919
        if (stbuf.st_size > 0) {
248✔
1920
                if (ftruncate(fd, 0) < 0) {
15✔
1921
                        r = erofs ? -EROFS : -errno;
2✔
1922
                        return log_error_errno(r, "Failed to truncate file %s: %m", path);
2✔
1923
                }
1924
        } else
1925
                st = &stbuf;
1926

1927
        log_debug("\"%s\" has been created.", path);
246✔
1928

1929
        if (item_binary_argument(i)) {
246✔
1930
                r = write_argument_data(i, fd, path);
122✔
1931
                if (r < 0)
122✔
1932
                        return r;
1933
        }
1934

1935
        return fd_set_perms(c, i, fd, path, st, creation);
246✔
1936
}
1937

1938
static int copy_files(Context *c, Item *i) {
3,859✔
1939
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
3,859✔
1940
        _cleanup_free_ char *bn = NULL;
3,859✔
1941
        struct stat st, a;
3,859✔
1942
        int r;
3,859✔
1943

1944
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
7,579✔
1945
        if (arg_dry_run)
3,859✔
1946
                return 0;
1947

1948
        r = path_extract_filename(i->path, &bn);
3,857✔
1949
        if (r < 0)
3,857✔
1950
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
1951

1952
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1953
         * path can't be changed behind our back. */
1954
        dfd = path_open_parent_safe(i->path, i->allow_failure);
3,857✔
1955
        if (dfd < 0)
3,857✔
1956
                return dfd;
1957

1958
        r = copy_tree_at(AT_FDCWD, i->argument,
3,861✔
1959
                         dfd, bn,
1960
                         i->uid_set ? i->uid : UID_INVALID,
3,857✔
1961
                         i->gid_set ? i->gid : GID_INVALID,
3,857✔
1962
                         COPY_REFLINK | ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
3,857✔
1963
                         NULL, NULL);
1964

1965
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
3,857✔
1966
        if (fd < 0) {
3,857✔
1967
                if (r < 0) /* Look at original error first */
×
1968
                        return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
×
1969

1970
                return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
×
1971
        }
1972

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

1976
        if (stat(i->argument, &a) < 0)
3,857✔
1977
                return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
×
1978

1979
        if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
3,857✔
1980
                log_debug("Can't copy to %s, file exists already and is of different type", i->path);
×
1981
                return 0;
×
1982
        }
1983

1984
        return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
3,857✔
1985
}
1986

1987
static int create_directory_or_subvolume(
7,894✔
1988
                const char *path,
1989
                mode_t mode,
1990
                bool subvol,
1991
                bool allow_failure,
1992
                struct stat *ret_st,
1993
                CreationMode *ret_creation) {
1994

1995
        _cleanup_free_ char *bn = NULL;
7,894✔
1996
        _cleanup_close_ int pfd = -EBADF;
7,894✔
1997
        CreationMode creation;
7,894✔
1998
        struct stat st;
7,894✔
1999
        int r, fd;
7,894✔
2000

2001
        assert(path);
7,894✔
2002

2003
        r = path_extract_filename(path, &bn);
7,894✔
2004
        if (r < 0)
7,894✔
2005
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
2006

2007
        pfd = path_open_parent_safe(path, allow_failure);
7,894✔
2008
        if (pfd < 0)
7,894✔
2009
                return pfd;
2010

2011
        if (subvol) {
7,892✔
2012
                r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
875✔
2013
                if (r < 0) {
875✔
2014
                        if (r != -ENXIO) /* env var is unset */
875✔
2015
                                log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
×
2016
                        r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
875✔
2017
                }
2018
                if (r == 0)
875✔
2019
                        /* Don't create a subvolume unless the root directory is one, too. We do this under
2020
                         * the assumption that if the root directory is just a plain directory (i.e. very
2021
                         * lightweight), we shouldn't try to split it up into subvolumes (i.e. more
2022
                         * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
2023
                         * subvolume set up below their tree only if they specifically set up a btrfs
2024
                         * subvolume for the root dir too. */
2025
                        subvol = false;
2026
                else {
2027
                        log_action("Would create", "Creating", "%s btrfs subvolume %s", path);
×
2028
                        if (!arg_dry_run)
×
2029
                                WITH_UMASK((~mode) & 0777)
×
2030
                                        r = btrfs_subvol_make(pfd, bn);
×
2031
                        else
2032
                                r = 0;
2033
                }
2034
        } else
2035
                r = 0;
2036

2037
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2038
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
15,494✔
2039
                if (!arg_dry_run)
7,892✔
2040
                        WITH_UMASK(0000)
15,784✔
2041
                                r = mkdirat_label(pfd, bn, mode);
7,892✔
2042
        }
2043

2044
        if (arg_dry_run)
7,892✔
2045
                return 0;
2046

2047
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
7,892✔
2048

2049
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
7,892✔
2050
        if (fd < 0) {
7,892✔
2051
                /* We couldn't open it because it is not actually a directory? */
2052
                if (errno == ENOTDIR)
×
2053
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
×
2054

2055
                /* Then look at the original error */
2056
                if (r < 0)
×
2057
                        return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
2058
                                              r,
2059
                                              "Failed to create directory or subvolume \"%s\"%s: %m",
2060
                                              path,
2061
                                              allow_failure ? ", ignoring" : "");
2062

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

2066
        if (fstat(fd, &st) < 0)
7,892✔
2067
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2068

2069
        assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
7,892✔
2070

2071
        log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
7,892✔
2072

2073
        if (ret_st)
7,892✔
2074
                *ret_st = st;
7,892✔
2075
        if (ret_creation)
7,892✔
2076
                *ret_creation = creation;
7,892✔
2077

2078
        return fd;
2079
}
2080

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

2086
        _cleanup_close_ int fd = -EBADF;
7,030✔
2087
        CreationMode creation;
7,030✔
2088
        struct stat st;
7,030✔
2089

2090
        assert(c);
7,030✔
2091
        assert(i);
7,030✔
2092
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
7,030✔
2093

2094
        if (arg_dry_run) {
7,030✔
2095
                log_info("Would create directory %s", path);
11✔
2096
                return 0;
11✔
2097
        }
2098

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

2105
        return fd_set_perms(c, i, fd, path, &st, creation);
7,017✔
2106
}
2107

2108
static int create_subvolume(
875✔
2109
                Context *c,
2110
                Item *i,
2111
                const char *path) {
2112

2113
        _cleanup_close_ int fd = -EBADF;
875✔
2114
        CreationMode creation;
875✔
2115
        struct stat st;
875✔
2116
        int r, q = 0;
875✔
2117

2118
        assert(c);
875✔
2119
        assert(i);
875✔
2120
        assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
875✔
2121

2122
        if (arg_dry_run) {
875✔
2123
                log_info("Would create subvolume %s", path);
×
2124
                return 0;
×
2125
        }
2126

2127
        fd = create_directory_or_subvolume(path, i->mode, /* subvol = */ true, i->allow_failure, &st, &creation);
875✔
2128
        if (fd == -EEXIST)
875✔
2129
                return 0;
2130
        if (fd < 0)
875✔
2131
                return fd;
2132

2133
        if (creation == CREATION_NORMAL &&
875✔
2134
            IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
3✔
2135
                r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
3✔
2136
                if (r == -ENOTTY)
3✔
2137
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
3✔
2138
                else if (r == -EROFS)
×
2139
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
×
2140
                else if (r == -ENOTCONN)
×
2141
                        log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
×
2142
                else if (r < 0)
×
2143
                        q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
×
2144
                else if (r > 0)
×
2145
                        log_debug("Adjusted quota for subvolume \"%s\".", i->path);
×
2146
                else if (r == 0)
×
2147
                        log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
×
2148
        }
2149

2150
        r = fd_set_perms(c, i, fd, path, &st, creation);
875✔
2151
        if (q < 0) /* prefer the quota change error from above */
875✔
2152
                return q;
×
2153

2154
        return r;
2155
}
2156

2157
static int empty_directory(
5✔
2158
                Context *c,
2159
                Item *i,
2160
                const char *path,
2161
                CreationMode creation) {
2162

2163
        _cleanup_close_ int fd = -EBADF;
5✔
2164
        struct stat st;
5✔
2165
        int r;
5✔
2166

2167
        assert(c);
5✔
2168
        assert(i);
5✔
2169
        assert(i->type == EMPTY_DIRECTORY);
5✔
2170

2171
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
5✔
2172
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
5✔
2173
                return r;
2174
        if (r == -ENOENT) {
5✔
2175
                /* Option "e" operates only on existing objects. Do not print errors about non-existent files
2176
                 * or directories */
2177
                log_debug_errno(r, "Skipping missing directory: %s", path);
×
2178
                return 0;
×
2179
        }
2180
        if (r < 0)
5✔
2181
                return log_error_errno(r, "Failed to open directory '%s': %m", path);
×
2182

2183
        if (fstat(fd, &st) < 0)
5✔
2184
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2185
        if (!S_ISDIR(st.st_mode)) {
5✔
2186
                log_warning("'%s' already exists and is not a directory.", path);
1✔
2187
                return 0;
1✔
2188
        }
2189

2190
        return fd_set_perms(c, i, fd, path, &st, creation);
4✔
2191
}
2192

2193
static int create_device(
1,924✔
2194
                Context *c,
2195
                Item *i,
2196
                mode_t file_type) {
2197

2198
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
1,924✔
2199
        _cleanup_free_ char *bn = NULL;
1,924✔
2200
        CreationMode creation;
1,924✔
2201
        struct stat st;
1,924✔
2202
        int r;
1,924✔
2203

2204
        assert(c);
1,924✔
2205
        assert(i);
1,924✔
2206
        assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
1,924✔
2207
        assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1,924✔
2208

2209
        r = path_extract_filename(i->path, &bn);
1,924✔
2210
        if (r < 0)
1,924✔
2211
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2212
        if (r == O_DIRECTORY)
1,924✔
2213
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2214
                                       "Cannot open path '%s' for creating device node, is a directory.", i->path);
2215

2216
        if (arg_dry_run) {
1,924✔
2217
                log_info("Would create device node %s", i->path);
4✔
2218
                return 0;
4✔
2219
        }
2220

2221
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2222
         * path can't be changed behind our back. */
2223
        dfd = path_open_parent_safe(i->path, i->allow_failure);
1,920✔
2224
        if (dfd < 0)
1,920✔
2225
                return dfd;
2226

2227
        WITH_UMASK(0000) {
3,840✔
2228
                mac_selinux_create_file_prepare(i->path, file_type);
1,920✔
2229
                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
1,920✔
2230
                mac_selinux_create_file_clear();
1,920✔
2231
        }
2232
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,920✔
2233

2234
        /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2235
         * order anyway and we hence can ignore the error to create the device node */
2236
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1,920✔
2237
        if (fd < 0) {
1,920✔
2238
                /* OK, so opening the inode failed, let's look at the original error then. */
2239

2240
                if (r < 0) {
×
2241
                        if (ERRNO_IS_PRIVILEGE(r))
×
2242
                                goto handle_privilege;
×
2243

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

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

2250
        if (fstat(fd, &st) < 0)
1,920✔
2251
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2252

2253
        if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
1,920✔
2254

2255
                if (i->append_or_force) {
×
2256
                        fd = safe_close(fd);
×
2257

2258
                        WITH_UMASK(0000) {
×
2259
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2260
                                r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
×
2261
                                mac_selinux_create_file_clear();
×
2262
                        }
2263
                        if (ERRNO_IS_PRIVILEGE(r))
×
2264
                                goto handle_privilege;
×
2265
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
×
2266
                                r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
×
2267
                                if (r < 0)
×
2268
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2269

2270
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2271
                                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
×
2272
                                mac_selinux_create_file_clear();
×
2273
                        }
2274
                        if (r < 0)
×
2275
                                return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
×
2276

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

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

2285
                        if (((st.st_mode ^ file_type) & S_IFMT) != 0)
×
2286
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2287
                                                       "Device node we just created is not a device node, refusing.");
2288

2289
                        creation = CREATION_FORCE;
2290
                } else {
2291
                        log_warning("\"%s\" already exists and is not a device node.", i->path);
×
2292
                        return 0;
×
2293
                }
2294
        }
2295

2296
        log_debug("%s %s device node \"%s\" %u:%u.",
3,840✔
2297
                  creation_mode_verb_to_string(creation),
2298
                  i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
2299
                  i->path, major(i->mode), minor(i->mode));
2300

2301
        return fd_set_perms(c, i, fd, i->path, &st, creation);
1,920✔
2302

2303
handle_privilege:
×
2304
        log_debug_errno(r,
1,924✔
2305
                        "We lack permissions, possibly because of cgroup configuration; "
2306
                        "skipping creation of device node '%s'.", i->path);
2307
        return 0;
2308
}
2309

2310
static int create_fifo(Context *c, Item *i) {
4✔
2311
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
4✔
2312
        _cleanup_free_ char *bn = NULL;
4✔
2313
        CreationMode creation;
4✔
2314
        struct stat st;
4✔
2315
        int r;
4✔
2316

2317
        assert(c);
4✔
2318
        assert(i);
4✔
2319
        assert(i->type == CREATE_FIFO);
4✔
2320

2321
        r = path_extract_filename(i->path, &bn);
4✔
2322
        if (r < 0)
4✔
2323
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2324
        if (r == O_DIRECTORY)
4✔
2325
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2326
                                       "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2327

2328
        if (arg_dry_run) {
4✔
2329
                log_info("Would create fifo %s", i->path);
1✔
2330
                return 0;
1✔
2331
        }
2332

2333
        pfd = path_open_parent_safe(i->path, i->allow_failure);
3✔
2334
        if (pfd < 0)
3✔
2335
                return pfd;
2336

2337
        WITH_UMASK(0000) {
6✔
2338
                mac_selinux_create_file_prepare(i->path, S_IFIFO);
3✔
2339
                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
3✔
2340
                mac_selinux_create_file_clear();
3✔
2341
        }
2342

2343
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
3✔
2344

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

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

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

2357
        if (!S_ISFIFO(st.st_mode)) {
3✔
2358

2359
                if (i->append_or_force) {
2✔
2360
                        fd = safe_close(fd);
1✔
2361

2362
                        WITH_UMASK(0000) {
2✔
2363
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
1✔
2364
                                r = mkfifoat_atomic(pfd, bn, i->mode);
1✔
2365
                                mac_selinux_create_file_clear();
1✔
2366
                        }
2367
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1✔
2368
                                r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
×
2369
                                if (r < 0)
×
2370
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2371

2372
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
×
2373
                                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
×
2374
                                mac_selinux_create_file_clear();
×
2375
                        }
2376
                        if (r < 0)
1✔
2377
                                return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
×
2378

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

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

2387
                        if (!S_ISFIFO(st.st_mode))
1✔
2388
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2389
                                                       "FIFO inode we just created is not a FIFO, refusing.");
2390

2391
                        creation = CREATION_FORCE;
2392
                } else {
2393
                        log_warning("\"%s\" already exists and is not a FIFO.", i->path);
1✔
2394
                        return 0;
1✔
2395
                }
2396
        }
2397

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

2400
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2✔
2401
}
2402

2403
static int create_symlink(Context *c, Item *i) {
1,506✔
2404
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
1,506✔
2405
        _cleanup_free_ char *bn = NULL;
1,506✔
2406
        CreationMode creation;
1,506✔
2407
        struct stat st;
1,506✔
2408
        bool good = false;
1,506✔
2409
        int r;
1,506✔
2410

2411
        assert(c);
1,506✔
2412
        assert(i);
1,506✔
2413

2414
        if (i->ignore_if_target_missing) {
1,506✔
2415
                r = chase(i->argument, arg_root, CHASE_SAFE|CHASE_PREFIX_ROOT|CHASE_NOFOLLOW, /* ret_path = */ NULL, /* ret_fd = */ NULL);
2✔
2416
                if (r == -ENOENT) {
2✔
2417
                        /* Silently skip over lines where the source file is missing. */
2418
                        log_info("Symlink source path '%s/%s' does not exist, skipping line.",
1✔
2419
                                 empty_to_root(arg_root), skip_leading_slash(i->argument));
2420
                        return 0;
1✔
2421
                }
2422
                if (r < 0)
1✔
2423
                        return log_error_errno(r, "Failed to check if symlink source path '%s/%s' exists: %m",
×
2424
                                               empty_to_root(arg_root), skip_leading_slash(i->argument));
2425
        }
2426

2427
        r = path_extract_filename(i->path, &bn);
1,505✔
2428
        if (r < 0)
1,505✔
2429
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2430
        if (r == O_DIRECTORY)
1,505✔
2431
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2432
                                       "Cannot open path '%s' for creating symlink, is a directory.", i->path);
2433

2434
        if (arg_dry_run) {
1,505✔
2435
                log_info("Would create symlink %s -> %s", i->path, i->argument);
2✔
2436
                return 0;
2✔
2437
        }
2438

2439
        pfd = path_open_parent_safe(i->path, i->allow_failure);
1,503✔
2440
        if (pfd < 0)
1,503✔
2441
                return pfd;
2442

2443
        mac_selinux_create_file_prepare(i->path, S_IFLNK);
1,503✔
2444
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
1,503✔
2445
        mac_selinux_create_file_clear();
1,503✔
2446

2447
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,503✔
2448

2449
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1,503✔
2450
        if (fd < 0) {
1,503✔
2451
                if (r < 0)
×
2452
                        return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
×
2453

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

2457
        if (fstat(fd, &st) < 0)
1,503✔
2458
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2459

2460
        if (S_ISLNK(st.st_mode)) {
1,503✔
2461
                _cleanup_free_ char *x = NULL;
×
2462

2463
                r = readlinkat_malloc(fd, "", &x);
1,502✔
2464
                if (r < 0)
1,502✔
2465
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
×
2466

2467
                good = streq(x, i->argument);
1,502✔
2468
        } else
2469
                good = false;
2470

2471
        if (!good) {
1,502✔
2472
                if (!i->append_or_force) {
504✔
2473
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
500✔
2474
                        return 0;
500✔
2475
                }
2476

2477
                fd = safe_close(fd);
4✔
2478

2479
                r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
4✔
2480
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
4✔
2481
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
1✔
2482
                        if (r < 0)
1✔
2483
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2484

2485
                        r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
1✔
2486
                }
2487
                if (r < 0)
4✔
2488
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2489

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

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

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

2501
                creation = CREATION_FORCE;
2502
        }
2503

2504
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
1,003✔
2505
        return fd_set_perms(c, i, fd, i->path, &st, creation);
1,003✔
2506
}
2507

2508
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2509
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2510

2511
static int item_do(
561✔
2512
                Context *c,
2513
                Item *i,
2514
                int fd,
2515
                const char *path,
2516
                CreationMode creation,
2517
                fdaction_t action) {
2518

2519
        struct stat st;
561✔
2520
        int r;
561✔
2521

2522
        assert(c);
561✔
2523
        assert(i);
561✔
2524
        assert(fd >= 0);
561✔
2525
        assert(path);
561✔
2526
        assert(action);
561✔
2527

2528
        if (fstat(fd, &st) < 0) {
561✔
2529
                r = log_error_errno(errno, "fstat() on file failed: %m");
×
2530
                goto finish;
×
2531
        }
2532

2533
        /* This returns the first error we run into, but nevertheless tries to go on */
2534
        r = action(c, i, fd, path, &st, creation);
561✔
2535

2536
        if (S_ISDIR(st.st_mode)) {
561✔
2537
                _cleanup_closedir_ DIR *d = NULL;
204✔
2538

2539
                /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2540
                 * reading the directory content. */
2541
                d = opendir(FORMAT_PROC_FD_PATH(fd));
204✔
2542
                if (!d) {
204✔
2543
                        RET_GATHER(r, log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd)));
×
2544
                        goto finish;
×
2545
                }
2546

2547
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
969✔
2548
                        _cleanup_close_ int de_fd = -EBADF;
765✔
2549
                        _cleanup_free_ char *de_path = NULL;
765✔
2550

2551
                        if (dot_or_dot_dot(de->d_name))
765✔
2552
                                continue;
408✔
2553

2554
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
357✔
2555
                        if (de_fd < 0) {
357✔
2556
                                if (errno != ENOENT)
×
2557
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
×
2558
                                continue;
×
2559
                        }
2560

2561
                        de_path = path_join(path, de->d_name);
357✔
2562
                        if (!de_path) {
357✔
2563
                                r = log_oom();
×
2564
                                goto finish;
×
2565
                        }
2566

2567
                        /* Pass ownership of dirent fd over */
2568
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
357✔
2569
                }
2570
        }
2571

2572
finish:
357✔
2573
        safe_close(fd);
561✔
2574
        return r;
561✔
2575
}
2576

2577
static int glob_item(Context *c, Item *i, action_t action) {
6,248✔
2578
        _cleanup_strv_free_ char **paths = NULL;
6,248✔
2579
        int r;
6,248✔
2580

2581
        assert(c);
6,248✔
2582
        assert(i);
6,248✔
2583
        assert(action);
6,248✔
2584

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

2591
        r = 0;
3,149✔
2592
        STRV_FOREACH(fn, paths)
6,805✔
2593
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2594
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
3,656✔
2595

2596
        return r;
2597
}
2598

2599
static int glob_item_recursively(
252✔
2600
                Context *c,
2601
                Item *i,
2602
                fdaction_t action) {
2603

2604
        _cleanup_strv_free_ char **paths = NULL;
252✔
2605
        int r;
252✔
2606

2607
        assert(c);
252✔
2608
        assert(i);
252✔
2609
        assert(action);
252✔
2610

2611
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
252✔
2612
        if (r == -ENOENT)
252✔
2613
                return 0;
2614
        if (r < 0)
204✔
2615
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2616

2617
        r = 0;
204✔
2618
        STRV_FOREACH(fn, paths) {
408✔
2619
                _cleanup_close_ int fd = -EBADF;
204✔
2620

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

2625
                fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
204✔
2626
                if (fd < 0) {
204✔
2627
                        RET_GATHER(r, log_error_errno(errno, "Failed to open '%s': %m", *fn));
×
2628
                        continue;
×
2629
                }
2630

2631
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
204✔
2632
        }
2633

2634
        return r;
2635
}
2636

2637
static int rm_if_wrong_type_safe(
×
2638
                mode_t mode,
2639
                int parent_fd,
2640
                const struct stat *parent_st, /* Only used if follow_links below is true. */
2641
                const char *name,
2642
                int flags) {
2643
        _cleanup_free_ char *parent_name = NULL;
×
2644
        bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
×
2645
        struct stat st;
×
2646
        int r;
×
2647

2648
        assert(name);
×
2649
        assert((mode & ~S_IFMT) == 0);
×
2650
        assert(!follow_links || parent_st);
×
2651
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2652

2653
        if (mode == 0)
×
2654
                return 0;
2655

2656
        if (!filename_is_valid(name))
×
2657
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2658

2659
        r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2660
        if (r < 0) {
×
2661
                (void) fd_get_path(parent_fd, &parent_name);
×
2662
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
2663
                                      "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
2664
        }
2665

2666
        /* Fail before removing anything if this is an unsafe transition. */
2667
        if (follow_links && unsafe_transition(parent_st, &st)) {
×
2668
                (void) fd_get_path(parent_fd, &parent_name);
×
2669
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
×
2670
                                       "Unsafe transition from \"%s\" to \"%s\".", parent_name ?: "...", name);
2671
        }
2672

2673
        if ((st.st_mode & S_IFMT) == mode)
×
2674
                return 0;
2675

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

2679
        /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2680
         * target, so make sure it is identified as a link and not a directory. */
2681
        if (follow_links) {
×
2682
                r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2683
                if (r < 0)
×
2684
                        return log_error_errno(r, "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
×
2685
        }
2686

2687
        /* Do not remove mount points. */
2688
        r = is_mount_point_at(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
×
2689
        if (r < 0)
×
2690
                (void) log_warning_errno(r, "Failed to check if  \"%s/%s\" is a mount point: %m; continuing.",
×
2691
                                         parent_name ?: "...", name);
2692
        else if (r > 0)
×
2693
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
×
2694
                                "Not removing  \"%s/%s\" because it is a mount point.", parent_name ?: "...", name);
2695

2696
        log_action("Would remove", "Removing", "%s %s/%s", parent_name ?: "...", name);
×
2697
        if (!arg_dry_run) {
×
2698
                if ((st.st_mode & S_IFMT) == S_IFDIR) {
×
2699
                        _cleanup_close_ int child_fd = -EBADF;
×
2700

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

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

2709
                        r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2710
                } else
2711
                        r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2712
                if (r < 0)
×
2713
                        return log_error_errno(r, "Failed to remove \"%s/%s\": %m", parent_name ?: "...", name);
×
2714
        }
2715

2716
        /* This is covered by the log_notice "Wrong file type...".
2717
         * It is logged earlier because it gives context to other error messages that might follow. */
2718
        return -ENOENT;
2719
}
2720

2721
/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2722
static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
×
2723
        _cleanup_close_ int parent_fd = -EBADF;
×
2724
        struct stat parent_st;
×
2725
        size_t path_len;
×
2726
        int r;
×
2727

2728
        assert(path);
×
2729
        assert((child_mode & ~S_IFMT) == 0);
×
2730

2731
        path_len = strlen(path);
×
2732

2733
        if (!is_path(path))
×
2734
                /* rm_if_wrong_type_safe already logs errors. */
2735
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2736

2737
        if (child_mode != 0 && endswith(path, "/"))
×
2738
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2739
                                "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2740

2741
        /* Get the parent_fd and stat. */
2742
        parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
×
2743
        if (parent_fd < 0)
×
2744
                return log_error_errno(errno, "Failed to open root: %m");
×
2745

2746
        if (fstat(parent_fd, &parent_st) < 0)
×
2747
                return log_error_errno(errno, "Failed to stat root: %m");
×
2748

2749
        /* Check every parent directory in the path, except the last component */
2750
        for (const char *e = path;;) {
×
2751
                _cleanup_close_ int next_fd = -EBADF;
×
2752
                char t[path_len + 1];
×
2753
                const char *s;
×
2754

2755
                /* Find the start of the next path component. */
2756
                s = e + strspn(e, "/");
×
2757
                /* Find the end of the next path component. */
2758
                e = s + strcspn(s, "/");
×
2759

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

2763
                /* Is this the last component? If so, then check the type */
2764
                if (*e == 0)
×
2765
                        return rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2766

2767
                r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
×
2768
                /* Remove dangling symlinks. */
2769
                if (r == -ENOENT)
×
2770
                        r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2771
                if (r == -ENOENT) {
×
2772
                        if (!arg_dry_run) {
×
2773
                                WITH_UMASK(0000)
×
2774
                                        r = mkdirat_label(parent_fd, t, 0755);
×
2775
                                if (r < 0) {
×
2776
                                        _cleanup_free_ char *parent_name = NULL;
×
2777

2778
                                        (void) fd_get_path(parent_fd, &parent_name);
×
2779
                                        return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2780
                                }
2781
                        }
2782
                } else if (r < 0)
×
2783
                        /* rm_if_wrong_type_safe already logs errors. */
2784
                        return r;
2785

2786
                next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
×
2787
                if (next_fd < 0) {
×
2788
                        _cleanup_free_ char *parent_name = NULL;
×
2789

2790
                        (void) fd_get_path(parent_fd, &parent_name);
×
2791
                        return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2792
                }
2793
                r = RET_NERRNO(fstat(next_fd, &parent_st));
×
2794
                if (r < 0) {
×
2795
                        _cleanup_free_ char *parent_name = NULL;
×
2796

2797
                        (void) fd_get_path(parent_fd, &parent_name);
×
2798
                        return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2799
                }
2800

2801
                close_and_replace(parent_fd, next_fd);
×
2802
        }
2803
}
2804

2805
static int mkdir_parents_item(Item *i, mode_t child_mode) {
16,237✔
2806
        int r;
16,237✔
2807

2808
        if (i->try_replace) {
16,237✔
2809
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2810
                if (r < 0 && r != -ENOENT)
×
2811
                        return r;
×
2812
        } else
2813
                WITH_UMASK(0000)
32,474✔
2814
                        if (!arg_dry_run)
16,237✔
2815
                                (void) mkdir_parents_label(i->path, 0755);
16,237✔
2816

2817
        return 0;
2818
}
2819

2820
static int create_item(Context *c, Item *i) {
23,580✔
2821
        int r;
23,580✔
2822

2823
        assert(c);
23,580✔
2824
        assert(i);
23,580✔
2825

2826
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
23,580✔
2827

2828
        switch (i->type) {
23,580✔
2829

2830
        case IGNORE_PATH:
2831
        case IGNORE_DIRECTORY_PATH:
2832
        case REMOVE_PATH:
2833
        case RECURSIVE_REMOVE_PATH:
2834
                return 0;
2835

2836
        case TRUNCATE_FILE:
1,039✔
2837
        case CREATE_FILE:
2838
                r = mkdir_parents_item(i, S_IFREG);
1,039✔
2839
                if (r < 0)
1,039✔
2840
                        return r;
2841

2842
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,039✔
2843
                        r = truncate_file(c, i, i->path);
251✔
2844
                else
2845
                        r = create_file(c, i, i->path);
788✔
2846
                if (r < 0)
1,039✔
2847
                        return r;
15✔
2848
                break;
2849

2850
        case COPY_FILES:
3,859✔
2851
                r = mkdir_parents_item(i, 0);
3,859✔
2852
                if (r < 0)
3,859✔
2853
                        return r;
2854

2855
                r = copy_files(c, i);
3,859✔
2856
                if (r < 0)
3,859✔
2857
                        return r;
×
2858
                break;
2859

2860
        case WRITE_FILE:
20✔
2861
                r = glob_item(c, i, write_one_file);
20✔
2862
                if (r < 0)
20✔
2863
                        return r;
×
2864

2865
                break;
2866

2867
        case CREATE_DIRECTORY:
7,030✔
2868
        case TRUNCATE_DIRECTORY:
2869
                r = mkdir_parents_item(i, S_IFDIR);
7,030✔
2870
                if (r < 0)
7,030✔
2871
                        return r;
2872

2873
                r = create_directory(c, i, i->path);
7,030✔
2874
                if (r < 0)
7,030✔
2875
                        return r;
2✔
2876
                break;
2877

2878
        case CREATE_SUBVOLUME:
875✔
2879
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
2880
        case CREATE_SUBVOLUME_NEW_QUOTA:
2881
                r = mkdir_parents_item(i, S_IFDIR);
875✔
2882
                if (r < 0)
875✔
2883
                        return r;
2884

2885
                r = create_subvolume(c, i, i->path);
875✔
2886
                if (r < 0)
875✔
2887
                        return r;
×
2888
                break;
2889

2890
        case EMPTY_DIRECTORY:
4✔
2891
                r = glob_item(c, i, empty_directory);
4✔
2892
                if (r < 0)
4✔
2893
                        return r;
×
2894
                break;
2895

2896
        case CREATE_FIFO:
4✔
2897
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2898
                if (r < 0)
4✔
2899
                        return r;
2900

2901
                r = create_fifo(c, i);
4✔
2902
                if (r < 0)
4✔
2903
                        return r;
×
2904
                break;
2905

2906
        case CREATE_SYMLINK:
1,506✔
2907
                r = mkdir_parents_item(i, S_IFLNK);
1,506✔
2908
                if (r < 0)
1,506✔
2909
                        return r;
2910

2911
                r = create_symlink(c, i);
1,506✔
2912
                if (r < 0)
1,506✔
2913
                        return r;
×
2914

2915
                break;
2916

2917
        case CREATE_BLOCK_DEVICE:
1,924✔
2918
        case CREATE_CHAR_DEVICE:
2919
                if (have_effective_cap(CAP_MKNOD) <= 0) {
1,924✔
2920
                        /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2921
                         * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2922

2923
                        log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
×
2924
                        return 0;
×
2925
                }
2926

2927
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,846✔
2928
                if (r < 0)
1,924✔
2929
                        return r;
2930

2931
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,846✔
2932
                if (r < 0)
1,924✔
2933
                        return r;
×
2934

2935
                break;
2936

2937
        case ADJUST_MODE:
4,335✔
2938
        case RELABEL_PATH:
2939
                r = glob_item(c, i, path_set_perms);
4,335✔
2940
                if (r < 0)
4,335✔
2941
                        return r;
×
2942
                break;
2943

2944
        case RECURSIVE_RELABEL_PATH:
127✔
2945
                r = glob_item_recursively(c, i, fd_set_perms);
127✔
2946
                if (r < 0)
127✔
2947
                        return r;
×
2948
                break;
2949

2950
        case SET_XATTR:
×
2951
                r = glob_item(c, i, path_set_xattrs);
×
2952
                if (r < 0)
×
2953
                        return r;
×
2954
                break;
2955

2956
        case RECURSIVE_SET_XATTR:
×
2957
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2958
                if (r < 0)
×
2959
                        return r;
×
2960
                break;
2961

2962
        case SET_ACL:
754✔
2963
                r = glob_item(c, i, path_set_acls);
754✔
2964
                if (r < 0)
754✔
2965
                        return r;
×
2966
                break;
2967

2968
        case RECURSIVE_SET_ACL:
125✔
2969
                r = glob_item_recursively(c, i, fd_set_acls);
125✔
2970
                if (r < 0)
125✔
2971
                        return r;
×
2972
                break;
2973

2974
        case SET_ATTRIBUTE:
375✔
2975
                r = glob_item(c, i, path_set_attribute);
375✔
2976
                if (r < 0)
375✔
2977
                        return r;
×
2978
                break;
2979

2980
        case RECURSIVE_SET_ATTRIBUTE:
×
2981
                r = glob_item_recursively(c, i, fd_set_attribute);
×
2982
                if (r < 0)
×
2983
                        return r;
×
2984
                break;
2985
        }
2986

2987
        return 0;
2988
}
2989

2990
static int remove_recursive(
501✔
2991
                Context *c,
2992
                Item *i,
2993
                const char *instance,
2994
                bool remove_instance) {
2995

2996
        _cleanup_closedir_ DIR *d = NULL;
501✔
2997
        struct statx sx;
501✔
2998
        bool mountpoint;
501✔
2999
        int r;
501✔
3000

3001
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
501✔
3002
        if (r < 0)
501✔
3003
                return r;
3004
        if (r == 0) {
501✔
3005
                if (remove_instance) {
491✔
3006
                        log_action("Would remove", "Removing", "%s file \"%s\".", instance);
13✔
3007
                        if (!arg_dry_run &&
14✔
3008
                            remove(instance) < 0 &&
5✔
3009
                            errno != ENOENT)
2✔
3010
                                return log_error_errno(errno, "rm %s: %m", instance);
×
3011
                }
3012
                return 0;
491✔
3013
        }
3014

3015
        r = dir_cleanup(c, i, instance, d,
20✔
3016
                        /* self_atime_nsec= */ NSEC_INFINITY,
3017
                        /* self_mtime_nsec= */ NSEC_INFINITY,
3018
                        /* cutoff_nsec= */ NSEC_INFINITY,
3019
                        sx.stx_dev_major, sx.stx_dev_minor,
10✔
3020
                        mountpoint,
3021
                        MAX_DEPTH,
3022
                        /* keep_this_level= */ false,
3023
                        /* age_by_file= */ 0,
3024
                        /* age_by_dir= */ 0);
3025
        if (r < 0)
10✔
3026
                return r;
3027

3028
        if (remove_instance) {
10✔
3029
                log_action("Would remove", "Removing", "%s directory \"%s\".", instance);
11✔
3030
                if (!arg_dry_run) {
9✔
3031
                        r = RET_NERRNO(rmdir(instance));
504✔
3032
                        if (r < 0) {
3✔
3033
                                bool fatal = !IN_SET(r, -ENOENT, -ENOTEMPTY);
3✔
3034
                                log_full_errno(fatal ? LOG_ERR : LOG_DEBUG, r, "Failed to remove %s: %m", instance);
3✔
3035
                                if (fatal)
3✔
3036
                                        return r;
×
3037
                        }
3038
                }
3039
        }
3040
        return 0;
3041
}
3042

3043
static int purge_item_instance(Context *c, Item *i, const char *instance, CreationMode creation) {
10✔
3044
        return remove_recursive(c, i, instance, /* remove_instance= */ true);
10✔
3045
}
3046

3047
static int purge_item(Context *c, Item *i) {
15✔
3048
        assert(i);
15✔
3049

3050
        if (!needs_purge(i->type))
15✔
3051
                return 0;
3052

3053
        if (!i->purge)
15✔
3054
                return 0;
3055

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

3058
        if (needs_glob(i->type))
10✔
3059
                return glob_item(c, i, purge_item_instance);
×
3060

3061
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3062
}
3063

3064
static int remove_item_instance(
16✔
3065
                Context *c,
3066
                Item *i,
3067
                const char *instance,
3068
                CreationMode creation) {
3069

3070
        assert(c);
16✔
3071
        assert(i);
16✔
3072

3073
        switch (i->type) {
16✔
3074

3075
        case REMOVE_PATH:
3076
                log_action("Would remove", "Removing", "%s \"%s\".", instance);
8✔
3077
                if (!arg_dry_run &&
15✔
3078
                    remove(instance) < 0 &&
7✔
3079
                    errno != ENOENT)
×
3080
                        return log_error_errno(errno, "rm %s: %m", instance);
×
3081

3082
                return 0;
3083

3084
        case RECURSIVE_REMOVE_PATH:
8✔
3085
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3086

3087
        default:
×
3088
                assert_not_reached();
×
3089
        }
3090
}
3091

3092
static int remove_item(Context *c, Item *i) {
18,038✔
3093
        assert(c);
18,038✔
3094
        assert(i);
18,038✔
3095

3096
        log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
18,038✔
3097

3098
        switch (i->type) {
18,038✔
3099

3100
        case TRUNCATE_DIRECTORY:
483✔
3101
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
483✔
3102

3103
        case REMOVE_PATH:
738✔
3104
        case RECURSIVE_REMOVE_PATH:
3105
                return glob_item(c, i, remove_item_instance);
738✔
3106

3107
        default:
3108
                return 0;
3109
        }
3110
}
3111

3112
static char *age_by_to_string(AgeBy ab, bool is_dir) {
44✔
3113
        static const char ab_map[] = { 'a', 'b', 'c', 'm' };
44✔
3114
        size_t j = 0;
44✔
3115
        char *ret;
44✔
3116

3117
        ret = new(char, ELEMENTSOF(ab_map) + 1);
44✔
3118
        if (!ret)
44✔
3119
                return NULL;
3120

3121
        for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
220✔
3122
                if (BIT_SET(ab, i))
176✔
3123
                        ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
110✔
3124

3125
        ret[j] = 0;
44✔
3126
        return ret;
44✔
3127
}
3128

3129
static int clean_item_instance(
50✔
3130
                Context *c,
3131
                Item *i,
3132
                const char* instance,
3133
                CreationMode creation) {
3134

3135
        assert(i);
50✔
3136

3137
        if (!i->age_set)
50✔
3138
                return 0;
50✔
3139

3140
        usec_t n = now(CLOCK_REALTIME);
38✔
3141
        if (n < i->age)
38✔
3142
                return 0;
3143

3144
        usec_t cutoff = n - i->age;
38✔
3145

3146
        _cleanup_closedir_ DIR *d = NULL;
50✔
3147
        struct statx sx;
38✔
3148
        bool mountpoint;
38✔
3149
        int r;
38✔
3150

3151
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
38✔
3152
        if (r <= 0)
38✔
3153
                return r;
3154

3155
        if (DEBUG_LOGGING) {
34✔
3156
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
22✔
3157

3158
                ab_f = age_by_to_string(i->age_by_file, false);
22✔
3159
                if (!ab_f)
22✔
3160
                        return log_oom();
×
3161

3162
                ab_d = age_by_to_string(i->age_by_dir, true);
22✔
3163
                if (!ab_d)
22✔
3164
                        return log_oom();
×
3165

3166
                log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
44✔
3167
                          mountpoint ? "mount point" : "directory",
3168
                          instance,
3169
                          FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
3170
                          ab_f, ab_d);
3171
        }
3172

3173
        return dir_cleanup(c, i, instance, d,
34✔
3174
                           statx_timestamp_load_nsec(&sx.stx_atime),
3175
                           statx_timestamp_load_nsec(&sx.stx_mtime),
3176
                           cutoff * NSEC_PER_USEC,
34✔
3177
                           sx.stx_dev_major, sx.stx_dev_minor,
34✔
3178
                           mountpoint,
3179
                           MAX_DEPTH, i->keep_first_level,
34✔
3180
                           i->age_by_file, i->age_by_dir);
3181
}
3182

3183
static int clean_item(Context *c, Item *i) {
50✔
3184
        assert(c);
50✔
3185
        assert(i);
50✔
3186

3187
        log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
50✔
3188

3189
        switch (i->type) {
50✔
3190

3191
        case CREATE_DIRECTORY:
24✔
3192
        case TRUNCATE_DIRECTORY:
3193
        case CREATE_SUBVOLUME:
3194
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3195
        case CREATE_SUBVOLUME_NEW_QUOTA:
3196
        case COPY_FILES:
3197
                clean_item_instance(c, i, i->path, CREATION_EXISTING);
24✔
3198
                return 0;
24✔
3199

3200
        case EMPTY_DIRECTORY:
22✔
3201
        case IGNORE_PATH:
3202
        case IGNORE_DIRECTORY_PATH:
3203
                return glob_item(c, i, clean_item_instance);
22✔
3204

3205
        default:
3206
                return 0;
3207
        }
3208
}
3209

3210
static int process_item(
78,077✔
3211
                Context *c,
3212
                Item *i,
3213
                OperationMask operation) {
3214

3215
        OperationMask todo;
78,077✔
3216
        _cleanup_free_ char *_path = NULL;
78,077✔
3217
        const char *path;
78,077✔
3218
        int r;
78,077✔
3219

3220
        assert(c);
78,077✔
3221
        assert(i);
78,077✔
3222

3223
        todo = operation & ~i->done;
78,077✔
3224
        if (todo == 0) /* Everything already done? */
78,077✔
3225
                return 0;
3226

3227
        i->done |= operation;
41,683✔
3228

3229
        path = i->path;
41,683✔
3230
        if (string_is_glob(path)) {
41,683✔
3231
                /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3232
                 * for the non-glob part. */
3233

3234
                r = glob_non_glob_prefix(path, &_path);
3,656✔
3235
                if (r < 0 && r != -ENOENT)
3,656✔
3236
                        return log_debug_errno(r, "Failed to deglob path: %m");
×
3237
                if (r >= 0)
3,656✔
3238
                        path = _path;
3,656✔
3239
        }
3240

3241
        r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
41,683✔
3242
        if (r == -EREMOTE) {
41,683✔
3243
                log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
×
3244
                return 0;
×
3245
        }
3246
        if (r < 0)
41,683✔
3247
                log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
×
3248

3249
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
41,683✔
3250
        /* Failure can only be tolerated for create */
3251
        if (i->allow_failure)
41,683✔
3252
                r = 0;
980✔
3253

3254
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
41,683✔
3255
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
41,683✔
3256
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
41,683✔
3257

3258
        return r;
3259
}
3260

3261
static int process_item_array(
71,824✔
3262
                Context *c,
3263
                ItemArray *array,
3264
                OperationMask operation) {
3265

3266
        int r = 0;
71,824✔
3267

3268
        assert(c);
71,824✔
3269
        assert(array);
71,824✔
3270

3271
        /* Create any parent first. */
3272
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
71,824✔
3273
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
17,205✔
3274

3275
        /* Clean up all children first */
3276
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
71,824✔
3277
                ItemArray *cc;
6,507✔
3278

3279
                SET_FOREACH(cc, array->children)
22,019✔
3280
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
15,512✔
3281
        }
3282

3283
        FOREACH_ARRAY(item, array->items, array->n_items)
149,901✔
3284
                RET_GATHER(r, process_item(c, item, operation));
78,077✔
3285

3286
        return r;
71,824✔
3287
}
3288

3289
static void item_free_contents(Item *i) {
88,354✔
3290
        assert(i);
88,354✔
3291
        free(i->path);
88,354✔
3292
        free(i->argument);
88,354✔
3293
        free(i->binary_argument);
88,354✔
3294
        strv_free(i->xattrs);
88,354✔
3295

3296
#if HAVE_ACL
3297
        if (i->acl_access)
88,354✔
3298
                acl_free(i->acl_access);
1,460✔
3299

3300
        if (i->acl_access_exec)
88,354✔
3301
                acl_free(i->acl_access_exec);
369✔
3302

3303
        if (i->acl_default)
88,354✔
3304
                acl_free(i->acl_default);
2,190✔
3305
#endif
3306
}
88,354✔
3307

3308
static ItemArray* item_array_free(ItemArray *a) {
22,288✔
3309
        if (!a)
22,288✔
3310
                return NULL;
3311

3312
        FOREACH_ARRAY(item, a->items, a->n_items)
45,952✔
3313
                item_free_contents(item);
23,664✔
3314

3315
        set_free(a->children);
22,288✔
3316
        free(a->items);
22,288✔
3317
        return mfree(a);
22,288✔
3318
}
3319

3320
static int item_compare(const Item *a, const Item *b) {
1,886✔
3321
        /* Make sure that the ownership taking item is put first, so
3322
         * that we first create the node, and then can adjust it */
3323

3324
        if (takes_ownership(a->type) && !takes_ownership(b->type))
1,886✔
3325
                return -1;
3326
        if (!takes_ownership(a->type) && takes_ownership(b->type))
1,886✔
3327
                return 1;
3328

3329
        return CMP(a->type, b->type);
1,886✔
3330
}
3331

3332
static bool item_compatible(const Item *a, const Item *b) {
1,637✔
3333
        assert(a);
1,637✔
3334
        assert(b);
1,637✔
3335
        assert(streq(a->path, b->path));
1,637✔
3336

3337
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,637✔
3338
                /* check if the items are the same */
3339
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
512✔
3340
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
493✔
3341

3342
                        a->uid_set == b->uid_set &&
493✔
3343
                        a->uid == b->uid &&
493✔
3344
                        a->uid_only_create == b->uid_only_create &&
493✔
3345

3346
                        a->gid_set == b->gid_set &&
493✔
3347
                        a->gid == b->gid &&
493✔
3348
                        a->gid_only_create == b->gid_only_create &&
493✔
3349

3350
                        a->mode_set == b->mode_set &&
493✔
3351
                        a->mode == b->mode &&
493✔
3352
                        a->mode_only_create == b->mode_only_create &&
493✔
3353

3354
                        a->age_set == b->age_set &&
493✔
3355
                        a->age == b->age &&
493✔
3356

3357
                        a->age_by_file == b->age_by_file &&
493✔
3358
                        a->age_by_dir == b->age_by_dir &&
493✔
3359

3360
                        a->mask_perms == b->mask_perms &&
493✔
3361

3362
                        a->keep_first_level == b->keep_first_level &&
1,517✔
3363

3364
                        a->major_minor == b->major_minor;
493✔
3365

3366
        return true;
3367
}
3368

3369
static bool should_include_path(const char *path) {
64,599✔
3370
        STRV_FOREACH(prefix, arg_exclude_prefixes)
83,440✔
3371
                if (path_startswith(path, *prefix)) {
21,201✔
3372
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,360✔
3373
                                  path, *prefix);
3374
                        return false;
2,360✔
3375
                }
3376

3377
        STRV_FOREACH(prefix, arg_include_prefixes)
99,921✔
3378
                if (path_startswith(path, *prefix)) {
42,402✔
3379
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
4,720✔
3380
                        return true;
4,720✔
3381
                }
3382

3383
        /* no matches, so we should include this path only if we have no allow list at all */
3384
        if (strv_isempty(arg_include_prefixes))
57,519✔
3385
                return true;
3386

3387
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
37,682✔
3388
        return false;
3389
}
3390

3391
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
24,557✔
3392
        int r;
24,557✔
3393

3394
        assert(i);
24,557✔
3395

3396
        if (!i->argument)
24,557✔
3397
                return 0;
3398

3399
        switch (i->type) {
6,242✔
3400
        case COPY_FILES:
3,063✔
3401
        case CREATE_SYMLINK:
3402
        case CREATE_FILE:
3403
        case TRUNCATE_FILE:
3404
        case WRITE_FILE: {
3405
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
3,063✔
3406
                ssize_t l;
3,063✔
3407

3408
                l = cunescape(i->argument, 0, &unescaped);
3,063✔
3409
                if (l < 0)
3,063✔
3410
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3411

3412
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
3,063✔
3413
                if (r < 0)
3,063✔
3414
                        return r;
3415

3416
                return free_and_replace(i->argument, resolved);
3,063✔
3417
        }
3418
        case SET_XATTR:
×
3419
        case RECURSIVE_SET_XATTR:
3420
                STRV_FOREACH(xattr, i->xattrs) {
×
3421
                        _cleanup_free_ char *resolved = NULL;
×
3422

3423
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3424
                        if (r < 0)
×
3425
                                return r;
×
3426

3427
                        free_and_replace(*xattr, resolved);
×
3428
                }
3429
                return 0;
3430

3431
        default:
3432
                return 0;
3433
        }
3434
}
3435

3436
static int patch_var_run(const char *fname, unsigned line, char **path) {
64,600✔
3437
        const char *k;
64,600✔
3438
        char *n;
64,600✔
3439

3440
        assert(path);
64,600✔
3441
        assert(*path);
64,600✔
3442

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

3454
        k = path_startswith(*path, "/var/run/");
64,600✔
3455
        if (isempty(k)) /* Don't complain about paths other than under /var/run,
64,600✔
3456
                         * and not about /var/run itself either. */
3457
                return 0;
64,600✔
3458

3459
        n = path_join("/run", k);
×
3460
        if (!n)
×
3461
                return log_oom();
×
3462

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

3471
        free_and_replace(*path, n);
×
3472

3473
        return 0;
×
3474
}
3475

3476
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
8,769✔
3477
        int r;
8,769✔
3478

3479
        assert(user);
8,769✔
3480
        assert(ret_uid);
8,769✔
3481

3482
        /* First: parse as numeric UID string */
3483
        r = parse_uid(user, ret_uid);
8,769✔
3484
        if (r >= 0)
8,769✔
3485
                return r;
3486

3487
        /* Second: pass to NSS if we are running "online" */
3488
        if (!arg_root)
8,755✔
3489
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
8,755✔
3490

3491
        /* Third, synthesize "root" unconditionally */
3492
        if (streq(user, "root")) {
×
3493
                *ret_uid = 0;
×
3494
                return 0;
×
3495
        }
3496

3497
        /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3498
        return name_to_uid_offline(arg_root, user, ret_uid, cache);
×
3499
}
3500

3501
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
10,239✔
3502
        int r;
10,239✔
3503

3504
        assert(group);
10,239✔
3505
        assert(ret_gid);
10,239✔
3506

3507
        /* First: parse as numeric GID string */
3508
        r = parse_gid(group, ret_gid);
10,239✔
3509
        if (r >= 0)
10,239✔
3510
                return r;
3511

3512
        /* Second: pass to NSS if we are running "online" */
3513
        if (!arg_root)
10,225✔
3514
                return get_group_creds(&group, ret_gid, 0);
10,225✔
3515

3516
        /* Third, synthesize "root" unconditionally */
3517
        if (streq(group, "root")) {
×
3518
                *ret_gid = 0;
×
3519
                return 0;
×
3520
        }
3521

3522
        /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3523
        return name_to_gid_offline(arg_root, group, ret_gid, cache);
×
3524
}
3525

3526
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
153✔
3527
        AgeBy ab_f = 0, ab_d = 0;
153✔
3528

3529
        static const struct {
153✔
3530
                char age_by_chr;
3531
                AgeBy age_by_flag;
3532
        } age_by_types[] = {
3533
                { 'a', AGE_BY_ATIME },
3534
                { 'b', AGE_BY_BTIME },
3535
                { 'c', AGE_BY_CTIME },
3536
                { 'm', AGE_BY_MTIME },
3537
        };
3538

3539
        assert(age_by_str);
153✔
3540
        assert(item);
153✔
3541

3542
        if (isempty(age_by_str))
153✔
3543
                return -EINVAL;
3544

3545
        for (const char *s = age_by_str; *s != 0; s++) {
325✔
3546
                size_t i;
178✔
3547

3548
                /* Ignore whitespace. */
3549
                if (strchr(WHITESPACE, *s))
178✔
3550
                        continue;
11✔
3551

3552
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
229✔
3553
                        /* Check lower-case for files, upper-case for directories. */
3554
                        if (*s == age_by_types[i].age_by_chr) {
226✔
3555
                                ab_f |= age_by_types[i].age_by_flag;
154✔
3556
                                break;
154✔
3557
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3558
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3559
                                break;
10✔
3560
                        }
3561
                }
3562

3563
                /* Invalid character. */
3564
                if (i >= ELEMENTSOF(age_by_types))
3565
                        return -EINVAL;
3566
        }
3567

3568
        /* No match. */
3569
        if (ab_f == 0 && ab_d == 0)
147✔
3570
                return -EINVAL;
3571

3572
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
146✔
3573
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
146✔
3574

3575
        return 0;
146✔
3576
}
3577

3578
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
1,379✔
3579
        assert(existing);
1,379✔
3580
        assert(i);
1,379✔
3581

3582
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
3,013✔
3583
                if (item_compatible(e, i))
1,637✔
3584
                        continue;
1,618✔
3585

3586
                /* Only multiple 'w+' lines for the same path are allowed. */
3587
                if (e->type != WRITE_FILE || !e->append_or_force ||
19✔
3588
                    i->type != WRITE_FILE || !i->append_or_force)
16✔
3589
                        return true;
3590
        }
3591

3592
        return false;
3593
}
3594

3595
static int parse_line(
64,690✔
3596
                const char *fname,
3597
                unsigned line,
3598
                const char *buffer,
3599
                bool *invalid_config,
3600
                void *context) {
3601

3602
        Context *c = ASSERT_PTR(context);
64,690✔
3603
        _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
64,690✔
3604
        _cleanup_(item_free_contents) Item i = {
×
3605
                /* The "age-by" argument considers all file timestamp types by default. */
3606
                .age_by_file = AGE_BY_DEFAULT_FILE,
3607
                .age_by_dir = AGE_BY_DEFAULT_DIR,
3608
        };
3609
        ItemArray *existing;
64,690✔
3610
        OrderedHashmap *h;
64,690✔
3611
        bool append_or_force = false, boot = false, allow_failure = false, try_replace = false,
64,690✔
3612
                unbase64 = false, from_cred = false, missing_user_or_group = false, purge = false,
64,690✔
3613
                ignore_if_target_missing = false;
64,690✔
3614
        int r;
64,690✔
3615

3616
        assert(fname);
64,690✔
3617
        assert(line >= 1);
64,690✔
3618
        assert(buffer);
64,690✔
3619

3620
        const Specifier specifier_table[] = {
64,690✔
3621
                { 'h', specifier_user_home,       NULL },
3622

3623
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3624
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3625
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3626
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3627

3628
                COMMON_SYSTEM_SPECIFIERS,
3629
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
64,690✔
3630
                COMMON_TMP_SPECIFIERS,
3631
                {}
3632
        };
3633

3634
        r = extract_many_words(
64,690✔
3635
                        &buffer,
3636
                        NULL,
3637
                        EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE,
3638
                        &action,
3639
                        &path,
3640
                        &mode,
3641
                        &user,
3642
                        &group,
3643
                        &age);
3644
        if (r < 0) {
64,690✔
3645
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3646
                        /* invalid quoting and such or an unknown specifier */
3647
                        *invalid_config = true;
×
3648
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
×
3649
        } else if (r < 2) {
64,690✔
3650
                *invalid_config = true;
×
3651
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
×
3652
        }
3653

3654
        if (!empty_or_dash(buffer)) {
64,690✔
3655
                i.argument = strdup(buffer);
15,374✔
3656
                if (!i.argument)
15,374✔
3657
                        return log_oom();
×
3658
        }
3659

3660
        if (isempty(action)) {
64,690✔
3661
                *invalid_config = true;
×
3662
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3663
                                  "Command too short '%s'.", action);
3664
        }
3665

3666
        for (int pos = 1; action[pos]; pos++)
85,128✔
3667
                if (action[pos] == '!' && !boot)
20,438✔
3668
                        boot = true;
3669
                else if (action[pos] == '+' && !append_or_force)
10,988✔
3670
                        append_or_force = true;
3671
                else if (action[pos] == '-' && !allow_failure)
7,314✔
3672
                        allow_failure = true;
3673
                else if (action[pos] == '=' && !try_replace)
5,854✔
3674
                        try_replace = true;
3675
                else if (action[pos] == '~' && !unbase64)
5,854✔
3676
                        unbase64 = true;
3677
                else if (action[pos] == '^' && !from_cred)
5,854✔
3678
                        from_cred = true;
3679
                else if (action[pos] == '$' && !purge)
4,394✔
3680
                        purge = true;
3681
                else if (action[pos] == '?' && !ignore_if_target_missing)
2✔
3682
                        ignore_if_target_missing = true;
3683
                else {
3684
                        *invalid_config = true;
×
3685
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3686
                                          "Unknown modifiers in command: %s", action);
3687
                }
3688

3689
        if (boot && !arg_boot) {
64,690✔
3690
                log_syntax(NULL, LOG_DEBUG, fname, line, 0,
90✔
3691
                           "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3692
                return 0;
90✔
3693
        }
3694

3695
        i.type = action[0];
64,600✔
3696
        i.append_or_force = append_or_force;
64,600✔
3697
        i.allow_failure = allow_failure;
64,600✔
3698
        i.try_replace = try_replace;
64,600✔
3699
        i.purge = purge;
64,600✔
3700
        i.ignore_if_target_missing = ignore_if_target_missing;
64,600✔
3701

3702
        r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
64,600✔
3703
        if (ERRNO_IS_NEG_NOINFO(r))
64,600✔
3704
                return log_unresolvable_specifier(fname, line);
×
3705
        if (r < 0) {
64,600✔
3706
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3707
                        *invalid_config = true;
×
3708
                return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3709
                                  "Failed to replace specifiers in '%s': %m", path);
3710
        }
3711

3712
        r = patch_var_run(fname, line, &i.path);
64,600✔
3713
        if (r < 0)
64,600✔
3714
                return r;
3715

3716
        if (!path_is_absolute(i.path)) {
64,600✔
3717
                *invalid_config = true;
×
3718
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3719
                                  "Path '%s' not absolute.", i.path);
3720
        }
3721

3722
        path_simplify(i.path);
64,600✔
3723

3724
        switch (i.type) {
64,600✔
3725

3726
        case CREATE_DIRECTORY:
36,825✔
3727
        case CREATE_SUBVOLUME:
3728
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3729
        case CREATE_SUBVOLUME_NEW_QUOTA:
3730
        case EMPTY_DIRECTORY:
3731
        case TRUNCATE_DIRECTORY:
3732
        case CREATE_FIFO:
3733
        case IGNORE_PATH:
3734
        case IGNORE_DIRECTORY_PATH:
3735
        case REMOVE_PATH:
3736
        case RECURSIVE_REMOVE_PATH:
3737
        case ADJUST_MODE:
3738
        case RELABEL_PATH:
3739
        case RECURSIVE_RELABEL_PATH:
3740
                if (i.argument)
36,825✔
3741
                        log_syntax(NULL, LOG_WARNING, fname, line, 0,
1✔
3742
                                   "%c lines don't take argument fields, ignoring.", (char) i.type);
3743
                break;
3744

3745
        case CREATE_FILE:
3746
        case TRUNCATE_FILE:
3747
                break;
3748

3749
        case CREATE_SYMLINK:
4,389✔
3750
                if (unbase64) {
4,389✔
3751
                        *invalid_config = true;
×
3752
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3753
                                          "base64 decoding not supported for symlink targets.");
3754
                }
3755
                break;
3756

3757
        case WRITE_FILE:
21✔
3758
                if (!i.argument) {
21✔
3759
                        *invalid_config = true;
1✔
3760
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1✔
3761
                                          "Write file requires argument.");
3762
                }
3763
                break;
3764

3765
        case COPY_FILES:
12,760✔
3766
                if (unbase64) {
12,760✔
3767
                        *invalid_config = true;
×
3768
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3769
                                          "base64 decoding not supported for copy sources.");
3770
                }
3771
                break;
3772

3773
        case CREATE_CHAR_DEVICE:
2,884✔
3774
        case CREATE_BLOCK_DEVICE:
3775
                if (unbase64) {
2,884✔
3776
                        *invalid_config = true;
×
3777
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3778
                                          "base64 decoding not supported for device node creation.");
3779
                }
3780

3781
                if (!i.argument) {
2,884✔
3782
                        *invalid_config = true;
×
3783
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3784
                                          "Device file requires argument.");
3785
                }
3786

3787
                r = parse_devnum(i.argument, &i.major_minor);
2,884✔
3788
                if (r < 0) {
2,884✔
3789
                        *invalid_config = true;
×
3790
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3791
                                          "Can't parse device file major/minor '%s'.", i.argument);
3792
                }
3793

3794
                break;
3795

3796
        case SET_XATTR:
×
3797
        case RECURSIVE_SET_XATTR:
3798
                if (unbase64) {
×
3799
                        *invalid_config = true;
×
3800
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3801
                                          "base64 decoding not supported for extended attributes.");
3802
                }
3803
                if (!i.argument) {
×
3804
                        *invalid_config = true;
×
3805
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3806
                                          "Set extended attribute requires argument.");
3807
                }
3808
                r = parse_xattrs_from_arg(&i);
×
3809
                if (r < 0)
×
3810
                        return r;
3811
                break;
3812

3813
        case SET_ACL:
2,559✔
3814
        case RECURSIVE_SET_ACL:
3815
                if (unbase64) {
2,559✔
3816
                        *invalid_config = true;
×
3817
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3818
                                          "base64 decoding not supported for ACLs.");
3819
                }
3820
                if (!i.argument) {
2,559✔
3821
                        *invalid_config = true;
×
3822
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3823
                                          "Set ACLs requires argument.");
3824
                }
3825
                r = parse_acls_from_arg(&i);
2,559✔
3826
                if (r < 0)
2,559✔
3827
                        return r;
3828
                break;
3829

3830
        case SET_ATTRIBUTE:
1,095✔
3831
        case RECURSIVE_SET_ATTRIBUTE:
3832
                if (unbase64) {
1,095✔
3833
                        *invalid_config = true;
×
3834
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3835
                                          "base64 decoding not supported for file attributes.");
3836
                }
3837
                if (!i.argument) {
1,095✔
3838
                        *invalid_config = true;
×
3839
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3840
                                          "Set file attribute requires argument.");
3841
                }
3842
                r = parse_attribute_from_arg(&i);
1,095✔
3843
                if (IN_SET(r, -EINVAL, -EBADSLT))
1,095✔
3844
                        *invalid_config = true;
×
3845
                if (r < 0)
1,095✔
3846
                        return r;
3847
                break;
3848

3849
        default:
×
3850
                *invalid_config = true;
×
3851
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3852
                                  "Unknown command type '%c'.", (char) i.type);
3853
        }
3854

3855
        if (i.purge && !needs_purge(i.type)) {
64,599✔
3856
                *invalid_config = true;
×
3857
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3858
                                  "Purge flag '$' combined with line type '%c' which does not support purging.", (char) i.type);
3859
        }
3860

3861
        if (i.ignore_if_target_missing && !supports_ignore_if_target_missing(i.type)) {
64,599✔
3862
                *invalid_config = true;
×
3863
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3864
                                  "Modifier '?' combined with line type '%c' which does not support this modifier.", (char) i.type);
3865
        }
3866

3867
        if (!should_include_path(i.path))
64,599✔
3868
                return 0;
3869

3870
        if (!unbase64) {
24,557✔
3871
                /* Do specifier expansion except if base64 mode is enabled */
3872
                r = specifier_expansion_from_arg(specifier_table, &i);
24,557✔
3873
                if (ERRNO_IS_NEG_NOINFO(r))
24,557✔
3874
                        return log_unresolvable_specifier(fname, line);
×
3875
                if (r < 0) {
24,557✔
3876
                        if (IN_SET(r, -EINVAL, -EBADSLT))
×
3877
                                *invalid_config = true;
×
3878
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3879
                                          "Failed to substitute specifiers in argument: %m");
3880
                }
3881
        }
3882

3883
        switch (i.type) {
24,557✔
3884
        case CREATE_SYMLINK:
1,509✔
3885
                if (!i.argument) {
1,509✔
3886
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3887
                        if (!i.argument)
2✔
3888
                                return log_oom();
×
3889
                }
3890

3891
                break;
3892

3893
        case COPY_FILES:
4,360✔
3894
                if (!i.argument) {
4,360✔
3895
                        i.argument = path_join("/usr/share/factory", i.path);
3,476✔
3896
                        if (!i.argument)
3,476✔
3897
                                return log_oom();
×
3898
                } else if (!path_is_absolute(i.argument)) {
884✔
3899
                        *invalid_config = true;
×
3900
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3901
                                          "Source path '%s' is not absolute.", i.argument);
3902

3903
                }
3904

3905
                if (!empty_or_root(arg_root)) {
4,360✔
3906
                        char *p;
1✔
3907

3908
                        p = path_join(arg_root, i.argument);
1✔
3909
                        if (!p)
1✔
3910
                                return log_oom();
×
3911
                        free_and_replace(i.argument, p);
1✔
3912
                }
3913

3914
                path_simplify(i.argument);
4,360✔
3915

3916
                if (access_nofollow(i.argument, F_OK) == -ENOENT) {
4,360✔
3917
                        /* Silently skip over lines where the source file is missing. */
3918
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
501✔
3919
                                   "Copy source path '%s' does not exist, skipping line.", i.argument);
3920
                        return 0;
501✔
3921
                }
3922

3923
                break;
3924

3925
        default:
24,056✔
3926
                ;
24,056✔
3927
        }
3928

3929
        if (from_cred) {
24,056✔
3930
                if (!i.argument)
500✔
3931
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3932
                                          "Reading from credential requested, but no credential name specified.");
3933
                if (!credential_name_valid(i.argument))
500✔
3934
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3935
                                          "Credential name not valid: %s", i.argument);
3936

3937
                r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
500✔
3938
                if (IN_SET(r, -ENXIO, -ENOENT)) {
500✔
3939
                        /* Silently skip over lines that have no credentials passed */
3940
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
380✔
3941
                                   "Credential '%s' not specified, skipping line.", i.argument);
3942
                        return 0;
380✔
3943
                }
3944
                if (r < 0)
120✔
3945
                        return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
×
3946
        }
3947

3948
        /* If base64 decoding is requested, do so now */
3949
        if (unbase64 && item_binary_argument(&i)) {
23,676✔
3950
                _cleanup_free_ void *data = NULL;
×
3951
                size_t data_size = 0;
×
3952

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

3958
                free_and_replace(i.binary_argument, data);
×
3959
                i.binary_argument_size = data_size;
×
3960
        }
3961

3962
        if (!empty_or_root(arg_root)) {
23,676✔
3963
                char *p;
14✔
3964

3965
                p = path_join(arg_root, i.path);
14✔
3966
                if (!p)
14✔
3967
                        return log_oom();
64,690✔
3968
                free_and_replace(i.path, p);
14✔
3969
        }
3970

3971
        if (!empty_or_dash(user)) {
23,676✔
3972
                const char *u;
8,769✔
3973

3974
                u = startswith(user, ":");
8,769✔
3975
                if (u)
8,769✔
3976
                        i.uid_only_create = true;
4✔
3977
                else
3978
                        u = user;
3979

3980
                r = find_uid(u, &i.uid, &c->uid_cache);
8,769✔
3981
                if (r == -ESRCH && arg_graceful) {
8,769✔
3982
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3983
                                   "%s: user '%s' not found, not adjusting ownership.", i.path, u);
3984
                        missing_user_or_group = true;
3985
                } else if (r < 0) {
8,769✔
3986
                        *invalid_config = true;
×
3987
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", u);
×
3988
                } else
3989
                        i.uid_set = true;
8,769✔
3990
        }
3991

3992
        if (!empty_or_dash(group)) {
23,676✔
3993
                const char *g;
10,239✔
3994

3995
                g = startswith(group, ":");
10,239✔
3996
                if (g)
10,239✔
3997
                        i.gid_only_create = true;
374✔
3998
                else
3999
                        g = group;
4000

4001
                r = find_gid(g, &i.gid, &c->gid_cache);
10,239✔
4002
                if (r == -ESRCH && arg_graceful) {
10,239✔
4003
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
4004
                                   "%s: group '%s' not found, not adjusting ownership.", i.path, g);
4005
                        missing_user_or_group = true;
4006
                } else if (r < 0) {
10,239✔
4007
                        *invalid_config = true;
×
4008
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s': %m", g);
×
4009
                } else
4010
                        i.gid_set = true;
10,239✔
4011
        }
4012

4013
        if (!empty_or_dash(mode)) {
23,676✔
4014
                const char *mm;
4015
                unsigned m;
4016

4017
                for (mm = mode;; mm++)
499✔
4018
                        if (*mm == '~')
15,564✔
4019
                                i.mask_perms = true;
125✔
4020
                        else if (*mm == ':')
15,439✔
4021
                                i.mode_only_create = true;
374✔
4022
                        else
4023
                                break;
4024

4025
                r = parse_mode(mm, &m);
15,065✔
4026
                if (r < 0) {
15,065✔
4027
                        *invalid_config = true;
×
4028
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
×
4029
                }
4030

4031
                i.mode = m;
15,065✔
4032
                i.mode_set = true;
15,065✔
4033
        } else
4034
                i.mode = IN_SET(i.type,
8,611✔
4035
                                CREATE_DIRECTORY,
4036
                                TRUNCATE_DIRECTORY,
4037
                                CREATE_SUBVOLUME,
4038
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4039
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4040

4041
        if (missing_user_or_group && (i.mode & ~0777) != 0) {
23,676✔
4042
                /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
4043
                mode_t adjusted = i.mode & 0777;
×
4044
                log_syntax(NULL, LOG_INFO, fname, line, 0,
×
4045
                           "Changing mode 0%o to 0%o because of changed ownership.", i.mode, adjusted);
4046
                i.mode = adjusted;
×
4047
        }
4048

4049
        if (!empty_or_dash(age)) {
23,676✔
4050
                const char *a = age;
1,270✔
4051
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,270✔
4052

4053
                if (*a == '~') {
1,270✔
4054
                        i.keep_first_level = true;
×
4055
                        a++;
×
4056
                }
4057

4058
                /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
4059
                r = split_pair(a, ":", &age_by, &seconds);
1,270✔
4060
                if (r == -ENOMEM)
1,270✔
4061
                        return log_oom();
×
4062
                if (r < 0 && r != -EINVAL)
1,270✔
4063
                        return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
×
4064
                if (r >= 0) {
1,270✔
4065
                        /* We found a ":", parse the "age-by" part. */
4066
                        r = parse_age_by_from_arg(age_by, &i);
153✔
4067
                        if (r == -ENOMEM)
153✔
4068
                                return log_oom();
×
4069
                        if (r < 0) {
153✔
4070
                                *invalid_config = true;
7✔
4071
                                return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
7✔
4072
                        }
4073

4074
                        /* For parsing the "age" part, after the ":". */
4075
                        a = seconds;
146✔
4076
                }
4077

4078
                r = parse_sec(a, &i.age);
1,263✔
4079
                if (r < 0) {
1,263✔
4080
                        *invalid_config = true;
2✔
4081
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
2✔
4082
                }
4083

4084
                i.age_set = true;
1,261✔
4085
        }
4086

4087
        h = needs_glob(i.type) ? c->globs : c->items;
23,667✔
4088

4089
        existing = ordered_hashmap_get(h, i.path);
23,667✔
4090
        if (existing) {
23,667✔
4091
                if (is_duplicated_item(existing, &i)) {
1,379✔
4092
                        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3✔
4093
                                   "Duplicate line for path \"%s\", ignoring.", i.path);
4094
                        return 0;
3✔
4095
                }
4096
        } else {
4097
                existing = new0(ItemArray, 1);
22,288✔
4098
                if (!existing)
22,288✔
4099
                        return log_oom();
×
4100

4101
                r = ordered_hashmap_put(h, i.path, existing);
22,288✔
4102
                if (r < 0) {
22,288✔
4103
                        free(existing);
×
4104
                        return log_oom();
×
4105
                }
4106
        }
4107

4108
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
23,664✔
4109
                return log_oom();
×
4110

4111
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
23,664✔
4112

4113
        /* Sort item array, to enforce stable ordering of application */
4114
        typesafe_qsort(existing->items, existing->n_items, item_compare);
23,664✔
4115

4116
        return 0;
4117
}
4118

4119
static int cat_config(char **config_dirs, char **args) {
×
4120
        _cleanup_strv_free_ char **files = NULL;
×
4121
        int r;
×
4122

4123
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4124
        if (r < 0)
×
4125
                return r;
4126

4127
        pager_open(arg_pager_flags);
×
4128

4129
        return cat_files(NULL, files, arg_cat_flags);
×
4130
}
4131

4132
static int exclude_default_prefixes(void) {
×
4133
        int r;
×
4134

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

4140
        r = strv_extend_many(
×
4141
                        &arg_exclude_prefixes,
4142
                        "/dev",
4143
                        "/proc",
4144
                        "/run",
4145
                        "/sys");
4146
        if (r < 0)
×
4147
                return log_oom();
×
4148

4149
        strv_uniq(arg_exclude_prefixes);
×
4150
        return 0;
×
4151
}
4152

4153
static int help(void) {
×
4154
        _cleanup_free_ char *link = NULL;
×
4155
        int r;
×
4156

4157
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4158
        if (r < 0)
×
4159
                return log_oom();
×
4160

4161
        printf("%1$s COMMAND [OPTIONS...] [CONFIGURATION FILE...]\n"
×
4162
               "\n%2$sCreate, delete, and clean up files and directories.%4$s\n"
4163
               "\n%3$sCommands:%4$s\n"
4164
               "     --create               Create and adjust files and directories\n"
4165
               "     --clean                Clean up files and directories\n"
4166
               "     --remove               Remove files and directories marked for removal\n"
4167
               "     --purge                Delete files and directories marked for creation in\n"
4168
               "                            specified configuration files (careful!)\n"
4169
               "     --cat-config           Show configuration files\n"
4170
               "     --tldr                 Show non-comment parts of configuration files\n"
4171
               "  -h --help                 Show this help\n"
4172
               "     --version              Show package version\n"
4173
               "\n%3$sOptions:%4$s\n"
4174
               "     --user                 Execute user configuration\n"
4175
               "     --boot                 Execute actions only safe at boot\n"
4176
               "     --graceful             Quietly ignore unknown users or groups\n"
4177
               "     --prefix=PATH          Only apply rules with the specified prefix\n"
4178
               "     --exclude-prefix=PATH  Ignore rules with the specified prefix\n"
4179
               "  -E                        Ignore rules prefixed with /dev, /proc, /run, /sys\n"
4180
               "     --root=PATH            Operate on an alternate filesystem root\n"
4181
               "     --image=PATH           Operate on disk image as filesystem root\n"
4182
               "     --image-policy=POLICY  Specify disk image dissection policy\n"
4183
               "     --replace=PATH         Treat arguments as replacement for PATH\n"
4184
               "     --dry-run              Just print what would be done\n"
4185
               "     --no-pager             Do not pipe output into a pager\n"
4186
               "\nSee the %5$s for details.\n",
4187
               program_invocation_short_name,
4188
               ansi_highlight(),
4189
               ansi_underline(),
4190
               ansi_normal(),
4191
               link);
4192

4193
        return 0;
4194
}
4195

4196
static int parse_argv(int argc, char *argv[]) {
689✔
4197
        enum {
689✔
4198
                ARG_VERSION = 0x100,
4199
                ARG_CAT_CONFIG,
4200
                ARG_TLDR,
4201
                ARG_USER,
4202
                ARG_CREATE,
4203
                ARG_CLEAN,
4204
                ARG_REMOVE,
4205
                ARG_PURGE,
4206
                ARG_BOOT,
4207
                ARG_GRACEFUL,
4208
                ARG_PREFIX,
4209
                ARG_EXCLUDE_PREFIX,
4210
                ARG_ROOT,
4211
                ARG_IMAGE,
4212
                ARG_IMAGE_POLICY,
4213
                ARG_REPLACE,
4214
                ARG_DRY_RUN,
4215
                ARG_NO_PAGER,
4216
        };
4217

4218
        static const struct option options[] = {
689✔
4219
                { "help",           no_argument,         NULL, 'h'                },
4220
                { "user",           no_argument,         NULL, ARG_USER           },
4221
                { "version",        no_argument,         NULL, ARG_VERSION        },
4222
                { "cat-config",     no_argument,         NULL, ARG_CAT_CONFIG     },
4223
                { "tldr",           no_argument,         NULL, ARG_TLDR           },
4224
                { "create",         no_argument,         NULL, ARG_CREATE         },
4225
                { "clean",          no_argument,         NULL, ARG_CLEAN          },
4226
                { "remove",         no_argument,         NULL, ARG_REMOVE         },
4227
                { "purge",          no_argument,         NULL, ARG_PURGE          },
4228
                { "boot",           no_argument,         NULL, ARG_BOOT           },
4229
                { "graceful",       no_argument,         NULL, ARG_GRACEFUL       },
4230
                { "prefix",         required_argument,   NULL, ARG_PREFIX         },
4231
                { "exclude-prefix", required_argument,   NULL, ARG_EXCLUDE_PREFIX },
4232
                { "root",           required_argument,   NULL, ARG_ROOT           },
4233
                { "image",          required_argument,   NULL, ARG_IMAGE          },
4234
                { "image-policy",   required_argument,   NULL, ARG_IMAGE_POLICY   },
4235
                { "replace",        required_argument,   NULL, ARG_REPLACE        },
4236
                { "dry-run",        no_argument,         NULL, ARG_DRY_RUN        },
4237
                { "no-pager",       no_argument,         NULL, ARG_NO_PAGER       },
4238
                {}
4239
        };
4240

4241
        int c, r;
689✔
4242

4243
        assert(argc >= 0);
689✔
4244
        assert(argv);
689✔
4245

4246
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
2,931✔
4247

4248
                switch (c) {
2,242✔
4249

4250
                case 'h':
×
4251
                        return help();
×
4252

4253
                case ARG_VERSION:
×
4254
                        return version();
×
4255

4256
                case ARG_CAT_CONFIG:
×
4257
                        arg_cat_flags = CAT_CONFIG_ON;
×
4258
                        break;
×
4259

4260
                case ARG_TLDR:
×
4261
                        arg_cat_flags = CAT_TLDR;
×
4262
                        break;
×
4263

4264
                case ARG_USER:
186✔
4265
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
186✔
4266
                        break;
186✔
4267

4268
                case ARG_CREATE:
638✔
4269
                        arg_operation |= OPERATION_CREATE;
638✔
4270
                        break;
638✔
4271

4272
                case ARG_CLEAN:
38✔
4273
                        arg_operation |= OPERATION_CLEAN;
38✔
4274
                        break;
38✔
4275

4276
                case ARG_REMOVE:
316✔
4277
                        arg_operation |= OPERATION_REMOVE;
316✔
4278
                        break;
316✔
4279

4280
                case ARG_BOOT:
542✔
4281
                        arg_boot = true;
542✔
4282
                        break;
542✔
4283

4284
                case ARG_PURGE:
5✔
4285
                        arg_operation |= OPERATION_PURGE;
5✔
4286
                        break;
5✔
4287

4288
                case ARG_GRACEFUL:
120✔
4289
                        arg_graceful = true;
120✔
4290
                        break;
120✔
4291

4292
                case ARG_PREFIX:
240✔
4293
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
240✔
4294
                                return log_oom();
×
4295
                        break;
4296

4297
                case ARG_EXCLUDE_PREFIX:
120✔
4298
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
120✔
4299
                                return log_oom();
×
4300
                        break;
4301

4302
                case ARG_ROOT:
8✔
4303
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
8✔
4304
                        if (r < 0)
8✔
4305
                                return r;
4306
                        break;
4307

4308
                case ARG_IMAGE:
×
4309
#ifdef STANDALONE
4310
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4311
                                               "This systemd-tmpfiles version is compiled without support for --image=.");
4312
#else
4313
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
4314
                        if (r < 0)
×
4315
                                return r;
4316
#endif
4317
                        /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4318
                        _fallthrough_;
×
4319

4320
                case 'E':
4321
                        r = exclude_default_prefixes();
×
4322
                        if (r < 0)
×
4323
                                return r;
4324

4325
                        break;
4326

4327
                case ARG_IMAGE_POLICY:
×
4328
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4329
                        if (r < 0)
×
4330
                                return r;
4331
                        break;
4332

4333
                case ARG_REPLACE:
×
4334
                        if (!path_is_absolute(optarg))
×
4335
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4336
                                                       "The argument to --replace= must be an absolute path.");
4337
                        if (!endswith(optarg, ".conf"))
×
4338
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4339
                                                       "The argument to --replace= must have the extension '.conf'.");
4340

4341
                        arg_replace = optarg;
×
4342
                        break;
×
4343

4344
                case ARG_DRY_RUN:
29✔
4345
                        arg_dry_run = true;
29✔
4346
                        break;
29✔
4347

4348
                case ARG_NO_PAGER:
×
4349
                        arg_pager_flags |= PAGER_DISABLE;
×
4350
                        break;
×
4351

4352
                case '?':
4353
                        return -EINVAL;
4354

4355
                default:
×
4356
                        assert_not_reached();
×
4357
                }
4358

4359
        if (arg_operation == 0 && arg_cat_flags == CAT_CONFIG_OFF)
689✔
4360
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4361
                                       "You need to specify at least one of --clean, --create, --remove, or --purge.");
4362

4363
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
689✔
4364
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4365
                                       "Refusing --purge without specification of a configuration file.");
4366

4367
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
689✔
4368
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4369
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4370

4371
        if (arg_replace && optind >= argc)
689✔
4372
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4373
                                       "When --replace= is given, some configuration items must be specified.");
4374

4375
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
689✔
4376
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4377
                                       "Combination of --user and --root= is not supported.");
4378

4379
        if (arg_image && arg_root)
689✔
4380
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4381
                                       "Please specify either --root= or --image=, the combination of both is not supported.");
4382

4383
        return 1;
4384
}
4385

4386
static int read_config_file(
15,666✔
4387
                Context *c,
4388
                char **config_dirs,
4389
                const char *fn,
4390
                bool ignore_enoent,
4391
                bool *invalid_config) {
4392

4393
        ItemArray *ia;
15,666✔
4394
        int r = 0;
15,666✔
4395

4396
        assert(c);
15,666✔
4397
        assert(fn);
15,666✔
4398

4399
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
15,666✔
4400
                           parse_line, c, ignore_enoent, invalid_config);
4401
        if (r <= 0)
15,666✔
4402
                return r;
15,666✔
4403

4404
        /* we have to determine age parameter for each entry of type X */
4405
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
119,310✔
4406
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
213,291✔
4407
                        ItemArray *ja;
109,290✔
4408
                        Item *candidate_item = NULL;
109,290✔
4409

4410
                        if (i->type != IGNORE_DIRECTORY_PATH)
109,290✔
4411
                                continue;
107,520✔
4412

4413
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
162,116✔
4414
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
325,814✔
4415
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
165,468✔
4416
                                                             TRUNCATE_DIRECTORY,
4417
                                                             CREATE_SUBVOLUME,
4418
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4419
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4420
                                                continue;
83,812✔
4421

4422
                                        if (path_equal(j->path, i->path)) {
81,656✔
4423
                                                candidate_item = j;
4424
                                                break;
4425
                                        }
4426

4427
                                        if (candidate_item
81,656✔
4428
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
7,669✔
4429
                                            : path_startswith(i->path, j->path) != NULL)
73,987✔
4430
                                                candidate_item = j;
4431
                                }
4432

4433
                        if (candidate_item && candidate_item->age_set) {
1,770✔
4434
                                i->age = candidate_item->age;
1,264✔
4435
                                i->age_set = true;
1,264✔
4436
                        }
4437
                }
4438

4439
        return r;
15,309✔
4440
}
4441

4442
static int parse_arguments(
138✔
4443
                Context *c,
4444
                char **config_dirs,
4445
                char **args,
4446
                bool *invalid_config) {
4447
        int r;
138✔
4448

4449
        assert(c);
138✔
4450

4451
        STRV_FOREACH(arg, args) {
276✔
4452
                r = read_config_file(c, config_dirs, *arg, false, invalid_config);
138✔
4453
                if (r < 0)
138✔
4454
                        return r;
4455
        }
4456

4457
        return 0;
4458
}
4459

4460
static int read_config_files(
551✔
4461
                Context *c,
4462
                char **config_dirs,
4463
                char **args,
4464
                bool *invalid_config) {
4465

4466
        _cleanup_strv_free_ char **files = NULL;
×
4467
        _cleanup_free_ char *p = NULL;
551✔
4468
        int r;
551✔
4469

4470
        assert(c);
551✔
4471

4472
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
551✔
4473
        if (r < 0)
551✔
4474
                return r;
4475

4476
        STRV_FOREACH(f, files)
15,719✔
4477
                if (p && path_equal(*f, p)) {
15,168✔
4478
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4479

4480
                        r = parse_arguments(c, config_dirs, args, invalid_config);
×
4481
                        if (r < 0)
×
4482
                                return r;
4483
                } else
4484
                        /* Just warn, ignore result otherwise.
4485
                         * read_config_file() has some debug output, so no need to print anything. */
4486
                        (void) read_config_file(c, config_dirs, *f, true, invalid_config);
15,168✔
4487

4488
        return 0;
4489
}
4490

4491
static int read_credential_lines(Context *c, bool *invalid_config) {
689✔
4492
        _cleanup_free_ char *j = NULL;
689✔
4493
        const char *d;
689✔
4494
        int r;
689✔
4495

4496
        assert(c);
689✔
4497

4498
        r = get_credentials_dir(&d);
689✔
4499
        if (r == -ENXIO)
689✔
4500
                return 0;
4501
        if (r < 0)
360✔
4502
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4503

4504
        j = path_join(d, "tmpfiles.extra");
360✔
4505
        if (!j)
360✔
4506
                return log_oom();
×
4507

4508
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
360✔
4509
        return 0;
4510
}
4511

4512
static int link_parent(Context *c, ItemArray *a) {
22,288✔
4513
        const char *path;
22,288✔
4514
        char *prefix;
22,288✔
4515
        int r;
22,288✔
4516

4517
        assert(c);
22,288✔
4518
        assert(a);
22,288✔
4519

4520
        /* Finds the closest "parent" item array for the specified item array. Then registers the specified
4521
         * item array as child of it, and fills the parent in, linking them both ways. This allows us to
4522
         * later create parents before their children, and clean up/remove children before their parents.
4523
         */
4524

4525
        if (a->n_items <= 0)
22,288✔
4526
                return 0;
4527

4528
        path = a->items[0].path;
22,288✔
4529
        prefix = newa(char, strlen(path) + 1);
22,288✔
4530
        PATH_FOREACH_PREFIX(prefix, path) {
74,013✔
4531
                ItemArray *j;
38,952✔
4532

4533
                j = ordered_hashmap_get(c->items, prefix);
38,952✔
4534
                if (!j)
38,952✔
4535
                        j = ordered_hashmap_get(c->globs, prefix);
30,320✔
4536
                if (j) {
30,320✔
4537
                        r = set_ensure_put(&j->children, NULL, a);
9,515✔
4538
                        if (r < 0)
9,515✔
4539
                                return log_oom();
×
4540

4541
                        a->parent = j;
9,515✔
4542
                        return 1;
9,515✔
4543
                }
4544
        }
4545

4546
        return 0;
4547
}
4548

4549
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
22,288✔
4550
                                              ItemArray, item_array_free);
4551

4552
static int run(int argc, char *argv[]) {
689✔
4553
#ifndef STANDALONE
4554
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
689✔
4555
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
689✔
4556
#endif
4557
        _cleanup_strv_free_ char **config_dirs = NULL;
689✔
4558
        _cleanup_(context_done) Context c = {};
×
4559
        bool invalid_config = false;
689✔
4560
        ItemArray *a;
689✔
4561
        enum {
689✔
4562
                PHASE_PURGE,
4563
                PHASE_REMOVE_AND_CLEAN,
4564
                PHASE_CREATE,
4565
                _PHASE_MAX
4566
        } phase;
4567
        int r;
689✔
4568

4569
        r = parse_argv(argc, argv);
689✔
4570
        if (r <= 0)
689✔
4571
                return r;
4572

4573
        log_setup();
689✔
4574

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

4585
        /* Descending down file system trees might take a lot of fds */
4586
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
689✔
4587

4588
        switch (arg_runtime_scope) {
689✔
4589

4590
        case RUNTIME_SCOPE_USER:
186✔
4591
                r = user_config_paths(&config_dirs);
186✔
4592
                if (r < 0)
186✔
4593
                        return log_error_errno(r, "Failed to initialize configuration directory list: %m");
×
4594
                break;
4595

4596
        case RUNTIME_SCOPE_SYSTEM:
503✔
4597
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
503✔
4598
                if (!config_dirs)
503✔
4599
                        return log_oom();
×
4600
                break;
4601

4602
        default:
×
4603
                assert_not_reached();
×
4604
        }
4605

4606
        if (DEBUG_LOGGING) {
689✔
4607
                _cleanup_free_ char *t = NULL;
577✔
4608

4609
                STRV_FOREACH(i, config_dirs) {
3,257✔
4610
                        _cleanup_free_ char *j = NULL;
2,680✔
4611

4612
                        j = path_join(arg_root, *i);
2,680✔
4613
                        if (!j)
2,680✔
4614
                                return log_oom();
×
4615

4616
                        if (!strextend(&t, "\n\t", j))
2,680✔
4617
                                return log_oom();
×
4618
                }
4619

4620
                log_debug("Looking for configuration files in (higher priority first):%s", t);
577✔
4621
        }
4622

4623
        if (arg_cat_flags != CAT_CONFIG_OFF)
689✔
4624
                return cat_config(config_dirs, argv + optind);
×
4625

4626
        if (should_bypass("SYSTEMD_TMPFILES"))
689✔
4627
                return 0;
4628

4629
        umask(0022);
689✔
4630

4631
        r = mac_init();
689✔
4632
        if (r < 0)
689✔
4633
                return r;
4634

4635
#ifndef STANDALONE
4636
        if (arg_image) {
689✔
4637
                assert(!arg_root);
×
4638

4639
                r = mount_image_privately_interactively(
×
4640
                                arg_image,
4641
                                arg_image_policy,
4642
                                DISSECT_IMAGE_GENERIC_ROOT |
4643
                                DISSECT_IMAGE_REQUIRE_ROOT |
4644
                                DISSECT_IMAGE_VALIDATE_OS |
4645
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
4646
                                DISSECT_IMAGE_FSCK |
4647
                                DISSECT_IMAGE_GROWFS |
4648
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
4649
                                &mounted_dir,
4650
                                /* ret_dir_fd= */ NULL,
4651
                                &loop_device);
4652
                if (r < 0)
×
4653
                        return r;
4654

4655
                arg_root = strdup(mounted_dir);
×
4656
                if (!arg_root)
×
4657
                        return log_oom();
×
4658
        }
4659
#else
4660
        assert(!arg_image);
4661
#endif
4662

4663
        c.items = ordered_hashmap_new(&item_array_hash_ops);
689✔
4664
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
689✔
4665
        if (!c.items || !c.globs)
689✔
4666
                return log_oom();
×
4667

4668
        /* If command line arguments are specified along with --replace=, read all configuration files and
4669
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4670
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
4671
         * read configuration and execute it. */
4672
        if (arg_replace || optind >= argc)
689✔
4673
                r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
551✔
4674
        else
4675
                r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
138✔
4676
        if (r < 0)
689✔
4677
                return r;
4678

4679
        r = read_credential_lines(&c, &invalid_config);
689✔
4680
        if (r < 0)
689✔
4681
                return r;
4682

4683
        /* Let's now link up all child/parent relationships */
4684
        ORDERED_HASHMAP_FOREACH(a, c.items) {
16,473✔
4685
                r = link_parent(&c, a);
15,784✔
4686
                if (r < 0)
15,784✔
4687
                        return r;
×
4688
        }
4689
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
7,193✔
4690
                r = link_parent(&c, a);
6,504✔
4691
                if (r < 0)
6,504✔
4692
                        return r;
×
4693
        }
4694

4695
        /* If multiple operations are requested, let's first run the remove/clean operations, and only then
4696
         * the create operations. i.e. that we first clean out the platform we then build on. */
4697
        for (phase = 0; phase < _PHASE_MAX; phase++) {
2,756✔
4698
                OperationMask op;
2,067✔
4699

4700
                if (phase == PHASE_PURGE)
2,067✔
4701
                        op = arg_operation & OPERATION_PURGE;
689✔
4702
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,378✔
4703
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
689✔
4704
                else if (phase == PHASE_CREATE)
689✔
4705
                        op = arg_operation & OPERATION_CREATE;
689✔
4706
                else
4707
                        assert_not_reached();
×
4708

4709
                if (op == 0) /* Nothing requested in this phase */
2,067✔
4710
                        continue;
1,070✔
4711

4712
                /* The non-globbing ones usually create things, hence we apply them first */
4713
                ORDERED_HASHMAP_FOREACH(a, c.items)
29,516✔
4714
                        RET_GATHER(r, process_item_array(&c, a, op));
28,519✔
4715

4716
                /* The globbing ones usually alter things, hence we apply them second. */
4717
                ORDERED_HASHMAP_FOREACH(a, c.globs)
11,585✔
4718
                        RET_GATHER(r, process_item_array(&c, a, op));
10,588✔
4719
        }
4720

4721
        if (ERRNO_IS_NEG_RESOURCE(r))
1,378✔
4722
                return r;
4723
        if (invalid_config)
689✔
4724
                return EX_DATAERR;
4725
        if (r < 0)
679✔
4726
                return EX_CANTCREAT;
15✔
4727
        return 0;
4728
}
4729

4730
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
689✔
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