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

systemd / systemd / 15646177709

13 Jun 2025 10:59PM UTC coverage: 72.071% (+0.06%) from 72.008%
15646177709

push

github

YHNdnzj
nsresourced: make sure "tun" driver is properly loaded and accessible

We need access to /dev/net/tun, hence make sure we can actually see
/dev/. Also make sure the module is properly loaded before we operate,
given that we run with limit caps. But then again give the CAP_NET_ADMIN
cap, since we need to configure the network tap/tun devices.

Follow-up for: 136503472

300309 of 416683 relevant lines covered (72.07%)

701997.93 hits per line

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

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

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

11
#include "sd-path.h"
12

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

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

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

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

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

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

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

129
typedef struct Item {
130
        ItemType type;
131

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

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

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

162
        bool keep_first_level:1;
163

164
        bool append_or_force:1;
165

166
        bool allow_failure:1;
167

168
        bool try_replace:1;
169

170
        bool purge:1;
171

172
        bool ignore_if_target_missing:1;
173

174
        OperationMask done;
175
} Item;
176

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

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

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

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

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

215
#define MAX_DEPTH 256
216

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

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

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

237
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
10,497✔
238

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

312
        return 0;
313
}
314

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

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

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

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

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

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

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

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

356
        assert(ret);
179✔
357

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

549
        return dir;
550
}
551

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

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

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

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

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

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

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

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

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

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

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

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

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

625
                return false;
24✔
626
        }
627

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

634
                return false;
63✔
635
        }
636

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

647
                return false;
7✔
648
        }
649

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

656
                return false;
5✔
657
        }
658

659
        return true;
660
}
661

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

790
                                        continue;
×
791
                                }
792

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

917
        return r;
81✔
918
}
919

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

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

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

931
        _cleanup_free_ char *value = NULL;
×
932

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

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

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

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

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

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

962
        return mode;
279✔
963
}
964

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

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

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

985
        if (!i->mode_set && !i->uid_set && !i->gid_set)
19,101✔
986
                goto shortcut;
5,082✔
987

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1096
        return fd;
16,219✔
1097
}
1098

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

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

1106
        assert(path);
3,605✔
1107

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

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

1119
        return fd;
3,605✔
1120
}
1121

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

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

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

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

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

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

1147
        assert(i);
×
1148

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

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

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

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

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

1173
                name = value = NULL;
×
1174
        }
1175

1176
        return 0;
×
1177
}
1178

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

1187
        int r;
×
1188

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

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

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

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

1214
        _cleanup_close_ int fd = -EBADF;
×
1215

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

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

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

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

1233
        assert(item);
2,559✔
1234

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

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

1247
        return 0;
2,559✔
1248
}
1249

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

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

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

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

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

1276
                has_exec = false;
177✔
1277

1278
                for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
177✔
1279
                     r > 0;
708✔
1280
                     r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
531✔
1281

1282
                        acl_tag_t tag;
541✔
1283

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

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

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

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

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

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

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

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

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

1335
        for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
279✔
1336
             r > 0;
833✔
1337
             r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
554✔
1338

1339
                acl_entry_t parsed_entry;
554✔
1340

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

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

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

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

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

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

1367
        return 0;
279✔
1368
}
1369

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

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

1382
        assert(c);
996✔
1383

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1547
        assert(item);
1,095✔
1548

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

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

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

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

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

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

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

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

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

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

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

1595
        return 0;
1,095✔
1596
}
1597

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

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

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

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

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

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

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

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

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

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

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

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

1661
        return 0;
1662
}
1663

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

1670
        _cleanup_close_ int fd = -EBADF;
46✔
1671

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

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

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

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

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

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

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

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

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

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

1707
        return 0;
1708
}
1709

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1828
                creation = CREATION_NORMAL;
1829
        }
1830

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1996
        assert(path);
7,860✔
1997

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

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

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

2032
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2033
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
15,426✔
2034
                if (!arg_dry_run)
7,858✔
2035
                        WITH_UMASK(0000)
15,716✔
2036
                                r = mkdirat_label(pfd, bn, mode);
7,858✔
2037
        }
2038

2039
        if (arg_dry_run)
7,858✔
2040
                return 0;
2041

2042
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
7,858✔
2043

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

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

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

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

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

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

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

2073
        return fd;
2074
}
2075

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

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

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

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

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

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

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

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

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

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

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

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

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

2149
        return r;
2150
}
2151

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2472
                fd = safe_close(fd);
4✔
2473

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

2482
                        mac_selinux_create_file_prepare(i->path, S_IFLNK);
1✔
2483
                        r = RET_NERRNO(symlinkat(i->argument, pfd, i->path));
1✔
2484
                        mac_selinux_create_file_clear();
1✔
2485
                }
2486
                if (r < 0)
3✔
2487
                        return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
×
2488

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

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

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

2500
                creation = CREATION_FORCE;
2501
        }
2502

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

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

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

2518
        struct stat st;
559✔
2519
        int r;
559✔
2520

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

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

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

2535
        if (S_ISDIR(st.st_mode)) {
559✔
2536
                _cleanup_closedir_ DIR *d = NULL;
206✔
2537

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

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

2550
                        if (dot_or_dot_dot(de->d_name))
765✔
2551
                                continue;
412✔
2552

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

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

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

2571
finish:
353✔
2572
        safe_close(fd);
559✔
2573
        return r;
559✔
2574
}
2575

