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

systemd / systemd / 20977275812

13 Jan 2026 03:18AM UTC coverage: 72.685% (+0.3%) from 72.39%
20977275812

push

github

web-flow
Bump kernel requirements to >= 5.10, and recommend >= 5.14 (#38977)

Then, this drops several unnecessary code for older kernels.

83 of 98 new or added lines in 14 files covered. (84.69%)

267 existing lines in 44 files now uncovered.

310058 of 426578 relevant lines covered (72.68%)

1143071.97 hits per line

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

68.06
/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,665✔
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) {
88,193✔
252
        return IN_SET(r,
88,193✔
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) {
192✔
351
        _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
192✔
352
        _cleanup_free_ char *runtime_config = NULL;
192✔
353
        int r;
192✔
354

355
        assert(ret);
192✔
356

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

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

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

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

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

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

382
static bool needs_purge(ItemType t) {
4,335✔
383
        return IN_SET(t,
4,335✔
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,424✔
401
        return IN_SET(t,
23,424✔
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,827✔
420
        return IN_SET(t,
5,827✔
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,763✔
523
        assert(i);
1,763✔
524
        return i->binary_argument ?: i->argument;
1,763✔
525
}
526

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

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

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

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

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

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

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

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

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

592
        r = statx_warn_mount_root(&sx, LOG_ERR);
44✔
593
        if (r < 0)
44✔
594
                return r;
595

596
        *ret_mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
44✔
597
        *ret = TAKE_PTR(d);
44✔
598
        *ret_sx = sx;
44✔
599
        return 1;
44✔
600
}
601

602
static bool needs_cleanup(
165✔
603
                nsec_t atime,
604
                nsec_t btime,
605
                nsec_t ctime,
606
                nsec_t mtime,
607
                nsec_t cutoff,
608
                const char *sub_path,
609
                AgeBy age_by,
610
                bool is_dir) {
611

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

619
                return false;
24✔
620
        }
621

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

628
                return false;
63✔
629
        }
630

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

641
                return false;
7✔
642
        }
643

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

650
                return false;
5✔
651
        }
652

653
        return true;
654
}
655

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

672
        bool deleted = false;
81✔
673
        int r = 0;
81✔
674

675
        assert(c);
81✔
676
        assert(i);
81✔
677
        assert(d);
81✔
678

679
        FOREACH_DIRENT_ALL(de, d, break) {
431✔
680
                _cleanup_free_ char *sub_path = NULL;
350✔
681
                nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
350✔
682

683
                if (dot_or_dot_dot(de->d_name))
350✔
684
                        continue;
162✔
685

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

697
                struct statx sx;
188✔
698
                if (statx(dirfd(d), de->d_name,
188✔
699
                          AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
700
                          STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
701
                          &sx) < 0) {
702
                        if (errno == ENOENT)
×
703
                                continue;
×
704

705
                        /* FUSE, NFS mounts, SELinux might return EACCES */
706
                        log_full_errno(errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
×
707
                                       "statx(%s/%s) failed: %m", p, de->d_name);
708
                        continue;
×
709
                }
710

711
                r = statx_warn_mount_root(&sx, LOG_ERR);
188✔
712
                if (r < 0)
188✔
NEW
713
                        return r;
×
714

715
                if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
188✔
NEW
716
                        log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
×
NEW
717
                        continue;
×
718
                }
719

720
                atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : 0;
188✔
721
                mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : 0;
188✔
722
                ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : 0;
188✔
723
                btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : 0;
188✔
724

725
                sub_path = path_join(p, de->d_name);
188✔
726
                if (!sub_path) {
188✔
727
                        r = log_oom();
×
728
                        goto finish;
×
729
                }
730

731
                /* Is there an item configured for this path? */
732
                if (ordered_hashmap_get(c->items, sub_path)) {
188✔
733
                        log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
5✔
734
                        continue;
5✔
735
                }
736

737
                if (find_glob(c->globs, sub_path)) {
183✔
738
                        log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
18✔
739
                        continue;
18✔
740
                }
741

742
                if (S_ISDIR(sx.stx_mode)) {
165✔
743
                        _cleanup_closedir_ DIR *sub_dir = NULL;
×
744

745
                        if (mountpoint &&
37✔
746
                            streq(de->d_name, "lost+found") &&
×
747
                            sx.stx_uid == 0) {
×
748
                                log_debug("Ignoring directory \"%s\".", sub_path);
×
749
                                continue;
×
750
                        }
751

752
                        if (maxdepth <= 0)
37✔
753
                                log_warning("Reached max depth on \"%s\".", sub_path);
×
754
                        else {
755
                                int q;
37✔
756

757
                                sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
37✔
758
                                if (!sub_dir) {
37✔
759
                                        if (errno != ENOENT)
×
760
                                                r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
×
761

762
                                        continue;
×
763
                                }
764

765
                                if (!arg_dry_run &&
70✔
766
                                    flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
33✔
767
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path);
×
768
                                        continue;
×
769
                                }
770

771
                                q = dir_cleanup(c, i,
37✔
772
                                                sub_path, sub_dir,
773
                                                atime_nsec, mtime_nsec, cutoff_nsec,
774
                                                rootdev_major, rootdev_minor,
775
                                                false, maxdepth-1, false,
776
                                                age_by_file, age_by_dir);
777
                                if (q < 0)
37✔
778
                                        r = q;
×
779
                        }
780

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

786
                        if (keep_this_level) {
37✔
787
                                log_debug("Keeping directory \"%s\".", sub_path);
×
788
                                continue;
×
789
                        }
790

791
                        /*
792
                         * Check the file timestamps of an entry against the
793
                         * given cutoff time; delete if it is older.
794
                         */
795
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
37✔
796
                                           cutoff_nsec, sub_path, age_by_dir, true))
797
                                continue;
25✔
798

799
                        log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path);
16✔
800
                        if (!arg_dry_run &&
20✔
801
                            unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0 &&
8✔
802
                            !IN_SET(errno, ENOENT, ENOTEMPTY))
×
803
                                r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
×
804

805
                } else {
806
                        _cleanup_close_ int fd = -EBADF; /* This file descriptor is defined here so that the
350✔
807
                                                          * lock that is taken below is only dropped _after_
808
                                                          * the unlink operation has finished. */
809

810
                        /* Skip files for which the sticky bit is set. These are semantics we define, and are
811
                         * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
812
                        if (sx.stx_mode & S_ISVTX) {
128✔
813
                                log_debug("Skipping \"%s\": sticky bit set.", sub_path);
×
814
                                continue;
×
815
                        }
816

817
                        if (mountpoint &&
128✔
818
                            S_ISREG(sx.stx_mode) &&
×
819
                            sx.stx_uid == 0 &&
×
820
                            STR_IN_SET(de->d_name,
×
821
                                       ".journal",
822
                                       "aquota.user",
823
                                       "aquota.group")) {
824
                                log_debug("Skipping \"%s\".", sub_path);
×
825
                                continue;
×
826
                        }
827

828
                        /* Ignore sockets that are listed in /proc/net/unix */
829
                        if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
128✔
830
                                log_debug("Skipping \"%s\": live socket.", sub_path);
×
831
                                continue;
×
832
                        }
833

834
                        /* Ignore device nodes */
835
                        if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
128✔
836
                                log_debug("Skipping \"%s\": a device.", sub_path);
×
837
                                continue;
×
838
                        }
839

840
                        /* Keep files on this level if this was requested */
841
                        if (keep_this_level) {
128✔
842
                                log_debug("Keeping \"%s\".", sub_path);
×
843
                                continue;
×
844
                        }
845

846
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
128✔
847
                                           cutoff_nsec, sub_path, age_by_file, false))
848
                                continue;
74✔
849

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

860
                        log_action("Would remove", "Removing", "%s \"%s\"", sub_path);
70✔
861
                        if (!arg_dry_run &&
88✔
862
                            unlinkat(dirfd(d), de->d_name, 0) < 0 &&
34✔
863
                            errno != ENOENT)
×
864
                                r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
×
865

866
                        deleted = true;
54✔
867
                }
868
        }
869

870
finish:
81✔
871
        if (deleted && (self_atime_nsec < NSEC_INFINITY || self_mtime_nsec < NSEC_INFINITY)) {
81✔
872
                struct timespec ts[2];
28✔
873

874
                log_action("Would restore", "Restoring",
37✔
875
                           "%s access and modification time on \"%s\": %s, %s",
876
                           p,
877
                           FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
878
                           FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
879

880
                timespec_store_nsec(ts + 0, self_atime_nsec);
28✔
881
                timespec_store_nsec(ts + 1, self_mtime_nsec);
28✔
882

883
                /* Restore original directory timestamps */
884
                if (!arg_dry_run &&
45✔
885
                    futimens(dirfd(d), ts) < 0)
17✔
886
                        log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
28✔
887
        }
888

889
        return r;
890
}
891

892
static bool hardlinks_protected(void) {
×
893
        static int cached = -1;
×
894
        int r;
×
895

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

900
        if (cached >= 0)
×
901
                return cached;
×
902

903
        _cleanup_free_ char *value = NULL;
×
904

905
        r = sysctl_read("fs/protected_hardlinks", &value);
×
906
        if (r < 0) {
×
907
                log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
×
908
                return false;
×
909
        }
910

911
        cached = parse_boolean(value);
×
912
        if (cached < 0)
×
913
                log_debug_errno(cached, "Failed to parse fs.protected_hardlinks sysctl, assuming disabled: %m");
×
914
        return cached > 0;
×
915
}
916

917
static bool hardlink_vulnerable(const struct stat *st) {
14,152✔
918
        assert(st);
14,152✔
919

920
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
14,152✔
921
}
922

923
static mode_t process_mask_perms(mode_t mode, mode_t current) {
309✔
924

925
        if ((current & 0111) == 0)
309✔
926
                mode &= ~0111;
210✔
927
        if ((current & 0222) == 0)
309✔
928
                mode &= ~0222;
×
929
        if ((current & 0444) == 0)
309✔
930
                mode &= ~0444;
×
931
        if (!S_ISDIR(current))
309✔
932
                mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
210✔
933

934
        return mode;
309✔
935
}
936

937
static int fd_set_perms(
18,457✔
938
                Context *c,
939
                Item *i,
940
                int fd,
941
                const char *path,
942
                const struct stat *st,
943
                CreationMode creation) {
944

945
        bool do_chown, do_chmod;
18,457✔
946
        struct stat stbuf;
18,457✔
947
        mode_t new_mode;
18,457✔
948
        uid_t new_uid;
18,457✔
949
        gid_t new_gid;
18,457✔
950
        int r;
18,457✔
951

952
        assert(c);
18,457✔
953
        assert(i);
18,457✔
954
        assert(fd >= 0);
18,457✔
955
        assert(path);
18,457✔
956

957
        if (!i->mode_set && !i->uid_set && !i->gid_set)
18,457✔
958
                goto shortcut;
5,054✔
959

960
        if (!st) {
13,403✔
961
                if (fstat(fd, &stbuf) < 0)
2,449✔
962
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
963
                st = &stbuf;
964
        }
965

966
        if (hardlink_vulnerable(st))
13,403✔
967
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
968
                                       "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
969
                                       path);
970
        new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
13,403✔
971
        new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
13,403✔
972

973
        /* Do we need a chown()? */
974
        do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
13,403✔
975

976
        /* Calculate the mode to apply */
977
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
26,231✔
978
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
26,542✔
979
                (st->st_mode & 07777);
264✔
980

981
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
13,403✔
982

983
        if (do_chmod && do_chown) {
13,403✔
984
                /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
985
                 * the new mode. That way there's no time window where the file exists under the old owner
986
                 * with more than the old access modes — and not under the new owner with more than the new
987
                 * access modes either. */
988

989
                if (S_ISLNK(st->st_mode))
715✔
990
                        log_debug("Skipping temporary mode fix for symlink %s.", path);
×
991
                else {
992
                        mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
715✔
993

994
                        if (((m ^ st->st_mode) & 07777) == 0)
715✔
995
                                log_debug("\"%s\" matches temporary mode %o already.", path, m);
704✔
996
                        else {
997
                                log_action("Would temporarily change", "Temporarily changing",
11✔
998
                                           "%s \"%s\" to mode %o", path, m);
999
                                if (!arg_dry_run) {
11✔
1000
                                        r = fchmod_opath(fd, m);
11✔
1001
                                        if (r < 0)
11✔
1002
                                                return log_error_errno(r, "fchmod() of %s failed: %m", path);
×
1003
                                }
1004
                        }
1005
                }
1006
        }
1007

1008
        if (do_chown) {
13,403✔
1009
                log_action("Would change", "Changing",
2,744✔
1010
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1011

1012
                if (!arg_dry_run &&
2,776✔
1013
                    fchownat(fd, "",
1,387✔
1014
                             new_uid != st->st_uid ? new_uid : UID_INVALID,
1,387✔
1015
                             new_gid != st->st_gid ? new_gid : GID_INVALID,
1,387✔
1016
                             AT_EMPTY_PATH) < 0)
1017
                        return log_error_errno(errno, "fchownat() of %s failed: %m", path);
×
1018
        }
1019

1020
        /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
1021
         * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
1022
        if (do_chmod || do_chown) {
13,403✔
1023
                if (S_ISLNK(st->st_mode))
2,692✔
1024
                        log_debug("Skipping mode fix for symlink %s.", path);
×
1025
                else {
1026
                        log_action("Would change", "Changing", "%s \"%s\" to mode %o", path, new_mode);
5,346✔
1027
                        if (!arg_dry_run) {
2,692✔
1028
                                r = fchmod_opath(fd, new_mode);
2,690✔
1029
                                if (r < 0)
2,690✔
1030
                                        return log_error_errno(r, "fchmod() of %s failed: %m", path);
2✔
1031
                        }
1032
                }
1033
        }
1034

1035
shortcut:
13,401✔
1036
        if (arg_dry_run) {
18,455✔
1037
                log_debug("Would relabel \"%s\"", path);
5✔
1038
                return 0;
5✔
1039
        }
1040

1041
        log_debug("Relabelling \"%s\"", path);
18,450✔
1042
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
18,450✔
1043
}
1044

1045
static int path_open_parent_safe(const char *path, bool allow_failure) {
16,341✔
1046
        _cleanup_free_ char *dn = NULL;
16,341✔
1047
        int r, fd;
16,341✔
1048

1049
        if (!path_is_normalized(path))
16,341✔
1050
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1051
                                      SYNTHETIC_ERRNO(EINVAL),
1052
                                      "Failed to open parent of '%s': path not normalized%s.",
1053
                                      path,
1054
                                      allow_failure ? ", ignoring" : "");
1055

1056
        r = path_extract_directory(path, &dn);
16,341✔
1057
        if (r < 0)
16,341✔
1058
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1059
                                      r,
1060
                                      "Unable to determine parent directory of '%s'%s: %m",
1061
                                      path,
1062
                                      allow_failure ? ", ignoring" : "");
1063

1064
        r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
32,436✔
1065
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
16,341✔
1066
                return r;
1067
        if (r < 0)
16,336✔
1068
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1069
                                      r,
1070
                                      "Failed to open path '%s'%s: %m",
1071
                                      dn,
1072
                                      allow_failure ? ", ignoring" : "");
1073

1074
        return fd;
16,336✔
1075
}
1076

1077
static int path_open_safe(const char *path) {
2,799✔
1078
        int r, fd;
2,799✔
1079

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

1084
        assert(path);
2,799✔
1085

1086
        if (!path_is_normalized(path))
2,799✔
1087
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
×
1088

1089
        r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
2,799✔
1090
        if (r == -ENOLINK)
2,799✔
1091
                return r; /* Unsafe symlink: already covered by CHASE_WARN */
1092
        if (r < 0)
2,799✔
1093
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
1094
                                      "Failed to open path %s%s: %m", path,
1095
                                      r == -ENOENT ? ", ignoring" : "");
1096

1097
        return fd;
2,799✔
1098
}
1099

