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

systemd / systemd / 15789897806

20 Jun 2025 05:25PM UTC coverage: 72.105% (+0.06%) from 72.045%
15789897806

push

github

web-flow
bootctl: honour architecture when updating boot loaders (#37913)

Fixes: #33413
Follow-up for: #30418

21 of 29 new or added lines in 2 files covered. (72.41%)

1701 existing lines in 55 files now uncovered.

300497 of 416750 relevant lines covered (72.1%)

721912.12 hits per line

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

67.51
/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 "missing_fs.h"
45
#include "mkdir-label.h"
46
#include "mount-util.h"
47
#include "mountpoint-util.h"
48
#include "offline-passwd.h"
49
#include "pager.h"
50
#include "parse-argument.h"
51
#include "parse-util.h"
52
#include "path-lookup.h"
53
#include "path-util.h"
54
#include "pretty-print.h"
55
#include "rlimit-util.h"
56
#include "rm-rf.h"
57
#include "selinux-util.h"
58
#include "set.h"
59
#include "sort-util.h"
60
#include "specifier.h"
61
#include "stat-util.h"
62
#include "string-table.h"
63
#include "string-util.h"
64
#include "strv.h"
65
#include "sysctl-util.h"
66
#include "time-util.h"
67
#include "umask-util.h"
68
#include "user-util.h"
69
#include "verbs.h"
70
#include "virt.h"
71
#include "xattr-util.h"
72

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

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

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

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

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

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

129
typedef struct Item {
130
        ItemType type;
131

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

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

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

162
        bool keep_first_level:1;
163

164
        bool append_or_force:1;
165

166
        bool allow_failure:1;
167

168
        bool try_replace:1;
169

170
        bool purge:1;
171

172
        bool ignore_if_target_missing:1;
173

174
        OperationMask done;
175
} Item;
176

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

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

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

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

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

215
#define MAX_DEPTH 256
216

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

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

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

237
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
11,093✔
238

239
static void context_done(Context *c) {
700✔
240
        assert(c);
700✔
241

242
        ordered_hashmap_free(c->items);
700✔
243
        ordered_hashmap_free(c->globs);
700✔
244

245
        set_free(c->unix_sockets);
700✔
246

247
        hashmap_free(c->uid_cache);
700✔
248
        hashmap_free(c->gid_cache);
700✔
249
}
700✔
250

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

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

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

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

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

286
        const struct table_entry *paths;
×
287
        _cleanup_free_ char *p = NULL;
×
288
        unsigned i;
×
289
        int r;
×
290

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

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

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

301
        if (arg_root) {
×
302
                _cleanup_free_ char *j = NULL;
×
303

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

308
                *ret = TAKE_PTR(j);
×
309
        } else
310
                *ret = TAKE_PTR(p);
×
311

312
        return 0;
313
}
314

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

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

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

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

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

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

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

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

356
        assert(ret);
179✔
357

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

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

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

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

375
        r = path_strv_make_absolute_cwd(config_dirs);
179✔
376
        if (r < 0)
179✔
377
                return r;
378

379
        *ret = TAKE_PTR(config_dirs);
179✔
380
        return 0;
179✔
381
}
382

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

549
        return dir;
550
}
551

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

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

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

566
        assert(path);
563✔
567
        assert(ret);
563✔
568
        assert(ret_sx);
563✔
569
        assert(ret_mountpoint);
563✔
570

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

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

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

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

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

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

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

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

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

625
                return false;
24✔
626
        }
627

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

634
                return false;
63✔
635
        }
636

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

647
                return false;
7✔
648
        }
649

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

656
                return false;
5✔
657
        }
658

659
        return true;
660
}
661

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

790
                                        continue;
×
791
                                }
792

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

917
        return r;
81✔
918
}
919

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

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

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

931
        _cleanup_free_ char *value = NULL;
×
932

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

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

945
static bool hardlink_vulnerable(const struct stat *st) {
15,542✔
946
        assert(st);
15,542✔
947

948
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
15,542✔
949
}
950

951
static mode_t process_mask_perms(mode_t mode, mode_t current) {
296✔
952

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

962
        return mode;
296✔
963
}
964

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

973
        bool do_chown, do_chmod;
20,116✔
974
        struct stat stbuf;
20,116✔
975
        mode_t new_mode;
20,116✔
976
        uid_t new_uid;
20,116✔
977
        gid_t new_gid;
20,116✔
978
        int r;
20,116✔
979

980
        assert(c);
20,116✔
981
        assert(i);
20,116✔
982
        assert(fd >= 0);
20,116✔
983
        assert(path);
20,116✔
984

985
        if (!i->mode_set && !i->uid_set && !i->gid_set)
20,116✔
986
                goto shortcut;
5,328✔
987

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

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

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

1004
        /* Calculate the mode to apply */
1005
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
28,995✔
1006
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
29,293✔
1007
                (st->st_mode & 07777);
283✔
1008

1009
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
14,788✔
1010

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

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

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

1036
        if (do_chown) {
14,788✔
1037
                log_action("Would change", "Changing",
3,098✔
1038
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1039

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

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

1063
shortcut:
14,786✔
1064
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
20,114✔
1065
}
1066

1067
static int path_open_parent_safe(const char *path, bool allow_failure) {
17,078✔
1068
        _cleanup_free_ char *dn = NULL;
17,078✔
1069
        int r, fd;
17,078✔
1070

1071
        if (!path_is_normalized(path))
17,078✔
1072
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1073
                                      SYNTHETIC_ERRNO(EINVAL),
1074
                                      "Failed to open parent of '%s': path not normalized%s.",
1075
                                      path,
1076
                                      allow_failure ? ", ignoring" : "");
1077

1078
        r = path_extract_directory(path, &dn);
17,078✔
1079
        if (r < 0)
17,078✔
1080
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1081
                                      r,
1082
                                      "Unable to determine parent directory of '%s'%s: %m",
1083
                                      path,
1084
                                      allow_failure ? ", ignoring" : "");
1085

1086
        r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
33,894✔
1087
        if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
17,078✔
1088
                return r;
1089
        if (r < 0)
17,073✔
1090
                return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
×
1091
                                      r,
1092
                                      "Failed to open path '%s'%s: %m",
1093
                                      dn,
1094
                                      allow_failure ? ", ignoring" : "");
1095

1096
        return fd;
17,073✔
1097
}
1098

1099
static int path_open_safe(const char *path) {
3,791✔
1100
        int r, fd;
3,791✔
1101

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

1106
        assert(path);
3,791✔
1107

1108
        if (!path_is_normalized(path))
3,791✔
1109
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
×
1110

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

1119
        return fd;
3,791✔
1120
}
1121

1122
static int path_set_perms(
3,279✔
1123
                Context *c,
1124
                Item *i,
1125
                const char *path,
1126
                CreationMode creation) {
1127

1128
        _cleanup_close_ int fd = -EBADF;
3,279✔
1129

1130
        assert(c);
3,279✔
1131
        assert(i);
3,279✔
1132
        assert(path);
3,279✔
1133

1134
        fd = path_open_safe(path);
3,279✔
1135
        if (fd == -ENOENT)
3,279✔
1136
                return 0;
1137
        if (fd < 0)
3,279✔
1138
                return fd;
1139

1140
        return fd_set_perms(c, i, fd, path, /* st= */ NULL, creation);
3,279✔
1141
}
1142

1143
static int parse_xattrs_from_arg(Item *i) {
×
1144
        const char *p;
×
1145
        int r;
×
1146

1147
        assert(i);
×
1148

1149
        assert_se(p = i->argument);
×
1150
        for (;;) {
×
1151
                _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
×
1152

1153
                r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
×
1154
                if (r < 0)
×
1155
                        log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
×
1156
                if (r <= 0)
×
1157
                        break;
1158

1159
                r = split_pair(xattr, "=", &name, &value);
×
1160
                if (r < 0) {
×
1161
                        log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
×
1162
                        continue;
×
1163
                }
1164

1165
                if (isempty(name) || isempty(value)) {
×
1166
                        log_warning("Malformed extended attribute found, ignoring: %s", xattr);
×
1167
                        continue;
×
1168
                }
1169

1170
                if (strv_push_pair(&i->xattrs, name, value) < 0)
×
1171
                        return log_oom();
×
1172

1173
                name = value = NULL;
×
1174
        }
1175

1176
        return 0;
×
1177
}
1178