2576
static int glob_item(Context *c, Item *i, action_t action) {
6,242✔
2577
        _cleanup_globfree_ glob_t g = {
6,242✔
2578
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2579
        };
2580
        int r;
6,242✔
2581

2582
        assert(c);
6,242✔
2583
        assert(i);
6,242✔
2584
        assert(action);
6,242✔
2585

2586
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
6,242✔
2587
        if (r == -ENOENT)
6,242✔
2588
                return 0;
2589
        if (r < 0)
3,163✔
2590
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2591

2592
        r = 0;
3,163✔
2593
        STRV_FOREACH(fn, g.gl_pathv)
6,833✔
2594
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2595
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
3,670✔
2596

2597
        return r;
2598
}
2599

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

2605
        _cleanup_globfree_ glob_t g = {
252✔
2606
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2607
        };
2608
        int r;
252✔
2609

2610
        assert(c);
252✔
2611
        assert(i);
252✔
2612
        assert(action);
252✔
2613

2614
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
252✔
2615
        if (r == -ENOENT)
252✔
2616
                return 0;
2617
        if (r < 0)
206✔
2618
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2619

2620
        r = 0;
206✔
2621
        STRV_FOREACH(fn, g.gl_pathv) {
412✔
2622
                _cleanup_close_ int fd = -EBADF;
206✔
2623

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

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

2634
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
206✔
2635
        }
2636

2637
        return r;
2638
}
2639

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

2651
        assert(name);
×
2652
        assert((mode & ~S_IFMT) == 0);
×
2653
        assert(!follow_links || parent_st);
×
2654
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2655

2656
        if (mode == 0)
×
2657
                return 0;
2658

2659
        if (!filename_is_valid(name))
×
2660
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2661

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

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

2676
        if ((st.st_mode & S_IFMT) == mode)
×
2677
                return 0;
2678

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

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

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

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

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

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

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

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

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

2731
        assert(path);
×
2732
        assert((child_mode & ~S_IFMT) == 0);
×
2733

2734
        path_len = strlen(path);
×
2735

2736
        if (!is_path(path))
×
2737
                /* rm_if_wrong_type_safe already logs errors. */
2738
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2739

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

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

2749
        if (fstat(parent_fd, &parent_st) < 0)
×
2750
                return log_error_errno(errno, "Failed to stat root: %m");
×
2751

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

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

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

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

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

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

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

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

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

2804
                close_and_replace(parent_fd, next_fd);
×
2805
        }
2806
}
2807

2808
static int mkdir_parents_item(Item *i, mode_t child_mode) {
16,231✔
2809
        int r;
16,231✔
2810

2811
        if (i->try_replace) {
16,231✔
2812
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2813
                if (r < 0 && r != -ENOENT)
×
2814
                        return r;
×
2815
        } else
2816
                WITH_UMASK(0000)
32,462✔
2817
                        if (!arg_dry_run)
16,231✔
2818
                                (void) mkdir_parents_label(i->path, 0755);
16,231✔
2819

2820
        return 0;
2821
}
2822

