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

systemd / systemd / 14872145375

06 May 2025 09:07PM UTC coverage: 72.232% (+0.02%) from 72.214%
14872145375

push

github

DaanDeMeyer
string-table: annotate _to_string and _from_string with _const_ and _pure_, respectively

Follow-up for c94f6ab1b

297286 of 411572 relevant lines covered (72.23%)

695615.99 hits per line

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

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

3
#include <errno.h>
4
#include <fcntl.h>
5
#include <fnmatch.h>
6
#include <getopt.h>
7
#include <limits.h>
8
#include <stdbool.h>
9
#include <stddef.h>
10
#include <stdlib.h>
11
#include <sys/file.h>
12
#include <sysexits.h>
13
#include <time.h>
14
#include <unistd.h>
15

16
#include "sd-path.h"
17

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

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

84
typedef enum OperationMask {
85
        OPERATION_CREATE = 1 << 0,
86
        OPERATION_REMOVE = 1 << 1,
87
        OPERATION_CLEAN  = 1 << 2,
88
        OPERATION_PURGE  = 1 << 3,
89
} OperationMask;
90

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

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

124
typedef enum AgeBy {
125
        AGE_BY_ATIME = 1 << 0,
126
        AGE_BY_BTIME = 1 << 1,
127
        AGE_BY_CTIME = 1 << 2,
128
        AGE_BY_MTIME = 1 << 3,
129

130
        /* All file timestamp types are checked by default. */
131
        AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
132
        AGE_BY_DEFAULT_DIR  = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME,
133
} AgeBy;
134

135
typedef struct Item {
136
        ItemType type;
137

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

154
        dev_t major_minor;
155
        unsigned attribute_value;
156
        unsigned attribute_mask;
157

158
        bool uid_set:1;
159
        bool gid_set:1;
160
        bool mode_set:1;
161
        bool uid_only_create:1;
162
        bool gid_only_create:1;
163
        bool mode_only_create:1;
164
        bool age_set:1;
165
        bool mask_perms:1;
166
        bool attribute_set:1;
167

168
        bool keep_first_level:1;
169

170
        bool append_or_force:1;
171

172
        bool allow_failure:1;
173

174
        bool try_replace:1;
175

176
        bool purge:1;
177

178
        bool ignore_if_target_missing:1;
179

180
        OperationMask done;
181
} Item;
182

183
typedef struct ItemArray {
184
        Item *items;
185
        size_t n_items;
186

187
        struct ItemArray *parent;
188
        Set *children;
189
} ItemArray;
190

191
typedef enum DirectoryType {
192
        DIRECTORY_RUNTIME,
193
        DIRECTORY_STATE,
194
        DIRECTORY_CACHE,
195
        DIRECTORY_LOGS,
196
        _DIRECTORY_TYPE_MAX,
197
} DirectoryType;
198

199
typedef enum {
200
        CREATION_NORMAL,
201
        CREATION_EXISTING,
202
        CREATION_FORCE,
203
        _CREATION_MODE_MAX,
204
        _CREATION_MODE_INVALID = -EINVAL,
205
} CreationMode;
206

207
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
208
static bool arg_dry_run = false;
209
static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
210
static OperationMask arg_operation = 0;
211
static bool arg_boot = false;
212
static bool arg_graceful = false;
213
static PagerFlags arg_pager_flags = 0;
214
static char **arg_include_prefixes = NULL;
215
static char **arg_exclude_prefixes = NULL;
216
static char *arg_root = NULL;
217
static char *arg_image = NULL;
218
static char *arg_replace = NULL;
219
static ImagePolicy *arg_image_policy = NULL;
220

221
#define MAX_DEPTH 256
222

223
typedef struct Context {
224
        OrderedHashmap *items;
225
        OrderedHashmap *globs;
226
        Set *unix_sockets;
227
        Hashmap *uid_cache;
228
        Hashmap *gid_cache;
229
} Context;
230

231
STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, strv_freep);
680✔
232
STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, strv_freep);
680✔
233
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
680✔
234
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
680✔
235
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
680✔
236

237
static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
238
        [CREATION_NORMAL]   = "Created",
239
        [CREATION_EXISTING] = "Found existing",
240
        [CREATION_FORCE]    = "Created replacement",
241
};
242

243
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
10,497✔
244

245
static void context_done(Context *c) {
680✔
246
        assert(c);
680✔
247

248
        ordered_hashmap_free(c->items);
680✔
249
        ordered_hashmap_free(c->globs);
680✔
250

251
        set_free(c->unix_sockets);
680✔
252

253
        hashmap_free(c->uid_cache);
680✔
254
        hashmap_free(c->gid_cache);
680✔
255
}
680✔
256

257
/* Different kinds of errors that mean that information is not available in the environment. */
258
static bool ERRNO_IS_NEG_NOINFO(intmax_t r) {
89,183✔
259
        return IN_SET(r,
89,183✔
260
                      -EUNATCH,    /* os-release or machine-id missing */
261
                      -ENOMEDIUM,  /* machine-id or another file empty */
262
                      -ENOPKG,     /* machine-id is uninitialized */
263
                      -ENXIO);     /* env var is unset */
264
}
265

266
static int specifier_directory(
×
267
                char specifier,
268
                const void *data,
269
                const char *root,
270
                const void *userdata,
271
                char **ret) {
272

273
        struct table_entry {
×
274
                uint64_t type;
275
                const char *suffix;
276
        };
277

278
        static const struct table_entry paths_system[] = {
×
279
                [DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME            },
280
                [DIRECTORY_STATE] =   { SD_PATH_SYSTEM_STATE_PRIVATE      },
281
                [DIRECTORY_CACHE] =   { SD_PATH_SYSTEM_STATE_CACHE        },
282
                [DIRECTORY_LOGS] =    { SD_PATH_SYSTEM_STATE_LOGS         },
283
        };
284

285
        static const struct table_entry paths_user[] = {
×
286
                [DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME              },
287
                [DIRECTORY_STATE] =   { SD_PATH_USER_STATE_PRIVATE        },
288
                [DIRECTORY_CACHE] =   { SD_PATH_USER_STATE_CACHE          },
289
                [DIRECTORY_LOGS] =    { SD_PATH_USER_STATE_PRIVATE, "log" },
290
        };
291

292
        const struct table_entry *paths;
×
293
        _cleanup_free_ char *p = NULL;
×
294
        unsigned i;
×
295
        int r;
×
296

297
        assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
×
298
        paths = arg_runtime_scope == RUNTIME_SCOPE_USER ? paths_user : paths_system;
×
299

300
        i = PTR_TO_UINT(data);
×
301
        assert(i < ELEMENTSOF(paths_system));
×
302

303
        r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
×
304
        if (r < 0)
×
305
                return r;
306

307
        if (arg_root) {
×
308
                _cleanup_free_ char *j = NULL;
×
309

310
                j = path_join(arg_root, p);
×
311
                if (!j)
×
312
                        return -ENOMEM;
×
313

314
                *ret = TAKE_PTR(j);
×
315
        } else
316
                *ret = TAKE_PTR(p);
×
317

318
        return 0;
319
}
320

321
static int log_unresolvable_specifier(const char *filename, unsigned line) {
×
322
        static bool notified = false;
×
323

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

334
        int log_level = notified || arg_root || running_in_chroot() > 0 ?
×
335
                LOG_DEBUG : LOG_NOTICE;
×
336

337
        log_syntax(NULL,
×
338
                   log_level,
339
                   filename, line, 0,
340
                   "Failed to resolve specifier: %s, skipping.",
341
                   arg_runtime_scope == RUNTIME_SCOPE_USER ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
342

343
        if (!notified)
×
344
                log_full(log_level,
×
345
                         "All rules containing unresolvable specifiers will be skipped.");
346

347
        notified = true;
×
348
        return 0;
×
349
}
350

351
#define log_action(would, doing, fmt, ...)              \
352
        log_full(arg_dry_run ? LOG_INFO : LOG_DEBUG,    \
353
                 fmt,                                   \
354
                 arg_dry_run ? (would) : (doing),       \
355
                 __VA_ARGS__)
356

357
static int user_config_paths(char ***ret) {
176✔
358
        _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
176✔
359
        _cleanup_free_ char *runtime_config = NULL;
176✔
360
        int r;
176✔
361

362
        assert(ret);
176✔
363

364
        /* Combined user-specific and global dirs */
365
        r = user_search_dirs("/user-tmpfiles.d", &config_dirs, &data_dirs);
176✔
366
        if (r < 0)
176✔
367
                return r;
368

369
        r = xdg_user_runtime_dir("/user-tmpfiles.d", &runtime_config);
176✔
370
        if (r < 0 && !ERRNO_IS_NEG_NOINFO(r))
176✔
371
                return r;
372

373
        r = strv_consume(&config_dirs, TAKE_PTR(runtime_config));
176✔
374
        if (r < 0)
176✔
375
                return r;
376

377
        r = strv_extend_strv_consume(&config_dirs, TAKE_PTR(data_dirs), /* filter_duplicates = */ true);
176✔
378
        if (r < 0)
176✔
379
                return r;
380

381
        r = path_strv_make_absolute_cwd(config_dirs);
176✔
382
        if (r < 0)
176✔
383
                return r;
384

385
        *ret = TAKE_PTR(config_dirs);
176✔
386
        return 0;
176✔
387
}
388

389
static bool needs_purge(ItemType t) {
4,419✔
390
        return IN_SET(t,
4,419✔
391
                      CREATE_FILE,
392
                      TRUNCATE_FILE,
393
                      CREATE_DIRECTORY,
394
                      TRUNCATE_DIRECTORY,
395
                      CREATE_SUBVOLUME,
396
                      CREATE_SUBVOLUME_INHERIT_QUOTA,
397
                      CREATE_SUBVOLUME_NEW_QUOTA,
398
                      CREATE_FIFO,
399
                      CREATE_SYMLINK,
400
                      CREATE_CHAR_DEVICE,
401
                      CREATE_BLOCK_DEVICE,
402
                      COPY_FILES,
403
                      WRITE_FILE,
404
                      EMPTY_DIRECTORY);
405
}
406

407
static bool needs_glob(ItemType t) {
23,798✔
408
        return IN_SET(t,
23,798✔
409
                      WRITE_FILE,
410
                      EMPTY_DIRECTORY,
411
                      SET_XATTR,
412
                      RECURSIVE_SET_XATTR,
413
                      SET_ACL,
414
                      RECURSIVE_SET_ACL,
415
                      SET_ATTRIBUTE,
416
                      RECURSIVE_SET_ATTRIBUTE,
417
                      IGNORE_PATH,
418
                      IGNORE_DIRECTORY_PATH,
419
                      REMOVE_PATH,
420
                      RECURSIVE_REMOVE_PATH,
421
                      RELABEL_PATH,
422
                      RECURSIVE_RELABEL_PATH,
423
                      ADJUST_MODE);
424
}
425

426
static bool takes_ownership(ItemType t) {
5,976✔
427
        return IN_SET(t,
5,976✔
428
                      CREATE_FILE,
429
                      TRUNCATE_FILE,
430
                      CREATE_DIRECTORY,
431
                      TRUNCATE_DIRECTORY,
432
                      CREATE_SUBVOLUME,
433
                      CREATE_SUBVOLUME_INHERIT_QUOTA,
434
                      CREATE_SUBVOLUME_NEW_QUOTA,
435
                      CREATE_FIFO,
436
                      CREATE_SYMLINK,
437
                      CREATE_CHAR_DEVICE,
438
                      CREATE_BLOCK_DEVICE,
439
                      COPY_FILES,
440
                      WRITE_FILE,
441
                      EMPTY_DIRECTORY,
442
                      IGNORE_PATH,
443
                      IGNORE_DIRECTORY_PATH,
444
                      REMOVE_PATH,
445
                      RECURSIVE_REMOVE_PATH);
446
}
447

448
static bool supports_ignore_if_target_missing(ItemType t) {
2✔
449
        return t == CREATE_SYMLINK;
2✔
450
}
451

452
static struct Item* find_glob(OrderedHashmap *h, const char *match) {
189✔
453
        ItemArray *j;
189✔
454

455
        ORDERED_HASHMAP_FOREACH(j, h)
500✔
456
                FOREACH_ARRAY(item, j->items, j->n_items)
678✔
457
                        if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
367✔
458
                                return item;
20✔
459
        return NULL;
169✔
460
}
461

462
static int load_unix_sockets(Context *c) {
×
463
        _cleanup_set_free_ Set *sockets = NULL;
×
464
        _cleanup_fclose_ FILE *f = NULL;
×
465
        int r;
×
466

467
        if (c->unix_sockets)
×
468
                return 0;
469

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

472
        f = fopen("/proc/net/unix", "re");
×
473
        if (!f)
×
474
                return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
×
475
                                      "Failed to open /proc/net/unix, ignoring: %m");
476

477
        /* Skip header */
478
        r = read_line(f, LONG_LINE_MAX, NULL);
×
479
        if (r < 0)
×
480
                return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
×
481
        if (r == 0)
×
482
                return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
×
483

484
        for (;;) {
×
485
                _cleanup_free_ char *line = NULL;
×
486
                char *p;
×
487

488
                r = read_line(f, LONG_LINE_MAX, &line);
×
489
                if (r < 0)
×
490
                        return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
×
491
                if (r == 0) /* EOF */
×
492
                        break;
493

494
                p = strchr(line, ':');
×
495
                if (!p)
×
496
                        continue;
×
497

498
                if (strlen(p) < 37)
×
499
                        continue;
×
500

501
                p += 37;
×
502
                p += strspn(p, WHITESPACE);
×
503
                p += strcspn(p, WHITESPACE); /* skip one more word */
×
504
                p += strspn(p, WHITESPACE);
×
505

506
                if (!path_is_absolute(p))
×
507
                        continue;
×
508

509
                r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
×
510
                if (r < 0)
×
511
                        return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
×
512
        }
513

514
        c->unix_sockets = TAKE_PTR(sockets);
×
515
        return 1;
×
516
}
517

