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

systemd / systemd / 14003033674

21 Mar 2025 09:36PM UTC coverage: 71.949% (-0.009%) from 71.958%
14003033674

push

github

DaanDeMeyer
mkosi: Hide patches on debian instead of removing them

296609 of 412251 relevant lines covered (71.95%)

718460.92 hits per line

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

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

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

16
#include "sd-path.h"
17

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

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

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

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

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

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

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

134
typedef struct Item {
135
        ItemType type;
136

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

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

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

167
        bool keep_first_level:1;
168

169
        bool append_or_force:1;
170

171
        bool allow_failure:1;
172

173
        bool try_replace:1;
174

175
        bool purge:1;
176

177
        bool ignore_if_target_missing:1;
178

179
        OperationMask done;
180
} Item;
181

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

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

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

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

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

220
#define MAX_DEPTH 256
221

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

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

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

242
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
15,878✔
243

244
static void context_done(Context *c) {
806✔
245
        assert(c);
806✔
246

247
        ordered_hashmap_free(c->items);
806✔
248
        ordered_hashmap_free(c->globs);
806✔
249

250
        set_free(c->unix_sockets);
806✔
251

252
        hashmap_free(c->uid_cache);
806✔
253
        hashmap_free(c->gid_cache);
806✔
254
}
806✔
255

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

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

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

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

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

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

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

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

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

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

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

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

317
        return 0;
318
}
319

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

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

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

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

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

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

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

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

361
        assert(ret);
140✔
362

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

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

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

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

380
        r = path_strv_make_absolute_cwd(config_dirs);
140✔
381
        if (r < 0)
140✔
382
                return r;
383

384
        *ret = TAKE_PTR(config_dirs);
140✔
385
        return 0;
140✔
386
}
387

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

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

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

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

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

454
        ORDERED_HASHMAP_FOREACH(j, h)
652✔
455
                FOREACH_ARRAY(item, j->items, j->n_items)
1,002✔
456
                        if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
543✔
457
                                return item;
20✔
458
        return NULL;
173✔
459
}
460

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

538
static DIR* xopendirat_nomod(int dirfd, const char *path) {
2,225✔
539
        DIR *dir;
2,225✔
540

541
        dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
2,225✔
542
        if (dir)
2,225✔
543
                return dir;
544

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

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

554
        return dir;
555
}
556

557
static DIR* opendir_nomod(const char *path) {
2,183✔
558
        return xopendirat_nomod(AT_FDCWD, path);
2,183✔
559
}
560

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

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

571
        assert(path);
763✔
572
        assert(ret);
763✔
573
        assert(ret_sx);
763✔
574
        assert(ret_mountpoint);
763✔
575

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

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

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

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

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

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

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

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

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

630
                return false;
32✔
631
        }
632

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

639
                return false;
63✔
640
        }
641

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

652
                return false;
7✔
653
        }
654

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

661
                return false;
5✔
662
        }
663

664
        return true;
665
}
666

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

683
        bool deleted = false;
94✔
684
        int r = 0;
94✔
685

686
        assert(c);
94✔
687
        assert(i);
94✔
688
        assert(d);
94✔
689

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

694
                if (dot_or_dot_dot(de->d_name))
386✔
695
                        continue;
188✔
696

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

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

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

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

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

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

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

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

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

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

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

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

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

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

795
                                        continue;
×
796
                                }
797

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

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

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

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

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

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

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

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

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

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

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

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

879
                        if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
131✔
880
                                           cutoff_nsec, sub_path, age_by_file, false))
881
                                continue;
77✔
882

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

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

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

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

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

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

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

922
        return r;
94✔
923
}
924

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

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

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

936
        _cleanup_free_ char *value = NULL;
×
937

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

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

950
static bool hardlink_vulnerable(const struct stat *st) {
22,346✔
951
        assert(st);
22,346✔
952

953
        return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
22,346✔
954
}
955

956
static mode_t process_mask_perms(mode_t mode, mode_t current) {
470✔
957

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

967
        return mode;
470✔
968
}
969

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

978
        bool do_chown, do_chmod;
28,088✔
979
        struct stat stbuf;
28,088✔
980
        mode_t new_mode;
28,088✔
981
        uid_t new_uid;
28,088✔
982
        gid_t new_gid;
28,088✔
983
        int r;
28,088✔
984

985
        assert(c);
28,088✔
986
        assert(i);
28,088✔
987
        assert(fd >= 0);
28,088✔
988
        assert(path);
28,088✔
989

990
        if (!i->mode_set && !i->uid_set && !i->gid_set)
28,088✔
991
                goto shortcut;
6,819✔
992

993
        if (!st) {
21,269✔
994
                if (fstat(fd, &stbuf) < 0)
5,213✔
995
                        return log_error_errno(errno, "fstat(%s) failed: %m", path);
×
996
                st = &stbuf;
997
        }
998

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

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

1009
        /* Calculate the mode to apply */
1010
        new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
21,267✔
1011
                (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
42,162✔
1012
                (st->st_mode & 07777);
376✔
1013

1014
        do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
21,269✔
1015

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

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

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

1041
        if (do_chown) {
21,269✔
1042
                log_action("Would change", "Changing",
5,793✔
1043
                           "%s \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
1044

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

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

1068
shortcut:
21,267✔
1069
        return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
28,086✔
1070
}
1071

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

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

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

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

1101
        return fd;
23,608✔
1102
}
1103

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

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

1111
        assert(path);
5,443✔
1112

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

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

1124
        return fd;
5,443✔
1125
}
1126

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

1133
        _cleanup_close_ int fd = -EBADF;
4,787✔
1134

1135
        assert(c);
4,787✔
1136
        assert(i);
4,787✔
1137
        assert(path);
4,787✔
1138

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

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

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

1152
        assert(i);
×
1153

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

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

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

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

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

1178
                name = value = NULL;
×
1179
        }
1180

1181
        return 0;
×
1182
}
1183

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

1192
        int r;
×
1193

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

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

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

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

1219
        _cleanup_close_ int fd = -EBADF;
×
1220

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

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

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

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

1238
        assert(item);
3,700✔
1239

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

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

1252
        return 0;
3,700✔
1253
}
1254

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

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

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

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

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

1281
                has_exec = false;
315✔
1282

1283
                for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
315✔
1284
                     r > 0;
978✔
1285
                     r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
663✔
1286

1287
                        acl_tag_t tag;
814✔
1288

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

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

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

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

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

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

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

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

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

1340
        for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
471✔
1341
             r > 0;
1,409✔
1342
             r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
938✔
1343

1344
                acl_entry_t parsed_entry;
938✔
1345

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

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

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

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

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

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

1372
        return 0;
471✔
1373
}
1374

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

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

1387
        assert(c);
1,458✔
1388

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1552
        assert(item);
1,584✔
1553

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

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

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

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

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

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

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

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

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

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

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

1600
        return 0;
1,584✔
1601
}
1602

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

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

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

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

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

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

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

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

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

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

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

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

1666
        return 0;
1667
}
1668

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

1675
        _cleanup_close_ int fd = -EBADF;
46✔
1676

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

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

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

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

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

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

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

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

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

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

1712
        return 0;
1713
}
1714

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1833
                creation = CREATION_NORMAL;
1834
        }
1835

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1944
        log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i->argument, i->path);
15,633✔
1945
        if (arg_dry_run)
5,258✔
1946
                return 0;
1947

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

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

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

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

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

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

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

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

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

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

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

2001
        assert(path);
11,055✔
2002

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

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

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