2823
static int create_item(Context *c, Item *i) {
23,556✔
2824
        int r;
23,556✔
2825

2826
        assert(c);
23,556✔
2827
        assert(i);
23,556✔
2828

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

2831
        switch (i->type) {
23,556✔
2832

2833
        case IGNORE_PATH:
2834
        case IGNORE_DIRECTORY_PATH:
2835
        case REMOVE_PATH:
2836
        case RECURSIVE_REMOVE_PATH:
2837
                return 0;
2838

2839
        case TRUNCATE_FILE:
1,027✔
2840
        case CREATE_FILE:
2841
                r = mkdir_parents_item(i, S_IFREG);
1,027✔
2842
                if (r < 0)
1,027✔
2843
                        return r;
2844

2845
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,027✔
2846
                        r = truncate_file(c, i, i->path);
251✔
2847
                else
2848
                        r = create_file(c, i, i->path);
776✔
2849
                if (r < 0)
1,027✔
2850
                        return r;
15✔
2851
                break;
2852

2853
        case COPY_FILES:
3,845✔
2854
                r = mkdir_parents_item(i, 0);
3,845✔
2855
                if (r < 0)
3,845✔
2856
                        return r;
2857

2858
                r = copy_files(c, i);
3,845✔
2859
                if (r < 0)
3,845✔
2860
                        return r;
×
2861
                break;
2862

2863
        case WRITE_FILE:
20✔
2864
                r = glob_item(c, i, write_one_file);
20✔
2865
                if (r < 0)
20✔
2866
                        return r;
×
2867

2868
                break;
2869

2870
        case CREATE_DIRECTORY:
6,996✔
2871
        case TRUNCATE_DIRECTORY:
2872
                r = mkdir_parents_item(i, S_IFDIR);
6,996✔
2873
                if (r < 0)
6,996✔
2874
                        return r;
2875

2876
                r = create_directory(c, i, i->path);
6,996✔
2877
                if (r < 0)
6,996✔
2878
                        return r;
2✔
2879
                break;
2880

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

2888
                r = create_subvolume(c, i, i->path);
875✔
2889
                if (r < 0)
875✔
2890
                        return r;
×
2891
                break;
2892

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

2899
        case CREATE_FIFO:
4✔
2900
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2901
                if (r < 0)
4✔
2902
                        return r;
2903

2904
                r = create_fifo(c, i);
4✔
2905
                if (r < 0)
4✔
2906
                        return r;
×
2907
                break;
2908

2909
        case CREATE_SYMLINK:
1,500✔
2910
                r = mkdir_parents_item(i, S_IFLNK);
1,500✔
2911
                if (r < 0)
1,500✔
2912
                        return r;
2913

2914
                r = create_symlink(c, i);
1,500✔
2915
                if (r < 0)
1,500✔
2916
                        return r;
×
2917

2918
                break;
2919

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

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

2930
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,966✔
2931
                if (r < 0)
1,984✔
2932
                        return r;
2933

2934
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
3,966✔
2935
                if (r < 0)
1,984✔
2936
                        return r;
×
2937

2938
                break;
2939

2940
        case ADJUST_MODE:
4,329✔
2941
        case RELABEL_PATH:
2942
                r = glob_item(c, i, path_set_perms);
4,329✔
2943
                if (r < 0)
4,329✔
2944
                        return r;
×
2945
                break;
2946

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

2953
        case SET_XATTR:
×
2954
                r = glob_item(c, i, path_set_xattrs);
×
2955
                if (r < 0)
×
2956
                        return r;
×
2957
                break;
2958

2959
        case RECURSIVE_SET_XATTR:
×
2960
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2961
                if (r < 0)
×
2962
                        return r;
×
2963
                break;
2964

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

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

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

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

2990
        return 0;
2991
}
2992

2993
static int remove_recursive(
501✔
2994
                Context *c,
2995
                Item *i,
2996
                const char *instance,
2997
                bool remove_instance) {
2998

2999
        _cleanup_closedir_ DIR *d = NULL;
501✔
3000
        struct statx sx;
501✔
3001
        bool mountpoint;
501✔
3002
        int r;
501✔
3003

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

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

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

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

3050
static int purge_item(Context *c, Item *i) {
15✔
3051
        assert(i);
15✔
3052

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

3056
        if (!i->purge)
15✔
3057
                return 0;
3058

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

3061
        if (needs_glob(i->type))
10✔
3062
                return glob_item(c, i, purge_item_instance);
×
3063

3064
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3065
}
3066

3067
static int remove_item_instance(
16✔
3068
                Context *c,
3069
                Item *i,
3070
                const char *instance,
3071
                CreationMode creation) {
3072

3073
        assert(c);
16✔
3074
        assert(i);
16✔
3075

3076
        switch (i->type) {
16✔
3077

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

3085
                return 0;
3086

3087
        case RECURSIVE_REMOVE_PATH:
8✔
3088
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3089

3090
        default:
×
3091
                assert_not_reached();
×
3092
        }
3093
}
3094

3095
static int remove_item(Context *c, Item *i) {
17,934✔
3096
        assert(c);
17,934✔
3097
        assert(i);
17,934✔
3098

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

3101
        switch (i->type) {
17,934✔
3102

3103
        case TRUNCATE_DIRECTORY:
483✔
3104
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
483✔
3105

3106
        case REMOVE_PATH:
738✔
3107
        case RECURSIVE_REMOVE_PATH:
3108
                return glob_item(c, i, remove_item_instance);
738✔
3109

3110
        default:
3111
                return 0;
3112
        }
3113
}
3114

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

3120
        ret = new(char, ELEMENTSOF(ab_map) + 1);
44✔
3121
        if (!ret)
44✔
3122
                return NULL;
3123

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

3128
        ret[j] = 0;
44✔
3129
        return ret;
44✔
3130
}
3131

3132
static int clean_item_instance(
50✔
3133
                Context *c,
3134
                Item *i,
3135
                const char* instance,
3136
                CreationMode creation) {
3137

3138
        assert(i);
50✔
3139

3140
        if (!i->age_set)
50✔
3141
                return 0;
50✔
3142

3143
        usec_t n = now(CLOCK_REALTIME);
38✔
3144
        if (n < i->age)
38✔
3145
                return 0;
3146

3147
        usec_t cutoff = n - i->age;
38✔
3148

3149
        _cleanup_closedir_ DIR *d = NULL;
50✔
3150
        struct statx sx;
38✔
3151
        bool mountpoint;
38✔
3152
        int r;
38✔
3153

3154
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
38✔
3155
        if (r <= 0)
38✔
3156
                return r;
3157

3158
        if (DEBUG_LOGGING) {
34✔
3159
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
22✔
3160

3161
                ab_f = age_by_to_string(i->age_by_file, false);
22✔
3162
                if (!ab_f)
22✔
3163
                        return log_oom();
×
3164

3165
                ab_d = age_by_to_string(i->age_by_dir, true);
22✔
3166
                if (!ab_d)
22✔
3167
                        return log_oom();
×
3168

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

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

3186
static int clean_item(Context *c, Item *i) {
50✔
3187
        assert(c);
50✔
3188
        assert(i);
50✔
3189

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

3192
        switch (i->type) {
50✔
3193

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

3203
        case EMPTY_DIRECTORY:
22✔
3204
        case IGNORE_PATH:
3205
        case IGNORE_DIRECTORY_PATH:
3206
                return glob_item(c, i, clean_item_instance);
22✔
3207

3208
        default:
3209
                return 0;
3210
        }
3211
}
3212

3213
static int process_item(
77,737✔
3214
                Context *c,
3215
                Item *i,
3216
                OperationMask operation) {
3217

3218
        OperationMask todo;
77,737✔
3219
        _cleanup_free_ char *_path = NULL;
77,737✔
3220
        const char *path;
77,737✔
3221
        int r;
77,737✔
3222

3223
        assert(c);
77,737✔
3224
        assert(i);
77,737✔
3225

3226
        todo = operation & ~i->done;
77,737✔
3227
        if (todo == 0) /* Everything already done? */
77,737✔
3228
                return 0;
3229

3230
        i->done |= operation;
41,555✔
3231

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

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

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

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

3257
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
41,555✔
3258
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
41,555✔
3259
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
41,555✔
3260

3261
        return r;
3262
}
3263

3264
static int process_item_array(
71,464✔
3265
                Context *c,
3266
                ItemArray *array,
3267
                OperationMask operation) {
3268

3269
        int r = 0;
71,464✔
3270

3271
        assert(c);
71,464✔
3272
        assert(array);
71,464✔
3273

3274
        /* Create any parent first. */
3275
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
71,464✔
3276
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
17,109✔
3277

3278
        /* Clean up all children first */
3279
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
71,464✔
3280
                ItemArray *cc;
6,453✔
3281

3282
                SET_FOREACH(cc, array->children)
21,833✔
3283
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
15,380✔
3284
        }
3285

3286
        FOREACH_ARRAY(item, array->items, array->n_items)
149,201✔
3287
                RET_GATHER(r, process_item(c, item, operation));
77,737✔
3288

3289
        return r;
71,464✔
3290
}
3291

3292
static void item_free_contents(Item *i) {
88,090✔
3293
        assert(i);
88,090✔
3294
        free(i->path);
88,090✔
3295
        free(i->argument);
88,090✔
3296
        free(i->binary_argument);
88,090✔
3297
        strv_free(i->xattrs);
88,090✔
3298

3299
#if HAVE_ACL
3300
        if (i->acl_access)
88,090✔
3301
                acl_free(i->acl_access);
1,460✔
3302

3303
        if (i->acl_access_exec)
88,090✔
3304
                acl_free(i->acl_access_exec);
369✔
3305

3306
        if (i->acl_default)
88,090✔
3307
                acl_free(i->acl_default);
2,190✔
3308
#endif
3309
}
88,090✔
3310

3311
static ItemArray* item_array_free(ItemArray *a) {
22,260✔
3312
        if (!a)
22,260✔
3313
                return NULL;
3314

3315
        FOREACH_ARRAY(item, a->items, a->n_items)
45,900✔
3316
                item_free_contents(item);
23,640✔
3317

3318
        set_free(a->children);
22,260✔
3319
        free(a->items);
22,260✔
3320
        return mfree(a);
22,260✔
3321
}
3322

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

3327
        if (takes_ownership(a->type) && !takes_ownership(b->type))
1,890✔
3328
                return -1;
3329
        if (!takes_ownership(a->type) && takes_ownership(b->type))
1,890✔
3330
                return 1;
3331

3332
        return CMP(a->type, b->type);
1,890✔
3333
}
3334

3335
static bool item_compatible(const Item *a, const Item *b) {
1,641✔
3336
        assert(a);
1,641✔
3337
        assert(b);
1,641✔
3338
        assert(streq(a->path, b->path));
1,641✔
3339

3340
        if (takes_ownership(a->type) && takes_ownership(b->type))
1,641✔
3341
                /* check if the items are the same */
3342
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
516✔
3343
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
497✔
3344

3345
                        a->uid_set == b->uid_set &&
497✔
3346
                        a->uid == b->uid &&
497✔
3347
                        a->uid_only_create == b->uid_only_create &&
497✔
3348

3349
                        a->gid_set == b->gid_set &&
497✔
3350
                        a->gid == b->gid &&
497✔
3351
                        a->gid_only_create == b->gid_only_create &&
497✔
3352

3353
                        a->mode_set == b->mode_set &&
497✔
3354
                        a->mode == b->mode &&
497✔
3355
                        a->mode_only_create == b->mode_only_create &&
497✔
3356

3357
                        a->age_set == b->age_set &&
497✔
3358
                        a->age == b->age &&
497✔
3359

3360
                        a->age_by_file == b->age_by_file &&
497✔
3361
                        a->age_by_dir == b->age_by_dir &&
497✔
3362

3363
                        a->mask_perms == b->mask_perms &&
497✔
3364

3365
                        a->keep_first_level == b->keep_first_level &&
1,529✔
3366

3367
                        a->major_minor == b->major_minor;
497✔
3368

3369
        return true;
3370
}
3371

3372
static bool should_include_path(const char *path) {
64,359✔
3373
        STRV_FOREACH(prefix, arg_exclude_prefixes)
83,080✔
3374
                if (path_startswith(path, *prefix)) {
21,121✔
3375
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2,400✔
3376
                                  path, *prefix);
3377
                        return false;
2,400✔
3378
                }
3379

3380
        STRV_FOREACH(prefix, arg_include_prefixes)
99,401✔
3381
                if (path_startswith(path, *prefix)) {
42,242✔
3382
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
4,800✔
3383
                        return true;
4,800✔
3384
                }
3385

3386
        /* no matches, so we should include this path only if we have no allow list at all */
3387
        if (strv_isempty(arg_include_prefixes))
57,159✔
3388
                return true;
3389

3390
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
37,442✔
3391
        return false;
3392
}
3393