1100
static int path_set_perms(
2,306✔
1101
                Context *c,
1102
                Item *i,
1103
                const char *path,
1104
                CreationMode creation) {
1105

1106
        _cleanup_close_ int fd = -EBADF;
2,306✔
1107

1108
        assert(c);
2,306✔
1109
        assert(i);
2,306✔
1110
        assert(path);
2,306✔
1111

1112
        fd = path_open_safe(path);
2,306✔
1113
        if (fd == -ENOENT)
2,306✔
1114
                return 0;
1115
        if (fd < 0)
2,306✔
1116
                return fd;
1117

1118
        return fd_set_perms(c, i, fd, path, /* st= */ NULL, creation);
2,306✔
1119
}
1120

1121
static int parse_xattrs_from_arg(Item *i) {
×
1122
        const char *p;
×
1123
        int r;
×
1124

1125
        assert(i);
×
1126

1127
        assert_se(p = i->argument);
×
1128
        for (;;) {
×
1129
                _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
×
1130

1131
                r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
×
1132
                if (r < 0)
×
1133
                        log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
×
1134
                if (r <= 0)
×
1135
                        break;
1136

1137
                r = split_pair(xattr, "=", &name, &value);
×
1138
                if (r < 0) {
×
1139
                        log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
×
1140
                        continue;
×
1141
                }
1142

1143
                if (isempty(name) || isempty(value)) {
×
1144
                        log_warning("Malformed extended attribute found, ignoring: %s", xattr);
×
1145
                        continue;
×
1146
                }
1147

1148
                if (strv_push_pair(&i->xattrs, name, value) < 0)
×
1149
                        return log_oom();
×
1150

1151
                name = value = NULL;
×
1152
        }
1153

1154
        return 0;
×
1155
}
1156

1157
static int fd_set_xattrs(
×
1158
                Context *c,
1159
                Item *i,
1160
                int fd,
1161
                const char *path,
1162
                const struct stat *st,
1163
                CreationMode creation) {
1164

1165
        int r;
×
1166

1167
        assert(c);
×
1168
        assert(i);
×
1169
        assert(fd >= 0);
×
1170
        assert(path);
×
1171

1172
        STRV_FOREACH_PAIR(name, value, i->xattrs) {
×
1173
                log_action("Would set", "Setting",
×
1174
                           "%s extended attribute '%s=%s' on %s", *name, *value, path);
1175

1176
                if (!arg_dry_run) {
×
1177
                        r = xsetxattr(fd, /* path= */ NULL, AT_EMPTY_PATH, *name, *value);
×
1178
                        if (r < 0)
×
1179
                                return log_error_errno(r, "Failed to set extended attribute %s=%s on '%s': %m",
×
1180
                                                       *name, *value, path);
1181
                }
1182
        }
1183
        return 0;
1184
}
1185

1186
static int path_set_xattrs(
×
1187
                Context *c,
1188
                Item *i,
1189
                const char *path,
1190
                CreationMode creation) {
1191

1192
        _cleanup_close_ int fd = -EBADF;
×
1193

1194
        assert(c);
×
1195
        assert(i);
×
1196
        assert(path);
×
1197

1198
        fd = path_open_safe(path);
×
1199
        if (fd == -ENOENT)
×
1200
                return 0;
1201
        if (fd < 0)
×
1202
                return fd;
1203

1204
        return fd_set_xattrs(c, i, fd, path, /* st= */ NULL, creation);
×
1205
}
1206

1207
static int parse_acls_from_arg(Item *item) {
2,517✔
1208
#if HAVE_ACL
1209
        int r;
2,517✔
1210

1211
        assert(item);
2,517✔
1212

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

1216
        r = parse_acl(item->argument, &item->acl_access, &item->acl_access_exec,
5,034✔
1217
                      &item->acl_default, !item->append_or_force);
2,517✔
1218
        if (r < 0)
2,517✔
1219
                log_full_errno(arg_graceful && IN_SET(r, -EINVAL, -ENOENT, -ESRCH) ? LOG_DEBUG : LOG_WARNING,
×
1220
                               r, "Failed to parse ACL \"%s\", ignoring: %m", item->argument);
1221
#else
1222
        log_warning("ACLs are not supported, ignoring.");
1223
#endif
1224

1225
        return 0;
2,517✔
1226
}
1227

1228
#if HAVE_ACL
1229
static int parse_acl_cond_exec(
308✔
1230
                const char *path,
1231
                const struct stat *st,
1232
                acl_t cond_exec,
1233
                acl_t access, /* could be empty (NULL) */
1234
                bool append,
1235
                acl_t *ret) {
1236

1237
        acl_entry_t entry;
308✔
1238
        acl_permset_t permset;
308✔
1239
        bool has_exec;
308✔
1240
        int r;
308✔
1241

1242
        assert(path);
308✔
1243
        assert(st);
308✔
1244
        assert(cond_exec);
308✔
1245
        assert(ret);
308✔
1246

1247
        r = dlopen_libacl();
308✔
1248
        if (r < 0)
308✔
1249
                return r;
308✔
1250

1251
        if (!S_ISDIR(st->st_mode)) {
308✔
1252
                _cleanup_(acl_freep) acl_t old = NULL;
209✔
1253

1254
                old = sym_acl_get_file(path, ACL_TYPE_ACCESS);
209✔
1255
                if (!old)
209✔
1256
                        return -errno;
×
1257

1258
                has_exec = false;
209✔
1259

1260
                for (r = sym_acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
209✔
1261
                     r > 0;
832✔
1262
                     r = sym_acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
623✔
1263

1264
                        acl_tag_t tag;
635✔
1265

1266
                        if (sym_acl_get_tag_type(entry, &tag) < 0)
635✔
1267
                                return -errno;
×
1268

1269
                        if (tag == ACL_MASK)
635✔
1270
                                continue;
8✔
1271

1272
                        /* If not appending, skip ACL definitions */
1273
                        if (!append && IN_SET(tag, ACL_USER, ACL_GROUP))
629✔
1274
                                continue;
2✔
1275

1276
                        if (sym_acl_get_permset(entry, &permset) < 0)
627✔
1277
                                return -errno;
×
1278

1279
                        r = sym_acl_get_perm(permset, ACL_EXECUTE);
627✔
1280
                        if (r < 0)
627✔
1281
                                return -errno;
×
1282
                        if (r > 0) {
627✔
1283
                                has_exec = true;
12✔
1284
                                break;
12✔
1285
                        }
1286
                }
1287
                if (r < 0)
209✔
1288
                        return -errno;
×
1289

1290
                /* Check if we're about to set the execute bit in acl_access */
1291
                if (!has_exec && access) {
209✔
1292
                        for (r = sym_acl_get_entry(access, ACL_FIRST_ENTRY, &entry);
×
1293
                             r > 0;
×
1294
                             r = sym_acl_get_entry(access, ACL_NEXT_ENTRY, &entry)) {
×
1295

1296
                                if (sym_acl_get_permset(entry, &permset) < 0)
×
1297
                                        return -errno;
×
1298

1299
                                r = sym_acl_get_perm(permset, ACL_EXECUTE);
×
1300
                                if (r < 0)
×
1301
                                        return -errno;
×
1302
                                if (r > 0) {
×
1303
                                        has_exec = true;
1304
                                        break;
1305
                                }
1306
                        }
1307
                        if (r < 0)
×
1308
                                return -errno;
×
1309
                }
1310
        } else
1311
                has_exec = true;
1312

1313
        _cleanup_(acl_freep) acl_t parsed = access ? sym_acl_dup(access) : sym_acl_init(0);
616✔
1314
        if (!parsed)
308✔
1315
                return -errno;
×
1316

1317
        for (r = sym_acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
308✔
1318
             r > 0;
920✔
1319
             r = sym_acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
612✔
1320

1321
                acl_entry_t parsed_entry;
612✔
1322

1323
                if (sym_acl_create_entry(&parsed, &parsed_entry) < 0)
612✔
1324
                        return -errno;
×
1325

1326
                if (sym_acl_copy_entry(parsed_entry, entry) < 0)
612✔
1327
                        return -errno;
×
1328

1329
                /* We substituted 'X' with 'x' in parse_acl(), so drop execute bit here if not applicable. */
1330
                if (!has_exec) {
612✔
1331
                        if (sym_acl_get_permset(parsed_entry, &permset) < 0)
391✔
1332
                                return -errno;
×
1333

1334
                        if (sym_acl_delete_perm(permset, ACL_EXECUTE) < 0)
391✔
1335
                                return -errno;
×
1336
                }
1337
        }
1338
        if (r < 0)
308✔
1339
                return -errno;
×
1340

1341
        if (!append) { /* want_mask = true */
308✔
1342
                r = calc_acl_mask_if_needed(&parsed);
3✔
1343
                if (r < 0)
3✔
1344
                        return r;
1345
        }
1346

1347
        *ret = TAKE_PTR(parsed);
308✔
1348

1349
        return 0;
308✔
1350
}
1351

1352
static int path_set_acl(
1,019✔
1353
                Context *c,
1354
                const char *path,
1355
                const char *pretty,
1356
                acl_type_t type,
1357
                acl_t acl,
1358
                bool modify) {
1359

1360
        _cleanup_(acl_free_charpp) char *t = NULL;
1,019✔
1361
        _cleanup_(acl_freep) acl_t dup = NULL;
1,019✔
1362
        int r;
1,019✔
1363

1364
        assert(c);
1,019✔
1365

1366
        r = dlopen_libacl();
1,019✔
1367
        if (r < 0)
1,019✔
1368
                return r;
1369

1370
        /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1371

1372
        if (modify) {
1,019✔
1373
                r = acls_for_file(path, type, acl, &dup);
1,016✔
1374
                if (r < 0)
1,016✔
1375
                        return r;
1376

1377
                r = calc_acl_mask_if_needed(&dup);
1,016✔
1378
                if (r < 0)
1,016✔
1379
                        return r;
1380
        } else {
1381
                dup = sym_acl_dup(acl);
3✔
1382
                if (!dup)
3✔
1383
                        return -errno;
×
1384

1385
                /* the mask was already added earlier if needed */
1386
        }
1387

1388
        r = add_base_acls_if_needed(&dup, path);
1,019✔
1389
        if (r < 0)
1,019✔
1390
                return r;
1391

1392
        t = sym_acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1,019✔
1393
        log_action("Would set", "Setting",
2,494✔
1394
                   "%s %s ACL %s on %s",
1395
                   type == ACL_TYPE_ACCESS ? "access" : "default",
1396
                   strna(t), pretty);
1397

1398
        if (!arg_dry_run &&
2,037✔
1399
            sym_acl_set_file(path, type, dup) < 0) {
1,018✔
1400
                if (ERRNO_IS_NOT_SUPPORTED(errno))
×
1401
                        /* No error if filesystem doesn't support ACLs. Return negative. */
1402
                        return -errno;
×
1403
                else
1404
                        /* Return positive to indicate we already warned */
1405
                        return -log_error_errno(errno,
×
1406
                                                "Setting %s ACL \"%s\" on %s failed: %m",
1407
                                                type == ACL_TYPE_ACCESS ? "access" : "default",
1408
                                                strna(t), pretty);
1409
        }
1410
        return 0;
1411
}
1412
#endif
1413

1414
static int fd_set_acls(
749✔
1415
                Context *c,
1416
                Item *item,
1417
                int fd,
1418
                const char *path,
1419
                const struct stat *st,
1420
                CreationMode creation) {
1421

1422
        int r = 0;
749✔
1423
#if HAVE_ACL
1424
        _cleanup_(acl_freep) acl_t access_with_exec_parsed = NULL;
749✔
1425
        struct stat stbuf;
749✔
1426

1427
        assert(c);
749✔
1428
        assert(item);
749✔
1429
        assert(fd >= 0);
749✔
1430
        assert(path);
749✔
1431

1432
        if (!st) {
749✔
1433
                if (fstat(fd, &stbuf) < 0)
445✔
1434
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1435
                st = &stbuf;
1436
        }
1437

1438
        if (hardlink_vulnerable(st))
749✔
1439
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
1440
                                       "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1441
                                       path);
1442

1443
        if (!inode_type_can_acl(st->st_mode)) {
749✔
1444
                log_debug("Skipping ACL fix for '%s' (inode type does not support ACLs).", path);
×
1445
                return 0;
×
1446
        }
1447

1448
        if (item->acl_access_exec) {
749✔
1449
                r = parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd), st,
308✔
1450
                                        item->acl_access_exec,
1451
                                        item->acl_access,
1452
                                        item->append_or_force,
308✔
1453
                                        &access_with_exec_parsed);
1454
                if (r < 0)
308✔
1455
                        return log_error_errno(r, "Failed to parse conditionalized execute bit for \"%s\": %m", path);
×
1456

1457
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
308✔
1458
        } else if (item->acl_access)
441✔
1459
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
195✔
1460

1461
        /* set only default acls to folders */
1462
        if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
749✔
1463
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
516✔
1464

1465
        if (ERRNO_IS_NOT_SUPPORTED(r)) {
749✔
1466
                log_debug_errno(r, "ACLs not supported by file system at %s", path);
×
1467
                return 0;
×
1468
        }
1469
        if (r > 0)
749✔
1470
                return -r; /* already warned in path_set_acl */
×
1471
        if (r < 0)
749✔
1472
                return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
×
1473
#endif
1474
        return r;
1475
}
1476

1477
static int path_set_acls(
445✔
1478
                Context *c,
1479
                Item *item,
1480
                const char *path,
1481
                CreationMode creation) {
1482

1483
        int r = 0;
445✔
1484
#if HAVE_ACL
1485
        _cleanup_close_ int fd = -EBADF;
445✔
1486

1487
        assert(c);
445✔
1488
        assert(item);
445✔
1489
        assert(path);
445✔
1490

1491
        fd = path_open_safe(path);
445✔
1492
        if (fd == -ENOENT)
445✔
1493
                return 0;
1494
        if (fd < 0)
445✔
1495
                return fd;
1496

1497
        r = fd_set_acls(c, item, fd, path, /* st= */ NULL, creation);
445✔
1498
#endif
1499
        return r;
1500
}
1501

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

1524
        enum {
1,077✔
1525
                MODE_ADD,
1526
                MODE_DEL,
1527
                MODE_SET
1528
        } mode = MODE_ADD;
1,077✔
1529

1530
        unsigned value = 0, mask = 0;
1,077✔
1531
        const char *p;
1,077✔
1532

1533
        assert(item);
1,077✔
1534

1535
        p = item->argument;
1,077✔
1536
        if (p) {
1,077✔
1537
                if (*p == '+') {
1,077✔
1538
                        mode = MODE_ADD;
1,077✔
1539
                        p++;
1,077✔
1540
                } else if (*p == '-') {
×
1541
                        mode = MODE_DEL;
×
1542
                        p++;
×
1543
                } else  if (*p == '=') {
×
1544
                        mode = MODE_SET;
×
1545
                        p++;
×
1546
                }
1547
        }
1548

1549
        if (isempty(p) && mode != MODE_SET)
1,077✔
1550
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1551
                                       "Setting file attribute on '%s' needs an attribute specification.",
1552
                                       item->path);
1553

1554
        for (; p && *p ; p++) {
2,154✔
1555
                unsigned i, v;
1556

1557
                for (i = 0; i < ELEMENTSOF(attributes); i++)
15,078✔
1558
                        if (*p == attributes[i].character)
15,078✔
1559
                                break;
1560

1561
                if (i >= ELEMENTSOF(attributes))
1,077✔
1562
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1563
                                               "Unknown file attribute '%c' on '%s'.", *p, item->path);
1564

1565
                v = attributes[i].value;
1,077✔
1566

1567
                SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1,077✔
1568

1569
                mask |= v;
1,077✔
1570
        }
1571

1572
        if (mode == MODE_SET)
1,077✔
1573
                mask |= CHATTR_ALL_FL;
×
1574

1575
        assert(mask != 0);
1,077✔
1576

1577
        item->attribute_mask = mask;
1,077✔
1578
        item->attribute_value = value;
1,077✔
1579
        item->attribute_set = true;
1,077✔
1580

1581
        return 0;
1,077✔
1582
}
1583