518
static bool unix_socket_alive(Context *c, const char *fn) {
×
519
        assert(c);
×
520
        assert(fn);
×
521

522
        if (load_unix_sockets(c) < 0)
×
523
                return true;     /* We don't know, so assume yes */
524

525
        return set_contains(c->unix_sockets, fn);
×
526
}
527

528
/* Accessors for the argument in binary format */
529
static const void* item_binary_argument(const Item *i) {
1,803✔
530
        assert(i);
1,803✔
531
        return i->binary_argument ?: i->argument;
1,803✔
532
}
533

534
static size_t item_binary_argument_size(const Item *i) {
1,583✔
535
        assert(i);
1,583✔
536
        return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
1,583✔
537
}
538

539
static DIR* xopendirat_nomod(int dirfd, const char *path) {
1,576✔
540
        DIR *dir;
1,576✔
541

542
        dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
1,576✔
543
        if (dir)
1,576✔
544
                return dir;
545

546
        if (!IN_SET(errno, ENOENT, ELOOP))
497✔
547
                log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
11✔
548
        if (!ERRNO_IS_PRIVILEGE(errno))
497✔
549
                return NULL;
550

551
        dir = xopendirat(dirfd, path, O_NOFOLLOW);
×
552
        if (!dir)
×
553
                log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with or without O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
×
554

555
        return dir;
556
}
557

558
static DIR* opendir_nomod(const char *path) {
1,535✔
559
        return xopendirat_nomod(AT_FDCWD, path);
1,535✔
560
}
561

562
static int opendir_and_stat(
547✔
563
                const char *path,
564
                DIR **ret,
565
                struct statx *ret_sx,
566
                bool *ret_mountpoint) {
567

568
        _cleanup_closedir_ DIR *d = NULL;
547✔
569
        struct statx sx1;
547✔
570
        int r;
547✔
571

572
        assert(path);
547✔
573
        assert(ret);
547✔
574
        assert(ret_sx);
547✔
575
        assert(ret_mountpoint);
547✔
576

577
        /* Do opendir() and statx() on the directory.
578
         * Return 1 if successful, 0 if file doesn't exist or is not a directory,
579
         * negative errno otherwise.
580
         */
581

582
        d = opendir_nomod(path);
547✔
583
        if (!d) {
547✔
584
                bool ignore = IN_SET(errno, ENOENT, ENOTDIR);
495✔
585
                r = log_full_errno(ignore ? LOG_DEBUG : LOG_ERR,
495✔
586
                                   errno, "Failed to open directory %s: %m", path);
587
                if (!ignore)
495✔
588
                        return r;
589

590
                *ret = NULL;
495✔
591
                *ret_sx = (struct statx) {};
495✔
592
                *ret_mountpoint = false;
495✔
593
                return 0;
495✔
594
        }
595

596
        if (statx(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx1) < 0)
52✔
597
                return log_error_errno(errno, "statx(%s) failed: %m", path);
×
598

599
        if (FLAGS_SET(sx1.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
52✔
600
                *ret_mountpoint = FLAGS_SET(sx1.stx_attributes, STATX_ATTR_MOUNT_ROOT);
52✔
601
        else {
602
                struct statx sx2;
×
603
                if (statx(dirfd(d), "..", 0, STATX_INO, &sx2) < 0)
×
604
                        return log_error_errno(errno, "statx(%s/..) failed: %m", path);
×
605

606
                *ret_mountpoint = !statx_mount_same(&sx1, &sx2);
×
607
        }
608

609
        *ret = TAKE_PTR(d);
52✔
610
        *ret_sx = sx1;
52✔
611
        return 1;
52✔
612
}
613

614
static bool needs_cleanup(
169✔
615
                nsec_t atime,
616
                nsec_t btime,
617
                nsec_t ctime,
618
                nsec_t mtime,
619
                nsec_t cutoff,
620
                const char *sub_path,
621
                AgeBy age_by,
622
                bool is_dir) {
623

624
        if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
169✔
625
                /* Follows spelling in stat(1). */
626
                log_debug("%s \"%s\": modify time %s is too new.",
38✔
627
                          is_dir ? "Directory" : "File",
628
                          sub_path,
629
                          FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
630

631
                return false;
28✔
632
        }
633

634
        if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
141✔
635
                log_debug("%s \"%s\": access time %s is too new.",
117✔
636
                          is_dir ? "Directory" : "File",
637
                          sub_path,
638
                          FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
639

640
                return false;
63✔
641
        }
642

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

653
                return false;
7✔
654
        }
655

656
        if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
71✔
657
                log_debug("%s \"%s\": birth time %s is too new.",
8✔
658
                          is_dir ? "Directory" : "File",
659
                          sub_path,
660
                          FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
661

662
                return false;
5✔
663
        }
664

665
        return true;
666
}
667

668
static int dir_cleanup(
93✔
669
                Context *c,
670
                Item *i,
671
                const char *p,
672
                DIR *d,
673
                nsec_t self_atime_nsec,
674
                nsec_t self_mtime_nsec,
675
                nsec_t cutoff_nsec,
676
                dev_t rootdev_major,
677
                dev_t rootdev_minor,
678
                bool mountpoint,
679
                int maxdepth,
680
                bool keep_this_level,
681
                AgeBy age_by_file,
682
                AgeBy age_by_dir) {
683

684
        bool deleted = false;
93✔
685
        int r = 0;
93✔
686

687
        assert(c);
93✔
688
        assert(i);
93✔
689
        assert(d);
93✔
690

691
        FOREACH_DIRENT_ALL(de, d, break) {
473✔
692
                _cleanup_free_ char *sub_path = NULL;
380✔
693
                nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
380✔
694

695
                if (dot_or_dot_dot(de->d_name))
380✔
696
                        continue;
186✔
697

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

709
                struct statx sx;
194✔
710
                if (statx(dirfd(d), de->d_name,
194✔
711
                          AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
712
                          STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
713
                          &sx) < 0) {
714
                        if (errno == ENOENT)
×
715
                                continue;
×
716

717
                        /* FUSE, NFS mounts, SELinux might return EACCES */
718
                        log_full_errno(errno == EACCES ? LOG_DEBUG : LOG_ERR, errno,
×
719
                                       "statx(%s/%s) failed: %m", p, de->d_name);
720
                        continue;
×
721
                }
722

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

738
                        /* Try to detect bind mounts of the same filesystem instance; they do not differ in
739
                         * device major/minors. This type of query is not supported on all kernels or
740
                         * filesystem types though. */
741
                        if (S_ISDIR(sx.stx_mode)) {
×
742
                                int q;
×
743

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

754
                atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : 0;
388✔
755
                mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : 0;
388✔
756
                ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : 0;
388✔
757
                btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : 0;
388✔
758

759
                sub_path = path_join(p, de->d_name);
194✔
760
                if (!sub_path) {
194✔
761
                        r = log_oom();
×
762
                        goto finish;
×
763
                }
764

765
                /* Is there an item configured for this path? */
766
                if (ordered_hashmap_get(c->items, sub_path)) {
194✔
767
                        log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
5✔
768
                        continue;
5✔
769
                }
770

771
                if (find_glob(c->globs, sub_path)) {
189✔
772
                        log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
20✔
773
                        continue;
20✔
774
                }
775

776
                if (S_ISDIR(sx.stx_mode)) {
169✔
777
                        _cleanup_closedir_ DIR *sub_dir = NULL;
×
778

779
                        if (mountpoint &&
41✔
780
                            streq(de->d_name, "lost+found") &&
4✔
781
                            sx.stx_uid == 0) {
×
782
                                log_debug("Ignoring directory \"%s\".", sub_path);
×
783
                                continue;
×
784
                        }
785

786
                        if (maxdepth <= 0)
41✔
787
                                log_warning("Reached max depth on \"%s\".", sub_path);
×
788
                        else {
789
                                int q;
41✔
790

791
                                sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
41✔
792
                                if (!sub_dir) {
41✔
793
                                        if (errno != ENOENT)
×
794
                                                r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
×
795

796
                                        continue;
×
797
                                }
798

799
                                if (!arg_dry_run &&
78✔
800
                                    flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
37✔
801
                                        log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path);
×
802
                                        continue;
×
803
                                }
804

805
                                q = dir_cleanup(c, i,
41✔
806
                                                sub_path, sub_dir,
807
                                                atime_nsec, mtime_nsec, cutoff_nsec,
808
                                                rootdev_major, rootdev_minor,
809
                                                false, maxdepth-1, false,
810
                                                age_by_file, age_by_dir);
811
                                if (q < 0)
41✔
812
                                        r = q;
×
813
                        }
814

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

820
                        if (keep_this_level) {
41✔
821
                                log_debug("Keeping directory \"%s\".", sub_path);
×
822
                                continue;
×
823
                        }
824

825
                        /*
826
                         * Check the file timestamps of an entry against the
827
                         * given cutoff time; delete if it is older.
828
                         */
829
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
41✔
830
                                           cutoff_nsec, sub_path, age_by_dir, true))
831
                                continue;
29✔
832

833
                        log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path);
16✔
834
                        if (!arg_dry_run &&
20✔
835
                            unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0 &&
8✔
836
                            !IN_SET(errno, ENOENT, ENOTEMPTY))
×
837
                                r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
×
838

839
                } else {
840
                        _cleanup_close_ int fd = -EBADF; /* This file descriptor is defined here so that the
380✔
841
                                                          * lock that is taken below is only dropped _after_
842
                                                          * the unlink operation has finished. */
843

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

851
                        if (mountpoint &&
128✔
852
                            S_ISREG(sx.stx_mode) &&
×
853
                            sx.stx_uid == 0 &&
×
854
                            STR_IN_SET(de->d_name,
×
855
                                       ".journal",
856
                                       "aquota.user",
857
                                       "aquota.group")) {
858
                                log_debug("Skipping \"%s\".", sub_path);
×
859
                                continue;
×
860
                        }
861

862
                        /* Ignore sockets that are listed in /proc/net/unix */
863
                        if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
128✔
864
                                log_debug("Skipping \"%s\": live socket.", sub_path);
×
865
                                continue;
×
866
                        }
867

868
                        /* Ignore device nodes */
869
                        if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
128✔
870
                                log_debug("Skipping \"%s\": a device.", sub_path);
×
871
                                continue;
×
872
                        }
873

874
                        /* Keep files on this level if this was requested */
875
                        if (keep_this_level) {
128✔
876
                                log_debug("Keeping \"%s\".", sub_path);
×
877
                                continue;
×
878
                        }
879

880
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
128✔
881
                                           cutoff_nsec, sub_path, age_by_file, false))
882
                                continue;
74✔
883

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

894
                        log_action("Would remove", "Removing", "%s \"%s\"", sub_path);
70✔
895
                        if (!arg_dry_run &&
88✔
896
                            unlinkat(dirfd(d), de->d_name, 0) < 0 &&
34✔
897
                            errno != ENOENT)
×
898
                                r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
×
899

900
                        deleted = true;
54✔
901
                }
902
        }
903

904
finish:
93✔
905
        if (deleted && (self_atime_nsec < NSEC_INFINITY || self_mtime_nsec < NSEC_INFINITY)) {
93✔
906
                struct timespec ts[2];
28✔
907

908
                log_action("Would restore", "Restoring",
37✔
909
                           "%s access and modification time on \"%s\": %s, %s",
910
                           p,
911
                           FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
912
                           FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
913

914
                timespec_store_nsec(ts + 0, self_atime_nsec);
28✔
915
                timespec_store_nsec(ts + 1, self_mtime_nsec);
28✔
916

917
                /* Restore original directory timestamps */
918
                if (!arg_dry_run &&
45✔
919
                    futimens(dirfd(d), ts) < 0)
17✔
920
                        log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
28✔
921
        }
922

923
        return r;
93✔
924
}
925

926
static bool hardlinks_protected(void) {
×
927
        static int cached = -1;
×
928
        int r;
×
929

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

934
        if (cached >= 0)
×
935
                return cached;
×
936

937
        _cleanup_free_ char *value = NULL;
×
938

939
        r = sysctl_read("fs/protected_hardlinks", &value);
×
940
        if (r < 0) {
×
941
                log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
×
942
                return false;
×
943
        }
944

945
        cached = parse_boolean(value);
×
946
        if (cached < 0)
×
947
                log_debug_errno(cached, "Failed to parse fs.protected_hardlinks sysctl, assuming disabled: %m");
×
948
        return cached > 0;
×
949
}
950

951
static bool hardlink_vulnerable(const struct stat *st) {
14,762✔
952
        assert(st);
14,762✔
953

954
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
14,762✔
955
}
956

957
static mode_t process_mask_perms(mode_t mode, mode_t current) {
293✔
958

959
        if ((current & 0111) == 0)
293✔
960
                mode &= ~0111;
191✔
961
        if ((current & 0222) == 0)
293✔
962
                mode &= ~0222;
×
963
        if ((current & 0444) == 0)
293✔
964
                mode &= ~0444;
×
965
        if (!S_ISDIR(current))
293✔
966
                mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
191✔
967

968
        return mode;
293✔
969
}
970