2037
        if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r)) {
×
2038
                log_action("Would create", "Creating", "%s directory \"%s\"", path);
32,869✔
2039
                if (!arg_dry_run)
11,053✔
2040
                        WITH_UMASK(0000)
22,106✔
2041
                                r = mkdirat_label(pfd, bn, mode);
11,053✔
2042
        }
2043

2044
        if (arg_dry_run)
11,053✔
2045
                return 0;
2046

2047
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
11,053✔
2048

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

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

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

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

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

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

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

2078
        return fd;
2079
}
2080

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

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

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

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

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

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

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

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

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

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

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

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

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

2154
        return r;
2155
}
2156

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2411
        assert(c);
2,095✔
2412
        assert(i);
2,095✔
2413

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

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

2432
        if (arg_dry_run) {
2,094✔
2433
                log_info("Would create symlink %s -> %s", i->path, i->argument);
2✔
2434
                return 0;
2✔
2435
        }
2436

2437
        pfd = path_open_parent_safe(i->path, i->allow_failure);
2,092✔
2438
        if (pfd < 0)
2,092✔
2439
                return pfd;
2440

2441
        mac_selinux_create_file_prepare(i->path, S_IFLNK);
2,092✔
2442
        r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
2,092✔
2443
        mac_selinux_create_file_clear();
2,092✔
2444

2445
        creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2,092✔
2446

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

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

2455
        if (fstat(fd, &st) < 0)
2,092✔
2456
                return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
×
2457

2458
        if (S_ISLNK(st.st_mode)) {
2,092✔
2459
                _cleanup_free_ char *x = NULL;
×
2460

2461
                r = readlinkat_malloc(fd, "", &x);
2,032✔
2462
                if (r < 0)
2,032✔
2463
                        return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
×
2464

2465
                good = streq(x, i->argument);
2,032✔
2466
        } else
2467
                good = false;
2468

2469
        if (!good) {
2,032✔
2470
                if (!i->append_or_force) {
779✔
2471
                        log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
775✔
2472
                        return 0;
775✔
2473
                }
2474

2475
                fd = safe_close(fd);
4✔
2476

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

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

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

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

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

2503
                creation = CREATION_FORCE;
2504
        }
2505

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

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

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

2521
        struct stat st;
942✔
2522
        int r;
942✔
2523

2524
        assert(c);
942✔
2525
        assert(i);
942✔
2526
        assert(fd >= 0);
942✔
2527
        assert(path);
942✔
2528
        assert(action);
942✔
2529

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

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

2538
        if (S_ISDIR(st.st_mode)) {
942✔
2539
                _cleanup_closedir_ DIR *d = NULL;
314✔
2540

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

2549
                FOREACH_DIRENT_ALL(de, d, RET_GATHER(r, -errno); goto finish) {
1,570✔
2550
                        _cleanup_close_ int de_fd = -EBADF;
1,256✔
2551
                        _cleanup_free_ char *de_path = NULL;
1,256✔
2552

2553
                        if (dot_or_dot_dot(de->d_name))
1,256✔
2554
                                continue;
628✔
2555

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

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

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

2574
finish:
628✔
2575
        safe_close(fd);
942✔
2576
        return r;
942✔
2577
}
2578

2579
static int glob_item(Context *c, Item *i, action_t action) {
8,896✔
2580
        _cleanup_globfree_ glob_t g = {
8,896✔
2581
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2582
        };
2583
        int r;
8,896✔
2584

2585
        assert(c);
8,896✔
2586
        assert(i);
8,896✔
2587
        assert(action);
8,896✔
2588

2589
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
8,896✔
2590
        if (r == -ENOENT)
8,896✔
2591
                return 0;
2592
        if (r < 0)
4,789✔
2593
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2594

2595
        r = 0;
4,789✔
2596
        STRV_FOREACH(fn, g.gl_pathv)
10,301✔
2597
                /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2598
                RET_GATHER(r, action(c, i, *fn, CREATION_EXISTING));
5,512✔
2599

2600
        return r;
2601
}
2602

2603
static int glob_item_recursively(
360✔
2604
                Context *c,
2605
                Item *i,
2606
                fdaction_t action) {
2607

2608
        _cleanup_globfree_ glob_t g = {
360✔
2609
                .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2610
        };
2611
        int r;
360✔
2612

2613
        assert(c);
360✔
2614
        assert(i);
360✔
2615
        assert(action);
360✔
2616

2617
        r = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
360✔
2618
        if (r == -ENOENT)
360✔
2619
                return 0;
2620
        if (r < 0)
314✔
2621
                return log_error_errno(r, "Failed to glob '%s': %m", i->path);
×
2622

2623
        r = 0;
314✔
2624
        STRV_FOREACH(fn, g.gl_pathv) {
628✔
2625
                _cleanup_close_ int fd = -EBADF;
314✔
2626

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

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

2637
                RET_GATHER(r, item_do(c, i, TAKE_FD(fd), *fn, CREATION_EXISTING, action));
314✔
2638
        }
2639

2640
        return r;
2641
}
2642

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

2654
        assert(name);
×
2655
        assert((mode & ~S_IFMT) == 0);
×
2656
        assert(!follow_links || parent_st);
×
2657
        assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
×
2658

2659
        if (mode == 0)
×
2660
                return 0;
2661

2662
        if (!filename_is_valid(name))
×
2663
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
×
2664

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

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

2679
        if ((st.st_mode & S_IFMT) == mode)
×
2680
                return 0;
2681

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

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

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

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

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

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

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

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

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

2734
        assert(path);
×
2735
        assert((child_mode & ~S_IFMT) == 0);
×
2736

2737
        path_len = strlen(path);
×
2738

2739
        if (!is_path(path))
×
2740
                /* rm_if_wrong_type_safe already logs errors. */
2741
                return rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW);
×
2742

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

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

2752
        if (fstat(parent_fd, &parent_st) < 0)
×
2753
                return log_error_errno(errno, "Failed to stat root: %m");
×
2754

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

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

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

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

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

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

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

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

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

2807
                close_and_replace(parent_fd, next_fd);
×
2808
        }
2809
}
2810

2811
static int mkdir_parents_item(Item *i, mode_t child_mode) {
23,620✔
2812
        int r;
23,620✔
2813

2814
        if (i->try_replace) {
23,620✔
2815
                r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
×
2816
                if (r < 0 && r != -ENOENT)
×
2817
                        return r;
×
2818
        } else
2819
                WITH_UMASK(0000)
47,240✔
2820
                        if (!arg_dry_run)
23,620✔
2821
                                (void) mkdir_parents_label(i->path, 0755);
23,620✔
2822

2823
        return 0;
2824
}
2825