1584
static int fd_set_attribute(
48✔
1585
                Context *c,
1586
                Item *item,
1587
                int fd,
1588
                const char *path,
1589
                const struct stat *st,
1590
                CreationMode creation) {
1591

1592
        struct stat stbuf;
48✔
1593
        unsigned f;
48✔
1594
        int r;
48✔
1595

1596
        assert(c);
48✔
1597
        assert(item);
48✔
1598
        assert(fd >= 0);
48✔
1599
        assert(path);
48✔
1600

1601
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1602
                return 0;
48✔
1603

1604
        if (!st) {
48✔
1605
                if (fstat(fd, &stbuf) < 0)
48✔
1606
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1607
                st = &stbuf;
1608
        }
1609

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

1617
        f = item->attribute_value & item->attribute_mask;
48✔
1618

1619
        /* Mask away directory-specific flags */
1620
        if (!S_ISDIR(st->st_mode))
48✔
1621
                f &= ~FS_DIRSYNC_FL;
×
1622

1623
        log_action("Would try to set", "Trying to set",
96✔
1624
                   "%s file attributes 0x%08x on %s",
1625
                   f & item->attribute_mask,
1626
                   path);
1627

1628
        if (!arg_dry_run) {
48✔
1629
                _cleanup_close_ int procfs_fd = -EBADF;
48✔
1630

1631
                procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
48✔
1632
                if (procfs_fd < 0)
48✔
1633
                        return log_error_errno(procfs_fd, "Failed to reopen '%s': %m", path);
×
1634

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

1647
        return 0;
1648
}
1649

1650
static int path_set_attribute(
48✔
1651
                Context *c,
1652
                Item *item,
1653
                const char *path,
1654
                CreationMode creation) {
1655

1656
        _cleanup_close_ int fd = -EBADF;
48✔
1657

1658
        assert(c);
48✔
1659
        assert(item);
48✔
1660

1661
        if (!item->attribute_set || item->attribute_mask == 0)
48✔
1662
                return 0;
1663

1664
        fd = path_open_safe(path);
48✔
1665
        if (fd == -ENOENT)
48✔
1666
                return 0;
1667
        if (fd < 0)
48✔
1668
                return fd;
1669

1670
        return fd_set_attribute(c, item, fd, path, /* st= */ NULL, creation);
48✔
1671
}
1672

1673
static int write_argument_data(Item *i, int fd, const char *path) {
266✔
1674
        int r;
266✔
1675

1676
        assert(i);
266✔
1677
        assert(fd >= 0);
266✔
1678
        assert(path);
266✔
1679

1680
        if (item_binary_argument_size(i) == 0)
266✔
1681
                return 0;
1682

1683
        assert(item_binary_argument(i));
258✔
1684

1685
        log_action("Would write", "Writing", "%s to \"%s\"", path);
484✔
1686

1687
        if (!arg_dry_run) {
258✔
1688
                r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i));
255✔
1689
                if (r < 0)
255✔
1690
                        return log_error_errno(r, "Failed to write file \"%s\": %m", path);
×
1691
        }
1692

1693
        return 0;
1694
}
1695

1696
static int write_one_file(Context *c, Item *i, const char *path, CreationMode creation) {
18✔
1697
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
18✔
1698
        _cleanup_free_ char *bn = NULL;
18✔
1699
        int r;
18✔
1700

1701
        assert(c);
18✔
1702
        assert(i);
18✔
1703
        assert(path);
18✔
1704
        assert(i->type == WRITE_FILE);
18✔
1705

1706
        r = path_extract_filename(path, &bn);
18✔
1707
        if (r < 0)
18✔
1708
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1709
        if (r == O_DIRECTORY)
18✔
1710
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1711

1712
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1713
         * can't be changed behind our back. */
1714
        dir_fd = path_open_parent_safe(path, i->allow_failure);
18✔
1715
        if (dir_fd < 0)
18✔
1716
                return dir_fd;
1717

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

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

1730
                return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
×
1731
        }
1732

1733
        /* 'w' is allowed to write into any kind of files. */
1734

1735
        r = write_argument_data(i, fd, path);
18✔
1736
        if (r < 0)
18✔
1737
                return r;
1738

1739
        return fd_set_perms(c, i, fd, path, NULL, creation);
18✔
1740
}
1741

1742
static int create_file(
776✔
1743
                Context *c,
1744
                Item *i,
1745
                const char *path) {
1746

1747
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
776✔
1748
        _cleanup_free_ char *bn = NULL;
776✔
1749
        struct stat stbuf, *st = NULL;
776✔
1750
        CreationMode creation;
776✔
1751
        int r = 0;
776✔
1752

1753
        assert(c);
776✔
1754
        assert(i);
776✔
1755
        assert(path);
776✔
1756
        assert(i->type == CREATE_FILE);
776✔
1757

1758
        /* 'f' operates on regular files exclusively. */
1759

1760
        r = path_extract_filename(path, &bn);
776✔
1761
        if (r < 0)
776✔
1762
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1763
        if (r == O_DIRECTORY)
776✔
1764
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1765

1766
        if (arg_dry_run) {
776✔
1767
                log_info("Would create file %s", path);
4✔
1768
                return 0;
4✔
1769

1770
                /* The opening of the directory below would fail if it doesn't exist,
1771
                 * so log and exit before even trying to do that. */
1772
        }
1773

1774
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1775
         * can't be changed behind our back. */
1776
        dir_fd = path_open_parent_safe(path, i->allow_failure);
772✔
1777
        if (dir_fd < 0)
772✔
1778
                return dir_fd;
1779

1780
        WITH_UMASK(0000) {
1,540✔
1781
                mac_selinux_create_file_prepare(path, S_IFREG);
770✔
1782
                fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
770✔
1783
                mac_selinux_create_file_clear();
770✔
1784
        }
1785

1786
        if (fd < 0) {
770✔
1787
                /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1788
                 * returns EROFS only if it needs to create the file. */
1789
                if (fd != -EEXIST)
642✔
1790
                        return log_error_errno(fd, "Failed to create file %s: %m", path);
1✔
1791

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

1799
                if (fstat(fd, &stbuf) < 0)
641✔
1800
                        return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1801

1802
                if (!S_ISREG(stbuf.st_mode))
641✔
1803
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
5✔
1804
                                               "%s exists and is not a regular file.",
1805
                                               path);
1806

1807
                st = &stbuf;
1808
                creation = CREATION_EXISTING;
1809
        } else {
1810
                r = write_argument_data(i, fd, path);
128✔
1811
                if (r < 0)
128✔
1812
                        return r;
1813

1814
                creation = CREATION_NORMAL;
1815
        }
1816

1817
        return fd_set_perms(c, i, fd, path, st, creation);
764✔
1818
}
1819

1820
static int truncate_file(
247✔
1821
                Context *c,
1822
                Item *i,
1823
                const char *path) {
1824

1825
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
247✔
1826
        _cleanup_free_ char *bn = NULL;
247✔
1827
        struct stat stbuf, *st = NULL;
247✔
1828
        CreationMode creation;
247✔
1829
        bool erofs = false;
247✔
1830
        int r = 0;
247✔
1831

1832
        assert(c);
247✔
1833
        assert(i);
247✔
1834
        assert(path);
247✔
1835
        assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
247✔
1836

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

1841
        r = path_extract_filename(path, &bn);
247✔
1842
        if (r < 0)
247✔
1843
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1844
        if (r == O_DIRECTORY)
247✔
1845
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
×
1846

1847
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1848
         * can't be changed behind our back. */
1849
        dir_fd = path_open_parent_safe(path, i->allow_failure);
247✔
1850
        if (dir_fd < 0)
247✔
1851
                return dir_fd;
1852

1853
        if (arg_dry_run) {
246✔
1854
                log_info("Would truncate %s", path);
×
1855
                return 0;
×
1856
        }
1857

1858
        creation = CREATION_EXISTING;
246✔
1859
        fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
246✔
1860
        if (fd == -ENOENT) {
222✔
1861
                creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
217✔
1862

1863
                WITH_UMASK(0000) {
434✔
1864
                        mac_selinux_create_file_prepare(path, S_IFREG);
217✔
1865
                        fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
217✔
1866
                        mac_selinux_create_file_clear();
217✔
1867
                }
1868
        }
1869

1870
        if (fd < 0) {
246✔
1871
                if (fd != -EROFS)
6✔
1872
                        return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1✔
1873

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

1878
                fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
5✔
1879
                if (fd < 0) {
5✔
1880
                        if (errno == ENOENT)
1✔
1881
                                return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1✔
1882
                                                       "Cannot create file %s on a read-only file system.",
1883
                                                       path);
1884

1885
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
×
1886
                }
1887

1888
                erofs = true;
1889
                creation = CREATION_EXISTING;
1890
        }
1891

1892
        if (fstat(fd, &stbuf) < 0)
244✔
1893
                return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1894

1895
        if (!S_ISREG(stbuf.st_mode))
244✔
1896
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1897
                                       "%s exists and is not a regular file.",
1898
                                       path);
1899

1900
        if (stbuf.st_size > 0) {
244✔
1901
                if (ftruncate(fd, 0) < 0) {
15✔
1902
                        r = erofs ? -EROFS : -errno;
2✔
1903
                        return log_error_errno(r, "Failed to truncate file %s: %m", path);
2✔
1904
                }
1905
        } else
1906
                st = &stbuf;
1907

1908
        log_debug("\"%s\" has been created.", path);
242✔
1909

1910
        if (item_binary_argument(i)) {
242✔
1911
                r = write_argument_data(i, fd, path);
120✔
1912
                if (r < 0)
120✔
1913
                        return r;
1914
        }
1915

1916
        return fd_set_perms(c, i, fd, path, st, creation);
242✔
1917
}
1918

1919
static int copy_files(Context *c, Item *i) {
3,797✔
1920
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
3,797✔
1921
        _cleanup_free_ char *bn = NULL;
3,797✔
1922
        struct stat st, a;
3,797✔
1923
        int r;
3,797✔
1924

1925
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
7,455✔
1926
        if (arg_dry_run)
3,797✔
1927
                return 0;
1928

1929
        r = path_extract_filename(i->path, &bn);
3,795✔
1930
        if (r < 0)
3,795✔
1931
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
1932

1933
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1934
         * path can't be changed behind our back. */
1935
        dfd = path_open_parent_safe(i->path, i->allow_failure);
3,795✔
1936
        if (dfd < 0)
3,795✔
1937
                return dfd;
1938

1939
        r = copy_tree_at(AT_FDCWD, i->argument,
3,799✔
1940
                         dfd, bn,
1941
                         i->uid_set ? i->uid : UID_INVALID,
3,795✔
1942
                         i->gid_set ? i->gid : GID_INVALID,
3,795✔
1943
                         COPY_REFLINK | ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
3,795✔
1944
                         NULL, NULL);
1945

1946
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
3,795✔
1947
        if (fd < 0) {
3,795✔
1948
                if (r < 0) /* Look at original error first */
×
1949
                        return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
×
1950

1951
                return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
×
1952
        }
1953

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

1957
        if (stat(i->argument, &a) < 0)
3,795✔
1958
                return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
×
1959

1960
        if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
3,795✔
1961
                log_debug("Can't copy to %s, file exists already and is of different type", i->path);
×
1962
                return 0;
×
1963
        }
1964

1965
        return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
3,795✔
1966
}
1967

1968
static int create_directory_or_subvolume(
8,137✔
1969
                const char *path,
1970
                mode_t mode,
1971
                bool subvol,
1972
                bool allow_failure,
1973
                struct stat *ret_st,
1974
                CreationMode *ret_creation) {
1975

1976
        _cleanup_free_ char *bn = NULL;
8,137✔
1977
        _cleanup_close_ int pfd = -EBADF;
8,137✔
1978
        CreationMode creation;
8,137✔
1979
        struct stat st;
8,137✔
1980
        int r, fd;
8,137✔
1981

1982
        assert(path);
8,137✔
1983

1984
        r = path_extract_filename(path, &bn);
8,137✔
1985
        if (r < 0)
8,137✔
1986
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1987

1988
        pfd = path_open_parent_safe(path, allow_failure);
8,137✔
1989
        if (pfd < 0)
8,137✔
1990
                return pfd;
1991

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

2018
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2019
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
15,965✔
2020
                if (!arg_dry_run)
8,135✔
2021
                        WITH_UMASK(0000)
16,270✔
2022
                                r = mkdirat_label(pfd, bn, mode);
8,135✔
2023
        }
2024

2025
        if (arg_dry_run)
8,135✔
2026
                return 0;
2027

2028
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
8,135✔
2029

2030
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
8,135✔
2031
        if (fd < 0) {
8,135✔
2032
                /* We couldn't open it because it is not actually a directory? */
2033
                if (errno == ENOTDIR)
×
2034
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
×
2035

2036
                /* Then look at the original error */
2037
                if (r < 0)
×
2038
                        return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
2039
                                              r,
2040
                                              "Failed to create directory or subvolume \"%s\"%s: %m",
2041
                                              path,
2042
                                              allow_failure ? ", ignoring" : "");
2043

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

2047
        if (fstat(fd, &st) < 0)
8,135✔
2048
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2049

2050
        assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
8,135✔
2051

2052
        log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
8,135✔
2053

2054
        if (ret_st)
8,135✔
2055
                *ret_st = st;
8,135✔
2056
        if (ret_creation)
8,135✔
2057
                *ret_creation = creation;
8,135✔
2058

2059
        return fd;
2060
}
2061

2062
static int create_directory(
7,287✔
2063
                Context *c,
2064
                Item *i,
2065
                const char *path) {
2066

2067
        _cleanup_close_ int fd = -EBADF;
7,287✔
2068
        CreationMode creation;
7,287✔
2069
        struct stat st;
7,287✔
2070

2071
        assert(c);
7,287✔
2072
        assert(i);
7,287✔
2073
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
7,287✔
2074

2075
        if (arg_dry_run) {
7,287✔
2076
                log_info("Would create directory %s", path);
11✔
2077
                return 0;
11✔
2078
        }
2079

2080
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
7,276✔
2081
        if (fd == -EEXIST)
7,276✔
2082
                return 0;
2083
        if (fd < 0)
7,276✔
2084
                return fd;
2085

2086
        return fd_set_perms(c, i, fd, path, &st, creation);
7,274✔
2087
}
2088

2089
static int create_subvolume(
861✔
2090
                Context *c,
2091
                Item *i,
2092
                const char *path) {
2093

2094
        _cleanup_close_ int fd = -EBADF;
861✔
2095
        CreationMode creation;
861✔
2096
        struct stat st;
861✔
2097
        int r, q = 0;
861✔
2098

2099
        assert(c);
861✔
2100
        assert(i);
861✔
2101
        assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
861✔
2102

2103
        if (arg_dry_run) {
861✔
2104
                log_info("Would create subvolume %s", path);
×
2105
                return 0;
×
2106
        }
2107

2108
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ true, i->allow_failure, &st, &creation);
861✔
2109
        if (fd == -EEXIST)
861✔
2110
                return 0;
2111
        if (fd < 0)
861✔
2112
                return fd;
2113

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

2131
        r = fd_set_perms(c, i, fd, path, &st, creation);
861✔
2132
        if (q < 0) /* prefer the quota change error from above */
861✔
2133
                return q;
×
2134

2135
        return r;
2136
}
2137

2138
static int empty_directory(
5✔
2139
                Context *c,
2140
                Item *i,
2141
                const char *path,
2142
                CreationMode creation) {
2143

2144
        _cleanup_close_ int fd = -EBADF;
5✔
2145
        struct stat st;
5✔
2146
        int r;
5✔
2147

2148
        assert(c);
5✔
2149
        assert(i);
5✔
2150
        assert(i->type == EMPTY_DIRECTORY);
5✔
2151

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

2164
        if (fstat(fd, &st) < 0)
5✔
2165
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2166
        if (!S_ISDIR(st.st_mode)) {
5✔
2167
                log_warning("'%s' already exists and is not a directory.", path);
1✔
2168
                return 0;
1✔
2169
        }
2170

2171
        return fd_set_perms(c, i, fd, path, &st, creation);
4✔
2172
}
2173

2174
static int create_device(
1,894✔
2175
                Context *c,
2176
                Item *i,
2177
                mode_t file_type) {
2178

2179
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
1,894✔
2180
        _cleanup_free_ char *bn = NULL;
1,894✔
2181
        CreationMode creation;
1,894✔
2182
        struct stat st;
1,894✔
2183
        int r;
1,894✔
2184

2185
        assert(c);
1,894✔
2186
        assert(i);
1,894✔
2187
        assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
1,894✔
2188
        assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1,894✔
2189

2190
        r = path_extract_filename(i->path, &bn);
1,894✔
2191
        if (r < 0)
1,894✔
2192
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2193
        if (r == O_DIRECTORY)
1,894✔
2194
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2195
                                       "Cannot open path '%s' for creating device node, is a directory.", i->path);