3394
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
24,517✔
3395
        int r;
24,517✔
3396

3397
        assert(i);
24,517✔
3398

3399
        if (!i->argument)
24,517✔
3400
                return 0;
3401

3402
        switch (i->type) {
6,296✔
3403
        case COPY_FILES:
3,057✔
3404
        case CREATE_SYMLINK:
3405
        case CREATE_FILE:
3406
        case TRUNCATE_FILE:
3407
        case WRITE_FILE: {
3408
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
3,057✔
3409
                ssize_t l;
3,057✔
3410

3411
                l = cunescape(i->argument, 0, &unescaped);
3,057✔
3412
                if (l < 0)
3,057✔
3413
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3414

3415
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
3,057✔
3416
                if (r < 0)
3,057✔
3417
                        return r;
3418

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

3426
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3427
                        if (r < 0)
×
3428
                                return r;
×
3429

3430
                        free_and_replace(*xattr, resolved);
×
3431
                }
3432
                return 0;
3433

3434
        default:
3435
                return 0;
3436
        }
3437
}
3438

3439
static int patch_var_run(const char *fname, unsigned line, char **path) {
64,360✔
3440
        const char *k;
64,360✔
3441
        char *n;
64,360✔
3442

3443
        assert(path);
64,360✔
3444
        assert(*path);
64,360✔
3445

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

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

3462
        n = path_join("/run", k);
×
3463
        if (!n)
×
3464
                return log_oom();
×
3465

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

3474
        free_and_replace(*path, n);
×
3475

3476
        return 0;
×
3477
}
3478