2826
static int create_item(Context *c, Item *i) {
33,972✔
2827
        int r;
33,972✔
2828

2829
        assert(c);
33,972✔
2830
        assert(i);
33,972✔
2831

2832
        log_debug("Running create action for entry %c %s", (char) i->type, i->path);
33,972✔
2833

2834
        switch (i->type) {
33,972✔
2835

2836
        case IGNORE_PATH:
2837
        case IGNORE_DIRECTORY_PATH:
2838
        case REMOVE_PATH:
2839
        case RECURSIVE_REMOVE_PATH:
2840
                return 0;
2841

2842
        case TRUNCATE_FILE:
1,353✔
2843
        case CREATE_FILE:
2844
                r = mkdir_parents_item(i, S_IFREG);
1,353✔
2845
                if (r < 0)
1,353✔
2846
                        return r;
2847

2848
                if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
1,353✔
2849
                        r = truncate_file(c, i, i->path);
359✔
2850
                else
2851
                        r = create_file(c, i, i->path);
994✔
2852
                if (r < 0)
1,353✔
2853
                        return r;
15✔
2854
                break;
2855

2856
        case COPY_FILES:
5,258✔
2857
                r = mkdir_parents_item(i, 0);
5,258✔
2858
                if (r < 0)
5,258✔
2859
                        return r;
2860

2861
                r = copy_files(c, i);
5,258✔
2862
                if (r < 0)
5,258✔
2863
                        return r;
×
2864
                break;
2865

2866
        case WRITE_FILE:
20✔
2867
                r = glob_item(c, i, write_one_file);
20✔
2868
                if (r < 0)
20✔
2869
                        return r;
×
2870

2871
                break;
2872

2873
        case CREATE_DIRECTORY:
9,813✔
2874
        case TRUNCATE_DIRECTORY:
2875
                r = mkdir_parents_item(i, S_IFDIR);
9,813✔
2876
                if (r < 0)
9,813✔
2877
                        return r;
2878

2879
                r = create_directory(c, i, i->path);
9,813✔
2880
                if (r < 0)
9,813✔
2881
                        return r;
2✔
2882
                break;
2883

2884
        case CREATE_SUBVOLUME:
1,253✔
2885
        case CREATE_SUBVOLUME_INHERIT_QUOTA:
2886
        case CREATE_SUBVOLUME_NEW_QUOTA:
2887
                r = mkdir_parents_item(i, S_IFDIR);
1,253✔
2888
                if (r < 0)
1,253✔
2889
                        return r;
2890

2891
                r = create_subvolume(c, i, i->path);
1,253✔
2892
                if (r < 0)
1,253✔
2893
                        return r;
×
2894
                break;
2895

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

2902
        case CREATE_FIFO:
4✔
2903
                r = mkdir_parents_item(i, S_IFIFO);
4✔
2904
                if (r < 0)
4✔
2905
                        return r;
2906

2907
                r = create_fifo(c, i);
4✔
2908
                if (r < 0)
4✔
2909
                        return r;
×
2910
                break;
2911

2912
        case CREATE_SYMLINK:
2,095✔
2913
                r = mkdir_parents_item(i, S_IFLNK);
2,095✔
2914
                if (r < 0)
2,095✔
2915
                        return r;
2916

2917
                r = create_symlink(c, i);
2,095✔
2918
                if (r < 0)
2,095✔
2919
                        return r;
×
2920

2921
                break;
2922

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

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

2933
                r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
7,686✔
2934
                if (r < 0)
3,844✔
2935
                        return r;
2936

2937
                r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
7,686✔
2938
                if (r < 0)
3,844✔
2939
                        return r;
×
2940

2941
                break;
2942

2943
        case ADJUST_MODE:
6,166✔
2944
        case RELABEL_PATH:
2945
                r = glob_item(c, i, path_set_perms);
6,166✔
2946
                if (r < 0)
6,166✔
2947
                        return r;
×
2948
                break;
2949

2950
        case RECURSIVE_RELABEL_PATH:
181✔
2951
                r = glob_item_recursively(c, i, fd_set_perms);
181✔
2952
                if (r < 0)
181✔
2953
                        return r;
×
2954
                break;
2955

2956
        case SET_XATTR:
×
2957
                r = glob_item(c, i, path_set_xattrs);
×
2958
                if (r < 0)
×
2959
                        return r;
×
2960
                break;
2961

2962
        case RECURSIVE_SET_XATTR:
×
2963
                r = glob_item_recursively(c, i, fd_set_xattrs);
×
2964
                if (r < 0)
×
2965
                        return r;
×
2966
                break;
2967

2968
        case SET_ACL:
1,078✔
2969
                r = glob_item(c, i, path_set_acls);
1,078✔
2970
                if (r < 0)
1,078✔
2971
                        return r;
×
2972
                break;
2973

2974
        case RECURSIVE_SET_ACL:
179✔
2975
                r = glob_item_recursively(c, i, fd_set_acls);
179✔
2976
                if (r < 0)
179✔
2977
                        return r;
×
2978
                break;
2979

2980
        case SET_ATTRIBUTE:
537✔
2981
                r = glob_item(c, i, path_set_attribute);
537✔
2982
                if (r < 0)
537✔
2983
                        return r;
×
2984
                break;
2985

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

2993
        return 0;
2994
}
2995

2996
static int remove_recursive(
717✔
2997
                Context *c,
2998
                Item *i,
2999
                const char *instance,
3000
                bool remove_instance) {
3001

3002
        _cleanup_closedir_ DIR *d = NULL;
717✔
3003
        struct statx sx;
717✔
3004
        bool mountpoint;
717✔
3005
        int r;
717✔
3006

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

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

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

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

3053
static int purge_item(Context *c, Item *i) {
15✔
3054
        assert(i);
15✔
3055

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

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

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

3064
        if (needs_glob(i->type))
10✔
3065
                return glob_item(c, i, purge_item_instance);
×
3066

3067
        return purge_item_instance(c, i, i->path, CREATION_EXISTING);
10✔
3068
}
3069

3070
static int remove_item_instance(
16✔
3071
                Context *c,
3072
                Item *i,
3073
                const char *instance,
3074
                CreationMode creation) {
3075

3076
        assert(c);
16✔
3077
        assert(i);
16✔
3078

3079
        switch (i->type) {
16✔
3080

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

3088
                return 0;
3089

3090
        case RECURSIVE_REMOVE_PATH:
8✔
3091
                return remove_recursive(c, i, instance, /* remove_instance= */ true);
8✔
3092

3093
        default:
×
3094
                assert_not_reached();
×
3095
        }
3096
}
3097

3098
static int remove_item(Context *c, Item *i) {
24,978✔
3099
        assert(c);
24,978✔
3100
        assert(i);
24,978✔
3101

3102
        log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
24,978✔
3103

3104
        switch (i->type) {
24,978✔
3105

3106
        case TRUNCATE_DIRECTORY:
699✔
3107
                return remove_recursive(c, i, i->path, /* remove_instance= */ false);
699✔
3108

3109
        case REMOVE_PATH:
1,062✔
3110
        case RECURSIVE_REMOVE_PATH:
3111
                return glob_item(c, i, remove_item_instance);
1,062✔
3112

3113
        default:
3114
                return 0;
3115
        }
3116
}
3117

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

3123
        ret = new(char, ELEMENTSOF(ab_map) + 1);
60✔
3124
        if (!ret)
60✔
3125
                return NULL;
3126

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

3131
        ret[j] = 0;
60✔
3132
        return ret;
60✔
3133
}
3134

3135
static int clean_item_instance(
139✔
3136
                Context *c,
3137
                Item *i,
3138
                const char* instance,
3139
                CreationMode creation) {
3140

3141
        assert(i);
139✔
3142

3143
        if (!i->age_set)
139✔
3144
                return 0;
139✔
3145

3146
        usec_t n = now(CLOCK_REALTIME);
46✔
3147
        if (n < i->age)
46✔
3148
                return 0;
3149

3150
        usec_t cutoff = n - i->age;
46✔
3151

3152
        _cleanup_closedir_ DIR *d = NULL;
139✔
3153
        struct statx sx;
46✔
3154
        bool mountpoint;
46✔
3155
        int r;
46✔
3156

3157
        r = opendir_and_stat(instance, &d, &sx, &mountpoint);
46✔
3158
        if (r <= 0)
46✔
3159
                return r;
3160

3161
        if (DEBUG_LOGGING) {
42✔
3162
                _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
30✔
3163

3164
                ab_f = age_by_to_string(i->age_by_file, false);
30✔
3165
                if (!ab_f)
30✔
3166
                        return log_oom();
×
3167

3168
                ab_d = age_by_to_string(i->age_by_dir, true);
30✔
3169
                if (!ab_d)
30✔
3170
                        return log_oom();
×
3171

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

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

3189
static int clean_item(Context *c, Item *i) {
195✔
3190
        assert(c);
195✔
3191
        assert(i);
195✔
3192

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

3195
        switch (i->type) {
195✔
3196

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

3206
        case EMPTY_DIRECTORY:
29✔
3207
        case IGNORE_PATH:
3208
        case IGNORE_DIRECTORY_PATH:
3209
                return glob_item(c, i, clean_item_instance);
29✔
3210

3211
        default:
3212
                return 0;
3213
        }
3214
}
3215

3216
static int process_item(
109,882✔
3217
                Context *c,
3218
                Item *i,
3219
                OperationMask operation) {
3220

3221
        OperationMask todo;
109,882✔
3222
        _cleanup_free_ char *_path = NULL;
109,882✔
3223
        const char *path;
109,882✔
3224
        int r;
109,882✔
3225

3226
        assert(c);
109,882✔
3227
        assert(i);
109,882✔
3228

3229
        todo = operation & ~i->done;
109,882✔
3230
        if (todo == 0) /* Everything already done? */
109,882✔
3231
                return 0;
3232

3233
        i->done |= operation;
59,160✔
3234

3235
        path = i->path;
59,160✔
3236
        if (string_is_glob(path)) {
59,160✔
3237
                /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3238
                 * for the non-glob part. */
3239

3240
                r = glob_non_glob_prefix(path, &_path);
5,049✔
3241
                if (r < 0 && r != -ENOENT)
5,049✔
3242
                        return log_debug_errno(r, "Failed to deglob path: %m");
×
3243
                if (r >= 0)
5,049✔
3244
                        path = _path;
5,049✔
3245
        }
3246

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

3255
        r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
59,160✔
3256
        /* Failure can only be tolerated for create */
3257
        if (i->allow_failure)
59,160✔
3258
                r = 0;
1,416✔
3259

3260
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
59,160✔
3261
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
59,160✔
3262
        RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
59,160✔
3263

3264
        return r;
3265
}
3266

3267
static int process_item_array(
100,559✔
3268
                Context *c,
3269
                ItemArray *array,
3270
                OperationMask operation) {
3271

3272
        int r = 0;
100,559✔
3273

3274
        assert(c);
100,559✔
3275
        assert(array);
100,559✔
3276

3277
        /* Create any parent first. */
3278
        if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
100,559✔
3279
                r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
23,881✔
3280

3281
        /* Clean up all children first */
3282
        if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
100,559✔
3283
                ItemArray *cc;
8,943✔
3284

3285
                SET_FOREACH(cc, array->children)
30,238✔
3286
                        RET_GATHER(r, process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)));
21,295✔
3287
        }
3288

3289
        FOREACH_ARRAY(item, array->items, array->n_items)
210,441✔
3290
                RET_GATHER(r, process_item(c, item, operation));
109,882✔
3291

3292
        return r;
100,559✔
3293
}
3294