2196

2197
        if (arg_dry_run) {
1,894✔
2198
                log_info("Would create device node %s", i->path);
4✔
2199
                return 0;
4✔
2200
        }
2201

2202
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2203
         * path can't be changed behind our back. */
2204
        dfd = path_open_parent_safe(i->path, i->allow_failure);
1,890✔
2205
        if (dfd < 0)
1,890✔
2206
                return dfd;
2207

2208
        WITH_UMASK(0000) {
3,780✔
2209
                mac_selinux_create_file_prepare(i->path, file_type);
1,890✔
2210
                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
1,890✔
2211
                mac_selinux_create_file_clear();
1,890✔
2212
        }
2213
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,890✔
2214

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

2221
                if (r < 0) {
×
2222
                        if (ERRNO_IS_PRIVILEGE(r))
×
2223
                                goto handle_privilege;
×
2224

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

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

2231
        if (fstat(fd, &st) < 0)
1,890✔
2232
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2233

2234
        if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
1,890✔
2235

2236
                if (i->append_or_force) {
×
2237
                        fd = safe_close(fd);
×
2238

2239
                        WITH_UMASK(0000) {
×
2240
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2241
                                r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
×
2242
                                mac_selinux_create_file_clear();
×
2243
                        }
2244
                        if (ERRNO_IS_PRIVILEGE(r))
×
2245
                                goto handle_privilege;
×
2246
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
×
2247
                                r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
×
2248
                                if (r < 0)
×
2249
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2250

2251
                                mac_selinux_create_file_prepare(i->path, file_type);
×
2252
                                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
×
2253
                                mac_selinux_create_file_clear();
×
2254
                        }
2255
                        if (r < 0)
×
2256
                                return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
×
2257

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

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

2266
                        if (((st.st_mode ^ file_type) & S_IFMT) != 0)
×
2267
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2268
                                                       "Device node we just created is not a device node, refusing.");
2269

2270
                        creation = CREATION_FORCE;
2271
                } else {
2272
                        log_warning("\"%s\" already exists and is not a device node.", i->path);
×
2273
                        return 0;
×
2274
                }
2275
        }
2276

2277
        log_debug("%s %s device node \"%s\" %u:%u.",
3,780✔
2278
                  creation_mode_verb_to_string(creation),
2279
                  i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
2280
                  i->path, major(i->mode), minor(i->mode));
2281

2282
        return fd_set_perms(c, i, fd, i->path, &st, creation);
1,890✔
2283

2284
handle_privilege:
×
2285
        log_debug_errno(r,
1,894✔
2286
                        "We lack permissions, possibly because of cgroup configuration; "
2287
                        "skipping creation of device node '%s'.", i->path);
2288
        return 0;
2289
}
2290

2291
static int create_fifo(Context *c, Item *i) {
4✔
2292
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
4✔
2293
        _cleanup_free_ char *bn = NULL;
4✔
2294
        CreationMode creation;
4✔
2295
        struct stat st;
4✔
2296
        int r;
4✔
2297

2298
        assert(c);
4✔
2299
        assert(i);
4✔
2300
        assert(i->type == CREATE_FIFO);
4✔
2301

2302
        r = path_extract_filename(i->path, &bn);
4✔
2303
        if (r < 0)
4✔
2304
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2305
        if (r == O_DIRECTORY)
4✔
2306
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2307
                                       "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2308

2309
        if (arg_dry_run) {
4✔
2310
                log_info("Would create fifo %s", i->path);
1✔
2311
                return 0;
1✔
2312
        }
2313

2314
        pfd = path_open_parent_safe(i->path, i->allow_failure);
3✔
2315
        if (pfd < 0)
3✔
2316
                return pfd;
2317

2318
        WITH_UMASK(0000) {
6✔
2319
                mac_selinux_create_file_prepare(i->path, S_IFIFO);
3✔
2320
                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
3✔
2321
                mac_selinux_create_file_clear();
3✔
2322
        }
2323

2324
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
3✔
2325

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

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

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

2338
        if (!S_ISFIFO(st.st_mode)) {
3✔
2339

2340
                if (i->append_or_force) {
2✔
2341
                        fd = safe_close(fd);
1✔
2342

2343
                        WITH_UMASK(0000) {
2✔
2344
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
1✔
2345
                                r = mkfifoat_atomic(pfd, bn, i->mode);
1✔
2346
                                mac_selinux_create_file_clear();
1✔
2347
                        }
2348
                        if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1✔
2349
                                r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
×
2350
                                if (r < 0)
×
2351
                                        return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2352

2353
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
×
2354
                                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
×
2355
                                mac_selinux_create_file_clear();
×
2356
                        }
2357
                        if (r < 0)
1✔
2358
                                return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
×
2359

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

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

2368
                        if (!S_ISFIFO(st.st_mode))
1✔
2369
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2370
                                                       "FIFO inode we just created is not a FIFO, refusing.");
2371

2372
                        creation = CREATION_FORCE;
2373
                } else {
2374
                        log_warning("\"%s\" already exists and is not a FIFO.", i->path);
1✔
2375
                        return 0;
1✔
2376
                }
2377
        }
2378

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

2381
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2✔
2382
}
2383

2384
static int create_symlink(Context *c, Item *i) {
1,482✔
2385
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
1,482✔
2386
        _cleanup_free_ char *bn = NULL;
1,482✔
2387
        CreationMode creation;
1,482✔
2388
        struct stat st;
1,482✔
2389
        bool good = false;
1,482✔
2390
        int r;
1,482✔
2391

2392
        assert(c);
1,482✔
2393
        assert(i);
1,482✔
2394

2395
        if (i->ignore_if_target_missing) {
1,482✔
2396
                r = chase(i->argument, arg_root, CHASE_SAFE|CHASE_PREFIX_ROOT|CHASE_NOFOLLOW, /* ret_path= */ NULL, /* ret_fd= */ NULL);
2✔
2397
                if (r == -ENOENT) {
2✔
2398
                        /* Silently skip over lines where the source file is missing. */
2399
                        log_info("Symlink source path '%s/%s' does not exist, skipping line.",
1✔
2400
                                 empty_to_root(arg_root), skip_leading_slash(i->argument));
2401
                        return 0;
1✔
2402
                }
2403
                if (r < 0)
1✔
2404
                        return log_error_errno(r, "Failed to check if symlink source path '%s/%s' exists: %m",
×
2405
                                               empty_to_root(arg_root), skip_leading_slash(i->argument));
2406
        }
2407

2408
        r = path_extract_filename(i->path, &bn);
1,481✔
2409
        if (r < 0)
1,481✔
2410
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2411
        if (r == O_DIRECTORY)
1,481✔
2412
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2413
                                       "Cannot open path '%s' for creating symlink, is a directory.", i->path);
2414

2415
        if (arg_dry_run) {
1,481✔
2416
                log_info("Would create symlink %s -> %s", i->path, i->argument);
2✔
2417
                return 0;
2✔
2418
        }
2419

2420
        pfd = path_open_parent_safe(i->path, i->allow_failure);
1,479✔
2421
        if (pfd < 0)
1,479✔
2422
                return pfd;
2423

2424
        mac_selinux_create_file_prepare(i->path, S_IFLNK);
1,479✔
2425
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
1,479✔
2426
        mac_selinux_create_file_clear();
1,479✔
2427

2428
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,479✔
2429

2430
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1,479✔
2431
        if (fd < 0) {
1,479✔
2432
                if (r < 0)
×
2433
                        return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
×
2434

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

2438
        if (fstat(fd, &st) < 0)
1,479✔
2439
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2440

2441
        if (S_ISLNK(st.st_mode)) {
1,479✔
2442
                _cleanup_free_ char *x = NULL;
×
2443

2444
                r = readlinkat_malloc(fd, "", &x);
1,478✔
2445
                if (r < 0)
1,478✔
2446
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
×
2447

2448
                good = streq(x, i->argument);
1,478✔
2449
        } else
2450
                good = false;
2451

2452
        if (!good) {
1,478✔
2453
                if (!i->append_or_force) {
496✔
2454
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
492✔
2455
                        return 0;
492✔
2456
                }
2457

2458
                fd = safe_close(fd);
4✔
2459

2460
                r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
4✔
2461
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
4✔
2462
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
1✔
2463
                        if (r < 0)
1✔
2464
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2465

2466
                        r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
1✔
2467
                }
2468
                if (r < 0)
4✔
2469
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2470

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

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

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

2482
                creation = CREATION_FORCE;
2483
        }
2484

2485
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
987✔
2486
        return fd_set_perms(c, i, fd, i->path, &st, creation);
987✔
2487
}
2488

2489
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2490
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2491

2492
static int item_do(
618✔
2493
                Context *c,
2494
                Item *i,
2495
                int fd,
2496
                const char *path,
2497
                CreationMode creation,
2498
                fdaction_t action) {
2499

2500
        struct stat st;
618✔
2501
        int r;
618✔
2502

2503
        assert(c);
618✔
2504
        assert(i);
618✔
2505
        assert(fd >= 0);
618✔
2506
        assert(path);
618✔
2507
        assert(action);
618✔
2508

2509
        if (fstat(fd, &st) < 0) {
618✔
2510
                r = log_error_errno(errno, "fstat() on file failed: %m");
×
2511
                goto finish;
×
2512
        }
2513

2514
        /* This returns the first error we run into, but nevertheless tries to go on */
2515
        r = action(c, i, fd, path, &st, creation);
618✔
2516

2517
        if (S_ISDIR(st.st_mode)) {
618✔
2518
                _cleanup_closedir_ DIR *d = NULL;
200✔
2519

2520
                /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2521
                 * reading the directory content. */
2522
                d = opendir(FORMAT_PROC_FD_PATH(fd));
200✔
2523
                if (!d) {
200✔
2524
                        RET_GATHER(r, log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd)));
×
2525
                        goto finish;
×
2526
                }
2527

2528
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
1,018✔
2529
                        _cleanup_close_ int de_fd = -EBADF;
818✔
2530
                        _cleanup_free_ char *de_path = NULL;
818✔
2531

2532
                        if (dot_or_dot_dot(de->d_name))
818✔
2533
                                continue;
400✔
2534

2535
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
418✔
2536
                        if (de_fd < 0) {
418✔
2537
                                if (errno != ENOENT)
×
2538
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
×
2539
                                continue;
×
2540
                        }
2541

2542
                        de_path = path_join(path, de->d_name);
418✔
2543
                        if (!de_path) {
418✔
2544
                                r = log_oom();
×
2545
                                goto finish;
×
2546
                        }
2547

2548
                        /* Pass ownership of dirent fd over */
2549
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
418✔
2550
                }
2551
        }
2552

2553
finish:
418✔
2554
        safe_close(fd);
618✔
2555
        return r;
618✔
2556
}
2557

2558
static int glob_item(Context *c, Item *i, action_t action) {
5,902✔
2559
        _cleanup_strv_free_ char **paths = NULL;
5,902✔
2560
        int r;
5,902✔
2561

2562
        assert(c);
5,902✔
2563
        assert(i);
5,902✔
2564
        assert(action);
5,902✔
2565

2566
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
5,902✔
2567
        if (r == -ENOENT)
5,902✔
2568
                return 0;
2569
        if (r < 0)
2,857✔
2570
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2571

2572
        r = 0;
2,857✔
2573
        STRV_FOREACH(fn, paths)
5,721✔
2574
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2575
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
2,864✔
2576

2577
        return r;
2578
}
2579

2580
static int glob_item_recursively(
248✔
2581
                Context *c,
2582
                Item *i,
2583
                fdaction_t action) {
2584

2585
        _cleanup_strv_free_ char **paths = NULL;
248✔
2586
        int r;
248✔
2587

2588
        assert(c);
248✔
2589
        assert(i);
248✔
2590
        assert(action);
248✔
2591

2592
        r = safe_glob_full(i->path, GLOB_NOSORT|GLOB_BRACE, opendir_nomod, &paths);
248✔
2593
        if (r == -ENOENT)
248✔
2594
                return 0;
2595
        if (r < 0)
200✔
2596
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2597

2598
        r = 0;
200✔
2599
        STRV_FOREACH(fn, paths) {
400✔
2600
                _cleanup_close_ int fd = -EBADF;
200✔
2601

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

2606
                fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
200✔
2607
                if (fd < 0) {
200✔
2608
                        RET_GATHER(r, log_error_errno(errno, "Failed to open '%s': %m", *fn));
×
2609
                        continue;
×
2610
                }
2611

2612
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
200✔
2613
        }
2614

2615
        return r;
2616
}
2617

2618
static int rm_if_wrong_type_safe(
×
2619
                mode_t mode,
2620
                int parent_fd,
2621
                const struct stat *parent_st, /* Only used if follow_links below is true. */
2622
                const char *name,
2623
                int flags) {
2624
        _cleanup_free_ char *parent_name = NULL;
×
2625
        bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
×
2626
        struct stat st;
×
2627
        int r;
×
2628

2629
        assert(name);
×
2630
        assert((mode & ~S_IFMT) == 0);
×
2631
        assert(!follow_links || parent_st);
×
2632
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2633

2634
        if (mode == 0)
×
2635
                return 0;
2636

2637
        if (!filename_is_valid(name))
×
2638
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2639

2640
        r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2641
        if (r < 0) {
×
2642
                (void) fd_get_path(parent_fd, &parent_name);
×
2643
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
2644
                                      "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
2645
        }
2646

2647
        /* Fail before removing anything if this is an unsafe transition. */
2648
        if (follow_links && unsafe_transition(parent_st, &st)) {
×
2649
                (void) fd_get_path(parent_fd, &parent_name);
×
2650
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
×
2651
                                       "Unsafe transition from \"%s\" to \"%s\".", parent_name ?: "...", name);
2652
        }
2653

2654
        if ((st.st_mode & S_IFMT) == mode)
×
2655
                return 0;
2656

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

2660
        /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2661
         * target, so make sure it is identified as a link and not a directory. */
2662
        if (follow_links) {
×
2663
                r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2664
                if (r < 0)
×
2665
                        return log_error_errno(r, "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
×
2666
        }
2667

2668
        /* Do not remove mount points. */
2669
        r = is_mount_point_at(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
×
2670
        if (r < 0)
×
2671
                (void) log_warning_errno(r, "Failed to check if  \"%s/%s\" is a mount point: %m; continuing.",
×
2672
                                         parent_name ?: "...", name);
2673
        else if (r > 0)
×
2674
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
×
2675
                                "Not removing  \"%s/%s\" because it is a mount point.", parent_name ?: "...", name);
2676

2677
        log_action("Would remove", "Removing", "%s %s/%s", parent_name ?: "...", name);
×
2678
        if (!arg_dry_run) {
×
2679
                if ((st.st_mode & S_IFMT) == S_IFDIR) {
×
2680
                        _cleanup_close_ int child_fd = -EBADF;
×
2681

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

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

2690
                        r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2691
                } else
2692
                        r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2693
                if (r < 0)
×
2694
                        return log_error_errno(r, "Failed to remove \"%s/%s\": %m", parent_name ?: "...", name);
×
2695
        }
2696

2697
        /* This is covered by the log_notice "Wrong file type...".
2698
         * It is logged earlier because it gives context to other error messages that might follow. */
2699
        return -ENOENT;
2700
}
2701

2702
/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2703
static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
×
2704
        _cleanup_close_ int parent_fd = -EBADF;
×
2705
        struct stat parent_st;
×
2706
        size_t path_len;
×
2707
        int r;
×
2708

2709
        assert(path);
×
2710
        assert((child_mode & ~S_IFMT) == 0);
×
2711

2712
        path_len = strlen(path);
×
2713

2714
        if (!is_path(path))
×
2715
                /* rm_if_wrong_type_safe already logs errors. */
2716
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2717

2718
        if (child_mode != 0 && endswith(path, "/"))
×
2719
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2720
                                "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2721

2722
        /* Get the parent_fd and stat. */
2723
        parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
×
2724
        if (parent_fd < 0)