1179
static int fd_set_xattrs(
×
1180
                Context *c,
1181
                Item *i,
1182
                int fd,
1183
                const char *path,
1184
                const struct stat *st,
1185
                CreationMode creation) {
1186

1187
        int r;
×
1188

1189
        assert(c);
×
1190
        assert(i);
×
1191
        assert(fd >= 0);
×
1192
        assert(path);
×
1193

1194
        STRV_FOREACH_PAIR(name, value, i->xattrs) {
×
1195
                log_action("Would set", "Setting",
×
1196
                           "%s extended attribute '%s=%s' on %s", *name, *value, path);
1197

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

1208
static int path_set_xattrs(
×
1209
                Context *c,
1210
                Item *i,
1211
                const char *path,
1212
                CreationMode creation) {
1213

1214
        _cleanup_close_ int fd = -EBADF;
×
1215

1216
        assert(c);
×
1217
        assert(i);
×
1218
        assert(path);
×
1219

1220
        fd = path_open_safe(path);
×
1221
        if (fd == -ENOENT)
×
1222
                return 0;
1223
        if (fd < 0)
×
1224
                return fd;
1225

1226
        return fd_set_xattrs(c, i, fd, path, /* st = */ NULL, creation);
×
1227
}
1228

1229
static int parse_acls_from_arg(Item *item) {
2,685✔
1230
#if HAVE_ACL
1231
        int r;
2,685✔
1232

1233
        assert(item);
2,685✔
1234

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

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

1247
        return 0;
2,685✔
1248
}
1249

1250
#if HAVE_ACL
1251
static int parse_acl_cond_exec(
292✔
1252
                const char *path,
1253
                const struct stat *st,
1254
                acl_t cond_exec,
1255
                acl_t access, /* could be empty (NULL) */
1256
                bool append,
1257
                acl_t *ret) {
1258

1259
        acl_entry_t entry;
292✔
1260
        acl_permset_t permset;
292✔
1261
        bool has_exec;
292✔
1262
        int r;
292✔
1263

1264
        assert(path);
292✔
1265
        assert(st);
292✔
1266
        assert(cond_exec);
292✔
1267
        assert(ret);
292✔
1268

1269
        if (!S_ISDIR(st->st_mode)) {
292✔
1270
                _cleanup_(acl_freep) acl_t old = NULL;
×
1271

1272
                old = acl_get_file(path, ACL_TYPE_ACCESS);
184✔
1273
                if (!old)
184✔
1274
                        return -errno;
×
1275

1276
                has_exec = false;
184✔
1277

1278
                for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
184✔
1279
                     r > 0;
736✔
1280
                     r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
552✔
1281

1282
                        acl_tag_t tag;
562✔
1283

1284
                        if (acl_get_tag_type(entry, &tag) < 0)
562✔
1285
                                return -errno;
×
1286

1287
                        if (tag == ACL_MASK)
562✔
1288
                                continue;
8✔
1289

1290
                        /* If not appending, skip ACL definitions */
1291
                        if (!append && IN_SET(tag, ACL_USER, ACL_GROUP))
556✔
1292
                                continue;
2✔
1293

1294
                        if (acl_get_permset(entry, &permset) < 0)
554✔
1295
                                return -errno;
×
1296

1297
                        r = acl_get_perm(permset, ACL_EXECUTE);
554✔
1298
                        if (r < 0)
554✔
1299
                                return -errno;
×
1300
                        if (r > 0) {
554✔
1301
                                has_exec = true;
10✔
1302
                                break;
10✔
1303
                        }
1304
                }
1305
                if (r < 0)
184✔
1306
                        return -errno;
×
1307

1308
                /* Check if we're about to set the execute bit in acl_access */
1309
                if (!has_exec && access) {
184✔
1310
                        for (r = acl_get_entry(access, ACL_FIRST_ENTRY, &entry);
×
1311
                             r > 0;
×
1312
                             r = acl_get_entry(access, ACL_NEXT_ENTRY, &entry)) {
×
1313

1314
                                if (acl_get_permset(entry, &permset) < 0)
×
1315
                                        return -errno;
×
1316

1317
                                r = acl_get_perm(permset, ACL_EXECUTE);
×
1318
                                if (r < 0)
×
1319
                                        return -errno;
×
1320
                                if (r > 0) {
×
1321
                                        has_exec = true;
1322
                                        break;
1323
                                }
1324
                        }
1325
                        if (r < 0)
×
1326
                                return -errno;
×
1327
                }
1328
        } else
1329
                has_exec = true;
1330

1331
        _cleanup_(acl_freep) acl_t parsed = access ? acl_dup(access) : acl_init(0);
584✔
1332
        if (!parsed)
292✔
1333
                return -errno;
×
1334

1335
        for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
292✔
1336
             r > 0;
872✔
1337
             r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
580✔
1338

1339
                acl_entry_t parsed_entry;
580✔
1340

1341
                if (acl_create_entry(&parsed, &parsed_entry) < 0)
580✔
1342
                        return -errno;
×
1343

1344
                if (acl_copy_entry(parsed_entry, entry) < 0)
580✔
1345
                        return -errno;
×
1346

1347
                /* We substituted 'X' with 'x' in parse_acl(), so drop execute bit here if not applicable. */
1348
                if (!has_exec) {
580✔
1349
                        if (acl_get_permset(parsed_entry, &permset) < 0)
345✔
1350
                                return -errno;
×
1351

1352
                        if (acl_delete_perm(permset, ACL_EXECUTE) < 0)
345✔
1353
                                return -errno;
×
1354
                }
1355
        }
1356
        if (r < 0)
292✔
1357
                return -errno;
×
1358

1359
        if (!append) { /* want_mask = true */
292✔
1360
                r = calc_acl_mask_if_needed(&parsed);
3✔
1361
                if (r < 0)
3✔
1362
                        return r;
1363
        }
1364

1365
        *ret = TAKE_PTR(parsed);
292✔
1366

1367
        return 0;
292✔
1368
}
1369

1370
static int path_set_acl(
1,039✔
1371
                Context *c,
1372
                const char *path,
1373
                const char *pretty,
1374
                acl_type_t type,
1375
                acl_t acl,
1376
                bool modify) {
1377

1378
        _cleanup_(acl_free_charpp) char *t = NULL;
1,039✔
1379
        _cleanup_(acl_freep) acl_t dup = NULL;
1,039✔
1380
        int r;
1,039✔
1381

1382
        assert(c);
1,039✔
1383

1384
        /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1385

1386
        if (modify) {
1,039✔
1387
                r = acls_for_file(path, type, acl, &dup);
1,036✔
1388
                if (r < 0)
1,036✔
1389
                        return r;
1390

1391
                r = calc_acl_mask_if_needed(&dup);
1,034✔
1392
                if (r < 0)
1,034✔
1393
                        return r;
1394
        } else {
1395
                dup = acl_dup(acl);
3✔
1396
                if (!dup)
3✔
1397
                        return -errno;
×
1398

1399
                /* the mask was already added earlier if needed */
1400
        }
1401

1402
        r = add_base_acls_if_needed(&dup, path);
1,037✔
1403
        if (r < 0)
1,037✔
1404
                return r;
1405

1406
        t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1,037✔
1407
        log_action("Would set", "Setting",
2,559✔
1408
                   "%s %s ACL %s on %s",
1409
                   type == ACL_TYPE_ACCESS ? "access" : "default",
1410
                   strna(t), pretty);
1411

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

1428
static int fd_set_acls(
754✔
1429
                Context *c,
1430
                Item *item,
1431
                int fd,
1432
                const char *path,
1433
                const struct stat *st,
1434
                CreationMode creation) {
1435

1436
        int r = 0;
754✔
1437
#if HAVE_ACL
1438
        _cleanup_(acl_freep) acl_t access_with_exec_parsed = NULL;
754✔
1439
        struct stat stbuf;
754✔
1440

1441
        assert(c);
754✔
1442
        assert(item);
754✔
1443
        assert(fd >= 0);
754✔
1444
        assert(path);
754✔
1445

1446
        if (!st) {
754✔
1447
                if (fstat(fd, &stbuf) < 0)
466✔
1448
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1449
                st = &stbuf;
1450
        }
1451

1452
        if (hardlink_vulnerable(st))
754✔
1453
                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
×
1454
                                       "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1455
                                       path);
1456

1457
        if (S_ISLNK(st->st_mode)) {
754✔
1458
                log_debug("Skipping ACL fix for symlink %s.", path);
×
1459
                return 0;
×
1460
        }
1461

1462
        if (item->acl_access_exec) {
754✔
1463
                r = parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd), st,
292✔
1464
                                        item->acl_access_exec,
1465
                                        item->acl_access,
1466
                                        item->append_or_force,
292✔
1467
                                        &access_with_exec_parsed);