3295
static void item_free_contents(Item *i) {
126,150✔
3296
        assert(i);
126,150✔
3297
        free(i->path);
126,150✔
3298
        free(i->argument);
126,150✔
3299
        free(i->binary_argument);
126,150✔
3300
        strv_free(i->xattrs);
126,150✔
3301

3302
#if HAVE_ACL
3303
        if (i->acl_access)
126,150✔
3304
                acl_free(i->acl_access);
2,112✔
3305

3306
        if (i->acl_access_exec)
126,150✔
3307
                acl_free(i->acl_access_exec);
532✔
3308

3309
        if (i->acl_default)
126,150✔
3310
                acl_free(i->acl_default);
3,168✔
3311
#endif
3312
}
126,150✔
3313

3314
static ItemArray* item_array_free(ItemArray *a) {
32,164✔
3315
        if (!a)
32,164✔
3316
                return NULL;
3317

3318
        FOREACH_ARRAY(item, a->items, a->n_items)
66,365✔
3319
                item_free_contents(item);
34,201✔
3320

3321
        set_free(a->children);
32,164✔
3322
        free(a->items);
32,164✔
3323
        return mfree(a);
32,164✔
3324
}
3325

3326
static int item_compare(const Item *a, const Item *b) {
2,767✔
3327
        /* Make sure that the ownership taking item is put first, so
3328
         * that we first create the node, and then can adjust it */
3329

3330
        if (takes_ownership(a->type) && !takes_ownership(b->type))
2,767✔
3331
                return -1;
3332
        if (!takes_ownership(a->type) && takes_ownership(b->type))
2,767✔
3333
                return 1;
3334

3335
        return CMP(a->type, b->type);
2,767✔
3336
}
3337

3338
static bool item_compatible(const Item *a, const Item *b) {
2,408✔
3339
        assert(a);
2,408✔
3340
        assert(b);
2,408✔
3341
        assert(streq(a->path, b->path));
2,408✔
3342

3343
        if (takes_ownership(a->type) && takes_ownership(b->type))
2,408✔
3344
                /* check if the items are the same */
3345
                return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
788✔
3346
                                 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
769✔
3347

3348
                        a->uid_set == b->uid_set &&
769✔
3349
                        a->uid == b->uid &&
769✔
3350
                        a->uid_only_create == b->uid_only_create &&
769✔
3351

3352
                        a->gid_set == b->gid_set &&
769✔
3353
                        a->gid == b->gid &&
769✔
3354
                        a->gid_only_create == b->gid_only_create &&
769✔
3355

3356
                        a->mode_set == b->mode_set &&
769✔
3357
                        a->mode == b->mode &&
769✔
3358
                        a->mode_only_create == b->mode_only_create &&
769✔
3359

3360
                        a->age_set == b->age_set &&
769✔
3361
                        a->age == b->age &&
769✔
3362

3363
                        a->age_by_file == b->age_by_file &&
769✔
3364
                        a->age_by_dir == b->age_by_dir &&
769✔
3365

3366
                        a->mask_perms == b->mask_perms &&
769✔
3367

3368
                        a->keep_first_level == b->keep_first_level &&
2,345✔
3369

3370
                        a->major_minor == b->major_minor;
769✔
3371

3372
        return true;
3373
}
3374

3375
static bool should_include_path(const char *path) {
91,824✔
3376
        STRV_FOREACH(prefix, arg_exclude_prefixes)
117,963✔
3377
                if (path_startswith(path, *prefix)) {
30,225✔
3378
                        log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
4,086✔
3379
                                  path, *prefix);
3380
                        return false;
4,086✔
3381
                }
3382

3383
        STRV_FOREACH(prefix, arg_include_prefixes)
140,016✔
3384
                if (path_startswith(path, *prefix)) {
60,450✔
3385
                        log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
8,172✔
3386
                        return true;
8,172✔
3387
                }
3388

3389
        /* no matches, so we should include this path only if we have no allow list at all */
3390
        if (strv_isempty(arg_include_prefixes))
79,566✔
3391
                return true;
3392

3393
        log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
52,278✔
3394
        return false;
3395
}
3396

3397
static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
35,460✔
3398
        int r;
35,460✔
3399

3400
        assert(i);
35,460✔
3401

3402
        if (!i->argument)
35,460✔
3403
                return 0;
3404