3479
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
8,725✔
3480
        int r;
8,725✔
3481

3482
        assert(user);
8,725✔
3483
        assert(ret_uid);
8,725✔
3484

3485
        /* First: parse as numeric UID string */
3486
        r = parse_uid(user, ret_uid);
8,725✔
3487
        if (r >= 0)
8,725✔
3488
                return r;
3489

3490
        /* Second: pass to NSS if we are running "online" */
3491
        if (!arg_root)
8,711✔
3492
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
8,711✔
3493

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

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

3504
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
10,195✔
3505
        int r;
10,195✔
3506

3507
        assert(group);
10,195✔
3508
        assert(ret_gid);
10,195✔
3509

3510
        /* First: parse as numeric GID string */
3511
        r = parse_gid(group, ret_gid);
10,195✔
3512
        if (r >= 0)
10,195✔
3513
                return r;
3514

3515
        /* Second: pass to NSS if we are running "online" */
3516
        if (!arg_root)
10,181✔
3517
                return get_group_creds(&group, ret_gid, 0);
10,181✔
3518

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

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

3529
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
147✔
3530
        AgeBy ab_f = 0, ab_d = 0;
147✔
3531

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

3542
        assert(age_by_str);
147✔
3543
        assert(item);
147✔
3544

3545
        if (isempty(age_by_str))
147✔
3546
                return -EINVAL;
3547

3548
        for (const char *s = age_by_str; *s != 0; s++) {
313✔
3549
                size_t i;
172✔
3550

3551
                /* Ignore whitespace. */
3552
                if (strchr(WHITESPACE, *s))
172✔
3553
                        continue;
11✔
3554

3555
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
223✔
3556
                        /* Check lower-case for files, upper-case for directories. */
3557
                        if (*s == age_by_types[i].age_by_chr) {
220✔
3558
                                ab_f |= age_by_types[i].age_by_flag;
148✔
3559
                                break;
148✔
3560
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3561
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3562
                                break;
10✔
3563
                        }
3564
                }
3565

3566
                /* Invalid character. */
3567
                if (i >= ELEMENTSOF(age_by_types))
3568
                        return -EINVAL;
3569
        }
3570

3571
        /* No match. */
3572
        if (ab_f == 0 && ab_d == 0)
141✔
3573
                return -EINVAL;
3574

3575
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
140✔
3576
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
140✔
3577

3578
        return 0;
140✔
3579
}
3580

3581
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
1,383✔
3582
        assert(existing);
1,383✔
3583
        assert(i);
1,383✔
3584

3585
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
3,021✔
3586
                if (item_compatible(e, i))
1,641✔
3587
                        continue;
1,622✔
3588

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

3595
        return false;
3596
}
3597

3598
static int parse_line(
64,450✔
3599
                const char *fname,
3600
                unsigned line,
3601
                const char *buffer,
3602
                bool *invalid_config,
3603
                void *context) {
3604

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

3619
        assert(fname);
64,450✔
3620
        assert(line >= 1);
64,450✔
3621
        assert(buffer);
64,450✔
3622

3623
        const Specifier specifier_table[] = {
64,450✔
3624
                { 'h', specifier_user_home,       NULL },
3625

3626
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3627
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3628
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3629
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3630

3631
                COMMON_SYSTEM_SPECIFIERS,
3632
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
64,450✔
3633
                COMMON_TMP_SPECIFIERS,
3634
                {}
3635
        };
3636

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

3657
        if (!empty_or_dash(buffer)) {
64,450✔
3658
                i.argument = strdup(buffer);
15,446✔
3659
                if (!i.argument)
15,446✔
3660
                        return log_oom();
×
3661
        }
3662

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

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

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

3698
        i.type = action[0];
64,360✔
3699
        i.append_or_force = append_or_force;
64,360✔
3700
        i.allow_failure = allow_failure;
64,360✔
3701
        i.try_replace = try_replace;
64,360✔
3702
        i.purge = purge;
64,360✔
3703
        i.ignore_if_target_missing = ignore_if_target_missing;
64,360✔
3704

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

3715
        r = patch_var_run(fname, line, &i.path);
64,360✔
3716
        if (r < 0)
64,360✔
3717
                return r;
3718

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

3725
        path_simplify(i.path);
64,360✔
3726

3727
        switch (i.type) {
64,360✔
3728

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

3748
        case CREATE_FILE:
3749
        case TRUNCATE_FILE:
3750
                break;
3751

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

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

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

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

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

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

3797
                break;
3798

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

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

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

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

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

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

3870
        if (!should_include_path(i.path))
64,359✔
3871
                return 0;
3872

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

3886
        switch (i.type) {
24,517✔
3887
        case CREATE_SYMLINK:
1,503✔
3888
                if (!i.argument) {
1,503✔
3889
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3890
                        if (!i.argument)
2✔
3891
                                return log_oom();
×
3892
                }
3893

3894
                break;
3895

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

3906
                }
3907

3908
                if (!empty_or_root(arg_root)) {
4,330✔
3909
                        char *p;
1✔
3910

3911
                        p = path_join(arg_root, i.argument);
1✔
3912
                        if (!p)
1✔
3913
                                return log_oom();
×
3914
                        free_and_replace(i.argument, p);
1✔
3915
                }
3916

3917
                path_simplify(i.argument);
4,330✔
3918

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

3926
                break;
3927

3928
        default:
24,032✔
3929
                ;
24,032✔
3930
        }
3931

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

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

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

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

3961
                free_and_replace(i.binary_argument, data);
×
3962
                i.binary_argument_size = data_size;
×
3963
        }