1468
                if (r < 0)
292✔
1469
                        return log_error_errno(r, "Failed to parse conditionalized execute bit for \"%s\": %m", path);
×
1470

1471
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
292✔
1472
        } else if (item->acl_access)
462✔
1473
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
200✔
1474

1475
        /* set only default acls to folders */
1476
        if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
754✔
1477
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
547✔
1478

1479
        if (ERRNO_IS_NOT_SUPPORTED(r)) {
754✔
1480
                log_debug_errno(r, "ACLs not supported by file system at %s", path);
2✔
1481
                return 0;
2✔
1482
        }
1483
        if (r > 0)
752✔
1484
                return -r; /* already warned in path_set_acl */
×
1485
        if (r < 0)
752✔
1486
                return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
×
1487
#endif
1488
        return r;
1489
}
1490

1491
static int path_set_acls(
466✔
1492
                Context *c,
1493
                Item *item,
1494
                const char *path,
1495
                CreationMode creation) {
1496

1497
        int r = 0;
466✔
1498
#if HAVE_ACL
1499
        _cleanup_close_ int fd = -EBADF;
466✔
1500

1501
        assert(c);
466✔
1502
        assert(item);
466✔
1503
        assert(path);
466✔
1504

1505
        fd = path_open_safe(path);
466✔
1506
        if (fd == -ENOENT)
466✔
1507
                return 0;
1508
        if (fd < 0)
466✔
1509
                return fd;
1510

1511
        r = fd_set_acls(c, item, fd, path, /* st= */ NULL, creation);
466✔
1512
#endif
1513
        return r;
1514
}
1515

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

1538
        enum {
1,149✔
1539
                MODE_ADD,
1540
                MODE_DEL,
1541
                MODE_SET
1542
        } mode = MODE_ADD;
1,149✔
1543

1544
        unsigned value = 0, mask = 0;
1,149✔
1545
        const char *p;
1,149✔
1546

1547
        assert(item);
1,149✔
1548

1549
        p = item->argument;
1,149✔
1550
        if (p) {
1,149✔
1551
                if (*p == '+') {
1,149✔
1552
                        mode = MODE_ADD;
1,149✔
1553
                        p++;
1,149✔
1554
                } else if (*p == '-') {
×
1555
                        mode = MODE_DEL;
×
1556
                        p++;
×
1557
                } else  if (*p == '=') {
×
1558
                        mode = MODE_SET;
×
1559
                        p++;
×
1560
                }
1561
        }
1562

1563
        if (isempty(p) && mode != MODE_SET)
1,149✔
1564
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1565
                                       "Setting file attribute on '%s' needs an attribute specification.",
1566
                                       item->path);
1567

1568
        for (; p && *p ; p++) {
2,298✔
1569
                unsigned i, v;
1570

1571
                for (i = 0; i < ELEMENTSOF(attributes); i++)
16,086✔
1572
                        if (*p == attributes[i].character)
16,086✔
1573
                                break;
1574

1575
                if (i >= ELEMENTSOF(attributes))
1,149✔
1576
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
1577
                                               "Unknown file attribute '%c' on '%s'.", *p, item->path);
1578

1579
                v = attributes[i].value;
1,149✔
1580

1581
                SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1,149✔
1582

1583
                mask |= v;
1,149✔
1584
        }
1585

1586
        if (mode == MODE_SET)
1,149✔
1587
                mask |= CHATTR_ALL_FL;
×
1588

1589
        assert(mask != 0);
1,149✔
1590

1591
        item->attribute_mask = mask;
1,149✔
1592
        item->attribute_value = value;
1,149✔
1593
        item->attribute_set = true;
1,149✔
1594

1595
        return 0;
1,149✔
1596
}
1597

1598
static int fd_set_attribute(
46✔
1599
                Context *c,
1600
                Item *item,
1601
                int fd,
1602
                const char *path,
1603
                const struct stat *st,
1604
                CreationMode creation) {
1605

1606
        struct stat stbuf;
46✔
1607
        unsigned f;
46✔
1608
        int r;
46✔
1609

1610
        assert(c);
46✔
1611
        assert(item);
46✔
1612
        assert(fd >= 0);
46✔
1613
        assert(path);
46✔
1614

1615
        if (!item->attribute_set || item->attribute_mask == 0)
46✔
1616
                return 0;
46✔
1617

1618
        if (!st) {
46✔
1619
                if (fstat(fd, &stbuf) < 0)
46✔
1620
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
1621
                st = &stbuf;
1622
        }
1623

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

1631
        f = item->attribute_value & item->attribute_mask;
46✔
1632

1633
        /* Mask away directory-specific flags */
1634
        if (!S_ISDIR(st->st_mode))
46✔
1635
                f &= ~FS_DIRSYNC_FL;
×
1636

1637
        log_action("Would try to set", "Trying to set",
92✔
1638
                   "%s file attributes 0x%08x on %s",
1639
                   f & item->attribute_mask,
1640
                   path);
1641

1642
        if (!arg_dry_run) {
46✔
1643
                _cleanup_close_ int procfs_fd = -EBADF;
46✔
1644

1645
                procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
46✔
1646
                if (procfs_fd < 0)
46✔
1647
                        return log_error_errno(procfs_fd, "Failed to reopen '%s': %m", path);
×
1648

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

1661
        return 0;
1662
}
1663

1664
static int path_set_attribute(
46✔
1665
                Context *c,
1666
                Item *item,
1667
                const char *path,
1668
                CreationMode creation) {
1669

1670
        _cleanup_close_ int fd = -EBADF;
46✔
1671

1672
        assert(c);
46✔
1673
        assert(item);
46✔
1674

1675
        if (!item->attribute_set || item->attribute_mask == 0)
46✔
1676
                return 0;
1677

1678
        fd = path_open_safe(path);
46✔
1679
        if (fd == -ENOENT)
46✔
1680
                return 0;
1681
        if (fd < 0)
46✔
1682
                return fd;
1683

1684
        return fd_set_attribute(c, item, fd, path, /* st= */ NULL, creation);
46✔
1685
}
1686

1687
static int write_argument_data(Item *i, int fd, const char *path) {
297✔
1688
        int r;
297✔
1689

1690
        assert(i);
297✔
1691
        assert(fd >= 0);
297✔
1692
        assert(path);
297✔
1693

1694
        if (item_binary_argument_size(i) == 0)
297✔
1695
                return 0;
1696

1697
        assert(item_binary_argument(i));
271✔
1698

1699
        log_action("Would write", "Writing", "%s to \"%s\"", path);
510✔
1700

1701
        if (!arg_dry_run) {
271✔
1702
                r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i));
268✔
1703
                if (r < 0)
268✔
1704
                        return log_error_errno(r, "Failed to write file \"%s\": %m", path);
×
1705
        }
1706

1707
        return 0;
1708
}
1709

1710
static int write_one_file(Context *c, Item *i, const char *path, CreationMode creation) {
18✔
1711
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
18✔
1712
        _cleanup_free_ char *bn = NULL;
18✔
1713
        int r;
18✔
1714

1715
        assert(c);
18✔
1716
        assert(i);
18✔
1717
        assert(path);
18✔
1718
        assert(i->type == WRITE_FILE);
18✔
1719

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

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

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

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

1744
                return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
×
1745
        }
1746

1747
        /* 'w' is allowed to write into any kind of files. */
1748

1749
        r = write_argument_data(i, fd, path);
18✔
1750
        if (r < 0)
18✔
1751
                return r;
1752

1753
        return fd_set_perms(c, i, fd, path, NULL, creation);
18✔
1754
}
1755