971
static int fd_set_perms(
19,115✔
972
                Context *c,
973
                Item *i,
974
                int fd,
975
                const char *path,
976
                const struct stat *st,
977
                CreationMode creation) {
978

979
        bool do_chown, do_chmod;
19,115✔
980
        struct stat stbuf;
19,115✔
981
        mode_t new_mode;
19,115✔
982
        uid_t new_uid;
19,115✔
983
        gid_t new_gid;
19,115✔
984
        int r;
19,115✔
985

986
        assert(c);
19,115✔
987
        assert(i);
19,115✔
988
        assert(fd >= 0);
19,115✔
989
        assert(path);
19,115✔
990

991
        if (!i->mode_set && !i->uid_set && !i->gid_set)
19,115✔
992
                goto shortcut;
5,082✔
993

994
        if (!st) {
14,033✔
995
                if (fstat(fd, &stbuf) < 0)
3,272✔
996
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
997
                st = &stbuf;
998
        }
999

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

1007
        /* Do we need a chown()? */
1008
        do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
14,033✔
1009

1010
        /* Calculate the mode to apply */
1011
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
27,503✔
1012
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
27,798✔
1013
                (st->st_mode & 07777);
268✔
1014

1015
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
14,033✔
1016

1017
        if (do_chmod && do_chown) {
14,033✔
1018
                /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
1019
                 * the new mode. That way there's no time window where the file exists under the old owner
1020
                 * with more than the old access modes — and not under the new owner with more than the new
1021
                 * access modes either. */
1022

1023
                if (S_ISLNK(st->st_mode))
754✔
1024
                        log_debug("Skipping temporary mode fix for symlink %s.", path);
×
1025
                else {
1026
                        mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
754✔
1027

1028
                        if (((m ^ st->st_mode) & 07777) == 0)
754✔
1029
                                log_debug("\"%s\" matches temporary mode %o already.", path, m);
743✔
1030
                        else {
1031
                                log_action("Would temporarily change", "Temporarily changing",
11✔
1032
                                           "%s \"%s\" to mode %o", path, m);
1033
                                if (!arg_dry_run) {
11✔
1034
                                        r = fchmod_opath(fd, m);
11✔
1035
                                        if (r < 0)
11✔
1036
                                                return log_error_errno(r, "fchmod() of %s failed: %m", path);
×
1037
                                }
1038
                        }
1039
                }
1040
        }
1041

1042
        if (do_chown) {
14,033✔
1043
                log_action("Would change", "Changing",
2,896✔
1044
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1045

1046
                if (!arg_dry_run &&
2,928✔
1047
                    fchownat(fd, "",
1,463✔
1048
                             new_uid != st->st_uid ? new_uid : UID_INVALID,
1,463✔
1049
                             new_gid != st->st_gid ? new_gid : GID_INVALID,
1,463✔
1050
                             AT_EMPTY_PATH) < 0)
1051
                        return log_error_errno(errno, "fchownat() of %s failed: %m", path);
×
1052
        }
1053

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

1069
shortcut:
14,031✔
1070
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
19,113✔
1071
}
1072

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

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

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

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

1102
        return fd;
16,219✔
1103
}
1104

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

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

1112
        assert(path);
3,605✔
1113

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

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

1125
        return fd;
3,605✔
1126
}
1127

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

1134
        _cleanup_close_ int fd = -EBADF;
3,111✔
1135

1136
        assert(c);
3,111✔
1137
        assert(i);
3,111✔
1138
        assert(path);
3,111✔
1139

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

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

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

1153
        assert(i);
×
1154

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

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

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

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

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

1179
                name = value = NULL;
×
1180
        }
1181

1182
        return 0;
×
1183
}
1184

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

1193
        int r;
×
1194

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

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

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

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

1220
        _cleanup_close_ int fd = -EBADF;
×
1221

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

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

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

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

1239
        assert(item);
2,566✔
1240

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

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

1253
        return 0;
2,566✔
1254
}
1255

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

1265
        acl_entry_t entry;
285✔
1266
        acl_permset_t permset;
285✔
1267
        bool has_exec;
285✔
1268
        int r;
285✔
1269

1270
        assert(path);
285✔
1271
        assert(st);
285✔
1272
        assert(cond_exec);
285✔
1273
        assert(ret);
285✔
1274

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

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

1282
                has_exec = false;
183✔
1283

1284
                for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
183✔
1285
                     r > 0;
730✔
1286
                     r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
547✔
1287

1288
                        acl_tag_t tag;
558✔
1289

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

1293
                        if (tag == ACL_MASK)
558✔
1294
                                continue;
8✔
1295

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

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

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

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

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

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

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

1341
        for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
285✔
1342
             r > 0;
851✔
1343
             r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
566✔
1344

1345
                acl_entry_t parsed_entry;
566✔
1346

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

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

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

1358
                        if (acl_delete_perm(permset, ACL_EXECUTE) < 0)
341✔
1359
                                return -errno;
×
1360
                }
1361
        }
1362
        if (r < 0)
285✔
1363
                return -errno;
×
1364

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

1371
        *ret = TAKE_PTR(parsed);
285✔
1372

1373
        return 0;
285✔
1374
}
1375

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

1384
        _cleanup_(acl_free_charpp) char *t = NULL;
1,002✔
1385
        _cleanup_(acl_freep) acl_t dup = NULL;
1,002✔
1386
        int r;
1,002✔
1387

1388
        assert(c);
1,002✔
1389

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

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

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

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

1408
        r = add_base_acls_if_needed(&dup, path);
1,000✔
1409
        if (r < 0)
1,000✔
1410
                return r;
1411

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

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

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

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

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

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

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

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

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

1477
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
285✔
1478
        } else if (item->acl_access)
444✔
1479
                r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
194✔
1480

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

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

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

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

1507
        assert(c);
448✔
1508
        assert(item);
448✔
1509
        assert(path);
448✔
1510

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

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

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

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

1550
        unsigned value = 0, mask = 0;
1,098✔
1551
        const char *p;
1,098✔
1552

1553
        assert(item);
1,098✔
1554

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

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

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

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

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

1585
                v = attributes[i].value;
1,098✔
1586

1587
                SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1,098✔
1588

1589
                mask |= v;
1,098✔
1590
        }
1591

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

1595
        assert(mask != 0);
1,098✔
1596

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

1601
        return 0;
1,098✔
1602
}
1603

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

1612
        struct stat stbuf;
46✔
1613
        unsigned f;
46✔
1614
        int r;
46✔
1615

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

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

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

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

1637
        f = item->attribute_value & item->attribute_mask;
46✔
1638

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

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

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

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

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

1667
        return 0;
1668
}
1669

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

1676
        _cleanup_close_ int fd = -EBADF;
46✔
1677

1678
        assert(c);
46✔
1679
        assert(item);
46✔
1680

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

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

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

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

1696
        assert(i);
288✔
1697
        assert(fd >= 0);
288✔
1698
        assert(path);
288✔
1699

1700
        if (item_binary_argument_size(i) == 0)
288✔
1701
                return 0;
1702

1703
        assert(item_binary_argument(i));
262✔
1704

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

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

1713
        return 0;
1714
}
1715

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1834
                creation = CREATION_NORMAL;
1835
        }
1836

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2002
        assert(path);
7,860✔
2003

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

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

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

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

2045
        if (arg_dry_run)
7,858✔
2046
                return 0;
2047

2048
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
7,858✔
2049

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

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

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

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

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

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

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

2079
        return fd;
2080
}
2081

2082
static int create_directory(
6,996✔
2083
                Context *c,
2084
                Item *i,
2085
                const char *path) {
2086

2087
        _cleanup_close_ int fd = -EBADF;
6,996✔
2088
        CreationMode creation;
6,996✔
2089
        struct stat st;
6,996✔
2090

2091
        assert(c);
6,996✔
2092
        assert(i);
6,996✔
2093
        assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
6,996✔
2094

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

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

2106
        return fd_set_perms(c, i, fd, path, &st, creation);
6,983✔
2107
}
2108

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

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

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

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

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

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

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

2155
        return r;
2156
}
2157

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2412
        assert(c);
1,500✔
2413
        assert(i);
1,500✔
2414

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

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

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

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

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

2448
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1,497✔
2449

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

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

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

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

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

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

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

2478
                fd = safe_close(fd);
4✔
2479

2480
                mac_selinux_create_file_prepare(i->path, S_IFLNK);
4✔
2481
                r = symlinkat_atomic_full(i->argument, pfd, bn, /* make_relative= */ false);
4✔
2482
                mac_selinux_create_file_clear();
4✔
2483
                if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
4✔
2484
                        r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
1✔
2485
                        if (r < 0)
1✔
2486
                                return log_error_errno(r, "rm -rf %s failed: %m", i->path);
×
2487

2488
                        mac_selinux_create_file_prepare(i->path, S_IFLNK);
1✔
2489
                        r = RET_NERRNO(symlinkat(i->argument, pfd, i->path));
1✔
2490
                        mac_selinux_create_file_clear();
1✔
2491
                }
2492
                if (r < 0)
3✔
2493
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2494

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

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

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

2506
                creation = CREATION_FORCE;
2507
        }
2508

2509
        log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
991✔
2510
        return fd_set_perms(c, i, fd, i->path, &st, creation);
991✔
2511
}
2512

2513
typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2514
typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2515

2516
static int item_do(
579✔
2517
                Context *c,
2518
                Item *i,
2519
                int fd,
2520
                const char *path,
2521
                CreationMode creation,
2522
                fdaction_t action) {
2523

2524
        struct stat st;
579✔
2525
        int r;
579✔
2526

2527
        assert(c);
579✔
2528
        assert(i);
579✔
2529
        assert(fd >= 0);
579✔
2530
        assert(path);
579✔
2531
        assert(action);
579✔
2532

2533
        if (fstat(fd, &st) < 0) {
579✔
2534
                r = log_error_errno(errno, "fstat() on file failed: %m");
×
2535
                goto finish;
×
2536
        }
2537

2538
        /* This returns the first error we run into, but nevertheless tries to go on */
2539
        r = action(c, i, fd, path, &st, creation);
579✔
2540

2541
        if (S_ISDIR(st.st_mode)) {
579✔
2542
                _cleanup_closedir_ DIR *d = NULL;
206✔
2543

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

2552
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
991✔
2553
                        _cleanup_close_ int de_fd = -EBADF;
785✔
2554
                        _cleanup_free_ char *de_path = NULL;
785✔
2555

2556
                        if (dot_or_dot_dot(de->d_name))
785✔
2557
                                continue;
412✔
2558

2559
                        de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
373✔
2560
                        if (de_fd < 0) {
373✔
2561
                                if (errno != ENOENT)
×
2562
                                        RET_GATHER(r, log_error_errno(errno, "Failed to open file '%s': %m", de->d_name));
×
2563
                                continue;
×
2564
                        }
2565

2566
                        de_path = path_join(path, de->d_name);
373✔
2567
                        if (!de_path) {
373✔
2568
                                r = log_oom();
×
2569
                                goto finish;
×
2570
                        }
2571

2572
                        /* Pass ownership of dirent fd over */
2573
                        RET_GATHER(r, item_do(c, i, TAKE_FD(de_fd), de_path, CREATION_EXISTING, action));
373✔
2574
                }
2575
        }
2576

2577
finish:
373✔
2578
        safe_close(fd);
579✔
2579
        return r;
579✔
2580
}
2581

2582
static int glob_item(Context *c, Item *i, action_t action) {
6,249✔
2583
        _cleanup_globfree_ glob_t g = {
6,249✔
2584
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2585
        };
2586
        int r;
6,249✔
2587

2588
        assert(c);
6,249✔
2589
        assert(i);
6,249✔
2590
        assert(action);
6,249✔
2591

2592
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
6,249✔
2593
        if (r == -ENOENT)
6,249✔
2594
                return 0;
2595
        if (r < 0)
3,167✔
2596
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2597

2598
        r = 0;
3,167✔
2599
        STRV_FOREACH(fn, g.gl_pathv)
6,841✔
2600
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2601
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
3,674✔
2602

2603
        return r;
2604
}
2605

2606
static int glob_item_recursively(
252✔
2607
                Context *c,
2608
                Item *i,
2609
                fdaction_t action) {
2610

2611
        _cleanup_globfree_ glob_t g = {
252✔
2612
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2613
        };
2614
        int r;
252✔
2615

2616
        assert(c);
252✔
2617
        assert(i);
252✔
2618
        assert(action);
252✔
2619

2620
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
252✔
2621
        if (r == -ENOENT)
252✔
2622
                return 0;
2623
        if (r < 0)
206✔
2624
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2625

2626
        r = 0;
206✔
2627
        STRV_FOREACH(fn, g.gl_pathv) {
412✔
2628
                _cleanup_close_ int fd = -EBADF;
206✔
2629

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

2634
                fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
206✔
2635
                if (fd < 0) {
206✔
2636
                        RET_GATHER(r, log_error_errno(errno, "Failed to open '%s': %m", *fn));
×
2637
                        continue;
×
2638
                }
2639

2640
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
206✔
2641
        }
2642

2643
        return r;
2644
}
2645

2646
static int rm_if_wrong_type_safe(
×
2647
                mode_t mode,
2648
                int parent_fd,
2649
                const struct stat *parent_st, /* Only used if follow_links below is true. */
2650
                const char *name,
2651
                int flags) {
2652
        _cleanup_free_ char *parent_name = NULL;
×
2653
        bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
×
2654
        struct stat st;
×
2655
        int r;
×
2656

2657
        assert(name);
×
2658
        assert((mode & ~S_IFMT) == 0);
×
2659
        assert(!follow_links || parent_st);
×
2660
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2661

2662
        if (mode == 0)
×
2663
                return 0;
2664

2665
        if (!filename_is_valid(name))
×
2666
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2667

2668
        r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2669
        if (r < 0) {
×
2670
                (void) fd_get_path(parent_fd, &parent_name);
×
2671
                return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_ERR, r,
×
2672
                                      "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
2673
        }
2674

2675
        /* Fail before removing anything if this is an unsafe transition. */
2676
        if (follow_links && unsafe_transition(parent_st, &st)) {
×
2677
                (void) fd_get_path(parent_fd, &parent_name);
×
2678
                return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
×
2679
                                       "Unsafe transition from \"%s\" to \"%s\".", parent_name ?: "...", name);
2680
        }
2681

2682
        if ((st.st_mode & S_IFMT) == mode)
×
2683
                return 0;
2684

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

2688
        /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2689
         * target, so make sure it is identified as a link and not a directory. */
2690
        if (follow_links) {
×
2691
                r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2692
                if (r < 0)
×
2693
                        return log_error_errno(r, "Failed to stat \"%s/%s\": %m", parent_name ?: "...", name);
×
2694
        }
2695

2696
        /* Do not remove mount points. */
