1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
14 #include "alloc-util.h"
16 #include "btrfs-util.h"
18 #include "capability-util.h"
20 #include "chattr-util.h"
21 #include "conf-files.h"
22 #include "constants.h"
24 #include "creds-util.h"
25 #include "devnum-util.h"
26 #include "dirent-util.h"
27 #include "dissect-image.h"
29 #include "errno-util.h"
31 #include "extract-word.h"
34 #include "format-util.h"
36 #include "glob-util.h"
37 #include "hexdecoct.h"
38 #include "image-policy.h"
40 #include "label-util.h"
42 #include "loop-util.h"
43 #include "main-func.h"
44 #include "mkdir-label.h"
45 #include "mount-util.h"
46 #include "mountpoint-util.h"
47 #include "offline-passwd.h"
49 #include "parse-argument.h"
50 #include "parse-util.h"
51 #include "path-lookup.h"
52 #include "path-util.h"
53 #include "pretty-print.h"
54 #include "rlimit-util.h"
56 #include "selinux-util.h"
58 #include "sort-util.h"
59 #include "specifier.h"
60 #include "stat-util.h"
61 #include "string-table.h"
62 #include "string-util.h"
64 #include "sysctl-util.h"
65 #include "time-util.h"
66 #include "umask-util.h"
67 #include "user-util.h"
70 #include "xattr-util.h"
72 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
73 * them in the file system. This is intended to be used to create
74 * properly owned directories beneath /tmp, /var/tmp, /run, which are
75 * volatile and hence need to be recreated on bootup. */
77 typedef enum OperationMask
{
78 OPERATION_CREATE
= 1 << 0,
79 OPERATION_REMOVE
= 1 << 1,
80 OPERATION_CLEAN
= 1 << 2,
81 OPERATION_PURGE
= 1 << 3,
84 typedef enum ItemType
{
85 /* These ones take file names */
87 TRUNCATE_FILE
= 'F', /* deprecated: use f+ */
88 CREATE_DIRECTORY
= 'd',
89 TRUNCATE_DIRECTORY
= 'D',
90 CREATE_SUBVOLUME
= 'v',
91 CREATE_SUBVOLUME_INHERIT_QUOTA
= 'q',
92 CREATE_SUBVOLUME_NEW_QUOTA
= 'Q',
95 CREATE_CHAR_DEVICE
= 'c',
96 CREATE_BLOCK_DEVICE
= 'b',
99 /* These ones take globs */
101 EMPTY_DIRECTORY
= 'e',
103 RECURSIVE_SET_XATTR
= 'T',
105 RECURSIVE_SET_ACL
= 'A',
107 RECURSIVE_SET_ATTRIBUTE
= 'H',
109 IGNORE_DIRECTORY_PATH
= 'X',
111 RECURSIVE_REMOVE_PATH
= 'R',
113 RECURSIVE_RELABEL_PATH
= 'Z',
114 ADJUST_MODE
= 'm', /* legacy, 'z' is identical to this */
118 AGE_BY_ATIME
= 1 << 0,
119 AGE_BY_BTIME
= 1 << 1,
120 AGE_BY_CTIME
= 1 << 2,
121 AGE_BY_MTIME
= 1 << 3,
123 /* All file timestamp types are checked by default. */
124 AGE_BY_DEFAULT_FILE
= AGE_BY_ATIME
| AGE_BY_BTIME
| AGE_BY_CTIME
| AGE_BY_MTIME
,
125 AGE_BY_DEFAULT_DIR
= AGE_BY_ATIME
| AGE_BY_BTIME
| AGE_BY_MTIME
,
128 typedef struct Item
{
133 void *binary_argument
; /* set if binary data, in which case it takes precedence over 'argument' */
134 size_t binary_argument_size
;
138 acl_t acl_access_exec
;
145 AgeBy age_by_file
, age_by_dir
;
148 unsigned attribute_value
;
149 unsigned attribute_mask
;
154 bool uid_only_create
:1;
155 bool gid_only_create
:1;
156 bool mode_only_create
:1;
159 bool attribute_set
:1;
161 bool keep_first_level
:1;
163 bool append_or_force
:1;
165 bool allow_failure
:1;
171 bool ignore_if_target_missing
:1;
176 typedef struct ItemArray
{
180 struct ItemArray
*parent
;
184 typedef enum DirectoryType
{
197 _CREATION_MODE_INVALID
= -EINVAL
,
200 static CatFlags arg_cat_flags
= CAT_CONFIG_OFF
;
201 static bool arg_dry_run
= false;
202 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
203 static OperationMask arg_operation
= 0;
204 static bool arg_boot
= false;
205 static bool arg_graceful
= false;
206 static PagerFlags arg_pager_flags
= 0;
207 static char **arg_include_prefixes
= NULL
;
208 static char **arg_exclude_prefixes
= NULL
;
209 static char *arg_root
= NULL
;
210 static char *arg_image
= NULL
;
211 static char *arg_replace
= NULL
;
212 static ImagePolicy
*arg_image_policy
= NULL
;
214 #define MAX_DEPTH 256
216 typedef struct Context
{
217 OrderedHashmap
*items
;
218 OrderedHashmap
*globs
;
224 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes
, strv_freep
);
225 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes
, strv_freep
);
226 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
227 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
228 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
230 static const char *const creation_mode_verb_table
[_CREATION_MODE_MAX
] = {
231 [CREATION_NORMAL
] = "Created",
232 [CREATION_EXISTING
] = "Found existing",
233 [CREATION_FORCE
] = "Created replacement",
236 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb
, CreationMode
);
238 static void context_done(Context
*c
) {
241 ordered_hashmap_free(c
->items
);
242 ordered_hashmap_free(c
->globs
);
244 set_free(c
->unix_sockets
);
246 hashmap_free(c
->uid_cache
);
247 hashmap_free(c
->gid_cache
);
250 /* Different kinds of errors that mean that information is not available in the environment. */
251 static bool ERRNO_IS_NEG_NOINFO(intmax_t r
) {
253 -EUNATCH
, /* os-release or machine-id missing */
254 -ENOMEDIUM
, /* machine-id or another file empty */
255 -ENOPKG
, /* machine-id is uninitialized */
256 -ENXIO
); /* env var is unset */
259 static int specifier_directory(
263 const void *userdata
,
271 static const struct table_entry paths_system
[] = {
272 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
273 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
274 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
275 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
278 static const struct table_entry paths_user
[] = {
279 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
280 [DIRECTORY_STATE
] = { SD_PATH_USER_STATE_PRIVATE
},
281 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
282 [DIRECTORY_LOGS
] = { SD_PATH_USER_STATE_PRIVATE
, "log" },
285 const struct table_entry
*paths
;
286 _cleanup_free_
char *p
= NULL
;
290 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
291 paths
= arg_runtime_scope
== RUNTIME_SCOPE_USER
? paths_user
: paths_system
;
293 i
= PTR_TO_UINT(data
);
294 assert(i
< ELEMENTSOF(paths_system
));
296 r
= sd_path_lookup(paths
[i
].type
, paths
[i
].suffix
, &p
);
301 _cleanup_free_
char *j
= NULL
;
303 j
= path_join(arg_root
, p
);
314 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
315 static bool notified
= false;
317 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
318 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
319 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
320 * to LOG_DEBUG for the rest.
322 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
323 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
324 * expectation that machine-id and other files will be populated.
327 int log_level
= notified
|| arg_root
|| running_in_chroot() > 0 ?
328 LOG_DEBUG
: LOG_NOTICE
;
333 "Failed to resolve specifier: %s, skipping.",
334 arg_runtime_scope
== RUNTIME_SCOPE_USER
? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
338 "All rules containing unresolvable specifiers will be skipped.");
344 #define log_action(would, doing, fmt, ...) \
345 log_full(arg_dry_run ? LOG_INFO : LOG_DEBUG, \
347 arg_dry_run ? (would) : (doing), \
350 static int user_config_paths(char ***ret
) {
351 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
352 _cleanup_free_
char *runtime_config
= NULL
;
357 /* Combined user-specific and global dirs */
358 r
= user_search_dirs("/user-tmpfiles.d", &config_dirs
, &data_dirs
);
362 r
= xdg_user_runtime_dir("/user-tmpfiles.d", &runtime_config
);
363 if (r
< 0 && !ERRNO_IS_NEG_NOINFO(r
))
366 r
= strv_consume(&config_dirs
, TAKE_PTR(runtime_config
));
370 r
= strv_extend_strv_consume(&config_dirs
, TAKE_PTR(data_dirs
), /* filter_duplicates = */ true);
374 r
= path_strv_make_absolute_cwd(config_dirs
);
378 *ret
= TAKE_PTR(config_dirs
);
382 static bool needs_purge(ItemType t
) {
389 CREATE_SUBVOLUME_INHERIT_QUOTA
,
390 CREATE_SUBVOLUME_NEW_QUOTA
,
400 static bool needs_glob(ItemType t
) {
409 RECURSIVE_SET_ATTRIBUTE
,
411 IGNORE_DIRECTORY_PATH
,
413 RECURSIVE_REMOVE_PATH
,
415 RECURSIVE_RELABEL_PATH
,
419 static bool takes_ownership(ItemType t
) {
426 CREATE_SUBVOLUME_INHERIT_QUOTA
,
427 CREATE_SUBVOLUME_NEW_QUOTA
,
436 IGNORE_DIRECTORY_PATH
,
438 RECURSIVE_REMOVE_PATH
);
441 static bool supports_ignore_if_target_missing(ItemType t
) {
442 return t
== CREATE_SYMLINK
;
445 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
448 ORDERED_HASHMAP_FOREACH(j
, h
)
449 FOREACH_ARRAY(item
, j
->items
, j
->n_items
)
450 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
455 static int load_unix_sockets(Context
*c
) {
456 _cleanup_set_free_ Set
*sockets
= NULL
;
457 _cleanup_fclose_
FILE *f
= NULL
;
463 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
465 f
= fopen("/proc/net/unix", "re");
467 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
468 "Failed to open %s, ignoring: %m", "/proc/net/unix");
471 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
473 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
475 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
478 _cleanup_free_
char *line
= NULL
;
481 r
= read_line(f
, LONG_LINE_MAX
, &line
);
483 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
484 if (r
== 0) /* EOF */
487 p
= strchr(line
, ':');
495 p
+= strspn(p
, WHITESPACE
);
496 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
497 p
+= strspn(p
, WHITESPACE
);
499 if (!path_is_absolute(p
))
502 r
= set_put_strdup_full(&sockets
, &path_hash_ops_free
, p
);
504 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
507 c
->unix_sockets
= TAKE_PTR(sockets
);
511 static bool unix_socket_alive(Context
*c
, const char *fn
) {
515 if (load_unix_sockets(c
) < 0)
516 return true; /* We don't know, so assume yes */
518 return set_contains(c
->unix_sockets
, fn
);
521 /* Accessors for the argument in binary format */
522 static const void* item_binary_argument(const Item
*i
) {
524 return i
->binary_argument
?: i
->argument
;
527 static size_t item_binary_argument_size(const Item
*i
) {
529 return i
->binary_argument
? i
->binary_argument_size
: strlen_ptr(i
->argument
);
532 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
535 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
539 if (!IN_SET(errno
, ENOENT
, ELOOP
))
540 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\" with O_NOATIME: %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
541 if (!ERRNO_IS_PRIVILEGE(errno
))
544 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
546 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\" with or without O_NOATIME: %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
551 static DIR* opendir_nomod(const char *path
) {
552 return xopendirat_nomod(AT_FDCWD
, path
);
555 static int opendir_and_stat(
558 struct statx
*ret_sx
,
559 bool *ret_mountpoint
) {
561 _cleanup_closedir_
DIR *d
= NULL
;
568 assert(ret_mountpoint
);
570 /* Do opendir() and statx() on the directory.
571 * Return 1 if successful, 0 if file doesn't exist or is not a directory,
572 * negative errno otherwise.
575 d
= opendir_nomod(path
);
577 bool ignore
= IN_SET(errno
, ENOENT
, ENOTDIR
);
578 r
= log_full_errno(ignore
? LOG_DEBUG
: LOG_ERR
,
579 errno
, "Failed to open directory %s: %m", path
);
584 *ret_sx
= (struct statx
) {};
585 *ret_mountpoint
= false;
589 if (statx(dirfd(d
), "", AT_EMPTY_PATH
, STATX_MODE
|STATX_INO
|STATX_ATIME
|STATX_MTIME
, &sx1
) < 0)
590 return log_error_errno(errno
, "statx(%s) failed: %m", path
);
592 if (FLAGS_SET(sx1
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
))
593 *ret_mountpoint
= FLAGS_SET(sx1
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
);
596 if (statx(dirfd(d
), "..", 0, STATX_INO
, &sx2
) < 0)
597 return log_error_errno(errno
, "statx(%s/..) failed: %m", path
);
599 *ret_mountpoint
= !statx_mount_same(&sx1
, &sx2
);
607 static bool needs_cleanup(
613 const char *sub_path
,
617 if (FLAGS_SET(age_by
, AGE_BY_MTIME
) && mtime
!= NSEC_INFINITY
&& mtime
>= cutoff
) {
618 /* Follows spelling in stat(1). */
619 log_debug("%s \"%s\": modify time %s is too new.",
620 is_dir
? "Directory" : "File",
622 FORMAT_TIMESTAMP_STYLE(mtime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
627 if (FLAGS_SET(age_by
, AGE_BY_ATIME
) && atime
!= NSEC_INFINITY
&& atime
>= cutoff
) {
628 log_debug("%s \"%s\": access time %s is too new.",
629 is_dir
? "Directory" : "File",
631 FORMAT_TIMESTAMP_STYLE(atime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
637 * Note: Unless explicitly specified by the user, "ctime" is ignored
638 * by default for directories, because we change it when deleting.
640 if (FLAGS_SET(age_by
, AGE_BY_CTIME
) && ctime
!= NSEC_INFINITY
&& ctime
>= cutoff
) {
641 log_debug("%s \"%s\": change time %s is too new.",
642 is_dir
? "Directory" : "File",
644 FORMAT_TIMESTAMP_STYLE(ctime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
649 if (FLAGS_SET(age_by
, AGE_BY_BTIME
) && btime
!= NSEC_INFINITY
&& btime
>= cutoff
) {
650 log_debug("%s \"%s\": birth time %s is too new.",
651 is_dir
? "Directory" : "File",
653 FORMAT_TIMESTAMP_STYLE(btime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
661 static int dir_cleanup(
666 nsec_t self_atime_nsec
,
667 nsec_t self_mtime_nsec
,
673 bool keep_this_level
,
677 bool deleted
= false;
684 FOREACH_DIRENT_ALL(de
, d
, break) {
685 _cleanup_free_
char *sub_path
= NULL
;
686 nsec_t atime_nsec
, mtime_nsec
, ctime_nsec
, btime_nsec
;
688 if (dot_or_dot_dot(de
->d_name
))
691 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
692 * explicitly where we are looking at a mount point, for free as side information. Determining
693 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
694 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
695 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
696 * while on older kernels's well do traditional st_dev based detection of mount points.
698 * Using statx() for detecting mount points also has the benefit that we handle weird file
699 * systems such as overlayfs better where each file is originating from a different
703 if (statx(dirfd(d
), de
->d_name
,
704 AT_SYMLINK_NOFOLLOW
|AT_NO_AUTOMOUNT
,
705 STATX_TYPE
|STATX_MODE
|STATX_UID
|STATX_ATIME
|STATX_MTIME
|STATX_CTIME
|STATX_BTIME
,
710 /* FUSE, NFS mounts, SELinux might return EACCES */
711 log_full_errno(errno
== EACCES
? LOG_DEBUG
: LOG_ERR
, errno
,
712 "statx(%s/%s) failed: %m", p
, de
->d_name
);
716 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
)) {
717 /* Yay, we have the mount point API, use it */
718 if (FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
)) {
719 log_debug("Ignoring \"%s/%s\": different mount points.", p
, de
->d_name
);
723 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
724 * back to traditional stx_dev checking. */
725 if (sx
.stx_dev_major
!= rootdev_major
||
726 sx
.stx_dev_minor
!= rootdev_minor
) {
727 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, de
->d_name
);
731 /* Try to detect bind mounts of the same filesystem instance; they do not differ in
732 * device major/minors. This type of query is not supported on all kernels or
733 * filesystem types though. */
734 if (S_ISDIR(sx
.stx_mode
)) {
737 q
= is_mount_point_at(dirfd(d
), de
->d_name
, 0);
739 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, de
->d_name
);
741 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, de
->d_name
);
747 atime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_ATIME
) ? statx_timestamp_load_nsec(&sx
.stx_atime
) : 0;
748 mtime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_MTIME
) ? statx_timestamp_load_nsec(&sx
.stx_mtime
) : 0;
749 ctime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_CTIME
) ? statx_timestamp_load_nsec(&sx
.stx_ctime
) : 0;
750 btime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_BTIME
) ? statx_timestamp_load_nsec(&sx
.stx_btime
) : 0;
752 sub_path
= path_join(p
, de
->d_name
);
758 /* Is there an item configured for this path? */
759 if (ordered_hashmap_get(c
->items
, sub_path
)) {
760 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
764 if (find_glob(c
->globs
, sub_path
)) {
765 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
769 if (S_ISDIR(sx
.stx_mode
)) {
770 _cleanup_closedir_
DIR *sub_dir
= NULL
;
773 streq(de
->d_name
, "lost+found") &&
775 log_debug("Ignoring directory \"%s\".", sub_path
);
780 log_warning("Reached max depth on \"%s\".", sub_path
);
784 sub_dir
= xopendirat_nomod(dirfd(d
), de
->d_name
);
787 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
793 flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
794 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path
);
798 q
= dir_cleanup(c
, i
,
800 atime_nsec
, mtime_nsec
, cutoff_nsec
,
801 rootdev_major
, rootdev_minor
,
802 false, maxdepth
-1, false,
803 age_by_file
, age_by_dir
);
808 /* Note: if you are wondering why we don't support the sticky bit for excluding
809 * directories from cleaning like we do it for other file system objects: well, the
810 * sticky bit already has a meaning for directories, so we don't want to overload
813 if (keep_this_level
) {
814 log_debug("Keeping directory \"%s\".", sub_path
);
819 * Check the file timestamps of an entry against the
820 * given cutoff time; delete if it is older.
822 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
823 cutoff_nsec
, sub_path
, age_by_dir
, true))
826 log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path
);
828 unlinkat(dirfd(d
), de
->d_name
, AT_REMOVEDIR
) < 0 &&
829 !IN_SET(errno
, ENOENT
, ENOTEMPTY
))
830 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
833 _cleanup_close_
int fd
= -EBADF
; /* This file descriptor is defined here so that the
834 * lock that is taken below is only dropped _after_
835 * the unlink operation has finished. */
837 /* Skip files for which the sticky bit is set. These are semantics we define, and are
838 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
839 if (sx
.stx_mode
& S_ISVTX
) {
840 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
845 S_ISREG(sx
.stx_mode
) &&
847 STR_IN_SET(de
->d_name
,
851 log_debug("Skipping \"%s\".", sub_path
);
855 /* Ignore sockets that are listed in /proc/net/unix */
856 if (S_ISSOCK(sx
.stx_mode
) && unix_socket_alive(c
, sub_path
)) {
857 log_debug("Skipping \"%s\": live socket.", sub_path
);
861 /* Ignore device nodes */
862 if (S_ISCHR(sx
.stx_mode
) || S_ISBLK(sx
.stx_mode
)) {
863 log_debug("Skipping \"%s\": a device.", sub_path
);
867 /* Keep files on this level if this was requested */
868 if (keep_this_level
) {
869 log_debug("Keeping \"%s\".", sub_path
);
873 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
874 cutoff_nsec
, sub_path
, age_by_file
, false))
878 fd
= xopenat(dirfd(d
), de
->d_name
, O_RDONLY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
|O_NONBLOCK
|O_NOCTTY
);
879 if (fd
< 0 && !IN_SET(fd
, -ENOENT
, -ELOOP
))
880 log_warning_errno(fd
, "Opening file \"%s\" failed, proceeding without lock: %m", sub_path
);
881 if (fd
>= 0 && flock(fd
, LOCK_EX
|LOCK_NB
) < 0 && errno
== EAGAIN
) {
882 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", sub_path
);
887 log_action("Would remove", "Removing", "%s \"%s\"", sub_path
);
889 unlinkat(dirfd(d
), de
->d_name
, 0) < 0 &&
891 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
898 if (deleted
&& (self_atime_nsec
< NSEC_INFINITY
|| self_mtime_nsec
< NSEC_INFINITY
)) {
899 struct timespec ts
[2];
901 log_action("Would restore", "Restoring",
902 "%s access and modification time on \"%s\": %s, %s",
904 FORMAT_TIMESTAMP_STYLE(self_atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
),
905 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
907 timespec_store_nsec(ts
+ 0, self_atime_nsec
);
908 timespec_store_nsec(ts
+ 1, self_mtime_nsec
);
910 /* Restore original directory timestamps */
912 futimens(dirfd(d
), ts
) < 0)
913 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
919 static bool hardlinks_protected(void) {
920 static int cached
= -1;
923 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off,
924 * as that's what the kernel default is.
925 * Note that we ship 50-default.conf where it is enabled, but better be safe than sorry. */
930 _cleanup_free_
char *value
= NULL
;
932 r
= sysctl_read("fs/protected_hardlinks", &value
);
934 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
938 cached
= parse_boolean(value
);
940 log_debug_errno(cached
, "Failed to parse fs.protected_hardlinks sysctl, assuming disabled: %m");
944 static bool hardlink_vulnerable(const struct stat
*st
) {
947 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && !hardlinks_protected();
950 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
952 if ((current
& 0111) == 0)
954 if ((current
& 0222) == 0)
956 if ((current
& 0444) == 0)
958 if (!S_ISDIR(current
))
959 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
964 static int fd_set_perms(
969 const struct stat
*st
,
970 CreationMode creation
) {
972 bool do_chown
, do_chmod
;
984 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
988 if (fstat(fd
, &stbuf
) < 0)
989 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
993 if (hardlink_vulnerable(st
))
994 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
995 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
997 new_uid
= i
->uid_set
&& (creation
!= CREATION_EXISTING
|| !i
->uid_only_create
) ? i
->uid
: st
->st_uid
;
998 new_gid
= i
->gid_set
&& (creation
!= CREATION_EXISTING
|| !i
->gid_only_create
) ? i
->gid
: st
->st_gid
;
1000 /* Do we need a chown()? */
1001 do_chown
= (new_uid
!= st
->st_uid
) || (new_gid
!= st
->st_gid
);
1003 /* Calculate the mode to apply */
1004 new_mode
= i
->mode_set
&& (creation
!= CREATION_EXISTING
|| !i
->mode_only_create
) ?
1005 (i
->mask_perms
? process_mask_perms(i
->mode
, st
->st_mode
) : i
->mode
) :
1006 (st
->st_mode
& 07777);
1008 do_chmod
= ((new_mode
^ st
->st_mode
) & 07777) != 0;
1010 if (do_chmod
&& do_chown
) {
1011 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
1012 * the new mode. That way there's no time window where the file exists under the old owner
1013 * with more than the old access modes — and not under the new owner with more than the new
1014 * access modes either. */
1016 if (S_ISLNK(st
->st_mode
))
1017 log_debug("Skipping temporary mode fix for symlink %s.", path
);
1019 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
1021 if (((m
^ st
->st_mode
) & 07777) == 0)
1022 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
1024 log_action("Would temporarily change", "Temporarily changing",
1025 "%s \"%s\" to mode %o", path
, m
);
1027 r
= fchmod_opath(fd
, m
);
1029 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
1036 log_action("Would change", "Changing",
1037 "%s \"%s\" to owner "UID_FMT
":"GID_FMT
, path
, new_uid
, new_gid
);
1041 new_uid
!= st
->st_uid
? new_uid
: UID_INVALID
,
1042 new_gid
!= st
->st_gid
? new_gid
: GID_INVALID
,
1044 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
1047 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
1048 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
1049 if (do_chmod
|| do_chown
) {
1050 if (S_ISLNK(st
->st_mode
))
1051 log_debug("Skipping mode fix for symlink %s.", path
);
1053 log_action("Would change", "Changing", "%s \"%s\" to mode %o", path
, new_mode
);
1055 r
= fchmod_opath(fd
, new_mode
);
1057 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
1063 return label_fix_full(fd
, /* inode_path= */ NULL
, /* label_path= */ path
, 0);
1066 static int path_open_parent_safe(const char *path
, bool allow_failure
) {
1067 _cleanup_free_
char *dn
= NULL
;
1070 if (!path_is_normalized(path
))
1071 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1072 SYNTHETIC_ERRNO(EINVAL
),
1073 "Failed to open parent of '%s': path not normalized%s.",
1075 allow_failure
? ", ignoring" : "");
1077 r
= path_extract_directory(path
, &dn
);
1079 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1081 "Unable to determine parent directory of '%s'%s: %m",
1083 allow_failure
? ", ignoring" : "");
1085 r
= chase(dn
, arg_root
, allow_failure
? CHASE_SAFE
: CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
1086 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
1089 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1091 "Failed to open path '%s'%s: %m",
1093 allow_failure
? ", ignoring" : "");
1098 static int path_open_safe(const char *path
) {
1101 /* path_open_safe() returns a file descriptor opened with O_PATH after
1102 * verifying that the path doesn't contain unsafe transitions, except
1103 * for its final component as the function does not follow symlink. */
1107 if (!path_is_normalized(path
))
1108 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to open invalid path '%s'.", path
);
1110 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
1112 return r
; /* Unsafe symlink: already covered by CHASE_WARN */
1114 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_ERR
, r
,
1115 "Failed to open path %s%s: %m", path
,
1116 r
== -ENOENT
? ", ignoring" : "");
1121 static int path_set_perms(
1125 CreationMode creation
) {
1127 _cleanup_close_
int fd
= -EBADF
;
1133 fd
= path_open_safe(path
);
1139 return fd_set_perms(c
, i
, fd
, path
, /* st= */ NULL
, creation
);
1142 static int parse_xattrs_from_arg(Item
*i
) {
1148 assert_se(p
= i
->argument
);
1150 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
1152 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
1154 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
1158 r
= split_pair(xattr
, "=", &name
, &value
);
1160 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
1164 if (isempty(name
) || isempty(value
)) {
1165 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
1169 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
1172 name
= value
= NULL
;
1178 static int fd_set_xattrs(
1183 const struct stat
*st
,
1184 CreationMode creation
) {
1193 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
1194 log_action("Would set", "Setting",
1195 "%s extended attribute '%s=%s' on %s", *name
, *value
, path
);
1198 r
= xsetxattr(fd
, /* path = */ NULL
, AT_EMPTY_PATH
, *name
, *value
);
1200 return log_error_errno(r
, "Failed to set extended attribute %s=%s on '%s': %m",
1201 *name
, *value
, path
);
1207 static int path_set_xattrs(
1211 CreationMode creation
) {
1213 _cleanup_close_
int fd
= -EBADF
;
1219 fd
= path_open_safe(path
);
1225 return fd_set_xattrs(c
, i
, fd
, path
, /* st = */ NULL
, creation
);
1228 static int parse_acls_from_arg(Item
*item
) {
1234 /* If append_or_force (= modify) is set, we will not modify the acl
1235 * afterwards, so the mask can be added now if necessary. */
1237 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_access_exec
,
1238 &item
->acl_default
, !item
->append_or_force
);
1240 log_full_errno(arg_graceful
&& IN_SET(r
, -EINVAL
, -ENOENT
, -ESRCH
) ? LOG_DEBUG
: LOG_WARNING
,
1241 r
, "Failed to parse ACL \"%s\", ignoring: %m", item
->argument
);
1243 log_warning("ACLs are not supported, ignoring.");
1250 static int parse_acl_cond_exec(
1252 const struct stat
*st
,
1254 acl_t access
, /* could be empty (NULL) */
1259 acl_permset_t permset
;
1268 if (!S_ISDIR(st
->st_mode
)) {
1269 _cleanup_(acl_freep
) acl_t old
= NULL
;
1271 old
= acl_get_file(path
, ACL_TYPE_ACCESS
);
1277 for (r
= acl_get_entry(old
, ACL_FIRST_ENTRY
, &entry
);
1279 r
= acl_get_entry(old
, ACL_NEXT_ENTRY
, &entry
)) {
1283 if (acl_get_tag_type(entry
, &tag
) < 0)
1286 if (tag
== ACL_MASK
)
1289 /* If not appending, skip ACL definitions */
1290 if (!append
&& IN_SET(tag
, ACL_USER
, ACL_GROUP
))
1293 if (acl_get_permset(entry
, &permset
) < 0)
1296 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1307 /* Check if we're about to set the execute bit in acl_access */
1308 if (!has_exec
&& access
) {
1309 for (r
= acl_get_entry(access
, ACL_FIRST_ENTRY
, &entry
);
1311 r
= acl_get_entry(access
, ACL_NEXT_ENTRY
, &entry
)) {
1313 if (acl_get_permset(entry
, &permset
) < 0)
1316 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1330 _cleanup_(acl_freep
) acl_t parsed
= access
? acl_dup(access
) : acl_init(0);
1334 for (r
= acl_get_entry(cond_exec
, ACL_FIRST_ENTRY
, &entry
);
1336 r
= acl_get_entry(cond_exec
, ACL_NEXT_ENTRY
, &entry
)) {
1338 acl_entry_t parsed_entry
;
1340 if (acl_create_entry(&parsed
, &parsed_entry
) < 0)
1343 if (acl_copy_entry(parsed_entry
, entry
) < 0)
1346 /* We substituted 'X' with 'x' in parse_acl(), so drop execute bit here if not applicable. */
1348 if (acl_get_permset(parsed_entry
, &permset
) < 0)
1351 if (acl_delete_perm(permset
, ACL_EXECUTE
) < 0)
1358 if (!append
) { /* want_mask = true */
1359 r
= calc_acl_mask_if_needed(&parsed
);
1364 *ret
= TAKE_PTR(parsed
);
1369 static int path_set_acl(
1377 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1378 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1383 /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1386 r
= acls_for_file(path
, type
, acl
, &dup
);
1390 r
= calc_acl_mask_if_needed(&dup
);
1398 /* the mask was already added earlier if needed */
1401 r
= add_base_acls_if_needed(&dup
, path
);
1405 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1406 log_action("Would set", "Setting",
1407 "%s %s ACL %s on %s",
1408 type
== ACL_TYPE_ACCESS
? "access" : "default",
1412 acl_set_file(path
, type
, dup
) < 0) {
1413 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1414 /* No error if filesystem doesn't support ACLs. Return negative. */
1417 /* Return positive to indicate we already warned */
1418 return -log_error_errno(errno
,
1419 "Setting %s ACL \"%s\" on %s failed: %m",
1420 type
== ACL_TYPE_ACCESS
? "access" : "default",
1427 static int fd_set_acls(
1432 const struct stat
*st
,
1433 CreationMode creation
) {
1437 _cleanup_(acl_freep
) acl_t access_with_exec_parsed
= NULL
;
1446 if (fstat(fd
, &stbuf
) < 0)
1447 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1451 if (hardlink_vulnerable(st
))
1452 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1453 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1456 if (S_ISLNK(st
->st_mode
)) {
1457 log_debug("Skipping ACL fix for symlink %s.", path
);
1461 if (item
->acl_access_exec
) {
1462 r
= parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd
), st
,
1463 item
->acl_access_exec
,
1465 item
->append_or_force
,
1466 &access_with_exec_parsed
);
1468 return log_error_errno(r
, "Failed to parse conditionalized execute bit for \"%s\": %m", path
);
1470 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, access_with_exec_parsed
, item
->append_or_force
);
1471 } else if (item
->acl_access
)
1472 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1474 /* set only default acls to folders */
1475 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1476 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1478 if (ERRNO_IS_NOT_SUPPORTED(r
)) {
1479 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1483 return -r
; /* already warned in path_set_acl */
1485 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1490 static int path_set_acls(
1494 CreationMode creation
) {
1498 _cleanup_close_
int fd
= -EBADF
;
1504 fd
= path_open_safe(path
);
1510 r
= fd_set_acls(c
, item
, fd
, path
, /* st= */ NULL
, creation
);
1515 static int parse_attribute_from_arg(Item
*item
) {
1516 static const struct {
1520 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1521 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1522 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1523 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1524 { 'c', FS_COMPR_FL
}, /* Compress file */
1525 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1526 { 'e', FS_EXTENT_FL
}, /* Extents */
1527 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1528 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1529 { 's', FS_SECRM_FL
}, /* Secure deletion */
1530 { 'u', FS_UNRM_FL
}, /* Undelete */
1531 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1532 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1533 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1534 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1543 unsigned value
= 0, mask
= 0;
1553 } else if (*p
== '-') {
1556 } else if (*p
== '=') {
1562 if (isempty(p
) && mode
!= MODE_SET
)
1563 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1564 "Setting file attribute on '%s' needs an attribute specification.",
1567 for (; p
&& *p
; p
++) {
1570 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1571 if (*p
== attributes
[i
].character
)
1574 if (i
>= ELEMENTSOF(attributes
))
1575 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1576 "Unknown file attribute '%c' on '%s'.", *p
, item
->path
);
1578 v
= attributes
[i
].value
;
1580 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1585 if (mode
== MODE_SET
)
1586 mask
|= CHATTR_ALL_FL
;
1590 item
->attribute_mask
= mask
;
1591 item
->attribute_value
= value
;
1592 item
->attribute_set
= true;
1597 static int fd_set_attribute(
1602 const struct stat
*st
,
1603 CreationMode creation
) {
1614 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1618 if (fstat(fd
, &stbuf
) < 0)
1619 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1623 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1624 * drivers, not the file system containing the device node. */
1625 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1626 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1627 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1630 f
= item
->attribute_value
& item
->attribute_mask
;
1632 /* Mask away directory-specific flags */
1633 if (!S_ISDIR(st
->st_mode
))
1634 f
&= ~FS_DIRSYNC_FL
;
1636 log_action("Would try to set", "Trying to set",
1637 "%s file attributes 0x%08x on %s",
1638 f
& item
->attribute_mask
,
1642 _cleanup_close_
int procfs_fd
= -EBADF
;
1644 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1646 return log_error_errno(procfs_fd
, "Failed to reopen '%s': %m", path
);
1648 unsigned previous
, current
;
1649 r
= chattr_full(procfs_fd
, NULL
, f
, item
->attribute_mask
, &previous
, ¤t
, CHATTR_FALLBACK_BITWISE
);
1651 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1652 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1653 path
, previous
, current
, (previous
& ~item
->attribute_mask
) | (f
& item
->attribute_mask
));
1655 log_full_errno(ERRNO_IS_IOCTL_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1656 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1657 path
, item
->attribute_value
, item
->attribute_mask
);
1663 static int path_set_attribute(
1667 CreationMode creation
) {
1669 _cleanup_close_
int fd
= -EBADF
;
1674 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1677 fd
= path_open_safe(path
);
1683 return fd_set_attribute(c
, item
, fd
, path
, /* st= */ NULL
, creation
);
1686 static int write_argument_data(Item
*i
, int fd
, const char *path
) {
1693 if (item_binary_argument_size(i
) == 0)
1696 assert(item_binary_argument(i
));
1698 log_action("Would write", "Writing", "%s to \"%s\"", path
);
1701 r
= loop_write(fd
, item_binary_argument(i
), item_binary_argument_size(i
));
1703 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1709 static int write_one_file(Context
*c
, Item
*i
, const char *path
, CreationMode creation
) {
1710 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1711 _cleanup_free_
char *bn
= NULL
;
1717 assert(i
->type
== WRITE_FILE
);
1719 r
= path_extract_filename(path
, &bn
);
1721 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1722 if (r
== O_DIRECTORY
)
1723 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1725 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1726 * can't be changed behind our back. */
1727 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1731 /* Follow symlinks. Open with O_PATH in dry-run mode to make sure we don't use the path inadvertently. */
1732 int flags
= O_NONBLOCK
| O_CLOEXEC
| O_WRONLY
| O_NOCTTY
| i
->append_or_force
* O_APPEND
| arg_dry_run
* O_PATH
;
1733 fd
= openat(dir_fd
, bn
, flags
, i
->mode
);
1735 if (errno
== ENOENT
) {
1736 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1740 if (i
->allow_failure
)
1741 return log_debug_errno(errno
, "Failed to open file \"%s\", ignoring: %m", path
);
1743 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1746 /* 'w' is allowed to write into any kind of files. */
1748 r
= write_argument_data(i
, fd
, path
);
1752 return fd_set_perms(c
, i
, fd
, path
, NULL
, creation
);
1755 static int create_file(
1760 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1761 _cleanup_free_
char *bn
= NULL
;
1762 struct stat stbuf
, *st
= NULL
;
1763 CreationMode creation
;
1769 assert(i
->type
== CREATE_FILE
);
1771 /* 'f' operates on regular files exclusively. */
1773 r
= path_extract_filename(path
, &bn
);
1775 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1776 if (r
== O_DIRECTORY
)
1777 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1780 log_info("Would create file %s", path
);
1783 /* The opening of the directory below would fail if it doesn't exist,
1784 * so log and exit before even trying to do that. */
1787 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1788 * can't be changed behind our back. */
1789 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1794 mac_selinux_create_file_prepare(path
, S_IFREG
);
1795 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1796 mac_selinux_create_file_clear();
1800 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1801 * returns EROFS only if it needs to create the file. */
1803 return log_error_errno(fd
, "Failed to create file %s: %m", path
);
1805 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1806 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1807 * fd_set_perms() report the error if the perms need to be modified. */
1808 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1810 return log_error_errno(errno
, "Failed to reopen file %s: %m", path
);
1812 if (fstat(fd
, &stbuf
) < 0)
1813 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1815 if (!S_ISREG(stbuf
.st_mode
))
1816 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1817 "%s exists and is not a regular file.",
1821 creation
= CREATION_EXISTING
;
1823 r
= write_argument_data(i
, fd
, path
);
1827 creation
= CREATION_NORMAL
;
1830 return fd_set_perms(c
, i
, fd
, path
, st
, creation
);
1833 static int truncate_file(
1838 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1839 _cleanup_free_
char *bn
= NULL
;
1840 struct stat stbuf
, *st
= NULL
;
1841 CreationMode creation
;
1848 assert(i
->type
== TRUNCATE_FILE
|| (i
->type
== CREATE_FILE
&& i
->append_or_force
));
1850 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1851 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1852 * make sure it's a regular one before truncating it. */
1854 r
= path_extract_filename(path
, &bn
);
1856 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1857 if (r
== O_DIRECTORY
)
1858 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for truncation, is a directory.", path
);
1860 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1861 * can't be changed behind our back. */
1862 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1867 log_info("Would truncate %s", path
);
1871 creation
= CREATION_EXISTING
;
1872 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1873 if (fd
== -ENOENT
) {
1874 creation
= CREATION_NORMAL
; /* Didn't work without O_CREATE, try again with */
1877 mac_selinux_create_file_prepare(path
, S_IFREG
);
1878 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1879 mac_selinux_create_file_clear();
1885 return log_error_errno(fd
, "Failed to open/create file %s: %m", path
);
1887 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1888 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1889 * fail with EROFS if they try to modify the target file. */
1891 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1893 if (errno
== ENOENT
)
1894 return log_error_errno(SYNTHETIC_ERRNO(EROFS
),
1895 "Cannot create file %s on a read-only file system.",
1898 return log_error_errno(errno
, "Failed to reopen file %s: %m", path
);
1902 creation
= CREATION_EXISTING
;
1905 if (fstat(fd
, &stbuf
) < 0)
1906 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1908 if (!S_ISREG(stbuf
.st_mode
))
1909 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1910 "%s exists and is not a regular file.",
1913 if (stbuf
.st_size
> 0) {
1914 if (ftruncate(fd
, 0) < 0) {
1915 r
= erofs
? -EROFS
: -errno
;
1916 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1921 log_debug("\"%s\" has been created.", path
);
1923 if (item_binary_argument(i
)) {
1924 r
= write_argument_data(i
, fd
, path
);
1929 return fd_set_perms(c
, i
, fd
, path
, st
, creation
);
1932 static int copy_files(Context
*c
, Item
*i
) {
1933 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
1934 _cleanup_free_
char *bn
= NULL
;
1938 log_action("Would copy", "Copying", "%s tree \"%s\" to \"%s\"", i
->argument
, i
->path
);
1942 r
= path_extract_filename(i
->path
, &bn
);
1944 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
1946 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1947 * path can't be changed behind our back. */
1948 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
1952 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1954 i
->uid_set
? i
->uid
: UID_INVALID
,
1955 i
->gid_set
? i
->gid
: GID_INVALID
,
1956 COPY_REFLINK
| ((i
->append_or_force
) ? COPY_MERGE
: COPY_MERGE_EMPTY
) | COPY_MAC_CREATE
| COPY_HARDLINKS
,
1959 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1961 if (r
< 0) /* Look at original error first */
1962 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1964 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1967 if (fstat(fd
, &st
) < 0)
1968 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
1970 if (stat(i
->argument
, &a
) < 0)
1971 return log_error_errno(errno
, "Failed to stat(%s): %m", i
->argument
);
1973 if (((st
.st_mode
^ a
.st_mode
) & S_IFMT
) != 0) {
1974 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1978 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, _CREATION_MODE_INVALID
);
1981 static int create_directory_or_subvolume(
1986 struct stat
*ret_st
,
1987 CreationMode
*ret_creation
) {
1989 _cleanup_free_
char *bn
= NULL
;
1990 _cleanup_close_
int pfd
= -EBADF
;
1991 CreationMode creation
;
1997 r
= path_extract_filename(path
, &bn
);
1999 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
2001 pfd
= path_open_parent_safe(path
, allow_failure
);
2006 r
= getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
2008 if (r
!= -ENXIO
) /* env var is unset */
2009 log_warning_errno(r
, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
2010 r
= btrfs_is_subvol(empty_to_root(arg_root
)) > 0;
2013 /* Don't create a subvolume unless the root directory is one, too. We do this under
2014 * the assumption that if the root directory is just a plain directory (i.e. very
2015 * lightweight), we shouldn't try to split it up into subvolumes (i.e. more
2016 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
2017 * subvolume set up below their tree only if they specifically set up a btrfs
2018 * subvolume for the root dir too. */
2021 log_action("Would create", "Creating", "%s btrfs subvolume %s", path
);
2023 WITH_UMASK((~mode
) & 0777)
2024 r
= btrfs_subvol_make(pfd
, bn
);
2031 if (!subvol
|| ERRNO_IS_NEG_NOT_SUPPORTED(r
)) {
2032 log_action("Would create", "Creating", "%s directory \"%s\"", path
);
2035 r
= mkdirat_label(pfd
, bn
, mode
);
2041 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2043 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_DIRECTORY
|O_PATH
);
2045 /* We couldn't open it because it is not actually a directory? */
2046 if (errno
== ENOTDIR
)
2047 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "\"%s\" already exists and is not a directory.", path
);
2049 /* Then look at the original error */
2051 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
2053 "Failed to create directory or subvolume \"%s\"%s: %m",
2055 allow_failure
? ", ignoring" : "");
2057 return log_error_errno(errno
, "Failed to open directory/subvolume we just created '%s': %m", path
);
2060 if (fstat(fd
, &st
) < 0)
2061 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
2063 assert(S_ISDIR(st
.st_mode
)); /* we used O_DIRECTORY above */
2065 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation
), path
);
2070 *ret_creation
= creation
;
2075 static int create_directory(
2080 _cleanup_close_
int fd
= -EBADF
;
2081 CreationMode creation
;
2086 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
2089 log_info("Would create directory %s", path
);
2093 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol= */ false, i
->allow_failure
, &st
, &creation
);
2099 return fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2102 static int create_subvolume(
2107 _cleanup_close_
int fd
= -EBADF
;
2108 CreationMode creation
;
2114 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
2117 log_info("Would create subvolume %s", path
);
2121 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol = */ true, i
->allow_failure
, &st
, &creation
);
2127 if (creation
== CREATION_NORMAL
&&
2128 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
2129 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
2131 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
2132 else if (r
== -EROFS
)
2133 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
2134 else if (r
== -ENOTCONN
)
2135 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
2137 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
2139 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
2141 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
2144 r
= fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2145 if (q
< 0) /* prefer the quota change error from above */
2151 static int empty_directory(
2155 CreationMode creation
) {
2157 _cleanup_close_
int fd
= -EBADF
;
2163 assert(i
->type
== EMPTY_DIRECTORY
);
2165 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
2166 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
2169 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
2171 log_debug_errno(r
, "Skipping missing directory: %s", path
);
2175 return log_error_errno(r
, "Failed to open directory '%s': %m", path
);
2177 if (fstat(fd
, &st
) < 0)
2178 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
2179 if (!S_ISDIR(st
.st_mode
)) {
2180 log_warning("'%s' already exists and is not a directory.", path
);
2184 return fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2187 static int create_device(
2192 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
2193 _cleanup_free_
char *bn
= NULL
;
2194 CreationMode creation
;
2200 assert(IN_SET(i
->type
, CREATE_BLOCK_DEVICE
, CREATE_CHAR_DEVICE
));
2201 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
2203 r
= path_extract_filename(i
->path
, &bn
);
2205 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2206 if (r
== O_DIRECTORY
)
2207 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
2208 "Cannot open path '%s' for creating device node, is a directory.", i
->path
);
2211 log_info("Would create device node %s", i
->path
);
2215 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2216 * path can't be changed behind our back. */
2217 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2222 mac_selinux_create_file_prepare(i
->path
, file_type
);
2223 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2224 mac_selinux_create_file_clear();
2226 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2228 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2229 * order anyway and we hence can ignore the error to create the device node */
2230 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2232 /* OK, so opening the inode failed, let's look at the original error then. */
2235 if (ERRNO_IS_PRIVILEGE(r
))
2236 goto handle_privilege
;
2238 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2241 return log_error_errno(errno
, "Failed to open device node '%s' we just created: %m", i
->path
);
2244 if (fstat(fd
, &st
) < 0)
2245 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2247 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0) {
2249 if (i
->append_or_force
) {
2250 fd
= safe_close(fd
);
2253 mac_selinux_create_file_prepare(i
->path
, file_type
);
2254 r
= mknodat_atomic(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
2255 mac_selinux_create_file_clear();
2257 if (ERRNO_IS_PRIVILEGE(r
))
2258 goto handle_privilege
;
2259 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2260 r
= rm_rf_child(dfd
, bn
, REMOVE_PHYSICAL
);
2262 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2264 mac_selinux_create_file_prepare(i
->path
, file_type
);
2265 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2266 mac_selinux_create_file_clear();
2269 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2271 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2273 return log_error_errno(errno
, "Failed to open device node we just created '%s': %m", i
->path
);
2275 /* Validate type before change ownership below */
2276 if (fstat(fd
, &st
) < 0)
2277 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2279 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0)
2280 return log_error_errno(SYNTHETIC_ERRNO(EBADF
),
2281 "Device node we just created is not a device node, refusing.");
2283 creation
= CREATION_FORCE
;
2285 log_warning("\"%s\" already exists and is not a device node.", i
->path
);
2290 log_debug("%s %s device node \"%s\" %u:%u.",
2291 creation_mode_verb_to_string(creation
),
2292 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
2293 i
->path
, major(i
->mode
), minor(i
->mode
));
2295 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2299 "We lack permissions, possibly because of cgroup configuration; "
2300 "skipping creation of device node '%s'.", i
->path
);
2304 static int create_fifo(Context
*c
, Item
*i
) {
2305 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2306 _cleanup_free_
char *bn
= NULL
;
2307 CreationMode creation
;
2313 assert(i
->type
== CREATE_FIFO
);
2315 r
= path_extract_filename(i
->path
, &bn
);
2317 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2318 if (r
== O_DIRECTORY
)
2319 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
2320 "Cannot open path '%s' for creating FIFO, is a directory.", i
->path
);
2323 log_info("Would create fifo %s", i
->path
);
2327 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2332 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2333 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2334 mac_selinux_create_file_clear();
2337 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2339 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
2340 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2343 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
); /* original error! */
2345 return log_error_errno(errno
, "Failed to open FIFO we just created %s: %m", i
->path
);
2348 if (fstat(fd
, &st
) < 0)
2349 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2351 if (!S_ISFIFO(st
.st_mode
)) {
2353 if (i
->append_or_force
) {
2354 fd
= safe_close(fd
);
2357 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2358 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
2359 mac_selinux_create_file_clear();
2361 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2362 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2364 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2366 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2367 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2368 mac_selinux_create_file_clear();
2371 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
);
2373 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2375 return log_error_errno(errno
, "Failed to open FIFO we just created '%s': %m", i
->path
);
2377 /* Validate type before change ownership below */
2378 if (fstat(fd
, &st
) < 0)
2379 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2381 if (!S_ISFIFO(st
.st_mode
))
2382 return log_error_errno(SYNTHETIC_ERRNO(EBADF
),
2383 "FIFO inode we just created is not a FIFO, refusing.");
2385 creation
= CREATION_FORCE
;
2387 log_warning("\"%s\" already exists and is not a FIFO.", i
->path
);
2392 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2394 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2397 static int create_symlink(Context
*c
, Item
*i
) {
2398 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2399 _cleanup_free_
char *bn
= NULL
;
2400 CreationMode creation
;
2408 if (i
->ignore_if_target_missing
) {
2409 r
= chase(i
->argument
, arg_root
, CHASE_SAFE
|CHASE_PREFIX_ROOT
|CHASE_NOFOLLOW
, /* ret_path = */ NULL
, /* ret_fd = */ NULL
);
2411 /* Silently skip over lines where the source file is missing. */
2412 log_info("Symlink source path '%s/%s' does not exist, skipping line.",
2413 empty_to_root(arg_root
), skip_leading_slash(i
->argument
));
2417 return log_error_errno(r
, "Failed to check if symlink source path '%s/%s' exists: %m",
2418 empty_to_root(arg_root
), skip_leading_slash(i
->argument
));
2421 r
= path_extract_filename(i
->path
, &bn
);
2423 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2424 if (r
== O_DIRECTORY
)
2425 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
),
2426 "Cannot open path '%s' for creating symlink, is a directory.", i
->path
);
2429 log_info("Would create symlink %s -> %s", i
->path
, i
->argument
);
2433 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2437 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2438 r
= RET_NERRNO(symlinkat(i
->argument
, pfd
, bn
));
2439 mac_selinux_create_file_clear();
2441 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2443 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2446 return log_error_errno(r
, "Failed to create symlink '%s': %m", i
->path
); /* original error! */
2448 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2451 if (fstat(fd
, &st
) < 0)
2452 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2454 if (S_ISLNK(st
.st_mode
)) {
2455 _cleanup_free_
char *x
= NULL
;
2457 r
= readlinkat_malloc(fd
, "", &x
);
2459 return log_error_errno(r
, "readlinkat(%s) failed: %m", i
->path
);
2461 good
= streq(x
, i
->argument
);
2466 if (!i
->append_or_force
) {
2467 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2471 fd
= safe_close(fd
);
2473 r
= symlinkat_atomic_full(i
->argument
, pfd
, bn
, SYMLINK_LABEL
);
2474 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2475 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2477 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2479 r
= symlinkat_atomic_full(i
->argument
, pfd
, bn
, SYMLINK_LABEL
);
2482 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2484 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2486 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2488 /* Validate type before change ownership below */
2489 if (fstat(fd
, &st
) < 0)
2490 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2492 if (!S_ISLNK(st
.st_mode
))
2493 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Symlink we just created is not a symlink, refusing.");
2495 creation
= CREATION_FORCE
;
2498 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2499 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2502 typedef int (*action_t
)(Context
*c
, Item
*i
, const char *path
, CreationMode creation
);
2503 typedef int (*fdaction_t
)(Context
*c
, Item
*i
, int fd
, const char *path
, const struct stat
*st
, CreationMode creation
);
2510 CreationMode creation
,
2511 fdaction_t action
) {
2522 if (fstat(fd
, &st
) < 0) {
2523 r
= log_error_errno(errno
, "fstat() on file failed: %m");
2527 /* This returns the first error we run into, but nevertheless tries to go on */
2528 r
= action(c
, i
, fd
, path
, &st
, creation
);
2530 if (S_ISDIR(st
.st_mode
)) {
2531 _cleanup_closedir_
DIR *d
= NULL
;
2533 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2534 * reading the directory content. */
2535 d
= opendir(FORMAT_PROC_FD_PATH(fd
));
2537 RET_GATHER(r
, log_error_errno(errno
, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd
)));
2541 FOREACH_DIRENT_ALL(de
, d
, RET_GATHER(r
, -errno
); goto finish
) {
2542 _cleanup_close_
int de_fd
= -EBADF
;
2543 _cleanup_free_
char *de_path
= NULL
;
2545 if (dot_or_dot_dot(de
->d_name
))
2548 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2550 if (errno
!= ENOENT
)
2551 RET_GATHER(r
, log_error_errno(errno
, "Failed to open file '%s': %m", de
->d_name
));
2555 de_path
= path_join(path
, de
->d_name
);
2561 /* Pass ownership of dirent fd over */
2562 RET_GATHER(r
, item_do(c
, i
, TAKE_FD(de_fd
), de_path
, CREATION_EXISTING
, action
));
2571 static int glob_item(Context
*c
, Item
*i
, action_t action
) {
2572 _cleanup_strv_free_
char **paths
= NULL
;
2579 r
= safe_glob_full(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, opendir_nomod
, &paths
);
2583 return log_error_errno(r
, "Failed to glob '%s': %m", i
->path
);
2586 STRV_FOREACH(fn
, paths
)
2587 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2588 RET_GATHER(r
, action(c
, i
, *fn
, CREATION_EXISTING
));
2593 static int glob_item_recursively(
2596 fdaction_t action
) {
2598 _cleanup_strv_free_
char **paths
= NULL
;
2605 r
= safe_glob_full(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, opendir_nomod
, &paths
);
2609 return log_error_errno(r
, "Failed to glob '%s': %m", i
->path
);
2612 STRV_FOREACH(fn
, paths
) {
2613 _cleanup_close_
int fd
= -EBADF
;
2615 /* Make sure we won't trigger/follow file object (such as device nodes, automounts, ...)
2616 * pointed out by 'fn' with O_PATH. Note, when O_PATH is used, flags other than
2617 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2619 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
2621 RET_GATHER(r
, log_error_errno(errno
, "Failed to open '%s': %m", *fn
));
2625 RET_GATHER(r
, item_do(c
, i
, TAKE_FD(fd
), *fn
, CREATION_EXISTING
, action
));
2631 static int rm_if_wrong_type_safe(
2634 const struct stat
*parent_st
, /* Only used if follow_links below is true. */
2637 _cleanup_free_
char *parent_name
= NULL
;
2638 bool follow_links
= !FLAGS_SET(flags
, AT_SYMLINK_NOFOLLOW
);
2643 assert((mode
& ~S_IFMT
) == 0);
2644 assert(!follow_links
|| parent_st
);
2645 assert((flags
& ~AT_SYMLINK_NOFOLLOW
) == 0);
2650 if (!filename_is_valid(name
))
2651 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "\"%s\" is not a valid filename.", name
);
2653 r
= fstatat_harder(parent_fd
, name
, &st
, flags
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2655 (void) fd_get_path(parent_fd
, &parent_name
);
2656 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_ERR
, r
,
2657 "Failed to stat \"%s/%s\": %m", parent_name
?: "...", name
);
2660 /* Fail before removing anything if this is an unsafe transition. */
2661 if (follow_links
&& unsafe_transition(parent_st
, &st
)) {
2662 (void) fd_get_path(parent_fd
, &parent_name
);
2663 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK
),
2664 "Unsafe transition from \"%s\" to \"%s\".", parent_name
?: "...", name
);
2667 if ((st
.st_mode
& S_IFMT
) == mode
)
2670 (void) fd_get_path(parent_fd
, &parent_name
);
2671 log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st
.st_mode
& S_IFMT
, parent_name
?: "...", name
);
2673 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2674 * target, so make sure it is identified as a link and not a directory. */
2676 r
= fstatat_harder(parent_fd
, name
, &st
, AT_SYMLINK_NOFOLLOW
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2678 return log_error_errno(r
, "Failed to stat \"%s/%s\": %m", parent_name
?: "...", name
);
2681 /* Do not remove mount points. */
2682 r
= is_mount_point_at(parent_fd
, name
, follow_links
? AT_SYMLINK_FOLLOW
: 0);
2684 (void) log_warning_errno(r
, "Failed to check if \"%s/%s\" is a mount point: %m; continuing.",
2685 parent_name
?: "...", name
);
2687 return log_error_errno(SYNTHETIC_ERRNO(EBUSY
),
2688 "Not removing \"%s/%s\" because it is a mount point.", parent_name
?: "...", name
);
2690 log_action("Would remove", "Removing", "%s %s/%s", parent_name
?: "...", name
);
2692 if ((st
.st_mode
& S_IFMT
) == S_IFDIR
) {
2693 _cleanup_close_
int child_fd
= -EBADF
;
2695 child_fd
= openat(parent_fd
, name
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2697 return log_error_errno(errno
, "Failed to open \"%s/%s\": %m", parent_name
?: "...", name
);
2699 r
= rm_rf_children(TAKE_FD(child_fd
), REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
, &st
);
2701 return log_error_errno(r
, "Failed to remove contents of \"%s/%s\": %m", parent_name
?: "...", name
);
2703 r
= unlinkat_harder(parent_fd
, name
, AT_REMOVEDIR
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2705 r
= unlinkat_harder(parent_fd
, name
, 0, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2707 return log_error_errno(r
, "Failed to remove \"%s/%s\": %m", parent_name
?: "...", name
);
2710 /* This is covered by the log_notice "Wrong file type...".
2711 * It is logged earlier because it gives context to other error messages that might follow. */
2715 /* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2716 static int mkdir_parents_rm_if_wrong_type(mode_t child_mode
, const char *path
) {
2717 _cleanup_close_
int parent_fd
= -EBADF
;
2718 struct stat parent_st
;
2723 assert((child_mode
& ~S_IFMT
) == 0);
2725 path_len
= strlen(path
);
2728 /* rm_if_wrong_type_safe already logs errors. */
2729 return rm_if_wrong_type_safe(child_mode
, AT_FDCWD
, NULL
, path
, AT_SYMLINK_NOFOLLOW
);
2731 if (child_mode
!= 0 && endswith(path
, "/"))
2732 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2733 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path
);
2735 /* Get the parent_fd and stat. */
2736 parent_fd
= openat(AT_FDCWD
, path_is_absolute(path
) ? "/" : ".", O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2738 return log_error_errno(errno
, "Failed to open root: %m");
2740 if (fstat(parent_fd
, &parent_st
) < 0)
2741 return log_error_errno(errno
, "Failed to stat root: %m");
2743 /* Check every parent directory in the path, except the last component */
2744 for (const char *e
= path
;;) {
2745 _cleanup_close_
int next_fd
= -EBADF
;
2746 char t
[path_len
+ 1];
2749 /* Find the start of the next path component. */
2750 s
= e
+ strspn(e
, "/");
2751 /* Find the end of the next path component. */
2752 e
= s
+ strcspn(s
, "/");
2754 /* Copy the path component to t so it can be a null terminated string. */
2755 *mempcpy_typesafe(t
, s
, e
- s
) = 0;
2757 /* Is this the last component? If so, then check the type */
2759 return rm_if_wrong_type_safe(child_mode
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
);
2761 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, 0);
2762 /* Remove dangling symlinks. */
2764 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
);
2768 r
= mkdirat_label(parent_fd
, t
, 0755);
2770 _cleanup_free_
char *parent_name
= NULL
;
2772 (void) fd_get_path(parent_fd
, &parent_name
);
2773 return log_error_errno(r
, "Failed to mkdir \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2777 /* rm_if_wrong_type_safe already logs errors. */
2780 next_fd
= RET_NERRNO(openat(parent_fd
, t
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
));
2782 _cleanup_free_
char *parent_name
= NULL
;
2784 (void) fd_get_path(parent_fd
, &parent_name
);
2785 return log_error_errno(next_fd
, "Failed to open \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2787 r
= RET_NERRNO(fstat(next_fd
, &parent_st
));
2789 _cleanup_free_
char *parent_name
= NULL
;
2791 (void) fd_get_path(parent_fd
, &parent_name
);
2792 return log_error_errno(r
, "Failed to stat \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2795 close_and_replace(parent_fd
, next_fd
);
2799 static int mkdir_parents_item(Item
*i
, mode_t child_mode
) {
2802 if (i
->try_replace
) {
2803 r
= mkdir_parents_rm_if_wrong_type(child_mode
, i
->path
);
2804 if (r
< 0 && r
!= -ENOENT
)
2809 (void) mkdir_parents_label(i
->path
, 0755);
2814 static int create_item(Context
*c
, Item
*i
) {
2820 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
2825 case IGNORE_DIRECTORY_PATH
:
2827 case RECURSIVE_REMOVE_PATH
:
2832 r
= mkdir_parents_item(i
, S_IFREG
);
2836 if ((i
->type
== CREATE_FILE
&& i
->append_or_force
) || i
->type
== TRUNCATE_FILE
)
2837 r
= truncate_file(c
, i
, i
->path
);
2839 r
= create_file(c
, i
, i
->path
);
2845 r
= mkdir_parents_item(i
, 0);
2849 r
= copy_files(c
, i
);
2855 r
= glob_item(c
, i
, write_one_file
);
2861 case CREATE_DIRECTORY
:
2862 case TRUNCATE_DIRECTORY
:
2863 r
= mkdir_parents_item(i
, S_IFDIR
);
2867 r
= create_directory(c
, i
, i
->path
);
2872 case CREATE_SUBVOLUME
:
2873 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2874 case CREATE_SUBVOLUME_NEW_QUOTA
:
2875 r
= mkdir_parents_item(i
, S_IFDIR
);
2879 r
= create_subvolume(c
, i
, i
->path
);
2884 case EMPTY_DIRECTORY
:
2885 r
= glob_item(c
, i
, empty_directory
);
2891 r
= mkdir_parents_item(i
, S_IFIFO
);
2895 r
= create_fifo(c
, i
);
2900 case CREATE_SYMLINK
:
2901 r
= mkdir_parents_item(i
, S_IFLNK
);
2905 r
= create_symlink(c
, i
);
2911 case CREATE_BLOCK_DEVICE
:
2912 case CREATE_CHAR_DEVICE
:
2913 if (have_effective_cap(CAP_MKNOD
) <= 0) {
2914 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2915 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2917 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2921 r
= mkdir_parents_item(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2925 r
= create_device(c
, i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2933 r
= glob_item(c
, i
, path_set_perms
);
2938 case RECURSIVE_RELABEL_PATH
:
2939 r
= glob_item_recursively(c
, i
, fd_set_perms
);
2945 r
= glob_item(c
, i
, path_set_xattrs
);
2950 case RECURSIVE_SET_XATTR
:
2951 r
= glob_item_recursively(c
, i
, fd_set_xattrs
);
2957 r
= glob_item(c
, i
, path_set_acls
);
2962 case RECURSIVE_SET_ACL
:
2963 r
= glob_item_recursively(c
, i
, fd_set_acls
);
2969 r
= glob_item(c
, i
, path_set_attribute
);
2974 case RECURSIVE_SET_ATTRIBUTE
:
2975 r
= glob_item_recursively(c
, i
, fd_set_attribute
);
2984 static int remove_recursive(
2987 const char *instance
,
2988 bool remove_instance
) {
2990 _cleanup_closedir_
DIR *d
= NULL
;
2995 r
= opendir_and_stat(instance
, &d
, &sx
, &mountpoint
);
2999 if (remove_instance
) {
3000 log_action("Would remove", "Removing", "%s file \"%s\".", instance
);
3002 remove(instance
) < 0 &&
3004 return log_error_errno(errno
, "rm %s: %m", instance
);
3009 r
= dir_cleanup(c
, i
, instance
, d
,
3010 /* self_atime_nsec= */ NSEC_INFINITY
,
3011 /* self_mtime_nsec= */ NSEC_INFINITY
,
3012 /* cutoff_nsec= */ NSEC_INFINITY
,
3013 sx
.stx_dev_major
, sx
.stx_dev_minor
,
3016 /* keep_this_level= */ false,
3017 /* age_by_file= */ 0,
3018 /* age_by_dir= */ 0);
3022 if (remove_instance
) {
3023 log_action("Would remove", "Removing", "%s directory \"%s\".", instance
);
3025 r
= RET_NERRNO(rmdir(instance
));
3027 bool fatal
= !IN_SET(r
, -ENOENT
, -ENOTEMPTY
);
3028 log_full_errno(fatal
? LOG_ERR
: LOG_DEBUG
, r
, "Failed to remove %s: %m", instance
);
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);
3041 static int purge_item(Context
*c
, Item
*i
) {
3044 if (!needs_purge(i
->type
))
3050 log_debug("Running purge action for entry %c %s", (char) i
->type
, i
->path
);
3052 if (needs_glob(i
->type
))
3053 return glob_item(c
, i
, purge_item_instance
);
3055 return purge_item_instance(c
, i
, i
->path
, CREATION_EXISTING
);
3058 static int remove_item_instance(
3061 const char *instance
,
3062 CreationMode creation
) {
3070 log_action("Would remove", "Removing", "%s \"%s\".", instance
);
3072 remove(instance
) < 0 &&
3074 return log_error_errno(errno
, "rm %s: %m", instance
);
3078 case RECURSIVE_REMOVE_PATH
:
3079 return remove_recursive(c
, i
, instance
, /* remove_instance= */ true);
3082 assert_not_reached();
3086 static int remove_item(Context
*c
, Item
*i
) {
3090 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
3094 case TRUNCATE_DIRECTORY
:
3095 return remove_recursive(c
, i
, i
->path
, /* remove_instance= */ false);
3098 case RECURSIVE_REMOVE_PATH
:
3099 return glob_item(c
, i
, remove_item_instance
);
3106 static char *age_by_to_string(AgeBy ab
, bool is_dir
) {
3107 static const char ab_map
[] = { 'a', 'b', 'c', 'm' };
3111 ret
= new(char, ELEMENTSOF(ab_map
) + 1);
3115 for (size_t i
= 0; i
< ELEMENTSOF(ab_map
); i
++)
3117 ret
[j
++] = is_dir
? ascii_toupper(ab_map
[i
]) : ab_map
[i
];
3123 static int clean_item_instance(
3126 const char* instance
,
3127 CreationMode creation
) {
3134 usec_t n
= now(CLOCK_REALTIME
);
3138 usec_t cutoff
= n
- i
->age
;
3140 _cleanup_closedir_
DIR *d
= NULL
;
3145 r
= opendir_and_stat(instance
, &d
, &sx
, &mountpoint
);
3149 if (DEBUG_LOGGING
) {
3150 _cleanup_free_
char *ab_f
= NULL
, *ab_d
= NULL
;
3152 ab_f
= age_by_to_string(i
->age_by_file
, false);
3156 ab_d
= age_by_to_string(i
->age_by_dir
, true);
3160 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
3161 mountpoint
? "mount point" : "directory",
3163 FORMAT_TIMESTAMP_STYLE(cutoff
, TIMESTAMP_US
),
3167 return dir_cleanup(c
, i
, instance
, d
,
3168 statx_timestamp_load_nsec(&sx
.stx_atime
),
3169 statx_timestamp_load_nsec(&sx
.stx_mtime
),
3170 cutoff
* NSEC_PER_USEC
,
3171 sx
.stx_dev_major
, sx
.stx_dev_minor
,
3173 MAX_DEPTH
, i
->keep_first_level
,
3174 i
->age_by_file
, i
->age_by_dir
);
3177 static int clean_item(Context
*c
, Item
*i
) {
3181 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
3185 case CREATE_DIRECTORY
:
3186 case TRUNCATE_DIRECTORY
:
3187 case CREATE_SUBVOLUME
:
3188 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
3189 case CREATE_SUBVOLUME_NEW_QUOTA
:
3191 clean_item_instance(c
, i
, i
->path
, CREATION_EXISTING
);
3194 case EMPTY_DIRECTORY
:
3196 case IGNORE_DIRECTORY_PATH
:
3197 return glob_item(c
, i
, clean_item_instance
);
3204 static int process_item(
3207 OperationMask operation
) {
3210 _cleanup_free_
char *_path
= NULL
;
3217 todo
= operation
& ~i
->done
;
3218 if (todo
== 0) /* Everything already done? */
3221 i
->done
|= operation
;
3224 if (string_is_glob(path
)) {
3225 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3226 * for the non-glob part. */
3228 r
= glob_non_glob_prefix(path
, &_path
);
3229 if (r
< 0 && r
!= -ENOENT
)
3230 return log_debug_errno(r
, "Failed to deglob path: %m");
3235 r
= chase(path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_NONEXISTENT
|CHASE_WARN
, NULL
, NULL
);
3236 if (r
== -EREMOTE
) {
3237 log_notice_errno(r
, "Skipping %s", i
->path
); /* We log the configured path, to not confuse the user. */
3241 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
3243 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(c
, i
) : 0;
3244 /* Failure can only be tolerated for create */
3245 if (i
->allow_failure
)
3248 RET_GATHER(r
, FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(c
, i
) : 0);
3249 RET_GATHER(r
, FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(c
, i
) : 0);
3250 RET_GATHER(r
, FLAGS_SET(operation
, OPERATION_PURGE
) ? purge_item(c
, i
) : 0);
3255 static int process_item_array(
3258 OperationMask operation
) {
3265 /* Create any parent first. */
3266 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
3267 r
= process_item_array(c
, array
->parent
, operation
& OPERATION_CREATE
);
3269 /* Clean up all children first */
3270 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
|OPERATION_PURGE
)) && !set_isempty(array
->children
)) {
3273 SET_FOREACH(cc
, array
->children
)
3274 RET_GATHER(r
, process_item_array(c
, cc
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
|OPERATION_PURGE
)));
3277 FOREACH_ARRAY(item
, array
->items
, array
->n_items
)
3278 RET_GATHER(r
, process_item(c
, item
, operation
));
3283 static void item_free_contents(Item
*i
) {
3287 free(i
->binary_argument
);
3288 strv_free(i
->xattrs
);
3292 acl_free(i
->acl_access
);
3294 if (i
->acl_access_exec
)
3295 acl_free(i
->acl_access_exec
);
3298 acl_free(i
->acl_default
);
3302 static ItemArray
* item_array_free(ItemArray
*a
) {
3306 FOREACH_ARRAY(item
, a
->items
, a
->n_items
)
3307 item_free_contents(item
);
3309 set_free(a
->children
);
3314 static int item_compare(const Item
*a
, const Item
*b
) {
3315 /* Make sure that the ownership taking item is put first, so
3316 * that we first create the node, and then can adjust it */
3318 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
3320 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
3323 return CMP(a
->type
, b
->type
);
3326 static bool item_compatible(const Item
*a
, const Item
*b
) {
3329 assert(streq(a
->path
, b
->path
));
3331 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
3332 /* check if the items are the same */
3333 return memcmp_nn(item_binary_argument(a
), item_binary_argument_size(a
),
3334 item_binary_argument(b
), item_binary_argument_size(b
)) == 0 &&
3336 a
->uid_set
== b
->uid_set
&&
3338 a
->uid_only_create
== b
->uid_only_create
&&
3340 a
->gid_set
== b
->gid_set
&&
3342 a
->gid_only_create
== b
->gid_only_create
&&
3344 a
->mode_set
== b
->mode_set
&&
3345 a
->mode
== b
->mode
&&
3346 a
->mode_only_create
== b
->mode_only_create
&&
3348 a
->age_set
== b
->age_set
&&
3351 a
->age_by_file
== b
->age_by_file
&&
3352 a
->age_by_dir
== b
->age_by_dir
&&
3354 a
->mask_perms
== b
->mask_perms
&&
3356 a
->keep_first_level
== b
->keep_first_level
&&
3358 a
->major_minor
== b
->major_minor
;
3363 static bool should_include_path(const char *path
) {
3364 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
3365 if (path_startswith(path
, *prefix
)) {
3366 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
3371 STRV_FOREACH(prefix
, arg_include_prefixes
)
3372 if (path_startswith(path
, *prefix
)) {
3373 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
3377 /* no matches, so we should include this path only if we have no allow list at all */
3378 if (strv_isempty(arg_include_prefixes
))
3381 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
3385 static int specifier_expansion_from_arg(const Specifier
*specifier_table
, Item
*i
) {
3395 case CREATE_SYMLINK
:
3399 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
3402 l
= cunescape(i
->argument
, 0, &unescaped
);
3404 return log_error_errno(l
, "Failed to unescape parameter to write: %s", i
->argument
);
3406 r
= specifier_printf(unescaped
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &resolved
);
3410 return free_and_replace(i
->argument
, resolved
);
3413 case RECURSIVE_SET_XATTR
:
3414 STRV_FOREACH(xattr
, i
->xattrs
) {
3415 _cleanup_free_
char *resolved
= NULL
;
3417 r
= specifier_printf(*xattr
, SIZE_MAX
, specifier_table
, arg_root
, NULL
, &resolved
);
3421 free_and_replace(*xattr
, resolved
);
3430 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
3437 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges
3438 * lines in some cases and detects conflicts in others. If files/directories are specified through
3439 * two equivalent lines this is problematic as neither case will be detected. Ideally we'd detect
3440 * these cases by resolving symlinks early, but that's precisely not what we can do here as this code
3441 * very likely is running very early on, at a time where the paths in question are not available yet,
3442 * or even more importantly, our own tmpfiles rules might create the paths that are intermediary to
3443 * the listed paths. We can't really cover the generic case, but the least we can do is cover the
3444 * specific case of /var/run vs. /run, as /var/run is a legacy name for /run only, and we explicitly
3445 * document that and require that on systemd systems the former is a symlink to the latter. Moreover
3446 * files below this path are by far the primary use case for tmpfiles.d/. */
3448 k
= path_startswith(*path
, "/var/run/");
3449 if (isempty(k
)) /* Don't complain about paths other than under /var/run,
3450 * and not about /var/run itself either. */
3453 n
= path_join("/run", k
);
3457 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation
3458 * automatically, hence there's no immediate need for action by the user. However, in the interest of
3459 * making things less confusing to the user, let's still inform the user that these snippets should
3460 * really be updated. */
3461 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
3462 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3465 free_and_replace(*path
, n
);
3470 static int find_uid(const char *user
, uid_t
*ret_uid
, Hashmap
**cache
) {
3476 /* First: parse as numeric UID string */
3477 r
= parse_uid(user
, ret_uid
);
3481 /* Second: pass to NSS if we are running "online" */
3483 return get_user_creds(&user
, ret_uid
, NULL
, NULL
, NULL
, 0);
3485 /* Third, synthesize "root" unconditionally */
3486 if (streq(user
, "root")) {
3491 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3492 return name_to_uid_offline(arg_root
, user
, ret_uid
, cache
);
3495 static int find_gid(const char *group
, gid_t
*ret_gid
, Hashmap
**cache
) {
3501 /* First: parse as numeric GID string */
3502 r
= parse_gid(group
, ret_gid
);
3506 /* Second: pass to NSS if we are running "online" */
3508 return get_group_creds(&group
, ret_gid
, 0);
3510 /* Third, synthesize "root" unconditionally */
3511 if (streq(group
, "root")) {
3516 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3517 return name_to_gid_offline(arg_root
, group
, ret_gid
, cache
);
3520 static int parse_age_by_from_arg(const char *age_by_str
, Item
*item
) {
3521 AgeBy ab_f
= 0, ab_d
= 0;
3523 static const struct {
3526 } age_by_types
[] = {
3527 { 'a', AGE_BY_ATIME
},
3528 { 'b', AGE_BY_BTIME
},
3529 { 'c', AGE_BY_CTIME
},
3530 { 'm', AGE_BY_MTIME
},
3536 if (isempty(age_by_str
))
3539 for (const char *s
= age_by_str
; *s
!= 0; s
++) {
3542 /* Ignore whitespace. */
3543 if (strchr(WHITESPACE
, *s
))
3546 for (i
= 0; i
< ELEMENTSOF(age_by_types
); i
++) {
3547 /* Check lower-case for files, upper-case for directories. */
3548 if (*s
== age_by_types
[i
].age_by_chr
) {
3549 ab_f
|= age_by_types
[i
].age_by_flag
;
3551 } else if (*s
== ascii_toupper(age_by_types
[i
].age_by_chr
)) {
3552 ab_d
|= age_by_types
[i
].age_by_flag
;
3557 /* Invalid character. */
3558 if (i
>= ELEMENTSOF(age_by_types
))
3563 if (ab_f
== 0 && ab_d
== 0)
3566 item
->age_by_file
= ab_f
> 0 ? ab_f
: AGE_BY_DEFAULT_FILE
;
3567 item
->age_by_dir
= ab_d
> 0 ? ab_d
: AGE_BY_DEFAULT_DIR
;
3572 static bool is_duplicated_item(ItemArray
*existing
, const Item
*i
) {
3576 FOREACH_ARRAY(e
, existing
->items
, existing
->n_items
) {
3577 if (item_compatible(e
, i
))
3580 /* Only multiple 'w+' lines for the same path are allowed. */
3581 if (e
->type
!= WRITE_FILE
|| !e
->append_or_force
||
3582 i
->type
!= WRITE_FILE
|| !i
->append_or_force
)
3589 static int parse_line(
3593 bool *invalid_config
,
3596 Context
*c
= ASSERT_PTR(context
);
3597 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
3598 _cleanup_(item_free_contents
) Item i
= {
3599 /* The "age-by" argument considers all file timestamp types by default. */
3600 .age_by_file
= AGE_BY_DEFAULT_FILE
,
3601 .age_by_dir
= AGE_BY_DEFAULT_DIR
,
3603 ItemArray
*existing
;
3605 bool append_or_force
= false, boot
= false, allow_failure
= false, try_replace
= false,
3606 unbase64
= false, from_cred
= false, missing_user_or_group
= false, purge
= false,
3607 ignore_if_target_missing
= false;
3614 const Specifier specifier_table
[] = {
3615 { 'h', specifier_user_home
, NULL
},
3617 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
3618 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
3619 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
3620 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
3622 COMMON_SYSTEM_SPECIFIERS
,
3623 COMMON_CREDS_SPECIFIERS(arg_runtime_scope
),
3624 COMMON_TMP_SPECIFIERS
,
3628 r
= extract_many_words(
3631 EXTRACT_UNQUOTE
| EXTRACT_CUNESCAPE
,
3639 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3640 /* invalid quoting and such or an unknown specifier */
3641 *invalid_config
= true;
3642 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to parse line: %m");
3644 *invalid_config
= true;
3645 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Syntax error.");
3648 if (!empty_or_dash(buffer
)) {
3649 i
.argument
= strdup(buffer
);
3654 if (isempty(action
)) {
3655 *invalid_config
= true;
3656 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3657 "Command too short '%s'.", action
);
3660 for (int pos
= 1; action
[pos
]; pos
++)
3661 if (action
[pos
] == '!' && !boot
)
3663 else if (action
[pos
] == '+' && !append_or_force
)
3664 append_or_force
= true;
3665 else if (action
[pos
] == '-' && !allow_failure
)
3666 allow_failure
= true;
3667 else if (action
[pos
] == '=' && !try_replace
)
3669 else if (action
[pos
] == '~' && !unbase64
)
3671 else if (action
[pos
] == '^' && !from_cred
)
3673 else if (action
[pos
] == '$' && !purge
)
3675 else if (action
[pos
] == '?' && !ignore_if_target_missing
)
3676 ignore_if_target_missing
= true;
3678 *invalid_config
= true;
3679 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3680 "Unknown modifiers in command: %s", action
);
3683 if (boot
&& !arg_boot
) {
3684 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0,
3685 "Ignoring entry %s \"%s\" because --boot is not specified.", action
, path
);
3690 i
.append_or_force
= append_or_force
;
3691 i
.allow_failure
= allow_failure
;
3692 i
.try_replace
= try_replace
;
3694 i
.ignore_if_target_missing
= ignore_if_target_missing
;
3696 r
= specifier_printf(path
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &i
.path
);
3697 if (ERRNO_IS_NEG_NOINFO(r
))
3698 return log_unresolvable_specifier(fname
, line
);
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
);
3706 r
= patch_var_run(fname
, line
, &i
.path
);
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
);
3716 path_simplify(i
.path
);
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
:
3728 case IGNORE_DIRECTORY_PATH
:
3730 case RECURSIVE_REMOVE_PATH
:
3733 case RECURSIVE_RELABEL_PATH
:
3735 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0,
3736 "%c lines don't take argument fields, ignoring.", (char) i
.type
);
3743 case CREATE_SYMLINK
:
3745 *invalid_config
= true;
3746 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3747 "base64 decoding not supported for symlink targets.");
3753 *invalid_config
= true;
3754 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3755 "Write file requires argument.");
3761 *invalid_config
= true;
3762 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3763 "base64 decoding not supported for copy sources.");
3767 case CREATE_CHAR_DEVICE
:
3768 case CREATE_BLOCK_DEVICE
:
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.");
3776 *invalid_config
= true;
3777 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3778 "Device file requires argument.");
3781 r
= parse_devnum(i
.argument
, &i
.major_minor
);
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
);
3791 case RECURSIVE_SET_XATTR
:
3793 *invalid_config
= true;
3794 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3795 "base64 decoding not supported for extended attributes.");
3798 *invalid_config
= true;
3799 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3800 "Set extended attribute requires argument.");
3802 r
= parse_xattrs_from_arg(&i
);
3808 case RECURSIVE_SET_ACL
:
3810 *invalid_config
= true;
3811 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3812 "base64 decoding not supported for ACLs.");
3815 *invalid_config
= true;
3816 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3817 "Set ACLs requires argument.");
3819 r
= parse_acls_from_arg(&i
);
3825 case RECURSIVE_SET_ATTRIBUTE
:
3827 *invalid_config
= true;
3828 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3829 "base64 decoding not supported for file attributes.");
3832 *invalid_config
= true;
3833 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3834 "Set file attribute requires argument.");
3836 r
= parse_attribute_from_arg(&i
);
3837 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3838 *invalid_config
= true;
3844 *invalid_config
= true;
3845 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3846 "Unknown command type '%c'.", (char) i
.type
);
3849 if (i
.purge
&& !needs_purge(i
.type
)) {
3850 *invalid_config
= true;
3851 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3852 "Purge flag '$' combined with line type '%c' which does not support purging.", (char) i
.type
);
3855 if (i
.ignore_if_target_missing
&& !supports_ignore_if_target_missing(i
.type
)) {
3856 *invalid_config
= true;
3857 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3858 "Modifier '?' combined with line type '%c' which does not support this modifier.", (char) i
.type
);
3861 if (!should_include_path(i
.path
))
3865 /* Do specifier expansion except if base64 mode is enabled */
3866 r
= specifier_expansion_from_arg(specifier_table
, &i
);
3867 if (ERRNO_IS_NEG_NOINFO(r
))
3868 return log_unresolvable_specifier(fname
, line
);
3870 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3871 *invalid_config
= true;
3872 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
,
3873 "Failed to substitute specifiers in argument: %m");
3878 case CREATE_SYMLINK
:
3880 i
.argument
= path_join("/usr/share/factory", i
.path
);
3889 i
.argument
= path_join("/usr/share/factory", i
.path
);
3892 } else if (!path_is_absolute(i
.argument
)) {
3893 *invalid_config
= true;
3894 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3895 "Source path '%s' is not absolute.", i
.argument
);
3899 if (!empty_or_root(arg_root
)) {
3902 p
= path_join(arg_root
, i
.argument
);
3905 free_and_replace(i
.argument
, p
);
3908 path_simplify(i
.argument
);
3910 if (access_nofollow(i
.argument
, F_OK
) == -ENOENT
) {
3911 /* Silently skip over lines where the source file is missing. */
3912 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0,
3913 "Copy source path '%s' does not exist, skipping line.", i
.argument
);
3925 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
3926 "Reading from credential requested, but no credential name specified.");
3927 if (!credential_name_valid(i
.argument
))
3928 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
),
3929 "Credential name not valid: %s", i
.argument
);
3931 r
= read_credential(i
.argument
, &i
.binary_argument
, &i
.binary_argument_size
);
3932 if (IN_SET(r
, -ENXIO
, -ENOENT
)) {
3933 /* Silently skip over lines that have no credentials passed */
3934 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0,
3935 "Credential '%s' not specified, skipping line.", i
.argument
);
3939 return log_error_errno(r
, "Failed to read credential '%s': %m", i
.argument
);
3942 /* If base64 decoding is requested, do so now */
3943 if (unbase64
&& item_binary_argument(&i
)) {
3944 _cleanup_free_
void *data
= NULL
;
3945 size_t data_size
= 0;
3947 r
= unbase64mem_full(item_binary_argument(&i
), item_binary_argument_size(&i
), /* secure = */ false,
3950 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to base64 decode specified argument '%s': %m", i
.argument
);
3952 free_and_replace(i
.binary_argument
, data
);
3953 i
.binary_argument_size
= data_size
;
3956 if (!empty_or_root(arg_root
)) {
3959 p
= path_join(arg_root
, i
.path
);
3962 free_and_replace(i
.path
, p
);
3965 if (!empty_or_dash(user
)) {
3968 u
= startswith(user
, ":");
3970 i
.uid_only_create
= true;
3974 r
= find_uid(u
, &i
.uid
, &c
->uid_cache
);
3975 if (r
== -ESRCH
&& arg_graceful
) {
3976 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, r
,
3977 "%s: user '%s' not found, not adjusting ownership.", i
.path
, u
);
3978 missing_user_or_group
= true;
3980 *invalid_config
= true;
3981 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve user '%s': %m", u
);
3986 if (!empty_or_dash(group
)) {
3989 g
= startswith(group
, ":");
3991 i
.gid_only_create
= true;
3995 r
= find_gid(g
, &i
.gid
, &c
->gid_cache
);
3996 if (r
== -ESRCH
&& arg_graceful
) {
3997 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, r
,
3998 "%s: group '%s' not found, not adjusting ownership.", i
.path
, g
);
3999 missing_user_or_group
= true;
4001 *invalid_config
= true;
4002 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve group '%s': %m", g
);
4007 if (!empty_or_dash(mode
)) {
4011 for (mm
= mode
;; mm
++)
4013 i
.mask_perms
= true;
4014 else if (*mm
== ':')
4015 i
.mode_only_create
= true;
4019 r
= parse_mode(mm
, &m
);
4021 *invalid_config
= true;
4022 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid mode '%s'.", mode
);
4028 i
.mode
= IN_SET(i
.type
,
4032 CREATE_SUBVOLUME_INHERIT_QUOTA
,
4033 CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
4035 if (missing_user_or_group
&& (i
.mode
& ~0777) != 0) {
4036 /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
4037 mode_t adjusted
= i
.mode
& 0777;
4038 log_syntax(NULL
, LOG_INFO
, fname
, line
, 0,
4039 "Changing mode 0%o to 0%o because of changed ownership.", i
.mode
, adjusted
);
4043 if (!empty_or_dash(age
)) {
4044 const char *a
= age
;
4045 _cleanup_free_
char *seconds
= NULL
, *age_by
= NULL
;
4048 i
.keep_first_level
= true;
4052 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
4053 r
= split_pair(a
, ":", &age_by
, &seconds
);
4056 if (r
< 0 && r
!= -EINVAL
)
4057 return log_error_errno(r
, "Failed to parse age-by for '%s': %m", age
);
4059 /* We found a ":", parse the "age-by" part. */
4060 r
= parse_age_by_from_arg(age_by
, &i
);
4064 *invalid_config
= true;
4065 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age-by '%s'.", age_by
);
4068 /* For parsing the "age" part, after the ":". */
4072 r
= parse_sec(a
, &i
.age
);
4074 *invalid_config
= true;
4075 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age '%s'.", a
);
4081 h
= needs_glob(i
.type
) ? c
->globs
: c
->items
;
4083 existing
= ordered_hashmap_get(h
, i
.path
);
4085 if (is_duplicated_item(existing
, &i
)) {
4086 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
4087 "Duplicate line for path \"%s\", ignoring.", i
.path
);
4091 existing
= new0(ItemArray
, 1);
4095 r
= ordered_hashmap_put(h
, i
.path
, existing
);
4102 if (!GREEDY_REALLOC(existing
->items
, existing
->n_items
+ 1))
4105 existing
->items
[existing
->n_items
++] = TAKE_STRUCT(i
);
4107 /* Sort item array, to enforce stable ordering of application */
4108 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
4113 static int cat_config(char **config_dirs
, char **args
) {
4114 _cleanup_strv_free_
char **files
= NULL
;
4117 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
4121 pager_open(arg_pager_flags
);
4123 return cat_files(NULL
, files
, arg_cat_flags
);
4126 static int exclude_default_prefixes(void) {
4129 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
4130 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
4131 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
4132 * all kinds of files created/adjusted underneath these mount points. */
4134 r
= strv_extend_many(
4135 &arg_exclude_prefixes
,
4143 strv_uniq(arg_exclude_prefixes
);
4147 static int help(void) {
4148 _cleanup_free_
char *link
= NULL
;
4151 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
4155 printf("%1$s COMMAND [OPTIONS...] [CONFIGURATION FILE...]\n"
4156 "\n%2$sCreate, delete, and clean up files and directories.%4$s\n"
4157 "\n%3$sCommands:%4$s\n"
4158 " --create Create and adjust files and directories\n"
4159 " --clean Clean up files and directories\n"
4160 " --remove Remove files and directories marked for removal\n"
4161 " --purge Delete files and directories marked for creation in\n"
4162 " specified configuration files (careful!)\n"
4163 " --cat-config Show configuration files\n"
4164 " --tldr Show non-comment parts of configuration files\n"
4165 " -h --help Show this help\n"
4166 " --version Show package version\n"
4167 "\n%3$sOptions:%4$s\n"
4168 " --user Execute user configuration\n"
4169 " --boot Execute actions only safe at boot\n"
4170 " --graceful Quietly ignore unknown users or groups\n"
4171 " --prefix=PATH Only apply rules with the specified prefix\n"
4172 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
4173 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
4174 " --root=PATH Operate on an alternate filesystem root\n"
4175 " --image=PATH Operate on disk image as filesystem root\n"
4176 " --image-policy=POLICY Specify disk image dissection policy\n"
4177 " --replace=PATH Treat arguments as replacement for PATH\n"
4178 " --dry-run Just print what would be done\n"
4179 " --no-pager Do not pipe output into a pager\n"
4180 "\nSee the %5$s for details.\n",
4181 program_invocation_short_name
,
4190 static int parse_argv(int argc
, char *argv
[]) {
4192 ARG_VERSION
= 0x100,
4212 static const struct option options
[] = {
4213 { "help", no_argument
, NULL
, 'h' },
4214 { "user", no_argument
, NULL
, ARG_USER
},
4215 { "version", no_argument
, NULL
, ARG_VERSION
},
4216 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
4217 { "tldr", no_argument
, NULL
, ARG_TLDR
},
4218 { "create", no_argument
, NULL
, ARG_CREATE
},
4219 { "clean", no_argument
, NULL
, ARG_CLEAN
},
4220 { "remove", no_argument
, NULL
, ARG_REMOVE
},
4221 { "purge", no_argument
, NULL
, ARG_PURGE
},
4222 { "boot", no_argument
, NULL
, ARG_BOOT
},
4223 { "graceful", no_argument
, NULL
, ARG_GRACEFUL
},
4224 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
4225 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
4226 { "root", required_argument
, NULL
, ARG_ROOT
},
4227 { "image", required_argument
, NULL
, ARG_IMAGE
},
4228 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
4229 { "replace", required_argument
, NULL
, ARG_REPLACE
},
4230 { "dry-run", no_argument
, NULL
, ARG_DRY_RUN
},
4231 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
4240 while ((c
= getopt_long(argc
, argv
, "hE", options
, NULL
)) >= 0)
4250 case ARG_CAT_CONFIG
:
4251 arg_cat_flags
= CAT_CONFIG_ON
;
4255 arg_cat_flags
= CAT_TLDR
;
4259 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
4263 arg_operation
|= OPERATION_CREATE
;
4267 arg_operation
|= OPERATION_CLEAN
;
4271 arg_operation
|= OPERATION_REMOVE
;
4279 arg_operation
|= OPERATION_PURGE
;
4283 arg_graceful
= true;
4287 if (strv_extend(&arg_include_prefixes
, optarg
) < 0)
4291 case ARG_EXCLUDE_PREFIX
:
4292 if (strv_extend(&arg_exclude_prefixes
, optarg
) < 0)
4297 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
4304 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
4305 "This systemd-tmpfiles version is compiled without support for --image=.");
4307 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
4311 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4315 r
= exclude_default_prefixes();
4321 case ARG_IMAGE_POLICY
:
4322 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
4328 if (!path_is_absolute(optarg
))
4329 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4330 "The argument to --replace= must be an absolute path.");
4331 if (!endswith(optarg
, ".conf"))
4332 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4333 "The argument to --replace= must have the extension '.conf'.");
4335 arg_replace
= optarg
;
4343 arg_pager_flags
|= PAGER_DISABLE
;
4350 assert_not_reached();
4353 if (arg_operation
== 0 && arg_cat_flags
== CAT_CONFIG_OFF
)
4354 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4355 "You need to specify at least one of --clean, --create, --remove, or --purge.");
4357 if (FLAGS_SET(arg_operation
, OPERATION_PURGE
) && optind
>= argc
)
4358 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4359 "Refusing --purge without specification of a configuration file.");
4361 if (arg_replace
&& arg_cat_flags
!= CAT_CONFIG_OFF
)
4362 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4363 "Option --replace= is not supported with --cat-config/--tldr.");
4365 if (arg_replace
&& optind
>= argc
)
4366 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4367 "When --replace= is given, some configuration items must be specified.");
4369 if (arg_root
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
)
4370 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4371 "Combination of --user and --root= is not supported.");
4373 if (arg_image
&& arg_root
)
4374 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4375 "Please specify either --root= or --image=, the combination of both is not supported.");
4380 static int read_config_file(
4385 bool *invalid_config
) {
4393 r
= conf_file_read(arg_root
, (const char**) config_dirs
, fn
,
4394 parse_line
, c
, ignore_enoent
, invalid_config
);
4398 /* we have to determine age parameter for each entry of type X */
4399 ORDERED_HASHMAP_FOREACH(ia
, c
->globs
)
4400 FOREACH_ARRAY(i
, ia
->items
, ia
->n_items
) {
4402 Item
*candidate_item
= NULL
;
4404 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
4407 ORDERED_HASHMAP_FOREACH(ja
, c
->items
)
4408 FOREACH_ARRAY(j
, ja
->items
, ja
->n_items
) {
4409 if (!IN_SET(j
->type
, CREATE_DIRECTORY
,
4412 CREATE_SUBVOLUME_INHERIT_QUOTA
,
4413 CREATE_SUBVOLUME_NEW_QUOTA
))
4416 if (path_equal(j
->path
, i
->path
)) {
4422 ? (path_startswith(j
->path
, candidate_item
->path
) && fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)
4423 : path_startswith(i
->path
, j
->path
) != NULL
)
4427 if (candidate_item
&& candidate_item
->age_set
) {
4428 i
->age
= candidate_item
->age
;
4436 static int parse_arguments(
4440 bool *invalid_config
) {
4445 STRV_FOREACH(arg
, args
) {
4446 r
= read_config_file(c
, config_dirs
, *arg
, false, invalid_config
);
4454 static int read_config_files(
4458 bool *invalid_config
) {
4460 _cleanup_strv_free_
char **files
= NULL
;
4461 _cleanup_free_
char *p
= NULL
;
4466 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
4470 STRV_FOREACH(f
, files
)
4471 if (p
&& path_equal(*f
, p
)) {
4472 log_debug("Parsing arguments at position \"%s\"%s", *f
, glyph(GLYPH_ELLIPSIS
));
4474 r
= parse_arguments(c
, config_dirs
, args
, invalid_config
);
4478 /* Just warn, ignore result otherwise.
4479 * read_config_file() has some debug output, so no need to print anything. */
4480 (void) read_config_file(c
, config_dirs
, *f
, true, invalid_config
);
4485 static int read_credential_lines(Context
*c
, bool *invalid_config
) {
4486 _cleanup_free_
char *j
= NULL
;
4492 r
= get_credentials_dir(&d
);
4496 return log_error_errno(r
, "Failed to get credentials directory: %m");
4498 j
= path_join(d
, "tmpfiles.extra");
4502 (void) read_config_file(c
, /* config_dirs= */ NULL
, j
, /* ignore_enoent= */ true, invalid_config
);
4506 static int link_parent(Context
*c
, ItemArray
*a
) {
4514 /* Finds the closest "parent" item array for the specified item array. Then registers the specified
4515 * item array as child of it, and fills the parent in, linking them both ways. This allows us to
4516 * later create parents before their children, and clean up/remove children before their parents.
4519 if (a
->n_items
<= 0)
4522 path
= a
->items
[0].path
;
4523 prefix
= newa(char, strlen(path
) + 1);
4524 PATH_FOREACH_PREFIX(prefix
, path
) {
4527 j
= ordered_hashmap_get(c
->items
, prefix
);
4529 j
= ordered_hashmap_get(c
->globs
, prefix
);
4531 r
= set_ensure_put(&j
->children
, NULL
, a
);
4543 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
4544 ItemArray
, item_array_free
);
4546 static int run(int argc
, char *argv
[]) {
4548 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4549 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
4551 _cleanup_strv_free_
char **config_dirs
= NULL
;
4552 _cleanup_(context_done
) Context c
= {};
4553 bool invalid_config
= false;
4557 PHASE_REMOVE_AND_CLEAN
,
4563 r
= parse_argv(argc
, argv
);
4569 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4570 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4571 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4572 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4573 * and output a nice and friendly warning. */
4574 if (proc_mounted() == 0)
4575 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
4576 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4577 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4579 /* Descending down file system trees might take a lot of fds */
4580 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
4582 switch (arg_runtime_scope
) {
4584 case RUNTIME_SCOPE_USER
:
4585 r
= user_config_paths(&config_dirs
);
4587 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
4590 case RUNTIME_SCOPE_SYSTEM
:
4591 config_dirs
= strv_new(CONF_PATHS("tmpfiles.d"));
4597 assert_not_reached();
4600 if (DEBUG_LOGGING
) {
4601 _cleanup_free_
char *t
= NULL
;
4603 STRV_FOREACH(i
, config_dirs
) {
4604 _cleanup_free_
char *j
= NULL
;
4606 j
= path_join(arg_root
, *i
);
4610 if (!strextend(&t
, "\n\t", j
))
4614 log_debug("Looking for configuration files in (higher priority first):%s", t
);
4617 if (arg_cat_flags
!= CAT_CONFIG_OFF
)
4618 return cat_config(config_dirs
, argv
+ optind
);
4620 if (should_bypass("SYSTEMD_TMPFILES"))
4633 r
= mount_image_privately_interactively(
4636 DISSECT_IMAGE_GENERIC_ROOT
|
4637 DISSECT_IMAGE_REQUIRE_ROOT
|
4638 DISSECT_IMAGE_VALIDATE_OS
|
4639 DISSECT_IMAGE_RELAX_VAR_CHECK
|
4640 DISSECT_IMAGE_FSCK
|
4641 DISSECT_IMAGE_GROWFS
|
4642 DISSECT_IMAGE_ALLOW_USERSPACE_VERITY
,
4644 /* ret_dir_fd= */ NULL
,
4649 arg_root
= strdup(mounted_dir
);
4657 c
.items
= ordered_hashmap_new(&item_array_hash_ops
);
4658 c
.globs
= ordered_hashmap_new(&item_array_hash_ops
);
4659 if (!c
.items
|| !c
.globs
)
4662 /* If command line arguments are specified along with --replace=, read all configuration files and
4663 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
4664 * specified, execute just them, and finally, without --replace= or any positional arguments, just
4665 * read configuration and execute it. */
4666 if (arg_replace
|| optind
>= argc
)
4667 r
= read_config_files(&c
, config_dirs
, argv
+ optind
, &invalid_config
);
4669 r
= parse_arguments(&c
, config_dirs
, argv
+ optind
, &invalid_config
);
4673 r
= read_credential_lines(&c
, &invalid_config
);
4677 /* Let's now link up all child/parent relationships */
4678 ORDERED_HASHMAP_FOREACH(a
, c
.items
) {
4679 r
= link_parent(&c
, a
);
4683 ORDERED_HASHMAP_FOREACH(a
, c
.globs
) {
4684 r
= link_parent(&c
, a
);
4689 /* If multiple operations are requested, let's first run the remove/clean operations, and only then
4690 * the create operations. i.e. that we first clean out the platform we then build on. */
4691 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
4694 if (phase
== PHASE_PURGE
)
4695 op
= arg_operation
& OPERATION_PURGE
;
4696 else if (phase
== PHASE_REMOVE_AND_CLEAN
)
4697 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
4698 else if (phase
== PHASE_CREATE
)
4699 op
= arg_operation
& OPERATION_CREATE
;
4701 assert_not_reached();
4703 if (op
== 0) /* Nothing requested in this phase */
4706 /* The non-globbing ones usually create things, hence we apply them first */
4707 ORDERED_HASHMAP_FOREACH(a
, c
.items
)
4708 RET_GATHER(r
, process_item_array(&c
, a
, op
));
4710 /* The globbing ones usually alter things, hence we apply them second. */
4711 ORDERED_HASHMAP_FOREACH(a
, c
.globs
)
4712 RET_GATHER(r
, process_item_array(&c
, a
, op
));
4715 if (ERRNO_IS_NEG_RESOURCE(r
))
4720 return EX_CANTCREAT
;
4724 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);