1756
static int create_file(
812✔
1757
                Context *c,
1758
                Item *i,
1759
                const char *path) {
1760

1761
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
812✔
1762
        _cleanup_free_ char *bn = NULL;
812✔
1763
        struct stat stbuf, *st = NULL;
812✔
1764
        CreationMode creation;
812✔
1765
        int r = 0;
812✔
1766

1767
        assert(c);
812✔
1768
        assert(i);
812✔
1769
        assert(path);
812✔
1770
        assert(i->type == CREATE_FILE);
812✔
1771

1772
        /* 'f' operates on regular files exclusively. */
1773

1774
        r = path_extract_filename(path, &bn);
812✔
1775
        if (r < 0)
812✔
1776
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1777
        if (r == O_DIRECTORY)
812✔
1778
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
×
1779

1780
        if (arg_dry_run) {
812✔
1781
                log_info("Would create file %s", path);
4✔
1782
                return 0;
4✔
1783

1784
                /* The opening of the directory below would fail if it doesn't exist,
1785
                 * so log and exit before even trying to do that. */
1786
        }
1787

1788
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1789
         * can't be changed behind our back. */
1790
        dir_fd = path_open_parent_safe(path, i->allow_failure);
808✔
1791
        if (dir_fd < 0)
808✔
1792
                return dir_fd;
1793

1794
        WITH_UMASK(0000) {
1,612✔
1795
                mac_selinux_create_file_prepare(path, S_IFREG);
806✔
1796
                fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
806✔
1797
                mac_selinux_create_file_clear();
806✔
1798
        }
1799

1800
        if (fd < 0) {
806✔
1801
                /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1802
                 * returns EROFS only if it needs to create the file. */
1803
                if (fd != -EEXIST)
655✔
1804
                        return log_error_errno(fd, "Failed to create file %s: %m", path);
1✔
1805

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

1813
                if (fstat(fd, &stbuf) < 0)
654✔
1814
                        return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1815

1816
                if (!S_ISREG(stbuf.st_mode))
654✔
1817
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
5✔
1818
                                               "%s exists and is not a regular file.",
1819
                                               path);
1820

1821
                st = &stbuf;
1822
                creation = CREATION_EXISTING;
1823
        } else {
1824
                r = write_argument_data(i, fd, path);
151✔
1825
                if (r < 0)
151✔
1826
                        return r;
1827

1828
                creation = CREATION_NORMAL;
1829
        }
1830

1831
        return fd_set_perms(c, i, fd, path, st, creation);
800✔
1832
}
1833

1834
static int truncate_file(
263✔
1835
                Context *c,
1836
                Item *i,
1837
                const char *path) {
1838

1839
        _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
263✔
1840
        _cleanup_free_ char *bn = NULL;
263✔
1841
        struct stat stbuf, *st = NULL;
263✔
1842
        CreationMode creation;
263✔
1843
        bool erofs = false;
263✔
1844
        int r = 0;
263✔
1845

1846
        assert(c);
263✔
1847
        assert(i);
263✔
1848
        assert(path);
263✔
1849
        assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
263✔
1850

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

1855
        r = path_extract_filename(path, &bn);
263✔
1856
        if (r < 0)
263✔
1857
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
1858
        if (r == O_DIRECTORY)
263✔
1859
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
×
1860

1861
        /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1862
         * can't be changed behind our back. */
1863
        dir_fd = path_open_parent_safe(path, i->allow_failure);
263✔
1864
        if (dir_fd < 0)
263✔
1865
                return dir_fd;
1866

1867
        if (arg_dry_run) {
262✔
1868
                log_info("Would truncate %s", path);
×
1869
                return 0;
×
1870
        }
1871

1872
        creation = CREATION_EXISTING;
262✔
1873
        fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
262✔
1874
        if (fd == -ENOENT) {
242✔
1875
                creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
237✔
1876

1877
                WITH_UMASK(0000) {
474✔
1878
                        mac_selinux_create_file_prepare(path, S_IFREG);
237✔
1879
                        fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
237✔
1880
                        mac_selinux_create_file_clear();
237✔
1881
                }
1882
        }
1883

1884
        if (fd < 0) {
262✔
1885
                if (fd != -EROFS)
6✔
1886
                        return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1✔
1887

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

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

1899
                        return log_error_errno(errno, "Failed to reopen file %s: %m", path);
×
1900
                }
1901

1902
                erofs = true;
1903
                creation = CREATION_EXISTING;
1904
        }
1905

1906
        if (fstat(fd, &stbuf) < 0)
260✔
1907
                return log_error_errno(errno, "stat(%s) failed: %m", path);
×
1908

1909
        if (!S_ISREG(stbuf.st_mode))
260✔
1910
                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
1911
                                       "%s exists and is not a regular file.",
1912
                                       path);
1913

1914
        if (stbuf.st_size > 0) {
260✔
1915
                if (ftruncate(fd, 0) < 0) {
13✔
1916
                        r = erofs ? -EROFS : -errno;
2✔
1917
                        return log_error_errno(r, "Failed to truncate file %s: %m", path);
2✔
1918
                }
1919
        } else
1920
                st = &stbuf;
1921

1922
        log_debug("\"%s\" has been created.", path);
258✔
1923

1924
        if (item_binary_argument(i)) {
258✔
1925
                r = write_argument_data(i, fd, path);
128✔
1926
                if (r < 0)
128✔
1927
                        return r;
1928
        }
1929

1930
        return fd_set_perms(c, i, fd, path, st, creation);
258✔
1931
}
1932

1933
static int copy_files(Context *c, Item *i) {
4,031✔
1934
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
4,031✔
1935
        _cleanup_free_ char *bn = NULL;
4,031✔
1936
        struct stat st, a;
4,031✔
1937
        int r;
4,031✔
1938

1939
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
7,923✔
1940
        if (arg_dry_run)
4,031✔
1941
                return 0;
1942

1943
        r = path_extract_filename(i->path, &bn);
4,029✔
1944
        if (r < 0)
4,029✔
1945
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
1946

1947
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1948
         * path can't be changed behind our back. */
1949
        dfd = path_open_parent_safe(i->path, i->allow_failure);
4,029✔
1950
        if (dfd < 0)
4,029✔
1951
                return dfd;
1952

1953
        r = copy_tree_at(AT_FDCWD, i->argument,
4,049✔
1954
                         dfd, bn,
1955
                         i->uid_set ? i->uid : UID_INVALID,
4,029✔
1956
                         i->gid_set ? i->gid : GID_INVALID,
4,029✔
1957
                         COPY_REFLINK | ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
4,029✔
1958
                         NULL, NULL);
1959

1960
        fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
4,029✔
1961
        if (fd < 0) {
4,029✔
1962
                if (r < 0) /* Look at original error first */
×
1963
                        return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
×
1964

1965
                return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
×
1966
        }
1967

1968
        if (fstat(fd, &st) < 0)
4,029✔
1969
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
1970

1971
        if (stat(i->argument, &a) < 0)
4,029✔
1972
                return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
×
1973

1974
        if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
4,029✔
1975
                log_debug("Can't copy to %s, file exists already and is of different type", i->path);
×
1976
                return 0;
×
1977
        }
1978

1979
        return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
4,029✔
1980
}
1981

1982
static int create_directory_or_subvolume(
8,258✔
1983
                const char *path,
1984
                mode_t mode,
1985
                bool subvol,
1986
                bool allow_failure,
1987
                struct stat *ret_st,
1988
                CreationMode *ret_creation) {
1989

1990
        _cleanup_free_ char *bn = NULL;
8,258✔
1991
        _cleanup_close_ int pfd = -EBADF;
8,258✔
1992
        CreationMode creation;
8,258✔
1993
        struct stat st;
8,258✔
1994
        int r, fd;
8,258✔
1995

1996
        assert(path);
8,258✔
1997

1998
        r = path_extract_filename(path, &bn);
8,258✔
1999
        if (r < 0)
8,258✔
2000
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
2001

2002
        pfd = path_open_parent_safe(path, allow_failure);
8,258✔
2003
        if (pfd < 0)
8,258✔
2004
                return pfd;
2005

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

2032
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2033
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
16,222✔
2034
                if (!arg_dry_run)
8,256✔
2035
                        WITH_UMASK(0000)
16,512✔
2036
                                r = mkdirat_label(pfd, bn, mode);
8,256✔
2037
        }
2038

2039
        if (arg_dry_run)
8,256✔
2040
                return 0;
2041

2042
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
8,256✔
2043

2044
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
8,256✔
2045
        if (fd < 0) {
8,256✔
2046
                /* We couldn't open it because it is not actually a directory? */
2047
                if (errno == ENOTDIR)
×
2048
                        return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
×
2049

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

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

2061
        if (fstat(fd, &st) < 0)
8,256✔
2062
                return log_error_errno(errno, "Failed to fstat(%s): %m", path);
×
2063

2064
        assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
8,256✔
2065

2066
        log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
8,256✔
2067

2068
        if (ret_st)
8,256✔
2069
                *ret_st = st;
8,256✔
2070
        if (ret_creation)
8,256✔
2071
                *ret_creation = creation;
8,256✔
2072

2073
        return fd;
2074
}
2075