3405
        switch (i->type) {
9,971✔
3406
        case COPY_FILES:
4,322✔
3407
        case CREATE_SYMLINK:
3408
        case CREATE_FILE:
3409
        case TRUNCATE_FILE:
3410
        case WRITE_FILE: {
3411
                _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
4,322✔
3412
                ssize_t l;
4,322✔
3413

3414
                l = cunescape(i->argument, 0, &unescaped);
4,322✔
3415
                if (l < 0)
4,322✔
3416
                        return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
×
3417

3418
                r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
4,322✔
3419
                if (r < 0)
4,322✔
3420
                        return r;
3421

3422
                return free_and_replace(i->argument, resolved);
4,322✔
3423
        }
3424
        case SET_XATTR:
×
3425
        case RECURSIVE_SET_XATTR:
3426
                STRV_FOREACH(xattr, i->xattrs) {
×
3427
                        _cleanup_free_ char *resolved = NULL;
×
3428

3429
                        r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
×
3430
                        if (r < 0)
×
3431
                                return r;
×
3432

3433
                        free_and_replace(*xattr, resolved);
×
3434
                }
3435
                return 0;
3436

3437
        default:
3438
                return 0;
3439
        }
3440
}
3441

3442
static int patch_var_run(const char *fname, unsigned line, char **path) {
91,825✔
3443
        const char *k;
91,825✔
3444
        char *n;
91,825✔
3445

3446
        assert(path);
91,825✔
3447
        assert(*path);
91,825✔
3448

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

3460
        k = path_startswith(*path, "/var/run/");
91,825✔
3461
        if (isempty(k)) /* Don't complain about paths other than under /var/run,
91,825✔
3462
                         * and not about /var/run itself either. */
3463
                return 0;
91,825✔
3464

3465
        n = path_join("/run", k);
×
3466
        if (!n)
×
3467
                return log_oom();
×
3468

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

3477
        free_and_replace(*path, n);
×
3478

3479
        return 0;
×
3480
}
3481

3482
static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
12,043✔
3483
        int r;
12,043✔
3484

3485
        assert(user);
12,043✔
3486
        assert(ret_uid);
12,043✔
3487

3488
        /* First: parse as numeric UID string */
3489
        r = parse_uid(user, ret_uid);
12,043✔
3490
        if (r >= 0)
12,043✔
3491
                return r;
3492

3493
        /* Second: pass to NSS if we are running "online" */
3494
        if (!arg_root)
12,029✔
3495
                return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
12,029✔
3496

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

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

3507
static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
14,167✔
3508
        int r;
14,167✔
3509

3510
        assert(group);
14,167✔
3511
        assert(ret_gid);
14,167✔
3512

3513
        /* First: parse as numeric GID string */
3514
        r = parse_gid(group, ret_gid);
14,167✔
3515
        if (r >= 0)
14,167✔
3516
                return r;
3517

3518
        /* Second: pass to NSS if we are running "online" */
3519
        if (!arg_root)
14,153✔
3520
                return get_group_creds(&group, ret_gid, 0);
14,153✔
3521

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

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

3532
static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
149✔
3533
        AgeBy ab_f = 0, ab_d = 0;
149✔
3534

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

3545
        assert(age_by_str);
149✔
3546
        assert(item);
149✔
3547

3548
        if (isempty(age_by_str))
149✔
3549
                return -EINVAL;
3550

3551
        for (const char *s = age_by_str; *s != 0; s++) {
317✔
3552
                size_t i;
174✔
3553

3554
                /* Ignore whitespace. */
3555
                if (strchr(WHITESPACE, *s))
174✔
3556
                        continue;
11✔
3557

3558
                for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
225✔
3559
                        /* Check lower-case for files, upper-case for directories. */
3560
                        if (*s == age_by_types[i].age_by_chr) {
222✔
3561
                                ab_f |= age_by_types[i].age_by_flag;
150✔
3562
                                break;
150✔
3563
                        } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
72✔
3564
                                ab_d |= age_by_types[i].age_by_flag;
10✔
3565
                                break;
10✔
3566
                        }
3567
                }
3568

3569
                /* Invalid character. */
3570
                if (i >= ELEMENTSOF(age_by_types))
3571
                        return -EINVAL;
3572
        }
3573

3574
        /* No match. */
3575
        if (ab_f == 0 && ab_d == 0)
143✔
3576
                return -EINVAL;
3577

3578
        item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
142✔
3579
        item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
142✔
3580

3581
        return 0;
142✔
3582
}
3583

3584
static bool is_duplicated_item(ItemArray *existing, const Item *i) {
2,040✔
3585
        assert(existing);
2,040✔
3586
        assert(i);
2,040✔
3587

3588
        FOREACH_ARRAY(e, existing->items, existing->n_items) {
4,445✔
3589
                if (item_compatible(e, i))
2,408✔
3590
                        continue;
2,389✔
3591

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

3598
        return false;
3599
}
3600

3601
static int parse_line(
91,949✔
3602
                const char *fname,
3603
                unsigned line,
3604
                const char *buffer,
3605
                bool *invalid_config,
3606
                void *context) {
3607

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

3622
        assert(fname);
91,949✔
3623
        assert(line >= 1);
91,949✔
3624
        assert(buffer);
91,949✔
3625

3626
        const Specifier specifier_table[] = {
91,949✔
3627
                { 'h', specifier_user_home,       NULL },
3628

3629
                { 'C', specifier_directory,       UINT_TO_PTR(DIRECTORY_CACHE)   },
3630
                { 'L', specifier_directory,       UINT_TO_PTR(DIRECTORY_LOGS)    },
3631
                { 'S', specifier_directory,       UINT_TO_PTR(DIRECTORY_STATE)   },
3632
                { 't', specifier_directory,       UINT_TO_PTR(DIRECTORY_RUNTIME) },
3633

3634
                COMMON_SYSTEM_SPECIFIERS,
3635
                COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
91,949✔
3636
                COMMON_TMP_SPECIFIERS,
3637
                {}
3638
        };
3639

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

3660
        if (!empty_or_dash(buffer)) {
91,949✔
3661
                i.argument = strdup(buffer);
23,635✔
3662
                if (!i.argument)
23,635✔
3663
                        return log_oom();
×
3664
        }
3665

3666
        if (isempty(action)) {
91,949✔
3667
                *invalid_config = true;
×
3668
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3669
                                  "Command too short '%s'.", action);
3670
        }
3671

3672
        for (int pos = 1; action[pos]; pos++)
123,107✔
3673
                if (action[pos] == '!' && !boot)
31,158✔
3674
                        boot = true;
3675
                else if (action[pos] == '+' && !append_or_force)
15,878✔
3676
                        append_or_force = true;
3677
                else if (action[pos] == '-' && !allow_failure)
10,574✔
3678
                        allow_failure = true;
3679
                else if (action[pos] == '=' && !try_replace)
8,462✔
3680
                        try_replace = true;
3681
                else if (action[pos] == '~' && !unbase64)
8,462✔
3682
                        unbase64 = true;
3683
                else if (action[pos] == '^' && !from_cred)
8,462✔
3684
                        from_cred = true;
3685
                else if (action[pos] == '$' && !purge)
6,350✔
3686
                        purge = true;
3687
                else if (action[pos] == '?' && !ignore_if_target_missing)
2✔
3688
                        ignore_if_target_missing = true;
3689
                else {
3690
                        *invalid_config = true;
×
3691
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3692
                                          "Unknown modifiers in command: %s", action);
3693
                }
3694