2697
        r = is_mount_point_at(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
×
2698
        if (r < 0)
×
2699
                (void) log_warning_errno(r, "Failed to check if  \"%s/%s\" is a mount point: %m; continuing.",
×
2700
                                         parent_name ?: "...", name);
2701
        else if (r > 0)
×
2702
                return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
×
2703
                                "Not removing  \"%s/%s\" because it is a mount point.", parent_name ?: "...", name);
2704

2705
        log_action("Would remove", "Removing", "%s %s/%s", parent_name ?: "...", name);
×
2706
        if (!arg_dry_run) {
×
2707
                if ((st.st_mode & S_IFMT) == S_IFDIR) {
×
2708
                        _cleanup_close_ int child_fd = -EBADF;
×
2709

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

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

2718
                        r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2719
                } else
2720
                        r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
×
2721
                if (r < 0)
×
2722
                        return log_error_errno(r, "Failed to remove \"%s/%s\": %m", parent_name ?: "...", name);
×
2723
        }
2724

2725
        /* This is covered by the log_notice "Wrong file type...".
2726
         * It is logged earlier because it gives context to other error messages that might follow. */
2727
        return -ENOENT;
2728
}
2729

2730
/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2731
static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
×
2732
        _cleanup_close_ int parent_fd = -EBADF;
×
2733
        struct stat parent_st;
×
2734
        size_t path_len;
×
2735
        int r;
×
2736

2737
        assert(path);
×
2738
        assert((child_mode & ~S_IFMT) == 0);
×
2739

2740
        path_len = strlen(path);
×
2741

2742
        if (!is_path(path))
×
2743
                /* rm_if_wrong_type_safe already logs errors. */
2744
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2745

2746
        if (child_mode != 0 && endswith(path, "/"))
×
2747
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2748
                                "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2749

2750
        /* Get the parent_fd and stat. */
2751
        parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
×
2752
        if (parent_fd < 0)
×
2753
                return log_error_errno(errno, "Failed to open root: %m");
×
2754

2755
        if (fstat(parent_fd, &parent_st) < 0)
×
2756
                return log_error_errno(errno, "Failed to stat root: %m");
×
2757

2758
        /* Check every parent directory in the path, except the last component */
2759
        for (const char *e = path;;) {
×
2760
                _cleanup_close_ int next_fd = -EBADF;
×
2761
                char t[path_len + 1];
×
2762
                const char *s;
×
2763

2764
                /* Find the start of the next path component. */
2765
                s = e + strspn(e, "/");
×
2766
                /* Find the end of the next path component. */
2767
                e = s + strcspn(s, "/");
×
2768

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

2772
                /* Is this the last component? If so, then check the type */
2773
                if (*e == 0)
×
2774
                        return rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2775

2776
                r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
×
2777
                /* Remove dangling symlinks. */
2778
                if (r == -ENOENT)
×
2779
                        r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
×
2780
                if (r == -ENOENT) {
×
2781
                        if (!arg_dry_run) {
×
2782
                                WITH_UMASK(0000)
×
2783
                                        r = mkdirat_label(parent_fd, t, 0755);
×
2784
                                if (r < 0) {
×
2785
                                        _cleanup_free_ char *parent_name = NULL;
×
2786

2787
                                        (void) fd_get_path(parent_fd, &parent_name);
×
2788
                                        return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2789
                                }
2790
                        }
2791
                } else if (r < 0)
×
2792
                        /* rm_if_wrong_type_safe already logs errors. */
2793
                        return r;
2794

2795
                next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
×
2796
                if (next_fd < 0) {
×
2797
                        _cleanup_free_ char *parent_name = NULL;
×
2798

2799
                        (void) fd_get_path(parent_fd, &parent_name);
×
2800
                        return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2801
                }
2802
                r = RET_NERRNO(fstat(next_fd, &parent_st));
×
2803
                if (r < 0) {
×
2804
                        _cleanup_free_ char *parent_name = NULL;
×
2805

2806
                        (void) fd_get_path(parent_fd, &parent_name);
×
2807
                        return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
×
2808
                }
2809

2810
                close_and_replace(parent_fd, next_fd);
×
2811
        }
2812
}
2813

2814
static int mkdir_parents_item(Item *i, mode_t child_mode) {
16,231✔
2815
        int r;
16,231✔
2816

2817
        if (i->try_replace) {
16,231✔
2818
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2819
                if (r < 0 && r != -ENOENT)
×
2820
                        return r;
×
2821
        } else
2822
                WITH_UMASK(0000)
32,462✔
2823
                        if (!arg_dry_run)
16,231✔
2824
                                (void) mkdir_parents_label(i->path, 0755);
16,231✔
2825

2826
        return 0;
2827
}
2828

2829
static int create_item(Context *c, Item *i) {
23,556✔
2830
        int r;
23,556✔
2831

2832
        assert(c);
23,556✔
2833
        assert(i);
23,556✔
2834

2835
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
23,556✔
2836

2837
        switch (i->type) {
23,556✔
2838

2839
        case IGNORE_PATH:
2840
        case IGNORE_DIRECTORY_PATH:
2841
        case REMOVE_PATH:
2842
        case RECURSIVE_REMOVE_PATH:
2843
                return 0;
2844

2845
        case TRUNCATE_FILE:
1,027✔
2846
        case CREATE_FILE:
2847
                r = mkdir_parents_item(i, S_IFREG);
1,027✔
2848
                if (r < 0)
1,027✔
2849
                        return r;
2850

2851
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,027✔
2852
                        r = truncate_file(c, i, i->path);
251✔
2853
                else
2854
                        r = create_file(c, i, i->path);
776✔
2855
                if (r < 0)
1,027✔
2856
                        return r;
15✔
2857
                break;
2858

2859
        case COPY_FILES:
3,845✔
2860
                r = mkdir_parents_item(i, 0);
3,845✔
2861
                if (r < 0)
3,845✔
2862
                        return r;
2863

2864
                r = copy_files(c, i);
3,845✔
2865
                if (r < 0)
3,845✔
2866
                        return r;
×
2867
                break;
2868

2869
        case WRITE_FILE:
20✔
2870
                r = glob_item(c, i, write_one_file);
20✔
2871
                if (r < 0)
20✔
2872
                        return r;
×
2873

2874
                break;
2875

2876
        case CREATE_DIRECTORY:
6,996✔
2877
        case TRUNCATE_DIRECTORY:
2878
                r = mkdir_parents_item(i, S_IFDIR);
6,996✔
2879
                if (r < 0)
6,996✔
2880
                        return r;
2881

2882
                r = create_directory(c, i, i->path);
6,996✔
2883
                if (r < 0)
6,996✔
2884
                        return r;
2✔
2885
                break;
2886

2887
        case CREATE_SUBVOLUME:
875✔
2888
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
2889
        case CREATE_SUBVOLUME_NEW_QUOTA:
2890
                r = mkdir_parents_item(i, S_IFDIR);
875✔
2891
                if (r < 0)
875✔
2892
                        return r;
2893

2894
                r = create_subvolume(c, i, i->path);
875✔
2895
                if (r < 0)
875✔
2896
                        return r;
×
2897
                break;
2898

2899
        case EMPTY_DIRECTORY:
4✔
2900
                r = glob_item(c, i, empty_directory);
4✔
2901
                if (r < 0)
4✔
2902
                        return r;
×
2903
                break;
2904

2905
        case CREATE_FIFO:
4✔
2906
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2907
                if (r < 0)
4✔
2908
                        return r;
2909

2910
                r = create_fifo(c, i);
4✔
2911
                if (r < 0)
4✔
2912
                        return r;
×
2913
                break;
2914

2915
        case CREATE_SYMLINK:
1,500✔
2916
                r = mkdir_parents_item(i, S_IFLNK);
1,500✔
2917
                if (r < 0)
1,500✔
2918
                        return r;
2919

2920
                r = create_symlink(c, i);
1,500✔
2921
                if (r < 0)
1,500✔
2922
                        return r;
×
2923

2924
                break;
2925

2926
        case CREATE_BLOCK_DEVICE:
1,984✔
2927
        case CREATE_CHAR_DEVICE:
2928
                if (have_effective_cap(CAP_MKNOD) <= 0) {
1,984✔
2929
                        /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2930
                         * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2931

2932
                        log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
×
2933
                        return 0;
×
2934
                }
2935

2936
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,966✔
2937
                if (r < 0)
1,984✔
2938
                        return r;
2939

2940
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,966✔
2941
                if (r < 0)
1,984✔
2942
                        return r;
×
2943

2944
                break;
2945

2946
        case ADJUST_MODE:
4,329✔
2947
        case RELABEL_PATH:
2948
                r = glob_item(c, i, path_set_perms);
4,329✔
2949
                if (r < 0)
4,329✔
2950
                        return r;
×
2951
                break;
2952

2953
        case RECURSIVE_RELABEL_PATH:
127✔
2954
                r = glob_item_recursively(c, i, fd_set_perms);
127✔
2955
                if (r < 0)
127✔
2956
                        return r;
×
2957
                break;
2958

2959
        case SET_XATTR:
×
2960
                r = glob_item(c, i, path_set_xattrs);
×
2961
                if (r < 0)
×
2962
                        return r;
×
2963
                break;
2964

2965
        case RECURSIVE_SET_XATTR:
×
2966
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2967
                if (r < 0)
×
2968
                        return r;
×
2969
                break;
2970

2971
        case SET_ACL:
754✔
2972
                r = glob_item(c, i, path_set_acls);
754✔
2973
                if (r < 0)
754✔
2974
                        return r;
×
2975
                break;
2976

2977
        case RECURSIVE_SET_ACL:
125✔
2978
                r = glob_item_recursively(c, i, fd_set_acls);
125✔
2979
                if (r < 0)
125✔
2980
                        return r;
×
2981
                break;
2982

2983
        case SET_ATTRIBUTE:
375✔
2984
                r = glob_item(c, i, path_set_attribute);
375✔
2985
                if (r < 0)
375✔
2986
                        return r;
×
2987
                break;
2988

2989
        case RECURSIVE_SET_ATTRIBUTE:
×
2990
                r = glob_item_recursively(c, i, fd_set_attribute);
×
2991
                if (r < 0)
×
2992
                        return r;
×
2993
                break;
2994
        }
2995

2996
        return 0;
2997
}
2998

2999
static int remove_recursive(
501✔
3000
                Context *c,
3001
                Item *i,
3002
                const char *instance,
3003
                bool remove_instance) {
3004

3005
        _cleanup_closedir_ DIR *d = NULL;
501✔
3006
        struct statx sx;
501✔
3007
        bool mountpoint;
501✔
3008
        int r;
501✔
3009

3010
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
501✔
3011
        if (r < 0)
501✔
3012
                return r;
3013
        if (r == 0) {
501✔
3014
                if (remove_instance) {
491✔
3015
                        log_action("Would remove", "Removing", "%s file \"%s\".", instance);
13✔
3016
                        if (!arg_dry_run &&
14✔
3017
                            remove(instance) < 0 &&
5✔
3018
                            errno != ENOENT)
2✔
3019
                                return log_error_errno(errno, "rm %s: %m", instance);
×
3020
                }
3021
                return 0;
491✔
3022
        }
3023

3024
        r = dir_cleanup(c, i, instance, d,
20✔
3025
                        /* self_atime_nsec= */ NSEC_INFINITY,
3026
                        /* self_mtime_nsec= */ NSEC_INFINITY,
3027
                        /* cutoff_nsec= */ NSEC_INFINITY,
3028
                        sx.stx_dev_major, sx.stx_dev_minor,
10✔
3029
                        mountpoint,
3030
                        MAX_DEPTH,
3031
                        /* keep_this_level= */ false,
3032
                        /* age_by_file= */ 0,
3033
                        /* age_by_dir= */ 0);
3034
        if (r < 0)
10✔
3035
                return r;
3036

3037
        if (remove_instance) {
10✔
3038
                log_action("Would remove", "Removing", "%s directory \"%s\".", instance);
11✔
3039
                if (!arg_dry_run) {
9✔
3040
                        r = RET_NERRNO(rmdir(instance));
504✔
3041
                        if (r < 0) {
3✔
3042
                                bool fatal = !IN_SET(r, -ENOENT, -ENOTEMPTY);
3✔
3043
                                log_full_errno(fatal ? LOG_ERR : LOG_DEBUG, r, "Failed to remove %s: %m", instance);
3✔
3044
                                if (fatal)
3✔
3045
                                        return r;
×
3046
                        }
3047
                }
3048
        }
3049
        return 0;
3050
}
3051

3052
static int purge_item_instance(Context *c, Item *i, const char *instance, CreationMode creation) {
10✔
3053
        return remove_recursive(c, i, instance, /* remove_instance= */ true);
10✔
3054
}
3055

3056
static int purge_item(Context *c, Item *i) {
15✔
3057
        assert(i);
15✔
3058

3059
        if (!needs_purge(i->type))
15✔
3060
                return 0;
3061

3062
        if (!i->purge)
15✔
3063
                return 0;
3064

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

3067
        if (needs_glob(i->type))
10✔
3068
                return glob_item(c, i, purge_item_instance);
×
3069

3070
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3071
}
3072

3073
static int remove_item_instance(
16✔
3074
                Context *c,
3075
                Item *i,
3076
                const char *instance,
3077
                CreationMode creation) {
3078

3079
        assert(c);
16✔
3080
        assert(i);
16✔
3081

3082
        switch (i->type) {
16✔
3083

3084
        case REMOVE_PATH:
3085
                log_action("Would remove", "Removing", "%s \"%s\".", instance);
8✔
3086
                if (!arg_dry_run &&
15✔
3087
                    remove(instance) < 0 &&
7✔
3088
                    errno != ENOENT)
×
3089
                        return log_error_errno(errno, "rm %s: %m", instance);
×
3090

3091
                return 0;
3092

3093
        case RECURSIVE_REMOVE_PATH:
8✔
3094
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3095

3096
        default:
×
3097
                assert_not_reached();
×
3098
        }
3099
}
3100