2076
static int create_directory(
7,352✔
2077
                Context *c,
2078
                Item *i,
2079
                const char *path) {
2080

2081
        _cleanup_close_ int fd = -EBADF;
7,352✔
2082
        CreationMode creation;
7,352✔
2083
        struct stat st;
7,352✔
2084

2085
        assert(c);
7,352✔
2086
        assert(i);
7,352✔
2087
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
7,352✔
2088

2089
        if (arg_dry_run) {
7,352✔
2090
                log_info("Would create directory %s", path);
11✔
2091
                return 0;
11✔
2092
        }
2093

2094
        fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
7,341✔
2095
        if (fd == -EEXIST)
7,341✔
2096
                return 0;
2097
        if (fd < 0)
7,341✔
2098
                return fd;
2099

2100
        return fd_set_perms(c, i, fd, path, &st, creation);
7,339✔
2101
}
2102

2103
static int create_subvolume(
917✔
2104
                Context *c,
2105
                Item *i,
2106
                const char *path) {
2107

2108
        _cleanup_close_ int fd = -EBADF;
917✔
2109
        CreationMode creation;
917✔
2110
        struct stat st;
917✔
2111
        int r, q = 0;
917✔
2112

2113
        assert(c);
917✔
2114
        assert(i);
917✔
2115
        assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
917✔
2116

2117
        if (arg_dry_run) {
917✔
2118
                log_info("Would create subvolume %s", path);
×
2119
                return 0;
×
2120
        }
2121

2122
        fd = create_directory_or_subvolume(path, i->mode, /* subvol = */ true, i->allow_failure, &st, &creation);
917✔
2123
        if (fd == -EEXIST)
917✔
2124
                return 0;
2125
        if (fd < 0)
917✔
2126
                return fd;
2127

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

2145
        r = fd_set_perms(c, i, fd, path, &st, creation);
917✔
2146
        if (q < 0) /* prefer the quota change error from above */
917✔
2147
                return q;
×
2148

2149
        return r;
2150
}
2151

2152
static int empty_directory(
5✔
2153
                Context *c,
2154
                Item *i,
2155
                const char *path,
2156
                CreationMode creation) {
2157

2158
        _cleanup_close_ int fd = -EBADF;
5✔
2159
        struct stat st;
5✔
2160
        int r;
5✔
2161

2162
        assert(c);
5✔
2163
        assert(i);
5✔
2164
        assert(i->type == EMPTY_DIRECTORY);
5✔
2165

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

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

2185
        return fd_set_perms(c, i, fd, path, &st, creation);
4✔
2186
}
2187

2188
static int create_device(
2,134✔
2189
                Context *c,
2190
                Item *i,
2191
                mode_t file_type) {
2192

2193
        _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
2,134✔
2194
        _cleanup_free_ char *bn = NULL;
2,134✔
2195
        CreationMode creation;
2,134✔
2196
        struct stat st;
2,134✔
2197
        int r;
2,134✔
2198

2199
        assert(c);
2,134✔
2200
        assert(i);
2,134✔
2201
        assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
2,134✔
2202
        assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
2,134✔
2203

2204
        r = path_extract_filename(i->path, &bn);
2,134✔
2205
        if (r < 0)
2,134✔
2206
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2207
        if (r == O_DIRECTORY)
2,134✔
2208
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2209
                                       "Cannot open path '%s' for creating device node, is a directory.", i->path);
2210

2211
        if (arg_dry_run) {
2,134✔
2212
                log_info("Would create device node %s", i->path);
4✔
2213
                return 0;
4✔
2214
        }
2215

2216
        /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2217
         * path can't be changed behind our back. */
2218
        dfd = path_open_parent_safe(i->path, i->allow_failure);
2,130✔
2219
        if (dfd < 0)
2,130✔
2220
                return dfd;
2221

2222
        WITH_UMASK(0000) {
4,260✔
2223
                mac_selinux_create_file_prepare(i->path, file_type);
2,130✔
2224
                r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
2,130✔
2225
                mac_selinux_create_file_clear();
2,130✔
2226
        }
2227
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2,130✔
2228

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

2235
                if (r < 0) {
×
2236
                        if (ERRNO_IS_PRIVILEGE(r))
×
2237
                                goto handle_privilege;
×
2238

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

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

2245
        if (fstat(fd, &st) < 0)
2,130✔
2246
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2247

2248
        if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
2,130✔
2249

2250
                if (i->append_or_force) {
×
2251
                        fd = safe_close(fd);
×
2252

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

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

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

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

2280
                        if (((st.st_mode ^ file_type) & S_IFMT) != 0)
×
2281
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2282
                                                       "Device node we just created is not a device node, refusing.");
2283

2284
                        creation = CREATION_FORCE;
2285
                } else {
2286
                        log_warning("\"%s\" already exists and is not a device node.", i->path);
×
2287
                        return 0;
×
2288
                }
2289
        }
2290

2291
        log_debug("%s %s device node \"%s\" %u:%u.",
4,260✔
2292
                  creation_mode_verb_to_string(creation),
2293
                  i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
2294
                  i->path, major(i->mode), minor(i->mode));
2295

2296
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2,130✔
2297

2298
handle_privilege:
×
2299
        log_debug_errno(r,
2,134✔
2300
                        "We lack permissions, possibly because of cgroup configuration; "
2301
                        "skipping creation of device node '%s'.", i->path);
2302
        return 0;
2303
}
2304

2305
static int create_fifo(Context *c, Item *i) {
4✔
2306
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
4✔
2307
        _cleanup_free_ char *bn = NULL;
4✔
2308
        CreationMode creation;
4✔
2309
        struct stat st;
4✔
2310
        int r;
4✔
2311

2312
        assert(c);
4✔
2313
        assert(i);
4✔
2314
        assert(i->type == CREATE_FIFO);
4✔
2315

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

2323
        if (arg_dry_run) {
4✔
2324
                log_info("Would create fifo %s", i->path);
1✔
2325
                return 0;
1✔
2326
        }
2327

2328
        pfd = path_open_parent_safe(i->path, i->allow_failure);
3✔
2329
        if (pfd < 0)
3✔
2330
                return pfd;
2331

2332
        WITH_UMASK(0000) {
6✔
2333
                mac_selinux_create_file_prepare(i->path, S_IFIFO);
3✔
2334
                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
3✔
2335
                mac_selinux_create_file_clear();
3✔
2336
        }
2337

2338
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
3✔
2339

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

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

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

2352
        if (!S_ISFIFO(st.st_mode)) {
3✔
2353

2354
                if (i->append_or_force) {
2✔
2355
                        fd = safe_close(fd);
1✔
2356

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

2367
                                mac_selinux_create_file_prepare(i->path, S_IFIFO);
×
2368
                                r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
×
2369
                                mac_selinux_create_file_clear();
×
2370
                        }
2371
                        if (r < 0)
1✔
2372
                                return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
×
2373

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

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

2382
                        if (!S_ISFIFO(st.st_mode))
1✔
2383
                                return log_error_errno(SYNTHETIC_ERRNO(EBADF),
×
2384
                                                       "FIFO inode we just created is not a FIFO, refusing.");
2385

2386
                        creation = CREATION_FORCE;
2387
                } else {
2388
                        log_warning("\"%s\" already exists and is not a FIFO.", i->path);
1✔
2389
                        return 0;
1✔
2390
                }
2391
        }
2392

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

2395
        return fd_set_perms(c, i, fd, i->path, &st, creation);
2✔
2396
}
2397

2398
static int create_symlink(Context *c, Item *i) {
1,572✔
2399
        _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
1,572✔
2400
        _cleanup_free_ char *bn = NULL;
1,572✔
2401
        CreationMode creation;
1,572✔
2402
        struct stat st;
1,572✔
2403
        bool good = false;
1,572✔
2404
        int r;
1,572✔
2405

2406
        assert(c);
1,572✔
2407
        assert(i);
1,572✔
2408

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

2422
        r = path_extract_filename(i->path, &bn);
1,571✔
2423
        if (r < 0)
1,571✔
2424
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
×
2425
        if (r == O_DIRECTORY)
1,571✔
2426
                return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
×
2427
                                       "Cannot open path '%s' for creating symlink, is a directory.", i->path);
2428

