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