3695
        if (boot && !arg_boot) {
91,949✔
3696
                log_syntax(NULL, LOG_DEBUG, fname, line, 0,
124✔
3697
                           "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3698
                return 0;
124✔
3699
        }
3700

3701
        i.type = action[0];
91,825✔
3702
        i.append_or_force = append_or_force;
91,825✔
3703
        i.allow_failure = allow_failure;
91,825✔
3704
        i.try_replace = try_replace;
91,825✔
3705
        i.purge = purge;
91,825✔
3706
        i.ignore_if_target_missing = ignore_if_target_missing;
91,825✔
3707

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

3718
        r = patch_var_run(fname, line, &i.path);
91,825✔
3719
        if (r < 0)
91,825✔
3720
                return r;
3721

3722
        if (!path_is_absolute(i.path)) {
91,825✔
3723
                *invalid_config = true;
×
3724
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3725
                                  "Path '%s' not absolute.", i.path);
3726
        }
3727

3728
        path_simplify(i.path);
91,825✔
3729

3730
        switch (i.type) {
91,825✔
3731

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

3751
        case CREATE_FILE:
3752
        case TRUNCATE_FILE:
3753
                break;
3754

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

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

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

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

3787
                if (!i.argument) {
5,764✔
3788
                        *invalid_config = true;
×
3789
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3790
                                          "Device file requires argument.");
3791
                }
3792

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

3800
                break;
3801

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

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

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

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

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

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

3873
        if (!should_include_path(i.path))
91,824✔
3874
                return 0;
3875

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

3889
        switch (i.type) {
35,460✔
3890
        case CREATE_SYMLINK:
2,109✔
3891
                if (!i.argument) {
2,109✔
3892
                        i.argument = path_join("/usr/share/factory", i.path);
2✔
3893
                        if (!i.argument)
2✔
3894
                                return log_oom();
×
3895
                }
3896

3897
                break;
3898

3899
        case COPY_FILES:
5,985✔
3900
                if (!i.argument) {
5,985✔
3901
                        i.argument = path_join("/usr/share/factory", i.path);
4,716✔
3902
                        if (!i.argument)
4,716✔
3903
                                return log_oom();
×
3904
                } else if (!path_is_absolute(i.argument)) {
1,269✔
3905
                        *invalid_config = true;
×
3906
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
3907
                                          "Source path '%s' is not absolute.", i.argument);
3908

3909
                }
3910

3911
                if (!empty_or_root(arg_root)) {
5,985✔
3912
                        char *p;
1✔
3913

3914
                        p = path_join(arg_root, i.argument);
1✔
3915
                        if (!p)
1✔
3916
                                return log_oom();
×
3917
                        free_and_replace(i.argument, p);
1✔
3918
                }
3919

3920
                path_simplify(i.argument);
5,985✔
3921

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

3929
                break;
3930

3931
        default:
34,759✔
3932
                ;
34,759✔
3933
        }
3934

3935
        if (from_cred) {
34,759✔
3936
                if (!i.argument)
720✔
3937
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3938
                                          "Reading from credential requested, but no credential name specified.");
3939
                if (!credential_name_valid(i.argument))
720✔
3940
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
3941
                                          "Credential name not valid: %s", i.argument);
3942

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

3954
        /* If base64 decoding is requested, do so now */
3955
        if (unbase64 && item_binary_argument(&i)) {
34,213✔
3956
                _cleanup_free_ void *data = NULL;
×
3957
                size_t data_size = 0;
×
3958

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

3964
                free_and_replace(i.binary_argument, data);
×
3965
                i.binary_argument_size = data_size;
×
3966
        }
3967

3968
        if (!empty_or_root(arg_root)) {
34,213✔
3969
                char *p;
14✔
3970

3971
                p = path_join(arg_root, i.path);
14✔
3972
                if (!p)
14✔
3973
                        return log_oom();
91,949✔
3974
                free_and_replace(i.path, p);
14✔
3975
        }
3976

3977
        if (!empty_or_dash(user)) {
34,213✔
3978
                const char *u;
12,043✔
3979

3980
                u = startswith(user, ":");
12,043✔
3981
                if (u)
12,043✔
3982
                        i.uid_only_create = true;
4✔
3983
                else
3984
                        u = user;
3985

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

3998
        if (!empty_or_dash(group)) {
34,213✔
3999
                const char *g;
14,167✔
4000

4001
                g = startswith(group, ":");
14,167✔
4002
                if (g)
14,167✔
4003
                        i.gid_only_create = true;
538✔
4004
                else
4005
                        g = group;
4006

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

4019
        if (!empty_or_dash(mode)) {
34,213✔
4020
                const char *mm;
4021
                unsigned m;
4022

4023
                for (mm = mode;; mm++)
718✔
4024
                        if (*mm == '~')
23,182✔
4025
                                i.mask_perms = true;
180✔
4026
                        else if (*mm == ':')
23,002✔
4027
                                i.mode_only_create = true;
538✔
4028
                        else
4029
                                break;
4030

4031
                r = parse_mode(mm, &m);
22,464✔
4032
                if (r < 0) {
22,464✔
4033
                        *invalid_config = true;
×
4034
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
×
4035
                }
4036

4037
                i.mode = m;
22,464✔
4038
                i.mode_set = true;
22,464✔
4039
        } else
4040
                i.mode = IN_SET(i.type,
11,749✔
4041
                                CREATE_DIRECTORY,
4042
                                TRUNCATE_DIRECTORY,
4043
                                CREATE_SUBVOLUME,
4044
                                CREATE_SUBVOLUME_INHERIT_QUOTA,
4045
                                CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
4046

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

4055
        if (!empty_or_dash(age)) {
34,213✔
4056
                const char *a = age;
1,757✔
4057
                _cleanup_free_ char *seconds = NULL, *age_by = NULL;
1,757✔
4058

4059
                if (*a == '~') {
1,757✔
4060
                        i.keep_first_level = true;
×
4061
                        a++;
×
4062
                }
4063

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

4080
                        /* For parsing the "age" part, after the ":". */
4081
                        a = seconds;
142✔
4082
                }
4083

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

4090
                i.age_set = true;
1,748✔
4091
        }
4092

4093
        h = needs_glob(i.type) ? c->globs : c->items;
34,204✔
4094

4095
        existing = ordered_hashmap_get(h, i.path);
34,204✔
4096
        if (existing) {
34,204✔
4097
                if (is_duplicated_item(existing, &i)) {
2,040✔
4098
                        log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3✔
4099
                                   "Duplicate line for path \"%s\", ignoring.", i.path);
4100
                        return 0;
3✔
4101
                }
4102
        } else {
4103
                existing = new0(ItemArray, 1);
32,164✔
4104
                if (!existing)
32,164✔
4105
                        return log_oom();
×
4106

4107
                r = ordered_hashmap_put(h, i.path, existing);
32,164✔
4108
                if (r < 0) {
32,164✔
4109
                        free(existing);
×
4110
                        return log_oom();
×
4111
                }
4112
        }
4113

4114
        if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
34,201✔
4115
                return log_oom();
×
4116

4117
        existing->items[existing->n_items++] = TAKE_STRUCT(i);
34,201✔
4118

4119
        /* Sort item array, to enforce stable ordering of application */
4120
        typesafe_qsort(existing->items, existing->n_items, item_compare);
34,201✔
4121

4122
        return 0;
4123
}
4124

4125
static int cat_config(char **config_dirs, char **args) {
×
4126
        _cleanup_strv_free_ char **files = NULL;
×
4127
        int r;
×
4128

4129
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
×
4130
        if (r < 0)
×
4131
                return r;
4132

4133
        pager_open(arg_pager_flags);
×
4134

4135
        return cat_files(NULL, files, arg_cat_flags);
×
4136
}
4137

4138
static int exclude_default_prefixes(void) {
×
4139
        int r;
×
4140

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

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

4155
        strv_uniq(arg_exclude_prefixes);
×
4156
        return 0;
×
4157
}
4158