2429
        if (arg_dry_run) {
1,571✔
2430
                log_info("Would create symlink %s -> %s", i->path, i->argument);
2✔
2431
                return 0;
2✔
2432
        }
2433

2434
        pfd = path_open_parent_safe(i->path, i->allow_failure);
1,569✔
2435
        if (pfd < 0)
1,569✔
2436
                return pfd;
2437

2438
        mac_selinux_create_file_prepare(i->path, S_IFLNK);
1,569✔
2439
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
1,569✔
2440
        mac_selinux_create_file_clear();
1,569✔
2441

2442
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,569✔
2443

2444
        fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1,569✔
2445
        if (fd < 0) {
1,569✔
2446
                if (r < 0)
×
2447
                        return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
×
2448

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

2452
        if (fstat(fd, &st) < 0)
1,569✔
2453
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2454

2455
        if (S_ISLNK(st.st_mode)) {
1,569✔
2456
                _cleanup_free_ char *x = NULL;
×
2457

2458
                r = readlinkat_malloc(fd, "", &x);
1,562✔
2459
                if (r < 0)
1,562✔
2460
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
×
2461

2462
                good = streq(x, i->argument);
1,562✔
2463
        } else
2464
                good = false;
2465

2466
        if (!good) {
1,562✔
2467
                if (!i->append_or_force) {
534✔
2468
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
530✔
2469
                        return 0;
530✔
2470
                }
2471

2472
                fd = safe_close(fd);
4✔
2473

2474
                r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
4✔
2475
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
4✔
2476
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
1✔
2477
                        if (r < 0)
1✔
UNCOV
2478
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2479

2480
                        r = symlinkat_atomic_full(i->argument, pfd, bn, SYMLINK_LABEL);
1✔
2481
                }
2482
                if (r < 0)
4✔
UNCOV
2483
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2484

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

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

2493
                if (!S_ISLNK(st.st_mode))
4✔
UNCOV
2494
                        return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
×
2495

2496
                creation = CREATION_FORCE;
2497
        }
2498

2499
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
1,039✔
2500
        return fd_set_perms(c, i, fd, i->path, &st, creation);
1,039✔
2501
}
2502

2503
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2504
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2505

2506
static int item_do(
589✔
2507
                Context *c,
2508
                Item *i,
2509
                int fd,
2510
                const char *path,
2511
                CreationMode creation,
2512
                fdaction_t action) {
2513

2514
        struct stat st;
589✔
2515
        int r;
589✔
2516

2517
        assert(c);
589✔
2518
        assert(i);
589✔
2519
        assert(fd >= 0);
589✔
2520
        assert(path);
589✔
2521
        assert(action);
589✔
2522

2523
        if (fstat(fd, &st) < 0) {
589✔
UNCOV
2524
                r = log_error_errno(errno, "fstat() on file failed: %m");
×
UNCOV
2525
                goto finish;
×
2526
        }
2527

2528
        /* This returns the first error we run into, but nevertheless tries to go on */
2529
        r = action(c, i, fd, path, &st, creation);
589✔
2530

2531
        if (S_ISDIR(st.st_mode)) {
589✔
2532
                _cleanup_closedir_ DIR *d = NULL;
218✔
2533

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

2542
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
1,025✔
2543
                        _cleanup_close_ int de_fd = -EBADF;
807✔
2544
                        _cleanup_free_ char *de_path = NULL;
807✔
2545

2546
                        if (dot_or_dot_dot(de->d_name))
807✔
2547
                                continue;
436✔
2548

2549
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
371✔
2550
                        if (de_fd < 0) {
371✔
UNCOV
2551
                                if (errno != ENOENT)
×
UNCOV
2552
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
×
UNCOV
2553
                                continue;
×
2554
                        }
2555

2556
                        de_path = path_join(path, de->d_name);
371✔
2557
                        if (!de_path) {
371✔
UNCOV
2558
                                r = log_oom();
×
UNCOV
2559
                                goto finish;
×
2560
                        }
2561

2562
                        /* Pass ownership of dirent fd over */
2563
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
371✔
2564
                }
2565
        }
2566

2567
finish:
371✔
2568
        safe_close(fd);
589✔
2569
        return r;
589✔
2570
}
2571

2572
static int glob_item(Context *c, Item *i, action_t action) {
6,542✔
2573
        _cleanup_globfree_ glob_t g = {
6,542✔
2574
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2575
        };
2576
        int r;
6,542✔
2577

2578
        assert(c);
6,542✔
2579
        assert(i);
6,542✔
2580
        assert(action);
6,542✔
2581

2582
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
6,542✔
2583
        if (r == -ENOENT)
6,542✔
2584
                return 0;
2585
        if (r < 0)
3,325✔
UNCOV
2586
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2587

2588
        r = 0;
3,325✔
2589
        STRV_FOREACH(fn, g.gl_pathv)
7,181✔
2590
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2591
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
3,856✔
2592

2593
        return r;
2594
}
2595

2596
static int glob_item_recursively(
264✔
2597
                Context *c,
2598
                Item *i,
2599
                fdaction_t action) {
2600

2601
        _cleanup_globfree_ glob_t g = {
264✔
2602
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2603
        };
2604
        int r;
264✔
2605

2606
        assert(c);
264✔
2607
        assert(i);
264✔
2608
        assert(action);
264✔
2609

2610
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
264✔
2611
        if (r == -ENOENT)
264✔
2612
                return 0;
2613
        if (r < 0)
218✔
UNCOV
2614
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2615

2616
        r = 0;
218✔
2617
        STRV_FOREACH(fn, g.gl_pathv) {
436✔
2618
                _cleanup_close_ int fd = -EBADF;
218✔
2619

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

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

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

2633
        return r;
2634
}
2635

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
2730
        path_len = strlen(path);
×
2731

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2804
static int mkdir_parents_item(Item *i, mode_t child_mode) {
17,085✔
2805
        int r;
17,085✔
2806

2807
        if (i->try_replace) {
17,085✔
UNCOV
2808
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
UNCOV
2809
                if (r < 0 && r != -ENOENT)
×
UNCOV
2810
                        return r;
×
2811
        } else
2812
                WITH_UMASK(0000)
34,170✔
2813
                        if (!arg_dry_run)
17,085✔
2814
                                (void) mkdir_parents_label(i->path, 0755);
17,085✔
2815

2816
        return 0;
2817
}
2818

2819
static int create_item(Context *c, Item *i) {
24,764✔
2820
        int r;
24,764✔
2821

2822
        assert(c);
24,764✔
2823
        assert(i);
24,764✔
2824

2825
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
24,764✔
2826

2827
        switch (i->type) {
24,764✔
2828

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

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

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

2849
        case COPY_FILES:
4,031✔
2850
                r = mkdir_parents_item(i, 0);
4,031✔
2851
                if (r < 0)
4,031✔
2852
                        return r;
2853

2854
                r = copy_files(c, i);
4,031✔
2855
                if (r < 0)
4,031✔
UNCOV
2856
                        return r;
×
2857
                break;
2858

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

2864
                break;
2865

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

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

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

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

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

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

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

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

2910
                r = create_symlink(c, i);
1,572✔
2911
                if (r < 0)
1,572✔
UNCOV
2912
                        return r;
×
2913

2914
                break;
2915

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

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

2926
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
4,266✔
2927
                if (r < 0)
2,134✔
2928
                        return r;
2929

2930
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
4,266✔
2931
                if (r < 0)
2,134✔
UNCOV
2932
                        return r;
×
2933

2934
                break;
2935

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

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

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

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

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

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

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

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

2986
        return 0;
2987
}
2988

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3081
                return 0;
3082

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

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

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

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

3097
        switch (i->type) {
18,834✔
3098

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

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

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

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

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

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

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

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

3134
        assert(i);
50✔
3135

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3209
static int process_item(
81,679✔
3210
                Context *c,
3211
                Item *i,
3212
                OperationMask operation) {
3213

3214
        OperationMask todo;
81,679✔
3215
        _cleanup_free_ char *_path = NULL;
81,679✔
3216
        const char *path;
81,679✔
3217
        int r;
81,679✔
3218

3219
        assert(c);
81,679✔
3220
        assert(i);
81,679✔
3221

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

3226
        i->done |= operation;
43,663✔
3227

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

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

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

3248
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
43,663✔
3249
        /* Failure can only be tolerated for create */
3250
        if (i->allow_failure)
43,663✔
3251
                r = 0;
1,028✔
3252

3253
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
43,663✔
3254
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
43,663✔
3255
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
43,663✔
3256

3257
        return r;
3258
}
3259

3260
static int process_item_array(
75,080✔
3261
                Context *c,
3262
                ItemArray *array,
3263
                OperationMask operation) {
3264

3265
        int r = 0;
75,080✔
3266

3267
        assert(c);
75,080✔
3268
        assert(array);
75,080✔
3269

3270
        /* Create any parent first. */
3271
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
75,080✔
3272
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
17,973✔
3273

3274
        /* Clean up all children first */
3275
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
75,080✔
3276
                ItemArray *cc;
6,777✔
3277

3278
                SET_FOREACH(cc, array->children)
22,931✔
3279
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
16,154✔
3280
        }
3281

3282
        FOREACH_ARRAY(item, array->items, array->n_items)
156,759✔
3283
                RET_GATHER(r, process_item(c, item, operation));
81,679✔
3284

3285
        return r;
75,080✔
3286
}
3287

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

3295
#if HAVE_ACL
3296
        if (i->acl_access)
92,586✔
3297
                acl_free(i->acl_access);
1,532✔
3298

3299
        if (i->acl_access_exec)
92,586✔
3300
                acl_free(i->acl_access_exec);
387✔
3301

3302
        if (i->acl_default)
92,586✔
3303
                acl_free(i->acl_default);
2,298✔
3304
#endif
3305
}
92,586✔
3306

3307
static ItemArray* item_array_free(ItemArray *a) {
23,398✔
3308
        if (!a)
23,398✔
3309
                return NULL;
3310

3311
        FOREACH_ARRAY(item, a->items, a->n_items)
48,246✔
3312
                item_free_contents(item);
24,848✔
3313

3314
        set_free(a->children);
23,398✔
3315
        free(a->items);
23,398✔
3316
        return mfree(a);
23,398✔
3317
}
3318

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

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

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

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

3336
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,723✔
3337
                /* check if the items are the same */
3338
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
544✔
3339
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
525✔
3340

3341
                        a->uid_set == b->uid_set &&
525✔
3342
                        a->uid == b->uid &&
525✔
3343
                        a->uid_only_create == b->uid_only_create &&
525✔
3344

3345
                        a->gid_set == b->gid_set &&
525✔
3346
                        a->gid == b->gid &&
525✔
3347
                        a->gid_only_create == b->gid_only_create &&
525✔
3348

3349
                        a->mode_set == b->mode_set &&
525✔
3350
                        a->mode == b->mode &&
525✔
3351
                        a->mode_only_create == b->mode_only_create &&
525✔
3352

3353
                        a->age_set == b->age_set &&
525✔
3354
                        a->age == b->age &&
525✔
3355

3356
                        a->age_by_file == b->age_by_file &&
525✔
3357
                        a->age_by_dir == b->age_by_dir &&
525✔
3358

3359
                        a->mask_perms == b->mask_perms &&
525✔
3360

3361
                        a->keep_first_level == b->keep_first_level &&
1,613✔
3362

3363
                        a->major_minor == b->major_minor;
525✔
3364

3365
        return true;
3366
}
3367