×
2725
                return log_error_errno(errno, "Failed to open root: %m");
×
2726

2727
        if (fstat(parent_fd, &parent_st) < 0)
×
2728
                return log_error_errno(errno, "Failed to stat root: %m");
×
2729

2730
        /* Check every parent directory in the path, except the last component */
2731
        for (const char *e = path;;) {
×
2732
                _cleanup_close_ int next_fd = -EBADF;
×
2733
                char t[path_len + 1];
×
2734
                const char *s;
×
2735

2736
                /* Find the start of the next path component. */
2737
                s = e + strspn(e, "/");
×
2738
                /* Find the end of the next path component. */
2739
                e = s + strcspn(s, "/");
×
2740

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

2744
                /* Is this the last component? If so, then check the type */
2745
                if (*e == 0)
×
2746
                        return rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2747

2748
                r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
×
2749
                /* Remove dangling symlinks. */
2750
                if (r == -ENOENT)
×
2751
                        r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2752
                if (r == -ENOENT) {
×
2753
                        if (!arg_dry_run) {
×
2754
                                WITH_UMASK(0000)
×
2755
                                        r = mkdirat_label(parent_fd, t, 0755);
×
2756
                                if (r < 0) {
×
2757
                                        _cleanup_free_ char *parent_name = NULL;
×
2758

2759
                                        (void) fd_get_path(parent_fd, &parent_name);
×
2760
                                        return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2761
                                }
2762
                        }
2763
                } else if (r < 0)
×
2764
                        /* rm_if_wrong_type_safe already logs errors. */
2765
                        return r;
2766

2767
                next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
×
2768
                if (next_fd < 0) {
×
2769
                        _cleanup_free_ char *parent_name = NULL;
×
2770

2771
                        (void) fd_get_path(parent_fd, &parent_name);
×
2772
                        return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2773
                }
2774
                r = RET_NERRNO(fstat(next_fd, &parent_st));
×
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 stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2780
                }
2781

2782
                close_and_replace(parent_fd, next_fd);
×
2783
        }
2784
}
2785

2786
static int mkdir_parents_item(Item *i, mode_t child_mode) {
16,348✔
2787
        int r;
16,348✔
2788

2789
        if (i->try_replace) {
16,348✔
2790
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2791
                if (r < 0 && r != -ENOENT)
×
2792
                        return r;
×
2793
        } else
2794
                WITH_UMASK(0000)
32,696✔
2795
                        if (!arg_dry_run)
16,348✔
2796
                                (void) mkdir_parents_label(i->path, 0755);
16,348✔
2797

2798
        return 0;
2799
}
2800

2801
static int create_item(Context *c, Item *i) {
23,327✔
2802
        int r;
23,327✔
2803

2804
        assert(c);
23,327✔
2805
        assert(i);
23,327✔
2806

2807
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
23,327✔
2808

2809
        switch (i->type) {
23,327✔
2810

2811
        case IGNORE_PATH:
2812
        case IGNORE_DIRECTORY_PATH:
2813
        case REMOVE_PATH:
2814
        case RECURSIVE_REMOVE_PATH:
2815
                return 0;
2816

2817
        case TRUNCATE_FILE:
1,023✔
2818
        case CREATE_FILE:
2819
                r = mkdir_parents_item(i, S_IFREG);
1,023✔
2820
                if (r < 0)
1,023✔
2821
                        return r;
2822

2823
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,023✔
2824
                        r = truncate_file(c, i, i->path);
247✔
2825
                else
2826
                        r = create_file(c, i, i->path);
776✔
2827
                if (r < 0)
1,023✔
2828
                        return r;
15✔
2829
                break;
2830

2831
        case COPY_FILES:
3,797✔
2832
                r = mkdir_parents_item(i, 0);
3,797✔
2833
                if (r < 0)
3,797✔
2834
                        return r;
2835

2836
                r = copy_files(c, i);
3,797✔
2837
                if (r < 0)
3,797✔
2838
                        return r;
×
2839
                break;
2840

2841
        case WRITE_FILE:
20✔
2842
                r = glob_item(c, i, write_one_file);
20✔
2843
                if (r < 0)
20✔
2844
                        return r;
×
2845

2846
                break;
2847

2848
        case CREATE_DIRECTORY:
7,287✔
2849
        case TRUNCATE_DIRECTORY:
2850
                r = mkdir_parents_item(i, S_IFDIR);
7,287✔
2851
                if (r < 0)
7,287✔
2852
                        return r;
2853

2854
                r = create_directory(c, i, i->path);
7,287✔
2855
                if (r < 0)
7,287✔
2856
                        return r;
2✔
2857
                break;
2858

2859
        case CREATE_SUBVOLUME:
861✔
2860
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
2861
        case CREATE_SUBVOLUME_NEW_QUOTA:
2862
                r = mkdir_parents_item(i, S_IFDIR);
861✔
2863
                if (r < 0)
861✔
2864
                        return r;
2865

2866
                r = create_subvolume(c, i, i->path);
861✔
2867
                if (r < 0)
861✔
2868
                        return r;
×
2869
                break;
2870

2871
        case EMPTY_DIRECTORY:
4✔
2872
                r = glob_item(c, i, empty_directory);
4✔
2873
                if (r < 0)
4✔
2874
                        return r;
×
2875
                break;
2876

2877
        case CREATE_FIFO:
4✔
2878
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2879
                if (r < 0)
4✔
2880
                        return r;
2881

2882
                r = create_fifo(c, i);
4✔
2883
                if (r < 0)
4✔
2884
                        return r;
×
2885
                break;
2886

2887
        case CREATE_SYMLINK:
1,482✔
2888
                r = mkdir_parents_item(i, S_IFLNK);
1,482✔
2889
                if (r < 0)
1,482✔
2890
                        return r;
2891

2892
                r = create_symlink(c, i);
1,482✔
2893
                if (r < 0)
1,482✔
2894
                        return r;
×
2895

2896
                break;
2897

2898
        case CREATE_BLOCK_DEVICE:
1,894✔
2899
        case CREATE_CHAR_DEVICE:
2900
                if (have_effective_cap(CAP_MKNOD) <= 0) {
1,894✔
2901
                        /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2902
                         * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2903

2904
                        log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
×
2905
                        return 0;
×
2906
                }
2907

2908
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,786✔
2909
                if (r < 0)
1,894✔
2910
                        return r;
2911

2912
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,786✔
2913
                if (r < 0)
1,894✔
2914
                        return r;
×
2915

2916
                break;
2917

2918
        case ADJUST_MODE:
4,019✔
2919
        case RELABEL_PATH:
2920
                r = glob_item(c, i, path_set_perms);
4,019✔
2921
                if (r < 0)
4,019✔
2922
                        return r;
×
2923
                break;
2924

2925
        case RECURSIVE_RELABEL_PATH:
125✔
2926
                r = glob_item_recursively(c, i, fd_set_perms);
125✔
2927
                if (r < 0)
125✔
2928
                        return r;
×
2929
                break;
2930

2931
        case SET_XATTR:
×
2932
                r = glob_item(c, i, path_set_xattrs);
×
2933
                if (r < 0)
×
2934
                        return r;
×
2935
                break;
2936

2937
        case RECURSIVE_SET_XATTR:
×
2938
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2939
                if (r < 0)
×
2940
                        return r;
×
2941
                break;
2942

2943
        case SET_ACL:
742✔
2944
                r = glob_item(c, i, path_set_acls);
742✔
2945
                if (r < 0)
742✔
2946
                        return r;
×
2947
                break;
2948

2949
        case RECURSIVE_SET_ACL:
123✔
2950
                r = glob_item_recursively(c, i, fd_set_acls);
123✔
2951
                if (r < 0)
123✔
2952
                        return r;
×
2953
                break;
2954

2955
        case SET_ATTRIBUTE:
369✔
2956
                r = glob_item(c, i, path_set_attribute);
369✔
2957
                if (r < 0)
369✔
2958
                        return r;
×
2959
                break;
2960

2961
        case RECURSIVE_SET_ATTRIBUTE:
×
2962
                r = glob_item_recursively(c, i, fd_set_attribute);
×
2963
                if (r < 0)
×
2964
                        return r;
×
2965
                break;
2966
        }
2967

2968
        return 0;
2969
}
2970

2971
static int remove_recursive(
493✔
2972
                Context *c,
2973
                Item *i,
2974
                const char *instance,
2975
                bool remove_instance) {
2976

2977
        _cleanup_closedir_ DIR *d = NULL;
493✔
2978
        struct statx sx;
493✔
2979
        bool mountpoint;
493✔
2980
        int r;
493✔
2981

2982
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
493✔
2983
        if (r < 0)
493✔
2984
                return r;
2985
        if (r == 0) {
493✔
2986
                if (remove_instance) {
483✔
2987
                        log_action("Would remove", "Removing", "%s file \"%s\".", instance);
13✔
2988
                        if (!arg_dry_run &&
14✔
2989
                            remove(instance) < 0 &&
5✔
2990
                            errno != ENOENT)
2✔
2991
                                return log_error_errno(errno, "rm %s: %m", instance);
×
2992
                }
2993
                return 0;
483✔
2994
        }
2995

2996
        r = dir_cleanup(c, i, instance, d,
20✔
2997
                        /* self_atime_nsec= */ NSEC_INFINITY,
2998
                        /* self_mtime_nsec= */ NSEC_INFINITY,
2999
                        /* cutoff_nsec= */ NSEC_INFINITY,
3000
                        sx.stx_dev_major, sx.stx_dev_minor,
10✔
3001
                        mountpoint,
3002
                        MAX_DEPTH,
3003
                        /* keep_this_level= */ false,
3004
                        /* age_by_file= */ 0,
3005
                        /* age_by_dir= */ 0);
3006
        if (r < 0)
10✔
3007
                return r;
3008

3009
        if (remove_instance) {
10✔
3010
                log_action("Would remove", "Removing", "%s directory \"%s\".", instance);
11✔
3011
                if (!arg_dry_run) {
9✔
3012
                        r = RET_NERRNO(rmdir(instance));
496✔
3013
                        if (r < 0) {
3✔
3014
                                bool fatal = !IN_SET(r, -ENOENT, -ENOTEMPTY);
3✔
3015
                                log_full_errno(fatal ? LOG_ERR : LOG_DEBUG, r, "Failed to remove %s: %m", instance);
3✔
3016
                                if (fatal)
3✔
3017
                                        return r;
×
3018
                        }
3019
                }
3020
        }
3021
        return 0;
3022
}
3023

3024
static int purge_item_instance(Context *c, Item *i, const char *instance, CreationMode creation) {
10✔
3025
        return remove_recursive(c, i, instance, /* remove_instance= */ true);
10✔
3026
}
3027

3028
static int purge_item(Context *c, Item *i) {
15✔
3029
        assert(i);
15✔
3030

3031
        if (!needs_purge(i->type))
15✔
3032
                return 0;
3033

3034
        if (!i->purge)
15✔
3035
                return 0;
3036

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

3039
        if (needs_glob(i->type))
10✔
3040
                return glob_item(c, i, purge_item_instance);
×
3041

3042
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3043
}
3044

3045
static int remove_item_instance(
16✔
3046
                Context *c,
3047
                Item *i,
3048
                const char *instance,
3049
                CreationMode creation) {
3050

3051
        assert(c);
16✔
3052
        assert(i);
16✔
3053

3054
        switch (i->type) {
16✔
3055

3056
        case REMOVE_PATH:
3057
                log_action("Would remove", "Removing", "%s \"%s\".", instance);
8✔
3058
                if (!arg_dry_run &&
15✔
3059
                    remove(instance) < 0 &&
7✔
3060
                    errno != ENOENT)
×
3061
                        return log_error_errno(errno, "rm %s: %m", instance);
×
3062

3063
                return 0;
3064

3065
        case RECURSIVE_REMOVE_PATH:
8✔
3066
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3067

3068
        default:
×
3069
                assert_not_reached();
×
3070
        }
3071
}
3072

3073
static int remove_item(Context *c, Item *i) {
17,856✔
3074
        assert(c);
17,856✔
3075
        assert(i);
17,856✔
3076

3077
        log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
17,856✔
3078

3079
        switch (i->type) {
17,856✔
3080

3081
        case TRUNCATE_DIRECTORY:
475✔
3082
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
475✔
3083

3084
        case REMOVE_PATH:
726✔
3085
        case RECURSIVE_REMOVE_PATH:
3086
                return glob_item(c, i, remove_item_instance);
726✔
3087

3088
        default:
3089
                return 0;
3090
        }
3091
}
3092

3093
static char *age_by_to_string(AgeBy ab, bool is_dir) {
44✔
3094
        static const char ab_map[] = { 'a', 'b', 'c', 'm' };
44✔
3095
        size_t j = 0;
44✔
3096
        char *ret;
44✔
3097

3098
        ret = new(char, ELEMENTSOF(ab_map) + 1);
44✔
3099
        if (!ret)
44✔
3100
                return NULL;
3101

3102
        for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
220✔
3103
                if (BIT_SET(ab, i))
176✔
3104
                        ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
110✔
3105

3106
        ret[j] = 0;
44✔
3107
        return ret;
44✔
3108
}
3109

3110
static int clean_item_instance(
50✔
3111
                Context *c,
3112
                Item *i,
3113
                const char* instance,
3114
                CreationMode creation) {
3115

3116
        assert(i);
50✔
3117

3118
        if (!i->age_set)
50✔
3119
                return 0;
50✔
3120

3121
        usec_t n = now(CLOCK_REALTIME);
38✔
3122
        if (n < i->age)
38✔
3123
                return 0;
3124

3125
        usec_t cutoff = n - i->age;
38✔
3126

3127
        _cleanup_closedir_ DIR *d = NULL;
50✔
3128
        struct statx sx;
38✔
3129
        bool mountpoint;
38✔
3130
        int r;
38✔
3131

3132
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
38✔
3133
        if (r <= 0)
38✔
3134
                return r;
3135

3136
        if (DEBUG_LOGGING) {
34✔
3137
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
22✔
3138

3139
                ab_f = age_by_to_string(i->age_by_file, false);
22✔
3140
                if (!ab_f)
22✔
3141
                        return log_oom();
×
3142

3143
                ab_d = age_by_to_string(i->age_by_dir, true);
22✔
3144
                if (!ab_d)
22✔
3145
                        return log_oom();
×
3146

3147
                log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
44✔
3148
                          mountpoint ? "mount point" : "directory",
3149
                          instance,
3150
                          FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
3151
                          ab_f, ab_d);
3152
        }
3153

3154
        return dir_cleanup(c, i, instance, d,
34✔
3155
                           statx_timestamp_load_nsec(&sx.stx_atime),
3156
                           statx_timestamp_load_nsec(&sx.stx_mtime),
3157
                           cutoff * NSEC_PER_USEC,
34✔
3158
                           sx.stx_dev_major, sx.stx_dev_minor,
34✔
3159
                           mountpoint,
3160
                           MAX_DEPTH, i->keep_first_level,
34✔
3161
                           i->age_by_file, i->age_by_dir);
3162
}
3163

3164
static int clean_item(Context *c, Item *i) {
50✔
3165
        assert(c);
50✔
3166
        assert(i);
50✔
3167

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

3170
        switch (i->type) {
50✔
3171

3172
        case CREATE_DIRECTORY:
24✔
3173
        case TRUNCATE_DIRECTORY:
3174
        case CREATE_SUBVOLUME:
3175
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3176
        case CREATE_SUBVOLUME_NEW_QUOTA:
3177
        case COPY_FILES:
3178
                clean_item_instance(c, i, i->path, CREATION_EXISTING);
24✔
3179
                return 0;
24✔
3180

3181
        case EMPTY_DIRECTORY:
22✔
3182
        case IGNORE_PATH:
3183
        case IGNORE_DIRECTORY_PATH:
3184
                return glob_item(c, i, clean_item_instance);
22✔
3185

3186
        default:
3187
                return 0;
3188
        }
3189
}
3190