3101
static int remove_item(Context *c, Item *i) {
17,934✔
3102
        assert(c);
17,934✔
3103
        assert(i);
17,934✔
3104

3105
        log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
17,934✔
3106

3107
        switch (i->type) {
17,934✔
3108

3109
        case TRUNCATE_DIRECTORY:
483✔
3110
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
483✔
3111

3112
        case REMOVE_PATH:
738✔
3113
        case RECURSIVE_REMOVE_PATH:
3114
                return glob_item(c, i, remove_item_instance);
738✔
3115

3116
        default:
3117
                return 0;
3118
        }
3119
}
3120

3121
static char *age_by_to_string(AgeBy ab, bool is_dir) {
60✔
3122
        static const char ab_map[] = { 'a', 'b', 'c', 'm' };
60✔
3123
        size_t j = 0;
60✔
3124
        char *ret;
60✔
3125

3126
        ret = new(char, ELEMENTSOF(ab_map) + 1);
60✔
3127
        if (!ret)
60✔
3128
                return NULL;
3129

3130
        for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
300✔
3131
                if (BIT_SET(ab, i))
240✔
3132
                        ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
163✔
3133

3134
        ret[j] = 0;
60✔
3135
        return ret;
60✔
3136
}
3137

3138
static int clean_item_instance(
139✔
3139
                Context *c,
3140
                Item *i,
3141
                const char* instance,
3142
                CreationMode creation) {
3143

3144
        assert(i);
139✔
3145

3146
        if (!i->age_set)
139✔
3147
                return 0;
139✔
3148

3149
        usec_t n = now(CLOCK_REALTIME);
46✔
3150
        if (n < i->age)
46✔
3151
                return 0;
3152

3153
        usec_t cutoff = n - i->age;
46✔
3154

3155
        _cleanup_closedir_ DIR *d = NULL;
139✔
3156
        struct statx sx;
46✔
3157
        bool mountpoint;
46✔
3158
        int r;
46✔
3159

3160
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
46✔
3161
        if (r <= 0)
46✔
3162
                return r;
3163

3164
        if (DEBUG_LOGGING) {
42✔
3165
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
30✔
3166

3167
                ab_f = age_by_to_string(i->age_by_file, false);
30✔
3168
                if (!ab_f)
30✔
3169
                        return log_oom();
×
3170

3171
                ab_d = age_by_to_string(i->age_by_dir, true);
30✔
3172
                if (!ab_d)
30✔
3173
                        return log_oom();
×
3174

3175
                log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
59✔
3176
                          mountpoint ? "mount point" : "directory",
3177
                          instance,
3178
                          FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
3179
                          ab_f, ab_d);
3180
        }
3181

3182
        return dir_cleanup(c, i, instance, d,
42✔
3183
                           statx_timestamp_load_nsec(&sx.stx_atime),
3184
                           statx_timestamp_load_nsec(&sx.stx_mtime),
3185
                           cutoff * NSEC_PER_USEC,
42✔
3186
                           sx.stx_dev_major, sx.stx_dev_minor,
42✔
3187
                           mountpoint,
3188
                           MAX_DEPTH, i->keep_first_level,
42✔
3189
                           i->age_by_file, i->age_by_dir);
3190
}
3191

3192
static int clean_item(Context *c, Item *i) {
195✔
3193
        assert(c);
195✔
3194
        assert(i);
195✔
3195

3196
        log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
195✔
3197

3198
        switch (i->type) {
195✔
3199

3200
        case CREATE_DIRECTORY:
109✔
3201
        case TRUNCATE_DIRECTORY:
3202
        case CREATE_SUBVOLUME:
3203
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3204
        case CREATE_SUBVOLUME_NEW_QUOTA:
3205
        case COPY_FILES:
3206
                clean_item_instance(c, i, i->path, CREATION_EXISTING);
109✔
3207
                return 0;
109✔
3208

3209
        case EMPTY_DIRECTORY:
29✔
3210
        case IGNORE_PATH:
3211
        case IGNORE_DIRECTORY_PATH:
3212
                return glob_item(c, i, clean_item_instance);
29✔
3213

3214
        default:
3215
                return 0;
3216
        }
3217
}
3218

3219
static int process_item(
78,014✔
3220
                Context *c,
3221
                Item *i,
3222
                OperationMask operation) {
3223

3224
        OperationMask todo;
78,014✔
3225
        _cleanup_free_ char *_path = NULL;
78,014✔
3226
        const char *path;
78,014✔
3227
        int r;
78,014✔
3228

3229
        assert(c);
78,014✔
3230
        assert(i);
78,014✔
3231

3232
        todo = operation & ~i->done;
78,014✔
3233
        if (todo == 0) /* Everything already done? */
78,014✔
3234
                return 0;
3235

3236
        i->done |= operation;
41,700✔
3237

3238
        path = i->path;
41,700✔
3239
        if (string_is_glob(path)) {
41,700✔
3240
                /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3241
                 * for the non-glob part. */
3242

3243
                r = glob_non_glob_prefix(path, &_path);
3,641✔
3244
                if (r < 0 && r != -ENOENT)
3,641✔
3245
                        return log_debug_errno(r, "Failed to deglob path: %m");
×
3246
                if (r >= 0)
3,641✔
3247
                        path = _path;
3,641✔
3248
        }
3249

3250
        r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
41,700✔
3251
        if (r == -EREMOTE) {
41,700✔
3252
                log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
×
3253
                return 0;
×
3254
        }
3255
        if (r < 0)
41,700✔
3256
                log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
×
3257

3258
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
41,700✔
3259
        /* Failure can only be tolerated for create */
3260
        if (i->allow_failure)
41,700✔
3261
                r = 0;
984✔
3262

3263
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
41,700✔
3264
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
41,700✔
3265
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
41,700✔
3266

3267
        return r;
3268
}
3269

3270
static int process_item_array(
71,715✔
3271
                Context *c,
3272
                ItemArray *array,
3273
                OperationMask operation) {
3274

3275
        int r = 0;
71,715✔
3276

3277
        assert(c);
71,715✔
3278
        assert(array);
71,715✔
3279

3280
        /* Create any parent first. */
3281
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
71,715✔
3282
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
17,109✔
3283

3284
        /* Clean up all children first */
3285
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
71,715✔
3286
                ItemArray *cc;
6,504✔
3287

3288
                SET_FOREACH(cc, array->children)
21,999✔
3289
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
15,495✔
3290
        }
3291

3292
        FOREACH_ARRAY(item, array->items, array->n_items)
149,729✔
3293
                RET_GATHER(r, process_item(c, item, operation));
78,014✔
3294

3295
        return r;
71,715✔
3296
}
3297

3298
static void item_free_contents(Item *i) {
88,421✔
3299
        assert(i);
88,421✔
3300
        free(i->path);
88,421✔
3301
        free(i->argument);
88,421✔
3302
        free(i->binary_argument);
88,421✔
3303
        strv_free(i->xattrs);
88,421✔
3304

3305
#if HAVE_ACL
3306
        if (i->acl_access)
88,421✔
3307
                acl_free(i->acl_access);
1,464✔
3308

3309
        if (i->acl_access_exec)
88,421✔
3310
                acl_free(i->acl_access_exec);
370✔
3311

3312
        if (i->acl_default)
88,421✔
3313
                acl_free(i->acl_default);
2,196✔
3314
#endif
3315
}
88,421✔
3316

3317
static ItemArray* item_array_free(ItemArray *a) {
22,396✔
3318
        if (!a)
22,396✔
3319
                return NULL;
3320

3321
        FOREACH_ARRAY(item, a->items, a->n_items)
46,181✔
3322
                item_free_contents(item);
23,785✔
3323

3324
        set_free(a->children);
22,396✔
3325
        free(a->items);
22,396✔
3326
        return mfree(a);
22,396✔
3327
}
3328

3329
static int item_compare(const Item *a, const Item *b) {
1,903✔
3330
        /* Make sure that the ownership taking item is put first, so
3331
         * that we first create the node, and then can adjust it */
3332

3333
        if (takes_ownership(a->type) && !takes_ownership(b->type))
1,903✔
3334
                return -1;
3335
        if (!takes_ownership(a->type) && takes_ownership(b->type))
1,903✔
3336
                return 1;
3337

3338
        return CMP(a->type, b->type);
1,903✔
3339
}
3340

3341
static bool item_compatible(const Item *a, const Item *b) {
1,652✔
3342
        assert(a);
1,652✔
3343
        assert(b);
1,652✔
3344
        assert(streq(a->path, b->path));
1,652✔
3345

3346
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,652✔
3347
                /* check if the items are the same */
3348
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
518✔
3349
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
499✔
3350

3351
                        a->uid_set == b->uid_set &&
499✔
3352
                        a->uid == b->uid &&
499✔
3353
                        a->uid_only_create == b->uid_only_create &&
499✔
3354

3355
                        a->gid_set == b->gid_set &&
499✔
3356
                        a->gid == b->gid &&
499✔
3357
                        a->gid_only_create == b->gid_only_create &&
499✔
3358

3359
                        a->mode_set == b->mode_set &&
499✔
3360
                        a->mode == b->mode &&
499✔
3361
                        a->mode_only_create == b->mode_only_create &&
499✔
3362

3363
                        a->age_set == b->age_set &&
499✔
3364
                        a->age == b->age &&
499✔
3365

3366
                        a->age_by_file == b->age_by_file &&
499✔
3367
                        a->age_by_dir == b->age_by_dir &&
499✔
3368

3369
                        a->mask_perms == b->mask_perms &&
499✔
3370

3371
                        a->keep_first_level == b->keep_first_level &&
1,535✔
3372

3373
                        a->major_minor == b->major_minor;
499✔
3374

3375
        return true;
3376
}
3377

3378
static bool should_include_path(const char *path) {
64,512✔
3379
        STRV_FOREACH(prefix, arg_exclude_prefixes)
83,233✔
3380
                if (path_startswith(path, *prefix)) {
21,121✔
3381
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,400✔
3382
                                  path, *prefix);
3383
                        return false;
2,400✔
3384
                }
3385

3386
        STRV_FOREACH(prefix, arg_include_prefixes)
99,554✔
3387
                if (path_startswith(path, *prefix)) {
42,242✔
3388
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
4,800✔
3389
                        return true;
4,800✔
3390
                }
3391

3392
        /* no matches, so we should include this path only if we have no allow list at all */
3393
        if (strv_isempty(arg_include_prefixes))
57,312✔
3394
                return true;
3395

3396
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
37,442✔
3397
        return false;
3398
}
3399

3400
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
24,670✔
3401
        int r;
24,670✔
3402

3403
        assert(i);
24,670✔
3404

3405
        if (!i->argument)
24,670✔
3406
                return 0;
3407

3408
        switch (i->type) {
6,328✔
3409
        case COPY_FILES:
3,079✔
3410
        case CREATE_SYMLINK:
3411
        case CREATE_FILE:
3412
        case TRUNCATE_FILE:
3413
        case WRITE_FILE: {
3414
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
3,079✔
3415
                ssize_t l;
3,079✔
3416

3417
                l = cunescape(i->argument, 0, &unescaped);
3,079✔
3418
                if (l < 0)
3,079✔
3419
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3420

3421
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
3,079✔
3422
                if (r < 0)
3,079✔
3423
                        return r;
3424

3425
                return free_and_replace(i->argument, resolved);
3,079✔
3426
        }
3427
        case SET_XATTR:
×
3428
        case RECURSIVE_SET_XATTR:
3429
                STRV_FOREACH(xattr, i->xattrs) {
×
3430
                        _cleanup_free_ char *resolved = NULL;
×
3431

3432
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3433
                        if (r < 0)
×
3434
                                return r;
×
3435

3436
                        free_and_replace(*xattr, resolved);
×
3437
                }
3438
                return 0;
3439

3440
        default:
3441
                return 0;
3442
        }
3443
}
3444

3445
static int patch_var_run(const char *fname, unsigned line, char **path) {
64,513✔
3446
        const char *k;
64,513✔
3447
        char *n;
64,513✔
3448

3449
        assert(path);
64,513✔
3450
        assert(*path);
64,513✔
3451

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

3463
        k = path_startswith(*path, "/var/run/");
64,513✔
3464
        if (isempty(k)) /* Don't complain about paths other than under /var/run,
64,513✔
3465
                         * and not about /var/run itself either. */
3466
                return 0;
64,513✔
3467

3468
        n = path_join("/run", k);
×
3469
        if (!n)
×
3470
                return log_oom();
×
3471

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

3480
        free_and_replace(*path, n);
×
3481

3482
        return 0;
×
3483
}
3484

3485
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
8,789✔
3486
        int r;
8,789✔
3487

3488
        assert(user);
8,789✔
3489
        assert(ret_uid);
8,789✔
3490

3491
        /* First: parse as numeric UID string */
3492
        r = parse_uid(user, ret_uid);
8,789✔
3493
        if (r >= 0)
8,789✔
3494
                return r;
3495

3496
        /* Second: pass to NSS if we are running "online" */
3497
        if (!arg_root)
8,775✔
3498
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
8,775✔
3499

3500
        /* Third, synthesize "root" unconditionally */
3501
        if (streq(user, "root")) {
×
3502
                *ret_uid = 0;
×
3503
                return 0;
×
3504
        }
3505

3506
        /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3507
        return name_to_uid_offline(arg_root, user, ret_uid, cache);
×
3508
}
3509

3510
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
10,265✔
3511
        int r;
10,265✔
3512

3513
        assert(group);
10,265✔
3514
        assert(ret_gid);
10,265✔
3515

3516
        /* First: parse as numeric GID string */
3517
        r = parse_gid(group, ret_gid);
10,265✔
3518
        if (r >= 0)
10,265✔
3519
                return r;
3520

3521
        /* Second: pass to NSS if we are running "online" */
3522
        if (!arg_root)
10,251✔
3523
                return get_group_creds(&group, ret_gid, 0);
10,251✔
3524

3525
        /* Third, synthesize "root" unconditionally */