3368
static bool should_include_path(const char *path) {
67,647✔
3369
        STRV_FOREACH(prefix, arg_exclude_prefixes)
87,310✔
3370
                if (path_startswith(path, *prefix)) {
22,217✔
3371
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,554✔
3372
                                  path, *prefix);
3373
                        return false;
2,554✔
3374
                }
3375

3376
        STRV_FOREACH(prefix, arg_include_prefixes)
104,419✔
3377
                if (path_startswith(path, *prefix)) {
44,434✔
3378
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
5,108✔
3379
                        return true;
5,108✔
3380
                }
3381

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

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

3390
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
25,767✔
3391
        int r;
25,767✔
3392

3393
        assert(i);
25,767✔
3394

3395
        if (!i->argument)
25,767✔
3396
                return 0;
3397

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

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

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

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

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

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

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

3435
static int patch_var_run(const char *fname, unsigned line, char **path) {
67,648✔
3436
        const char *k;
67,648✔
3437
        char *n;
67,648✔
3438

3439
        assert(path);
67,648✔
3440
        assert(*path);
67,648✔
3441

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

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

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

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

3470
        free_and_replace(*path, n);
×
3471

UNCOV
3472
        return 0;
×
3473
}
3474

3475
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
9,145✔
3476
        int r;
9,145✔
3477

3478
        assert(user);
9,145✔
3479
        assert(ret_uid);
9,145✔
3480

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

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

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

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

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

3503
        assert(group);
10,687✔
3504
        assert(ret_gid);
10,687✔
3505

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3574
        return 0;
146✔
3575
}
3576

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

3581
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
3,173✔
3582
                if (item_compatible(e, i))
1,723✔
3583
                        continue;
1,704✔
3584

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

3591
        return false;
3592
}
3593

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

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

3615
        assert(fname);
67,738✔
3616
        assert(line >= 1);
67,738✔
3617
        assert(buffer);
67,738✔
3618

3619
        const Specifier specifier_table[] = {
67,738✔
3620
                { 'h', specifier_user_home,       NULL },
3621

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

3627
                COMMON_SYSTEM_SPECIFIERS,
3628
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
67,738✔
3629
                COMMON_TMP_SPECIFIERS,
3630
                {}
3631
        };
3632

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

3653
        if (!empty_or_dash(buffer)) {
67,738✔
3654
                i.argument = strdup(buffer);
16,283✔
3655
                if (!i.argument)
16,283✔
UNCOV
3656
                        return log_oom();
×
3657
        }
3658

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

3665
        for (int pos = 1; action[pos]; pos++)
89,355✔
3666
                if (action[pos] == '!' && !boot)
21,617✔
3667
                        boot = true;
3668
                else if (action[pos] == '+' && !append_or_force)
11,528✔
3669
                        append_or_force = true;
3670
                else if (action[pos] == '-' && !allow_failure)
7,674✔
3671
                        allow_failure = true;
3672
                else if (action[pos] == '=' && !try_replace)
6,142✔
3673
                        try_replace = true;
3674
                else if (action[pos] == '~' && !unbase64)
6,142✔
3675
                        unbase64 = true;
3676
                else if (action[pos] == '^' && !from_cred)
6,142✔
3677
                        from_cred = true;
3678
                else if (action[pos] == '$' && !purge)
4,610✔
3679
                        purge = true;
3680
                else if (action[pos] == '?' && !ignore_if_target_missing)
2✔
3681
                        ignore_if_target_missing = true;
3682
                else {
UNCOV
3683
                        *invalid_config = true;
×
UNCOV
3684
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3685
                                          "Unknown modifiers in command: %s", action);
3686
                }
3687

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

3694
        i.type = action[0];
67,648✔
3695
        i.append_or_force = append_or_force;
67,648✔
3696
        i.allow_failure = allow_failure;
67,648✔
3697
        i.try_replace = try_replace;
67,648✔
3698
        i.purge = purge;
67,648✔
3699
        i.ignore_if_target_missing = ignore_if_target_missing;
67,648✔
3700

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

3711
        r = patch_var_run(fname, line, &i.path);
67,648✔
3712
        if (r < 0)
67,648✔
3713
                return r;
3714

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

3721
        path_simplify(i.path);
67,648✔
3722

3723
        switch (i.type) {
67,648✔
3724

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

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

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

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

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

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

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

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

3793
                break;
3794

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

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

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

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

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

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

3866
        if (!should_include_path(i.path))
67,647✔
3867
                return 0;
3868

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

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

3890
                break;
3891

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

3902
                }
3903

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

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

3913
                path_simplify(i.argument);
4,540✔
3914

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

3922
                break;
3923

3924
        default:
25,258✔
3925
                ;
25,258✔
3926
        }
3927

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

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

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

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

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