3964

3965
        if (!empty_or_root(arg_root)) {
23,652✔
3966
                char *p;
14✔
3967

3968
                p = path_join(arg_root, i.path);
14✔
3969
                if (!p)
14✔
3970
                        return log_oom();
64,450✔
3971
                free_and_replace(i.path, p);
14✔
3972
        }
3973

3974
        if (!empty_or_dash(user)) {
23,652✔
3975
                const char *u;
8,725✔
3976

3977
                u = startswith(user, ":");
8,725✔
3978
                if (u)
8,725✔
3979
                        i.uid_only_create = true;
4✔
3980
                else
3981
                        u = user;
3982

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

3995
        if (!empty_or_dash(group)) {
23,652✔
3996
                const char *g;
10,195✔
3997

3998
                g = startswith(group, ":");
10,195✔
3999
                if (g)
10,195✔
4000
                        i.gid_only_create = true;
374✔
4001
                else
4002
                        g = group;
4003

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

4016
        if (!empty_or_dash(mode)) {
23,652✔
4017
                const char *mm;
4018
                unsigned m;
4019

4020
                for (mm = mode;; mm++)
499✔
4021
                        if (*mm == '~')
15,600✔
4022
                                i.mask_perms = true;
125✔
4023
                        else if (*mm == ':')
15,475✔
4024
                                i.mode_only_create = true;
374✔
4025
                        else
4026
                                break;
4027

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

4034
                i.mode = m;
15,101✔
4035
                i.mode_set = true;
15,101✔
4036
        } else
4037
                i.mode = IN_SET(i.type,
8,551✔
4038
                                CREATE_DIRECTORY,
4039
                                TRUNCATE_DIRECTORY,
4040
                                CREATE_SUBVOLUME,
4041
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4042
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4043

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

4052
        if (!empty_or_dash(age)) {
23,652✔
4053
                const char *a = age;
1,264✔
4054
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,264✔
4055

4056
                if (*a == '~') {
1,264✔
4057
                        i.keep_first_level = true;
×
4058
                        a++;
×
4059
                }
4060

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

4077
                        /* For parsing the "age" part, after the ":". */
4078
                        a = seconds;
140✔
4079
                }
4080

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

4087
                i.age_set = true;
1,255✔
4088
        }
4089

4090
        h = needs_glob(i.type) ? c->globs : c->items;
23,643✔
4091

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

4104
                r = ordered_hashmap_put(h, i.path, existing);
22,260✔
4105
                if (r < 0) {
22,260✔
4106
                        free(existing);
×
4107
                        return log_oom();
×
4108
                }
4109
        }
4110

4111
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
23,640✔
4112
                return log_oom();
×
4113

4114
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
23,640✔
4115

4116
        /* Sort item array, to enforce stable ordering of application */
4117
        typesafe_qsort(existing->items, existing->n_items, item_compare);
23,640✔
4118

4119
        return 0;
4120
}
4121

4122
static int cat_config(char **config_dirs, char **args) {
×
4123
        _cleanup_strv_free_ char **files = NULL;
×
4124
        int r;
×
4125

4126
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4127
        if (r < 0)
×
4128
                return r;
4129

4130
        pager_open(arg_pager_flags);
×
4131

4132
        return cat_files(NULL, files, arg_cat_flags);
×
4133
}
4134

4135
static int exclude_default_prefixes(void) {
×
4136
        int r;
×
4137

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

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

4152
        strv_uniq(arg_exclude_prefixes);
×
4153
        return 0;
×
4154
}
4155

4156
static int help(void) {
×
4157
        _cleanup_free_ char *link = NULL;
×
4158
        int r;
×
4159

4160
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4161
        if (r < 0)
×
4162
                return log_oom();
×
4163

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

4196
        return 0;
4197
}
4198

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

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

4244
        int c, r;
682✔
4245

4246
        assert(argc >= 0);
682✔
4247
        assert(argv);
682✔
4248

4249
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
2,892✔
4250