4159
static int help(void) {
×
4160
        _cleanup_free_ char *link = NULL;
×
4161
        int r;
×
4162

4163
        r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
×
4164
        if (r < 0)
×
4165
                return log_oom();
×
4166

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

4199
        return 0;
4200
}
4201

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

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

4247
        int c, r;
806✔
4248

4249
        assert(argc >= 0);
806✔
4250
        assert(argv);
806✔
4251

4252
        while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3,461✔
4253

4254
                switch (c) {
2,655✔
4255

4256
                case 'h':
×
4257
                        return help();
×
4258

4259
                case ARG_VERSION:
×
4260
                        return version();
×
4261

4262
                case ARG_CAT_CONFIG:
×
4263
                        arg_cat_flags = CAT_CONFIG_ON;
×
4264
                        break;
×
4265

4266
                case ARG_TLDR:
×
4267
                        arg_cat_flags = CAT_TLDR;
×
4268
                        break;
×
4269

4270
                case ARG_USER:
140✔
4271
                        arg_runtime_scope = RUNTIME_SCOPE_USER;
140✔
4272
                        break;
140✔
4273

4274
                case ARG_CREATE:
755✔
4275
                        arg_operation |= OPERATION_CREATE;
755✔
4276
                        break;
755✔
4277

4278
                case ARG_CLEAN:
38✔
4279
                        arg_operation |= OPERATION_CLEAN;
38✔
4280
                        break;
38✔
4281

4282
                case ARG_REMOVE:
325✔
4283
                        arg_operation |= OPERATION_REMOVE;
325✔
4284
                        break;
325✔
4285

4286
                case ARG_BOOT:
659✔
4287
                        arg_boot = true;
659✔
4288
                        break;
659✔
4289

4290
                case ARG_PURGE:
5✔
4291
                        arg_operation |= OPERATION_PURGE;
5✔
4292
                        break;
5✔
4293

4294
                case ARG_GRACEFUL:
174✔
4295
                        arg_graceful = true;
174✔
4296
                        break;
174✔
4297

4298
                case ARG_PREFIX:
348✔
4299
                        if (strv_extend(&arg_include_prefixes, optarg) < 0)
348✔
4300
                                return log_oom();
×
4301
                        break;
4302

4303
                case ARG_EXCLUDE_PREFIX:
174✔
4304
                        if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
174✔
4305
                                return log_oom();
×
4306
                        break;
4307

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

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

4326
                case 'E':
4327
                        r = exclude_default_prefixes();
×
4328
                        if (r < 0)
×
4329
                                return r;
4330

4331
                        break;
4332

4333
                case ARG_IMAGE_POLICY:
×
4334
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
4335
                        if (r < 0)
×
4336
                                return r;
4337
                        break;
4338

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

4347
                        arg_replace = optarg;
×
4348
                        break;
×
4349

4350
                case ARG_DRY_RUN:
29✔
4351
                        arg_dry_run = true;
29✔
4352
                        break;
29✔
4353

4354
                case ARG_NO_PAGER:
×
4355
                        arg_pager_flags |= PAGER_DISABLE;
×
4356
                        break;
×
4357

4358
                case '?':
4359
                        return -EINVAL;
4360

4361
                default:
×
4362
                        assert_not_reached();
×
4363
                }
4364

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

4369
        if (FLAGS_SET(arg_operation, OPERATION_PURGE) && optind >= argc)
806✔
4370
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4371
                                       "Refusing --purge without specification of a configuration file.");
4372

4373
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
806✔
4374
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4375
                                       "Option --replace= is not supported with --cat-config/--tldr.");
4376

4377
        if (arg_replace && optind >= argc)
806✔
4378
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4379
                                       "When --replace= is given, some configuration items must be specified.");
4380

4381
        if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
806✔
4382
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
4383
                                       "Combination of --user and --root= is not supported.");
4384

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

4389
        return 1;
4390
}
4391

4392
static int read_config_file(
21,093✔
4393
                Context *c,
4394
                char **config_dirs,
4395
                const char *fn,
4396
                bool ignore_enoent,
4397
                bool *invalid_config) {
4398

4399
        ItemArray *ia;
21,093✔
4400
        int r = 0;
21,093✔
4401

4402
        assert(c);
21,093✔
4403
        assert(fn);
21,093✔
4404

4405
        r = conf_file_read(arg_root, (const char**) config_dirs, fn,
21,093✔
4406
                           parse_line, c, ignore_enoent, invalid_config);
4407
        if (r <= 0)
21,093✔
4408
                return r;
21,093✔
4409

4410
        /* we have to determine age parameter for each entry of type X */
4411
        ORDERED_HASHMAP_FOREACH(ia, c->globs)
161,375✔
4412
                FOREACH_ARRAY(i, ia->items, ia->n_items) {
289,203✔
4413
                        ItemArray *ja;
148,401✔
4414
                        Item *candidate_item = NULL;
148,401✔
4415

4416
                        if (i->type != IGNORE_DIRECTORY_PATH)
148,401✔
4417
                                continue;
145,861✔
4418

4419
                        ORDERED_HASHMAP_FOREACH(ja, c->items)
219,476✔
4420
                                FOREACH_ARRAY(j, ja->items, ja->n_items) {
441,290✔
4421
                                        if (!IN_SET(j->type, CREATE_DIRECTORY,
224,354✔
4422
                                                             TRUNCATE_DIRECTORY,
4423
                                                             CREATE_SUBVOLUME,
4424
                                                             CREATE_SUBVOLUME_INHERIT_QUOTA,
4425
                                                             CREATE_SUBVOLUME_NEW_QUOTA))
4426
                                                continue;
114,320✔
4427

4428
                                        if (path_equal(j->path, i->path)) {
110,034✔
4429
                                                candidate_item = j;
4430
                                                break;
4431
                                        }
4432

4433
                                        if (candidate_item
110,034✔
4434
                                            ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
11,016✔
4435
                                            : path_startswith(i->path, j->path) != NULL)
99,018✔
4436
                                                candidate_item = j;
4437
                                }
4438

4439
                        if (candidate_item && candidate_item->age_set) {
2,540✔
4440
                                i->age = candidate_item->age;
1,814✔
4441
                                i->age_set = true;
1,814✔
4442
                        }
4443
                }
4444

4445
        return r;
20,573✔
4446
}
4447

4448
static int parse_arguments(
138✔
4449
                Context *c,
4450
                char **config_dirs,
4451
                char **args,
4452
                bool *invalid_config) {
4453
        int r;
138✔
4454

4455
        assert(c);
138✔
4456

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

4463
        return 0;
4464
}
4465

