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