3526
        if (streq(group, "root")) {
×
3527
                *ret_gid = 0;
×
3528
                return 0;
×
3529
        }
3530

3531
        /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3532
        return name_to_gid_offline(arg_root, group, ret_gid, cache);
×
3533
}
3534

3535
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
148✔
3536
        AgeBy ab_f = 0, ab_d = 0;
148✔
3537

3538
        static const struct {
148✔
3539
                char age_by_chr;
3540
                AgeBy age_by_flag;
3541
        } age_by_types[] = {
3542
                { 'a', AGE_BY_ATIME },
3543
                { 'b', AGE_BY_BTIME },
3544
                { 'c', AGE_BY_CTIME },
3545
                { 'm', AGE_BY_MTIME },
3546
        };
3547

3548
        assert(age_by_str);
148✔
3549
        assert(item);
148✔
3550

3551
        if (isempty(age_by_str))
148✔
3552
                return -EINVAL;
3553

3554
        for (const char *s = age_by_str; *s != 0; s++) {
315✔
3555
                size_t i;
173✔
3556

3557
                /* Ignore whitespace. */
3558
                if (strchr(WHITESPACE, *s))
173✔
3559
                        continue;
11✔
3560

3561
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
224✔
3562
                        /* Check lower-case for files, upper-case for directories. */
3563
                        if (*s == age_by_types[i].age_by_chr) {
221✔
3564
                                ab_f |= age_by_types[i].age_by_flag;
149✔
3565
                                break;
149✔
3566
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3567
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3568
                                break;
10✔
3569
                        }
3570
                }
3571

3572
                /* Invalid character. */
3573
                if (i >= ELEMENTSOF(age_by_types))
3574
                        return -EINVAL;
3575
        }
3576

3577
        /* No match. */
3578
        if (ab_f == 0 && ab_d == 0)
142✔
3579
                return -EINVAL;
3580

3581
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
141✔
3582
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
141✔
3583

3584
        return 0;
141✔
3585
}
3586

3587
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
1,392✔
3588
        assert(existing);
1,392✔
3589
        assert(i);
1,392✔
3590

3591
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
3,041✔
3592
                if (item_compatible(e, i))
1,652✔
3593
                        continue;
1,633✔
3594

3595
                /* Only multiple 'w+' lines for the same path are allowed. */
3596
                if (e->type != WRITE_FILE || !e->append_or_force ||
19✔
3597
                    i->type != WRITE_FILE || !i->append_or_force)
16✔
3598
                        return true;
3599
        }
3600

3601
        return false;
3602
}
3603

3604
static int parse_line(
64,636✔
3605
                const char *fname,
3606
                unsigned line,
3607
                const char *buffer,
3608
                bool *invalid_config,
3609
                void *context) {
3610

3611
        Context *c = ASSERT_PTR(context);
64,636✔
3612
        _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
64,636✔
3613
        _cleanup_(item_free_contents) Item i = {
×
3614
                /* The "age-by" argument considers all file timestamp types by default. */
3615
                .age_by_file = AGE_BY_DEFAULT_FILE,
3616
                .age_by_dir = AGE_BY_DEFAULT_DIR,
3617
        };
3618
        ItemArray *existing;
64,636✔
3619
        OrderedHashmap *h;
64,636✔
3620
        bool append_or_force = false, boot = false, allow_failure = false, try_replace = false,
64,636✔
3621
                unbase64 = false, from_cred = false, missing_user_or_group = false, purge = false,
64,636✔
3622
                ignore_if_target_missing = false;
64,636✔
3623
        int r;
64,636✔
3624

3625
        assert(fname);
64,636✔
3626
        assert(line >= 1);
64,636✔
3627
        assert(buffer);
64,636✔
3628

3629
        const Specifier specifier_table[] = {
64,636✔
3630
                { 'h', specifier_user_home,       NULL },
3631

3632
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3633
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3634
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3635
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3636

3637
                COMMON_SYSTEM_SPECIFIERS,
3638
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
64,636✔
3639
                COMMON_TMP_SPECIFIERS,
3640
                {}
3641
        };
3642

3643
        r = extract_many_words(
64,636✔
3644
                        &buffer,
3645
                        NULL,
3646
                        EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE,
3647
                        &action,
3648
                        &path,
3649
                        &mode,
3650
                        &user,
3651
                        &group,
3652
                        &age);
3653
        if (r < 0) {
64,636✔
3654
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3655
                        /* invalid quoting and such or an unknown specifier */
3656
                        *invalid_config = true;
×
3657
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
×
3658
        } else if (r < 2) {
64,636✔
3659
                *invalid_config = true;
×
3660
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
×
3661
        }
3662

3663
        if (!empty_or_dash(buffer)) {
64,636✔
3664
                i.argument = strdup(buffer);
15,495✔
3665
                if (!i.argument)
15,495✔
3666
                        return log_oom();
×
3667
        }
3668

3669
        if (isempty(action)) {
64,636✔
3670
                *invalid_config = true;
×
3671
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3672
                                  "Command too short '%s'.", action);
3673
        }
3674

3675
        for (int pos = 1; action[pos]; pos++)
85,227✔
3676
                if (action[pos] == '!' && !boot)
20,591✔
3677
                        boot = true;
3678
                else if (action[pos] == '+' && !append_or_force)
11,018✔
3679
                        append_or_force = true;
3680
                else if (action[pos] == '-' && !allow_failure)
7,334✔
3681
                        allow_failure = true;
3682
                else if (action[pos] == '=' && !try_replace)
5,870✔
3683
                        try_replace = true;
3684
                else if (action[pos] == '~' && !unbase64)
5,870✔
3685
                        unbase64 = true;
3686
                else if (action[pos] == '^' && !from_cred)
5,870✔
3687
                        from_cred = true;
3688
                else if (action[pos] == '$' && !purge)
4,406✔
3689
                        purge = true;
3690
                else if (action[pos] == '?' && !ignore_if_target_missing)
2✔
3691
                        ignore_if_target_missing = true;
3692
                else {
3693
                        *invalid_config = true;
×
3694
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3695
                                          "Unknown modifiers in command: %s", action);
3696
                }
3697

3698
        if (boot && !arg_boot) {
64,636✔
3699
                log_syntax(NULL, LOG_DEBUG, fname, line, 0,
123✔
3700
                           "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3701
                return 0;
123✔
3702
        }
3703

3704
        i.type = action[0];
64,513✔
3705
        i.append_or_force = append_or_force;
64,513✔
3706
        i.allow_failure = allow_failure;
64,513✔
3707
        i.try_replace = try_replace;
64,513✔
3708
        i.purge = purge;
64,513✔
3709
        i.ignore_if_target_missing = ignore_if_target_missing;
64,513✔
3710

3711
        r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
64,513✔
3712
        if (ERRNO_IS_NEG_NOINFO(r))
64,513✔
3713
                return log_unresolvable_specifier(fname, line);
×
3714
        if (r < 0) {
64,513✔
3715
                if (IN_SET(r, -EINVAL, -EBADSLT))
×
3716
                        *invalid_config = true;
×
3717
                return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3718
                                  "Failed to replace specifiers in '%s': %m", path);
3719
        }
3720

3721
        r = patch_var_run(fname, line, &i.path);
64,513✔
3722
        if (r < 0)
64,513✔
3723
                return r;
3724

3725
        if (!path_is_absolute(i.path)) {
64,513✔
3726
                *invalid_config = true;
×
3727
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3728
                                  "Path '%s' not absolute.", i.path);
3729
        }
3730

3731
        path_simplify(i.path);
64,513✔
3732

3733
        switch (i.type) {
64,513✔
3734

3735
        case CREATE_DIRECTORY:
36,732✔
3736
        case CREATE_SUBVOLUME:
3737
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
3738
        case CREATE_SUBVOLUME_NEW_QUOTA:
3739
        case EMPTY_DIRECTORY:
3740
        case TRUNCATE_DIRECTORY:
3741
        case CREATE_FIFO:
3742
        case IGNORE_PATH:
3743
        case IGNORE_DIRECTORY_PATH:
3744
        case REMOVE_PATH:
3745
        case RECURSIVE_REMOVE_PATH:
3746
        case ADJUST_MODE:
3747
        case RELABEL_PATH:
3748
        case RECURSIVE_RELABEL_PATH:
3749
                if (i.argument)
36,732✔
3750
                        log_syntax(NULL, LOG_WARNING, fname, line, 0,
1✔
3751
                                   "%c lines don't take argument fields, ignoring.", (char) i.type);
3752
                break;
3753

3754
        case CREATE_FILE:
3755
        case TRUNCATE_FILE:
3756
                break;
3757

3758
        case CREATE_SYMLINK:
4,382✔
3759
                if (unbase64) {
4,382✔
3760
                        *invalid_config = true;
×
3761
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3762
                                          "base64 decoding not supported for symlink targets.");
3763
                }
3764
                break;
3765

3766
        case WRITE_FILE:
21✔
3767
                if (!i.argument) {
21✔
3768
                        *invalid_config = true;
1✔
3769
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1✔
3770
                                          "Write file requires argument.");
3771
                }
3772
                break;
3773

3774
        case COPY_FILES:
12,700✔
3775
                if (unbase64) {
12,700✔
3776
                        *invalid_config = true;
×
3777
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3778
                                          "base64 decoding not supported for copy sources.");
3779
                }
3780
                break;
3781

3782
        case CREATE_CHAR_DEVICE:
2,974✔
3783
        case CREATE_BLOCK_DEVICE:
3784
                if (unbase64) {
2,974✔
3785
                        *invalid_config = true;
×
3786
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3787
                                          "base64 decoding not supported for device node creation.");
3788
                }
3789

3790
                if (!i.argument) {
2,974✔
3791
                        *invalid_config = true;
×
3792
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3793
                                          "Device file requires argument.");
3794
                }
3795

3796
                r = parse_devnum(i.argument, &i.major_minor);
2,974✔
3797
                if (r < 0) {
2,974✔
3798
                        *invalid_config = true;
×
3799
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3800
                                          "Can't parse device file major/minor '%s'.", i.argument);
3801
                }
3802

3803
                break;
3804

3805
        case SET_XATTR:
×
3806
        case RECURSIVE_SET_XATTR:
3807
                if (unbase64) {
×
3808
                        *invalid_config = true;
×
3809
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3810
                                          "base64 decoding not supported for extended attributes.");
3811
                }
3812
                if (!i.argument) {
×
3813
                        *invalid_config = true;
×
3814
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3815
                                          "Set extended attribute requires argument.");
3816
                }
3817
                r = parse_xattrs_from_arg(&i);
×
3818
                if (r < 0)
×
3819
                        return r;
3820
                break;
3821

3822
        case SET_ACL:
2,566✔
3823
        case RECURSIVE_SET_ACL:
3824
                if (unbase64) {
2,566✔
3825
                        *invalid_config = true;
×
3826
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3827
                                          "base64 decoding not supported for ACLs.");
3828
                }
3829
                if (!i.argument) {
2,566✔
3830
                        *invalid_config = true;
×
3831
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3832
                                          "Set ACLs requires argument.");
3833
                }
3834
                r = parse_acls_from_arg(&i);
2,566✔
3835
                if (r < 0)
2,566✔
3836
                        return r;
3837
                break;
3838

3839
        case SET_ATTRIBUTE:
1,098✔
3840
        case RECURSIVE_SET_ATTRIBUTE:
3841
                if (unbase64) {
1,098✔
3842
                        *invalid_config = true;
×
3843
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3844
                                          "base64 decoding not supported for file attributes.");
3845
                }
3846
                if (!i.argument) {
1,098✔
3847
                        *invalid_config = true;
×
3848
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3849
                                          "Set file attribute requires argument.");
3850
                }
3851
                r = parse_attribute_from_arg(&i);
1,098✔
3852
                if (IN_SET(r, -EINVAL, -EBADSLT))
1,098✔
3853
                        *invalid_config = true;
×
3854
                if (r < 0)
1,098✔
3855
                        return r;
3856
                break;
3857

3858
        default:
×
3859
                *invalid_config = true;
×
3860
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3861
                                  "Unknown command type '%c'.", (char) i.type);
3862
        }
3863

3864
        if (i.purge && !needs_purge(i.type)) {
64,512✔
3865
                *invalid_config = true;
×
3866
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3867
                                  "Purge flag '$' combined with line type '%c' which does not support purging.", (char) i.type);
3868
        }
3869

3870
        if (i.ignore_if_target_missing && !supports_ignore_if_target_missing(i.type)) {
64,512✔
3871
                *invalid_config = true;
×
3872
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3873
                                  "Modifier '?' combined with line type '%c' which does not support this modifier.", (char) i.type);
3874
        }
3875

3876
        if (!should_include_path(i.path))
64,512✔
3877
                return 0;
3878

3879
        if (!unbase64) {
24,670✔
3880
                /* Do specifier expansion except if base64 mode is enabled */
3881
                r = specifier_expansion_from_arg(specifier_table, &i);
24,670✔
3882
                if (ERRNO_IS_NEG_NOINFO(r))
24,670✔
3883
                        return log_unresolvable_specifier(fname, line);
×
3884
                if (r < 0) {
24,670✔
3885
                        if (IN_SET(r, -EINVAL, -EBADSLT))
×
3886
                                *invalid_config = true;
×
3887
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
3888
                                          "Failed to substitute specifiers in argument: %m");
3889
                }
3890
        }
3891

3892
        switch (i.type) {
24,670✔
3893
        case CREATE_SYMLINK:
1,514✔
3894
                if (!i.argument) {
1,514✔
3895
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3896
                        if (!i.argument)
2✔
3897
                                return log_oom();
×
3898
                }
3899

3900
                break;
3901

3902
        case COPY_FILES:
4,360✔
3903
                if (!i.argument) {
4,360✔
3904
                        i.argument = path_join("/usr/share/factory", i.path);
3,469✔
3905
                        if (!i.argument)
3,469✔
3906
                                return log_oom();
×
3907
                } else if (!path_is_absolute(i.argument)) {
891✔
3908
                        *invalid_config = true;
×
3909
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3910
                                          "Source path '%s' is not absolute.", i.argument);
3911

3912
                }