3191
static int process_item(
76,084✔
3192
                Context *c,
3193
                Item *i,
3194
                OperationMask operation) {
3195

3196
        OperationMask todo;
76,084✔
3197
        _cleanup_free_ char *_path = NULL;
76,084✔
3198
        const char *path;
76,084✔
3199
        int r;
76,084✔
3200

3201
        assert(c);
76,084✔
3202
        assert(i);
76,084✔
3203

3204
        todo = operation & ~i->done;
76,084✔
3205
        if (todo == 0) /* Everything already done? */
76,084✔
3206
                return 0;
3207

3208
        i->done |= operation;
41,248✔
3209

3210
        path = i->path;
41,248✔
3211
        if (string_is_glob(path)) {
41,248✔
3212
                /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3213
                 * for the non-glob part. */
3214

3215
                r = glob_non_glob_prefix(path, &_path);
3,355✔
3216
                if (r < 0 && r != -ENOENT)
3,355✔
3217
                        return log_debug_errno(r, "Failed to deglob path: %m");
×
3218
                if (r >= 0)
3,355✔
3219
                        path = _path;
3,355✔
3220
        }
3221

3222
        r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
41,248✔
3223
        if (r == -EREMOTE) {
41,248✔
3224
                log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
×
3225
                return 0;
×
3226
        }
3227
        if (r < 0)
41,248✔
3228
                log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
×
3229

3230
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
41,248✔
3231
        /* Failure can only be tolerated for create */
3232
        if (i->allow_failure)
41,248✔
3233
                r = 0;
964✔
3234

3235
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
41,248✔
3236
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
41,248✔
3237
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
41,248✔
3238

3239
        return r;
3240
}
3241

3242
static int process_item_array(
69,933✔
3243
                Context *c,
3244
                ItemArray *array,
3245
                OperationMask operation) {
3246

3247
        int r = 0;
69,933✔
3248

3249
        assert(c);
69,933✔
3250
        assert(array);
69,933✔
3251

3252
        /* Create any parent first. */
3253
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
69,933✔
3254
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
16,437✔
3255

3256
        /* Clean up all children first */
3257
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
69,933✔
3258
                ItemArray *cc;
6,045✔
3259

3260
                SET_FOREACH(cc, array->children)
20,827✔
3261
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
14,782✔
3262
        }
3263

3264
        FOREACH_ARRAY(item, array->items, array->n_items)
146,017✔
3265
                RET_GATHER(r, process_item(c, item, operation));
76,084✔
3266

3267
        return r;
69,933✔
3268
}
3269

3270
static void item_free_contents(Item *i) {
87,404✔
3271
        assert(i);
87,404✔
3272
        free(i->path);
87,404✔
3273
        free(i->argument);
87,404✔
3274
        free(i->binary_argument);
87,404✔
3275
        strv_free(i->xattrs);
87,404✔
3276

3277
#if HAVE_ACL
3278
        if (i->acl_access)
87,404✔
3279
                sym_acl_free(i->acl_access);
1,436✔
3280

3281
        if (i->acl_access_exec)
87,404✔
3282
                sym_acl_free(i->acl_access_exec);
363✔
3283

3284
        if (i->acl_default)
87,404✔
3285
                sym_acl_free(i->acl_default);
2,154✔
3286
#endif
3287
}
87,404✔
3288

3289
static ItemArray* item_array_free(ItemArray *a) {
22,057✔
3290
        if (!a)
22,057✔
3291
                return NULL;
3292

3293
        FOREACH_ARRAY(item, a->items, a->n_items)
45,468✔
3294
                item_free_contents(item);
23,411✔
3295

3296
        set_free(a->children);
22,057✔
3297
        free(a->items);
22,057✔
3298
        return mfree(a);
22,057✔
3299
}
3300

3301
static int item_compare(const Item *a, const Item *b) {
1,856✔
3302
        /* Make sure that the ownership taking item is put first, so
3303
         * that we first create the node, and then can adjust it */
3304

3305
        if (takes_ownership(a->type) && !takes_ownership(b->type))
1,856✔
3306
                return -1;
3307
        if (!takes_ownership(a->type) && takes_ownership(b->type))
1,856✔
3308
                return 1;
3309

3310
        return CMP(a->type, b->type);
1,856✔
3311
}
3312

3313
static bool item_compatible(const Item *a, const Item *b) {
1,611✔
3314
        assert(a);
1,611✔
3315
        assert(b);
1,611✔
3316
        assert(streq(a->path, b->path));
1,611✔
3317

3318
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,611✔
3319
                /* check if the items are the same */
3320
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
504✔
3321
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
485✔
3322

3323
                        a->uid_set == b->uid_set &&
485✔
3324
                        a->uid == b->uid &&
485✔
3325
                        a->uid_only_create == b->uid_only_create &&
485✔
3326

3327
                        a->gid_set == b->gid_set &&
485✔
3328
                        a->gid == b->gid &&
485✔
3329
                        a->gid_only_create == b->gid_only_create &&
485✔
3330

3331
                        a->mode_set == b->mode_set &&
485✔
3332
                        a->mode == b->mode &&
485✔
3333
                        a->mode_only_create == b->mode_only_create &&
485✔
3334

3335
                        a->age_set == b->age_set &&
485✔
3336
                        a->age == b->age &&
485✔
3337

3338
                        a->age_by_file == b->age_by_file &&
485✔
3339
                        a->age_by_dir == b->age_by_dir &&
485✔
3340

3341
                        a->mask_perms == b->mask_perms &&
485✔
3342

3343
                        a->keep_first_level == b->keep_first_level &&
1,493✔
3344

3345
                        a->major_minor == b->major_minor;
485✔
3346

3347
        return true;
3348
}
3349

3350
static bool should_include_path(const char *path) {
63,902✔
3351
        STRV_FOREACH(prefix, arg_exclude_prefixes)
82,547✔
3352
                if (path_startswith(path, *prefix)) {
20,967✔
3353
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,322✔
3354
                                  path, *prefix);
3355
                        return false;
2,322✔
3356
                }
3357

3358
        STRV_FOREACH(prefix, arg_include_prefixes)
98,870✔
3359
                if (path_startswith(path, *prefix)) {
41,934✔
3360
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
4,644✔
3361
                        return true;
4,644✔
3362
                }
3363

3364
        /* no matches, so we should include this path only if we have no allow list at all */
3365
        if (strv_isempty(arg_include_prefixes))
56,936✔
3366
                return true;
3367

3368
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
37,290✔
3369
        return false;
3370
}
3371

3372
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
24,290✔
3373
        int r;
24,290✔
3374

3375
        assert(i);
24,290✔
3376

3377
        if (!i->argument)
24,290✔
3378
                return 0;
3379

3380
        switch (i->type) {
5,775✔
3381
        case COPY_FILES:
2,646✔
3382
        case CREATE_SYMLINK:
3383
        case CREATE_FILE:
3384
        case TRUNCATE_FILE:
3385
        case WRITE_FILE: {
3386
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2,646✔
3387
                ssize_t l;
2,646✔
3388

3389
                l = cunescape(i->argument, 0, &unescaped);
2,646✔
3390
                if (l < 0)
2,646✔
3391
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3392

3393
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
2,646✔
3394
                if (r < 0)
2,646✔
3395
                        return r;
3396

3397
                return free_and_replace(i->argument, resolved);
2,646✔
3398
        }
3399
        case SET_XATTR:
×
3400
        case RECURSIVE_SET_XATTR:
3401
                STRV_FOREACH(xattr, i->xattrs) {
×
3402
                        _cleanup_free_ char *resolved = NULL;
×
3403

3404
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3405
                        if (r < 0)
×
3406
                                return r;
×
3407

3408
                        free_and_replace(*xattr, resolved);
×
3409
                }
3410
                return 0;
3411

3412
        default:
3413
                return 0;
3414
        }
3415
}
3416

3417
static int patch_var_run(const char *fname, unsigned line, char **path) {
63,903✔
3418
        const char *k;
63,903✔
3419
        char *n;
63,903✔
3420

3421
        assert(path);
63,903✔
3422
        assert(*path);
63,903✔
3423

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

3435
        k = path_startswith(*path, "/var/run/");
63,903✔
3436
        if (isempty(k)) /* Don't complain about paths other than under /var/run,
63,903✔
3437
                         * and not about /var/run itself either. */
3438
                return 0;
63,903✔
3439

3440
        n = path_join("/run", k);
×
3441
        if (!n)
×
3442
                return log_oom();
×
3443

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

3452
        free_and_replace(*path, n);
×
3453

3454
        return 0;
×
3455
}
3456

3457
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
8,752✔
3458
        int r;
8,752✔
3459

3460
        assert(user);
8,752✔
3461
        assert(ret_uid);
8,752✔
3462

3463
        /* First: parse as numeric UID string */
3464
        r = parse_uid(user, ret_uid);
8,752✔
3465
        if (r >= 0)
8,752✔
3466
                return r;
3467

3468
        /* Second: pass to NSS if we are running "online" */
3469
        if (!arg_root)
8,738✔
3470
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
8,738✔
3471

3472
        /* Third, synthesize "root" unconditionally */
3473
        if (streq(user, "root")) {
×
3474
                *ret_uid = 0;
×
3475
                return 0;
×
3476
        }
3477

3478
        /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3479
        return name_to_uid_offline(arg_root, user, ret_uid, cache);
×
3480
}
3481

3482
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
10,198✔
3483
        int r;
10,198✔
3484

3485
        assert(group);
10,198✔
3486
        assert(ret_gid);
10,198✔
3487

3488
        /* First: parse as numeric GID string */
3489
        r = parse_gid(group, ret_gid);
10,198✔
3490
        if (r >= 0)
10,198✔
3491
                return r;
3492

3493
        /* Second: pass to NSS if we are running "online" */
3494
        if (!arg_root)
10,184✔
3495
                return get_group_creds(&group, ret_gid, 0);
10,184✔
3496

3497
        /* Third, synthesize "root" unconditionally */
3498
        if (streq(group, "root")) {
×
3499
                *ret_gid = 0;
×
3500
                return 0;
×
3501
        }
3502

3503
        /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3504
        return name_to_gid_offline(arg_root, group, ret_gid, cache);
×
3505
}
3506

3507
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
151✔
3508
        AgeBy ab_f = 0, ab_d = 0;
151✔
3509

3510
        static const struct {
151✔
3511
                char age_by_chr;
3512
                AgeBy age_by_flag;
3513
        } age_by_types[] = {
3514
                { 'a', AGE_BY_ATIME },
3515
                { 'b', AGE_BY_BTIME },
3516
                { 'c', AGE_BY_CTIME },
3517
                { 'm', AGE_BY_MTIME },
3518
        };
3519

3520
        assert(age_by_str);
151✔
3521
        assert(item);
151✔
3522

3523
        if (isempty(age_by_str))
151✔
3524
                return -EINVAL;
3525

3526
        for (const char *s = age_by_str; *s != 0; s++) {
321✔
3527
                size_t i;
176✔
3528

3529
                /* Ignore whitespace. */
3530
                if (strchr(WHITESPACE, *s))
176✔
3531
                        continue;
11✔
3532

3533
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
227✔
3534
                        /* Check lower-case for files, upper-case for directories. */
3535
                        if (*s == age_by_types[i].age_by_chr) {
224✔
3536
                                ab_f |= age_by_types[i].age_by_flag;
152✔
3537
                                break;
152✔
3538
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3539
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3540
                                break;
10✔
3541
                        }
3542
                }
3543

3544
                /* Invalid character. */
3545
                if (i >= ELEMENTSOF(age_by_types))
3546
                        return -EINVAL;
3547
        }
3548

3549
        /* No match. */
3550
        if (ab_f == 0 && ab_d == 0)
145✔
3551
                return -EINVAL;
3552

3553
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
144✔
3554
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
144✔
3555

3556
        return 0;
144✔
3557
}
3558

3559
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
1,357✔
3560
        assert(existing);
1,357✔
3561
        assert(i);
1,357✔
3562

3563
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
2,965✔
3564
                if (item_compatible(e, i))
1,611✔
3565
                        continue;
1,592✔
3566

3567
                /* Only multiple 'w+' lines for the same path are allowed. */
3568
                if (e->type != WRITE_FILE || !e->append_or_force ||
19✔
3569
                    i->type != WRITE_FILE || !i->append_or_force)
16✔
3570
                        return true;
3571
        }
3572

3573
        return false;
3574
}
3575

3576
static int parse_line(
63,993✔
3577
                const char *fname,
3578
                unsigned line,
3579
                const char *buffer,
3580
                bool *invalid_config,
3581
                void *context) {
3582

3583
        Context *c = ASSERT_PTR(context);
63,993✔
3584
        _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
63,993✔
3585
        _cleanup_(item_free_contents) Item i = {
×
3586
                /* The "age-by" argument considers all file timestamp types by default. */
3587
                .age_by_file = AGE_BY_DEFAULT_FILE,
3588
                .age_by_dir = AGE_BY_DEFAULT_DIR,
3589
        };
3590
        ItemArray *existing;
63,993✔
3591
        OrderedHashmap *h;
63,993✔
3592
        bool append_or_force = false, boot = false, allow_failure = false, try_replace = false,
63,993✔
3593
                unbase64 = false, from_cred = false, missing_user_or_group = false, purge = false,
63,993✔
3594
                ignore_if_target_missing = false;
63,993✔
3595
        int r;
63,993✔
3596

3597
        assert(fname);
63,993✔
3598
        assert(line >= 1);
63,993✔
3599
        assert(buffer);
63,993✔
3600

3601
        const Specifier specifier_table[] = {
63,993✔
3602
                { 'h', specifier_user_home,       NULL },
3603

3604
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3605
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3606
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3607
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3608

3609
                COMMON_SYSTEM_SPECIFIERS,
3610
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
63,993✔
3611
                COMMON_TMP_SPECIFIERS,
3612
                {}
3613
        };
3614

3615
        r = extract_many_words(
63,993✔
3616
                        &buffer,
3617
                        NULL,
3618
                        EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE,
3619
                        &action,
3620
                        &path,
3621
                        &mode,
3622
                        &user,
3623
                        &group,
3624
                        &age);
3625
        if (r < 0) {
63,993✔
3626
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3627
                        /* invalid quoting and such or an unknown specifier */
3628
                        *invalid_config = true;
×
3629
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
×
3630
        } else if (r < 2) {
63,993✔
3631
                *invalid_config = true;
×
3632
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
×
3633
        }
3634

3635
        if (!empty_or_dash(buffer)) {
63,993✔
3636
                i.argument = strdup(buffer);
14,048✔
3637
                if (!i.argument)
14,048✔
3638
                        return log_oom();
×
3639
        }
3640

3641
        if (isempty(action)) {
63,993✔
3642
                *invalid_config = true;
×
3643
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3644
                                  "Command too short '%s'.", action);
3645
        }
3646

3647
        for (int pos = 1; action[pos]; pos++)
84,098✔
3648
                if (action[pos] == '!' && !boot)
20,105✔
3649
                        boot = true;
3650
                else if (action[pos] == '+' && !append_or_force)
10,808✔
3651
                        append_or_force = true;
3652
                else if (action[pos] == '-' && !allow_failure)
7,194✔
3653
                        allow_failure = true;
3654
                else if (action[pos] == '=' && !try_replace)
5,758✔
3655
                        try_replace = true;
3656
                else if (action[pos] == '~' && !unbase64)
5,758✔
3657
                        unbase64 = true;
3658
                else if (action[pos] == '^' && !from_cred)
5,758✔
3659
                        from_cred = true;
3660
                else if (action[pos] == '$' && !purge)
4,322✔
3661
                        purge = true;
3662
                else if (action[pos] == '?' && !ignore_if_target_missing)
2✔
3663
                        ignore_if_target_missing = true;
3664
                else {
3665
                        *invalid_config = true;
×
3666
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3667
                                          "Unknown modifiers in command: %s", action);
3668
                }
3669

3670
        if (boot && !arg_boot) {
63,993✔
3671
                log_syntax(NULL, LOG_DEBUG, fname, line, 0,
90✔
3672
                           "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3673
                return 0;
90✔
3674
        }
3675

3676
        i.type = action[0];
63,903✔
3677
        i.append_or_force = append_or_force;
63,903✔
3678
        i.allow_failure = allow_failure;
63,903✔
3679
        i.try_replace = try_replace;
63,903✔
3680
        i.purge = purge;
63,903✔
3681
        i.ignore_if_target_missing = ignore_if_target_missing;
63,903✔
3682

3683
        r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
63,903✔
3684
        if (ERRNO_IS_NEG_NOINFO(r))
63,903✔
3685
                return log_unresolvable_specifier(fname, line);
×
3686
        if (r < 0) {
63,903✔
3687
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3688
                        *invalid_config = true;
×
3689
                return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3690
                                  "Failed to replace specifiers in '%s': %m", path);
3691
        }