4251
                switch (c) {
2,210✔
4252

4253
                case 'h':
×
4254
                        return help();
×
4255

4256
                case ARG_VERSION:
×
4257
                        return version();
×
4258

4259
                case ARG_CAT_CONFIG:
×
4260
                        arg_cat_flags = CAT_CONFIG_ON;
×
4261
                        break;
×
4262

4263
                case ARG_TLDR:
×
4264
                        arg_cat_flags = CAT_TLDR;
×
4265
                        break;
×
4266

4267
                case ARG_USER:
179✔
4268
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
179✔
4269
                        break;
179✔
4270

4271
                case ARG_CREATE:
629✔
4272
                        arg_operation |= OPERATION_CREATE;
629✔
4273
                        break;
629✔
4274

4275
                case ARG_CLEAN:
40✔
4276
                        arg_operation |= OPERATION_CLEAN;
40✔
4277
                        break;
40✔
4278

4279
                case ARG_REMOVE:
307✔
4280
                        arg_operation |= OPERATION_REMOVE;
307✔
4281
                        break;
307✔
4282

4283
                case ARG_BOOT:
533✔
4284
                        arg_boot = true;
533✔
4285
                        break;
533✔
4286

4287
                case ARG_PURGE:
5✔
4288
                        arg_operation |= OPERATION_PURGE;
5✔
4289
                        break;
5✔
4290

4291
                case ARG_GRACEFUL:
120✔
4292
                        arg_graceful = true;
120✔
4293
                        break;
120✔
4294

4295
                case ARG_PREFIX:
240✔
4296
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
240✔
4297
                                return log_oom();
×
4298
                        break;
4299

4300
                case ARG_EXCLUDE_PREFIX:
120✔
4301
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
120✔
4302
                                return log_oom();
×
4303
                        break;
4304

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

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

4323
                case 'E':
4324
                        r = exclude_default_prefixes();
×
4325
                        if (r < 0)
×
4326
                                return r;
4327

4328
                        break;
4329

4330
                case ARG_IMAGE_POLICY:
×
4331
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4332
                        if (r < 0)
×
4333
                                return r;
4334
                        break;
4335

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

4344
                        arg_replace = optarg;
×
4345
                        break;
×
4346

4347
                case ARG_DRY_RUN:
29✔
4348
                        arg_dry_run = true;
29✔
4349
                        break;
29✔
4350

4351
                case ARG_NO_PAGER:
×
4352
                        arg_pager_flags |= PAGER_DISABLE;
×
4353
                        break;
×
4354

4355
                case '?':
4356
                        return -EINVAL;
4357

4358
                default:
×
4359
                        assert_not_reached();
×
4360
                }
4361

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

4366
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
682✔
4367
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4368
                                       "Refusing --purge without specification of a configuration file.");
4369

4370
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
682✔
4371
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4372
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4373

4374
        if (arg_replace && optind >= argc)
682✔
4375
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4376
                                       "When --replace= is given, some configuration items must be specified.");
4377

4378
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
682✔
4379
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4380
                                       "Combination of --user and --root= is not supported.");
4381

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

4386
        return 1;
4387
}
4388

4389
static int read_config_file(
15,515✔
4390
                Context *c,
4391
                char **config_dirs,
4392
                const char *fn,
4393
                bool ignore_enoent,
4394
                bool *invalid_config) {
4395

4396
        ItemArray *ia;
15,515✔
4397
        int r = 0;
15,515✔
4398

4399
        assert(c);
15,515✔
4400
        assert(fn);
15,515✔
4401

4402
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
15,515✔
4403
                           parse_line, c, ignore_enoent, invalid_config);
4404
        if (r <= 0)
15,515✔
4405
                return r;
15,515✔
4406

4407
        /* we have to determine age parameter for each entry of type X */
4408
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
118,276✔
4409
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
211,525✔
4410
                        ItemArray *ja;
108,407✔
4411
                        Item *candidate_item = NULL;
108,407✔
4412

4413
                        if (i->type != IGNORE_DIRECTORY_PATH)
108,407✔
4414
                                continue;
106,637✔
4415

4416
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
160,912✔
4417
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
323,406✔
4418
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
164,264✔
4419
                                                             TRUNCATE_DIRECTORY,
4420
                                                             CREATE_SUBVOLUME,
4421
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4422
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4423
                                                continue;
83,364✔
4424

4425
                                        if (path_equal(j->path, i->path)) {
80,900✔
4426
                                                candidate_item = j;
4427
                                                break;
4428
                                        }
4429

4430
                                        if (candidate_item
80,900✔
4431
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
7,669✔
4432
                                            : path_startswith(i->path, j->path) != NULL)
73,231✔
4433
                                                candidate_item = j;
4434
                                }
4435

4436
                        if (candidate_item && candidate_item->age_set) {
1,770✔
4437
                                i->age = candidate_item->age;
1,264✔
4438
                                i->age_set = true;
1,264✔
4439
                        }
4440
                }
4441

4442
        return r;
15,158✔
4443
}
4444

4445
static int parse_arguments(
138✔
4446
                Context *c,
4447
                char **config_dirs,
4448
                char **args,
4449
                bool *invalid_config) {
4450
        int r;
138✔
4451

4452
        assert(c);
138✔
4453

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

4460
        return 0;
4461
}
4462