3913

3914
                if (!empty_or_root(arg_root)) {
4,360✔
3915
                        char *p;
1✔
3916

3917
                        p = path_join(arg_root, i.argument);
1✔
3918
                        if (!p)
1✔
3919
                                return log_oom();
×
3920
                        free_and_replace(i.argument, p);
1✔
3921
                }
3922

3923
                path_simplify(i.argument);
4,360✔
3924

3925
                if (access_nofollow(i.argument, F_OK) == -ENOENT) {
4,849✔
3926
                        /* Silently skip over lines where the source file is missing. */
3927
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
489✔
3928
                                   "Copy source path '%s' does not exist, skipping line.", i.argument);
3929
                        return 0;
489✔
3930
                }
3931

3932
                break;
3933

3934
        default:
24,181✔
3935
                ;
24,181✔
3936
        }
3937

3938
        if (from_cred) {
24,181✔
3939
                if (!i.argument)
504✔
3940
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3941
                                          "Reading from credential requested, but no credential name specified.");
3942
                if (!credential_name_valid(i.argument))
504✔
3943
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3944
                                          "Credential name not valid: %s", i.argument);
3945

3946
                r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
504✔
3947
                if (IN_SET(r, -ENXIO, -ENOENT)) {
504✔
3948
                        /* Silently skip over lines that have no credentials passed */
3949
                        log_syntax(NULL, LOG_DEBUG, fname, line, 0,
384✔
3950
                                   "Credential '%s' not specified, skipping line.", i.argument);
3951
                        return 0;
384✔
3952
                }
3953
                if (r < 0)
120✔
3954
                        return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
×
3955
        }
3956

3957
        /* If base64 decoding is requested, do so now */
3958
        if (unbase64 && item_binary_argument(&i)) {
23,797✔
3959
                _cleanup_free_ void *data = NULL;
×
3960
                size_t data_size = 0;
×
3961

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

3967
                free_and_replace(i.binary_argument, data);
×
3968
                i.binary_argument_size = data_size;
×
3969
        }
3970

3971
        if (!empty_or_root(arg_root)) {
23,797✔
3972
                char *p;
14✔
3973

3974
                p = path_join(arg_root, i.path);
14✔
3975
                if (!p)
14✔
3976
                        return log_oom();
64,636✔
3977
                free_and_replace(i.path, p);
14✔
3978
        }
3979

3980
        if (!empty_or_dash(user)) {
23,797✔
3981
                const char *u;
8,789✔
3982

3983
                u = startswith(user, ":");
8,789✔
3984
                if (u)
8,789✔
3985
                        i.uid_only_create = true;
4✔
3986
                else
3987
                        u = user;
3988

3989
                r = find_uid(u, &i.uid, &c->uid_cache);
8,789✔
3990
                if (r == -ESRCH && arg_graceful) {
8,789✔
3991
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
3992
                                   "%s: user '%s' not found, not adjusting ownership.", i.path, u);
3993
                        missing_user_or_group = true;
3994
                } else if (r < 0) {
8,789✔
3995
                        *invalid_config = true;
×
3996
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", u);
×
3997
                } else
3998
                        i.uid_set = true;
8,789✔
3999
        }
4000

4001
        if (!empty_or_dash(group)) {
23,797✔
4002
                const char *g;
10,265✔
4003

4004
                g = startswith(group, ":");
10,265✔
4005
                if (g)
10,265✔
4006
                        i.gid_only_create = true;
376✔
4007
                else
4008
                        g = group;
4009

4010
                r = find_gid(g, &i.gid, &c->gid_cache);
10,265✔
4011
                if (r == -ESRCH && arg_graceful) {
10,265✔
4012
                        log_syntax(NULL, LOG_DEBUG, fname, line, r,
×
4013
                                   "%s: group '%s' not found, not adjusting ownership.", i.path, g);
4014
                        missing_user_or_group = true;
4015
                } else if (r < 0) {
10,265✔
4016
                        *invalid_config = true;
×
4017
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s': %m", g);
×
4018
                } else
4019
                        i.gid_set = true;
10,265✔
4020
        }
4021

4022
        if (!empty_or_dash(mode)) {
23,797✔
4023
                const char *mm;
4024
                unsigned m;
4025

4026
                for (mm = mode;; mm++)
502✔
4027
                        if (*mm == '~')
15,692✔
4028
                                i.mask_perms = true;
126✔
4029
                        else if (*mm == ':')
15,566✔
4030
                                i.mode_only_create = true;
376✔
4031
                        else
4032
                                break;
4033

4034
                r = parse_mode(mm, &m);
15,190✔
4035
                if (r < 0) {
15,190✔
4036
                        *invalid_config = true;
×
4037
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
×
4038
                }
4039

4040
                i.mode = m;
15,190✔
4041
                i.mode_set = true;
15,190✔
4042
        } else
4043
                i.mode = IN_SET(i.type,
8,607✔
4044
                                CREATE_DIRECTORY,
4045
                                TRUNCATE_DIRECTORY,
4046
                                CREATE_SUBVOLUME,
4047
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4048
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4049

4050
        if (missing_user_or_group && (i.mode & ~0777) != 0) {
23,797✔
4051
                /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
4052
                mode_t adjusted = i.mode & 0777;
×
4053
                log_syntax(NULL, LOG_INFO, fname, line, 0,
×
4054
                           "Changing mode 0%o to 0%o because of changed ownership.", i.mode, adjusted);
4055
                i.mode = adjusted;
×
4056
        }
4057

4058
        if (!empty_or_dash(age)) {
23,797✔
4059
                const char *a = age;
1,270✔
4060
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,270✔
4061

4062
                if (*a == '~') {
1,270✔
4063
                        i.keep_first_level = true;
×
4064
                        a++;
×
4065
                }
4066

4067
                /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
4068
                r = split_pair(a, ":", &age_by, &seconds);
1,270✔
4069
                if (r == -ENOMEM)
1,270✔
4070
                        return log_oom();
×
4071
                if (r < 0 && r != -EINVAL)
1,270✔
4072
                        return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
×
4073
                if (r >= 0) {
1,270✔
4074
                        /* We found a ":", parse the "age-by" part. */
4075
                        r = parse_age_by_from_arg(age_by, &i);
148✔
4076
                        if (r == -ENOMEM)
148✔
4077
                                return log_oom();
×
4078
                        if (r < 0) {
148✔
4079
                                *invalid_config = true;
7✔
4080
                                return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
7✔
4081
                        }
4082

4083
                        /* For parsing the "age" part, after the ":". */
4084
                        a = seconds;
141✔
4085
                }
4086

4087
                r = parse_sec(a, &i.age);
1,263✔
4088
                if (r < 0) {
1,263✔
4089
                        *invalid_config = true;
2✔
4090
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
2✔
4091
                }
4092

4093
                i.age_set = true;
1,261✔
4094
        }
4095

4096
        h = needs_glob(i.type) ? c->globs : c->items;
23,788✔
4097

4098
        existing = ordered_hashmap_get(h, i.path);
23,788✔
4099
        if (existing) {
23,788✔
4100
                if (is_duplicated_item(existing, &i)) {
1,392✔
4101
                        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3✔
4102
                                   "Duplicate line for path \"%s\", ignoring.", i.path);
4103
                        return 0;
3✔
4104
                }
4105
        } else {
4106
                existing = new0(ItemArray, 1);
22,396✔
4107
                if (!existing)
22,396✔
4108
                        return log_oom();
×
4109

4110
                r = ordered_hashmap_put(h, i.path, existing);
22,396✔
4111
                if (r < 0) {
22,396✔
4112
                        free(existing);
×
4113
                        return log_oom();
×
4114
                }
4115
        }
4116

4117
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
23,785✔
4118
                return log_oom();
×
4119

4120
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
23,785✔
4121

4122
        /* Sort item array, to enforce stable ordering of application */
4123
        typesafe_qsort(existing->items, existing->n_items, item_compare);
23,785✔
4124

4125
        return 0;
4126
}
4127

4128
static int cat_config(char **config_dirs, char **args) {
×
4129
        _cleanup_strv_free_ char **files = NULL;
×
4130
        int r;
×
4131

4132
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4133
        if (r < 0)
×
4134
                return r;
4135

4136
        pager_open(arg_pager_flags);
×
4137

4138
        return cat_files(NULL, files, arg_cat_flags);
×
4139
}
4140

4141
static int exclude_default_prefixes(void) {
×
4142
        int r;
×
4143

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

4149
        r = strv_extend_many(
×
4150
                        &arg_exclude_prefixes,
4151
                        "/dev",
4152
                        "/proc",
4153
                        "/run",
4154
                        "/sys");
4155
        if (r < 0)
×
4156
                return log_oom();
×
4157

4158
        strv_uniq(arg_exclude_prefixes);
×
4159
        return 0;
×
4160
}
4161

4162
static int help(void) {
×
4163
        _cleanup_free_ char *link = NULL;
×
4164
        int r;
×
4165

4166
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4167
        if (r < 0)
×
4168
                return log_oom();
×
4169

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

4202
        return 0;
4203
}
4204

4205
static int parse_argv(int argc, char *argv[]) {
680✔
4206
        enum {
680✔
4207
                ARG_VERSION = 0x100,
4208
                ARG_CAT_CONFIG,
4209
                ARG_TLDR,
4210
                ARG_USER,
4211
                ARG_CREATE,
4212
                ARG_CLEAN,
4213
                ARG_REMOVE,
4214
                ARG_PURGE,
4215
                ARG_BOOT,
4216
                ARG_GRACEFUL,
4217
                ARG_PREFIX,
4218
                ARG_EXCLUDE_PREFIX,
4219
                ARG_ROOT,
4220
                ARG_IMAGE,
4221
                ARG_IMAGE_POLICY,
4222
                ARG_REPLACE,
4223
                ARG_DRY_RUN,
4224
                ARG_NO_PAGER,
4225
        };
4226

4227
        static const struct option options[] = {
680✔
4228
                { "help",           no_argument,         NULL, 'h'                },
4229
                { "user",           no_argument,         NULL, ARG_USER           },
4230
                { "version",        no_argument,         NULL, ARG_VERSION        },
4231
                { "cat-config",     no_argument,         NULL, ARG_CAT_CONFIG     },
4232
                { "tldr",           no_argument,         NULL, ARG_TLDR           },
4233
                { "create",         no_argument,         NULL, ARG_CREATE         },
4234
                { "clean",          no_argument,         NULL, ARG_CLEAN          },
4235
                { "remove",         no_argument,         NULL, ARG_REMOVE         },
4236
                { "purge",          no_argument,         NULL, ARG_PURGE          },
4237
                { "boot",           no_argument,         NULL, ARG_BOOT           },
4238
                { "graceful",       no_argument,         NULL, ARG_GRACEFUL       },
4239
                { "prefix",         required_argument,   NULL, ARG_PREFIX         },
4240
                { "exclude-prefix", required_argument,   NULL, ARG_EXCLUDE_PREFIX },
4241
                { "root",           required_argument,   NULL, ARG_ROOT           },
4242
                { "image",          required_argument,   NULL, ARG_IMAGE          },
4243
                { "image-policy",   required_argument,   NULL, ARG_IMAGE_POLICY   },
4244
                { "replace",        required_argument,   NULL, ARG_REPLACE        },
4245
                { "dry-run",        no_argument,         NULL, ARG_DRY_RUN        },
4246
                { "no-pager",       no_argument,         NULL, ARG_NO_PAGER       },
4247
                {}
4248
        };
4249

4250
        int c, r;
680✔
4251

4252
        assert(argc >= 0);
680✔
4253
        assert(argv);
680✔
4254

4255
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
2,883✔
4256

4257
                switch (c) {
2,203✔
4258

4259
                case 'h':
×
4260
                        return help();
×
4261

4262
                case ARG_VERSION:
×
4263
                        return version();
×
4264

4265
                case ARG_CAT_CONFIG:
×
4266
                        arg_cat_flags = CAT_CONFIG_ON;
×
4267
                        break;
×
4268

4269
                case ARG_TLDR:
×
4270
                        arg_cat_flags = CAT_TLDR;
×
4271
                        break;
×
4272

4273
                case ARG_USER:
176✔
4274
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
176✔
4275
                        break;
176✔
4276

4277
                case ARG_CREATE:
628✔
4278
                        arg_operation |= OPERATION_CREATE;
628✔
4279
                        break;
628✔
4280

4281
                case ARG_CLEAN:
39✔
4282
                        arg_operation |= OPERATION_CLEAN;
39✔
4283
                        break;
39✔
4284

4285
                case ARG_REMOVE:
306✔
4286
                        arg_operation |= OPERATION_REMOVE;
306✔
4287
                        break;
306✔
4288

4289
                case ARG_BOOT:
532✔
4290
                        arg_boot = true;
532✔
4291
                        break;
532✔
4292

4293
                case ARG_PURGE:
5✔
4294
                        arg_operation |= OPERATION_PURGE;
5✔
4295
                        break;
5✔
4296

4297
                case ARG_GRACEFUL:
120✔
4298
                        arg_graceful = true;
120✔
4299
                        break;
120✔
4300

4301
                case ARG_PREFIX:
240✔
4302
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
240✔
4303
                                return log_oom();
×
4304
                        break;
4305

4306
                case ARG_EXCLUDE_PREFIX:
120✔
4307
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
120✔
4308
                                return log_oom();
×
4309
                        break;
4310

4311
                case ARG_ROOT:
8✔
4312
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
8✔
4313
                        if (r < 0)
8✔
4314
                                return r;
4315
                        break;
4316

4317
                case ARG_IMAGE:
×
4318
#ifdef STANDALONE
4319
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4320
                                               "This systemd-tmpfiles version is compiled without support for --image=.");
4321
#else
4322
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
4323
                        if (r < 0)
×
4324
                                return r;
4325
#endif
4326
                        /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4327
                        _fallthrough_;
×
4328

4329
                case 'E':
4330
                        r = exclude_default_prefixes();
×
4331
                        if (r < 0)
×
4332
                                return r;
4333

4334
                        break;
4335

4336
                case ARG_IMAGE_POLICY:
×
4337
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4338
                        if (r < 0)
×
4339
                                return r;
4340
                        break;
4341

4342
                case ARG_REPLACE:
×
4343
                        if (!path_is_absolute(optarg))
×
4344
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4345
                                                       "The argument to --replace= must be an absolute path.");
