1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
13 #include <sys/xattr.h>
21 #include "alloc-util.h"
22 #include "btrfs-util.h"
24 #include "capability-util.h"
26 #include "chattr-util.h"
27 #include "conf-files.h"
28 #include "constants.h"
30 #include "creds-util.h"
31 #include "devnum-util.h"
32 #include "dirent-util.h"
33 #include "dissect-image.h"
35 #include "errno-util.h"
39 #include "format-util.h"
41 #include "glob-util.h"
42 #include "hexdecoct.h"
44 #include "label-util.h"
47 #include "main-func.h"
48 #include "missing_stat.h"
49 #include "missing_syscall.h"
50 #include "mkdir-label.h"
51 #include "mount-util.h"
52 #include "mountpoint-util.h"
53 #include "nulstr-util.h"
54 #include "offline-passwd.h"
56 #include "parse-argument.h"
57 #include "parse-util.h"
58 #include "path-lookup.h"
59 #include "path-util.h"
60 #include "pretty-print.h"
61 #include "rlimit-util.h"
63 #include "selinux-util.h"
65 #include "sort-util.h"
66 #include "specifier.h"
67 #include "stdio-util.h"
68 #include "string-table.h"
69 #include "string-util.h"
71 #include "terminal-util.h"
72 #include "umask-util.h"
73 #include "user-util.h"
76 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
77 * them in the file system. This is intended to be used to create
78 * properly owned directories beneath /tmp, /var/tmp, /run, which are
79 * volatile and hence need to be recreated on bootup. */
81 typedef enum OperationMask
{
82 OPERATION_CREATE
= 1 << 0,
83 OPERATION_REMOVE
= 1 << 1,
84 OPERATION_CLEAN
= 1 << 2,
87 typedef enum ItemType
{
88 /* These ones take file names */
90 TRUNCATE_FILE
= 'F', /* deprecated: use f+ */
91 CREATE_DIRECTORY
= 'd',
92 TRUNCATE_DIRECTORY
= 'D',
93 CREATE_SUBVOLUME
= 'v',
94 CREATE_SUBVOLUME_INHERIT_QUOTA
= 'q',
95 CREATE_SUBVOLUME_NEW_QUOTA
= 'Q',
98 CREATE_CHAR_DEVICE
= 'c',
99 CREATE_BLOCK_DEVICE
= 'b',
102 /* These ones take globs */
104 EMPTY_DIRECTORY
= 'e',
106 RECURSIVE_SET_XATTR
= 'T',
108 RECURSIVE_SET_ACL
= 'A',
110 RECURSIVE_SET_ATTRIBUTE
= 'H',
112 IGNORE_DIRECTORY_PATH
= 'X',
114 RECURSIVE_REMOVE_PATH
= 'R',
116 RECURSIVE_RELABEL_PATH
= 'Z',
117 ADJUST_MODE
= 'm', /* legacy, 'z' is identical to this */
121 AGE_BY_ATIME
= 1 << 0,
122 AGE_BY_BTIME
= 1 << 1,
123 AGE_BY_CTIME
= 1 << 2,
124 AGE_BY_MTIME
= 1 << 3,
126 /* All file timestamp types are checked by default. */
127 AGE_BY_DEFAULT_FILE
= AGE_BY_ATIME
| AGE_BY_BTIME
| AGE_BY_CTIME
| AGE_BY_MTIME
,
128 AGE_BY_DEFAULT_DIR
= AGE_BY_ATIME
| AGE_BY_BTIME
| AGE_BY_MTIME
,
131 typedef struct Item
{
136 void *binary_argument
; /* set if binary data, in which case it takes precedence over 'argument' */
137 size_t binary_argument_size
;
141 acl_t acl_access_exec
;
148 AgeBy age_by_file
, age_by_dir
;
151 unsigned attribute_value
;
152 unsigned attribute_mask
;
157 bool uid_only_create
:1;
158 bool gid_only_create
:1;
159 bool mode_only_create
:1;
162 bool attribute_set
:1;
164 bool keep_first_level
:1;
166 bool append_or_force
:1;
168 bool allow_failure
:1;
175 typedef struct ItemArray
{
179 struct ItemArray
*parent
;
183 typedef enum DirectoryType
{
196 _CREATION_MODE_INVALID
= -EINVAL
,
199 static CatFlags arg_cat_flags
= CAT_CONFIG_OFF
;
200 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
201 static OperationMask arg_operation
= 0;
202 static bool arg_boot
= false;
203 static bool arg_graceful
= false;
204 static PagerFlags arg_pager_flags
= 0;
206 static char **arg_include_prefixes
= NULL
;
207 static char **arg_exclude_prefixes
= NULL
;
208 static char *arg_root
= NULL
;
209 static char *arg_image
= NULL
;
210 static char *arg_replace
= NULL
;
211 static ImagePolicy
*arg_image_policy
= NULL
;
213 #define MAX_DEPTH 256
215 typedef struct Context
{
216 OrderedHashmap
*items
, *globs
;
220 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes
, freep
);
221 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes
, freep
);
222 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
223 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
224 STATIC_DESTRUCTOR_REGISTER(arg_image_policy
, image_policy_freep
);
226 static const char *const creation_mode_verb_table
[_CREATION_MODE_MAX
] = {
227 [CREATION_NORMAL
] = "Created",
228 [CREATION_EXISTING
] = "Found existing",
229 [CREATION_FORCE
] = "Created replacement",
232 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb
, CreationMode
);
234 static void context_done(Context
*c
) {
237 ordered_hashmap_free(c
->items
);
238 ordered_hashmap_free(c
->globs
);
240 set_free(c
->unix_sockets
);
243 /* Different kinds of errors that mean that information is not available in the environment. */
244 static bool ERRNO_IS_NOINFO(int r
) {
245 return IN_SET(abs(r
),
246 EUNATCH
, /* os-release or machine-id missing */
247 ENOMEDIUM
, /* machine-id or another file empty */
248 ENOPKG
, /* machine-id is uninitialized */
249 ENXIO
); /* env var is unset */
252 static int specifier_directory(char specifier
, const void *data
, const char *root
, const void *userdata
, char **ret
) {
258 static const struct table_entry paths_system
[] = {
259 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
260 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
261 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
262 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
265 static const struct table_entry paths_user
[] = {
266 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
267 [DIRECTORY_STATE
] = { SD_PATH_USER_STATE_PRIVATE
},
268 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
269 [DIRECTORY_LOGS
] = { SD_PATH_USER_STATE_PRIVATE
, "log" },
272 const struct table_entry
*paths
;
273 _cleanup_free_
char *p
= NULL
;
277 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
278 paths
= arg_runtime_scope
== RUNTIME_SCOPE_USER
? paths_user
: paths_system
;
280 i
= PTR_TO_UINT(data
);
281 assert(i
< ELEMENTSOF(paths_system
));
283 r
= sd_path_lookup(paths
[i
].type
, paths
[i
].suffix
, &p
);
288 _cleanup_free_
char *j
= NULL
;
290 j
= path_join(arg_root
, p
);
301 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
302 static bool notified
= false;
304 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
305 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
306 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
307 * to LOG_DEBUG for the rest.
309 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
310 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
311 * expectation that machine-id and other files will be populated.
314 int log_level
= notified
|| arg_root
|| running_in_chroot() > 0 ?
315 LOG_DEBUG
: LOG_NOTICE
;
320 "Failed to resolve specifier: %s, skipping.",
321 arg_runtime_scope
== RUNTIME_SCOPE_USER
? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
325 "All rules containing unresolvable specifiers will be skipped.");
331 static int user_config_paths(char*** ret
) {
332 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
333 _cleanup_free_
char *persistent_config
= NULL
, *runtime_config
= NULL
, *data_home
= NULL
;
334 _cleanup_strv_free_
char **res
= NULL
;
337 r
= xdg_user_dirs(&config_dirs
, &data_dirs
);
341 r
= xdg_user_config_dir(&persistent_config
, "/user-tmpfiles.d");
342 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
345 r
= xdg_user_runtime_dir(&runtime_config
, "/user-tmpfiles.d");
346 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
349 r
= xdg_user_data_dir(&data_home
, "/user-tmpfiles.d");
350 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
353 r
= strv_extend_strv_concat(&res
, config_dirs
, "/user-tmpfiles.d");
357 r
= strv_extend(&res
, persistent_config
);
361 r
= strv_extend(&res
, runtime_config
);
365 r
= strv_extend(&res
, data_home
);
369 r
= strv_extend_strv_concat(&res
, data_dirs
, "/user-tmpfiles.d");
373 r
= path_strv_make_absolute_cwd(res
);
377 *ret
= TAKE_PTR(res
);
381 static bool needs_glob(ItemType t
) {
385 IGNORE_DIRECTORY_PATH
,
387 RECURSIVE_REMOVE_PATH
,
391 RECURSIVE_RELABEL_PATH
,
397 RECURSIVE_SET_ATTRIBUTE
);
400 static bool takes_ownership(ItemType t
) {
408 CREATE_SUBVOLUME_INHERIT_QUOTA
,
409 CREATE_SUBVOLUME_NEW_QUOTA
,
417 IGNORE_DIRECTORY_PATH
,
419 RECURSIVE_REMOVE_PATH
);
422 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
425 ORDERED_HASHMAP_FOREACH(j
, h
) {
428 for (n
= 0; n
< j
->n_items
; n
++) {
429 Item
*item
= j
->items
+ n
;
431 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
439 static int load_unix_sockets(Context
*c
) {
440 _cleanup_set_free_ Set
*sockets
= NULL
;
441 _cleanup_fclose_
FILE *f
= NULL
;
447 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
449 f
= fopen("/proc/net/unix", "re");
451 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
452 "Failed to open /proc/net/unix, ignoring: %m");
455 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
457 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
459 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
462 _cleanup_free_
char *line
= NULL
;
465 r
= read_line(f
, LONG_LINE_MAX
, &line
);
467 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
468 if (r
== 0) /* EOF */
471 p
= strchr(line
, ':');
479 p
+= strspn(p
, WHITESPACE
);
480 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
481 p
+= strspn(p
, WHITESPACE
);
483 if (!path_is_absolute(p
))
486 r
= set_put_strdup_full(&sockets
, &path_hash_ops_free
, p
);
488 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
491 c
->unix_sockets
= TAKE_PTR(sockets
);
495 static bool unix_socket_alive(Context
*c
, const char *fn
) {
499 if (load_unix_sockets(c
) < 0)
500 return true; /* We don't know, so assume yes */
502 return set_contains(c
->unix_sockets
, fn
);
505 /* Accessors for the argument in binary format */
506 static const void* item_binary_argument(const Item
*i
) {
508 return i
->binary_argument
?: i
->argument
;
511 static size_t item_binary_argument_size(const Item
*i
) {
513 return i
->binary_argument
? i
->binary_argument_size
: strlen_ptr(i
->argument
);
516 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
519 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
523 if (!IN_SET(errno
, ENOENT
, ELOOP
))
524 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
529 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
531 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
536 static DIR* opendir_nomod(const char *path
) {
537 return xopendirat_nomod(AT_FDCWD
, path
);
540 static nsec_t
load_statx_timestamp_nsec(const struct statx_timestamp
*ts
) {
544 return NSEC_INFINITY
;
546 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
547 return NSEC_INFINITY
;
549 return ts
->tv_sec
* NSEC_PER_SEC
+ ts
->tv_nsec
;
552 static bool needs_cleanup(
558 const char *sub_path
,
562 if (FLAGS_SET(age_by
, AGE_BY_MTIME
) && mtime
!= NSEC_INFINITY
&& mtime
>= cutoff
) {
563 /* Follows spelling in stat(1). */
564 log_debug("%s \"%s\": modify time %s is too new.",
565 is_dir
? "Directory" : "File",
567 FORMAT_TIMESTAMP_STYLE(mtime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
572 if (FLAGS_SET(age_by
, AGE_BY_ATIME
) && atime
!= NSEC_INFINITY
&& atime
>= cutoff
) {
573 log_debug("%s \"%s\": access time %s is too new.",
574 is_dir
? "Directory" : "File",
576 FORMAT_TIMESTAMP_STYLE(atime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
582 * Note: Unless explicitly specified by the user, "ctime" is ignored
583 * by default for directories, because we change it when deleting.
585 if (FLAGS_SET(age_by
, AGE_BY_CTIME
) && ctime
!= NSEC_INFINITY
&& ctime
>= cutoff
) {
586 log_debug("%s \"%s\": change time %s is too new.",
587 is_dir
? "Directory" : "File",
589 FORMAT_TIMESTAMP_STYLE(ctime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
594 if (FLAGS_SET(age_by
, AGE_BY_BTIME
) && btime
!= NSEC_INFINITY
&& btime
>= cutoff
) {
595 log_debug("%s \"%s\": birth time %s is too new.",
596 is_dir
? "Directory" : "File",
598 FORMAT_TIMESTAMP_STYLE(btime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
606 static int dir_cleanup(
611 nsec_t self_atime_nsec
,
612 nsec_t self_mtime_nsec
,
618 bool keep_this_level
,
622 bool deleted
= false;
629 FOREACH_DIRENT_ALL(de
, d
, break) {
630 _cleanup_free_
char *sub_path
= NULL
;
631 nsec_t atime_nsec
, mtime_nsec
, ctime_nsec
, btime_nsec
;
633 if (dot_or_dot_dot(de
->d_name
))
636 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
637 * explicitly where we are looking at a mount point, for free as side information. Determining
638 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
639 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
640 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
641 * while on older kernels's well do traditional st_dev based detection of mount points.
643 * Using statx() for detecting mount points also has the benfit that we handle weird file
644 * systems such as overlayfs better where each file is originating from a different
647 STRUCT_STATX_DEFINE(sx
);
650 dirfd(d
), de
->d_name
,
651 AT_SYMLINK_NOFOLLOW
|AT_NO_AUTOMOUNT
,
652 STATX_TYPE
|STATX_MODE
|STATX_UID
|STATX_ATIME
|STATX_MTIME
|STATX_CTIME
|STATX_BTIME
,
657 /* FUSE, NFS mounts, SELinux might return EACCES */
658 r
= log_full_errno(r
== -EACCES
? LOG_DEBUG
: LOG_ERR
, r
,
659 "statx(%s/%s) failed: %m", p
, de
->d_name
);
663 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
)) {
664 /* Yay, we have the mount point API, use it */
665 if (FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
)) {
666 log_debug("Ignoring \"%s/%s\": different mount points.", p
, de
->d_name
);
670 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
671 * back to traditional stx_dev checking. */
672 if (sx
.stx_dev_major
!= rootdev_major
||
673 sx
.stx_dev_minor
!= rootdev_minor
) {
674 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, de
->d_name
);
678 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
679 * major/minors. This type of query is not supported on all kernels or filesystem types
681 if (S_ISDIR(sx
.stx_mode
)) {
684 q
= fd_is_mount_point(dirfd(d
), de
->d_name
, 0);
686 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, de
->d_name
);
688 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, de
->d_name
);
694 atime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_ATIME
) ? load_statx_timestamp_nsec(&sx
.stx_atime
) : 0;
695 mtime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_MTIME
) ? load_statx_timestamp_nsec(&sx
.stx_mtime
) : 0;
696 ctime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_CTIME
) ? load_statx_timestamp_nsec(&sx
.stx_ctime
) : 0;
697 btime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_BTIME
) ? load_statx_timestamp_nsec(&sx
.stx_btime
) : 0;
699 sub_path
= path_join(p
, de
->d_name
);
705 /* Is there an item configured for this path? */
706 if (ordered_hashmap_get(c
->items
, sub_path
)) {
707 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
711 if (find_glob(c
->globs
, sub_path
)) {
712 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
716 if (S_ISDIR(sx
.stx_mode
)) {
717 _cleanup_closedir_
DIR *sub_dir
= NULL
;
720 streq(de
->d_name
, "lost+found") &&
722 log_debug("Ignoring directory \"%s\".", sub_path
);
727 log_warning("Reached max depth on \"%s\".", sub_path
);
731 sub_dir
= xopendirat_nomod(dirfd(d
), de
->d_name
);
734 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
739 if (flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
740 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", sub_path
);
744 q
= dir_cleanup(c
, i
,
746 atime_nsec
, mtime_nsec
, cutoff_nsec
,
747 rootdev_major
, rootdev_minor
,
748 false, maxdepth
-1, false,
749 age_by_file
, age_by_dir
);
754 /* Note: if you are wondering why we don't support the sticky bit for excluding
755 * directories from cleaning like we do it for other file system objects: well, the
756 * sticky bit already has a meaning for directories, so we don't want to overload
759 if (keep_this_level
) {
760 log_debug("Keeping directory \"%s\".", sub_path
);
765 * Check the file timestamps of an entry against the
766 * given cutoff time; delete if it is older.
768 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
769 cutoff_nsec
, sub_path
, age_by_dir
, true))
772 log_debug("Removing directory \"%s\".", sub_path
);
773 if (unlinkat(dirfd(d
), de
->d_name
, AT_REMOVEDIR
) < 0)
774 if (!IN_SET(errno
, ENOENT
, ENOTEMPTY
))
775 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
778 _cleanup_close_
int fd
= -EBADF
;
780 /* Skip files for which the sticky bit is set. These are semantics we define, and are
781 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
782 if (sx
.stx_mode
& S_ISVTX
) {
783 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
788 S_ISREG(sx
.stx_mode
) &&
790 STR_IN_SET(de
->d_name
,
794 log_debug("Skipping \"%s\".", sub_path
);
798 /* Ignore sockets that are listed in /proc/net/unix */
799 if (S_ISSOCK(sx
.stx_mode
) && unix_socket_alive(c
, sub_path
)) {
800 log_debug("Skipping \"%s\": live socket.", sub_path
);
804 /* Ignore device nodes */
805 if (S_ISCHR(sx
.stx_mode
) || S_ISBLK(sx
.stx_mode
)) {
806 log_debug("Skipping \"%s\": a device.", sub_path
);
810 /* Keep files on this level around if this is requested */
811 if (keep_this_level
) {
812 log_debug("Keeping \"%s\".", sub_path
);
816 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
817 cutoff_nsec
, sub_path
, age_by_file
, false))
820 fd
= xopenat(dirfd(d
),
822 O_RDONLY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
,
823 /* xopen_flags = */ 0,
825 if (fd
< 0 && !IN_SET(fd
, -ENOENT
, -ELOOP
))
826 log_warning_errno(fd
, "Opening file \"%s\" failed, ignoring: %m", sub_path
);
827 if (fd
>= 0 && flock(fd
, LOCK_EX
|LOCK_NB
) < 0 && errno
== EAGAIN
) {
828 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", sub_path
);
832 log_debug("Removing \"%s\".", sub_path
);
833 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
835 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
843 struct timespec ts
[2];
845 log_debug("Restoring access and modification time on \"%s\": %s, %s",
847 FORMAT_TIMESTAMP_STYLE(self_atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
),
848 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
850 timespec_store_nsec(ts
+ 0, self_atime_nsec
);
851 timespec_store_nsec(ts
+ 1, self_mtime_nsec
);
853 /* Restore original directory timestamps */
854 if (futimens(dirfd(d
), ts
) < 0)
855 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
861 static bool dangerous_hardlinks(void) {
862 _cleanup_free_
char *value
= NULL
;
863 static int cached
= -1;
866 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
867 * what the upstream default is. */
872 r
= read_one_line_file("/proc/sys/fs/protected_hardlinks", &value
);
874 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl: %m");
878 r
= parse_boolean(value
);
880 log_debug_errno(r
, "Failed to parse fs.protected_hardlinks sysctl: %m");
888 static bool hardlink_vulnerable(const struct stat
*st
) {
891 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && dangerous_hardlinks();
894 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
896 if ((current
& 0111) == 0)
898 if ((current
& 0222) == 0)
900 if ((current
& 0444) == 0)
902 if (!S_ISDIR(current
))
903 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
908 static int fd_set_perms(
913 const struct stat
*st
,
914 CreationMode creation
) {
916 bool do_chown
, do_chmod
;
928 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
932 if (fstat(fd
, &stbuf
) < 0)
933 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
937 if (hardlink_vulnerable(st
))
938 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
939 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
941 new_uid
= i
->uid_set
&& (creation
!= CREATION_EXISTING
|| !i
->uid_only_create
) ? i
->uid
: st
->st_uid
;
942 new_gid
= i
->gid_set
&& (creation
!= CREATION_EXISTING
|| !i
->gid_only_create
) ? i
->gid
: st
->st_gid
;
944 /* Do we need a chown()? */
945 do_chown
= (new_uid
!= st
->st_uid
) || (new_gid
!= st
->st_gid
);
947 /* Calculate the mode to apply */
948 new_mode
= i
->mode_set
&& (creation
!= CREATION_EXISTING
|| !i
->mode_only_create
) ?
949 (i
->mask_perms
? process_mask_perms(i
->mode
, st
->st_mode
) : i
->mode
) :
950 (st
->st_mode
& 07777);
952 do_chmod
= ((new_mode
^ st
->st_mode
) & 07777) != 0;
954 if (do_chmod
&& do_chown
) {
955 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
956 * the new mode. That way there's no time window where the file exists under the old owner
957 * with more than the old access modes — and not under the new owner with more than the new
958 * access modes either. */
960 if (S_ISLNK(st
->st_mode
))
961 log_debug("Skipping temporary mode fix for symlink %s.", path
);
963 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
965 if (((m
^ st
->st_mode
) & 07777) == 0)
966 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
968 log_debug("Temporarily changing \"%s\" to mode %o.", path
, m
);
969 r
= fchmod_opath(fd
, m
);
971 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
977 log_debug("Changing \"%s\" to owner "UID_FMT
":"GID_FMT
, path
, new_uid
, new_gid
);
980 new_uid
!= st
->st_uid
? new_uid
: UID_INVALID
,
981 new_gid
!= st
->st_gid
? new_gid
: GID_INVALID
,
983 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
986 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
987 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
988 if (do_chmod
|| do_chown
) {
989 if (S_ISLNK(st
->st_mode
))
990 log_debug("Skipping mode fix for symlink %s.", path
);
992 log_debug("Changing \"%s\" to mode %o.", path
, new_mode
);
993 r
= fchmod_opath(fd
, new_mode
);
995 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
1000 return label_fix_full(fd
, /* inode_path= */ NULL
, /* label_path= */ path
, 0);
1003 static int path_open_parent_safe(const char *path
, bool allow_failure
) {
1004 _cleanup_free_
char *dn
= NULL
;
1007 if (!path_is_normalized(path
))
1008 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1009 SYNTHETIC_ERRNO(EINVAL
),
1010 "Failed to open parent of '%s': path not normalized%s.",
1012 allow_failure
? ", ignoring" : "");
1014 r
= path_extract_directory(path
, &dn
);
1016 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1018 "Unable to determine parent directory of '%s'%s: %m",
1020 allow_failure
? ", ignoring" : "");
1022 r
= chase(dn
, arg_root
, allow_failure
? CHASE_SAFE
: CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
1023 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
1026 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1028 "Failed to open path '%s'%s: %m",
1030 allow_failure
? ", ignoring" : "");
1035 static int path_open_safe(const char *path
) {
1038 /* path_open_safe() returns a file descriptor opened with O_PATH after
1039 * verifying that the path doesn't contain unsafe transitions, except
1040 * for its final component as the function does not follow symlink. */
1044 if (!path_is_normalized(path
))
1045 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to open invalid path '%s'.", path
);
1047 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
1049 return r
; /* Unsafe symlink: already covered by CHASE_WARN */
1051 return log_error_errno(r
, "Failed to open path %s: %m", path
);
1056 static int path_set_perms(
1060 CreationMode creation
) {
1062 _cleanup_close_
int fd
= -EBADF
;
1068 fd
= path_open_safe(path
);
1072 return fd_set_perms(c
, i
, fd
, path
, /* st= */ NULL
, creation
);
1075 static int parse_xattrs_from_arg(Item
*i
) {
1081 assert_se(p
= i
->argument
);
1083 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
1085 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
1087 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
1091 r
= split_pair(xattr
, "=", &name
, &value
);
1093 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
1097 if (isempty(name
) || isempty(value
)) {
1098 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
1102 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
1105 name
= value
= NULL
;
1111 static int fd_set_xattrs(
1116 const struct stat
*st
,
1117 CreationMode creation
) {
1124 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
1125 log_debug("Setting extended attribute '%s=%s' on %s.", *name
, *value
, path
);
1126 if (setxattr(FORMAT_PROC_FD_PATH(fd
), *name
, *value
, strlen(*value
), 0) < 0)
1127 return log_error_errno(errno
, "Setting extended attribute %s=%s on %s failed: %m",
1128 *name
, *value
, path
);
1133 static int path_set_xattrs(
1137 CreationMode creation
) {
1139 _cleanup_close_
int fd
= -EBADF
;
1145 fd
= path_open_safe(path
);
1149 return fd_set_xattrs(c
, i
, fd
, path
, /* st = */ NULL
, creation
);
1152 static int parse_acls_from_arg(Item
*item
) {
1158 /* If append_or_force (= modify) is set, we will not modify the acl
1159 * afterwards, so the mask can be added now if necessary. */
1161 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_access_exec
,
1162 &item
->acl_default
, !item
->append_or_force
);
1164 log_full_errno(arg_graceful
&& IN_SET(r
, -ENOENT
, -ESRCH
) ? LOG_DEBUG
: LOG_WARNING
,
1165 r
, "Failed to parse ACL \"%s\", ignoring: %m", item
->argument
);
1167 log_warning("ACLs are not supported, ignoring.");
1174 static int parse_acl_cond_exec(
1176 acl_t access
, /* could be empty (NULL) */
1178 const struct stat
*st
,
1182 _cleanup_(acl_freep
) acl_t parsed
= NULL
;
1184 acl_permset_t permset
;
1192 parsed
= access
? acl_dup(access
) : acl_init(0);
1196 /* Since we substitute 'X' with 'x' in parse_acl(), we just need to copy the entries over
1197 * for directories */
1198 if (S_ISDIR(st
->st_mode
)) {
1199 for (r
= acl_get_entry(cond_exec
, ACL_FIRST_ENTRY
, &entry
);
1201 r
= acl_get_entry(cond_exec
, ACL_NEXT_ENTRY
, &entry
)) {
1203 acl_entry_t parsed_entry
;
1205 if (acl_create_entry(&parsed
, &parsed_entry
) < 0)
1208 if (acl_copy_entry(parsed_entry
, entry
) < 0)
1217 has_exec
= st
->st_mode
& S_IXUSR
;
1219 if (!has_exec
&& append
) {
1220 _cleanup_(acl_freep
) acl_t old
= NULL
;
1222 old
= acl_get_file(path
, ACL_TYPE_ACCESS
);
1226 for (r
= acl_get_entry(old
, ACL_FIRST_ENTRY
, &entry
);
1228 r
= acl_get_entry(old
, ACL_NEXT_ENTRY
, &entry
)) {
1230 if (acl_get_permset(entry
, &permset
) < 0)
1233 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1245 /* Check if we're about to set the execute bit in acl_access */
1246 if (!has_exec
&& access
) {
1247 for (r
= acl_get_entry(access
, ACL_FIRST_ENTRY
, &entry
);
1249 r
= acl_get_entry(access
, ACL_NEXT_ENTRY
, &entry
)) {
1251 if (acl_get_permset(entry
, &permset
) < 0)
1254 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1266 for (r
= acl_get_entry(cond_exec
, ACL_FIRST_ENTRY
, &entry
);
1268 r
= acl_get_entry(cond_exec
, ACL_NEXT_ENTRY
, &entry
)) {
1270 acl_entry_t parsed_entry
;
1272 if (acl_create_entry(&parsed
, &parsed_entry
) < 0)
1275 if (acl_copy_entry(parsed_entry
, entry
) < 0)
1279 if (acl_get_permset(parsed_entry
, &permset
) < 0)
1282 if (acl_delete_perm(permset
, ACL_EXECUTE
) < 0)
1290 if (!append
) { /* want_mask = true */
1291 r
= calc_acl_mask_if_needed(&parsed
);
1296 *ret
= TAKE_PTR(parsed
);
1301 static int path_set_acl(
1309 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1310 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1315 /* Returns 0 for success, positive error if already warned, negative error otherwise. */
1318 r
= acls_for_file(path
, type
, acl
, &dup
);
1322 r
= calc_acl_mask_if_needed(&dup
);
1330 /* the mask was already added earlier if needed */
1333 r
= add_base_acls_if_needed(&dup
, path
);
1337 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1338 log_debug("Setting %s ACL %s on %s.",
1339 type
== ACL_TYPE_ACCESS
? "access" : "default",
1342 r
= acl_set_file(path
, type
, dup
);
1344 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1345 /* No error if filesystem doesn't support ACLs. Return negative. */
1348 /* Return positive to indicate we already warned */
1349 return -log_error_errno(errno
,
1350 "Setting %s ACL \"%s\" on %s failed: %m",
1351 type
== ACL_TYPE_ACCESS
? "access" : "default",
1358 static int fd_set_acls(
1363 const struct stat
*st
,
1364 CreationMode creation
) {
1368 _cleanup_(acl_freep
) acl_t access_with_exec_parsed
= NULL
;
1377 if (fstat(fd
, &stbuf
) < 0)
1378 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1382 if (hardlink_vulnerable(st
))
1383 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1384 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1387 if (S_ISLNK(st
->st_mode
)) {
1388 log_debug("Skipping ACL fix for symlink %s.", path
);
1392 if (item
->acl_access_exec
) {
1393 r
= parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd
),
1395 item
->acl_access_exec
,
1397 item
->append_or_force
,
1398 &access_with_exec_parsed
);
1400 return log_error_errno(r
, "Failed to parse conditionalized execute bit for \"%s\": %m", path
);
1402 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, access_with_exec_parsed
, item
->append_or_force
);
1403 } else if (item
->acl_access
)
1404 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1406 /* set only default acls to folders */
1407 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1408 r
= path_set_acl(c
, FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1410 if (ERRNO_IS_NOT_SUPPORTED(r
)) {
1411 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1416 return -r
; /* already warned in path_set_acl */
1418 /* The above procfs paths don't work if /proc is not mounted. */
1419 if (r
== -ENOENT
&& proc_mounted() == 0)
1423 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1428 static int path_set_acls(
1432 CreationMode creation
) {
1436 _cleanup_close_
int fd
= -EBADF
;
1442 fd
= path_open_safe(path
);
1446 r
= fd_set_acls(c
, item
, fd
, path
, /* st= */ NULL
, creation
);
1451 static int parse_attribute_from_arg(Item
*item
) {
1453 static const struct {
1457 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1458 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1459 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1460 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1461 { 'c', FS_COMPR_FL
}, /* Compress file */
1462 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1463 { 'e', FS_EXTENT_FL
}, /* Extents */
1464 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1465 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1466 { 's', FS_SECRM_FL
}, /* Secure deletion */
1467 { 'u', FS_UNRM_FL
}, /* Undelete */
1468 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1469 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1470 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1471 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1480 unsigned value
= 0, mask
= 0;
1490 } else if (*p
== '-') {
1493 } else if (*p
== '=') {
1499 if (isempty(p
) && mode
!= MODE_SET
)
1500 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1501 "Setting file attribute on '%s' needs an attribute specification.",
1504 for (; p
&& *p
; p
++) {
1507 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1508 if (*p
== attributes
[i
].character
)
1511 if (i
>= ELEMENTSOF(attributes
))
1512 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1513 "Unknown file attribute '%c' on '%s'.",
1516 v
= attributes
[i
].value
;
1518 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1523 if (mode
== MODE_SET
)
1524 mask
|= CHATTR_ALL_FL
;
1528 item
->attribute_mask
= mask
;
1529 item
->attribute_value
= value
;
1530 item
->attribute_set
= true;
1535 static int fd_set_attribute(
1540 const struct stat
*st
,
1541 CreationMode creation
) {
1543 _cleanup_close_
int procfs_fd
= -EBADF
;
1553 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1557 if (fstat(fd
, &stbuf
) < 0)
1558 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1562 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1563 * drivers, not the file system containing the device node. */
1564 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1565 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1566 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1569 f
= item
->attribute_value
& item
->attribute_mask
;
1571 /* Mask away directory-specific flags */
1572 if (!S_ISDIR(st
->st_mode
))
1573 f
&= ~FS_DIRSYNC_FL
;
1575 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1577 return log_error_errno(procfs_fd
, "Failed to re-open '%s': %m", path
);
1579 unsigned previous
, current
;
1580 r
= chattr_full(procfs_fd
, NULL
, f
, item
->attribute_mask
, &previous
, ¤t
, CHATTR_FALLBACK_BITWISE
);
1582 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1583 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1584 path
, previous
, current
, (previous
& ~item
->attribute_mask
) | (f
& item
->attribute_mask
));
1586 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1587 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1588 path
, item
->attribute_value
, item
->attribute_mask
);
1593 static int path_set_attribute(
1597 CreationMode creation
) {
1599 _cleanup_close_
int fd
= -EBADF
;
1604 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1607 fd
= path_open_safe(path
);
1611 return fd_set_attribute(c
, item
, fd
, path
, /* st= */ NULL
, creation
);
1614 static int write_argument_data(Item
*i
, int fd
, const char *path
) {
1621 if (item_binary_argument_size(i
) == 0)
1624 assert(item_binary_argument(i
));
1626 log_debug("Writing to \"%s\".", path
);
1628 r
= loop_write(fd
, item_binary_argument(i
), item_binary_argument_size(i
));
1630 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1635 static int write_one_file(Context
*c
, Item
*i
, const char *path
, CreationMode creation
) {
1636 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1637 _cleanup_free_
char *bn
= NULL
;
1643 assert(i
->type
== WRITE_FILE
);
1645 r
= path_extract_filename(path
, &bn
);
1647 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1648 if (r
== O_DIRECTORY
)
1649 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1651 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1652 * can't be changed behind our back. */
1653 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1657 /* Follows symlinks */
1658 fd
= openat(dir_fd
, bn
,
1659 O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
|(i
->append_or_force
? O_APPEND
: 0),
1662 if (errno
== ENOENT
) {
1663 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1667 if (i
->allow_failure
)
1668 return log_debug_errno(errno
, "Failed to open file \"%s\", ignoring: %m", path
);
1670 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1673 /* 'w' is allowed to write into any kind of files. */
1675 r
= write_argument_data(i
, fd
, path
);
1679 return fd_set_perms(c
, i
, fd
, path
, NULL
, creation
);
1682 static int create_file(
1687 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1688 _cleanup_free_
char *bn
= NULL
;
1689 struct stat stbuf
, *st
= NULL
;
1690 CreationMode creation
;
1696 assert(i
->type
== CREATE_FILE
);
1698 /* 'f' operates on regular files exclusively. */
1700 r
= path_extract_filename(path
, &bn
);
1702 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1703 if (r
== O_DIRECTORY
)
1704 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1706 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1707 * can't be changed behind our back. */
1708 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1713 mac_selinux_create_file_prepare(path
, S_IFREG
);
1714 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1715 mac_selinux_create_file_clear();
1719 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1720 * returns EROFS only if it needs to create the file. */
1722 return log_error_errno(fd
, "Failed to create file %s: %m", path
);
1724 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1725 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1726 * fd_set_perms() report the error if the perms need to be modified. */
1727 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1729 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1731 if (fstat(fd
, &stbuf
) < 0)
1732 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1734 if (!S_ISREG(stbuf
.st_mode
))
1735 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1736 "%s exists and is not a regular file.",
1740 creation
= CREATION_EXISTING
;
1742 r
= write_argument_data(i
, fd
, path
);
1746 creation
= CREATION_NORMAL
;
1749 return fd_set_perms(c
, i
, fd
, path
, st
, creation
);
1752 static int truncate_file(
1757 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1758 _cleanup_free_
char *bn
= NULL
;
1759 struct stat stbuf
, *st
= NULL
;
1760 CreationMode creation
;
1767 assert(i
->type
== TRUNCATE_FILE
|| (i
->type
== CREATE_FILE
&& i
->append_or_force
));
1769 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1770 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1771 * make sure it's a regular one before truncating it. */
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 truncation, is a directory.", path
);
1779 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1780 * can't be changed behind our back. */
1781 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1785 creation
= CREATION_EXISTING
;
1786 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1787 if (fd
== -ENOENT
) {
1788 creation
= CREATION_NORMAL
; /* Didn't work without O_CREATE, try again with */
1791 mac_selinux_create_file_prepare(path
, S_IFREG
);
1792 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1793 mac_selinux_create_file_clear();
1799 return log_error_errno(fd
, "Failed to open/create file %s: %m", path
);
1801 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1802 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1803 * fail with EROFS if they try to modify the target file. */
1805 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1807 if (errno
== ENOENT
)
1808 return log_error_errno(SYNTHETIC_ERRNO(EROFS
),
1809 "Cannot create file %s on a read-only file system.",
1812 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1816 creation
= CREATION_EXISTING
;
1819 if (fstat(fd
, &stbuf
) < 0)
1820 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1822 if (!S_ISREG(stbuf
.st_mode
))
1823 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1824 "%s exists and is not a regular file.",
1827 if (stbuf
.st_size
> 0) {
1828 if (ftruncate(fd
, 0) < 0) {
1829 r
= erofs
? -EROFS
: -errno
;
1830 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1835 log_debug("\"%s\" has been created.", path
);
1837 if (item_binary_argument(i
)) {
1838 r
= write_argument_data(i
, fd
, path
);
1843 return fd_set_perms(c
, i
, fd
, path
, st
, creation
);
1846 static int copy_files(Context
*c
, Item
*i
) {
1847 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
1848 _cleanup_free_
char *bn
= NULL
;
1852 log_debug("Copying tree \"%s\" to \"%s\".", i
->argument
, i
->path
);
1854 r
= path_extract_filename(i
->path
, &bn
);
1856 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
1858 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1859 * path can't be changed behind our back. */
1860 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
1864 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1866 i
->uid_set
? i
->uid
: UID_INVALID
,
1867 i
->gid_set
? i
->gid
: GID_INVALID
,
1868 COPY_REFLINK
| ((i
->append_or_force
) ? COPY_MERGE
: COPY_MERGE_EMPTY
) | COPY_MAC_CREATE
| COPY_HARDLINKS
,
1871 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1873 if (r
< 0) /* Look at original error first */
1874 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1876 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1879 if (fstat(fd
, &st
) < 0)
1880 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
1882 if (stat(i
->argument
, &a
) < 0)
1883 return log_error_errno(errno
, "Failed to stat(%s): %m", i
->argument
);
1885 if (((st
.st_mode
^ a
.st_mode
) & S_IFMT
) != 0) {
1886 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1890 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, _CREATION_MODE_INVALID
);
1893 static int create_directory_or_subvolume(
1898 struct stat
*ret_st
,
1899 CreationMode
*ret_creation
) {
1901 _cleanup_free_
char *bn
= NULL
;
1902 _cleanup_close_
int pfd
= -EBADF
;
1903 CreationMode creation
;
1909 r
= path_extract_filename(path
, &bn
);
1911 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1913 pfd
= path_open_parent_safe(path
, allow_failure
);
1918 r
= getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1920 if (r
!= -ENXIO
) /* env var is unset */
1921 log_warning_errno(r
, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1922 r
= btrfs_is_subvol(empty_to_root(arg_root
)) > 0;
1925 /* Don't create a subvolume unless the root directory is one, too. We do this under
1926 * the assumption that if the root directory is just a plain directory (i.e. very
1927 * light-weight), we shouldn't try to split it up into subvolumes (i.e. more
1928 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1929 * subvolume set up below their tree only if they specifically set up a btrfs
1930 * subvolume for the root dir too. */
1934 WITH_UMASK((~mode
) & 0777)
1935 r
= btrfs_subvol_make(pfd
, bn
);
1940 if (!subvol
|| ERRNO_IS_NEG_NOT_SUPPORTED(r
))
1942 r
= mkdirat_label(pfd
, bn
, mode
);
1944 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
1946 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_DIRECTORY
|O_PATH
);
1948 /* We couldn't open it because it is not actually a directory? */
1949 if (errno
== ENOTDIR
)
1950 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "\"%s\" already exists and is not a directory.", path
);
1952 /* Then look at the original error */
1954 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1956 "Failed to create directory or subvolume \"%s\"%s: %m",
1958 allow_failure
? ", ignoring" : "");
1960 return log_error_errno(errno
, "Failed to open directory/subvolume we just created '%s': %m", path
);
1963 if (fstat(fd
, &st
) < 0)
1964 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
1966 assert(S_ISDIR(st
.st_mode
)); /* we used O_DIRECTORY above */
1968 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation
), path
);
1973 *ret_creation
= creation
;
1978 static int create_directory(
1983 _cleanup_close_
int fd
= -EBADF
;
1984 CreationMode creation
;
1989 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
1991 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol= */ false, i
->allow_failure
, &st
, &creation
);
1997 return fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2000 static int create_subvolume(
2005 _cleanup_close_
int fd
= -EBADF
;
2006 CreationMode creation
;
2012 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
2014 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol = */ true, i
->allow_failure
, &st
, &creation
);
2020 if (creation
== CREATION_NORMAL
&&
2021 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
2022 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
2024 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
2025 else if (r
== -EROFS
)
2026 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
2027 else if (r
== -ENOTCONN
)
2028 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
2030 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
2032 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
2034 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
2037 r
= fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2038 if (q
< 0) /* prefer the quota change error from above */
2044 static int empty_directory(
2048 CreationMode creation
) {
2050 _cleanup_close_
int fd
= -EBADF
;
2056 assert(i
->type
== EMPTY_DIRECTORY
);
2058 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
2059 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
2062 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
2064 log_debug_errno(r
, "Skipping missing directory: %s", path
);
2068 return log_error_errno(r
, "Failed to open directory '%s': %m", path
);
2070 if (fstat(fd
, &st
) < 0)
2071 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
2072 if (!S_ISDIR(st
.st_mode
)) {
2073 log_warning("'%s' already exists and is not a directory.", path
);
2077 return fd_set_perms(c
, i
, fd
, path
, &st
, creation
);
2080 static int create_device(
2085 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
2086 _cleanup_free_
char *bn
= NULL
;
2087 CreationMode creation
;
2093 assert(IN_SET(i
->type
, CREATE_BLOCK_DEVICE
, CREATE_CHAR_DEVICE
));
2094 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
2096 r
= path_extract_filename(i
->path
, &bn
);
2098 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2099 if (r
== O_DIRECTORY
)
2100 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating device node, is a directory.", i
->path
);
2102 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2103 * path can't be changed behind our back. */
2104 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2109 mac_selinux_create_file_prepare(i
->path
, file_type
);
2110 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2111 mac_selinux_create_file_clear();
2113 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2115 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2116 * order anyway and we hence can ignore the error to create the device node */
2117 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2119 /* OK, so opening the inode failed, let's look at the original error then. */
2122 if (ERRNO_IS_PRIVILEGE(r
))
2123 goto handle_privilege
;
2125 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2128 return log_error_errno(errno
, "Failed to open device node '%s' we just created: %m", i
->path
);
2131 if (fstat(fd
, &st
) < 0)
2132 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2134 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0) {
2136 if (i
->append_or_force
) {
2137 fd
= safe_close(fd
);
2140 mac_selinux_create_file_prepare(i
->path
, file_type
);
2141 r
= mknodat_atomic(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
2142 mac_selinux_create_file_clear();
2144 if (ERRNO_IS_PRIVILEGE(r
))
2145 goto handle_privilege
;
2146 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2147 r
= rm_rf_child(dfd
, bn
, REMOVE_PHYSICAL
);
2149 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2151 mac_selinux_create_file_prepare(i
->path
, file_type
);
2152 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2153 mac_selinux_create_file_clear();
2156 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2158 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2160 return log_error_errno(errno
, "Failed to open device node we just created '%s': %m", i
->path
);
2162 /* Validate type before change ownership below */
2163 if (fstat(fd
, &st
) < 0)
2164 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2166 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0)
2167 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Device node we just created is not a device node, refusing.");
2169 creation
= CREATION_FORCE
;
2171 log_warning("\"%s\" already exists and is not a device node.", i
->path
);
2176 log_debug("%s %s device node \"%s\" %u:%u.",
2177 creation_mode_verb_to_string(creation
),
2178 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
2179 i
->path
, major(i
->mode
), minor(i
->mode
));
2181 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2185 "We lack permissions, possibly because of cgroup configuration; "
2186 "skipping creation of device node '%s'.", i
->path
);
2190 static int create_fifo(Context
*c
, Item
*i
) {
2191 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2192 _cleanup_free_
char *bn
= NULL
;
2193 CreationMode creation
;
2199 assert(i
->type
== CREATE_FIFO
);
2201 r
= path_extract_filename(i
->path
, &bn
);
2203 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2204 if (r
== O_DIRECTORY
)
2205 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating FIFO, is a directory.", i
->path
);
2207 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2212 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2213 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2214 mac_selinux_create_file_clear();
2217 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2219 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
2220 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2223 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
); /* original error! */
2225 return log_error_errno(errno
, "Failed to open FIFO we just created %s: %m", i
->path
);
2228 if (fstat(fd
, &st
) < 0)
2229 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2231 if (!S_ISFIFO(st
.st_mode
)) {
2233 if (i
->append_or_force
) {
2234 fd
= safe_close(fd
);
2237 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2238 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
2239 mac_selinux_create_file_clear();
2241 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2242 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2244 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2246 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2247 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2248 mac_selinux_create_file_clear();
2251 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
);
2253 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2255 return log_error_errno(errno
, "Failed to open FIFO we just created '%s': %m", i
->path
);
2257 /* Validate type before change ownership below */
2258 if (fstat(fd
, &st
) < 0)
2259 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2261 if (!S_ISFIFO(st
.st_mode
))
2262 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "FIFO inode we just created is not a FIFO, refusing.");
2264 creation
= CREATION_FORCE
;
2266 log_warning("\"%s\" already exists and is not a FIFO.", i
->path
);
2271 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2273 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2276 static int create_symlink(Context
*c
, Item
*i
) {
2277 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2278 _cleanup_free_
char *bn
= NULL
;
2279 CreationMode creation
;
2287 r
= path_extract_filename(i
->path
, &bn
);
2289 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2290 if (r
== O_DIRECTORY
)
2291 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating FIFO, is a directory.", i
->path
);
2293 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2297 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2298 r
= RET_NERRNO(symlinkat(i
->argument
, pfd
, bn
));
2299 mac_selinux_create_file_clear();
2301 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2303 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2306 return log_error_errno(r
, "Failed to create symlink '%s': %m", i
->path
); /* original error! */
2308 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2311 if (fstat(fd
, &st
) < 0)
2312 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2314 if (S_ISLNK(st
.st_mode
)) {
2315 _cleanup_free_
char *x
= NULL
;
2317 r
= readlinkat_malloc(fd
, "", &x
);
2319 return log_error_errno(r
, "readlinkat(%s) failed: %m", i
->path
);
2321 good
= streq(x
, i
->argument
);
2326 if (!i
->append_or_force
) {
2327 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2331 fd
= safe_close(fd
);
2333 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2334 r
= symlinkat_atomic_full(i
->argument
, pfd
, bn
, /* make_relative= */ false);
2335 mac_selinux_create_file_clear();
2336 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2337 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2339 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2341 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2342 r
= RET_NERRNO(symlinkat(i
->argument
, pfd
, i
->path
));
2343 mac_selinux_create_file_clear();
2346 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2348 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2350 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2352 /* Validate type before change ownership below */
2353 if (fstat(fd
, &st
) < 0)
2354 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2356 if (!S_ISLNK(st
.st_mode
))
2357 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Symlink we just created is not a symlink, refusing.");
2359 creation
= CREATION_FORCE
;
2362 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2363 return fd_set_perms(c
, i
, fd
, i
->path
, &st
, creation
);
2366 typedef int (*action_t
)(Context
*c
, Item
*i
, const char *path
, CreationMode creation
);
2367 typedef int (*fdaction_t
)(Context
*c
, Item
*i
, int fd
, const char *path
, const struct stat
*st
, CreationMode creation
);
2374 CreationMode creation
,
2375 fdaction_t action
) {
2385 if (fstat(fd
, &st
) < 0) {
2386 r
= log_error_errno(errno
, "fstat() on file failed: %m");
2390 /* This returns the first error we run into, but nevertheless tries to go on */
2391 r
= action(c
, i
, fd
, path
, &st
, creation
);
2393 if (S_ISDIR(st
.st_mode
)) {
2394 _cleanup_closedir_
DIR *d
= NULL
;
2396 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2397 * reading the directory content. */
2398 d
= opendir(FORMAT_PROC_FD_PATH(fd
));
2400 log_error_errno(errno
, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd
));
2406 FOREACH_DIRENT_ALL(de
, d
, q
= -errno
; goto finish
) {
2409 if (dot_or_dot_dot(de
->d_name
))
2412 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2414 q
= log_error_errno(errno
, "Failed to open() file '%s': %m", de
->d_name
);
2416 _cleanup_free_
char *de_path
= NULL
;
2418 de_path
= path_join(path
, de
->d_name
);
2422 /* Pass ownership of dirent fd over */
2423 q
= item_do(c
, i
, de_fd
, de_path
, CREATION_EXISTING
, action
);
2426 if (q
< 0 && r
== 0)
2435 static int glob_item(Context
*c
, Item
*i
, action_t action
) {
2436 _cleanup_globfree_ glob_t g
= {
2437 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
2444 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
2445 if (k
< 0 && k
!= -ENOENT
)
2446 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
2448 STRV_FOREACH(fn
, g
.gl_pathv
) {
2449 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2450 k
= action(c
, i
, *fn
, CREATION_EXISTING
);
2451 if (k
< 0 && r
== 0)
2458 static int glob_item_recursively(
2461 fdaction_t action
) {
2463 _cleanup_globfree_ glob_t g
= {
2464 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
2468 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
2469 if (k
< 0 && k
!= -ENOENT
)
2470 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
2472 STRV_FOREACH(fn
, g
.gl_pathv
) {
2473 _cleanup_close_
int fd
= -EBADF
;
2475 /* Make sure we won't trigger/follow file object (such as
2476 * device nodes, automounts, ...) pointed out by 'fn' with
2477 * O_PATH. Note, when O_PATH is used, flags other than
2478 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2480 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
2482 log_error_errno(errno
, "Opening '%s' failed: %m", *fn
);
2488 k
= item_do(c
, i
, fd
, *fn
, CREATION_EXISTING
, action
);
2489 if (k
< 0 && r
== 0)
2492 /* we passed fd ownership to the previous call */
2499 static int rm_if_wrong_type_safe(
2502 const struct stat
*parent_st
, /* Only used if follow_links below is true. */
2505 _cleanup_free_
char *parent_name
= NULL
;
2506 bool follow_links
= !FLAGS_SET(flags
, AT_SYMLINK_NOFOLLOW
);
2511 assert((mode
& ~S_IFMT
) == 0);
2512 assert(!follow_links
|| parent_st
);
2513 assert((flags
& ~AT_SYMLINK_NOFOLLOW
) == 0);
2515 if (!filename_is_valid(name
))
2516 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "\"%s\" is not a valid filename.", name
);
2518 r
= fstatat_harder(parent_fd
, name
, &st
, flags
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2520 (void) fd_get_path(parent_fd
, &parent_name
);
2521 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_ERR
, r
,
2522 "Failed to stat \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2525 /* Fail before removing anything if this is an unsafe transition. */
2526 if (follow_links
&& unsafe_transition(parent_st
, &st
)) {
2527 (void) fd_get_path(parent_fd
, &parent_name
);
2528 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK
),
2529 "Unsafe transition from \"%s\" to \"%s\".", parent_name
, name
);
2532 if ((st
.st_mode
& S_IFMT
) == mode
)
2535 (void) fd_get_path(parent_fd
, &parent_name
);
2536 log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st
.st_mode
& S_IFMT
, strna(parent_name
), name
);
2538 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2539 * target, so make sure it is identified as a link and not a directory. */
2541 r
= fstatat_harder(parent_fd
, name
, &st
, AT_SYMLINK_NOFOLLOW
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2543 return log_error_errno(r
, "Failed to stat \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2546 /* Do not remove mount points. */
2547 r
= fd_is_mount_point(parent_fd
, name
, follow_links
? AT_SYMLINK_FOLLOW
: 0);
2549 (void) log_warning_errno(r
, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2550 strna(parent_name
), name
);
2552 return log_error_errno(SYNTHETIC_ERRNO(EBUSY
),
2553 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name
), name
);
2555 if ((st
.st_mode
& S_IFMT
) == S_IFDIR
) {
2556 _cleanup_close_
int child_fd
= -EBADF
;
2558 child_fd
= openat(parent_fd
, name
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2560 return log_error_errno(errno
, "Failed to open \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2562 r
= rm_rf_children(TAKE_FD(child_fd
), REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
, &st
);
2564 return log_error_errno(r
, "Failed to remove contents of \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2566 r
= unlinkat_harder(parent_fd
, name
, AT_REMOVEDIR
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2568 r
= unlinkat_harder(parent_fd
, name
, 0, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2570 return log_error_errno(r
, "Failed to remove \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2572 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2573 * context to other error messages that might follow. */
2577 /* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2578 static int mkdir_parents_rm_if_wrong_type(mode_t child_mode
, const char *path
) {
2579 _cleanup_close_
int parent_fd
= -EBADF
;
2580 struct stat parent_st
;
2585 assert((child_mode
& ~S_IFMT
) == 0);
2587 path_len
= strlen(path
);
2590 /* rm_if_wrong_type_safe already logs errors. */
2591 return child_mode
!= 0 ? rm_if_wrong_type_safe(child_mode
, AT_FDCWD
, NULL
, path
, AT_SYMLINK_NOFOLLOW
) : 0;
2593 if (child_mode
!= 0 && endswith(path
, "/"))
2594 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2595 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path
);
2597 /* Get the parent_fd and stat. */
2598 parent_fd
= openat(AT_FDCWD
, path_is_absolute(path
) ? "/" : ".", O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2600 return log_error_errno(errno
, "Failed to open root: %m");
2602 if (fstat(parent_fd
, &parent_st
) < 0)
2603 return log_error_errno(errno
, "Failed to stat root: %m");
2605 /* Check every parent directory in the path, except the last component */
2606 for (const char *e
= path
;;) {
2607 _cleanup_close_
int next_fd
= -EBADF
;
2608 char t
[path_len
+ 1];
2611 /* Find the start of the next path component. */
2612 s
= e
+ strspn(e
, "/");
2613 /* Find the end of the next path component. */
2614 e
= s
+ strcspn(s
, "/");
2616 /* Copy the path component to t so it can be a null terminated string. */
2617 *((char*) mempcpy(t
, s
, e
- s
)) = 0;
2619 /* Is this the last component? If so, then check the type */
2621 return child_mode
!= 0 ? rm_if_wrong_type_safe(child_mode
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
) : 0;
2623 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, 0);
2624 /* Remove dangling symlinks. */
2626 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
);
2629 r
= mkdirat_label(parent_fd
, t
, 0755);
2631 _cleanup_free_
char *parent_name
= NULL
;
2633 (void) fd_get_path(parent_fd
, &parent_name
);
2634 return log_error_errno(r
, "Failed to mkdir \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2637 /* rm_if_wrong_type_safe already logs errors. */
2640 next_fd
= RET_NERRNO(openat(parent_fd
, t
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
));
2642 _cleanup_free_
char *parent_name
= NULL
;
2644 (void) fd_get_path(parent_fd
, &parent_name
);
2645 return log_error_errno(next_fd
, "Failed to open \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2647 r
= RET_NERRNO(fstat(next_fd
, &parent_st
));
2649 _cleanup_free_
char *parent_name
= NULL
;
2651 (void) fd_get_path(parent_fd
, &parent_name
);
2652 return log_error_errno(r
, "Failed to stat \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2655 close_and_replace(parent_fd
, next_fd
);
2659 static int mkdir_parents_item(Item
*i
, mode_t child_mode
) {
2661 if (i
->try_replace
) {
2662 r
= mkdir_parents_rm_if_wrong_type(child_mode
, i
->path
);
2663 if (r
< 0 && r
!= -ENOENT
)
2667 (void) mkdir_parents_label(i
->path
, 0755);
2672 static int create_item(Context
*c
, Item
*i
) {
2678 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
2683 case IGNORE_DIRECTORY_PATH
:
2685 case RECURSIVE_REMOVE_PATH
:
2690 r
= mkdir_parents_item(i
, S_IFREG
);
2694 if ((i
->type
== CREATE_FILE
&& i
->append_or_force
) || i
->type
== TRUNCATE_FILE
)
2695 r
= truncate_file(c
, i
, i
->path
);
2697 r
= create_file(c
, i
, i
->path
);
2703 r
= mkdir_parents_item(i
, 0);
2707 r
= copy_files(c
, i
);
2713 r
= glob_item(c
, i
, write_one_file
);
2719 case CREATE_DIRECTORY
:
2720 case TRUNCATE_DIRECTORY
:
2721 r
= mkdir_parents_item(i
, S_IFDIR
);
2725 r
= create_directory(c
, i
, i
->path
);
2730 case CREATE_SUBVOLUME
:
2731 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2732 case CREATE_SUBVOLUME_NEW_QUOTA
:
2733 r
= mkdir_parents_item(i
, S_IFDIR
);
2737 r
= create_subvolume(c
, i
, i
->path
);
2742 case EMPTY_DIRECTORY
:
2743 r
= glob_item(c
, i
, empty_directory
);
2749 r
= mkdir_parents_item(i
, S_IFIFO
);
2753 r
= create_fifo(c
, i
);
2758 case CREATE_SYMLINK
:
2759 r
= mkdir_parents_item(i
, S_IFLNK
);
2763 r
= create_symlink(c
, i
);
2769 case CREATE_BLOCK_DEVICE
:
2770 case CREATE_CHAR_DEVICE
:
2771 if (have_effective_cap(CAP_MKNOD
) <= 0) {
2772 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2773 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2775 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2779 r
= mkdir_parents_item(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2783 r
= create_device(c
, i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2791 r
= glob_item(c
, i
, path_set_perms
);
2796 case RECURSIVE_RELABEL_PATH
:
2797 r
= glob_item_recursively(c
, i
, fd_set_perms
);
2803 r
= glob_item(c
, i
, path_set_xattrs
);
2808 case RECURSIVE_SET_XATTR
:
2809 r
= glob_item_recursively(c
, i
, fd_set_xattrs
);
2815 r
= glob_item(c
, i
, path_set_acls
);
2820 case RECURSIVE_SET_ACL
:
2821 r
= glob_item_recursively(c
, i
, fd_set_acls
);
2827 r
= glob_item(c
, i
, path_set_attribute
);
2832 case RECURSIVE_SET_ATTRIBUTE
:
2833 r
= glob_item_recursively(c
, i
, fd_set_attribute
);
2842 static int remove_item_instance(
2845 const char *instance
,
2846 CreationMode creation
) {
2856 if (remove(instance
) < 0 && errno
!= ENOENT
)
2857 return log_error_errno(errno
, "rm(%s): %m", instance
);
2861 case RECURSIVE_REMOVE_PATH
:
2862 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2863 log_debug("rm -rf \"%s\"", instance
);
2864 r
= rm_rf(instance
, REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
);
2865 if (r
< 0 && r
!= -ENOENT
)
2866 return log_error_errno(r
, "rm_rf(%s): %m", instance
);
2871 assert_not_reached();
2877 static int remove_item(Context
*c
, Item
*i
) {
2883 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
2887 case TRUNCATE_DIRECTORY
:
2888 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2889 log_debug("rm -rf \"%s\"", i
->path
);
2890 r
= rm_rf(i
->path
, REMOVE_PHYSICAL
);
2891 if (r
< 0 && r
!= -ENOENT
)
2892 return log_error_errno(r
, "rm_rf(%s): %m", i
->path
);
2897 case RECURSIVE_REMOVE_PATH
:
2898 return glob_item(c
, i
, remove_item_instance
);
2905 static char *age_by_to_string(AgeBy ab
, bool is_dir
) {
2906 static const char ab_map
[] = { 'a', 'b', 'c', 'm' };
2910 ret
= new(char, ELEMENTSOF(ab_map
) + 1);
2914 for (size_t i
= 0; i
< ELEMENTSOF(ab_map
); i
++)
2915 if (FLAGS_SET(ab
, 1U << i
))
2916 ret
[j
++] = is_dir
? ascii_toupper(ab_map
[i
]) : ab_map
[i
];
2922 static int clean_item_instance(
2925 const char* instance
,
2926 CreationMode creation
) {
2928 _cleanup_closedir_
DIR *d
= NULL
;
2929 STRUCT_STATX_DEFINE(sx
);
2938 n
= now(CLOCK_REALTIME
);
2942 cutoff
= n
- i
->age
;
2944 d
= opendir_nomod(instance
);
2946 if (IN_SET(errno
, ENOENT
, ENOTDIR
)) {
2947 log_debug_errno(errno
, "Directory \"%s\": %m", instance
);
2951 return log_error_errno(errno
, "Failed to open directory %s: %m", instance
);
2954 r
= statx_fallback(dirfd(d
), "", AT_EMPTY_PATH
, STATX_MODE
|STATX_INO
|STATX_ATIME
|STATX_MTIME
, &sx
);
2956 return log_error_errno(r
, "statx(%s) failed: %m", instance
);
2958 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
))
2959 mountpoint
= FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
);
2963 if (fstatat(dirfd(d
), "..", &ps
, AT_SYMLINK_NOFOLLOW
) != 0)
2964 return log_error_errno(errno
, "stat(%s/..) failed: %m", i
->path
);
2967 sx
.stx_dev_major
!= major(ps
.st_dev
) ||
2968 sx
.stx_dev_minor
!= minor(ps
.st_dev
) ||
2969 sx
.stx_ino
!= ps
.st_ino
;
2972 if (DEBUG_LOGGING
) {
2973 _cleanup_free_
char *ab_f
= NULL
, *ab_d
= NULL
;
2975 ab_f
= age_by_to_string(i
->age_by_file
, false);
2979 ab_d
= age_by_to_string(i
->age_by_dir
, true);
2983 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
2984 mountpoint
? "mount point" : "directory",
2986 FORMAT_TIMESTAMP_STYLE(cutoff
, TIMESTAMP_US
),
2990 return dir_cleanup(c
, i
, instance
, d
,
2991 load_statx_timestamp_nsec(&sx
.stx_atime
),
2992 load_statx_timestamp_nsec(&sx
.stx_mtime
),
2993 cutoff
* NSEC_PER_USEC
,
2994 sx
.stx_dev_major
, sx
.stx_dev_minor
, mountpoint
,
2995 MAX_DEPTH
, i
->keep_first_level
,
2996 i
->age_by_file
, i
->age_by_dir
);
2999 static int clean_item(Context
*c
, Item
*i
) {
3003 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
3007 case CREATE_DIRECTORY
:
3008 case CREATE_SUBVOLUME
:
3009 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
3010 case CREATE_SUBVOLUME_NEW_QUOTA
:
3011 case TRUNCATE_DIRECTORY
:
3014 clean_item_instance(c
, i
, i
->path
, CREATION_EXISTING
);
3017 case EMPTY_DIRECTORY
:
3018 case IGNORE_DIRECTORY_PATH
:
3019 return glob_item(c
, i
, clean_item_instance
);
3026 static int process_item(
3029 OperationMask operation
) {
3032 _cleanup_free_
char *_path
= NULL
;
3039 todo
= operation
& ~i
->done
;
3040 if (todo
== 0) /* Everything already done? */
3043 i
->done
|= operation
;
3046 if (string_is_glob(path
)) {
3047 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
3048 * for the non-glob part. */
3050 r
= glob_non_glob_prefix(path
, &_path
);
3051 if (r
< 0 && r
!= -ENOENT
)
3052 return log_debug_errno(r
, "Failed to deglob path: %m");
3057 r
= chase(path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_NONEXISTENT
|CHASE_WARN
, NULL
, NULL
);
3058 if (r
== -EREMOTE
) {
3059 log_notice_errno(r
, "Skipping %s", i
->path
); /* We log the configured path, to not confuse the user. */
3063 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
3065 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(c
, i
) : 0;
3066 /* Failure can only be tolerated for create */
3067 if (i
->allow_failure
)
3070 q
= FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(c
, i
) : 0;
3071 p
= FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(c
, i
) : 0;
3078 static int process_item_array(
3081 OperationMask operation
) {
3089 /* Create any parent first. */
3090 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
3091 r
= process_item_array(c
, array
->parent
, operation
& OPERATION_CREATE
);
3093 /* Clean up all children first */
3094 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
)) && !set_isempty(array
->children
)) {
3097 SET_FOREACH(cc
, array
->children
) {
3100 k
= process_item_array(c
, cc
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
));
3101 if (k
< 0 && r
== 0)
3106 for (n
= 0; n
< array
->n_items
; n
++) {
3109 k
= process_item(c
, array
->items
+ n
, operation
);
3110 if (k
< 0 && r
== 0)
3117 static void item_free_contents(Item
*i
) {
3121 free(i
->binary_argument
);
3122 strv_free(i
->xattrs
);
3126 acl_free(i
->acl_access
);
3128 if (i
->acl_access_exec
)
3129 acl_free(i
->acl_access_exec
);
3132 acl_free(i
->acl_default
);
3136 static ItemArray
* item_array_free(ItemArray
*a
) {
3142 for (n
= 0; n
< a
->n_items
; n
++)
3143 item_free_contents(a
->items
+ n
);
3145 set_free(a
->children
);
3150 static int item_compare(const Item
*a
, const Item
*b
) {
3151 /* Make sure that the ownership taking item is put first, so
3152 * that we first create the node, and then can adjust it */
3154 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
3156 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
3159 return CMP(a
->type
, b
->type
);
3162 static bool item_compatible(const Item
*a
, const Item
*b
) {
3165 assert(streq(a
->path
, b
->path
));
3167 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
3168 /* check if the items are the same */
3169 return memcmp_nn(item_binary_argument(a
), item_binary_argument_size(a
),
3170 item_binary_argument(b
), item_binary_argument_size(b
)) == 0 &&
3172 a
->uid_set
== b
->uid_set
&&
3174 a
->uid_only_create
== b
->uid_only_create
&&
3176 a
->gid_set
== b
->gid_set
&&
3178 a
->gid_only_create
== b
->gid_only_create
&&
3180 a
->mode_set
== b
->mode_set
&&
3181 a
->mode
== b
->mode
&&
3182 a
->mode_only_create
== b
->mode_only_create
&&
3184 a
->age_set
== b
->age_set
&&
3187 a
->age_by_file
== b
->age_by_file
&&
3188 a
->age_by_dir
== b
->age_by_dir
&&
3190 a
->mask_perms
== b
->mask_perms
&&
3192 a
->keep_first_level
== b
->keep_first_level
&&
3194 a
->major_minor
== b
->major_minor
;
3199 static bool should_include_path(const char *path
) {
3200 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
3201 if (path_startswith(path
, *prefix
)) {
3202 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
3207 STRV_FOREACH(prefix
, arg_include_prefixes
)
3208 if (path_startswith(path
, *prefix
)) {
3209 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
3213 /* no matches, so we should include this path only if we have no allow list at all */
3214 if (strv_isempty(arg_include_prefixes
))
3217 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
3221 static int specifier_expansion_from_arg(const Specifier
*specifier_table
, Item
*i
) {
3231 case CREATE_SYMLINK
:
3235 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
3238 l
= cunescape(i
->argument
, 0, &unescaped
);
3240 return log_error_errno(l
, "Failed to unescape parameter to write: %s", i
->argument
);
3242 r
= specifier_printf(unescaped
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &resolved
);
3246 return free_and_replace(i
->argument
, resolved
);
3249 case RECURSIVE_SET_XATTR
:
3250 STRV_FOREACH(xattr
, i
->xattrs
) {
3251 _cleanup_free_
char *resolved
= NULL
;
3253 r
= specifier_printf(*xattr
, SIZE_MAX
, specifier_table
, arg_root
, NULL
, &resolved
);
3257 free_and_replace(*xattr
, resolved
);
3266 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
3273 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
3274 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
3275 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
3276 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
3277 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
3278 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
3279 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
3280 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
3281 * the latter. Moreover files below this path are by far the primary use case for tmpfiles.d/. */
3283 k
= path_startswith(*path
, "/var/run/");
3284 if (isempty(k
)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
3287 n
= path_join("/run", k
);
3291 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
3292 * there's no immediate need for action by the user. However, in the interest of making things less confusing
3293 * to the user, let's still inform the user that these snippets should really be updated. */
3294 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
3295 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3298 free_and_replace(*path
, n
);
3303 static int find_uid(const char *user
, uid_t
*ret_uid
, Hashmap
**cache
) {
3309 /* First: parse as numeric UID string */
3310 r
= parse_uid(user
, ret_uid
);
3314 /* Second: pass to NSS if we are running "online" */
3316 return get_user_creds(&user
, ret_uid
, NULL
, NULL
, NULL
, 0);
3318 /* Third, synthesize "root" unconditionally */
3319 if (streq(user
, "root")) {
3324 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3325 return name_to_uid_offline(arg_root
, user
, ret_uid
, cache
);
3328 static int find_gid(const char *group
, gid_t
*ret_gid
, Hashmap
**cache
) {
3334 /* First: parse as numeric GID string */
3335 r
= parse_gid(group
, ret_gid
);
3339 /* Second: pass to NSS if we are running "online" */
3341 return get_group_creds(&group
, ret_gid
, 0);
3343 /* Third, synthesize "root" unconditionally */
3344 if (streq(group
, "root")) {
3349 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3350 return name_to_gid_offline(arg_root
, group
, ret_gid
, cache
);
3353 static int parse_age_by_from_arg(const char *age_by_str
, Item
*item
) {
3354 AgeBy ab_f
= 0, ab_d
= 0;
3356 static const struct {
3359 } age_by_types
[] = {
3360 { 'a', AGE_BY_ATIME
},
3361 { 'b', AGE_BY_BTIME
},
3362 { 'c', AGE_BY_CTIME
},
3363 { 'm', AGE_BY_MTIME
},
3369 if (isempty(age_by_str
))
3372 for (const char *s
= age_by_str
; *s
!= 0; s
++) {
3375 /* Ignore whitespace. */
3376 if (strchr(WHITESPACE
, *s
))
3379 for (i
= 0; i
< ELEMENTSOF(age_by_types
); i
++) {
3380 /* Check lower-case for files, upper-case for directories. */
3381 if (*s
== age_by_types
[i
].age_by_chr
) {
3382 ab_f
|= age_by_types
[i
].age_by_flag
;
3384 } else if (*s
== ascii_toupper(age_by_types
[i
].age_by_chr
)) {
3385 ab_d
|= age_by_types
[i
].age_by_flag
;
3390 /* Invalid character. */
3391 if (i
>= ELEMENTSOF(age_by_types
))
3396 if (ab_f
== 0 && ab_d
== 0)
3399 item
->age_by_file
= ab_f
> 0 ? ab_f
: AGE_BY_DEFAULT_FILE
;
3400 item
->age_by_dir
= ab_d
> 0 ? ab_d
: AGE_BY_DEFAULT_DIR
;
3405 static bool is_duplicated_item(ItemArray
*existing
, const Item
*i
) {
3410 for (size_t n
= 0; n
< existing
->n_items
; n
++) {
3411 const Item
*e
= existing
->items
+ n
;
3413 if (item_compatible(e
, i
))
3416 /* Only multiple 'w+' lines for the same path are allowed. */
3417 if (e
->type
!= WRITE_FILE
|| !e
->append_or_force
||
3418 i
->type
!= WRITE_FILE
|| !i
->append_or_force
)
3425 static int parse_line(
3430 bool *invalid_config
,
3431 Hashmap
**uid_cache
,
3432 Hashmap
**gid_cache
) {
3434 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
3435 _cleanup_(item_free_contents
) Item i
= {
3436 /* The "age-by" argument considers all file timestamp types by default. */
3437 .age_by_file
= AGE_BY_DEFAULT_FILE
,
3438 .age_by_dir
= AGE_BY_DEFAULT_DIR
,
3440 ItemArray
*existing
;
3443 bool append_or_force
= false, boot
= false, allow_failure
= false, try_replace
= false,
3444 unbase64
= false, from_cred
= false, missing_user_or_group
= false;
3451 const Specifier specifier_table
[] = {
3452 { 'a', specifier_architecture
, NULL
},
3453 { 'b', specifier_boot_id
, NULL
},
3454 { 'B', specifier_os_build_id
, NULL
},
3455 { 'H', specifier_hostname
, NULL
},
3456 { 'l', specifier_short_hostname
, NULL
},
3457 { 'm', specifier_machine_id
, NULL
},
3458 { 'o', specifier_os_id
, NULL
},
3459 { 'v', specifier_kernel_release
, NULL
},
3460 { 'w', specifier_os_version_id
, NULL
},
3461 { 'W', specifier_os_variant_id
, NULL
},
3463 { 'h', specifier_user_home
, NULL
},
3465 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
3466 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
3467 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
3468 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
3470 COMMON_CREDS_SPECIFIERS(arg_runtime_scope
),
3471 COMMON_TMP_SPECIFIERS
,
3475 r
= extract_many_words(
3478 EXTRACT_UNQUOTE
| EXTRACT_CUNESCAPE
,
3487 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3488 /* invalid quoting and such or an unknown specifier */
3489 *invalid_config
= true;
3490 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to parse line: %m");
3492 *invalid_config
= true;
3493 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Syntax error.");
3496 if (!empty_or_dash(buffer
)) {
3497 i
.argument
= strdup(buffer
);
3502 if (isempty(action
)) {
3503 *invalid_config
= true;
3504 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Command too short '%s'.", action
);
3507 for (pos
= 1; action
[pos
]; pos
++) {
3508 if (action
[pos
] == '!' && !boot
)
3510 else if (action
[pos
] == '+' && !append_or_force
)
3511 append_or_force
= true;
3512 else if (action
[pos
] == '-' && !allow_failure
)
3513 allow_failure
= true;
3514 else if (action
[pos
] == '=' && !try_replace
)
3516 else if (action
[pos
] == '~' && !unbase64
)
3518 else if (action
[pos
] == '^' && !from_cred
)
3521 *invalid_config
= true;
3522 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Unknown modifiers in command '%s'", action
);
3526 if (boot
&& !arg_boot
) {
3527 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action
, path
);
3532 i
.append_or_force
= append_or_force
;
3533 i
.allow_failure
= allow_failure
;
3534 i
.try_replace
= try_replace
;
3536 r
= specifier_printf(path
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &i
.path
);
3537 if (ERRNO_IS_NOINFO(r
))
3538 return log_unresolvable_specifier(fname
, line
);
3540 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3541 *invalid_config
= true;
3542 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", path
);
3545 r
= patch_var_run(fname
, line
, &i
.path
);
3549 if (!path_is_absolute(i
.path
)) {
3550 *invalid_config
= true;
3551 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3552 "Path '%s' not absolute.", i
.path
);
3555 path_simplify(i
.path
);
3559 case CREATE_DIRECTORY
:
3560 case CREATE_SUBVOLUME
:
3561 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
3562 case CREATE_SUBVOLUME_NEW_QUOTA
:
3563 case EMPTY_DIRECTORY
:
3564 case TRUNCATE_DIRECTORY
:
3567 case IGNORE_DIRECTORY_PATH
:
3569 case RECURSIVE_REMOVE_PATH
:
3572 case RECURSIVE_RELABEL_PATH
:
3579 "%c lines don't take argument fields, ignoring.",
3588 case CREATE_SYMLINK
:
3590 *invalid_config
= true;
3591 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for symlink targets.");
3597 *invalid_config
= true;
3598 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Write file requires argument.");
3604 *invalid_config
= true;
3605 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for copy sources.");
3609 case CREATE_CHAR_DEVICE
:
3610 case CREATE_BLOCK_DEVICE
:
3612 *invalid_config
= true;
3613 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for device node creation.");
3617 *invalid_config
= true;
3618 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Device file requires argument.");
3621 r
= parse_devnum(i
.argument
, &i
.major_minor
);
3623 *invalid_config
= true;
3624 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Can't parse device file major/minor '%s'.", i
.argument
);
3630 case RECURSIVE_SET_XATTR
:
3632 *invalid_config
= true;
3633 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for extended attributes.");
3636 *invalid_config
= true;
3637 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3638 "Set extended attribute requires argument.");
3640 r
= parse_xattrs_from_arg(&i
);
3646 case RECURSIVE_SET_ACL
:
3648 *invalid_config
= true;
3649 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for ACLs.");
3652 *invalid_config
= true;
3653 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3654 "Set ACLs requires argument.");
3656 r
= parse_acls_from_arg(&i
);
3662 case RECURSIVE_SET_ATTRIBUTE
:
3664 *invalid_config
= true;
3665 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for file attributes.");
3668 *invalid_config
= true;
3669 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3670 "Set file attribute requires argument.");
3672 r
= parse_attribute_from_arg(&i
);
3673 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3674 *invalid_config
= true;
3680 *invalid_config
= true;
3681 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3682 "Unknown command type '%c'.", (char) i
.type
);
3685 if (!should_include_path(i
.path
))
3689 /* Do specifier expansion except if base64 mode is enabled */
3690 r
= specifier_expansion_from_arg(specifier_table
, &i
);
3691 if (ERRNO_IS_NOINFO(r
))
3692 return log_unresolvable_specifier(fname
, line
);
3694 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3695 *invalid_config
= true;
3696 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to substitute specifiers in argument: %m");
3701 case CREATE_SYMLINK
:
3703 i
.argument
= path_join("/usr/share/factory", i
.path
);
3711 i
.argument
= path_join("/usr/share/factory", i
.path
);
3714 } else if (!path_is_absolute(i
.argument
)) {
3715 *invalid_config
= true;
3716 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Source path '%s' is not absolute.", i
.argument
);
3720 if (!empty_or_root(arg_root
)) {
3723 p
= path_join(arg_root
, i
.argument
);
3726 free_and_replace(i
.argument
, p
);
3729 path_simplify(i
.argument
);
3731 if (laccess(i
.argument
, F_OK
) == -ENOENT
) {
3732 /* Silently skip over lines where the source file is missing. */
3733 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Copy source path '%s' does not exist, skipping line.", i
.argument
);
3745 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
), "Reading from credential requested, but no credential name specified.");
3746 if (!credential_name_valid(i
.argument
))
3747 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
), "Credential name not valid: %s", i
.argument
);
3749 r
= read_credential(i
.argument
, &i
.binary_argument
, &i
.binary_argument_size
);
3750 if (IN_SET(r
, -ENXIO
, -ENOENT
)) {
3751 /* Silently skip over lines that have no credentials passed */
3752 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0,
3753 "Credential '%s' not specified, skipping line.", i
.argument
);
3757 return log_error_errno(r
, "Failed to read credential '%s': %m", i
.argument
);
3760 /* If base64 decoding is requested, do so now */
3761 if (unbase64
&& item_binary_argument(&i
)) {
3762 _cleanup_free_
void *data
= NULL
;
3763 size_t data_size
= 0;
3765 r
= unbase64mem(item_binary_argument(&i
), item_binary_argument_size(&i
), &data
, &data_size
);
3767 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to base64 decode specified argument '%s': %m", i
.argument
);
3769 free_and_replace(i
.binary_argument
, data
);
3770 i
.binary_argument_size
= data_size
;
3773 if (!empty_or_root(arg_root
)) {
3776 p
= path_join(arg_root
, i
.path
);
3779 free_and_replace(i
.path
, p
);
3782 if (!empty_or_dash(user
)) {
3785 u
= startswith(user
, ":");
3787 i
.uid_only_create
= true;
3791 r
= find_uid(u
, &i
.uid
, uid_cache
);
3792 if (r
== -ESRCH
&& arg_graceful
) {
3793 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, r
,
3794 "%s: user '%s' not found, not adjusting ownership.", i
.path
, u
);
3795 missing_user_or_group
= true;
3797 *invalid_config
= true;
3798 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve user '%s': %m", u
);
3803 if (!empty_or_dash(group
)) {
3806 g
= startswith(group
, ":");
3808 i
.gid_only_create
= true;
3812 r
= find_gid(g
, &i
.gid
, gid_cache
);
3813 if (r
== -ESRCH
&& arg_graceful
) {
3814 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, r
,
3815 "%s: group '%s' not found, not adjusting ownership.", i
.path
, g
);
3816 missing_user_or_group
= true;
3818 *invalid_config
= true;
3819 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve group '%s': %m", g
);
3824 if (!empty_or_dash(mode
)) {
3828 for (mm
= mode
;; mm
++) {
3830 i
.mask_perms
= true;
3831 else if (*mm
== ':')
3832 i
.mode_only_create
= true;
3837 r
= parse_mode(mm
, &m
);
3839 *invalid_config
= true;
3840 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid mode '%s'.", mode
);
3846 i
.mode
= IN_SET(i
.type
,
3850 CREATE_SUBVOLUME_INHERIT_QUOTA
,
3851 CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
3853 if (missing_user_or_group
&& (i
.mode
& ~0777) != 0) {
3854 /* Refuse any special bits for nodes where we couldn't resolve the ownership properly. */
3855 mode_t adjusted
= i
.mode
& 0777;
3856 log_syntax(NULL
, LOG_INFO
, fname
, line
, 0,
3857 "Changing mode 0%o to 0%o because of changed ownership.", i
.mode
, adjusted
);
3861 if (!empty_or_dash(age
)) {
3862 const char *a
= age
;
3863 _cleanup_free_
char *seconds
= NULL
, *age_by
= NULL
;
3866 i
.keep_first_level
= true;
3870 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3871 r
= split_pair(a
, ":", &age_by
, &seconds
);
3874 if (r
< 0 && r
!= -EINVAL
)
3875 return log_error_errno(r
, "Failed to parse age-by for '%s': %m", age
);
3877 /* We found a ":", parse the "age-by" part. */
3878 r
= parse_age_by_from_arg(age_by
, &i
);
3882 *invalid_config
= true;
3883 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age-by '%s'.", age_by
);
3886 /* For parsing the "age" part, after the ":". */
3890 r
= parse_sec(a
, &i
.age
);
3892 *invalid_config
= true;
3893 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age '%s'.", a
);
3899 h
= needs_glob(i
.type
) ? c
->globs
: c
->items
;
3901 existing
= ordered_hashmap_get(h
, i
.path
);
3903 if (is_duplicated_item(existing
, &i
)) {
3904 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
3905 "Duplicate line for path \"%s\", ignoring.", i
.path
);
3909 existing
= new0(ItemArray
, 1);
3913 r
= ordered_hashmap_put(h
, i
.path
, existing
);
3920 if (!GREEDY_REALLOC(existing
->items
, existing
->n_items
+ 1))
3923 existing
->items
[existing
->n_items
++] = TAKE_STRUCT(i
);
3925 /* Sort item array, to enforce stable ordering of application */
3926 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
3931 static int cat_config(char **config_dirs
, char **args
) {
3932 _cleanup_strv_free_
char **files
= NULL
;
3935 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
3939 pager_open(arg_pager_flags
);
3941 return cat_files(NULL
, files
, arg_cat_flags
);
3944 static int exclude_default_prefixes(void) {
3947 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3948 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3949 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3950 * all kinds of files created/adjusted underneath these mount points. */
3952 r
= strv_extend_strv(
3953 &arg_exclude_prefixes
,
3965 static int help(void) {
3966 _cleanup_free_
char *link
= NULL
;
3969 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
3973 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3974 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3975 " -h --help Show this help\n"
3976 " --user Execute user configuration\n"
3977 " --version Show package version\n"
3978 " --cat-config Show configuration files\n"
3979 " --tldr Show non-comment parts of configuration\n"
3980 " --create Create marked files/directories\n"
3981 " --clean Clean up marked directories\n"
3982 " --remove Remove marked files/directories\n"
3983 " --boot Execute actions only safe at boot\n"
3984 " --graceful Quietly ignore unknown users or groups\n"
3985 " --prefix=PATH Only apply rules with the specified prefix\n"
3986 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3987 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3988 " --root=PATH Operate on an alternate filesystem root\n"
3989 " --image=PATH Operate on disk image as filesystem root\n"
3990 " --image-policy=POLICY Specify disk image dissection policy\n"
3991 " --replace=PATH Treat arguments as replacement for PATH\n"
3992 " --no-pager Do not pipe output into a pager\n"
3993 "\nSee the %s for details.\n",
3994 program_invocation_short_name
,
4002 static int parse_argv(int argc
, char *argv
[]) {
4005 ARG_VERSION
= 0x100,
4023 static const struct option options
[] = {
4024 { "help", no_argument
, NULL
, 'h' },
4025 { "user", no_argument
, NULL
, ARG_USER
},
4026 { "version", no_argument
, NULL
, ARG_VERSION
},
4027 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
4028 { "tldr", no_argument
, NULL
, ARG_TLDR
},
4029 { "create", no_argument
, NULL
, ARG_CREATE
},
4030 { "clean", no_argument
, NULL
, ARG_CLEAN
},
4031 { "remove", no_argument
, NULL
, ARG_REMOVE
},
4032 { "boot", no_argument
, NULL
, ARG_BOOT
},
4033 { "graceful", no_argument
, NULL
, ARG_GRACEFUL
},
4034 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
4035 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
4036 { "root", required_argument
, NULL
, ARG_ROOT
},
4037 { "image", required_argument
, NULL
, ARG_IMAGE
},
4038 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
4039 { "replace", required_argument
, NULL
, ARG_REPLACE
},
4040 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
4049 while ((c
= getopt_long(argc
, argv
, "hE", options
, NULL
)) >= 0)
4059 case ARG_CAT_CONFIG
:
4060 arg_cat_flags
= CAT_CONFIG_ON
;
4064 arg_cat_flags
= CAT_TLDR
;
4068 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
4072 arg_operation
|= OPERATION_CREATE
;
4076 arg_operation
|= OPERATION_CLEAN
;
4080 arg_operation
|= OPERATION_REMOVE
;
4088 arg_graceful
= true;
4092 if (strv_push(&arg_include_prefixes
, optarg
) < 0)
4096 case ARG_EXCLUDE_PREFIX
:
4097 if (strv_push(&arg_exclude_prefixes
, optarg
) < 0)
4102 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
4109 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
4110 "This systemd-tmpfiles version is compiled without support for --image=.");
4112 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
4116 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
4120 r
= exclude_default_prefixes();
4126 case ARG_IMAGE_POLICY
:
4127 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
4133 if (!path_is_absolute(optarg
) ||
4134 !endswith(optarg
, ".conf"))
4135 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4136 "The argument to --replace= must an absolute path to a config file");
4138 arg_replace
= optarg
;
4142 arg_pager_flags
|= PAGER_DISABLE
;
4149 assert_not_reached();
4152 if (arg_operation
== 0 && arg_cat_flags
== CAT_CONFIG_OFF
)
4153 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4154 "You need to specify at least one of --clean, --create, or --remove.");
4156 if (arg_replace
&& arg_cat_flags
!= CAT_CONFIG_OFF
)
4157 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4158 "Option --replace= is not supported with --cat-config/--tldr.");
4160 if (arg_replace
&& optind
>= argc
)
4161 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4162 "When --replace= is given, some configuration items must be specified.");
4164 if (arg_root
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
)
4165 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4166 "Combination of --user and --root= is not supported.");
4168 if (arg_image
&& arg_root
)
4169 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
4174 static int read_config_file(
4179 bool *invalid_config
) {
4181 _cleanup_hashmap_free_ Hashmap
*uid_cache
= NULL
, *gid_cache
= NULL
;
4182 _cleanup_fclose_
FILE *_f
= NULL
;
4183 _cleanup_free_
char *pp
= NULL
;
4192 if (streq(fn
, "-")) {
4193 log_debug("Reading config from stdin%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4197 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &_f
, &pp
);
4199 if (ignore_enoent
&& r
== -ENOENT
) {
4200 log_debug_errno(r
, "Failed to open \"%s\", ignoring: %m", fn
);
4204 return log_error_errno(r
, "Failed to open '%s': %m", fn
);
4207 log_debug("Reading config file \"%s\"%s", pp
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4213 _cleanup_free_
char *line
= NULL
;
4214 bool invalid_line
= false;
4217 k
= read_stripped_line(f
, LONG_LINE_MAX
, &line
);
4219 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
4225 if (IN_SET(line
[0], 0, '#'))
4228 k
= parse_line(c
, fn
, v
, line
, &invalid_line
, &uid_cache
, &gid_cache
);
4231 /* Allow reporting with a special code if the caller requested this */
4232 *invalid_config
= true;
4234 /* The first error becomes our return value */
4239 /* we have to determine age parameter for each entry of type X */
4240 ORDERED_HASHMAP_FOREACH(ia
, c
->globs
)
4241 for (size_t ni
= 0; ni
< ia
->n_items
; ni
++) {
4243 Item
*i
= ia
->items
+ ni
, *candidate_item
= NULL
;
4245 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
4248 ORDERED_HASHMAP_FOREACH(ja
, c
->items
)
4249 for (size_t nj
= 0; nj
< ja
->n_items
; nj
++) {
4250 Item
*j
= ja
->items
+ nj
;
4252 if (!IN_SET(j
->type
, CREATE_DIRECTORY
,
4255 CREATE_SUBVOLUME_INHERIT_QUOTA
,
4256 CREATE_SUBVOLUME_NEW_QUOTA
))
4259 if (path_equal(j
->path
, i
->path
)) {
4265 ? (path_startswith(j
->path
, candidate_item
->path
) && fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)
4266 : path_startswith(i
->path
, j
->path
) != NULL
)
4270 if (candidate_item
&& candidate_item
->age_set
) {
4271 i
->age
= candidate_item
->age
;
4277 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
4285 static int parse_arguments(
4289 bool *invalid_config
) {
4294 STRV_FOREACH(arg
, args
) {
4295 r
= read_config_file(c
, config_dirs
, *arg
, false, invalid_config
);
4303 static int read_config_files(
4307 bool *invalid_config
) {
4309 _cleanup_strv_free_
char **files
= NULL
;
4310 _cleanup_free_
char *p
= NULL
;
4315 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
4319 STRV_FOREACH(f
, files
)
4320 if (p
&& path_equal(*f
, p
)) {
4321 log_debug("Parsing arguments at position \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4323 r
= parse_arguments(c
, config_dirs
, args
, invalid_config
);
4327 /* Just warn, ignore result otherwise.
4328 * read_config_file() has some debug output, so no need to print anything. */
4329 (void) read_config_file(c
, config_dirs
, *f
, true, invalid_config
);
4334 static int read_credential_lines(Context
*c
, bool *invalid_config
) {
4336 _cleanup_free_
char *j
= NULL
;
4342 r
= get_credentials_dir(&d
);
4346 return log_error_errno(r
, "Failed to get credentials directory: %m");
4348 j
= path_join(d
, "tmpfiles.extra");
4352 (void) read_config_file(c
, /* config_dirs= */ NULL
, j
, /* ignore_enoent= */ true, invalid_config
);
4356 static int link_parent(Context
*c
, ItemArray
*a
) {
4364 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
4365 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
4366 * before their children, and clean up/remove children before their parents. */
4368 if (a
->n_items
<= 0)
4371 path
= a
->items
[0].path
;
4372 prefix
= newa(char, strlen(path
) + 1);
4373 PATH_FOREACH_PREFIX(prefix
, path
) {
4376 j
= ordered_hashmap_get(c
->items
, prefix
);
4378 j
= ordered_hashmap_get(c
->globs
, prefix
);
4380 r
= set_ensure_put(&j
->children
, NULL
, a
);
4392 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
4393 ItemArray
, item_array_free
);
4395 static int run(int argc
, char *argv
[]) {
4397 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4398 _cleanup_(umount_and_freep
) char *mounted_dir
= NULL
;
4400 _cleanup_strv_free_
char **config_dirs
= NULL
;
4401 _cleanup_(context_done
) Context c
= {};
4402 bool invalid_config
= false;
4405 PHASE_REMOVE_AND_CLEAN
,
4411 r
= parse_argv(argc
, argv
);
4417 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4418 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4419 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4420 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4421 * and output a nice and friendly warning. */
4422 if (proc_mounted() == 0)
4423 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
4424 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4425 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4427 /* Descending down file system trees might take a lot of fds */
4428 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
4430 switch (arg_runtime_scope
) {
4432 case RUNTIME_SCOPE_USER
:
4433 r
= user_config_paths(&config_dirs
);
4435 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
4438 case RUNTIME_SCOPE_SYSTEM
:
4439 config_dirs
= strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
4445 assert_not_reached();
4448 if (DEBUG_LOGGING
) {
4449 _cleanup_free_
char *t
= NULL
;
4451 STRV_FOREACH(i
, config_dirs
) {
4452 _cleanup_free_
char *j
= NULL
;
4454 j
= path_join(arg_root
, *i
);
4458 if (!strextend(&t
, "\n\t", j
))
4462 log_debug("Looking for configuration files in (higher priority first):%s", t
);
4465 if (arg_cat_flags
!= CAT_CONFIG_OFF
)
4466 return cat_config(config_dirs
, argv
+ optind
);
4478 r
= mount_image_privately_interactively(
4481 DISSECT_IMAGE_GENERIC_ROOT
|
4482 DISSECT_IMAGE_REQUIRE_ROOT
|
4483 DISSECT_IMAGE_VALIDATE_OS
|
4484 DISSECT_IMAGE_RELAX_VAR_CHECK
|
4485 DISSECT_IMAGE_FSCK
|
4486 DISSECT_IMAGE_GROWFS
,
4488 /* ret_dir_fd= */ NULL
,
4493 arg_root
= strdup(mounted_dir
);
4501 c
.items
= ordered_hashmap_new(&item_array_hash_ops
);
4502 c
.globs
= ordered_hashmap_new(&item_array_hash_ops
);
4503 if (!c
.items
|| !c
.globs
)
4506 /* If command line arguments are specified along with --replace, read all
4507 * configuration files and insert the positional arguments at the specified
4508 * place. Otherwise, if command line arguments are specified, execute just
4509 * them, and finally, without --replace= or any positional arguments, just
4510 * read configuration and execute it.
4512 if (arg_replace
|| optind
>= argc
)
4513 r
= read_config_files(&c
, config_dirs
, argv
+ optind
, &invalid_config
);
4515 r
= parse_arguments(&c
, config_dirs
, argv
+ optind
, &invalid_config
);
4519 r
= read_credential_lines(&c
, &invalid_config
);
4523 /* Let's now link up all child/parent relationships */
4524 ORDERED_HASHMAP_FOREACH(a
, c
.items
) {
4525 r
= link_parent(&c
, a
);
4529 ORDERED_HASHMAP_FOREACH(a
, c
.globs
) {
4530 r
= link_parent(&c
, a
);
4535 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
4536 * operations. i.e. that we first clean out the platform we then build on. */
4537 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
4540 if (phase
== PHASE_REMOVE_AND_CLEAN
)
4541 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
4542 else if (phase
== PHASE_CREATE
)
4543 op
= arg_operation
& OPERATION_CREATE
;
4545 assert_not_reached();
4547 if (op
== 0) /* Nothing requested in this phase */
4550 /* The non-globbing ones usually create things, hence we apply them first */
4551 ORDERED_HASHMAP_FOREACH(a
, c
.items
) {
4552 k
= process_item_array(&c
, a
, op
);
4553 if (k
< 0 && r
>= 0)
4557 /* The globbing ones usually alter things, hence we apply them second. */
4558 ORDERED_HASHMAP_FOREACH(a
, c
.globs
) {
4559 k
= process_item_array(&c
, a
, op
);
4560 if (k
< 0 && r
>= 0)
4565 if (ERRNO_IS_RESOURCE(r
))
4570 return EX_CANTCREAT
;
4574 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);