4466
static int read_config_files(
668✔
4467
                Context *c,
4468
                char **config_dirs,
4469
                char **args,
4470
                bool *invalid_config) {
4471

4472
        _cleanup_strv_free_ char **files = NULL;
×
4473
        _cleanup_free_ char *p = NULL;
668✔
4474
        int r;
668✔
4475

4476
        assert(c);
668✔
4477

4478
        r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
668✔
4479
        if (r < 0)
668✔
4480
                return r;
4481

4482
        STRV_FOREACH(f, files)
21,100✔
4483
                if (p && path_equal(*f, p)) {
20,432✔
4484
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
×
4485

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

4494
        return 0;
4495
}
4496

4497
static int read_credential_lines(Context *c, bool *invalid_config) {
806✔
4498
        _cleanup_free_ char *j = NULL;
806✔
4499
        const char *d;
806✔
4500
        int r;
806✔
4501

4502
        assert(c);
806✔
4503

4504
        r = get_credentials_dir(&d);
806✔
4505
        if (r == -ENXIO)
806✔
4506
                return 0;
4507
        if (r < 0)
523✔
4508
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
4509

4510
        j = path_join(d, "tmpfiles.extra");
523✔
4511
        if (!j)
523✔
4512
                return log_oom();
×
4513

4514
        (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
523✔
4515
        return 0;
4516
}
4517

4518
static int link_parent(Context *c, ItemArray *a) {
32,164✔
4519
        const char *path;
32,164✔
4520
        char *prefix;
32,164✔
4521
        int r;
32,164✔
4522

4523
        assert(c);
32,164✔
4524
        assert(a);
32,164✔
4525

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

4531
        if (a->n_items <= 0)
32,164✔
4532
                return 0;
4533

4534
        path = a->items[0].path;
32,164✔
4535
        prefix = newa(char, strlen(path) + 1);
32,164✔
4536
        PATH_FOREACH_PREFIX(prefix, path) {
106,594✔
4537
                ItemArray *j;
55,818✔
4538

4539
                j = ordered_hashmap_get(c->items, prefix);
55,818✔
4540
                if (!j)
55,818✔
4541
                        j = ordered_hashmap_get(c->globs, prefix);
43,534✔
4542
                if (j) {
43,534✔
4543
                        r = set_ensure_put(&j->children, NULL, a);
13,552✔
4544
                        if (r < 0)
13,552✔
4545
                                return log_oom();
×
4546

4547
                        a->parent = j;
13,552✔
4548
                        return 1;
13,552✔
4549
                }
4550
        }
4551

4552
        return 0;
4553
}
4554

4555
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
32,164✔
4556
                                              ItemArray, item_array_free);
4557

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

4575
        r = parse_argv(argc, argv);
806✔
4576
        if (r <= 0)
806✔
4577
                return r;
4578

4579
        log_setup();
806✔
4580

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

4591
        /* Descending down file system trees might take a lot of fds */
4592
        (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
806✔
4593

4594
        switch (arg_runtime_scope) {
806✔
4595

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

4602
        case RUNTIME_SCOPE_SYSTEM:
666✔
4603
                config_dirs = strv_new(CONF_PATHS("tmpfiles.d"));
666✔
4604
                if (!config_dirs)
666✔
4605
                        return log_oom();
×
4606
                break;
4607

4608
        default:
×
4609
                assert_not_reached();
×
4610
        }
4611

4612
        if (DEBUG_LOGGING) {
806✔
4613
                _cleanup_free_ char *t = NULL;
694✔
4614

4615
                STRV_FOREACH(i, config_dirs) {
3,750✔
4616
                        _cleanup_free_ char *j = NULL;
3,056✔
4617

4618
                        j = path_join(arg_root, *i);
3,056✔
4619
                        if (!j)
3,056✔
4620
                                return log_oom();
×
4621

4622
                        if (!strextend(&t, "\n\t", j))
3,056✔
4623
                                return log_oom();
×
4624
                }
4625

4626
                log_debug("Looking for configuration files in (higher priority first):%s", t);
694✔
4627
        }
4628

4629
        if (arg_cat_flags != CAT_CONFIG_OFF)
806✔
4630
                return cat_config(config_dirs, argv + optind);
×
4631

4632
        if (should_bypass("SYSTEMD_TMPFILES"))
806✔
4633
                return 0;
4634

4635
        umask(0022);
806✔
4636

4637
        r = mac_init();
806✔
4638
        if (r < 0)
806✔
4639
                return r;
4640

4641
#ifndef STANDALONE
4642
        if (arg_image) {
806✔
4643
                assert(!arg_root);
×
4644

4645
                r = mount_image_privately_interactively(
×
4646
                                arg_image,
4647
                                arg_image_policy,
4648
                                DISSECT_IMAGE_GENERIC_ROOT |
4649
                                DISSECT_IMAGE_REQUIRE_ROOT |
4650
                                DISSECT_IMAGE_VALIDATE_OS |
4651
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
4652
                                DISSECT_IMAGE_FSCK |
4653
                                DISSECT_IMAGE_GROWFS |
4654
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
4655
                                &mounted_dir,
4656
                                /* ret_dir_fd= */ NULL,
4657
                                &loop_device);
4658
                if (r < 0)
×
4659
                        return r;
4660

4661
                arg_root = strdup(mounted_dir);
×
4662
                if (!arg_root)
×
4663
                        return log_oom();
×
4664
        }
4665
#else
4666
        assert(!arg_image);
4667
#endif
4668

4669
        c.items = ordered_hashmap_new(&item_array_hash_ops);
806✔
4670
        c.globs = ordered_hashmap_new(&item_array_hash_ops);
806✔
4671
        if (!c.items || !c.globs)
806✔
4672
                return log_oom();
×
4673

4674
        /* If command line arguments are specified along with --replace=, read all configuration files and
4675
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4676
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
4677
         * read configuration and execute it. */
4678
        if (arg_replace || optind >= argc)
806✔
4679
                r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
668✔
4680
        else
4681
                r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
138✔
4682
        if (r < 0)
806✔
4683
                return r;
4684

4685
        r = read_credential_lines(&c, &invalid_config);
806✔
4686
        if (r < 0)
806✔
4687
                return r;
4688

4689
        /* Let's now link up all child/parent relationships */
4690
        ORDERED_HASHMAP_FOREACH(a, c.items) {
23,798✔
4691
                r = link_parent(&c, a);
22,992✔
4692
                if (r < 0)
22,992✔
4693
                        return r;
×
4694
        }
4695
        ORDERED_HASHMAP_FOREACH(a, c.globs) {
9,978✔
4696
                r = link_parent(&c, a);
9,172✔
4697
                if (r < 0)
9,172✔
4698
                        return r;
×
4699
        }
4700

4701
        /* If multiple operations are requested, let's first run the remove/clean operations, and only then
4702
         * the create operations. i.e. that we first clean out the platform we then build on. */
4703
        for (phase = 0; phase < _PHASE_MAX; phase++) {
3,224✔
4704
                OperationMask op;
2,418✔
4705

4706
                if (phase == PHASE_PURGE)
2,418✔
4707
                        op = arg_operation & OPERATION_PURGE;
806✔
4708
                else if (phase == PHASE_REMOVE_AND_CLEAN)
1,612✔
4709
                        op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
806✔
4710
                else if (phase == PHASE_CREATE)
806✔
4711
                        op = arg_operation & OPERATION_CREATE;
806✔
4712
                else
4713
                        assert_not_reached();
×
4714

4715
                if (op == 0) /* Nothing requested in this phase */
2,418✔
4716
                        continue;
1,295✔
4717

4718
                /* The non-globbing ones usually create things, hence we apply them first */
4719
                ORDERED_HASHMAP_FOREACH(a, c.items)
41,591✔
4720
                        RET_GATHER(r, process_item_array(&c, a, op));
40,468✔
4721

4722
                /* The globbing ones usually alter things, hence we apply them second. */
4723
                ORDERED_HASHMAP_FOREACH(a, c.globs)
16,038✔
4724
                        RET_GATHER(r, process_item_array(&c, a, op));
14,915✔
4725
        }
4726

4727
        if (ERRNO_IS_NEG_RESOURCE(r))
1,612✔
4728
                return r;
4729
        if (invalid_config)
806✔
4730
                return EX_DATAERR;
4731
        if (r < 0)
796✔
4732
                return EX_CANTCREAT;
15✔
4733
        return 0;
4734
}
4735

4736
DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
1,612✔
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