3692

3693
        r = patch_var_run(fname, line, &i.path);
63,903✔
3694
        if (r < 0)
63,903✔
3695
                return r;
3696

3697
        if (!path_is_absolute(i.path)) {
63,903✔
3698
                *invalid_config = true;
×
3699
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3700
                                  "Path '%s' not absolute.", i.path);
3701
        }
3702

3703
        path_simplify(i.path);
63,903✔
3704

3705
        switch (i.type) {
63,903✔
3706

3707
        case CREATE_DIRECTORY:
36,581✔
3708
        case CREATE_SUBVOLUME:
3709
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3710
        case CREATE_SUBVOLUME_NEW_QUOTA:
3711
        case EMPTY_DIRECTORY:
3712
        case TRUNCATE_DIRECTORY:
3713
        case CREATE_FIFO:
3714
        case IGNORE_PATH:
3715
        case IGNORE_DIRECTORY_PATH:
3716
        case REMOVE_PATH:
3717
        case RECURSIVE_REMOVE_PATH:
3718
        case ADJUST_MODE:
3719
        case RELABEL_PATH:
3720
        case RECURSIVE_RELABEL_PATH:
3721
                if (i.argument)
36,581✔
3722
                        log_syntax(NULL, LOG_WARNING, fname, line, 0,
1✔
3723
                                   "%c lines don't take argument fields, ignoring.", (char) i.type);
3724
                break;
3725

3726
        case CREATE_FILE:
3727
        case TRUNCATE_FILE:
3728
                break;
3729

3730
        case CREATE_SYMLINK:
4,317✔
3731
                if (unbase64) {
4,317✔
3732
                        *invalid_config = true;
×
3733
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3734
                                          "base64 decoding not supported for symlink targets.");
3735
                }
3736
                break;
3737

3738
        case WRITE_FILE:
21✔
3739
                if (!i.argument) {
21✔
3740
                        *invalid_config = true;
1✔
3741
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1✔
3742
                                          "Write file requires argument.");
3743
                }
3744
                break;
3745

3746
        case COPY_FILES:
12,550✔
3747
                if (unbase64) {
12,550✔
3748
                        *invalid_config = true;
×
3749
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3750
                                          "base64 decoding not supported for copy sources.");
3751
                }
3752
                break;
3753

3754
        case CREATE_CHAR_DEVICE:
2,839✔
3755
        case CREATE_BLOCK_DEVICE:
3756
                if (unbase64) {
2,839✔
3757
                        *invalid_config = true;
×
3758
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3759
                                          "base64 decoding not supported for device node creation.");
3760
                }
3761

3762
                if (!i.argument) {
2,839✔
3763
                        *invalid_config = true;
×
3764
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3765
                                          "Device file requires argument.");
3766
                }
3767

3768
                r = parse_devnum(i.argument, &i.major_minor);
2,839✔
3769
                if (r < 0) {
2,839✔
3770
                        *invalid_config = true;
×
3771
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3772
                                          "Can't parse device file major/minor '%s'.", i.argument);
3773
                }
3774

3775
                break;
3776

3777
        case SET_XATTR:
×
3778
        case RECURSIVE_SET_XATTR:
3779
                if (unbase64) {
×
3780
                        *invalid_config = true;
×
3781
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3782
                                          "base64 decoding not supported for extended attributes.");
3783
                }
3784
                if (!i.argument) {
×
3785
                        *invalid_config = true;
×
3786
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3787
                                          "Set extended attribute requires argument.");
3788
                }
3789
                r = parse_xattrs_from_arg(&i);
×
3790
                if (r < 0)
×
3791
                        return r;
3792
                break;
3793

3794
        case SET_ACL:
2,517✔
3795
        case RECURSIVE_SET_ACL:
3796
                if (unbase64) {
2,517✔
3797
                        *invalid_config = true;
×
3798
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3799
                                          "base64 decoding not supported for ACLs.");
3800
                }
3801
                if (!i.argument) {
2,517✔
3802
                        *invalid_config = true;
×
3803
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3804
                                          "Set ACLs requires argument.");
3805
                }
3806
                r = parse_acls_from_arg(&i);
2,517✔
3807
                if (r < 0)
2,517✔
3808
                        return r;
3809
                break;
3810

3811
        case SET_ATTRIBUTE:
1,077✔
3812
        case RECURSIVE_SET_ATTRIBUTE:
3813
                if (unbase64) {
1,077✔
3814
                        *invalid_config = true;
×
3815
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3816
                                          "base64 decoding not supported for file attributes.");
3817
                }
3818
                if (!i.argument) {
1,077✔
3819
                        *invalid_config = true;
×
3820
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3821
                                          "Set file attribute requires argument.");
3822
                }
3823
                r = parse_attribute_from_arg(&i);
1,077✔
3824
                if (IN_SET(r, -EINVAL, -EBADSLT))
1,077✔
3825
                        *invalid_config = true;
×
3826
                if (r < 0)
1,077✔
3827
                        return r;
3828
                break;
3829

3830
        default:
×
3831
                *invalid_config = true;
×
3832
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3833
                                  "Unknown command type '%c'.", (char) i.type);
3834
        }
3835

3836
        if (i.purge && !needs_purge(i.type)) {
63,902✔
3837
                *invalid_config = true;
×
3838
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3839
                                  "Purge flag '$' combined with line type '%c' which does not support purging.", (char) i.type);
3840
        }
3841

3842
        if (i.ignore_if_target_missing && !supports_ignore_if_target_missing(i.type)) {
63,902✔
3843
                *invalid_config = true;
×
3844
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3845
                                  "Modifier '?' combined with line type '%c' which does not support this modifier.", (char) i.type);
3846
        }
3847

3848
        if (!should_include_path(i.path))
63,902✔
3849
                return 0;
3850

3851
        if (!unbase64) {
24,290✔
3852
                /* Do specifier expansion except if base64 mode is enabled */
3853
                r = specifier_expansion_from_arg(specifier_table, &i);
24,290✔
3854
                if (ERRNO_IS_NEG_NOINFO(r))
24,290✔
3855
                        return log_unresolvable_specifier(fname, line);
×
3856
                if (r < 0) {
24,290✔
3857
                        if (IN_SET(r, -EINVAL, -EBADSLT))
×
3858
                                *invalid_config = true;
×
3859
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3860
                                          "Failed to substitute specifiers in argument: %m");
3861
                }
3862
        }
3863

3864
        switch (i.type) {
24,290✔
3865
        case CREATE_SYMLINK:
1,485✔
3866
                if (!i.argument) {
1,485✔
3867
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3868
                        if (!i.argument)
2✔
3869
                                return log_oom();
×
3870
                }
3871

3872
                break;
3873

3874
        case COPY_FILES:
4,290✔
3875
                if (!i.argument) {
4,290✔
3876
                        i.argument = path_join("/usr/share/factory", i.path);
3,789✔
3877
                        if (!i.argument)
3,789✔
3878
                                return log_oom();
×
3879
                } else if (!path_is_absolute(i.argument)) {
501✔
3880
                        *invalid_config = true;
×
3881
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3882
                                          "Source path '%s' is not absolute.", i.argument);
3883

3884
                }
3885

3886
                if (!empty_or_root(arg_root)) {
4,290✔
3887
                        char *p;
1✔
3888

3889
                        p = path_join(arg_root, i.argument);
1✔
3890
                        if (!p)
1✔
3891
                                return log_oom();
×
3892
                        free_and_replace(i.argument, p);
1✔
3893
                }
3894

3895
                path_simplify(i.argument);
4,290✔
3896

3897
                if (access_nofollow(i.argument, F_OK) == -ENOENT) {
4,290✔
3898
                        /* Silently skip over lines where the source file is missing. */
3899
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
493✔
3900
                                   "Copy source path '%s' does not exist, skipping line.", i.argument);
3901
                        return 0;
493✔
3902
                }
3903

3904
                break;
3905

3906
        default:
23,797✔
3907
                ;
23,797✔
3908
        }
3909

3910
        if (from_cred) {
23,797✔
3911
                if (!i.argument)
492✔
3912
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3913
                                          "Reading from credential requested, but no credential name specified.");
3914
                if (!credential_name_valid(i.argument))
492✔
3915
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3916
                                          "Credential name not valid: %s", i.argument);
3917

3918
                r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
492✔
3919
                if (IN_SET(r, -ENXIO, -ENOENT)) {
492✔
3920
                        /* Silently skip over lines that have no credentials passed */
3921
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
374✔
3922
                                   "Credential '%s' not specified, skipping line.", i.argument);
3923
                        return 0;
374✔
3924
                }
3925
                if (r < 0)
118✔
3926
                        return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
×
3927
        }
3928

3929
        /* If base64 decoding is requested, do so now */
3930
        if (unbase64 && item_binary_argument(&i)) {
23,423✔
3931
                _cleanup_free_ void *data = NULL;
×
3932
                size_t data_size = 0;
×
3933

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

3939
                free_and_replace(i.binary_argument, data);
×
3940
                i.binary_argument_size = data_size;
×
3941
        }
3942

3943
        if (!empty_or_root(arg_root)) {
23,423✔
3944
                char *p;
14✔
3945

3946
                p = path_join(arg_root, i.path);
14✔
3947
                if (!p)
14✔
3948
                        return log_oom();
63,993✔
3949
                free_and_replace(i.path, p);
14✔
3950
        }
3951

3952
        if (!empty_or_dash(user)) {
23,423✔
3953
                const char *u;
8,752✔
3954

3955
                u = startswith(user, ":");
8,752✔
3956
                if (u)
8,752✔
3957
                        i.uid_only_create = true;
4✔
3958
                else
3959
                        u = user;
3960

3961
                r = find_uid(u, &i.uid, &c->uid_cache);
8,752✔
3962
                if (r == -ESRCH && arg_graceful) {
8,752✔
3963
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3964
                                   "%s: user '%s' not found, not adjusting ownership.", i.path, u);
3965
                        missing_user_or_group = true;
3966
                } else if (r < 0) {
8,752✔
3967
                        *invalid_config = true;
×
3968
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3969
                                          "Failed to resolve user '%s': %s", u, STRERROR_USER(r));
3970
                } else
3971
                        i.uid_set = true;
8,752✔
3972
        }
3973

3974
        if (!empty_or_dash(group)) {
23,423✔
3975
                const char *g;
10,198✔
3976

3977
                g = startswith(group, ":");
10,198✔
3978
                if (g)
10,198✔
3979
                        i.gid_only_create = true;
368✔
3980
                else
3981
                        g = group;
3982

3983
                r = find_gid(g, &i.gid, &c->gid_cache);
10,198✔
3984
                if (r == -ESRCH && arg_graceful) {
10,198✔
3985
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3986
                                   "%s: group '%s' not found, not adjusting ownership.", i.path, g);
3987
                        missing_user_or_group = true;
3988
                } else if (r < 0) {
10,198✔
3989
                        *invalid_config = true;
×
3990
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3991
                                          "Failed to resolve group '%s': %s", g, STRERROR_GROUP(r));
3992
                } else
3993
                        i.gid_set = true;
10,198✔
3994
        }
3995

3996
        if (!empty_or_dash(mode)) {
23,423✔
3997
                const char *mm;
3998
                unsigned m;
3999

4000
                for (mm = mode;; mm++)
491✔
4001
                        if (*mm == '~')
15,439✔
4002
                                i.mask_perms = true;
123✔
4003
                        else if (*mm == ':')
15,316✔
4004
                                i.mode_only_create = true;
368✔
4005
                        else
4006
                                break;
4007

4008
                r = parse_mode(mm, &m);
14,948✔
4009
                if (r < 0) {
14,948✔
4010
                        *invalid_config = true;
×
4011
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
×
4012
                }
4013

4014
                i.mode = m;
14,948✔
4015
                i.mode_set = true;
14,948✔
4016
        } else
4017
                i.mode = IN_SET(i.type,
8,475✔
4018
                                CREATE_DIRECTORY,
4019
                                TRUNCATE_DIRECTORY,
4020
                                CREATE_SUBVOLUME,
4021
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4022
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4023

4024
        if (missing_user_or_group && (i.mode & ~0777) != 0) {
23,423✔
4025
                /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
4026
                mode_t adjusted = i.mode & 0777;
×
4027
                log_syntax(NULL, LOG_INFO, fname, line, 0,
×
4028
                           "Changing mode 0%o to 0%o because of changed ownership.", i.mode, adjusted);
4029
                i.mode = adjusted;
×
4030
        }
4031

4032
        if (!empty_or_dash(age)) {
23,423✔
4033
                const char *a = age;
1,250✔
4034
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,250✔
4035

4036
                if (*a == '~') {
1,250✔
4037
                        i.keep_first_level = true;
×
4038
                        a++;
×
4039
                }
4040

4041
                /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
4042
                r = split_pair(a, ":", &age_by, &seconds);
1,250✔
4043
                if (r == -ENOMEM)
1,250✔
4044
                        return log_oom();
×
4045
                if (r < 0 && r != -EINVAL)
1,250✔
4046
                        return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
×
4047
                if (r >= 0) {
1,250✔
4048
                        /* We found a ":", parse the "age-by" part. */
4049
                        r = parse_age_by_from_arg(age_by, &i);
151✔
4050
                        if (r == -ENOMEM)
151✔
4051
                                return log_oom();
×
4052
                        if (r < 0) {
151✔
4053
                                *invalid_config = true;
7✔
4054
                                return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
7✔
4055
                        }
4056

4057
                        /* For parsing the "age" part, after the ":". */
4058
                        a = seconds;
144✔
4059
                }
4060

4061
                r = parse_sec(a, &i.age);
1,243✔
4062
                if (r < 0) {
1,243✔
4063
                        *invalid_config = true;
2✔
4064
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
2✔
4065
                }
4066

4067
                i.age_set = true;
1,241✔
4068
        }
4069

4070
        h = needs_glob(i.type) ? c->globs : c->items;
23,414✔
4071

4072
        existing = ordered_hashmap_get(h, i.path);
23,414✔
4073
        if (existing) {
23,414✔
4074
                if (is_duplicated_item(existing, &i)) {
1,357✔
4075
                        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3✔
4076
                                   "Duplicate line for path \"%s\", ignoring.", i.path);
4077
                        return 0;
3✔
4078
                }
4079
        } else {
4080
                existing = new0(ItemArray, 1);
22,057✔
4081
                if (!existing)
22,057✔
4082
                        return log_oom();
×
4083

4084
                r = ordered_hashmap_put(h, i.path, existing);
22,057✔
4085
                if (r < 0) {
22,057✔
4086
                        free(existing);
×
4087
                        return log_oom();
×
4088
                }
4089
        }
4090

4091
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
23,411✔
4092
                return log_oom();
×
4093

4094
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
23,411✔
4095

4096
        /* Sort item array, to enforce stable ordering of application */
4097
        typesafe_qsort(existing->items, existing->n_items, item_compare);
23,411✔
4098

4099
        return 0;
4100
}
4101

4102
static int cat_config(char **config_dirs, char **args) {
×
4103
        _cleanup_strv_free_ char **files = NULL;
×
4104
        int r;
×
4105

4106
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4107
        if (r < 0)
×
4108
                return r;
4109

4110
        pager_open(arg_pager_flags);
×
4111

4112
        return cat_files(NULL, files, arg_cat_flags);
×
4113
}
4114

4115
static int exclude_default_prefixes(void) {
×
4116
        int r;
×
4117

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

4123
        r = strv_extend_many(
×
4124
                        &arg_exclude_prefixes,
4125
                        "/dev",
4126
                        "/proc",
4127
                        "/run",
4128
                        "/sys");
4129
        if (r < 0)
×
4130
                return log_oom();
×
4131

4132
        strv_uniq(arg_exclude_prefixes);
×
4133
        return 0;
×
4134
}
4135

4136
static int help(void) {
×
4137
        _cleanup_free_ char *link = NULL;
×
4138
        int r;
×
4139

4140
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4141
        if (r < 0)
×
4142
                return log_oom();
×
4143

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

4176
        return 0;
4177
}
4178