4463
static int read_config_files(
544✔
4464
                Context *c,
4465
                char **config_dirs,
4466
                char **args,
4467
                bool *invalid_config) {
4468

4469
        _cleanup_strv_free_ char **files = NULL;
×
4470
        _cleanup_free_ char *p = NULL;
544✔
4471
        int r;
544✔
4472

4473
        assert(c);
544✔
4474

4475
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
544✔
4476
        if (r < 0)
544✔
4477
                return r;
4478

4479
        STRV_FOREACH(f, files)
15,561✔
4480
                if (p && path_equal(*f, p)) {
15,017✔
4481
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4482

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

4491
        return 0;
4492
}
4493

4494
static int read_credential_lines(Context *c, bool *invalid_config) {
682✔
4495
        _cleanup_free_ char *j = NULL;
682✔
4496
        const char *d;
682✔
4497
        int r;
682✔
4498

4499
        assert(c);
682✔
4500

4501
        r = get_credentials_dir(&d);
682✔
4502
        if (r == -ENXIO)
682✔
4503
                return 0;
4504
        if (r < 0)
360✔
4505
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4506

4507
        j = path_join(d, "tmpfiles.extra");
360✔
4508
        if (!j)
360✔
4509
                return log_oom();
×
4510

4511
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
360✔
4512
        return 0;
4513
}
4514

4515
static int link_parent(Context *c, ItemArray *a) {
22,260✔
4516
        const char *path;
22,260✔
4517
        char *prefix;
22,260✔
4518
        int r;
22,260✔
4519

4520
        assert(c);
22,260✔
4521
        assert(a);
22,260✔
4522

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

4528
        if (a->n_items <= 0)
22,260✔
4529
                return 0;
4530

4531
        path = a->items[0].path;
22,260✔
4532
        prefix = newa(char, strlen(path) + 1);
22,260✔
4533
        PATH_FOREACH_PREFIX(prefix, path) {
73,939✔
4534
                ItemArray *j;
38,904✔
4535

4536
                j = ordered_hashmap_get(c->items, prefix);
38,904✔
4537
                if (!j)
38,904✔
4538
                        j = ordered_hashmap_get(c->globs, prefix);
30,302✔
4539
                if (j) {
30,302✔
4540
                        r = set_ensure_put(&j->children, NULL, a);
9,485✔
4541
                        if (r < 0)
9,485✔
4542
                                return log_oom();
×
4543

4544
                        a->parent = j;
9,485✔
4545
                        return 1;
9,485✔
4546
                }
4547
        }
4548

4549
        return 0;
4550
}
4551

4552
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
22,260✔
4553
                                              ItemArray, item_array_free);
4554

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

4572
        r = parse_argv(argc, argv);
682✔
4573
        if (r <= 0)
682✔
4574
                return r;
4575

4576
        log_setup();
682✔
4577

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

4588
        /* Descending down file system trees might take a lot of fds */
4589
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
682✔
4590

4591
        switch (arg_runtime_scope) {
682✔
4592

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

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

4605
        default:
×
4606
                assert_not_reached();
×
4607
        }
4608

4609
        if (DEBUG_LOGGING) {
682✔
4610
                _cleanup_free_ char *t = NULL;
570✔
4611

4612
                STRV_FOREACH(i, config_dirs) {
3,208✔
4613
                        _cleanup_free_ char *j = NULL;
2,638✔
4614

4615
                        j = path_join(arg_root, *i);
2,638✔
4616
                        if (!j)
2,638✔
4617
                                return log_oom();
×
4618

4619
                        if (!strextend(&t, "\n\t", j))
2,638✔
4620
                                return log_oom();
×
4621
                }
4622

4623
                log_debug("Looking for configuration files in (higher priority first):%s", t);
570✔
4624
        }
4625

4626
        if (arg_cat_flags != CAT_CONFIG_OFF)
682✔
4627
                return cat_config(config_dirs, argv + optind);
×
4628

4629
        if (should_bypass("SYSTEMD_TMPFILES"))
682✔
4630
                return 0;
4631

4632
        umask(0022);
682✔
4633

4634
        r = mac_init();
682✔
4635
        if (r < 0)
682✔
4636
                return r;
4637

4638
#ifndef STANDALONE
4639
        if (arg_image) {
682✔
4640
                assert(!arg_root);
×
4641

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

4658
                arg_root = strdup(mounted_dir);
×
4659
                if (!arg_root)
×
4660
                        return log_oom();
×
4661
        }
4662
#else
4663
        assert(!arg_image);
4664
#endif
4665

4666
        c.items = ordered_hashmap_new(&item_array_hash_ops);
682✔
4667
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
682✔
4668
        if (!c.items || !c.globs)
682✔
4669
                return log_oom();
×
4670

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

4682
        r = read_credential_lines(&c, &invalid_config);
682✔
4683
        if (r < 0)
682✔
4684
                return r;
4685

4686
        /* Let's now link up all child/parent relationships */
4687
        ORDERED_HASHMAP_FOREACH(a, c.items) {
16,456✔
4688
                r = link_parent(&c, a);
15,774✔
4689
                if (r < 0)
15,774✔
4690
                        return r;
×
4691
        }
4692
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
7,168✔
4693
                r = link_parent(&c, a);
6,486✔
4694
                if (r < 0)
6,486✔
4695
                        return r;
×
4696
        }
4697

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

4703
                if (phase == PHASE_PURGE)
2,046✔
4704
                        op = arg_operation & OPERATION_PURGE;
682✔
4705
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,364✔
4706
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
682✔
4707
                else if (phase == PHASE_CREATE)
682✔
4708
                        op = arg_operation & OPERATION_CREATE;
682✔
4709
                else
4710
                        assert_not_reached();
×
4711

4712
                if (op == 0) /* Nothing requested in this phase */
2,046✔
4713
                        continue;
1,065✔
4714

4715
                /* The non-globbing ones usually create things, hence we apply them first */
4716
                ORDERED_HASHMAP_FOREACH(a, c.items)
29,404✔
4717
                        RET_GATHER(r, process_item_array(&c, a, op));
28,423✔
4718

4719
                /* The globbing ones usually alter things, hence we apply them second. */
4720
                ORDERED_HASHMAP_FOREACH(a, c.globs)
11,533✔
4721
                        RET_GATHER(r, process_item_array(&c, a, op));
10,552✔
4722
        }
4723

4724
        if (ERRNO_IS_NEG_RESOURCE(r))
1,364✔
4725
                return r;
4726
        if (invalid_config)
682✔
4727
                return EX_DATAERR;
4728
        if (r < 0)
672✔
4729
                return EX_CANTCREAT;
15✔
4730
        return 0;
4731
}
4732

4733
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
682✔
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