]> git.ipfire.org Git - thirdparty/systemd.git/blame_incremental - src/tmpfiles/tmpfiles.c
tmpfiles: only populate uid and gid caches once
[thirdparty/systemd.git] / src / tmpfiles / tmpfiles.c
... / ...
CommitLineData
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 <linux/fs.h>
9#include <stdbool.h>
10#include <stddef.h>
11#include <stdlib.h>
12#include <sys/file.h>
13#include <sys/xattr.h>
14#include <sysexits.h>
15#include <time.h>
16#include <unistd.h>
17
18#include "sd-path.h"
19
20#include "acl-util.h"
21#include "alloc-util.h"
22#include "btrfs-util.h"
23#include "build.h"
24#include "capability-util.h"
25#include "chase.h"
26#include "chattr-util.h"
27#include "conf-files.h"
28#include "constants.h"
29#include "copy.h"
30#include "creds-util.h"
31#include "devnum-util.h"
32#include "dirent-util.h"
33#include "dissect-image.h"
34#include "env-util.h"
35#include "errno-util.h"
36#include "escape.h"
37#include "fd-util.h"
38#include "fileio.h"
39#include "format-util.h"
40#include "fs-util.h"
41#include "glob-util.h"
42#include "hexdecoct.h"
43#include "io-util.h"
44#include "label-util.h"
45#include "log.h"
46#include "macro.h"
47#include "main-func.h"
48#include "missing_syscall.h"
49#include "mkdir-label.h"
50#include "mount-util.h"
51#include "mountpoint-util.h"
52#include "nulstr-util.h"
53#include "offline-passwd.h"
54#include "pager.h"
55#include "parse-argument.h"
56#include "parse-util.h"
57#include "path-lookup.h"
58#include "path-util.h"
59#include "pretty-print.h"
60#include "rlimit-util.h"
61#include "rm-rf.h"
62#include "selinux-util.h"
63#include "set.h"
64#include "sort-util.h"
65#include "specifier.h"
66#include "stat-util.h"
67#include "stdio-util.h"
68#include "string-table.h"
69#include "string-util.h"
70#include "strv.h"
71#include "terminal-util.h"
72#include "umask-util.h"
73#include "user-util.h"
74#include "virt.h"
75
76/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
77 * them in the file system. This is intended to be used to create
78 * properly owned directories beneath /tmp, /var/tmp, /run, which are
79 * volatile and hence need to be recreated on bootup. */
80
81typedef enum OperationMask {
82 OPERATION_CREATE = 1 << 0,
83 OPERATION_REMOVE = 1 << 1,
84 OPERATION_CLEAN = 1 << 2,
85 OPERATION_PURGE = 1 << 3,
86} OperationMask;
87
88typedef enum ItemType {
89 /* These ones take file names */
90 CREATE_FILE = 'f',
91 TRUNCATE_FILE = 'F', /* deprecated: use f+ */
92 CREATE_DIRECTORY = 'd',
93 TRUNCATE_DIRECTORY = 'D',
94 CREATE_SUBVOLUME = 'v',
95 CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
96 CREATE_SUBVOLUME_NEW_QUOTA = 'Q',
97 CREATE_FIFO = 'p',
98 CREATE_SYMLINK = 'L',
99 CREATE_CHAR_DEVICE = 'c',
100 CREATE_BLOCK_DEVICE = 'b',
101 COPY_FILES = 'C',
102
103 /* These ones take globs */
104 WRITE_FILE = 'w',
105 EMPTY_DIRECTORY = 'e',
106 SET_XATTR = 't',
107 RECURSIVE_SET_XATTR = 'T',
108 SET_ACL = 'a',
109 RECURSIVE_SET_ACL = 'A',
110 SET_ATTRIBUTE = 'h',
111 RECURSIVE_SET_ATTRIBUTE = 'H',
112 IGNORE_PATH = 'x',
113 IGNORE_DIRECTORY_PATH = 'X',
114 REMOVE_PATH = 'r',
115 RECURSIVE_REMOVE_PATH = 'R',
116 RELABEL_PATH = 'z',
117 RECURSIVE_RELABEL_PATH = 'Z',
118 ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
119} ItemType;
120
121typedef enum AgeBy {
122 AGE_BY_ATIME = 1 << 0,
123 AGE_BY_BTIME = 1 << 1,
124 AGE_BY_CTIME = 1 << 2,
125 AGE_BY_MTIME = 1 << 3,
126
127 /* All file timestamp types are checked by default. */
128 AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
129 AGE_BY_DEFAULT_DIR = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME,
130} AgeBy;
131
132typedef struct Item {
133 ItemType type;
134
135 char *path;
136 char *argument;
137 void *binary_argument; /* set if binary data, in which case it takes precedence over 'argument' */
138 size_t binary_argument_size;
139 char **xattrs;
140#if HAVE_ACL
141 acl_t acl_access;
142 acl_t acl_access_exec;
143 acl_t acl_default;
144#endif
145 uid_t uid;
146 gid_t gid;
147 mode_t mode;
148 usec_t age;
149 AgeBy age_by_file, age_by_dir;
150
151 dev_t major_minor;
152 unsigned attribute_value;
153 unsigned attribute_mask;
154
155 bool uid_set:1;
156 bool gid_set:1;
157 bool mode_set:1;
158 bool uid_only_create:1;
159 bool gid_only_create:1;
160 bool mode_only_create:1;
161 bool age_set:1;
162 bool mask_perms:1;
163 bool attribute_set:1;
164
165 bool keep_first_level:1;
166
167 bool append_or_force:1;
168
169 bool allow_failure:1;
170
171 bool try_replace:1;
172
173 OperationMask done;
174} Item;
175
176typedef struct ItemArray {
177 Item *items;
178 size_t n_items;
179
180 struct ItemArray *parent;
181 Set *children;
182} ItemArray;
183
184typedef enum DirectoryType {
185 DIRECTORY_RUNTIME,
186 DIRECTORY_STATE,
187 DIRECTORY_CACHE,
188 DIRECTORY_LOGS,
189 _DIRECTORY_TYPE_MAX,
190} DirectoryType;
191
192typedef enum {
193 CREATION_NORMAL,
194 CREATION_EXISTING,
195 CREATION_FORCE,
196 _CREATION_MODE_MAX,
197 _CREATION_MODE_INVALID = -EINVAL,
198} CreationMode;
199
200static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
201static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
202static OperationMask arg_operation = 0;
203static bool arg_boot = false;
204static bool arg_graceful = false;
205static PagerFlags arg_pager_flags = 0;
206
207static char **arg_include_prefixes = NULL;
208static char **arg_exclude_prefixes = NULL;
209static char *arg_root = NULL;
210static char *arg_image = NULL;
211static char *arg_replace = NULL;
212static ImagePolicy *arg_image_policy = NULL;
213
214#define MAX_DEPTH 256
215
216typedef struct Context {
217 OrderedHashmap *items;
218 OrderedHashmap *globs;
219 Set *unix_sockets;
220 Hashmap *uid_cache;
221 Hashmap *gid_cache;
222} Context;
223
224STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, strv_freep);
225STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, strv_freep);
226STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
227STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
228STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
229
230static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
231 [CREATION_NORMAL] = "Created",
232 [CREATION_EXISTING] = "Found existing",
233 [CREATION_FORCE] = "Created replacement",
234};
235
236DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
237
238static void context_done(Context *c) {
239 assert(c);
240
241 ordered_hashmap_free(c->items);
242 ordered_hashmap_free(c->globs);
243
244 set_free(c->unix_sockets);
245
246 hashmap_free(c->uid_cache);
247 hashmap_free(c->gid_cache);
248}
249
250/* Different kinds of errors that mean that information is not available in the environment. */
251static bool ERRNO_IS_NOINFO(int r) {
252 return IN_SET(abs(r),
253 EUNATCH, /* os-release or machine-id missing */
254 ENOMEDIUM, /* machine-id or another file empty */
255 ENOPKG, /* machine-id is uninitialized */
256 ENXIO); /* env var is unset */
257}
258
259static int specifier_directory(
260 char specifier,
261 const void *data,
262 const char *root,
263 const void *userdata,
264 char **ret) {
265
266 struct table_entry {
267 uint64_t type;
268 const char *suffix;
269 };
270
271 static const struct table_entry paths_system[] = {
272 [DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME },
273 [DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE },
274 [DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE },
275 [DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS },
276 };
277
278 static const struct table_entry paths_user[] = {
279 [DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME },
280 [DIRECTORY_STATE] = { SD_PATH_USER_STATE_PRIVATE },
281 [DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE },
282 [DIRECTORY_LOGS] = { SD_PATH_USER_STATE_PRIVATE, "log" },
283 };
284
285 const struct table_entry *paths;
286 _cleanup_free_ char *p = NULL;
287 unsigned i;
288 int r;
289
290 assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
291 paths = arg_runtime_scope == RUNTIME_SCOPE_USER ? paths_user : paths_system;
292
293 i = PTR_TO_UINT(data);
294 assert(i < ELEMENTSOF(paths_system));
295
296 r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
297 if (r < 0)
298 return r;
299
300 if (arg_root) {
301 _cleanup_free_ char *j = NULL;
302
303 j = path_join(arg_root, p);
304 if (!j)
305 return -ENOMEM;
306
307 *ret = TAKE_PTR(j);
308 } else
309 *ret = TAKE_PTR(p);
310
311 return 0;
312}
313
314static int log_unresolvable_specifier(const char *filename, unsigned line) {
315 static bool notified = false;
316
317 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
318 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
319 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
320 * to LOG_DEBUG for the rest.
321 *
322 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
323 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
324 * expectation that machine-id and other files will be populated.
325 */
326
327 int log_level = notified || arg_root || running_in_chroot() > 0 ?
328 LOG_DEBUG : LOG_NOTICE;
329
330 log_syntax(NULL,
331 log_level,
332 filename, line, 0,
333 "Failed to resolve specifier: %s, skipping.",
334 arg_runtime_scope == RUNTIME_SCOPE_USER ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
335
336 if (!notified)
337 log_full(log_level,
338 "All rules containing unresolvable specifiers will be skipped.");
339
340 notified = true;
341 return 0;
342}
343
344static int user_config_paths(char*** ret) {
345 _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
346 _cleanup_free_ char *persistent_config = NULL, *runtime_config = NULL, *data_home = NULL;
347 _cleanup_strv_free_ char **res = NULL;
348 int r;
349
350 r = xdg_user_dirs(&config_dirs, &data_dirs);
351 if (r < 0)
352 return r;
353
354 r = xdg_user_config_dir(&persistent_config, "/user-tmpfiles.d");
355 if (r < 0 && !ERRNO_IS_NOINFO(r))
356 return r;
357
358 r = xdg_user_runtime_dir(&runtime_config, "/user-tmpfiles.d");
359 if (r < 0 && !ERRNO_IS_NOINFO(r))
360 return r;
361
362 r = xdg_user_data_dir(&data_home, "/user-tmpfiles.d");
363 if (r < 0 && !ERRNO_IS_NOINFO(r))
364 return r;
365
366 r = strv_extend_strv_concat(&res, config_dirs, "/user-tmpfiles.d");
367 if (r < 0)
368 return r;
369
370 r = strv_extend_many(
371 &res,
372 persistent_config,
373 runtime_config,
374 data_home);
375 if (r < 0)
376 return r;
377
378 r = strv_extend_strv_concat(&res, data_dirs, "/user-tmpfiles.d");
379 if (r < 0)
380 return r;
381
382 r = path_strv_make_absolute_cwd(res);
383 if (r < 0)
384 return r;
385
386 *ret = TAKE_PTR(res);
387 return 0;
388}
389
390static bool needs_purge(ItemType t) {
391 return IN_SET(t,
392 COPY_FILES,
393 TRUNCATE_FILE,
394 CREATE_FILE,
395 WRITE_FILE,
396 EMPTY_DIRECTORY,
397 CREATE_SUBVOLUME,
398 CREATE_SUBVOLUME_INHERIT_QUOTA,
399 CREATE_SUBVOLUME_NEW_QUOTA,
400 CREATE_CHAR_DEVICE,
401 CREATE_BLOCK_DEVICE,
402 CREATE_SYMLINK,
403 CREATE_FIFO,
404 CREATE_DIRECTORY,
405 TRUNCATE_DIRECTORY);
406}
407
408static bool needs_glob(ItemType t) {
409 return IN_SET(t,
410 WRITE_FILE,
411 EMPTY_DIRECTORY,
412 SET_XATTR,
413 RECURSIVE_SET_XATTR,
414 SET_ACL,
415 RECURSIVE_SET_ACL,
416 SET_ATTRIBUTE,
417 RECURSIVE_SET_ATTRIBUTE,
418 IGNORE_PATH,
419 IGNORE_DIRECTORY_PATH,
420 REMOVE_PATH,
421 RECURSIVE_REMOVE_PATH,
422 RELABEL_PATH,
423 RECURSIVE_RELABEL_PATH,
424 ADJUST_MODE);
425}
426
427static bool takes_ownership(ItemType t) {
428 return IN_SET(t,
429 CREATE_FILE,
430 TRUNCATE_FILE,
431 CREATE_DIRECTORY,
432 TRUNCATE_DIRECTORY,
433 CREATE_SUBVOLUME,
434 CREATE_SUBVOLUME_INHERIT_QUOTA,
435 CREATE_SUBVOLUME_NEW_QUOTA,
436 CREATE_FIFO,
437 CREATE_SYMLINK,
438 CREATE_CHAR_DEVICE,
439 CREATE_BLOCK_DEVICE,
440 COPY_FILES,
441 WRITE_FILE,
442 EMPTY_DIRECTORY,
443 IGNORE_PATH,
444 IGNORE_DIRECTORY_PATH,
445 REMOVE_PATH,
446 RECURSIVE_REMOVE_PATH);
447}
448
449static struct Item* find_glob(OrderedHashmap *h, const char *match) {
450 ItemArray *j;
451
452 ORDERED_HASHMAP_FOREACH(j, h) {
453 size_t n;
454
455 for (n = 0; n < j->n_items; n++) {
456 Item *item = j->items + n;
457
458 if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
459 return item;
460 }
461 }
462
463 return NULL;
464}
465
466static int load_unix_sockets(Context *c) {
467 _cleanup_set_free_ Set *sockets = NULL;
468 _cleanup_fclose_ FILE *f = NULL;
469 int r;
470
471 if (c->unix_sockets)
472 return 0;
473
474 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
475
476 f = fopen("/proc/net/unix", "re");
477 if (!f)
478 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
479 "Failed to open /proc/net/unix, ignoring: %m");
480
481 /* Skip header */
482 r = read_line(f, LONG_LINE_MAX, NULL);
483 if (r < 0)
484 return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
485 if (r == 0)
486 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
487
488 for (;;) {
489 _cleanup_free_ char *line = NULL;
490 char *p;
491
492 r = read_line(f, LONG_LINE_MAX, &line);
493 if (r < 0)
494 return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
495 if (r == 0) /* EOF */
496 break;
497
498 p = strchr(line, ':');
499 if (!p)
500 continue;
501
502 if (strlen(p) < 37)
503 continue;
504
505 p += 37;
506 p += strspn(p, WHITESPACE);
507 p += strcspn(p, WHITESPACE); /* skip one more word */
508 p += strspn(p, WHITESPACE);
509
510 if (!path_is_absolute(p))
511 continue;
512
513 r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
514 if (r < 0)
515 return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
516 }
517
518 c->unix_sockets = TAKE_PTR(sockets);
519 return 1;
520}
521
522static bool unix_socket_alive(Context *c, const char *fn) {
523 assert(c);
524 assert(fn);
525
526 if (load_unix_sockets(c) < 0)
527 return true; /* We don't know, so assume yes */
528
529 return set_contains(c->unix_sockets, fn);
530}
531
532/* Accessors for the argument in binary format */
533static const void* item_binary_argument(const Item *i) {
534 assert(i);
535 return i->binary_argument ?: i->argument;
536}
537
538static size_t item_binary_argument_size(const Item *i) {
539 assert(i);
540 return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
541}
542
543static DIR* xopendirat_nomod(int dirfd, const char *path) {
544 DIR *dir;
545
546 dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
547 if (dir)
548 return dir;
549
550 if (!IN_SET(errno, ENOENT, ELOOP))
551 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
552
553 if (errno != EPERM)
554 return NULL;
555
556 dir = xopendirat(dirfd, path, O_NOFOLLOW);
557 if (!dir)
558 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
559
560 return dir;
561}
562
563static DIR* opendir_nomod(const char *path) {
564 return xopendirat_nomod(AT_FDCWD, path);
565}
566
567static bool needs_cleanup(
568 nsec_t atime,
569 nsec_t btime,
570 nsec_t ctime,
571 nsec_t mtime,
572 nsec_t cutoff,
573 const char *sub_path,
574 AgeBy age_by,
575 bool is_dir) {
576
577 if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
578 /* Follows spelling in stat(1). */
579 log_debug("%s \"%s\": modify time %s is too new.",
580 is_dir ? "Directory" : "File",
581 sub_path,
582 FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
583
584 return false;
585 }
586
587 if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
588 log_debug("%s \"%s\": access time %s is too new.",
589 is_dir ? "Directory" : "File",
590 sub_path,
591 FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
592
593 return false;
594 }
595
596 /*
597 * Note: Unless explicitly specified by the user, "ctime" is ignored
598 * by default for directories, because we change it when deleting.
599 */
600 if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
601 log_debug("%s \"%s\": change time %s is too new.",
602 is_dir ? "Directory" : "File",
603 sub_path,
604 FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
605
606 return false;
607 }
608
609 if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
610 log_debug("%s \"%s\": birth time %s is too new.",
611 is_dir ? "Directory" : "File",
612 sub_path,
613 FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
614
615 return false;
616 }
617
618 return true;
619}
620
621static int dir_cleanup(
622 Context *c,
623 Item *i,
624 const char *p,
625 DIR *d,
626 nsec_t self_atime_nsec,
627 nsec_t self_mtime_nsec,
628 nsec_t cutoff_nsec,
629 dev_t rootdev_major,
630 dev_t rootdev_minor,
631 bool mountpoint,
632 int maxdepth,
633 bool keep_this_level,
634 AgeBy age_by_file,
635 AgeBy age_by_dir) {
636
637 bool deleted = false;
638 int r = 0;
639
640 assert(c);
641 assert(i);
642 assert(d);
643
644 FOREACH_DIRENT_ALL(de, d, break) {
645 _cleanup_free_ char *sub_path = NULL;
646 nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
647
648 if (dot_or_dot_dot(de->d_name))
649 continue;
650
651 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
652 * explicitly where we are looking at a mount point, for free as side information. Determining
653 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
654 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
655 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
656 * while on older kernels's well do traditional st_dev based detection of mount points.
657 *
658 * Using statx() for detecting mount points also has the benefit that we handle weird file
659 * systems such as overlayfs better where each file is originating from a different
660 * st_dev. */
661
662 STRUCT_STATX_DEFINE(sx);
663
664 r = statx_fallback(
665 dirfd(d), de->d_name,
666 AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
667 STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
668 &sx);
669 if (r == -ENOENT)
670 continue;
671 if (r < 0) {
672 /* FUSE, NFS mounts, SELinux might return EACCES */
673 r = log_full_errno(r == -EACCES ? LOG_DEBUG : LOG_ERR, r,
674 "statx(%s/%s) failed: %m", p, de->d_name);
675 continue;
676 }
677
678 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) {
679 /* Yay, we have the mount point API, use it */
680 if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
681 log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
682 continue;
683 }
684 } else {
685 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
686 * back to traditional stx_dev checking. */
687 if (sx.stx_dev_major != rootdev_major ||
688 sx.stx_dev_minor != rootdev_minor) {
689 log_debug("Ignoring \"%s/%s\": different filesystem.", p, de->d_name);
690 continue;
691 }
692
693 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
694 * major/minors. This type of query is not supported on all kernels or filesystem types
695 * though. */
696 if (S_ISDIR(sx.stx_mode)) {
697 int q;
698
699 q = fd_is_mount_point(dirfd(d), de->d_name, 0);
700 if (q < 0)
701 log_debug_errno(q, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p, de->d_name);
702 else if (q > 0) {
703 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p, de->d_name);
704 continue;
705 }
706 }
707 }
708
709 atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : 0;
710 mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : 0;
711 ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : 0;
712 btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : 0;
713
714 sub_path = path_join(p, de->d_name);
715 if (!sub_path) {
716 r = log_oom();
717 goto finish;
718 }
719
720 /* Is there an item configured for this path? */
721 if (ordered_hashmap_get(c->items, sub_path)) {
722 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
723 continue;
724 }
725
726 if (find_glob(c->globs, sub_path)) {
727 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
728 continue;
729 }
730
731 if (S_ISDIR(sx.stx_mode)) {
732 _cleanup_closedir_ DIR *sub_dir = NULL;
733
734 if (mountpoint &&
735 streq(de->d_name, "lost+found") &&
736 sx.stx_uid == 0) {
737 log_debug("Ignoring directory \"%s\".", sub_path);
738 continue;
739 }
740
741 if (maxdepth <= 0)
742 log_warning("Reached max depth on \"%s\".", sub_path);
743 else {
744 int q;
745
746 sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
747 if (!sub_dir) {
748 if (errno != ENOENT)
749 r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
750
751 continue;
752 }
753
754 if (flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
755 log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path);
756 continue;
757 }
758
759 q = dir_cleanup(c, i,
760 sub_path, sub_dir,
761 atime_nsec, mtime_nsec, cutoff_nsec,
762 rootdev_major, rootdev_minor,
763 false, maxdepth-1, false,
764 age_by_file, age_by_dir);
765 if (q < 0)
766 r = q;
767 }
768
769 /* Note: if you are wondering why we don't support the sticky bit for excluding
770 * directories from cleaning like we do it for other file system objects: well, the
771 * sticky bit already has a meaning for directories, so we don't want to overload
772 * that. */
773
774 if (keep_this_level) {
775 log_debug("Keeping directory \"%s\".", sub_path);
776 continue;
777 }
778
779 /*
780 * Check the file timestamps of an entry against the
781 * given cutoff time; delete if it is older.
782 */
783 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
784 cutoff_nsec, sub_path, age_by_dir, true))
785 continue;
786
787 log_debug("Removing directory \"%s\".", sub_path);
788 if (unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0)
789 if (!IN_SET(errno, ENOENT, ENOTEMPTY))
790 r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
791
792 } else {
793 _cleanup_close_ int fd = -EBADF;
794
795 /* Skip files for which the sticky bit is set. These are semantics we define, and are
796 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
797 if (sx.stx_mode & S_ISVTX) {
798 log_debug("Skipping \"%s\": sticky bit set.", sub_path);
799 continue;
800 }
801
802 if (mountpoint &&
803 S_ISREG(sx.stx_mode) &&
804 sx.stx_uid == 0 &&
805 STR_IN_SET(de->d_name,
806 ".journal",
807 "aquota.user",
808 "aquota.group")) {
809 log_debug("Skipping \"%s\".", sub_path);
810 continue;
811 }
812
813 /* Ignore sockets that are listed in /proc/net/unix */
814 if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
815 log_debug("Skipping \"%s\": live socket.", sub_path);
816 continue;
817 }
818
819 /* Ignore device nodes */
820 if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
821 log_debug("Skipping \"%s\": a device.", sub_path);
822 continue;
823 }
824
825 /* Keep files on this level around if this is requested */
826 if (keep_this_level) {
827 log_debug("Keeping \"%s\".", sub_path);
828 continue;
829 }
830
831 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
832 cutoff_nsec, sub_path, age_by_file, false))
833 continue;
834
835 fd = xopenat(dirfd(d),
836 de->d_name,
837 O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME|O_NONBLOCK,
838 /* xopen_flags = */ 0,
839 /* mode = */ 0);
840 if (fd < 0 && !IN_SET(fd, -ENOENT, -ELOOP))
841 log_warning_errno(fd, "Opening file \"%s\" failed, ignoring: %m", sub_path);
842 if (fd >= 0 && flock(fd, LOCK_EX|LOCK_NB) < 0 && errno == EAGAIN) {
843 log_debug_errno(errno, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", sub_path);
844 continue;
845 }
846
847 log_debug("Removing \"%s\".", sub_path);
848 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
849 if (errno != ENOENT)
850 r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
851
852 deleted = true;
853 }
854 }
855
856finish:
857 if (deleted) {
858 struct timespec ts[2];
859
860 log_debug("Restoring access and modification time on \"%s\": %s, %s",
861 p,
862 FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
863 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
864
865 timespec_store_nsec(ts + 0, self_atime_nsec);
866 timespec_store_nsec(ts + 1, self_mtime_nsec);
867
868 /* Restore original directory timestamps */
869 if (futimens(dirfd(d), ts) < 0)
870 log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
871 }
872
873 return r;
874}
875
876static bool dangerous_hardlinks(void) {
877 _cleanup_free_ char *value = NULL;
878 static int cached = -1;
879 int r;
880
881 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
882 * what the upstream default is. */
883
884 if (cached >= 0)
885 return cached;
886
887 r = read_one_line_file("/proc/sys/fs/protected_hardlinks", &value);
888 if (r < 0) {
889 log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl: %m");
890 return true;
891 }
892
893 r = parse_boolean(value);
894 if (r < 0) {
895 log_debug_errno(r, "Failed to parse fs.protected_hardlinks sysctl: %m");
896 return true;
897 }
898
899 cached = r == 0;
900 return cached;
901}
902
903static bool hardlink_vulnerable(const struct stat *st) {
904 assert(st);
905
906 return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && dangerous_hardlinks();
907}
908
909static mode_t process_mask_perms(mode_t mode, mode_t current) {
910
911 if ((current & 0111) == 0)
912 mode &= ~0111;
913 if ((current & 0222) == 0)
914 mode &= ~0222;
915 if ((current & 0444) == 0)
916 mode &= ~0444;
917 if (!S_ISDIR(current))
918 mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
919
920 return mode;
921}
922
923static int fd_set_perms(
924 Context *c,
925 Item *i,
926 int fd,
927 const char *path,
928 const struct stat *st,
929 CreationMode creation) {
930
931 bool do_chown, do_chmod;
932 struct stat stbuf;
933 mode_t new_mode;
934 uid_t new_uid;
935 gid_t new_gid;
936 int r;
937
938 assert(c);
939 assert(i);
940 assert(fd >= 0);
941 assert(path);
942
943 if (!i->mode_set && !i->uid_set && !i->gid_set)
944 goto shortcut;
945
946 if (!st) {
947 if (fstat(fd, &stbuf) < 0)
948 return log_error_errno(errno, "fstat(%s) failed: %m", path);
949 st = &stbuf;
950 }
951
952 if (hardlink_vulnerable(st))
953 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
954 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
955 path);
956 new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
957 new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
958
959 /* Do we need a chown()? */
960 do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
961
962 /* Calculate the mode to apply */
963 new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
964 (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
965 (st->st_mode & 07777);
966
967 do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
968
969 if (do_chmod && do_chown) {
970 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
971 * the new mode. That way there's no time window where the file exists under the old owner
972 * with more than the old access modes — and not under the new owner with more than the new
973 * access modes either. */
974
975 if (S_ISLNK(st->st_mode))
976 log_debug("Skipping temporary mode fix for symlink %s.", path);
977 else {
978 mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
979
980 if (((m ^ st->st_mode) & 07777) == 0)
981 log_debug("\"%s\" matches temporary mode %o already.", path, m);
982 else {
983 log_debug("Temporarily changing \"%s\" to mode %o.", path, m);
984 r = fchmod_opath(fd, m);
985 if (r < 0)
986 return log_error_errno(r, "fchmod() of %s failed: %m", path);
987 }
988 }
989 }
990
991 if (do_chown) {
992 log_debug("Changing \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
993
994 if (fchownat(fd, "",
995 new_uid != st->st_uid ? new_uid : UID_INVALID,
996 new_gid != st->st_gid ? new_gid : GID_INVALID,
997 AT_EMPTY_PATH) < 0)
998 return log_error_errno(errno, "fchownat() of %s failed: %m", path);
999 }
1000
1001 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
1002 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
1003 if (do_chmod || do_chown) {
1004 if (S_ISLNK(st->st_mode))
1005 log_debug("Skipping mode fix for symlink %s.", path);
1006 else {
1007 log_debug("Changing \"%s\" to mode %o.", path, new_mode);
1008 r = fchmod_opath(fd, new_mode);
1009 if (r < 0)
1010 return log_error_errno(r, "fchmod() of %s failed: %m", path);
1011 }
1012 }
1013
1014shortcut:
1015 return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
1016}
1017
1018static int path_open_parent_safe(const char *path, bool allow_failure) {
1019 _cleanup_free_ char *dn = NULL;
1020 int r, fd;
1021
1022 if (!path_is_normalized(path))
1023 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1024 SYNTHETIC_ERRNO(EINVAL),
1025 "Failed to open parent of '%s': path not normalized%s.",
1026 path,
1027 allow_failure ? ", ignoring" : "");
1028
1029 r = path_extract_directory(path, &dn);
1030 if (r < 0)
1031 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1032 r,
1033 "Unable to determine parent directory of '%s'%s: %m",
1034 path,
1035 allow_failure ? ", ignoring" : "");
1036
1037 r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
1038 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
1039 return r;
1040 if (r < 0)
1041 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1042 r,
1043 "Failed to open path '%s'%s: %m",
1044 dn,
1045 allow_failure ? ", ignoring" : "");
1046
1047 return fd;
1048}
1049
1050static int path_open_safe(const char *path) {
1051 int r, fd;
1052
1053 /* path_open_safe() returns a file descriptor opened with O_PATH after
1054 * verifying that the path doesn't contain unsafe transitions, except
1055 * for its final component as the function does not follow symlink. */
1056
1057 assert(path);
1058
1059 if (!path_is_normalized(path))
1060 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
1061
1062 r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
1063 if (r == -ENOLINK)
1064 return r; /* Unsafe symlink: already covered by CHASE_WARN */
1065 if (r < 0)
1066 return log_error_errno(r, "Failed to open path %s: %m", path);
1067
1068 return fd;
1069}
1070
1071static int path_set_perms(
1072 Context *c,
1073 Item *i,
1074 const char *path,
1075 CreationMode creation) {
1076
1077 _cleanup_close_ int fd = -EBADF;
1078
1079 assert(c);
1080 assert(i);
1081 assert(path);
1082
1083 fd = path_open_safe(path);
1084 if (fd < 0)
1085 return fd;
1086
1087 return fd_set_perms(c, i, fd, path, /* st= */ NULL, creation);
1088}
1089
1090static int parse_xattrs_from_arg(Item *i) {
1091 const char *p;
1092 int r;
1093
1094 assert(i);
1095
1096 assert_se(p = i->argument);
1097 for (;;) {
1098 _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
1099
1100 r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
1101 if (r < 0)
1102 log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
1103 if (r <= 0)
1104 break;
1105
1106 r = split_pair(xattr, "=", &name, &value);
1107 if (r < 0) {
1108 log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
1109 continue;
1110 }
1111
1112 if (isempty(name) || isempty(value)) {
1113 log_warning("Malformed extended attribute found, ignoring: %s", xattr);
1114 continue;
1115 }
1116
1117 if (strv_push_pair(&i->xattrs, name, value) < 0)
1118 return log_oom();
1119
1120 name = value = NULL;
1121 }
1122
1123 return 0;
1124}
1125
1126static int fd_set_xattrs(
1127 Context *c,
1128 Item *i,
1129 int fd,
1130 const char *path,
1131 const struct stat *st,
1132 CreationMode creation) {
1133
1134 assert(c);
1135 assert(i);
1136 assert(fd >= 0);
1137 assert(path);
1138
1139 STRV_FOREACH_PAIR(name, value, i->xattrs) {
1140 log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
1141 if (setxattr(FORMAT_PROC_FD_PATH(fd), *name, *value, strlen(*value), 0) < 0)
1142 return log_error_errno(errno, "Setting extended attribute %s=%s on %s failed: %m",
1143 *name, *value, path);
1144 }
1145 return 0;
1146}
1147
1148static int path_set_xattrs(
1149 Context *c,
1150 Item *i,
1151 const char *path,
1152 CreationMode creation) {
1153
1154 _cleanup_close_ int fd = -EBADF;
1155
1156 assert(c);
1157 assert(i);
1158 assert(path);
1159
1160 fd = path_open_safe(path);
1161 if (fd < 0)
1162 return fd;
1163
1164 return fd_set_xattrs(c, i, fd, path, /* st = */ NULL, creation);
1165}
1166
1167static int parse_acls_from_arg(Item *item) {
1168#if HAVE_ACL
1169 int r;
1170
1171 assert(item);
1172
1173 /* If append_or_force (= modify) is set, we will not modify the acl
1174 * afterwards, so the mask can be added now if necessary. */
1175
1176 r = parse_acl(item->argument, &item->acl_access, &item->acl_access_exec,
1177 &item->acl_default, !item->append_or_force);
1178 if (r < 0)
1179 log_full_errno(arg_graceful && IN_SET(r, -EINVAL, -ENOENT, -ESRCH) ? LOG_DEBUG : LOG_WARNING,
1180 r, "Failed to parse ACL \"%s\", ignoring: %m", item->argument);
1181#else
1182 log_warning("ACLs are not supported, ignoring.");
1183#endif
1184
1185 return 0;
1186}
1187
1188#if HAVE_ACL
1189static int parse_acl_cond_exec(
1190 const char *path,
1191 acl_t access, /* could be empty (NULL) */
1192 acl_t cond_exec,
1193 const struct stat *st,
1194 bool append,
1195 acl_t *ret) {
1196
1197 _cleanup_(acl_freep) acl_t parsed = NULL;
1198 acl_entry_t entry;
1199 acl_permset_t permset;
1200 bool has_exec;
1201 int r;
1202
1203 assert(path);
1204 assert(ret);
1205 assert(st);
1206
1207 parsed = access ? acl_dup(access) : acl_init(0);
1208 if (!parsed)
1209 return -errno;
1210
1211 /* Since we substitute 'X' with 'x' in parse_acl(), we just need to copy the entries over
1212 * for directories */
1213 if (S_ISDIR(st->st_mode)) {
1214 for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
1215 r > 0;
1216 r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
1217
1218 acl_entry_t parsed_entry;
1219
1220 if (acl_create_entry(&parsed, &parsed_entry) < 0)
1221 return -errno;
1222
1223 if (acl_copy_entry(parsed_entry, entry) < 0)
1224 return -errno;
1225 }
1226 if (r < 0)
1227 return -errno;
1228
1229 goto finish;
1230 }
1231
1232 has_exec = st->st_mode & S_IXUSR;
1233
1234 if (!has_exec && append) {
1235 _cleanup_(acl_freep) acl_t old = NULL;
1236
1237 old = acl_get_file(path, ACL_TYPE_ACCESS);
1238 if (!old)
1239 return -errno;
1240
1241 for (r = acl_get_entry(old, ACL_FIRST_ENTRY, &entry);
1242 r > 0;
1243 r = acl_get_entry(old, ACL_NEXT_ENTRY, &entry)) {
1244
1245 if (acl_get_permset(entry, &permset) < 0)
1246 return -errno;
1247
1248 r = acl_get_perm(permset, ACL_EXECUTE);
1249 if (r < 0)
1250 return -errno;
1251 if (r > 0) {
1252 has_exec = true;
1253 break;
1254 }
1255 }
1256 if (r < 0)
1257 return -errno;
1258 }
1259
1260 /* Check if we're about to set the execute bit in acl_access */
1261 if (!has_exec && access) {
1262 for (r = acl_get_entry(access, ACL_FIRST_ENTRY, &entry);
1263 r > 0;
1264 r = acl_get_entry(access, ACL_NEXT_ENTRY, &entry)) {
1265
1266 if (acl_get_permset(entry, &permset) < 0)
1267 return -errno;
1268
1269 r = acl_get_perm(permset, ACL_EXECUTE);
1270 if (r < 0)
1271 return -errno;
1272 if (r > 0) {
1273 has_exec = true;
1274 break;
1275 }
1276 }
1277 if (r < 0)
1278 return -errno;
1279 }
1280
1281 for (r = acl_get_entry(cond_exec, ACL_FIRST_ENTRY, &entry);
1282 r > 0;
1283 r = acl_get_entry(cond_exec, ACL_NEXT_ENTRY, &entry)) {
1284
1285 acl_entry_t parsed_entry;
1286
1287 if (acl_create_entry(&parsed, &parsed_entry) < 0)
1288 return -errno;
1289
1290 if (acl_copy_entry(parsed_entry, entry) < 0)
1291 return -errno;
1292
1293 if (!has_exec) {
1294 if (acl_get_permset(parsed_entry, &permset) < 0)
1295 return -errno;
1296
1297 if (acl_delete_perm(permset, ACL_EXECUTE) < 0)
1298 return -errno;
1299 }
1300 }
1301 if (r < 0)
1302 return -errno;
1303
1304finish:
1305 if (!append) { /* want_mask = true */
1306 r = calc_acl_mask_if_needed(&parsed);
1307 if (r < 0)
1308 return r;
1309 }
1310
1311 *ret = TAKE_PTR(parsed);
1312
1313 return 0;
1314}
1315
1316static int path_set_acl(
1317 Context *c,
1318 const char *path,
1319 const char *pretty,
1320 acl_type_t type,
1321 acl_t acl,
1322 bool modify) {
1323
1324 _cleanup_(acl_free_charpp) char *t = NULL;
1325 _cleanup_(acl_freep) acl_t dup = NULL;
1326 int r;
1327
1328 assert(c);
1329
1330 /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1331
1332 if (modify) {
1333 r = acls_for_file(path, type, acl, &dup);
1334 if (r < 0)
1335 return r;
1336
1337 r = calc_acl_mask_if_needed(&dup);
1338 if (r < 0)
1339 return r;
1340 } else {
1341 dup = acl_dup(acl);
1342 if (!dup)
1343 return -errno;
1344
1345 /* the mask was already added earlier if needed */
1346 }
1347
1348 r = add_base_acls_if_needed(&dup, path);
1349 if (r < 0)
1350 return r;
1351
1352 t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1353 log_debug("Setting %s ACL %s on %s.",
1354 type == ACL_TYPE_ACCESS ? "access" : "default",
1355 strna(t), pretty);
1356
1357 r = acl_set_file(path, type, dup);
1358 if (r < 0) {
1359 if (ERRNO_IS_NOT_SUPPORTED(errno))
1360 /* No error if filesystem doesn't support ACLs. Return negative. */
1361 return -errno;
1362 else
1363 /* Return positive to indicate we already warned */
1364 return -log_error_errno(errno,
1365 "Setting %s ACL \"%s\" on %s failed: %m",
1366 type == ACL_TYPE_ACCESS ? "access" : "default",
1367 strna(t), pretty);
1368 }
1369 return 0;
1370}
1371#endif
1372
1373static int fd_set_acls(
1374 Context *c,
1375 Item *item,
1376 int fd,
1377 const char *path,
1378 const struct stat *st,
1379 CreationMode creation) {
1380
1381 int r = 0;
1382#if HAVE_ACL
1383 _cleanup_(acl_freep) acl_t access_with_exec_parsed = NULL;
1384 struct stat stbuf;
1385
1386 assert(c);
1387 assert(item);
1388 assert(fd >= 0);
1389 assert(path);
1390
1391 if (!st) {
1392 if (fstat(fd, &stbuf) < 0)
1393 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1394 st = &stbuf;
1395 }
1396
1397 if (hardlink_vulnerable(st))
1398 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1399 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1400 path);
1401
1402 if (S_ISLNK(st->st_mode)) {
1403 log_debug("Skipping ACL fix for symlink %s.", path);
1404 return 0;
1405 }
1406
1407 if (item->acl_access_exec) {
1408 r = parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd),
1409 item->acl_access,
1410 item->acl_access_exec,
1411 st,
1412 item->append_or_force,
1413 &access_with_exec_parsed);
1414 if (r < 0)
1415 return log_error_errno(r, "Failed to parse conditionalized execute bit for \"%s\": %m", path);
1416
1417 r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, access_with_exec_parsed, item->append_or_force);
1418 } else if (item->acl_access)
1419 r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
1420
1421 /* set only default acls to folders */
1422 if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
1423 r = path_set_acl(c, FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
1424
1425 if (ERRNO_IS_NOT_SUPPORTED(r)) {
1426 log_debug_errno(r, "ACLs not supported by file system at %s", path);
1427 return 0;
1428 }
1429
1430 if (r > 0)
1431 return -r; /* already warned in path_set_acl */
1432
1433 /* The above procfs paths don't work if /proc is not mounted. */
1434 if (r == -ENOENT && proc_mounted() == 0)
1435 r = -ENOSYS;
1436
1437 if (r < 0)
1438 return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
1439#endif
1440 return r;
1441}
1442
1443static int path_set_acls(
1444 Context *c,
1445 Item *item,
1446 const char *path,
1447 CreationMode creation) {
1448
1449 int r = 0;
1450#if HAVE_ACL
1451 _cleanup_close_ int fd = -EBADF;
1452
1453 assert(c);
1454 assert(item);
1455 assert(path);
1456
1457 fd = path_open_safe(path);
1458 if (fd < 0)
1459 return fd;
1460
1461 r = fd_set_acls(c, item, fd, path, /* st= */ NULL, creation);
1462#endif
1463 return r;
1464}
1465
1466static int parse_attribute_from_arg(Item *item) {
1467 static const struct {
1468 char character;
1469 unsigned value;
1470 } attributes[] = {
1471 { 'A', FS_NOATIME_FL }, /* do not update atime */
1472 { 'S', FS_SYNC_FL }, /* Synchronous updates */
1473 { 'D', FS_DIRSYNC_FL }, /* dirsync behaviour (directories only) */
1474 { 'a', FS_APPEND_FL }, /* writes to file may only append */
1475 { 'c', FS_COMPR_FL }, /* Compress file */
1476 { 'd', FS_NODUMP_FL }, /* do not dump file */
1477 { 'e', FS_EXTENT_FL }, /* Extents */
1478 { 'i', FS_IMMUTABLE_FL }, /* Immutable file */
1479 { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1480 { 's', FS_SECRM_FL }, /* Secure deletion */
1481 { 'u', FS_UNRM_FL }, /* Undelete */
1482 { 't', FS_NOTAIL_FL }, /* file tail should not be merged */
1483 { 'T', FS_TOPDIR_FL }, /* Top of directory hierarchies */
1484 { 'C', FS_NOCOW_FL }, /* Do not cow file */
1485 { 'P', FS_PROJINHERIT_FL }, /* Inherit the quota project ID */
1486 };
1487
1488 enum {
1489 MODE_ADD,
1490 MODE_DEL,
1491 MODE_SET
1492 } mode = MODE_ADD;
1493
1494 unsigned value = 0, mask = 0;
1495 const char *p;
1496
1497 assert(item);
1498
1499 p = item->argument;
1500 if (p) {
1501 if (*p == '+') {
1502 mode = MODE_ADD;
1503 p++;
1504 } else if (*p == '-') {
1505 mode = MODE_DEL;
1506 p++;
1507 } else if (*p == '=') {
1508 mode = MODE_SET;
1509 p++;
1510 }
1511 }
1512
1513 if (isempty(p) && mode != MODE_SET)
1514 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1515 "Setting file attribute on '%s' needs an attribute specification.",
1516 item->path);
1517
1518 for (; p && *p ; p++) {
1519 unsigned i, v;
1520
1521 for (i = 0; i < ELEMENTSOF(attributes); i++)
1522 if (*p == attributes[i].character)
1523 break;
1524
1525 if (i >= ELEMENTSOF(attributes))
1526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1527 "Unknown file attribute '%c' on '%s'.",
1528 *p, item->path);
1529
1530 v = attributes[i].value;
1531
1532 SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1533
1534 mask |= v;
1535 }
1536
1537 if (mode == MODE_SET)
1538 mask |= CHATTR_ALL_FL;
1539
1540 assert(mask != 0);
1541
1542 item->attribute_mask = mask;
1543 item->attribute_value = value;
1544 item->attribute_set = true;
1545
1546 return 0;
1547}
1548
1549static int fd_set_attribute(
1550 Context *c,
1551 Item *item,
1552 int fd,
1553 const char *path,
1554 const struct stat *st,
1555 CreationMode creation) {
1556
1557 _cleanup_close_ int procfs_fd = -EBADF;
1558 struct stat stbuf;
1559 unsigned f;
1560 int r;
1561
1562 assert(c);
1563 assert(item);
1564 assert(fd >= 0);
1565 assert(path);
1566
1567 if (!item->attribute_set || item->attribute_mask == 0)
1568 return 0;
1569
1570 if (!st) {
1571 if (fstat(fd, &stbuf) < 0)
1572 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1573 st = &stbuf;
1574 }
1575
1576 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1577 * drivers, not the file system containing the device node. */
1578 if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode))
1579 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1580 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1581 path);
1582
1583 f = item->attribute_value & item->attribute_mask;
1584
1585 /* Mask away directory-specific flags */
1586 if (!S_ISDIR(st->st_mode))
1587 f &= ~FS_DIRSYNC_FL;
1588
1589 procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
1590 if (procfs_fd < 0)
1591 return log_error_errno(procfs_fd, "Failed to re-open '%s': %m", path);
1592
1593 unsigned previous, current;
1594 r = chattr_full(procfs_fd, NULL, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
1595 if (r == -ENOANO)
1596 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1597 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1598 path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1599 else if (r < 0)
1600 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
1601 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1602 path, item->attribute_value, item->attribute_mask);
1603
1604 return 0;
1605}
1606
1607static int path_set_attribute(
1608 Context *c,
1609 Item *item,
1610 const char *path,
1611 CreationMode creation) {
1612
1613 _cleanup_close_ int fd = -EBADF;
1614
1615 assert(c);
1616 assert(item);
1617
1618 if (!item->attribute_set || item->attribute_mask == 0)
1619 return 0;
1620
1621 fd = path_open_safe(path);
1622 if (fd < 0)
1623 return fd;
1624
1625 return fd_set_attribute(c, item, fd, path, /* st= */ NULL, creation);
1626}
1627
1628static int write_argument_data(Item *i, int fd, const char *path) {
1629 int r;
1630
1631 assert(i);
1632 assert(fd >= 0);
1633 assert(path);
1634
1635 if (item_binary_argument_size(i) == 0)
1636 return 0;
1637
1638 assert(item_binary_argument(i));
1639
1640 log_debug("Writing to \"%s\".", path);
1641
1642 r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i));
1643 if (r < 0)
1644 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
1645
1646 return 0;
1647}
1648
1649static int write_one_file(Context *c, Item *i, const char *path, CreationMode creation) {
1650 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1651 _cleanup_free_ char *bn = NULL;
1652 int r;
1653
1654 assert(c);
1655 assert(i);
1656 assert(path);
1657 assert(i->type == WRITE_FILE);
1658
1659 r = path_extract_filename(path, &bn);
1660 if (r < 0)
1661 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1662 if (r == O_DIRECTORY)
1663 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1664
1665 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1666 * can't be changed behind our back. */
1667 dir_fd = path_open_parent_safe(path, i->allow_failure);
1668 if (dir_fd < 0)
1669 return dir_fd;
1670
1671 /* Follows symlinks */
1672 fd = openat(dir_fd, bn,
1673 O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY|(i->append_or_force ? O_APPEND : 0),
1674 i->mode);
1675 if (fd < 0) {
1676 if (errno == ENOENT) {
1677 log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
1678 return 0;
1679 }
1680
1681 if (i->allow_failure)
1682 return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
1683
1684 return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
1685 }
1686
1687 /* 'w' is allowed to write into any kind of files. */
1688
1689 r = write_argument_data(i, fd, path);
1690 if (r < 0)
1691 return r;
1692
1693 return fd_set_perms(c, i, fd, path, NULL, creation);
1694}
1695
1696static int create_file(
1697 Context *c,
1698 Item *i,
1699 const char *path) {
1700
1701 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1702 _cleanup_free_ char *bn = NULL;
1703 struct stat stbuf, *st = NULL;
1704 CreationMode creation;
1705 int r = 0;
1706
1707 assert(c);
1708 assert(i);
1709 assert(path);
1710 assert(i->type == CREATE_FILE);
1711
1712 /* 'f' operates on regular files exclusively. */
1713
1714 r = path_extract_filename(path, &bn);
1715 if (r < 0)
1716 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1717 if (r == O_DIRECTORY)
1718 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1719
1720 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1721 * can't be changed behind our back. */
1722 dir_fd = path_open_parent_safe(path, i->allow_failure);
1723 if (dir_fd < 0)
1724 return dir_fd;
1725
1726 WITH_UMASK(0000) {
1727 mac_selinux_create_file_prepare(path, S_IFREG);
1728 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1729 mac_selinux_create_file_clear();
1730 }
1731
1732 if (fd < 0) {
1733 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1734 * returns EROFS only if it needs to create the file. */
1735 if (fd != -EEXIST)
1736 return log_error_errno(fd, "Failed to create file %s: %m", path);
1737
1738 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1739 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1740 * fd_set_perms() report the error if the perms need to be modified. */
1741 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1742 if (fd < 0)
1743 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1744
1745 if (fstat(fd, &stbuf) < 0)
1746 return log_error_errno(errno, "stat(%s) failed: %m", path);
1747
1748 if (!S_ISREG(stbuf.st_mode))
1749 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1750 "%s exists and is not a regular file.",
1751 path);
1752
1753 st = &stbuf;
1754 creation = CREATION_EXISTING;
1755 } else {
1756 r = write_argument_data(i, fd, path);
1757 if (r < 0)
1758 return r;
1759
1760 creation = CREATION_NORMAL;
1761 }
1762
1763 return fd_set_perms(c, i, fd, path, st, creation);
1764}
1765
1766static int truncate_file(
1767 Context *c,
1768 Item *i,
1769 const char *path) {
1770
1771 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1772 _cleanup_free_ char *bn = NULL;
1773 struct stat stbuf, *st = NULL;
1774 CreationMode creation;
1775 bool erofs = false;
1776 int r = 0;
1777
1778 assert(c);
1779 assert(i);
1780 assert(path);
1781 assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
1782
1783 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1784 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1785 * make sure it's a regular one before truncating it. */
1786
1787 r = path_extract_filename(path, &bn);
1788 if (r < 0)
1789 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1790 if (r == O_DIRECTORY)
1791 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
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);
1796 if (dir_fd < 0)
1797 return dir_fd;
1798
1799 creation = CREATION_EXISTING;
1800 fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1801 if (fd == -ENOENT) {
1802 creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
1803
1804 WITH_UMASK(0000) {
1805 mac_selinux_create_file_prepare(path, S_IFREG);
1806 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1807 mac_selinux_create_file_clear();
1808 }
1809 }
1810
1811 if (fd < 0) {
1812 if (fd != -EROFS)
1813 return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1814
1815 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1816 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1817 * fail with EROFS if they try to modify the target file. */
1818
1819 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1820 if (fd < 0) {
1821 if (errno == ENOENT)
1822 return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1823 "Cannot create file %s on a read-only file system.",
1824 path);
1825
1826 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1827 }
1828
1829 erofs = true;
1830 creation = CREATION_EXISTING;
1831 }
1832
1833 if (fstat(fd, &stbuf) < 0)
1834 return log_error_errno(errno, "stat(%s) failed: %m", path);
1835
1836 if (!S_ISREG(stbuf.st_mode))
1837 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1838 "%s exists and is not a regular file.",
1839 path);
1840
1841 if (stbuf.st_size > 0) {
1842 if (ftruncate(fd, 0) < 0) {
1843 r = erofs ? -EROFS : -errno;
1844 return log_error_errno(r, "Failed to truncate file %s: %m", path);
1845 }
1846 } else
1847 st = &stbuf;
1848
1849 log_debug("\"%s\" has been created.", path);
1850
1851 if (item_binary_argument(i)) {
1852 r = write_argument_data(i, fd, path);
1853 if (r < 0)
1854 return r;
1855 }
1856
1857 return fd_set_perms(c, i, fd, path, st, creation);
1858}
1859
1860static int copy_files(Context *c, Item *i) {
1861 _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
1862 _cleanup_free_ char *bn = NULL;
1863 struct stat st, a;
1864 int r;
1865
1866 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
1867
1868 r = path_extract_filename(i->path, &bn);
1869 if (r < 0)
1870 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
1871
1872 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1873 * path can't be changed behind our back. */
1874 dfd = path_open_parent_safe(i->path, i->allow_failure);
1875 if (dfd < 0)
1876 return dfd;
1877
1878 r = copy_tree_at(AT_FDCWD, i->argument,
1879 dfd, bn,
1880 i->uid_set ? i->uid : UID_INVALID,
1881 i->gid_set ? i->gid : GID_INVALID,
1882 COPY_REFLINK | ((i->append_or_force) ? COPY_MERGE : COPY_MERGE_EMPTY) | COPY_MAC_CREATE | COPY_HARDLINKS,
1883 NULL, NULL);
1884
1885 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1886 if (fd < 0) {
1887 if (r < 0) /* Look at original error first */
1888 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
1889
1890 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1891 }
1892
1893 if (fstat(fd, &st) < 0)
1894 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1895
1896 if (stat(i->argument, &a) < 0)
1897 return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
1898
1899 if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
1900 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1901 return 0;
1902 }
1903
1904 return fd_set_perms(c, i, fd, i->path, &st, _CREATION_MODE_INVALID);
1905}
1906
1907static int create_directory_or_subvolume(
1908 const char *path,
1909 mode_t mode,
1910 bool subvol,
1911 bool allow_failure,
1912 struct stat *ret_st,
1913 CreationMode *ret_creation) {
1914
1915 _cleanup_free_ char *bn = NULL;
1916 _cleanup_close_ int pfd = -EBADF;
1917 CreationMode creation;
1918 struct stat st;
1919 int r, fd;
1920
1921 assert(path);
1922
1923 r = path_extract_filename(path, &bn);
1924 if (r < 0)
1925 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1926
1927 pfd = path_open_parent_safe(path, allow_failure);
1928 if (pfd < 0)
1929 return pfd;
1930
1931 if (subvol) {
1932 r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1933 if (r < 0) {
1934 if (r != -ENXIO) /* env var is unset */
1935 log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1936 r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
1937 }
1938 if (r == 0)
1939 /* Don't create a subvolume unless the root directory is one, too. We do this under
1940 * the assumption that if the root directory is just a plain directory (i.e. very
1941 * light-weight), we shouldn't try to split it up into subvolumes (i.e. more
1942 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1943 * subvolume set up below their tree only if they specifically set up a btrfs
1944 * subvolume for the root dir too. */
1945
1946 subvol = false;
1947 else {
1948 WITH_UMASK((~mode) & 0777)
1949 r = btrfs_subvol_make(pfd, bn);
1950 }
1951 } else
1952 r = 0;
1953
1954 if (!subvol || ERRNO_IS_NEG_NOT_SUPPORTED(r))
1955 WITH_UMASK(0000)
1956 r = mkdirat_label(pfd, bn, mode);
1957
1958 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1959
1960 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
1961 if (fd < 0) {
1962 /* We couldn't open it because it is not actually a directory? */
1963 if (errno == ENOTDIR)
1964 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
1965
1966 /* Then look at the original error */
1967 if (r < 0)
1968 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1969 r,
1970 "Failed to create directory or subvolume \"%s\"%s: %m",
1971 path,
1972 allow_failure ? ", ignoring" : "");
1973
1974 return log_error_errno(errno, "Failed to open directory/subvolume we just created '%s': %m", path);
1975 }
1976
1977 if (fstat(fd, &st) < 0)
1978 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
1979
1980 assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
1981
1982 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
1983
1984 if (ret_st)
1985 *ret_st = st;
1986 if (ret_creation)
1987 *ret_creation = creation;
1988
1989 return fd;
1990}
1991
1992static int create_directory(
1993 Context *c,
1994 Item *i,
1995 const char *path) {
1996
1997 _cleanup_close_ int fd = -EBADF;
1998 CreationMode creation;
1999 struct stat st;
2000
2001 assert(c);
2002 assert(i);
2003 assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
2004
2005 fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
2006 if (fd == -EEXIST)
2007 return 0;
2008 if (fd < 0)
2009 return fd;
2010
2011 return fd_set_perms(c, i, fd, path, &st, creation);
2012}
2013
2014static int create_subvolume(
2015 Context *c,
2016 Item *i,
2017 const char *path) {
2018
2019 _cleanup_close_ int fd = -EBADF;
2020 CreationMode creation;
2021 struct stat st;
2022 int r, q = 0;
2023
2024 assert(c);
2025 assert(i);
2026 assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
2027
2028 fd = create_directory_or_subvolume(path, i->mode, /* subvol = */ true, i->allow_failure, &st, &creation);
2029 if (fd == -EEXIST)
2030 return 0;
2031 if (fd < 0)
2032 return fd;
2033
2034 if (creation == CREATION_NORMAL &&
2035 IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
2036 r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
2037 if (r == -ENOTTY)
2038 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
2039 else if (r == -EROFS)
2040 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
2041 else if (r == -ENOTCONN)
2042 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
2043 else if (r < 0)
2044 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
2045 else if (r > 0)
2046 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
2047 else if (r == 0)
2048 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
2049 }
2050
2051 r = fd_set_perms(c, i, fd, path, &st, creation);
2052 if (q < 0) /* prefer the quota change error from above */
2053 return q;
2054
2055 return r;
2056}
2057
2058static int empty_directory(
2059 Context *c,
2060 Item *i,
2061 const char *path,
2062 CreationMode creation) {
2063
2064 _cleanup_close_ int fd = -EBADF;
2065 struct stat st;
2066 int r;
2067
2068 assert(c);
2069 assert(i);
2070 assert(i->type == EMPTY_DIRECTORY);
2071
2072 r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
2073 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
2074 return r;
2075 if (r == -ENOENT) {
2076 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
2077 * or directories */
2078 log_debug_errno(r, "Skipping missing directory: %s", path);
2079 return 0;
2080 }
2081 if (r < 0)
2082 return log_error_errno(r, "Failed to open directory '%s': %m", path);
2083
2084 if (fstat(fd, &st) < 0)
2085 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
2086 if (!S_ISDIR(st.st_mode)) {
2087 log_warning("'%s' already exists and is not a directory.", path);
2088 return 0;
2089 }
2090
2091 return fd_set_perms(c, i, fd, path, &st, creation);
2092}
2093
2094static int create_device(
2095 Context *c,
2096 Item *i,
2097 mode_t file_type) {
2098
2099 _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
2100 _cleanup_free_ char *bn = NULL;
2101 CreationMode creation;
2102 struct stat st;
2103 int r;
2104
2105 assert(c);
2106 assert(i);
2107 assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
2108 assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
2109
2110 r = path_extract_filename(i->path, &bn);
2111 if (r < 0)
2112 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
2113 if (r == O_DIRECTORY)
2114 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating device node, is a directory.", i->path);
2115
2116 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2117 * path can't be changed behind our back. */
2118 dfd = path_open_parent_safe(i->path, i->allow_failure);
2119 if (dfd < 0)
2120 return dfd;
2121
2122 WITH_UMASK(0000) {
2123 mac_selinux_create_file_prepare(i->path, file_type);
2124 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
2125 mac_selinux_create_file_clear();
2126 }
2127 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2128
2129 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2130 * order anyway and we hence can ignore the error to create the device node */
2131 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2132 if (fd < 0) {
2133 /* OK, so opening the inode failed, let's look at the original error then. */
2134
2135 if (r < 0) {
2136 if (ERRNO_IS_PRIVILEGE(r))
2137 goto handle_privilege;
2138
2139 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
2140 }
2141
2142 return log_error_errno(errno, "Failed to open device node '%s' we just created: %m", i->path);
2143 }
2144
2145 if (fstat(fd, &st) < 0)
2146 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2147
2148 if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
2149
2150 if (i->append_or_force) {
2151 fd = safe_close(fd);
2152
2153 WITH_UMASK(0000) {
2154 mac_selinux_create_file_prepare(i->path, file_type);
2155 r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
2156 mac_selinux_create_file_clear();
2157 }
2158 if (ERRNO_IS_PRIVILEGE(r))
2159 goto handle_privilege;
2160 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2161 r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
2162 if (r < 0)
2163 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2164
2165 mac_selinux_create_file_prepare(i->path, file_type);
2166 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
2167 mac_selinux_create_file_clear();
2168 }
2169 if (r < 0)
2170 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
2171
2172 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2173 if (fd < 0)
2174 return log_error_errno(errno, "Failed to open device node we just created '%s': %m", i->path);
2175
2176 /* Validate type before change ownership below */
2177 if (fstat(fd, &st) < 0)
2178 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2179
2180 if (((st.st_mode ^ file_type) & S_IFMT) != 0)
2181 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Device node we just created is not a device node, refusing.");
2182
2183 creation = CREATION_FORCE;
2184 } else {
2185 log_warning("\"%s\" already exists and is not a device node.", i->path);
2186 return 0;
2187 }
2188 }
2189
2190 log_debug("%s %s device node \"%s\" %u:%u.",
2191 creation_mode_verb_to_string(creation),
2192 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
2193 i->path, major(i->mode), minor(i->mode));
2194
2195 return fd_set_perms(c, i, fd, i->path, &st, creation);
2196
2197handle_privilege:
2198 log_debug_errno(r,
2199 "We lack permissions, possibly because of cgroup configuration; "
2200 "skipping creation of device node '%s'.", i->path);
2201 return 0;
2202}
2203
2204static int create_fifo(Context *c, Item *i) {
2205 _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
2206 _cleanup_free_ char *bn = NULL;
2207 CreationMode creation;
2208 struct stat st;
2209 int r;
2210
2211 assert(c);
2212 assert(i);
2213 assert(i->type == CREATE_FIFO);
2214
2215 r = path_extract_filename(i->path, &bn);
2216 if (r < 0)
2217 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
2218 if (r == O_DIRECTORY)
2219 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2220
2221 pfd = path_open_parent_safe(i->path, i->allow_failure);
2222 if (pfd < 0)
2223 return pfd;
2224
2225 WITH_UMASK(0000) {
2226 mac_selinux_create_file_prepare(i->path, S_IFIFO);
2227 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
2228 mac_selinux_create_file_clear();
2229 }
2230
2231 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2232
2233 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
2234 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2235 if (fd < 0) {
2236 if (r < 0)
2237 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path); /* original error! */
2238
2239 return log_error_errno(errno, "Failed to open FIFO we just created %s: %m", i->path);
2240 }
2241
2242 if (fstat(fd, &st) < 0)
2243 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2244
2245 if (!S_ISFIFO(st.st_mode)) {
2246
2247 if (i->append_or_force) {
2248 fd = safe_close(fd);
2249
2250 WITH_UMASK(0000) {
2251 mac_selinux_create_file_prepare(i->path, S_IFIFO);
2252 r = mkfifoat_atomic(pfd, bn, i->mode);
2253 mac_selinux_create_file_clear();
2254 }
2255 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2256 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
2257 if (r < 0)
2258 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2259
2260 mac_selinux_create_file_prepare(i->path, S_IFIFO);
2261 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
2262 mac_selinux_create_file_clear();
2263 }
2264 if (r < 0)
2265 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
2266
2267 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2268 if (fd < 0)
2269 return log_error_errno(errno, "Failed to open FIFO we just created '%s': %m", i->path);
2270
2271 /* Validate type before change ownership below */
2272 if (fstat(fd, &st) < 0)
2273 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2274
2275 if (!S_ISFIFO(st.st_mode))
2276 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "FIFO inode we just created is not a FIFO, refusing.");
2277
2278 creation = CREATION_FORCE;
2279 } else {
2280 log_warning("\"%s\" already exists and is not a FIFO.", i->path);
2281 return 0;
2282 }
2283 }
2284
2285 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
2286
2287 return fd_set_perms(c, i, fd, i->path, &st, creation);
2288}
2289
2290static int create_symlink(Context *c, Item *i) {
2291 _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
2292 _cleanup_free_ char *bn = NULL;
2293 CreationMode creation;
2294 struct stat st;
2295 bool good = false;
2296 int r;
2297
2298 assert(c);
2299 assert(i);
2300
2301 r = path_extract_filename(i->path, &bn);
2302 if (r < 0)
2303 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
2304 if (r == O_DIRECTORY)
2305 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2306
2307 pfd = path_open_parent_safe(i->path, i->allow_failure);
2308 if (pfd < 0)
2309 return pfd;
2310
2311 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2312 r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
2313 mac_selinux_create_file_clear();
2314
2315 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2316
2317 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2318 if (fd < 0) {
2319 if (r < 0)
2320 return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
2321
2322 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2323 }
2324
2325 if (fstat(fd, &st) < 0)
2326 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2327
2328 if (S_ISLNK(st.st_mode)) {
2329 _cleanup_free_ char *x = NULL;
2330
2331 r = readlinkat_malloc(fd, "", &x);
2332 if (r < 0)
2333 return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
2334
2335 good = streq(x, i->argument);
2336 } else
2337 good = false;
2338
2339 if (!good) {
2340 if (!i->append_or_force) {
2341 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
2342 return 0;
2343 }
2344
2345 fd = safe_close(fd);
2346
2347 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2348 r = symlinkat_atomic_full(i->argument, pfd, bn, /* make_relative= */ false);
2349 mac_selinux_create_file_clear();
2350 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2351 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
2352 if (r < 0)
2353 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2354
2355 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2356 r = RET_NERRNO(symlinkat(i->argument, pfd, i->path));
2357 mac_selinux_create_file_clear();
2358 }
2359 if (r < 0)
2360 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
2361
2362 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2363 if (fd < 0)
2364 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2365
2366 /* Validate type before change ownership below */
2367 if (fstat(fd, &st) < 0)
2368 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2369
2370 if (!S_ISLNK(st.st_mode))
2371 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
2372
2373 creation = CREATION_FORCE;
2374 }
2375
2376 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
2377 return fd_set_perms(c, i, fd, i->path, &st, creation);
2378}
2379
2380typedef int (*action_t)(Context *c, Item *i, const char *path, CreationMode creation);
2381typedef int (*fdaction_t)(Context *c, Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2382
2383static int item_do(
2384 Context *c,
2385 Item *i,
2386 int fd,
2387 const char *path,
2388 CreationMode creation,
2389 fdaction_t action) {
2390
2391 struct stat st;
2392 int r = 0, q;
2393
2394 assert(c);
2395 assert(i);
2396 assert(path);
2397 assert(fd >= 0);
2398
2399 if (fstat(fd, &st) < 0) {
2400 r = log_error_errno(errno, "fstat() on file failed: %m");
2401 goto finish;
2402 }
2403
2404 /* This returns the first error we run into, but nevertheless tries to go on */
2405 r = action(c, i, fd, path, &st, creation);
2406
2407 if (S_ISDIR(st.st_mode)) {
2408 _cleanup_closedir_ DIR *d = NULL;
2409
2410 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2411 * reading the directory content. */
2412 d = opendir(FORMAT_PROC_FD_PATH(fd));
2413 if (!d) {
2414 log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd));
2415 if (r == 0)
2416 r = -errno;
2417 goto finish;
2418 }
2419
2420 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
2421 int de_fd;
2422
2423 if (dot_or_dot_dot(de->d_name))
2424 continue;
2425
2426 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2427 if (de_fd < 0)
2428 q = log_error_errno(errno, "Failed to open() file '%s': %m", de->d_name);
2429 else {
2430 _cleanup_free_ char *de_path = NULL;
2431
2432 de_path = path_join(path, de->d_name);
2433 if (!de_path)
2434 q = log_oom();
2435 else
2436 /* Pass ownership of dirent fd over */
2437 q = item_do(c, i, de_fd, de_path, CREATION_EXISTING, action);
2438 }
2439
2440 if (q < 0 && r == 0)
2441 r = q;
2442 }
2443 }
2444finish:
2445 safe_close(fd);
2446 return r;
2447}
2448
2449static int glob_item(Context *c, Item *i, action_t action) {
2450 _cleanup_globfree_ glob_t g = {
2451 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2452 };
2453 int r = 0, k;
2454
2455 assert(c);
2456 assert(i);
2457
2458 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2459 if (k < 0 && k != -ENOENT)
2460 return log_error_errno(k, "glob(%s) failed: %m", i->path);
2461
2462 STRV_FOREACH(fn, g.gl_pathv) {
2463 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2464 k = action(c, i, *fn, CREATION_EXISTING);
2465 if (k < 0 && r == 0)
2466 r = k;
2467 }
2468
2469 return r;
2470}
2471
2472static int glob_item_recursively(
2473 Context *c,
2474 Item *i,
2475 fdaction_t action) {
2476
2477 _cleanup_globfree_ glob_t g = {
2478 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2479 };
2480 int r = 0, k;
2481
2482 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2483 if (k < 0 && k != -ENOENT)
2484 return log_error_errno(k, "glob(%s) failed: %m", i->path);
2485
2486 STRV_FOREACH(fn, g.gl_pathv) {
2487 _cleanup_close_ int fd = -EBADF;
2488
2489 /* Make sure we won't trigger/follow file object (such as
2490 * device nodes, automounts, ...) pointed out by 'fn' with
2491 * O_PATH. Note, when O_PATH is used, flags other than
2492 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2493
2494 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
2495 if (fd < 0) {
2496 log_error_errno(errno, "Opening '%s' failed: %m", *fn);
2497 if (r == 0)
2498 r = -errno;
2499 continue;
2500 }
2501
2502 k = item_do(c, i, fd, *fn, CREATION_EXISTING, action);
2503 if (k < 0 && r == 0)
2504 r = k;
2505
2506 /* we passed fd ownership to the previous call */
2507 fd = -EBADF;
2508 }
2509
2510 return r;
2511}
2512
2513static int rm_if_wrong_type_safe(
2514 mode_t mode,
2515 int parent_fd,
2516 const struct stat *parent_st, /* Only used if follow_links below is true. */
2517 const char *name,
2518 int flags) {
2519 _cleanup_free_ char *parent_name = NULL;
2520 bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
2521 struct stat st;
2522 int r;
2523
2524 assert(name);
2525 assert((mode & ~S_IFMT) == 0);
2526 assert(!follow_links || parent_st);
2527 assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
2528
2529 if (!filename_is_valid(name))
2530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
2531
2532 r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2533 if (r < 0) {
2534 (void) fd_get_path(parent_fd, &parent_name);
2535 return log_full_errno(r == -ENOENT? LOG_DEBUG : LOG_ERR, r,
2536 "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2537 }
2538
2539 /* Fail before removing anything if this is an unsafe transition. */
2540 if (follow_links && unsafe_transition(parent_st, &st)) {
2541 (void) fd_get_path(parent_fd, &parent_name);
2542 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
2543 "Unsafe transition from \"%s\" to \"%s\".", parent_name, name);
2544 }
2545
2546 if ((st.st_mode & S_IFMT) == mode)
2547 return 0;
2548
2549 (void) fd_get_path(parent_fd, &parent_name);
2550 log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, strna(parent_name), name);
2551
2552 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2553 * target, so make sure it is identified as a link and not a directory. */
2554 if (follow_links) {
2555 r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2556 if (r < 0)
2557 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2558 }
2559
2560 /* Do not remove mount points. */
2561 r = fd_is_mount_point(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
2562 if (r < 0)
2563 (void) log_warning_errno(r, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2564 strna(parent_name), name);
2565 else if (r > 0)
2566 return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
2567 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name), name);
2568
2569 if ((st.st_mode & S_IFMT) == S_IFDIR) {
2570 _cleanup_close_ int child_fd = -EBADF;
2571
2572 child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2573 if (child_fd < 0)
2574 return log_error_errno(errno, "Failed to open \"%s\" at \"%s\": %m", name, strna(parent_name));
2575
2576 r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);
2577 if (r < 0)
2578 return log_error_errno(r, "Failed to remove contents of \"%s\" at \"%s\": %m", name, strna(parent_name));
2579
2580 r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2581 } else
2582 r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2583 if (r < 0)
2584 return log_error_errno(r, "Failed to remove \"%s\" at \"%s\": %m", name, strna(parent_name));
2585
2586 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2587 * context to other error messages that might follow. */
2588 return -ENOENT;
2589}
2590
2591/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2592static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
2593 _cleanup_close_ int parent_fd = -EBADF;
2594 struct stat parent_st;
2595 size_t path_len;
2596 int r;
2597
2598 assert(path);
2599 assert((child_mode & ~S_IFMT) == 0);
2600
2601 path_len = strlen(path);
2602
2603 if (!is_path(path))
2604 /* rm_if_wrong_type_safe already logs errors. */
2605 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW) : 0;
2606
2607 if (child_mode != 0 && endswith(path, "/"))
2608 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2609 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2610
2611 /* Get the parent_fd and stat. */
2612 parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2613 if (parent_fd < 0)
2614 return log_error_errno(errno, "Failed to open root: %m");
2615
2616 if (fstat(parent_fd, &parent_st) < 0)
2617 return log_error_errno(errno, "Failed to stat root: %m");
2618
2619 /* Check every parent directory in the path, except the last component */
2620 for (const char *e = path;;) {
2621 _cleanup_close_ int next_fd = -EBADF;
2622 char t[path_len + 1];
2623 const char *s;
2624
2625 /* Find the start of the next path component. */
2626 s = e + strspn(e, "/");
2627 /* Find the end of the next path component. */
2628 e = s + strcspn(s, "/");
2629
2630 /* Copy the path component to t so it can be a null terminated string. */
2631 *((char*) mempcpy(t, s, e - s)) = 0;
2632
2633 /* Is this the last component? If so, then check the type */
2634 if (*e == 0)
2635 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW) : 0;
2636
2637 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
2638 /* Remove dangling symlinks. */
2639 if (r == -ENOENT)
2640 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
2641 if (r == -ENOENT) {
2642 WITH_UMASK(0000)
2643 r = mkdirat_label(parent_fd, t, 0755);
2644 if (r < 0) {
2645 _cleanup_free_ char *parent_name = NULL;
2646
2647 (void) fd_get_path(parent_fd, &parent_name);
2648 return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
2649 }
2650 } else if (r < 0)
2651 /* rm_if_wrong_type_safe already logs errors. */
2652 return r;
2653
2654 next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
2655 if (next_fd < 0) {
2656 _cleanup_free_ char *parent_name = NULL;
2657
2658 (void) fd_get_path(parent_fd, &parent_name);
2659 return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
2660 }
2661 r = RET_NERRNO(fstat(next_fd, &parent_st));
2662 if (r < 0) {
2663 _cleanup_free_ char *parent_name = NULL;
2664
2665 (void) fd_get_path(parent_fd, &parent_name);
2666 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
2667 }
2668
2669 close_and_replace(parent_fd, next_fd);
2670 }
2671}
2672
2673static int mkdir_parents_item(Item *i, mode_t child_mode) {
2674 int r;
2675 if (i->try_replace) {
2676 r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
2677 if (r < 0 && r != -ENOENT)
2678 return r;
2679 } else
2680 WITH_UMASK(0000)
2681 (void) mkdir_parents_label(i->path, 0755);
2682
2683 return 0;
2684}
2685
2686static int create_item(Context *c, Item *i) {
2687 int r;
2688
2689 assert(c);
2690 assert(i);
2691
2692 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
2693
2694 switch (i->type) {
2695
2696 case IGNORE_PATH:
2697 case IGNORE_DIRECTORY_PATH:
2698 case REMOVE_PATH:
2699 case RECURSIVE_REMOVE_PATH:
2700 return 0;
2701
2702 case TRUNCATE_FILE:
2703 case CREATE_FILE:
2704 r = mkdir_parents_item(i, S_IFREG);
2705 if (r < 0)
2706 return r;
2707
2708 if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
2709 r = truncate_file(c, i, i->path);
2710 else
2711 r = create_file(c, i, i->path);
2712 if (r < 0)
2713 return r;
2714 break;
2715
2716 case COPY_FILES:
2717 r = mkdir_parents_item(i, 0);
2718 if (r < 0)
2719 return r;
2720
2721 r = copy_files(c, i);
2722 if (r < 0)
2723 return r;
2724 break;
2725
2726 case WRITE_FILE:
2727 r = glob_item(c, i, write_one_file);
2728 if (r < 0)
2729 return r;
2730
2731 break;
2732
2733 case CREATE_DIRECTORY:
2734 case TRUNCATE_DIRECTORY:
2735 r = mkdir_parents_item(i, S_IFDIR);
2736 if (r < 0)
2737 return r;
2738
2739 r = create_directory(c, i, i->path);
2740 if (r < 0)
2741 return r;
2742 break;
2743
2744 case CREATE_SUBVOLUME:
2745 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2746 case CREATE_SUBVOLUME_NEW_QUOTA:
2747 r = mkdir_parents_item(i, S_IFDIR);
2748 if (r < 0)
2749 return r;
2750
2751 r = create_subvolume(c, i, i->path);
2752 if (r < 0)
2753 return r;
2754 break;
2755
2756 case EMPTY_DIRECTORY:
2757 r = glob_item(c, i, empty_directory);
2758 if (r < 0)
2759 return r;
2760 break;
2761
2762 case CREATE_FIFO:
2763 r = mkdir_parents_item(i, S_IFIFO);
2764 if (r < 0)
2765 return r;
2766
2767 r = create_fifo(c, i);
2768 if (r < 0)
2769 return r;
2770 break;
2771
2772 case CREATE_SYMLINK:
2773 r = mkdir_parents_item(i, S_IFLNK);
2774 if (r < 0)
2775 return r;
2776
2777 r = create_symlink(c, i);
2778 if (r < 0)
2779 return r;
2780
2781 break;
2782
2783 case CREATE_BLOCK_DEVICE:
2784 case CREATE_CHAR_DEVICE:
2785 if (have_effective_cap(CAP_MKNOD) <= 0) {
2786 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2787 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2788
2789 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
2790 return 0;
2791 }
2792
2793 r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2794 if (r < 0)
2795 return r;
2796
2797 r = create_device(c, i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2798 if (r < 0)
2799 return r;
2800
2801 break;
2802
2803 case ADJUST_MODE:
2804 case RELABEL_PATH:
2805 r = glob_item(c, i, path_set_perms);
2806 if (r < 0)
2807 return r;
2808 break;
2809
2810 case RECURSIVE_RELABEL_PATH:
2811 r = glob_item_recursively(c, i, fd_set_perms);
2812 if (r < 0)
2813 return r;
2814 break;
2815
2816 case SET_XATTR:
2817 r = glob_item(c, i, path_set_xattrs);
2818 if (r < 0)
2819 return r;
2820 break;
2821
2822 case RECURSIVE_SET_XATTR:
2823 r = glob_item_recursively(c, i, fd_set_xattrs);
2824 if (r < 0)
2825 return r;
2826 break;
2827
2828 case SET_ACL:
2829 r = glob_item(c, i, path_set_acls);
2830 if (r < 0)
2831 return r;
2832 break;
2833
2834 case RECURSIVE_SET_ACL:
2835 r = glob_item_recursively(c, i, fd_set_acls);
2836 if (r < 0)
2837 return r;
2838 break;
2839
2840 case SET_ATTRIBUTE:
2841 r = glob_item(c, i, path_set_attribute);
2842 if (r < 0)
2843 return r;
2844 break;
2845
2846 case RECURSIVE_SET_ATTRIBUTE:
2847 r = glob_item_recursively(c, i, fd_set_attribute);
2848 if (r < 0)
2849 return r;
2850 break;
2851 }
2852
2853 return 0;
2854}
2855
2856static int purge_item_instance(Context *c, Item *i, const char *instance, CreationMode creation) {
2857 int r;
2858
2859 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2860 log_debug("rm -rf \"%s\"", instance);
2861 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
2862 if (r < 0 && r != -ENOENT)
2863 return log_error_errno(r, "rm_rf(%s): %m", instance);
2864
2865 return 0;
2866}
2867
2868static int purge_item(Context *c, Item *i) {
2869
2870 assert(i);
2871
2872 if (!needs_purge(i->type))
2873 return 0;
2874
2875 log_debug("Running purge owned action for entry %c %s", (char) i->type, i->path);
2876
2877 if (needs_glob(i->type))
2878 return glob_item(c, i, purge_item_instance);
2879
2880 return purge_item_instance(c, i, i->path, CREATION_EXISTING);
2881}
2882
2883static int remove_item_instance(
2884 Context *c,
2885 Item *i,
2886 const char *instance,
2887 CreationMode creation) {
2888
2889 int r;
2890
2891 assert(c);
2892 assert(i);
2893
2894 switch (i->type) {
2895
2896 case REMOVE_PATH:
2897 if (remove(instance) < 0 && errno != ENOENT)
2898 return log_error_errno(errno, "rm(%s): %m", instance);
2899
2900 break;
2901
2902 case RECURSIVE_REMOVE_PATH:
2903 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2904 log_debug("rm -rf \"%s\"", instance);
2905 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
2906 if (r < 0 && r != -ENOENT)
2907 return log_error_errno(r, "rm_rf(%s): %m", instance);
2908
2909 break;
2910
2911 default:
2912 assert_not_reached();
2913 }
2914
2915 return 0;
2916}
2917
2918static int remove_item(Context *c, Item *i) {
2919 int r;
2920
2921 assert(c);
2922 assert(i);
2923
2924 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2925
2926 switch (i->type) {
2927
2928 case TRUNCATE_DIRECTORY:
2929 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2930 log_debug("rm -rf \"%s\"", i->path);
2931 r = rm_rf(i->path, REMOVE_PHYSICAL);
2932 if (r < 0 && r != -ENOENT)
2933 return log_error_errno(r, "rm_rf(%s): %m", i->path);
2934
2935 return 0;
2936
2937 case REMOVE_PATH:
2938 case RECURSIVE_REMOVE_PATH:
2939 return glob_item(c, i, remove_item_instance);
2940
2941 default:
2942 return 0;
2943 }
2944}
2945
2946static char *age_by_to_string(AgeBy ab, bool is_dir) {
2947 static const char ab_map[] = { 'a', 'b', 'c', 'm' };
2948 size_t j = 0;
2949 char *ret;
2950
2951 ret = new(char, ELEMENTSOF(ab_map) + 1);
2952 if (!ret)
2953 return NULL;
2954
2955 for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
2956 if (FLAGS_SET(ab, 1U << i))
2957 ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
2958
2959 ret[j] = 0;
2960 return ret;
2961}
2962
2963static int clean_item_instance(
2964 Context *c,
2965 Item *i,
2966 const char* instance,
2967 CreationMode creation) {
2968
2969 _cleanup_closedir_ DIR *d = NULL;
2970 STRUCT_STATX_DEFINE(sx);
2971 int mountpoint, r;
2972 usec_t cutoff, n;
2973
2974 assert(i);
2975
2976 if (!i->age_set)
2977 return 0;
2978
2979 n = now(CLOCK_REALTIME);
2980 if (n < i->age)
2981 return 0;
2982
2983 cutoff = n - i->age;
2984
2985 d = opendir_nomod(instance);
2986 if (!d) {
2987 if (IN_SET(errno, ENOENT, ENOTDIR)) {
2988 log_debug_errno(errno, "Directory \"%s\": %m", instance);
2989 return 0;
2990 }
2991
2992 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
2993 }
2994
2995 r = statx_fallback(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx);
2996 if (r < 0)
2997 return log_error_errno(r, "statx(%s) failed: %m", instance);
2998
2999 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
3000 mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
3001 else {
3002 struct stat ps;
3003
3004 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
3005 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
3006
3007 mountpoint =
3008 sx.stx_dev_major != major(ps.st_dev) ||
3009 sx.stx_dev_minor != minor(ps.st_dev) ||
3010 sx.stx_ino != ps.st_ino;
3011 }
3012
3013 if (DEBUG_LOGGING) {
3014 _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
3015
3016 ab_f = age_by_to_string(i->age_by_file, false);
3017 if (!ab_f)
3018 return log_oom();
3019
3020 ab_d = age_by_to_string(i->age_by_dir, true);
3021 if (!ab_d)
3022 return log_oom();
3023
3024 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
3025 mountpoint ? "mount point" : "directory",
3026 instance,
3027 FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
3028 ab_f, ab_d);
3029 }
3030
3031 return dir_cleanup(c, i, instance, d,
3032 statx_timestamp_load_nsec(&sx.stx_atime),
3033 statx_timestamp_load_nsec(&sx.stx_mtime),
3034 cutoff * NSEC_PER_USEC,
3035 sx.stx_dev_major, sx.stx_dev_minor, mountpoint,
3036 MAX_DEPTH, i->keep_first_level,
3037 i->age_by_file, i->age_by_dir);
3038}
3039
3040static int clean_item(Context *c, Item *i) {
3041 assert(c);
3042 assert(i);
3043
3044 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
3045
3046 switch (i->type) {
3047
3048 case CREATE_DIRECTORY:
3049 case TRUNCATE_DIRECTORY:
3050 case CREATE_SUBVOLUME:
3051 case CREATE_SUBVOLUME_INHERIT_QUOTA:
3052 case CREATE_SUBVOLUME_NEW_QUOTA:
3053 case COPY_FILES:
3054 clean_item_instance(c, i, i->path, CREATION_EXISTING);
3055 return 0;
3056
3057 case EMPTY_DIRECTORY:
3058 case IGNORE_PATH:
3059 case IGNORE_DIRECTORY_PATH:
3060 return glob_item(c, i, clean_item_instance);
3061
3062 default:
3063 return 0;
3064 }
3065}
3066
3067static int process_item(
3068 Context *c,
3069 Item *i,
3070 OperationMask operation) {
3071
3072 OperationMask todo;
3073 _cleanup_free_ char *_path = NULL;
3074 const char *path;
3075 int r;
3076
3077 assert(c);
3078 assert(i);
3079
3080 todo = operation & ~i->done;
3081 if (todo == 0) /* Everything already done? */
3082 return 0;
3083
3084 i->done |= operation;
3085
3086 path = i->path;
3087 if (string_is_glob(path)) {
3088 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3089 * for the non-glob part. */
3090
3091 r = glob_non_glob_prefix(path, &_path);
3092 if (r < 0 && r != -ENOENT)
3093 return log_debug_errno(r, "Failed to deglob path: %m");
3094 if (r >= 0)
3095 path = _path;
3096 }
3097
3098 r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
3099 if (r == -EREMOTE) {
3100 log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
3101 return 0;
3102 }
3103 if (r < 0)
3104 log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
3105
3106 r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(c, i) : 0;
3107 /* Failure can only be tolerated for create */
3108 if (i->allow_failure)
3109 r = 0;
3110
3111 RET_GATHER(r, FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(c, i) : 0);
3112 RET_GATHER(r, FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(c, i) : 0);
3113 RET_GATHER(r, FLAGS_SET(operation, OPERATION_PURGE) ? purge_item(c, i) : 0);
3114
3115 return r;
3116}
3117
3118static int process_item_array(
3119 Context *c,
3120 ItemArray *array,
3121 OperationMask operation) {
3122
3123 int r = 0;
3124 size_t n;
3125
3126 assert(c);
3127 assert(array);
3128
3129 /* Create any parent first. */
3130 if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
3131 r = process_item_array(c, array->parent, operation & OPERATION_CREATE);
3132
3133 /* Clean up all children first */
3134 if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE)) && !set_isempty(array->children)) {
3135 ItemArray *cc;
3136
3137 SET_FOREACH(cc, array->children) {
3138 int k;
3139
3140 k = process_item_array(c, cc, operation & (OPERATION_REMOVE|OPERATION_CLEAN|OPERATION_PURGE));
3141 if (k < 0 && r == 0)
3142 r = k;
3143 }
3144 }
3145
3146 for (n = 0; n < array->n_items; n++) {
3147 int k;
3148
3149 k = process_item(c, array->items + n, operation);
3150 if (k < 0 && r == 0)
3151 r = k;
3152 }
3153
3154 return r;
3155}
3156
3157static void item_free_contents(Item *i) {
3158 assert(i);
3159 free(i->path);
3160 free(i->argument);
3161 free(i->binary_argument);
3162 strv_free(i->xattrs);
3163
3164#if HAVE_ACL
3165 if (i->acl_access)
3166 acl_free(i->acl_access);
3167
3168 if (i->acl_access_exec)
3169 acl_free(i->acl_access_exec);
3170
3171 if (i->acl_default)
3172 acl_free(i->acl_default);
3173#endif
3174}
3175
3176static ItemArray* item_array_free(ItemArray *a) {
3177 size_t n;
3178
3179 if (!a)
3180 return NULL;
3181
3182 for (n = 0; n < a->n_items; n++)
3183 item_free_contents(a->items + n);
3184
3185 set_free(a->children);
3186 free(a->items);
3187 return mfree(a);
3188}
3189
3190static int item_compare(const Item *a, const Item *b) {
3191 /* Make sure that the ownership taking item is put first, so
3192 * that we first create the node, and then can adjust it */
3193
3194 if (takes_ownership(a->type) && !takes_ownership(b->type))
3195 return -1;
3196 if (!takes_ownership(a->type) && takes_ownership(b->type))
3197 return 1;
3198
3199 return CMP(a->type, b->type);
3200}
3201
3202static bool item_compatible(const Item *a, const Item *b) {
3203 assert(a);
3204 assert(b);
3205 assert(streq(a->path, b->path));
3206
3207 if (takes_ownership(a->type) && takes_ownership(b->type))
3208 /* check if the items are the same */
3209 return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
3210 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
3211
3212 a->uid_set == b->uid_set &&
3213 a->uid == b->uid &&
3214 a->uid_only_create == b->uid_only_create &&
3215
3216 a->gid_set == b->gid_set &&
3217 a->gid == b->gid &&
3218 a->gid_only_create == b->gid_only_create &&
3219
3220 a->mode_set == b->mode_set &&
3221 a->mode == b->mode &&
3222 a->mode_only_create == b->mode_only_create &&
3223
3224 a->age_set == b->age_set &&
3225 a->age == b->age &&
3226
3227 a->age_by_file == b->age_by_file &&
3228 a->age_by_dir == b->age_by_dir &&
3229
3230 a->mask_perms == b->mask_perms &&
3231
3232 a->keep_first_level == b->keep_first_level &&
3233
3234 a->major_minor == b->major_minor;
3235
3236 return true;
3237}
3238
3239static bool should_include_path(const char *path) {
3240 STRV_FOREACH(prefix, arg_exclude_prefixes)
3241 if (path_startswith(path, *prefix)) {
3242 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
3243 path, *prefix);
3244 return false;
3245 }
3246
3247 STRV_FOREACH(prefix, arg_include_prefixes)
3248 if (path_startswith(path, *prefix)) {
3249 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
3250 return true;
3251 }
3252
3253 /* no matches, so we should include this path only if we have no allow list at all */
3254 if (strv_isempty(arg_include_prefixes))
3255 return true;
3256
3257 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
3258 return false;
3259}
3260
3261static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
3262 int r;
3263
3264 assert(i);
3265
3266 if (!i->argument)
3267 return 0;
3268
3269 switch (i->type) {
3270 case COPY_FILES:
3271 case CREATE_SYMLINK:
3272 case CREATE_FILE:
3273 case TRUNCATE_FILE:
3274 case WRITE_FILE: {
3275 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
3276 ssize_t l;
3277
3278 l = cunescape(i->argument, 0, &unescaped);
3279 if (l < 0)
3280 return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
3281
3282 r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
3283 if (r < 0)
3284 return r;
3285
3286 return free_and_replace(i->argument, resolved);
3287 }
3288 case SET_XATTR:
3289 case RECURSIVE_SET_XATTR:
3290 STRV_FOREACH(xattr, i->xattrs) {
3291 _cleanup_free_ char *resolved = NULL;
3292
3293 r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
3294 if (r < 0)
3295 return r;
3296
3297 free_and_replace(*xattr, resolved);
3298 }
3299 return 0;
3300
3301 default:
3302 return 0;
3303 }
3304}
3305
3306static int patch_var_run(const char *fname, unsigned line, char **path) {
3307 const char *k;
3308 char *n;
3309
3310 assert(path);
3311 assert(*path);
3312
3313 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
3314 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
3315 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
3316 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
3317 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
3318 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
3319 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
3320 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
3321 * the latter. Moreover files below this path are by far the primary use case for tmpfiles.d/. */
3322
3323 k = path_startswith(*path, "/var/run/");
3324 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
3325 return 0;
3326
3327 n = path_join("/run", k);
3328 if (!n)
3329 return log_oom();
3330
3331 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
3332 * there's no immediate need for action by the user. However, in the interest of making things less confusing
3333 * to the user, let's still inform the user that these snippets should really be updated. */
3334 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3335 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3336 *path, n);
3337
3338 free_and_replace(*path, n);
3339
3340 return 0;
3341}
3342
3343static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
3344 int r;
3345
3346 assert(user);
3347 assert(ret_uid);
3348
3349 /* First: parse as numeric UID string */
3350 r = parse_uid(user, ret_uid);
3351 if (r >= 0)
3352 return r;
3353
3354 /* Second: pass to NSS if we are running "online" */
3355 if (!arg_root)
3356 return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
3357
3358 /* Third, synthesize "root" unconditionally */
3359 if (streq(user, "root")) {
3360 *ret_uid = 0;
3361 return 0;
3362 }
3363
3364 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3365 return name_to_uid_offline(arg_root, user, ret_uid, cache);
3366}
3367
3368static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
3369 int r;
3370
3371 assert(group);
3372 assert(ret_gid);
3373
3374 /* First: parse as numeric GID string */
3375 r = parse_gid(group, ret_gid);
3376 if (r >= 0)
3377 return r;
3378
3379 /* Second: pass to NSS if we are running "online" */
3380 if (!arg_root)
3381 return get_group_creds(&group, ret_gid, 0);
3382
3383 /* Third, synthesize "root" unconditionally */
3384 if (streq(group, "root")) {
3385 *ret_gid = 0;
3386 return 0;
3387 }
3388
3389 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3390 return name_to_gid_offline(arg_root, group, ret_gid, cache);
3391}
3392
3393static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
3394 AgeBy ab_f = 0, ab_d = 0;
3395
3396 static const struct {
3397 char age_by_chr;
3398 AgeBy age_by_flag;
3399 } age_by_types[] = {
3400 { 'a', AGE_BY_ATIME },
3401 { 'b', AGE_BY_BTIME },
3402 { 'c', AGE_BY_CTIME },
3403 { 'm', AGE_BY_MTIME },
3404 };
3405
3406 assert(age_by_str);
3407 assert(item);
3408
3409 if (isempty(age_by_str))
3410 return -EINVAL;
3411
3412 for (const char *s = age_by_str; *s != 0; s++) {
3413 size_t i;
3414
3415 /* Ignore whitespace. */
3416 if (strchr(WHITESPACE, *s))
3417 continue;
3418
3419 for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
3420 /* Check lower-case for files, upper-case for directories. */
3421 if (*s == age_by_types[i].age_by_chr) {
3422 ab_f |= age_by_types[i].age_by_flag;
3423 break;
3424 } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
3425 ab_d |= age_by_types[i].age_by_flag;
3426 break;
3427 }
3428 }
3429
3430 /* Invalid character. */
3431 if (i >= ELEMENTSOF(age_by_types))
3432 return -EINVAL;
3433 }
3434
3435 /* No match. */
3436 if (ab_f == 0 && ab_d == 0)
3437 return -EINVAL;
3438
3439 item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
3440 item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
3441
3442 return 0;
3443}
3444
3445static bool is_duplicated_item(ItemArray *existing, const Item *i) {
3446
3447 assert(existing);
3448 assert(i);
3449
3450 for (size_t n = 0; n < existing->n_items; n++) {
3451 const Item *e = existing->items + n;
3452
3453 if (item_compatible(e, i))
3454 continue;
3455
3456 /* Only multiple 'w+' lines for the same path are allowed. */
3457 if (e->type != WRITE_FILE || !e->append_or_force ||
3458 i->type != WRITE_FILE || !i->append_or_force)
3459 return true;
3460 }
3461
3462 return false;
3463}
3464
3465static int parse_line(
3466 Context *c,
3467 const char *fname,
3468 unsigned line,
3469 const char *buffer,
3470 bool *invalid_config) {
3471
3472 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
3473 _cleanup_(item_free_contents) Item i = {
3474 /* The "age-by" argument considers all file timestamp types by default. */
3475 .age_by_file = AGE_BY_DEFAULT_FILE,
3476 .age_by_dir = AGE_BY_DEFAULT_DIR,
3477 };
3478 ItemArray *existing;
3479 OrderedHashmap *h;
3480 int r, pos;
3481 bool append_or_force = false, boot = false, allow_failure = false, try_replace = false,
3482 unbase64 = false, from_cred = false, missing_user_or_group = false;
3483
3484 assert(c);
3485 assert(fname);
3486 assert(line >= 1);
3487 assert(buffer);
3488
3489 const Specifier specifier_table[] = {
3490 { 'a', specifier_architecture, NULL },
3491 { 'b', specifier_boot_id, NULL },
3492 { 'B', specifier_os_build_id, NULL },
3493 { 'H', specifier_hostname, NULL },
3494 { 'l', specifier_short_hostname, NULL },
3495 { 'm', specifier_machine_id, NULL },
3496 { 'o', specifier_os_id, NULL },
3497 { 'v', specifier_kernel_release, NULL },
3498 { 'w', specifier_os_version_id, NULL },
3499 { 'W', specifier_os_variant_id, NULL },
3500
3501 { 'h', specifier_user_home, NULL },
3502
3503 { 'C', specifier_directory, UINT_TO_PTR(DIRECTORY_CACHE) },
3504 { 'L', specifier_directory, UINT_TO_PTR(DIRECTORY_LOGS) },
3505 { 'S', specifier_directory, UINT_TO_PTR(DIRECTORY_STATE) },
3506 { 't', specifier_directory, UINT_TO_PTR(DIRECTORY_RUNTIME) },
3507
3508 COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
3509 COMMON_TMP_SPECIFIERS,
3510 {}
3511 };
3512
3513 r = extract_many_words(
3514 &buffer,
3515 NULL,
3516 EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE,
3517 &action,
3518 &path,
3519 &mode,
3520 &user,
3521 &group,
3522 &age,
3523 NULL);
3524 if (r < 0) {
3525 if (IN_SET(r, -EINVAL, -EBADSLT))
3526 /* invalid quoting and such or an unknown specifier */
3527 *invalid_config = true;
3528 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
3529 } else if (r < 2) {
3530 *invalid_config = true;
3531 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
3532 }
3533
3534 if (!empty_or_dash(buffer)) {
3535 i.argument = strdup(buffer);
3536 if (!i.argument)
3537 return log_oom();
3538 }
3539
3540 if (isempty(action)) {
3541 *invalid_config = true;
3542 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Command too short '%s'.", action);
3543 }
3544
3545 for (pos = 1; action[pos]; pos++) {
3546 if (action[pos] == '!' && !boot)
3547 boot = true;
3548 else if (action[pos] == '+' && !append_or_force)
3549 append_or_force = true;
3550 else if (action[pos] == '-' && !allow_failure)
3551 allow_failure = true;
3552 else if (action[pos] == '=' && !try_replace)
3553 try_replace = true;
3554 else if (action[pos] == '~' && !unbase64)
3555 unbase64 = true;
3556 else if (action[pos] == '^' && !from_cred)
3557 from_cred = true;
3558 else {
3559 *invalid_config = true;
3560 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Unknown modifiers in command '%s'", action);
3561 }
3562 }
3563
3564 if (boot && !arg_boot) {
3565 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3566 return 0;
3567 }
3568
3569 i.type = action[0];
3570 i.append_or_force = append_or_force;
3571 i.allow_failure = allow_failure;
3572 i.try_replace = try_replace;
3573
3574 r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
3575 if (ERRNO_IS_NOINFO(r))
3576 return log_unresolvable_specifier(fname, line);
3577 if (r < 0) {
3578 if (IN_SET(r, -EINVAL, -EBADSLT))
3579 *invalid_config = true;
3580 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", path);
3581 }
3582
3583 r = patch_var_run(fname, line, &i.path);
3584 if (r < 0)
3585 return r;
3586
3587 if (!path_is_absolute(i.path)) {
3588 *invalid_config = true;
3589 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3590 "Path '%s' not absolute.", i.path);
3591 }
3592
3593 path_simplify(i.path);
3594
3595 switch (i.type) {
3596
3597 case CREATE_DIRECTORY:
3598 case CREATE_SUBVOLUME:
3599 case CREATE_SUBVOLUME_INHERIT_QUOTA:
3600 case CREATE_SUBVOLUME_NEW_QUOTA:
3601 case EMPTY_DIRECTORY:
3602 case TRUNCATE_DIRECTORY:
3603 case CREATE_FIFO:
3604 case IGNORE_PATH:
3605 case IGNORE_DIRECTORY_PATH:
3606 case REMOVE_PATH:
3607 case RECURSIVE_REMOVE_PATH:
3608 case ADJUST_MODE:
3609 case RELABEL_PATH:
3610 case RECURSIVE_RELABEL_PATH:
3611 if (i.argument)
3612 log_syntax(NULL,
3613 LOG_WARNING,
3614 fname,
3615 line,
3616 0,
3617 "%c lines don't take argument fields, ignoring.",
3618 (char) i.type);
3619
3620 break;
3621
3622 case CREATE_FILE:
3623 case TRUNCATE_FILE:
3624 break;
3625
3626 case CREATE_SYMLINK:
3627 if (unbase64) {
3628 *invalid_config = true;
3629 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for symlink targets.");
3630 }
3631 break;
3632
3633 case WRITE_FILE:
3634 if (!i.argument) {
3635 *invalid_config = true;
3636 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Write file requires argument.");
3637 }
3638 break;
3639
3640 case COPY_FILES:
3641 if (unbase64) {
3642 *invalid_config = true;
3643 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for copy sources.");
3644 }
3645 break;
3646
3647 case CREATE_CHAR_DEVICE:
3648 case CREATE_BLOCK_DEVICE:
3649 if (unbase64) {
3650 *invalid_config = true;
3651 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for device node creation.");
3652 }
3653
3654 if (!i.argument) {
3655 *invalid_config = true;
3656 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Device file requires argument.");
3657 }
3658
3659 r = parse_devnum(i.argument, &i.major_minor);
3660 if (r < 0) {
3661 *invalid_config = true;
3662 return log_syntax(NULL, LOG_ERR, fname, line, r, "Can't parse device file major/minor '%s'.", i.argument);
3663 }
3664
3665 break;
3666
3667 case SET_XATTR:
3668 case RECURSIVE_SET_XATTR:
3669 if (unbase64) {
3670 *invalid_config = true;
3671 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for extended attributes.");
3672 }
3673 if (!i.argument) {
3674 *invalid_config = true;
3675 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3676 "Set extended attribute requires argument.");
3677 }
3678 r = parse_xattrs_from_arg(&i);
3679 if (r < 0)
3680 return r;
3681 break;
3682
3683 case SET_ACL:
3684 case RECURSIVE_SET_ACL:
3685 if (unbase64) {
3686 *invalid_config = true;
3687 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for ACLs.");
3688 }
3689 if (!i.argument) {
3690 *invalid_config = true;
3691 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3692 "Set ACLs requires argument.");
3693 }
3694 r = parse_acls_from_arg(&i);
3695 if (r < 0)
3696 return r;
3697 break;
3698
3699 case SET_ATTRIBUTE:
3700 case RECURSIVE_SET_ATTRIBUTE:
3701 if (unbase64) {
3702 *invalid_config = true;
3703 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for file attributes.");
3704 }
3705 if (!i.argument) {
3706 *invalid_config = true;
3707 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3708 "Set file attribute requires argument.");
3709 }
3710 r = parse_attribute_from_arg(&i);
3711 if (IN_SET(r, -EINVAL, -EBADSLT))
3712 *invalid_config = true;
3713 if (r < 0)
3714 return r;
3715 break;
3716
3717 default:
3718 *invalid_config = true;
3719 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3720 "Unknown command type '%c'.", (char) i.type);
3721 }
3722
3723 if (!should_include_path(i.path))
3724 return 0;
3725
3726 if (!unbase64) {
3727 /* Do specifier expansion except if base64 mode is enabled */
3728 r = specifier_expansion_from_arg(specifier_table, &i);
3729 if (ERRNO_IS_NOINFO(r))
3730 return log_unresolvable_specifier(fname, line);
3731 if (r < 0) {
3732 if (IN_SET(r, -EINVAL, -EBADSLT))
3733 *invalid_config = true;
3734 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to substitute specifiers in argument: %m");
3735 }
3736 }
3737
3738 switch (i.type) {
3739 case CREATE_SYMLINK:
3740 if (!i.argument) {
3741 i.argument = path_join("/usr/share/factory", i.path);
3742 if (!i.argument)
3743 return log_oom();
3744 }
3745 break;
3746
3747 case COPY_FILES:
3748 if (!i.argument) {
3749 i.argument = path_join("/usr/share/factory", i.path);
3750 if (!i.argument)
3751 return log_oom();
3752 } else if (!path_is_absolute(i.argument)) {
3753 *invalid_config = true;
3754 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Source path '%s' is not absolute.", i.argument);
3755
3756 }
3757
3758 if (!empty_or_root(arg_root)) {
3759 char *p;
3760
3761 p = path_join(arg_root, i.argument);
3762 if (!p)
3763 return log_oom();
3764 free_and_replace(i.argument, p);
3765 }
3766
3767 path_simplify(i.argument);
3768
3769 if (laccess(i.argument, F_OK) == -ENOENT) {
3770 /* Silently skip over lines where the source file is missing. */
3771 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Copy source path '%s' does not exist, skipping line.", i.argument);
3772 return 0;
3773 }
3774
3775 break;
3776
3777 default:
3778 break;
3779 }
3780
3781 if (from_cred) {
3782 if (!i.argument)
3783 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Reading from credential requested, but no credential name specified.");
3784 if (!credential_name_valid(i.argument))
3785 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Credential name not valid: %s", i.argument);
3786
3787 r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
3788 if (IN_SET(r, -ENXIO, -ENOENT)) {
3789 /* Silently skip over lines that have no credentials passed */
3790 log_syntax(NULL, LOG_DEBUG, fname, line, 0,
3791 "Credential '%s' not specified, skipping line.", i.argument);
3792 return 0;
3793 }
3794 if (r < 0)
3795 return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
3796 }
3797
3798 /* If base64 decoding is requested, do so now */
3799 if (unbase64 && item_binary_argument(&i)) {
3800 _cleanup_free_ void *data = NULL;
3801 size_t data_size = 0;
3802
3803 r = unbase64mem_full(item_binary_argument(&i), item_binary_argument_size(&i), /* secure = */ false,
3804 &data, &data_size);
3805 if (r < 0)
3806 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to base64 decode specified argument '%s': %m", i.argument);
3807
3808 free_and_replace(i.binary_argument, data);
3809 i.binary_argument_size = data_size;
3810 }
3811
3812 if (!empty_or_root(arg_root)) {
3813 char *p;
3814
3815 p = path_join(arg_root, i.path);
3816 if (!p)
3817 return log_oom();
3818 free_and_replace(i.path, p);
3819 }
3820
3821 if (!empty_or_dash(user)) {
3822 const char *u;
3823
3824 u = startswith(user, ":");
3825 if (u)
3826 i.uid_only_create = true;
3827 else
3828 u = user;
3829
3830 r = find_uid(u, &i.uid, &c->uid_cache);
3831 if (r == -ESRCH && arg_graceful) {
3832 log_syntax(NULL, LOG_DEBUG, fname, line, r,
3833 "%s: user '%s' not found, not adjusting ownership.", i.path, u);
3834 missing_user_or_group = true;
3835 } else if (r < 0) {
3836 *invalid_config = true;
3837 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", u);
3838 } else
3839 i.uid_set = true;
3840 }
3841
3842 if (!empty_or_dash(group)) {
3843 const char *g;
3844
3845 g = startswith(group, ":");
3846 if (g)
3847 i.gid_only_create = true;
3848 else
3849 g = group;
3850
3851 r = find_gid(g, &i.gid, &c->gid_cache);
3852 if (r == -ESRCH && arg_graceful) {
3853 log_syntax(NULL, LOG_DEBUG, fname, line, r,
3854 "%s: group '%s' not found, not adjusting ownership.", i.path, g);
3855 missing_user_or_group = true;
3856 } else if (r < 0) {
3857 *invalid_config = true;
3858 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s': %m", g);
3859 } else
3860 i.gid_set = true;
3861 }
3862
3863 if (!empty_or_dash(mode)) {
3864 const char *mm;
3865 unsigned m;
3866
3867 for (mm = mode;; mm++) {
3868 if (*mm == '~')
3869 i.mask_perms = true;
3870 else if (*mm == ':')
3871 i.mode_only_create = true;
3872 else
3873 break;
3874 }
3875
3876 r = parse_mode(mm, &m);
3877 if (r < 0) {
3878 *invalid_config = true;
3879 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
3880 }
3881
3882 i.mode = m;
3883 i.mode_set = true;
3884 } else
3885 i.mode = IN_SET(i.type,
3886 CREATE_DIRECTORY,
3887 TRUNCATE_DIRECTORY,
3888 CREATE_SUBVOLUME,
3889 CREATE_SUBVOLUME_INHERIT_QUOTA,
3890 CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
3891
3892 if (missing_user_or_group && (i.mode & ~0777) != 0) {
3893 /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
3894 mode_t adjusted = i.mode & 0777;
3895 log_syntax(NULL, LOG_INFO, fname, line, 0,
3896 "Changing mode 0%o to 0%o because of changed ownership.", i.mode, adjusted);
3897 i.mode = adjusted;
3898 }
3899
3900 if (!empty_or_dash(age)) {
3901 const char *a = age;
3902 _cleanup_free_ char *seconds = NULL, *age_by = NULL;
3903
3904 if (*a == '~') {
3905 i.keep_first_level = true;
3906 a++;
3907 }
3908
3909 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3910 r = split_pair(a, ":", &age_by, &seconds);
3911 if (r == -ENOMEM)
3912 return log_oom();
3913 if (r < 0 && r != -EINVAL)
3914 return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
3915 if (r >= 0) {
3916 /* We found a ":", parse the "age-by" part. */
3917 r = parse_age_by_from_arg(age_by, &i);
3918 if (r == -ENOMEM)
3919 return log_oom();
3920 if (r < 0) {
3921 *invalid_config = true;
3922 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
3923 }
3924
3925 /* For parsing the "age" part, after the ":". */
3926 a = seconds;
3927 }
3928
3929 r = parse_sec(a, &i.age);
3930 if (r < 0) {
3931 *invalid_config = true;
3932 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
3933 }
3934
3935 i.age_set = true;
3936 }
3937
3938 h = needs_glob(i.type) ? c->globs : c->items;
3939
3940 existing = ordered_hashmap_get(h, i.path);
3941 if (existing) {
3942 if (is_duplicated_item(existing, &i)) {
3943 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3944 "Duplicate line for path \"%s\", ignoring.", i.path);
3945 return 0;
3946 }
3947 } else {
3948 existing = new0(ItemArray, 1);
3949 if (!existing)
3950 return log_oom();
3951
3952 r = ordered_hashmap_put(h, i.path, existing);
3953 if (r < 0) {
3954 free(existing);
3955 return log_oom();
3956 }
3957 }
3958
3959 if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
3960 return log_oom();
3961
3962 existing->items[existing->n_items++] = TAKE_STRUCT(i);
3963
3964 /* Sort item array, to enforce stable ordering of application */
3965 typesafe_qsort(existing->items, existing->n_items, item_compare);
3966
3967 return 0;
3968}
3969
3970static int cat_config(char **config_dirs, char **args) {
3971 _cleanup_strv_free_ char **files = NULL;
3972 int r;
3973
3974 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
3975 if (r < 0)
3976 return r;
3977
3978 pager_open(arg_pager_flags);
3979
3980 return cat_files(NULL, files, arg_cat_flags);
3981}
3982
3983static int exclude_default_prefixes(void) {
3984 int r;
3985
3986 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3987 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3988 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3989 * all kinds of files created/adjusted underneath these mount points. */
3990
3991 r = strv_extend_many(
3992 &arg_exclude_prefixes,
3993 "/dev",
3994 "/proc",
3995 "/run",
3996 "/sys");
3997 if (r < 0)
3998 return log_oom();
3999
4000 strv_uniq(arg_exclude_prefixes);
4001 return 0;
4002}
4003
4004static int help(void) {
4005 _cleanup_free_ char *link = NULL;
4006 int r;
4007
4008 r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
4009 if (r < 0)
4010 return log_oom();
4011
4012 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
4013 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
4014 " -h --help Show this help\n"
4015 " --user Execute user configuration\n"
4016 " --version Show package version\n"
4017 " --cat-config Show configuration files\n"
4018 " --tldr Show non-comment parts of configuration\n"
4019 " --create Create marked files/directories\n"
4020 " --clean Clean up marked directories\n"
4021 " --remove Remove marked files/directories\n"
4022 " --boot Execute actions only safe at boot\n"
4023 " --graceful Quietly ignore unknown users or groups\n"
4024 " --purge Delete all files owned by the configuration files\n"
4025 " --prefix=PATH Only apply rules with the specified prefix\n"
4026 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
4027 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
4028 " --root=PATH Operate on an alternate filesystem root\n"
4029 " --image=PATH Operate on disk image as filesystem root\n"
4030 " --image-policy=POLICY Specify disk image dissection policy\n"
4031 " --replace=PATH Treat arguments as replacement for PATH\n"
4032 " --no-pager Do not pipe output into a pager\n"
4033 "\nSee the %s for details.\n",
4034 program_invocation_short_name,
4035 ansi_highlight(),
4036 ansi_normal(),
4037 link);
4038
4039 return 0;
4040}
4041
4042static int parse_argv(int argc, char *argv[]) {
4043 enum {
4044 ARG_VERSION = 0x100,
4045 ARG_CAT_CONFIG,
4046 ARG_TLDR,
4047 ARG_USER,
4048 ARG_CREATE,
4049 ARG_CLEAN,
4050 ARG_REMOVE,
4051 ARG_PURGE,
4052 ARG_BOOT,
4053 ARG_GRACEFUL,
4054 ARG_PREFIX,
4055 ARG_EXCLUDE_PREFIX,
4056 ARG_ROOT,
4057 ARG_IMAGE,
4058 ARG_IMAGE_POLICY,
4059 ARG_REPLACE,
4060 ARG_NO_PAGER,
4061 };
4062
4063 static const struct option options[] = {
4064 { "help", no_argument, NULL, 'h' },
4065 { "user", no_argument, NULL, ARG_USER },
4066 { "version", no_argument, NULL, ARG_VERSION },
4067 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
4068 { "tldr", no_argument, NULL, ARG_TLDR },
4069 { "create", no_argument, NULL, ARG_CREATE },
4070 { "clean", no_argument, NULL, ARG_CLEAN },
4071 { "remove", no_argument, NULL, ARG_REMOVE },
4072 { "purge", no_argument, NULL, ARG_PURGE },
4073 { "boot", no_argument, NULL, ARG_BOOT },
4074 { "graceful", no_argument, NULL, ARG_GRACEFUL },
4075 { "prefix", required_argument, NULL, ARG_PREFIX },
4076 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
4077 { "root", required_argument, NULL, ARG_ROOT },
4078 { "image", required_argument, NULL, ARG_IMAGE },
4079 { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
4080 { "replace", required_argument, NULL, ARG_REPLACE },
4081 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
4082 {}
4083 };
4084
4085 int c, r;
4086
4087 assert(argc >= 0);
4088 assert(argv);
4089
4090 while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
4091
4092 switch (c) {
4093
4094 case 'h':
4095 return help();
4096
4097 case ARG_VERSION:
4098 return version();
4099
4100 case ARG_CAT_CONFIG:
4101 arg_cat_flags = CAT_CONFIG_ON;
4102 break;
4103
4104 case ARG_TLDR:
4105 arg_cat_flags = CAT_TLDR;
4106 break;
4107
4108 case ARG_USER:
4109 arg_runtime_scope = RUNTIME_SCOPE_USER;
4110 break;
4111
4112 case ARG_CREATE:
4113 arg_operation |= OPERATION_CREATE;
4114 break;
4115
4116 case ARG_CLEAN:
4117 arg_operation |= OPERATION_CLEAN;
4118 break;
4119
4120 case ARG_REMOVE:
4121 arg_operation |= OPERATION_REMOVE;
4122 break;
4123
4124 case ARG_BOOT:
4125 arg_boot = true;
4126 break;
4127
4128 case ARG_PURGE:
4129 arg_operation |= OPERATION_PURGE;
4130 break;
4131
4132 case ARG_GRACEFUL:
4133 arg_graceful = true;
4134 break;
4135
4136 case ARG_PREFIX:
4137 if (strv_extend(&arg_include_prefixes, optarg) < 0)
4138 return log_oom();
4139 break;
4140
4141 case ARG_EXCLUDE_PREFIX:
4142 if (strv_extend(&arg_exclude_prefixes, optarg) < 0)
4143 return log_oom();
4144 break;
4145
4146 case ARG_ROOT:
4147 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
4148 if (r < 0)
4149 return r;
4150 break;
4151
4152 case ARG_IMAGE:
4153#ifdef STANDALONE
4154 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
4155 "This systemd-tmpfiles version is compiled without support for --image=.");
4156#else
4157 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
4158 if (r < 0)
4159 return r;
4160#endif
4161 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4162 _fallthrough_;
4163
4164 case 'E':
4165 r = exclude_default_prefixes();
4166 if (r < 0)
4167 return r;
4168
4169 break;
4170
4171 case ARG_IMAGE_POLICY:
4172 r = parse_image_policy_argument(optarg, &arg_image_policy);
4173 if (r < 0)
4174 return r;
4175 break;
4176
4177 case ARG_REPLACE:
4178 if (!path_is_absolute(optarg))
4179 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4180 "The argument to --replace= must be an absolute path.");
4181 if (!endswith(optarg, ".conf"))
4182 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4183 "The argument to --replace= must have the extension '.conf'.");
4184
4185 arg_replace = optarg;
4186 break;
4187
4188 case ARG_NO_PAGER:
4189 arg_pager_flags |= PAGER_DISABLE;
4190 break;
4191
4192 case '?':
4193 return -EINVAL;
4194
4195 default:
4196 assert_not_reached();
4197 }
4198
4199 if (arg_operation == 0 && arg_cat_flags == CAT_CONFIG_OFF)
4200 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4201 "You need to specify at least one of --clean, --create, --remove, or --purge.");
4202
4203 if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
4204 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4205 "Option --replace= is not supported with --cat-config/--tldr.");
4206
4207 if (arg_replace && optind >= argc)
4208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4209 "When --replace= is given, some configuration items must be specified.");
4210
4211 if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
4212 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
4213 "Combination of --user and --root= is not supported.");
4214
4215 if (arg_image && arg_root)
4216 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
4217
4218 return 1;
4219}
4220
4221static int read_config_file(
4222 Context *c,
4223 char **config_dirs,
4224 const char *fn,
4225 bool ignore_enoent,
4226 bool *invalid_config) {
4227
4228 _cleanup_fclose_ FILE *_f = NULL;
4229 _cleanup_free_ char *pp = NULL;
4230 unsigned v = 0;
4231 FILE *f;
4232 ItemArray *ia;
4233 int r = 0;
4234
4235 assert(c);
4236 assert(fn);
4237
4238 if (streq(fn, "-")) {
4239 log_debug("Reading config from stdin%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
4240 fn = "<stdin>";
4241 f = stdin;
4242 } else {
4243 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f, &pp);
4244 if (r < 0) {
4245 if (ignore_enoent && r == -ENOENT) {
4246 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
4247 return 0;
4248 }
4249
4250 return log_error_errno(r, "Failed to open '%s': %m", fn);
4251 }
4252
4253 log_debug("Reading config file \"%s\"%s", pp, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
4254 fn = pp;
4255 f = _f;
4256 }
4257
4258 for (;;) {
4259 _cleanup_free_ char *line = NULL;
4260 bool invalid_line = false;
4261 int k;
4262
4263 k = read_stripped_line(f, LONG_LINE_MAX, &line);
4264 if (k < 0)
4265 return log_error_errno(k, "Failed to read '%s': %m", fn);
4266 if (k == 0)
4267 break;
4268
4269 v++;
4270
4271 if (IN_SET(line[0], 0, '#'))
4272 continue;
4273
4274 k = parse_line(c, fn, v, line, &invalid_line);
4275 if (k < 0) {
4276 if (invalid_line)
4277 /* Allow reporting with a special code if the caller requested this */
4278 *invalid_config = true;
4279 else if (r == 0)
4280 /* The first error becomes our return value */
4281 r = k;
4282 }
4283 }
4284
4285 /* we have to determine age parameter for each entry of type X */
4286 ORDERED_HASHMAP_FOREACH(ia, c->globs)
4287 for (size_t ni = 0; ni < ia->n_items; ni++) {
4288 ItemArray *ja;
4289 Item *i = ia->items + ni, *candidate_item = NULL;
4290
4291 if (i->type != IGNORE_DIRECTORY_PATH)
4292 continue;
4293
4294 ORDERED_HASHMAP_FOREACH(ja, c->items)
4295 for (size_t nj = 0; nj < ja->n_items; nj++) {
4296 Item *j = ja->items + nj;
4297
4298 if (!IN_SET(j->type, CREATE_DIRECTORY,
4299 TRUNCATE_DIRECTORY,
4300 CREATE_SUBVOLUME,
4301 CREATE_SUBVOLUME_INHERIT_QUOTA,
4302 CREATE_SUBVOLUME_NEW_QUOTA))
4303 continue;
4304
4305 if (path_equal(j->path, i->path)) {
4306 candidate_item = j;
4307 break;
4308 }
4309
4310 if (candidate_item
4311 ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
4312 : path_startswith(i->path, j->path) != NULL)
4313 candidate_item = j;
4314 }
4315
4316 if (candidate_item && candidate_item->age_set) {
4317 i->age = candidate_item->age;
4318 i->age_set = true;
4319 }
4320 }
4321
4322 if (ferror(f)) {
4323 log_error_errno(errno, "Failed to read from file %s: %m", fn);
4324 if (r == 0)
4325 r = -EIO;
4326 }
4327
4328 return r;
4329}
4330
4331static int parse_arguments(
4332 Context *c,
4333 char **config_dirs,
4334 char **args,
4335 bool *invalid_config) {
4336 int r;
4337
4338 assert(c);
4339
4340 STRV_FOREACH(arg, args) {
4341 r = read_config_file(c, config_dirs, *arg, false, invalid_config);
4342 if (r < 0)
4343 return r;
4344 }
4345
4346 return 0;
4347}
4348
4349static int read_config_files(
4350 Context *c,
4351 char **config_dirs,
4352 char **args,
4353 bool *invalid_config) {
4354
4355 _cleanup_strv_free_ char **files = NULL;
4356 _cleanup_free_ char *p = NULL;
4357 int r;
4358
4359 assert(c);
4360
4361 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
4362 if (r < 0)
4363 return r;
4364
4365 STRV_FOREACH(f, files)
4366 if (p && path_equal(*f, p)) {
4367 log_debug("Parsing arguments at position \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
4368
4369 r = parse_arguments(c, config_dirs, args, invalid_config);
4370 if (r < 0)
4371 return r;
4372 } else
4373 /* Just warn, ignore result otherwise.
4374 * read_config_file() has some debug output, so no need to print anything. */
4375 (void) read_config_file(c, config_dirs, *f, true, invalid_config);
4376
4377 return 0;
4378}
4379
4380static int read_credential_lines(Context *c, bool *invalid_config) {
4381 _cleanup_free_ char *j = NULL;
4382 const char *d;
4383 int r;
4384
4385 assert(c);
4386
4387 r = get_credentials_dir(&d);
4388 if (r == -ENXIO)
4389 return 0;
4390 if (r < 0)
4391 return log_error_errno(r, "Failed to get credentials directory: %m");
4392
4393 j = path_join(d, "tmpfiles.extra");
4394 if (!j)
4395 return log_oom();
4396
4397 (void) read_config_file(c, /* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
4398 return 0;
4399}
4400
4401static int link_parent(Context *c, ItemArray *a) {
4402 const char *path;
4403 char *prefix;
4404 int r;
4405
4406 assert(c);
4407 assert(a);
4408
4409 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
4410 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
4411 * before their children, and clean up/remove children before their parents. */
4412
4413 if (a->n_items <= 0)
4414 return 0;
4415
4416 path = a->items[0].path;
4417 prefix = newa(char, strlen(path) + 1);
4418 PATH_FOREACH_PREFIX(prefix, path) {
4419 ItemArray *j;
4420
4421 j = ordered_hashmap_get(c->items, prefix);
4422 if (!j)
4423 j = ordered_hashmap_get(c->globs, prefix);
4424 if (j) {
4425 r = set_ensure_put(&j->children, NULL, a);
4426 if (r < 0)
4427 return log_oom();
4428
4429 a->parent = j;
4430 return 1;
4431 }
4432 }
4433
4434 return 0;
4435}
4436
4437DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
4438 ItemArray, item_array_free);
4439
4440static int run(int argc, char *argv[]) {
4441#ifndef STANDALONE
4442 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4443 _cleanup_(umount_and_freep) char *mounted_dir = NULL;
4444#endif
4445 _cleanup_strv_free_ char **config_dirs = NULL;
4446 _cleanup_(context_done) Context c = {};
4447 bool invalid_config = false;
4448 ItemArray *a;
4449 enum {
4450 PHASE_PURGE,
4451 PHASE_REMOVE_AND_CLEAN,
4452 PHASE_CREATE,
4453 _PHASE_MAX
4454 } phase;
4455 int r, k;
4456
4457 r = parse_argv(argc, argv);
4458 if (r <= 0)
4459 return r;
4460
4461 log_setup();
4462
4463 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4464 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4465 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4466 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4467 * and output a nice and friendly warning. */
4468 if (proc_mounted() == 0)
4469 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
4470 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4471 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4472
4473 /* Descending down file system trees might take a lot of fds */
4474 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
4475
4476 switch (arg_runtime_scope) {
4477
4478 case RUNTIME_SCOPE_USER:
4479 r = user_config_paths(&config_dirs);
4480 if (r < 0)
4481 return log_error_errno(r, "Failed to initialize configuration directory list: %m");
4482 break;
4483
4484 case RUNTIME_SCOPE_SYSTEM:
4485 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
4486 if (!config_dirs)
4487 return log_oom();
4488 break;
4489
4490 default:
4491 assert_not_reached();
4492 }
4493
4494 if (DEBUG_LOGGING) {
4495 _cleanup_free_ char *t = NULL;
4496
4497 STRV_FOREACH(i, config_dirs) {
4498 _cleanup_free_ char *j = NULL;
4499
4500 j = path_join(arg_root, *i);
4501 if (!j)
4502 return log_oom();
4503
4504 if (!strextend(&t, "\n\t", j))
4505 return log_oom();
4506 }
4507
4508 log_debug("Looking for configuration files in (higher priority first):%s", t);
4509 }
4510
4511 if (arg_cat_flags != CAT_CONFIG_OFF)
4512 return cat_config(config_dirs, argv + optind);
4513
4514 umask(0022);
4515
4516 r = mac_init();
4517 if (r < 0)
4518 return r;
4519
4520#ifndef STANDALONE
4521 if (arg_image) {
4522 assert(!arg_root);
4523
4524 r = mount_image_privately_interactively(
4525 arg_image,
4526 arg_image_policy,
4527 DISSECT_IMAGE_GENERIC_ROOT |
4528 DISSECT_IMAGE_REQUIRE_ROOT |
4529 DISSECT_IMAGE_VALIDATE_OS |
4530 DISSECT_IMAGE_RELAX_VAR_CHECK |
4531 DISSECT_IMAGE_FSCK |
4532 DISSECT_IMAGE_GROWFS,
4533 &mounted_dir,
4534 /* ret_dir_fd= */ NULL,
4535 &loop_device);
4536 if (r < 0)
4537 return r;
4538
4539 arg_root = strdup(mounted_dir);
4540 if (!arg_root)
4541 return log_oom();
4542 }
4543#else
4544 assert(!arg_image);
4545#endif
4546
4547 c.items = ordered_hashmap_new(&item_array_hash_ops);
4548 c.globs = ordered_hashmap_new(&item_array_hash_ops);
4549 if (!c.items || !c.globs)
4550 return log_oom();
4551
4552 /* If command line arguments are specified along with --replace, read all
4553 * configuration files and insert the positional arguments at the specified
4554 * place. Otherwise, if command line arguments are specified, execute just
4555 * them, and finally, without --replace= or any positional arguments, just
4556 * read configuration and execute it.
4557 */
4558 if (arg_replace || optind >= argc)
4559 r = read_config_files(&c, config_dirs, argv + optind, &invalid_config);
4560 else
4561 r = parse_arguments(&c, config_dirs, argv + optind, &invalid_config);
4562 if (r < 0)
4563 return r;
4564
4565 r = read_credential_lines(&c, &invalid_config);
4566 if (r < 0)
4567 return r;
4568
4569 /* Let's now link up all child/parent relationships */
4570 ORDERED_HASHMAP_FOREACH(a, c.items) {
4571 r = link_parent(&c, a);
4572 if (r < 0)
4573 return r;
4574 }
4575 ORDERED_HASHMAP_FOREACH(a, c.globs) {
4576 r = link_parent(&c, a);
4577 if (r < 0)
4578 return r;
4579 }
4580
4581 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
4582 * operations. i.e. that we first clean out the platform we then build on. */
4583 for (phase = 0; phase < _PHASE_MAX; phase++) {
4584 OperationMask op;
4585
4586 if (phase == PHASE_PURGE)
4587 op = arg_operation & OPERATION_PURGE;
4588 else if (phase == PHASE_REMOVE_AND_CLEAN)
4589 op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
4590 else if (phase == PHASE_CREATE)
4591 op = arg_operation & OPERATION_CREATE;
4592 else
4593 assert_not_reached();
4594
4595 if (op == 0) /* Nothing requested in this phase */
4596 continue;
4597
4598 /* The non-globbing ones usually create things, hence we apply them first */
4599 ORDERED_HASHMAP_FOREACH(a, c.items) {
4600 k = process_item_array(&c, a, op);
4601 if (k < 0 && r >= 0)
4602 r = k;
4603 }
4604
4605 /* The globbing ones usually alter things, hence we apply them second. */
4606 ORDERED_HASHMAP_FOREACH(a, c.globs) {
4607 k = process_item_array(&c, a, op);
4608 if (k < 0 && r >= 0)
4609 r = k;
4610 }
4611 }
4612
4613 if (ERRNO_IS_RESOURCE(r))
4614 return r;
4615 if (invalid_config)
4616 return EX_DATAERR;
4617 if (r < 0)
4618 return EX_CANTCREAT;
4619 return 0;
4620}
4621
4622DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);