4179
static int parse_argv(int argc, char *argv[]) {
689✔
4180
        enum {
689✔
4181
                ARG_VERSION = 0x100,
4182
                ARG_CAT_CONFIG,
4183
                ARG_TLDR,
4184
                ARG_USER,
4185
                ARG_CREATE,
4186
                ARG_CLEAN,
4187
                ARG_REMOVE,
4188
                ARG_PURGE,
4189
                ARG_BOOT,
4190
                ARG_GRACEFUL,
4191
                ARG_PREFIX,
4192
                ARG_EXCLUDE_PREFIX,
4193
                ARG_ROOT,
4194
                ARG_IMAGE,
4195
                ARG_IMAGE_POLICY,
4196
                ARG_REPLACE,
4197
                ARG_DRY_RUN,
4198
                ARG_NO_PAGER,
4199
        };
4200

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

4224
        int c, r;
689✔
4225

4226
        assert(argc >= 0);
689✔
4227
        assert(argv);
689✔
4228

4229
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
2,933✔
4230

4231
                switch (c) {
2,244✔
4232

4233
                case 'h':
×
4234
                        return help();
×
4235

4236
                case ARG_VERSION:
×
4237
                        return version();
×
4238

4239
                case ARG_CAT_CONFIG:
×
4240
                        arg_cat_flags = CAT_CONFIG_ON;
×
4241
                        break;
×
4242

4243
                case ARG_TLDR:
×
4244
                        arg_cat_flags = CAT_TLDR;
×
4245
                        break;
×
4246

4247
                case ARG_USER:
192✔
4248
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
192✔
4249
                        break;
192✔
4250

4251
                case ARG_CREATE:
638✔
4252
                        arg_operation |= OPERATION_CREATE;
638✔
4253
                        break;
638✔
4254

4255
                case ARG_CLEAN:
38✔
4256
                        arg_operation |= OPERATION_CLEAN;
38✔
4257
                        break;
38✔
4258

4259
                case ARG_REMOVE:
320✔
4260
                        arg_operation |= OPERATION_REMOVE;
320✔
4261
                        break;
320✔
4262

4263
                case ARG_BOOT:
542✔
4264
                        arg_boot = true;
542✔
4265
                        break;
542✔
4266

4267
                case ARG_PURGE:
5✔
4268
                        arg_operation |= OPERATION_PURGE;
5✔
4269
                        break;
5✔
4270

4271
                case ARG_GRACEFUL:
118✔
4272
                        arg_graceful = true;
118✔
4273
                        break;
118✔
4274

4275
                case ARG_PREFIX:
236✔
4276
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
236✔
4277
                                return log_oom();
×
4278
                        break;
4279

4280
                case ARG_EXCLUDE_PREFIX:
118✔
4281
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
118✔
4282
                                return log_oom();
×
4283
                        break;
4284

4285
                case ARG_ROOT:
8✔
4286
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
8✔
4287
                        if (r < 0)
8✔
4288
                                return r;
4289
                        break;
4290

4291
                case ARG_IMAGE:
×
4292
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
4293
                        if (r < 0)
×
4294
                                return r;
4295

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

4299
                case 'E':
4300
                        r = exclude_default_prefixes();
×
4301
                        if (r < 0)
×
4302
                                return r;
4303

4304
                        break;
4305

4306
                case ARG_IMAGE_POLICY:
×
4307
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4308
                        if (r < 0)
×
4309
                                return r;
4310
                        break;
4311

4312
                case ARG_REPLACE:
×
4313
                        if (!path_is_absolute(optarg))
×
4314
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4315
                                                       "The argument to --replace= must be an absolute path.");
4316
                        if (!endswith(optarg, ".conf"))
×
4317
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4318
                                                       "The argument to --replace= must have the extension '.conf'.");
4319

4320
                        arg_replace = optarg;
×
4321
                        break;
×
4322

4323
                case ARG_DRY_RUN:
29✔
4324
                        arg_dry_run = true;
29✔
4325
                        break;
29✔
4326

4327
                case ARG_NO_PAGER:
×
4328
                        arg_pager_flags |= PAGER_DISABLE;
×
4329
                        break;
×
4330

4331
                case '?':
4332
                        return -EINVAL;
4333

4334
                default:
×
4335
                        assert_not_reached();
×
4336
                }
4337

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

4342
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
689✔
4343
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4344
                                       "Refusing --purge without specification of a configuration file.");
4345

4346
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
689✔
4347
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4348
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4349

4350
        if (arg_replace && optind >= argc)
689✔
4351
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4352
                                       "When --replace= is given, some configuration items must be specified.");
4353

4354
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
689✔
4355
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4356
                                       "Combination of --user and --root= is not supported.");
4357

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

4362
        return 1;
4363
}
4364

4365
static int read_config_file(
15,411✔
4366
                Context *c,
4367
                char **config_dirs,
4368
                const char *fn,
4369
                bool ignore_enoent,
4370
                bool *invalid_config) {
4371

4372
        ItemArray *ia;
15,411✔
4373
        int r = 0;
15,411✔
4374

4375
        assert(c);
15,411✔
4376
        assert(fn);
15,411✔
4377

4378
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
15,411✔
4379
                           parse_line, c, ignore_enoent, invalid_config);
4380
        if (r <= 0)
15,411✔
4381
                return r;
15,411✔
4382

4383
        /* we have to determine age parameter for each entry of type X */
4384
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
108,645✔
4385
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
192,375✔
4386
                        ItemArray *ja;
98,790✔
4387
                        Item *candidate_item = NULL;
98,790✔
4388

4389
                        if (i->type != IGNORE_DIRECTORY_PATH)
98,790✔
4390
                                continue;
97,048✔
4391

4392
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
164,718✔
4393
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
330,990✔
4394
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
168,014✔
4395
                                                             TRUNCATE_DIRECTORY,
4396
                                                             CREATE_SUBVOLUME,
4397
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4398
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4399
                                                continue;
82,468✔
4400

4401
                                        if (path_equal(j->path, i->path)) {
85,546✔
4402
                                                candidate_item = j;
4403
                                                break;
4404
                                        }
4405

4406
                                        if (candidate_item
85,546✔
4407
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
7,547✔
4408
                                            : path_startswith(i->path, j->path) != NULL)
77,999✔
4409
                                                candidate_item = j;
4410
                                }
4411

4412
                        if (candidate_item && candidate_item->age_set) {
1,742✔
4413
                                i->age = candidate_item->age;
1,244✔
4414
                                i->age_set = true;
1,244✔
4415
                        }
4416
                }
4417

4418
        return r;
15,060✔
4419
}
4420

4421
static int parse_arguments(
138✔
4422
                Context *c,
4423
                char **config_dirs,
4424
                char **args,
4425
                bool *invalid_config) {
4426
        int r;
138✔
4427

4428
        assert(c);
138✔
4429

4430
        STRV_FOREACH(arg, args) {
276✔
4431
                r = read_config_file(c, config_dirs, *arg, false, invalid_config);
138✔
4432
                if (r < 0)
138✔
4433
                        return r;
4434
        }
4435

4436
        return 0;
4437
}
4438

4439
static int read_config_files(
551✔
4440
                Context *c,
4441
                char **config_dirs,
4442
                char **args,
4443
                bool *invalid_config) {
4444

4445
        _cleanup_strv_free_ char **files = NULL;
×
4446
        _cleanup_free_ char *p = NULL;
551✔
4447
        int r;
551✔
4448

4449
        assert(c);
551✔
4450

4451
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
551✔
4452
        if (r < 0)
551✔
4453
                return r;
4454

4455
        STRV_FOREACH(f, files)
15,470✔
4456
                if (p && path_equal(*f, p)) {
14,919✔
4457
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4458

4459
                        r = parse_arguments(c, config_dirs, args, invalid_config);
×
4460
                        if (r < 0)
×
4461
                                return r;
4462
                } else
4463
                        /* Just warn, ignore result otherwise.
4464
                         * read_config_file() has some debug output, so no need to print anything. */
4465
                        (void) read_config_file(c, config_dirs, *f, true, invalid_config);
14,919✔
4466

4467
        return 0;
4468
}
4469

4470
static int read_credential_lines(Context *c, bool *invalid_config) {
689✔
4471
        _cleanup_free_ char *j = NULL;
689✔
4472
        const char *d;
689✔
4473
        int r;
689✔
4474

4475
        assert(c);
689✔
4476

4477
        r = get_credentials_dir(&d);
689✔
4478
        if (r == -ENXIO)
689✔
4479
                return 0;
4480
        if (r < 0)
354✔
4481
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4482

4483
        j = path_join(d, "tmpfiles.extra");
354✔
4484
        if (!j)
354✔
4485
                return log_oom();
×
4486

4487
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
354✔
4488
        return 0;
4489
}
4490

4491
static int link_parent(Context *c, ItemArray *a) {
22,057✔
4492
        const char *path;
22,057✔
4493
        char *prefix;
22,057✔
4494
        int r;
22,057✔
4495

4496
        assert(c);
22,057✔
4497
        assert(a);
22,057✔
4498

4499
        /* Finds the closest "parent" item array for the specified item array. Then registers the specified
4500
         * item array as child of it, and fills the parent in, linking them both ways. This allows us to
4501
         * later create parents before their children, and clean up/remove children before their parents.
4502
         */
4503

4504
        if (a->n_items <= 0)
22,057✔
4505
                return 0;
4506

4507
        path = a->items[0].path;
22,057✔
4508
        prefix = newa(char, strlen(path) + 1);
22,057✔
4509
        PATH_FOREACH_PREFIX(prefix, path) {
74,809✔
4510
                ItemArray *j;
39,689✔
4511

4512
                j = ordered_hashmap_get(c->items, prefix);
39,689✔
4513
                if (!j)
39,689✔
4514
                        j = ordered_hashmap_get(c->globs, prefix);
31,441✔
4515
                if (j) {
31,441✔
4516
                        r = set_ensure_put(&j->children, NULL, a);
8,994✔
4517
                        if (r < 0)
8,994✔
4518
                                return log_oom();
×
4519

4520
                        a->parent = j;
8,994✔
4521
                        return 1;
8,994✔
4522
                }
4523
        }
4524

4525
        return 0;
4526
}
4527

4528
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
22,057✔
4529
                                              ItemArray, item_array_free);
4530

4531
static int run(int argc, char *argv[]) {
689✔
4532
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
689✔
4533
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
689✔
4534
        _cleanup_strv_free_ char **config_dirs = NULL;
689✔
4535
        _cleanup_(context_done) Context c = {};
×
4536
        bool invalid_config = false;
689✔
4537
        ItemArray *a;
689✔
4538
        enum {
689✔
4539
                PHASE_PURGE,
4540
                PHASE_REMOVE_AND_CLEAN,
4541
                PHASE_CREATE,
4542
                _PHASE_MAX
4543
        } phase;
4544
        int r;
689✔
4545

4546
        r = parse_argv(argc, argv);
689✔
4547
        if (r <= 0)
689✔
4548
                return r;
4549

4550
        log_setup();
689✔
4551

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

4562
        /* Descending down file system trees might take a lot of fds */
4563
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
689✔
4564

4565
        switch (arg_runtime_scope) {
689✔
4566

4567
        case RUNTIME_SCOPE_USER:
192✔
4568
                r = user_config_paths(&config_dirs);
192✔
4569
                if (r < 0)
192✔
4570
                        return log_error_errno(r, "Failed to initialize configuration directory list: %m");
×
4571
                break;
4572

4573
        case RUNTIME_SCOPE_SYSTEM:
497✔
4574
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
497✔
4575
                if (!config_dirs)
497✔
4576
                        return log_oom();
×
4577
                break;
4578

4579
        default:
×
4580
                assert_not_reached();
×
4581
        }
4582

4583
        if (DEBUG_LOGGING) {
689✔
4584
                _cleanup_free_ char *t = NULL;
577✔
4585

4586
                STRV_FOREACH(i, config_dirs) {
3,269✔
4587
                        _cleanup_free_ char *j = NULL;
2,692✔
4588

4589
                        j = path_join(arg_root, *i);
2,692✔
4590
                        if (!j)
2,692✔
4591
                                return log_oom();
×
4592

4593
                        if (!strextend(&t, "\n\t", j))
2,692✔
4594
                                return log_oom();
×
4595
                }
4596

4597
                log_debug("Looking for configuration files in (higher priority first):%s", t);
577✔
4598
        }
4599

4600
        if (arg_cat_flags != CAT_CONFIG_OFF)
689✔
4601
                return cat_config(config_dirs, argv + optind);
×
4602

4603
        if (should_bypass("SYSTEMD_TMPFILES"))
689✔
4604
                return 0;
4605

4606
        umask(0022);
689✔
4607

4608
        r = mac_init();
689✔
4609
        if (r < 0)
689✔
4610
                return r;
4611

4612
        if (arg_image) {
689✔
4613
                assert(!arg_root);
×
4614

4615
                r = mount_image_privately_interactively(
×
4616
                                arg_image,
4617
                                arg_image_policy,
4618
                                DISSECT_IMAGE_GENERIC_ROOT |
4619
                                DISSECT_IMAGE_REQUIRE_ROOT |
4620
                                DISSECT_IMAGE_VALIDATE_OS |
4621
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
4622
                                DISSECT_IMAGE_FSCK |
4623
                                DISSECT_IMAGE_GROWFS |
4624
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
4625
                                &mounted_dir,
4626
                                /* ret_dir_fd= */ NULL,
4627
                                &loop_device);
4628
                if (r < 0)
×
4629
                        return r;
4630

4631
                arg_root = strdup(mounted_dir);
×
4632
                if (!arg_root)
×
4633
                        return log_oom();
×
4634
        }
4635

4636
        c.items = ordered_hashmap_new(&item_array_hash_ops);
689✔
4637
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
689✔
4638
        if (!c.items || !c.globs)
689✔
4639
                return log_oom();
×
4640

4641
        /* If command line arguments are specified along with --replace=, read all configuration files and
4642
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4643
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
4644
         * read configuration and execute it. */
4645
        if (arg_replace || optind >= argc)
689✔
4646
                r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
551✔
4647
        else
4648
                r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
138✔
4649
        if (r < 0)
689✔
4650
                return r;
4651

4652
        r = read_credential_lines(&c, &invalid_config);
689✔
4653
        if (r < 0)
689✔
4654
                return r;
4655

4656
        /* Let's now link up all child/parent relationships */
4657
        ORDERED_HASHMAP_FOREACH(a, c.items) {
16,592✔
4658
                r = link_parent(&c, a);
15,903✔
4659
                if (r < 0)
15,903✔
4660
                        return r;
×
4661
        }
4662
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
6,843✔
4663
                r = link_parent(&c, a);
6,154✔
4664
                if (r < 0)
6,154✔
4665
                        return r;
×
4666
        }
4667

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

4673
                if (phase == PHASE_PURGE)
2,067✔
4674
                        op = arg_operation & OPERATION_PURGE;
689✔
4675
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,378✔
4676
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
689✔
4677
                else if (phase == PHASE_CREATE)
689✔
4678
                        op = arg_operation & OPERATION_CREATE;
689✔
4679
                else
4680
                        assert_not_reached();
×
4681

4682
                if (op == 0) /* Nothing requested in this phase */
2,067✔
4683
                        continue;
1,066✔
4684

4685
                /* The non-globbing ones usually create things, hence we apply them first */
4686
                ORDERED_HASHMAP_FOREACH(a, c.items)
29,781✔
4687
                        RET_GATHER(r, process_item_array(&c, a, op));
28,780✔
4688

4689
                /* The globbing ones usually alter things, hence we apply them second. */
4690
                ORDERED_HASHMAP_FOREACH(a, c.globs)
10,935✔
4691
                        RET_GATHER(r, process_item_array(&c, a, op));
9,934✔
4692
        }
4693

4694
        if (ERRNO_IS_NEG_RESOURCE(r))
1,378✔
4695
                return r;
4696
        if (invalid_config)
689✔
4697
                return EX_DATAERR;
4698
        if (r < 0)
679✔
4699
                return EX_CANTCREAT;
15✔
4700
        return 0;
4701
}
4702

4703
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