4346
                        if (!endswith(optarg, ".conf"))
×
4347
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4348
                                                       "The argument to --replace= must have the extension '.conf'.");
4349

4350
                        arg_replace = optarg;
×
4351
                        break;
×
4352

4353
                case ARG_DRY_RUN:
29✔
4354
                        arg_dry_run = true;
29✔
4355
                        break;
29✔
4356

4357
                case ARG_NO_PAGER:
×
4358
                        arg_pager_flags |= PAGER_DISABLE;
×
4359
                        break;
×
4360

4361
                case '?':
4362
                        return -EINVAL;
4363

4364
                default:
×
4365
                        assert_not_reached();
×
4366
                }
4367

4368
        if (arg_operation == 0 && arg_cat_flags == CAT_CONFIG_OFF)
680✔
4369
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4370
                                       "You need to specify at least one of --clean, --create, --remove, or --purge.");
4371

4372
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
680✔
4373
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4374
                                       "Refusing --purge without specification of a configuration file.");
4375

4376
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
680✔
4377
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4378
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4379

4380
        if (arg_replace && optind >= argc)
680✔
4381
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4382
                                       "When --replace= is given, some configuration items must be specified.");
4383

4384
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
680✔
4385
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4386
                                       "Combination of --user and --root= is not supported.");
4387

4388
        if (arg_image && arg_root)
680✔
4389
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4390
                                       "Please specify either --root= or --image=, the combination of both is not supported.");
4391

4392
        return 1;
4393
}
4394

4395
static int read_config_file(
15,558✔
4396
                Context *c,
4397
                char **config_dirs,
4398
                const char *fn,
4399
                bool ignore_enoent,
4400
                bool *invalid_config) {
4401

4402
        ItemArray *ia;
15,558✔
4403
        int r = 0;
15,558✔
4404

4405
        assert(c);
15,558✔
4406
        assert(fn);
15,558✔
4407

4408
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
15,558✔
4409
                           parse_line, c, ignore_enoent, invalid_config);
4410
        if (r <= 0)
15,558✔
4411
                return r;
15,558✔
4412

4413
        /* we have to determine age parameter for each entry of type X */
4414
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
119,003✔
4415
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
212,937✔
4416
                        ItemArray *ja;
109,134✔
4417
                        Item *candidate_item = NULL;
109,134✔
4418

4419
                        if (i->type != IGNORE_DIRECTORY_PATH)
109,134✔
4420
                                continue;
107,350✔
4421

4422
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
162,158✔
4423
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
325,898✔
4424
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
165,524✔
4425
                                                             TRUNCATE_DIRECTORY,
4426
                                                             CREATE_SUBVOLUME,
4427
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4428
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4429
                                                continue;
83,912✔
4430

4431
                                        if (path_equal(j->path, i->path)) {
81,612✔
4432
                                                candidate_item = j;
4433
                                                break;
4434
                                        }
4435

4436
                                        if (candidate_item
81,612✔
4437
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
7,722✔
4438
                                            : path_startswith(i->path, j->path) != NULL)
73,890✔
4439
                                                candidate_item = j;
4440
                                }
4441

4442
                        if (candidate_item && candidate_item->age_set) {
1,784✔
4443
                                i->age = candidate_item->age;
1,274✔
4444
                                i->age_set = true;
1,274✔
4445
                        }
4446
                }
4447

4448
        return r;
15,200✔
4449
}
4450

4451
static int parse_arguments(
138✔
4452
                Context *c,
4453
                char **config_dirs,
4454
                char **args,
4455
                bool *invalid_config) {
4456
        int r;
138✔
4457

4458
        assert(c);
138✔
4459

4460
        STRV_FOREACH(arg, args) {
276✔
4461
                r = read_config_file(c, config_dirs, *arg, false, invalid_config);
138✔
4462
                if (r < 0)
138✔
4463
                        return r;
4464
        }
4465

4466
        return 0;
4467
}
4468

4469
static int read_config_files(
542✔
4470
                Context *c,
4471
                char **config_dirs,
4472
                char **args,
4473
                bool *invalid_config) {
4474

4475
        _cleanup_strv_free_ char **files = NULL;
×
4476
        _cleanup_free_ char *p = NULL;
542✔
4477
        int r;
542✔
4478

4479
        assert(c);
542✔
4480

4481
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
542✔
4482
        if (r < 0)
542✔
4483
                return r;
4484

4485
        STRV_FOREACH(f, files)
15,601✔
4486
                if (p && path_equal(*f, p)) {
15,059✔
4487
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4488

4489
                        r = parse_arguments(c, config_dirs, args, invalid_config);
×
4490
                        if (r < 0)
×
4491
                                return r;
4492
                } else
4493
                        /* Just warn, ignore result otherwise.
4494
                         * read_config_file() has some debug output, so no need to print anything. */
4495
                        (void) read_config_file(c, config_dirs, *f, true, invalid_config);
15,059✔
4496

4497
        return 0;
4498
}
4499

4500
static int read_credential_lines(Context *c, bool *invalid_config) {
680✔
4501
        _cleanup_free_ char *j = NULL;
680✔
4502
        const char *d;
680✔
4503
        int r;
680✔
4504

4505
        assert(c);
680✔
4506

4507
        r = get_credentials_dir(&d);
680✔
4508
        if (r == -ENXIO)
680✔
4509
                return 0;
4510
        if (r < 0)
361✔
4511
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4512

4513
        j = path_join(d, "tmpfiles.extra");
361✔
4514
        if (!j)
361✔
4515
                return log_oom();
×
4516

4517
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
361✔
4518
        return 0;
4519
}
4520

4521
static int link_parent(Context *c, ItemArray *a) {
22,396✔
4522
        const char *path;
22,396✔
4523
        char *prefix;
22,396✔
4524
        int r;
22,396✔
4525

4526
        assert(c);
22,396✔
4527
        assert(a);
22,396✔
4528

4529
        /* Finds the closest "parent" item array for the specified item array. Then registers the specified
4530
         * item array as child of it, and fills the parent in, linking them both ways. This allows us to
4531
         * later create parents before their children, and clean up/remove children before their parents.
4532
         */
4533

4534
        if (a->n_items <= 0)
22,396✔
4535
                return 0;
4536

4537
        path = a->items[0].path;
22,396✔
4538
        prefix = newa(char, strlen(path) + 1);
22,396✔
4539
        PATH_FOREACH_PREFIX(prefix, path) {
74,391✔
4540
                ItemArray *j;
39,144✔
4541

4542
                j = ordered_hashmap_get(c->items, prefix);
39,144✔
4543
                if (!j)
39,144✔
4544
                        j = ordered_hashmap_get(c->globs, prefix);
30,489✔
4545
                if (j) {
30,489✔
4546
                        r = set_ensure_put(&j->children, NULL, a);
9,545✔
4547
                        if (r < 0)
9,545✔
4548
                                return log_oom();
×
4549

4550
                        a->parent = j;
9,545✔
4551
                        return 1;
9,545✔
4552
                }
4553
        }
4554

4555
        return 0;
4556
}
4557

4558
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
22,396✔
4559
                                              ItemArray, item_array_free);
4560

4561
static int run(int argc, char *argv[]) {
680✔
4562
#ifndef STANDALONE
4563
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
680✔
4564
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
680✔
4565
#endif
4566
        _cleanup_strv_free_ char **config_dirs = NULL;
680✔
4567
        _cleanup_(context_done) Context c = {};
×
4568
        bool invalid_config = false;
680✔
4569
        ItemArray *a;
680✔
4570
        enum {
680✔
4571
                PHASE_PURGE,
4572
                PHASE_REMOVE_AND_CLEAN,
4573
                PHASE_CREATE,
4574
                _PHASE_MAX
4575
        } phase;
4576
        int r;
680✔
4577

4578
        r = parse_argv(argc, argv);
680✔
4579
        if (r <= 0)
680✔
4580
                return r;
4581

4582
        log_setup();
680✔
4583

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

4594
        /* Descending down file system trees might take a lot of fds */
4595
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
680✔
4596

4597
        switch (arg_runtime_scope) {
680✔
4598

4599
        case RUNTIME_SCOPE_USER:
176✔
4600
                r = user_config_paths(&config_dirs);
176✔
4601
                if (r < 0)
176✔
4602
                        return log_error_errno(r, "Failed to initialize configuration directory list: %m");
×
4603
                break;
4604

4605
        case RUNTIME_SCOPE_SYSTEM:
504✔
4606
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
504✔
4607
                if (!config_dirs)
504✔
4608
                        return log_oom();
×
4609
                break;
4610

4611
        default:
×
4612
                assert_not_reached();
×
4613
        }
4614

4615
        if (DEBUG_LOGGING) {
680✔
4616
                _cleanup_free_ char *t = NULL;
568✔
4617

4618
                STRV_FOREACH(i, config_dirs) {
3,192✔
4619
                        _cleanup_free_ char *j = NULL;
2,624✔
4620

4621
                        j = path_join(arg_root, *i);
2,624✔
4622
                        if (!j)
2,624✔
4623
                                return log_oom();
×
4624

4625
                        if (!strextend(&t, "\n\t", j))
2,624✔
4626
                                return log_oom();
×
4627
                }
4628

4629
                log_debug("Looking for configuration files in (higher priority first):%s", t);
568✔
4630
        }
4631

4632
        if (arg_cat_flags != CAT_CONFIG_OFF)
680✔
4633
                return cat_config(config_dirs, argv + optind);
×
4634

4635
        if (should_bypass("SYSTEMD_TMPFILES"))
680✔
4636
                return 0;
4637

4638
        umask(0022);
680✔
4639

4640
        r = mac_init();
680✔
4641
        if (r < 0)
680✔
4642
                return r;
4643

4644
#ifndef STANDALONE
4645
        if (arg_image) {
680✔
4646
                assert(!arg_root);
×
4647

4648
                r = mount_image_privately_interactively(
×
4649
                                arg_image,
4650
                                arg_image_policy,
4651
                                DISSECT_IMAGE_GENERIC_ROOT |
4652
                                DISSECT_IMAGE_REQUIRE_ROOT |
4653
                                DISSECT_IMAGE_VALIDATE_OS |
4654
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
4655
                                DISSECT_IMAGE_FSCK |
4656
                                DISSECT_IMAGE_GROWFS |
4657
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
4658
                                &mounted_dir,
4659
                                /* ret_dir_fd= */ NULL,
4660
                                &loop_device);
4661
                if (r < 0)
×
4662
                        return r;
4663

4664
                arg_root = strdup(mounted_dir);
×
4665
                if (!arg_root)
×
4666
                        return log_oom();
×
4667
        }
4668
#else
4669
        assert(!arg_image);
4670
#endif
4671

4672
        c.items = ordered_hashmap_new(&item_array_hash_ops);
680✔
4673
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
680✔
4674
        if (!c.items || !c.globs)
680✔
4675
                return log_oom();
×
4676

4677
        /* If command line arguments are specified along with --replace=, read all configuration files and
4678
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4679
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
4680
         * read configuration and execute it. */
4681
        if (arg_replace || optind >= argc)
680✔
4682
                r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
542✔
4683
        else
4684
                r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
138✔
4685
        if (r < 0)
680✔
4686
                return r;
4687

4688
        r = read_credential_lines(&c, &invalid_config);
680✔
4689
        if (r < 0)
680✔
4690
                return r;
4691

4692
        /* Let's now link up all child/parent relationships */
4693
        ORDERED_HASHMAP_FOREACH(a, c.items) {
16,553✔
4694
                r = link_parent(&c, a);
15,873✔
4695
                if (r < 0)
15,873✔
4696
                        return r;
×
4697
        }
4698
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
7,203✔
4699
                r = link_parent(&c, a);
6,523✔
4700
                if (r < 0)
6,523✔
4701
                        return r;
×
4702
        }
4703

4704
        /* If multiple operations are requested, let's first run the remove/clean operations, and only then
4705
         * the create operations. i.e. that we first clean out the platform we then build on. */
4706
        for (phase = 0; phase < _PHASE_MAX; phase++) {
2,720✔
4707
                OperationMask op;
2,040✔
4708

4709
                if (phase == PHASE_PURGE)
2,040✔
4710
                        op = arg_operation & OPERATION_PURGE;
680✔
4711
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,360✔
4712
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
680✔
4713
                else if (phase == PHASE_CREATE)
680✔
4714
                        op = arg_operation & OPERATION_CREATE;
680✔
4715
                else
4716
                        assert_not_reached();
×
4717

4718
                if (op == 0) /* Nothing requested in this phase */
2,040✔
4719
                        continue;
1,062✔
4720

4721
                /* The non-globbing ones usually create things, hence we apply them first */
4722
                ORDERED_HASHMAP_FOREACH(a, c.items)
29,500✔
4723
                        RET_GATHER(r, process_item_array(&c, a, op));
28,522✔
4724

4725
                /* The globbing ones usually alter things, hence we apply them second. */
4726
                ORDERED_HASHMAP_FOREACH(a, c.globs)
11,567✔
4727
                        RET_GATHER(r, process_item_array(&c, a, op));
10,589✔
4728
        }
4729

4730
        if (ERRNO_IS_NEG_RESOURCE(r))
1,360✔
4731
                return r;
4732
        if (invalid_config)
680✔
4733
                return EX_DATAERR;
4734
        if (r < 0)
670✔
4735
                return EX_CANTCREAT;
15✔
4736
        return 0;
4737
}
4738

4739
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
680✔
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