3961
        if (!empty_or_root(arg_root)) {
24,860✔
3962
                char *p;
14✔
3963

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

3970
        if (!empty_or_dash(user)) {
24,860✔
3971
                const char *u;
9,145✔
3972

3973
                u = startswith(user, ":");
9,145✔
3974
                if (u)
9,145✔
3975
                        i.uid_only_create = true;
4✔
3976
                else
3977
                        u = user;
3978

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

3991
        if (!empty_or_dash(group)) {
24,860✔
3992
                const char *g;
10,687✔
3993

3994
                g = startswith(group, ":");
10,687✔
3995
                if (g)
10,687✔
3996
                        i.gid_only_create = true;
392✔
3997
                else
3998
                        g = group;
3999

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

4012
        if (!empty_or_dash(mode)) {
24,860✔
4013
                const char *mm;
4014
                unsigned m;
4015

4016
                for (mm = mode;; mm++)
523✔
4017
                        if (*mm == '~')
16,424✔
4018
                                i.mask_perms = true;
131✔
4019
                        else if (*mm == ':')
16,293✔
4020
                                i.mode_only_create = true;
392✔
4021
                        else
4022
                                break;
4023

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

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

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

4048
        if (!empty_or_dash(age)) {
24,860✔
4049
                const char *a = age;
1,324✔
4050
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,324✔
4051

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

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

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

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

4083
                i.age_set = true;
1,315✔
4084
        }
4085

4086
        h = needs_glob(i.type) ? c->globs : c->items;
24,851✔
4087

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

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

4107
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
24,848✔
UNCOV
4108
                return log_oom();
×
4109

4110
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
24,848✔
4111

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

4115
        return 0;
4116
}
4117

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

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

4126
        pager_open(arg_pager_flags);
×
4127

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

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

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

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

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

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

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

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

4192
        return 0;
4193
}
4194

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

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

4240
        int c, r;
700✔
4241

4242
        assert(argc >= 0);
700✔
4243
        assert(argv);
700✔
4244

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

4247
                switch (c) {
2,278✔
4248

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

UNCOV
4252
                case ARG_VERSION:
×
4253
                        return version();
×
4254

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

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

4263
                case ARG_USER:
179✔
4264
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
179✔
4265
                        break;
179✔
4266

4267
                case ARG_CREATE:
648✔
4268
                        arg_operation |= OPERATION_CREATE;
648✔
4269
                        break;
648✔
4270

4271
                case ARG_CLEAN:
39✔
4272
                        arg_operation |= OPERATION_CLEAN;
39✔
4273
                        break;
39✔
4274

4275
                case ARG_REMOVE:
314✔
4276
                        arg_operation |= OPERATION_REMOVE;
314✔
4277
                        break;
314✔
4278

4279
                case ARG_BOOT:
552✔
4280
                        arg_boot = true;
552✔
4281
                        break;
552✔
4282

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

4287
                case ARG_GRACEFUL:
126✔
4288
                        arg_graceful = true;
126✔
4289
                        break;
126✔
4290

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

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

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

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

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

4324
                        break;
4325

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

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

4340
                        arg_replace = optarg;
×
4341
                        break;
×
4342

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

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

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

UNCOV
4354
                default:
×
UNCOV
4355
                        assert_not_reached();
×
4356
                }
4357

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

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

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

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

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

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

4382
        return 1;
4383
}
4384

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

4392
        ItemArray *ia;
16,286✔
4393
        int r = 0;
16,286✔
4394

4395
        assert(c);
16,286✔
4396
        assert(fn);
16,286✔
4397

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

4403
        /* we have to determine age parameter for each entry of type X */
4404
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
124,113✔
4405
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
221,945✔
4406
                        ItemArray *ja;
113,743✔
4407
                        Item *candidate_item = NULL;
113,743✔
4408

4409
                        if (i->type != IGNORE_DIRECTORY_PATH)
113,743✔
4410
                                continue;
111,889✔
4411

4412
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
168,676✔
4413
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
339,018✔
4414
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
172,196✔
4415
                                                             TRUNCATE_DIRECTORY,
4416
                                                             CREATE_SUBVOLUME,
4417
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4418
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4419
                                                continue;
87,396✔
4420

4421
                                        if (path_equal(j->path, i->path)) {
84,800✔
4422
                                                candidate_item = j;
4423
                                                break;
4424
                                        }
4425

4426
                                        if (candidate_item
84,800✔
4427
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
8,035✔
4428
                                            : path_startswith(i->path, j->path) != NULL)
76,765✔
4429
                                                candidate_item = j;
4430
                                }
4431

4432
                        if (candidate_item && candidate_item->age_set) {
1,854✔
4433
                                i->age = candidate_item->age;
1,324✔
4434
                                i->age_set = true;
1,324✔
4435
                        }
4436
                }
4437

4438
        return r;
15,911✔
4439
}
4440

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

4448
        assert(c);
138✔
4449

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

4456
        return 0;
4457
}
4458

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

UNCOV
4465
        _cleanup_strv_free_ char **files = NULL;
×
4466
        _cleanup_free_ char *p = NULL;
562✔
4467
        int r;
562✔
4468

4469
        assert(c);
562✔
4470

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

4475
        STRV_FOREACH(f, files)
16,332✔
4476
                if (p && path_equal(*f, p)) {
15,770✔
UNCOV
4477
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4478

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

4487
        return 0;
4488
}
4489

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

4495
        assert(c);
700✔
4496

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

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

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

4511
static int link_parent(Context *c, ItemArray *a) {
23,398✔
4512
        const char *path;
23,398✔
4513
        char *prefix;
23,398✔
4514
        int r;
23,398✔
4515

4516
        assert(c);
23,398✔
4517
        assert(a);
23,398✔
4518

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

4524
        if (a->n_items <= 0)
23,398✔
4525
                return 0;
4526

4527
        path = a->items[0].path;
23,398✔
4528
        prefix = newa(char, strlen(path) + 1);
23,398✔
4529
        PATH_FOREACH_PREFIX(prefix, path) {
77,671✔
4530
                ItemArray *j;
40,852✔
4531

4532
                j = ordered_hashmap_get(c->items, prefix);
40,852✔
4533
                if (!j)
40,852✔
4534
                        j = ordered_hashmap_get(c->globs, prefix);
31,800✔
4535
                if (j) {
31,800✔
4536
                        r = set_ensure_put(&j->children, NULL, a);
9,977✔
4537
                        if (r < 0)
9,977✔
UNCOV
4538
                                return log_oom();
×
4539

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

4545
        return 0;
4546
}
4547

4548
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
23,398✔
4549
                                              ItemArray, item_array_free);
4550

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

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

4572
        log_setup();
700✔
4573

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

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

4587
        switch (arg_runtime_scope) {
700✔
4588

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

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

UNCOV
4601
        default:
×
4602
                assert_not_reached();
×
4603
        }
4604

4605
        if (DEBUG_LOGGING) {
700✔
4606
                _cleanup_free_ char *t = NULL;
588✔
4607

4608
                STRV_FOREACH(i, config_dirs) {
3,298✔
4609
                        _cleanup_free_ char *j = NULL;
2,710✔
4610

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

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

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

4622
        if (arg_cat_flags != CAT_CONFIG_OFF)
700✔
UNCOV
4623
                return cat_config(config_dirs, argv + optind);
×
4624

4625
        if (should_bypass("SYSTEMD_TMPFILES"))
700✔
4626
                return 0;
4627

4628
        umask(0022);
700✔
4629

4630
        r = mac_init();
700✔
4631
        if (r < 0)
700✔
4632
                return r;
4633

4634
#ifndef STANDALONE
4635
        if (arg_image) {
700✔
UNCOV
4636
                assert(!arg_root);
×
4637

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

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

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

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

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

4682
        /* Let's now link up all child/parent relationships */
4683
        ORDERED_HASHMAP_FOREACH(a, c.items) {
17,300✔
4684
                r = link_parent(&c, a);
16,600✔
4685
                if (r < 0)
16,600✔
UNCOV
4686
                        return r;
×
4687
        }
4688
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
7,498✔
4689
                r = link_parent(&c, a);
6,798✔
4690
                if (r < 0)
6,798✔
UNCOV
4691
                        return r;
×
4692
        }
4693

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

4699
                if (phase == PHASE_PURGE)
2,100✔
4700
                        op = arg_operation & OPERATION_PURGE;
700✔
4701
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,400✔
4702
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
700✔
4703
                else if (phase == PHASE_CREATE)
700✔
4704
                        op = arg_operation & OPERATION_CREATE;
700✔
4705
                else
UNCOV
4706
                        assert_not_reached();
×
4707

4708
                if (op == 0) /* Nothing requested in this phase */
2,100✔
4709
                        continue;
1,094✔
4710

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

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

4720
        if (ERRNO_IS_NEG_RESOURCE(r))
1,400✔
4721
                return r;
4722
        if (invalid_config)
700✔
4723
                return EX_DATAERR;
4724
        if (r < 0)
690✔
4725
                return EX_CANTCREAT;
15✔
4726
        return 0;
4727
}
4728

4729
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
700✔
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