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"
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 bool arg_cat_config
= false;
200 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
201 static OperationMask arg_operation
= 0;
202 static bool arg_boot
= false;
203 static PagerFlags arg_pager_flags
= 0;
205 static char **arg_include_prefixes
= NULL
;
206 static char **arg_exclude_prefixes
= NULL
;
207 static char *arg_root
= NULL
;
208 static char *arg_image
= NULL
;
209 static char *arg_replace
= NULL
;
210 static ImagePolicy
*arg_image_policy
= NULL
;
212 #define MAX_DEPTH 256
214 static OrderedHashmap
*items
= NULL
, *globs
= NULL
;
215 static Set
*unix_sockets
= NULL
;
217 STATIC_DESTRUCTOR_REGISTER(items
, ordered_hashmap_freep
);
218 STATIC_DESTRUCTOR_REGISTER(globs
, ordered_hashmap_freep
);
219 STATIC_DESTRUCTOR_REGISTER(unix_sockets
, set_freep
);
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 /* Different kinds of errors that mean that information is not available in the environment. */
235 static inline bool ERRNO_IS_NOINFO(int r
) {
236 return IN_SET(abs(r
),
237 EUNATCH
, /* os-release or machine-id missing */
238 ENOMEDIUM
, /* machine-id or another file empty */
239 ENXIO
); /* env var is unset */
242 static int specifier_directory(char specifier
, const void *data
, const char *root
, const void *userdata
, char **ret
) {
248 static const struct table_entry paths_system
[] = {
249 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
250 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
251 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
252 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
255 static const struct table_entry paths_user
[] = {
256 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
257 [DIRECTORY_STATE
] = { SD_PATH_USER_CONFIGURATION
},
258 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
259 [DIRECTORY_LOGS
] = { SD_PATH_USER_CONFIGURATION
, "log" },
262 const struct table_entry
*paths
;
263 _cleanup_free_
char *p
= NULL
;
267 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
268 paths
= arg_runtime_scope
== RUNTIME_SCOPE_USER
? paths_user
: paths_system
;
270 i
= PTR_TO_UINT(data
);
271 assert(i
< ELEMENTSOF(paths_system
));
273 r
= sd_path_lookup(paths
[i
].type
, paths
[i
].suffix
, &p
);
278 _cleanup_free_
char *j
= NULL
;
280 j
= path_join(arg_root
, p
);
291 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
292 static bool notified
= false;
294 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
295 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
296 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
297 * to LOG_DEBUG for the rest.
299 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
300 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
301 * expectation that machine-id and other files will be populated.
304 int log_level
= notified
|| arg_root
|| running_in_chroot() > 0 ?
305 LOG_DEBUG
: LOG_NOTICE
;
310 "Failed to resolve specifier: %s, skipping.",
311 arg_runtime_scope
== RUNTIME_SCOPE_USER
? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
315 "All rules containing unresolvable specifiers will be skipped.");
321 static int user_config_paths(char*** ret
) {
322 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
323 _cleanup_free_
char *persistent_config
= NULL
, *runtime_config
= NULL
, *data_home
= NULL
;
324 _cleanup_strv_free_
char **res
= NULL
;
327 r
= xdg_user_dirs(&config_dirs
, &data_dirs
);
331 r
= xdg_user_config_dir(&persistent_config
, "/user-tmpfiles.d");
332 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
335 r
= xdg_user_runtime_dir(&runtime_config
, "/user-tmpfiles.d");
336 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
339 r
= xdg_user_data_dir(&data_home
, "/user-tmpfiles.d");
340 if (r
< 0 && !ERRNO_IS_NOINFO(r
))
343 r
= strv_extend_strv_concat(&res
, config_dirs
, "/user-tmpfiles.d");
347 r
= strv_extend(&res
, persistent_config
);
351 r
= strv_extend(&res
, runtime_config
);
355 r
= strv_extend(&res
, data_home
);
359 r
= strv_extend_strv_concat(&res
, data_dirs
, "/user-tmpfiles.d");
363 r
= path_strv_make_absolute_cwd(res
);
367 *ret
= TAKE_PTR(res
);
371 static bool needs_glob(ItemType t
) {
375 IGNORE_DIRECTORY_PATH
,
377 RECURSIVE_REMOVE_PATH
,
381 RECURSIVE_RELABEL_PATH
,
387 RECURSIVE_SET_ATTRIBUTE
);
390 static bool takes_ownership(ItemType t
) {
398 CREATE_SUBVOLUME_INHERIT_QUOTA
,
399 CREATE_SUBVOLUME_NEW_QUOTA
,
407 IGNORE_DIRECTORY_PATH
,
409 RECURSIVE_REMOVE_PATH
);
412 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
415 ORDERED_HASHMAP_FOREACH(j
, h
) {
418 for (n
= 0; n
< j
->n_items
; n
++) {
419 Item
*item
= j
->items
+ n
;
421 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
429 static int load_unix_sockets(void) {
430 _cleanup_set_free_ Set
*sockets
= NULL
;
431 _cleanup_fclose_
FILE *f
= NULL
;
437 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
439 f
= fopen("/proc/net/unix", "re");
441 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
442 "Failed to open /proc/net/unix, ignoring: %m");
445 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
447 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
449 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
452 _cleanup_free_
char *line
= NULL
;
455 r
= read_line(f
, LONG_LINE_MAX
, &line
);
457 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
458 if (r
== 0) /* EOF */
461 p
= strchr(line
, ':');
469 p
+= strspn(p
, WHITESPACE
);
470 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
471 p
+= strspn(p
, WHITESPACE
);
473 if (!path_is_absolute(p
))
476 r
= set_put_strdup_full(&sockets
, &path_hash_ops_free
, p
);
478 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
481 unix_sockets
= TAKE_PTR(sockets
);
485 static bool unix_socket_alive(const char *fn
) {
488 if (load_unix_sockets() < 0)
489 return true; /* We don't know, so assume yes */
491 return set_contains(unix_sockets
, fn
);
494 /* Accessors for the argument in binary format */
495 static const void* item_binary_argument(const Item
*i
) {
497 return i
->binary_argument
?: i
->argument
;
500 static size_t item_binary_argument_size(const Item
*i
) {
502 return i
->binary_argument
? i
->binary_argument_size
: strlen_ptr(i
->argument
);
505 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
508 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
512 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
516 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
518 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
523 static DIR* opendir_nomod(const char *path
) {
524 return xopendirat_nomod(AT_FDCWD
, path
);
527 static inline nsec_t
load_statx_timestamp_nsec(const struct statx_timestamp
*ts
) {
531 return NSEC_INFINITY
;
533 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
534 return NSEC_INFINITY
;
536 return ts
->tv_sec
* NSEC_PER_SEC
+ ts
->tv_nsec
;
539 static bool needs_cleanup(
545 const char *sub_path
,
549 if (FLAGS_SET(age_by
, AGE_BY_MTIME
) && mtime
!= NSEC_INFINITY
&& mtime
>= cutoff
) {
550 /* Follows spelling in stat(1). */
551 log_debug("%s \"%s\": modify time %s is too new.",
552 is_dir
? "Directory" : "File",
554 FORMAT_TIMESTAMP_STYLE(mtime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
559 if (FLAGS_SET(age_by
, AGE_BY_ATIME
) && atime
!= NSEC_INFINITY
&& atime
>= cutoff
) {
560 log_debug("%s \"%s\": access time %s is too new.",
561 is_dir
? "Directory" : "File",
563 FORMAT_TIMESTAMP_STYLE(atime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
569 * Note: Unless explicitly specified by the user, "ctime" is ignored
570 * by default for directories, because we change it when deleting.
572 if (FLAGS_SET(age_by
, AGE_BY_CTIME
) && ctime
!= NSEC_INFINITY
&& ctime
>= cutoff
) {
573 log_debug("%s \"%s\": change time %s is too new.",
574 is_dir
? "Directory" : "File",
576 FORMAT_TIMESTAMP_STYLE(ctime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
581 if (FLAGS_SET(age_by
, AGE_BY_BTIME
) && btime
!= NSEC_INFINITY
&& btime
>= cutoff
) {
582 log_debug("%s \"%s\": birth time %s is too new.",
583 is_dir
? "Directory" : "File",
585 FORMAT_TIMESTAMP_STYLE(btime
/ NSEC_PER_USEC
, TIMESTAMP_US
));
593 static int dir_cleanup(
597 nsec_t self_atime_nsec
,
598 nsec_t self_mtime_nsec
,
604 bool keep_this_level
,
608 bool deleted
= false;
611 FOREACH_DIRENT_ALL(de
, d
, break) {
612 _cleanup_free_
char *sub_path
= NULL
;
613 nsec_t atime_nsec
, mtime_nsec
, ctime_nsec
, btime_nsec
;
615 if (dot_or_dot_dot(de
->d_name
))
618 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
619 * explicitly where we are looking at a mount point, for free as side information. Determining
620 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
621 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
622 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
623 * while on older kernels's well do traditional st_dev based detection of mount points.
625 * Using statx() for detecting mount points also has the benfit that we handle weird file
626 * systems such as overlayfs better where each file is originating from a different
629 STRUCT_STATX_DEFINE(sx
);
632 dirfd(d
), de
->d_name
,
633 AT_SYMLINK_NOFOLLOW
|AT_NO_AUTOMOUNT
,
634 STATX_TYPE
|STATX_MODE
|STATX_UID
|STATX_ATIME
|STATX_MTIME
|STATX_CTIME
|STATX_BTIME
,
639 /* FUSE, NFS mounts, SELinux might return EACCES */
640 r
= log_full_errno(r
== -EACCES
? LOG_DEBUG
: LOG_ERR
, r
,
641 "statx(%s/%s) failed: %m", p
, de
->d_name
);
645 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
)) {
646 /* Yay, we have the mount point API, use it */
647 if (FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
)) {
648 log_debug("Ignoring \"%s/%s\": different mount points.", p
, de
->d_name
);
652 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
653 * back to traditional stx_dev checking. */
654 if (sx
.stx_dev_major
!= rootdev_major
||
655 sx
.stx_dev_minor
!= rootdev_minor
) {
656 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, de
->d_name
);
660 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
661 * major/minors. This type of query is not supported on all kernels or filesystem types
663 if (S_ISDIR(sx
.stx_mode
)) {
666 q
= fd_is_mount_point(dirfd(d
), de
->d_name
, 0);
668 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, de
->d_name
);
670 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, de
->d_name
);
676 atime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_ATIME
) ? load_statx_timestamp_nsec(&sx
.stx_atime
) : 0;
677 mtime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_MTIME
) ? load_statx_timestamp_nsec(&sx
.stx_mtime
) : 0;
678 ctime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_CTIME
) ? load_statx_timestamp_nsec(&sx
.stx_ctime
) : 0;
679 btime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_BTIME
) ? load_statx_timestamp_nsec(&sx
.stx_btime
) : 0;
681 sub_path
= path_join(p
, de
->d_name
);
687 /* Is there an item configured for this path? */
688 if (ordered_hashmap_get(items
, sub_path
)) {
689 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
693 if (find_glob(globs
, sub_path
)) {
694 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
698 if (S_ISDIR(sx
.stx_mode
)) {
699 _cleanup_closedir_
DIR *sub_dir
= NULL
;
702 streq(de
->d_name
, "lost+found") &&
704 log_debug("Ignoring directory \"%s\".", sub_path
);
709 log_warning("Reached max depth on \"%s\".", sub_path
);
713 sub_dir
= xopendirat_nomod(dirfd(d
), de
->d_name
);
716 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
721 if (flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
722 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p
);
728 atime_nsec
, mtime_nsec
, cutoff_nsec
,
729 rootdev_major
, rootdev_minor
,
730 false, maxdepth
-1, false,
731 age_by_file
, age_by_dir
);
736 /* Note: if you are wondering why we don't support the sticky bit for excluding
737 * directories from cleaning like we do it for other file system objects: well, the
738 * sticky bit already has a meaning for directories, so we don't want to overload
741 if (keep_this_level
) {
742 log_debug("Keeping directory \"%s\".", sub_path
);
747 * Check the file timestamps of an entry against the
748 * given cutoff time; delete if it is older.
750 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
751 cutoff_nsec
, sub_path
, age_by_dir
, true))
754 log_debug("Removing directory \"%s\".", sub_path
);
755 if (unlinkat(dirfd(d
), de
->d_name
, AT_REMOVEDIR
) < 0)
756 if (!IN_SET(errno
, ENOENT
, ENOTEMPTY
))
757 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
760 _cleanup_close_
int fd
= -EBADF
;
762 /* Skip files for which the sticky bit is set. These are semantics we define, and are
763 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
764 if (sx
.stx_mode
& S_ISVTX
) {
765 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
770 S_ISREG(sx
.stx_mode
) &&
772 STR_IN_SET(de
->d_name
,
776 log_debug("Skipping \"%s\".", sub_path
);
780 /* Ignore sockets that are listed in /proc/net/unix */
781 if (S_ISSOCK(sx
.stx_mode
) && unix_socket_alive(sub_path
)) {
782 log_debug("Skipping \"%s\": live socket.", sub_path
);
786 /* Ignore device nodes */
787 if (S_ISCHR(sx
.stx_mode
) || S_ISBLK(sx
.stx_mode
)) {
788 log_debug("Skipping \"%s\": a device.", sub_path
);
792 /* Keep files on this level around if this is requested */
793 if (keep_this_level
) {
794 log_debug("Keeping \"%s\".", sub_path
);
798 if (!needs_cleanup(atime_nsec
, btime_nsec
, ctime_nsec
, mtime_nsec
,
799 cutoff_nsec
, sub_path
, age_by_file
, false))
802 fd
= xopenat(dirfd(d
), de
->d_name
, O_RDONLY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
, 0);
803 if (fd
< 0 && fd
!= -ENOENT
)
804 log_warning_errno(fd
, "Opening file \"%s\" failed, ignoring: %m", sub_path
);
805 if (fd
>= 0 && flock(fd
, LOCK_EX
|LOCK_NB
) < 0 && errno
== EAGAIN
) {
806 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", p
);
810 log_debug("Removing \"%s\".", sub_path
);
811 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
813 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
821 struct timespec ts
[2];
823 log_debug("Restoring access and modification time on \"%s\": %s, %s",
825 FORMAT_TIMESTAMP_STYLE(self_atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
),
826 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
828 timespec_store_nsec(ts
+ 0, self_atime_nsec
);
829 timespec_store_nsec(ts
+ 1, self_mtime_nsec
);
831 /* Restore original directory timestamps */
832 if (futimens(dirfd(d
), ts
) < 0)
833 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
839 static bool dangerous_hardlinks(void) {
840 _cleanup_free_
char *value
= NULL
;
841 static int cached
= -1;
844 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
845 * what the upstream default is. */
850 r
= read_one_line_file("/proc/sys/fs/protected_hardlinks", &value
);
852 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl: %m");
856 r
= parse_boolean(value
);
858 log_debug_errno(r
, "Failed to parse fs.protected_hardlinks sysctl: %m");
866 static bool hardlink_vulnerable(const struct stat
*st
) {
869 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && dangerous_hardlinks();
872 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
874 if ((current
& 0111) == 0)
876 if ((current
& 0222) == 0)
878 if ((current
& 0444) == 0)
880 if (!S_ISDIR(current
))
881 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
886 static int fd_set_perms(
890 const struct stat
*st
,
891 CreationMode creation
) {
893 bool do_chown
, do_chmod
;
904 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
908 if (fstat(fd
, &stbuf
) < 0)
909 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
913 if (hardlink_vulnerable(st
))
914 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
915 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
917 new_uid
= i
->uid_set
&& (creation
!= CREATION_EXISTING
|| !i
->uid_only_create
) ? i
->uid
: st
->st_uid
;
918 new_gid
= i
->gid_set
&& (creation
!= CREATION_EXISTING
|| !i
->gid_only_create
) ? i
->gid
: st
->st_gid
;
920 /* Do we need a chown()? */
921 do_chown
= (new_uid
!= st
->st_uid
) || (new_gid
!= st
->st_gid
);
923 /* Calculate the mode to apply */
924 new_mode
= i
->mode_set
&& (creation
!= CREATION_EXISTING
|| !i
->mode_only_create
) ?
925 (i
->mask_perms
? process_mask_perms(i
->mode
, st
->st_mode
) : i
->mode
) :
926 (st
->st_mode
& 07777);
928 do_chmod
= ((new_mode
^ st
->st_mode
) & 07777) != 0;
930 if (do_chmod
&& do_chown
) {
931 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
932 * the new mode. That way there's no time window where the file exists under the old owner
933 * with more than the old access modes — and not under the new owner with more than the new
934 * access modes either. */
936 if (S_ISLNK(st
->st_mode
))
937 log_debug("Skipping temporary mode fix for symlink %s.", path
);
939 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
941 if (((m
^ st
->st_mode
) & 07777) == 0)
942 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
944 log_debug("Temporarily changing \"%s\" to mode %o.", path
, m
);
945 r
= fchmod_opath(fd
, m
);
947 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
953 log_debug("Changing \"%s\" to owner "UID_FMT
":"GID_FMT
, path
, new_uid
, new_gid
);
956 new_uid
!= st
->st_uid
? new_uid
: UID_INVALID
,
957 new_gid
!= st
->st_gid
? new_gid
: GID_INVALID
,
959 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
962 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
963 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
964 if (do_chmod
|| do_chown
) {
965 if (S_ISLNK(st
->st_mode
))
966 log_debug("Skipping mode fix for symlink %s.", path
);
968 log_debug("Changing \"%s\" to mode %o.", path
, new_mode
);
969 r
= fchmod_opath(fd
, new_mode
);
971 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
976 return label_fix_full(fd
, /* inode_path= */ NULL
, /* label_path= */ path
, 0);
979 static int path_open_parent_safe(const char *path
, bool allow_failure
) {
980 _cleanup_free_
char *dn
= NULL
;
983 if (!path_is_normalized(path
))
984 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
985 SYNTHETIC_ERRNO(EINVAL
),
986 "Failed to open parent of '%s': path not normalized%s.",
988 allow_failure
? ", ignoring" : "");
990 r
= path_extract_directory(path
, &dn
);
992 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
994 "Unable to determine parent directory of '%s'%s: %m",
996 allow_failure
? ", ignoring" : "");
998 r
= chase(dn
, arg_root
, allow_failure
? CHASE_SAFE
: CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
999 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
1002 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1004 "Failed to open path '%s'%s: %m",
1006 allow_failure
? ", ignoring" : "");
1011 static int path_open_safe(const char *path
) {
1014 /* path_open_safe() returns a file descriptor opened with O_PATH after
1015 * verifying that the path doesn't contain unsafe transitions, except
1016 * for its final component as the function does not follow symlink. */
1020 if (!path_is_normalized(path
))
1021 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to open invalid path '%s'.", path
);
1023 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
1025 return r
; /* Unsafe symlink: already covered by CHASE_WARN */
1027 return log_error_errno(r
, "Failed to open path %s: %m", path
);
1032 static int path_set_perms(
1035 CreationMode creation
) {
1037 _cleanup_close_
int fd
= -EBADF
;
1042 fd
= path_open_safe(path
);
1046 return fd_set_perms(i
, fd
, path
, /* st= */ NULL
, creation
);
1049 static int parse_xattrs_from_arg(Item
*i
) {
1055 assert_se(p
= i
->argument
);
1057 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
1059 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
1061 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
1065 r
= split_pair(xattr
, "=", &name
, &value
);
1067 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
1071 if (isempty(name
) || isempty(value
)) {
1072 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
1076 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
1079 name
= value
= NULL
;
1085 static int fd_set_xattrs(
1089 const struct stat
*st
,
1090 CreationMode creation
) {
1096 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
1097 log_debug("Setting extended attribute '%s=%s' on %s.", *name
, *value
, path
);
1098 if (setxattr(FORMAT_PROC_FD_PATH(fd
), *name
, *value
, strlen(*value
), 0) < 0)
1099 return log_error_errno(errno
, "Setting extended attribute %s=%s on %s failed: %m",
1100 *name
, *value
, path
);
1105 static int path_set_xattrs(
1108 CreationMode creation
) {
1110 _cleanup_close_
int fd
= -EBADF
;
1115 fd
= path_open_safe(path
);
1119 return fd_set_xattrs(i
, fd
, path
, /* st = */ NULL
, creation
);
1122 static int parse_acls_from_arg(Item
*item
) {
1128 /* If append_or_force (= modify) is set, we will not modify the acl
1129 * afterwards, so the mask can be added now if necessary. */
1131 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_access_exec
,
1132 &item
->acl_default
, !item
->append_or_force
);
1134 log_warning_errno(r
, "Failed to parse ACL \"%s\", ignoring: %m", item
->argument
);
1136 log_warning("ACLs are not supported, ignoring.");
1143 static int parse_acl_cond_exec(
1145 acl_t access
, /* could be empty (NULL) */
1147 const struct stat
*st
,
1151 _cleanup_(acl_freep
) acl_t parsed
= NULL
;
1153 acl_permset_t permset
;
1161 parsed
= access
? acl_dup(access
) : acl_init(0);
1165 /* Since we substitute 'X' with 'x' in parse_acl(), we just need to copy the entries over
1166 * for directories */
1167 if (S_ISDIR(st
->st_mode
)) {
1168 for (r
= acl_get_entry(cond_exec
, ACL_FIRST_ENTRY
, &entry
);
1170 r
= acl_get_entry(cond_exec
, ACL_NEXT_ENTRY
, &entry
)) {
1172 acl_entry_t parsed_entry
;
1174 if (acl_create_entry(&parsed
, &parsed_entry
) < 0)
1177 if (acl_copy_entry(parsed_entry
, entry
) < 0)
1186 has_exec
= st
->st_mode
& S_IXUSR
;
1188 if (!has_exec
&& append
) {
1189 _cleanup_(acl_freep
) acl_t old
= NULL
;
1191 old
= acl_get_file(path
, ACL_TYPE_ACCESS
);
1195 for (r
= acl_get_entry(old
, ACL_FIRST_ENTRY
, &entry
);
1197 r
= acl_get_entry(old
, ACL_NEXT_ENTRY
, &entry
)) {
1199 if (acl_get_permset(entry
, &permset
) < 0)
1202 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1214 /* Check if we're about to set the execute bit in acl_access */
1215 if (!has_exec
&& access
) {
1216 for (r
= acl_get_entry(access
, ACL_FIRST_ENTRY
, &entry
);
1218 r
= acl_get_entry(access
, ACL_NEXT_ENTRY
, &entry
)) {
1220 if (acl_get_permset(entry
, &permset
) < 0)
1223 r
= acl_get_perm(permset
, ACL_EXECUTE
);
1235 for (r
= acl_get_entry(cond_exec
, ACL_FIRST_ENTRY
, &entry
);
1237 r
= acl_get_entry(cond_exec
, ACL_NEXT_ENTRY
, &entry
)) {
1239 acl_entry_t parsed_entry
;
1241 if (acl_create_entry(&parsed
, &parsed_entry
) < 0)
1244 if (acl_copy_entry(parsed_entry
, entry
) < 0)
1248 if (acl_get_permset(parsed_entry
, &permset
) < 0)
1251 if (acl_delete_perm(permset
, ACL_EXECUTE
) < 0)
1259 if (!append
) { /* want_mask = true */
1260 r
= calc_acl_mask_if_needed(&parsed
);
1265 *ret
= TAKE_PTR(parsed
);
1270 static int path_set_acl(
1277 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1278 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1281 /* Returns 0 for success, positive error if already warned,
1282 * negative error otherwise. */
1285 r
= acls_for_file(path
, type
, acl
, &dup
);
1289 r
= calc_acl_mask_if_needed(&dup
);
1297 /* the mask was already added earlier if needed */
1300 r
= add_base_acls_if_needed(&dup
, path
);
1304 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1305 log_debug("Setting %s ACL %s on %s.",
1306 type
== ACL_TYPE_ACCESS
? "access" : "default",
1309 r
= acl_set_file(path
, type
, dup
);
1311 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1312 /* No error if filesystem doesn't support ACLs. Return negative. */
1315 /* Return positive to indicate we already warned */
1316 return -log_error_errno(errno
,
1317 "Setting %s ACL \"%s\" on %s failed: %m",
1318 type
== ACL_TYPE_ACCESS
? "access" : "default",
1325 static int fd_set_acls(
1329 const struct stat
*st
,
1330 CreationMode creation
) {
1334 _cleanup_(acl_freep
) acl_t access_with_exec_parsed
= NULL
;
1342 if (fstat(fd
, &stbuf
) < 0)
1343 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1347 if (hardlink_vulnerable(st
))
1348 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1349 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1352 if (S_ISLNK(st
->st_mode
)) {
1353 log_debug("Skipping ACL fix for symlink %s.", path
);
1357 if (item
->acl_access_exec
) {
1358 r
= parse_acl_cond_exec(FORMAT_PROC_FD_PATH(fd
),
1360 item
->acl_access_exec
,
1362 item
->append_or_force
,
1363 &access_with_exec_parsed
);
1365 return log_error_errno(r
, "Failed to parse conditionalized execute bit for \"%s\": %m", path
);
1367 r
= path_set_acl(FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, access_with_exec_parsed
, item
->append_or_force
);
1368 } else if (item
->acl_access
)
1369 r
= path_set_acl(FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1371 /* set only default acls to folders */
1372 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1373 r
= path_set_acl(FORMAT_PROC_FD_PATH(fd
), path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1375 if (ERRNO_IS_NOT_SUPPORTED(r
)) {
1376 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1381 return -r
; /* already warned in path_set_acl */
1383 /* The above procfs paths don't work if /proc is not mounted. */
1384 if (r
== -ENOENT
&& proc_mounted() == 0)
1388 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1393 static int path_set_acls(Item
*item
, const char *path
, CreationMode creation
) {
1396 _cleanup_close_
int fd
= -EBADF
;
1401 fd
= path_open_safe(path
);
1405 r
= fd_set_acls(item
, fd
, path
, /* st= */ NULL
, creation
);
1410 static int parse_attribute_from_arg(Item
*item
) {
1412 static const struct {
1416 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1417 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1418 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1419 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1420 { 'c', FS_COMPR_FL
}, /* Compress file */
1421 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1422 { 'e', FS_EXTENT_FL
}, /* Extents */
1423 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1424 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1425 { 's', FS_SECRM_FL
}, /* Secure deletion */
1426 { 'u', FS_UNRM_FL
}, /* Undelete */
1427 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1428 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1429 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1430 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1439 unsigned value
= 0, mask
= 0;
1449 } else if (*p
== '-') {
1452 } else if (*p
== '=') {
1458 if (isempty(p
) && mode
!= MODE_SET
)
1459 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1460 "Setting file attribute on '%s' needs an attribute specification.",
1463 for (; p
&& *p
; p
++) {
1466 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1467 if (*p
== attributes
[i
].character
)
1470 if (i
>= ELEMENTSOF(attributes
))
1471 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1472 "Unknown file attribute '%c' on '%s'.",
1475 v
= attributes
[i
].value
;
1477 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1482 if (mode
== MODE_SET
)
1483 mask
|= CHATTR_ALL_FL
;
1487 item
->attribute_mask
= mask
;
1488 item
->attribute_value
= value
;
1489 item
->attribute_set
= true;
1494 static int fd_set_attribute(
1498 const struct stat
*st
,
1499 CreationMode creation
) {
1501 _cleanup_close_
int procfs_fd
= -EBADF
;
1510 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1514 if (fstat(fd
, &stbuf
) < 0)
1515 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1519 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1520 * drivers, not the file system containing the device node. */
1521 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1522 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1523 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1526 f
= item
->attribute_value
& item
->attribute_mask
;
1528 /* Mask away directory-specific flags */
1529 if (!S_ISDIR(st
->st_mode
))
1530 f
&= ~FS_DIRSYNC_FL
;
1532 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1534 return log_error_errno(procfs_fd
, "Failed to re-open '%s': %m", path
);
1536 unsigned previous
, current
;
1537 r
= chattr_full(NULL
, procfs_fd
, f
, item
->attribute_mask
, &previous
, ¤t
, CHATTR_FALLBACK_BITWISE
);
1539 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1540 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1541 path
, previous
, current
, (previous
& ~item
->attribute_mask
) | (f
& item
->attribute_mask
));
1543 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1544 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1545 path
, item
->attribute_value
, item
->attribute_mask
);
1550 static int path_set_attribute(Item
*item
, const char *path
, CreationMode creation
) {
1551 _cleanup_close_
int fd
= -EBADF
;
1553 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1556 fd
= path_open_safe(path
);
1560 return fd_set_attribute(item
, fd
, path
, /* st= */ NULL
, creation
);
1563 static int write_argument_data(Item
*i
, int fd
, const char *path
) {
1570 if (item_binary_argument_size(i
) == 0)
1573 assert(item_binary_argument(i
));
1575 log_debug("Writing to \"%s\".", path
);
1577 r
= loop_write(fd
, item_binary_argument(i
), item_binary_argument_size(i
), /* do_poll= */ false);
1579 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1584 static int write_one_file(Item
*i
, const char *path
, CreationMode creation
) {
1585 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1586 _cleanup_free_
char *bn
= NULL
;
1591 assert(i
->type
== WRITE_FILE
);
1593 r
= path_extract_filename(path
, &bn
);
1595 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1596 if (r
== O_DIRECTORY
)
1597 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1599 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1600 * can't be changed behind our back. */
1601 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1605 /* Follows symlinks */
1606 fd
= openat(dir_fd
, bn
,
1607 O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
|(i
->append_or_force
? O_APPEND
: 0),
1610 if (errno
== ENOENT
) {
1611 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1615 if (i
->allow_failure
)
1616 return log_debug_errno(errno
, "Failed to open file \"%s\", ignoring: %m", path
);
1618 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1621 /* 'w' is allowed to write into any kind of files. */
1623 r
= write_argument_data(i
, fd
, path
);
1627 return fd_set_perms(i
, fd
, path
, NULL
, creation
);
1630 static int create_file(Item
*i
, const char *path
) {
1631 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1632 _cleanup_free_
char *bn
= NULL
;
1633 struct stat stbuf
, *st
= NULL
;
1634 CreationMode creation
;
1639 assert(i
->type
== CREATE_FILE
);
1641 /* 'f' operates on regular files exclusively. */
1643 r
= path_extract_filename(path
, &bn
);
1645 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1646 if (r
== O_DIRECTORY
)
1647 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for writing, is a directory.", path
);
1649 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1650 * can't be changed behind our back. */
1651 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1656 mac_selinux_create_file_prepare(path
, S_IFREG
);
1657 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1658 mac_selinux_create_file_clear();
1662 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1663 * returns EROFS only if it needs to create the file. */
1665 return log_error_errno(fd
, "Failed to create file %s: %m", path
);
1667 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1668 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1669 * fd_set_perms() report the error if the perms need to be modified. */
1670 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1672 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1674 if (fstat(fd
, &stbuf
) < 0)
1675 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1677 if (!S_ISREG(stbuf
.st_mode
))
1678 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1679 "%s exists and is not a regular file.",
1683 creation
= CREATION_EXISTING
;
1685 r
= write_argument_data(i
, fd
, path
);
1689 creation
= CREATION_NORMAL
;
1692 return fd_set_perms(i
, fd
, path
, st
, creation
);
1695 static int truncate_file(Item
*i
, const char *path
) {
1696 _cleanup_close_
int fd
= -EBADF
, dir_fd
= -EBADF
;
1697 _cleanup_free_
char *bn
= NULL
;
1698 struct stat stbuf
, *st
= NULL
;
1699 CreationMode creation
;
1705 assert(i
->type
== TRUNCATE_FILE
|| (i
->type
== CREATE_FILE
&& i
->append_or_force
));
1707 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1708 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1709 * make sure it's a regular one before truncating it. */
1711 r
= path_extract_filename(path
, &bn
);
1713 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1714 if (r
== O_DIRECTORY
)
1715 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for truncation, is a directory.", path
);
1717 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1718 * can't be changed behind our back. */
1719 dir_fd
= path_open_parent_safe(path
, i
->allow_failure
);
1723 creation
= CREATION_EXISTING
;
1724 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1725 if (fd
== -ENOENT
) {
1726 creation
= CREATION_NORMAL
; /* Didn't work without O_CREATE, try again with */
1729 mac_selinux_create_file_prepare(path
, S_IFREG
);
1730 fd
= RET_NERRNO(openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
));
1731 mac_selinux_create_file_clear();
1737 return log_error_errno(fd
, "Failed to open/create file %s: %m", path
);
1739 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1740 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1741 * fail with EROFS if they try to modify the target file. */
1743 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1745 if (errno
== ENOENT
)
1746 return log_error_errno(SYNTHETIC_ERRNO(EROFS
),
1747 "Cannot create file %s on a read-only file system.",
1750 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1754 creation
= CREATION_EXISTING
;
1757 if (fstat(fd
, &stbuf
) < 0)
1758 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1760 if (!S_ISREG(stbuf
.st_mode
))
1761 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1762 "%s exists and is not a regular file.",
1765 if (stbuf
.st_size
> 0) {
1766 if (ftruncate(fd
, 0) < 0) {
1767 r
= erofs
? -EROFS
: -errno
;
1768 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1773 log_debug("\"%s\" has been created.", path
);
1775 if (item_binary_argument(i
)) {
1776 r
= write_argument_data(i
, fd
, path
);
1781 return fd_set_perms(i
, fd
, path
, st
, creation
);
1784 static int copy_files(Item
*i
) {
1785 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
1786 _cleanup_free_
char *bn
= NULL
;
1790 log_debug("Copying tree \"%s\" to \"%s\".", i
->argument
, i
->path
);
1792 r
= path_extract_filename(i
->path
, &bn
);
1794 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
1796 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1797 * path can't be changed behind our back. */
1798 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
1802 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1804 i
->uid_set
? i
->uid
: UID_INVALID
,
1805 i
->gid_set
? i
->gid
: GID_INVALID
,
1806 COPY_REFLINK
| COPY_MERGE_EMPTY
| COPY_MAC_CREATE
| COPY_HARDLINKS
,
1809 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1811 if (r
< 0) /* Look at original error first */
1812 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1814 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1817 if (fstat(fd
, &st
) < 0)
1818 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
1820 if (stat(i
->argument
, &a
) < 0)
1821 return log_error_errno(errno
, "Failed to stat(%s): %m", i
->argument
);
1823 if (((st
.st_mode
^ a
.st_mode
) & S_IFMT
) != 0) {
1824 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1828 return fd_set_perms(i
, fd
, i
->path
, &st
, _CREATION_MODE_INVALID
);
1831 static int create_directory_or_subvolume(
1836 struct stat
*ret_st
,
1837 CreationMode
*ret_creation
) {
1839 _cleanup_free_
char *bn
= NULL
;
1840 _cleanup_close_
int pfd
= -EBADF
;
1841 CreationMode creation
;
1847 r
= path_extract_filename(path
, &bn
);
1849 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", path
);
1851 pfd
= path_open_parent_safe(path
, allow_failure
);
1856 r
= getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1858 if (r
!= -ENXIO
) /* env var is unset */
1859 log_warning_errno(r
, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1860 r
= btrfs_is_subvol(empty_to_root(arg_root
)) > 0;
1863 /* Don't create a subvolume unless the root directory is one, too. We do this under
1864 * the assumption that if the root directory is just a plain directory (i.e. very
1865 * light-weight), we shouldn't try to split it up into subvolumes (i.e. more
1866 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1867 * subvolume set up below their tree only if they specifically set up a btrfs
1868 * subvolume for the root dir too. */
1872 WITH_UMASK((~mode
) & 0777)
1873 r
= btrfs_subvol_make_fd(pfd
, bn
);
1878 if (!subvol
|| ERRNO_IS_NOT_SUPPORTED(r
))
1880 r
= mkdirat_label(pfd
, bn
, mode
);
1882 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
1884 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_DIRECTORY
|O_PATH
);
1886 /* We couldn't open it because it is not actually a directory? */
1887 if (errno
== ENOTDIR
)
1888 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
), "\"%s\" already exists and is not a directory.", path
);
1890 /* Then look at the original error */
1892 return log_full_errno(allow_failure
? LOG_INFO
: LOG_ERR
,
1894 "Failed to create directory or subvolume \"%s\"%s: %m",
1896 allow_failure
? ", ignoring" : "");
1898 return log_error_errno(errno
, "Failed to open directory/subvolume we just created '%s': %m", path
);
1901 if (fstat(fd
, &st
) < 0)
1902 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
1904 assert(S_ISDIR(st
.st_mode
)); /* we used O_DIRECTORY above */
1906 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation
), path
);
1911 *ret_creation
= creation
;
1916 static int create_directory(Item
*i
, const char *path
) {
1917 _cleanup_close_
int fd
= -EBADF
;
1918 CreationMode creation
;
1922 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
1924 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol= */ false, i
->allow_failure
, &st
, &creation
);
1930 return fd_set_perms(i
, fd
, path
, &st
, creation
);
1933 static int create_subvolume(Item
*i
, const char *path
) {
1934 _cleanup_close_
int fd
= -EBADF
;
1935 CreationMode creation
;
1940 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
1942 fd
= create_directory_or_subvolume(path
, i
->mode
, /* subvol = */ true, i
->allow_failure
, &st
, &creation
);
1948 if (creation
== CREATION_NORMAL
&&
1949 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
1950 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
1952 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
1953 else if (r
== -EROFS
)
1954 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
1955 else if (r
== -ENOTCONN
)
1956 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
1958 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
1960 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
1962 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
1965 r
= fd_set_perms(i
, fd
, path
, &st
, creation
);
1966 if (q
< 0) /* prefer the quota change error from above */
1972 static int empty_directory(Item
*i
, const char *path
, CreationMode creation
) {
1973 _cleanup_close_
int fd
= -EBADF
;
1978 assert(i
->type
== EMPTY_DIRECTORY
);
1980 r
= chase(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
1981 if (r
== -ENOLINK
) /* Unsafe symlink: already covered by CHASE_WARN */
1984 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
1986 log_debug_errno(r
, "Skipping missing directory: %s", path
);
1990 return log_error_errno(r
, "Failed to open directory '%s': %m", path
);
1992 if (fstat(fd
, &st
) < 0)
1993 return log_error_errno(errno
, "Failed to fstat(%s): %m", path
);
1994 if (!S_ISDIR(st
.st_mode
)) {
1995 log_warning("'%s' already exists and is not a directory.", path
);
1999 return fd_set_perms(i
, fd
, path
, &st
, creation
);
2002 static int create_device(Item
*i
, mode_t file_type
) {
2003 _cleanup_close_
int dfd
= -EBADF
, fd
= -EBADF
;
2004 _cleanup_free_
char *bn
= NULL
;
2005 CreationMode creation
;
2010 assert(IN_SET(i
->type
, CREATE_BLOCK_DEVICE
, CREATE_CHAR_DEVICE
));
2011 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
2013 r
= path_extract_filename(i
->path
, &bn
);
2015 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2016 if (r
== O_DIRECTORY
)
2017 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating device node, is a directory.", i
->path
);
2019 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
2020 * path can't be changed behind our back. */
2021 dfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2026 mac_selinux_create_file_prepare(i
->path
, file_type
);
2027 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2028 mac_selinux_create_file_clear();
2030 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2032 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
2033 * order anyway and we hence can ignore the error to create the device node */
2034 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2036 /* OK, so opening the inode failed, let's look at the original error then. */
2039 if (ERRNO_IS_PRIVILEGE(r
))
2040 goto handle_privilege
;
2042 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2045 return log_error_errno(errno
, "Failed to open device node '%s' we just created: %m", i
->path
);
2048 if (fstat(fd
, &st
) < 0)
2049 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2051 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0) {
2053 if (i
->append_or_force
) {
2054 fd
= safe_close(fd
);
2057 mac_selinux_create_file_prepare(i
->path
, file_type
);
2058 r
= mknodat_atomic(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
2059 mac_selinux_create_file_clear();
2061 if (ERRNO_IS_PRIVILEGE(r
))
2062 goto handle_privilege
;
2063 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2064 r
= rm_rf_child(dfd
, bn
, REMOVE_PHYSICAL
);
2066 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2068 mac_selinux_create_file_prepare(i
->path
, file_type
);
2069 r
= RET_NERRNO(mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
));
2070 mac_selinux_create_file_clear();
2073 return log_error_errno(r
, "Failed to create device node '%s': %m", i
->path
);
2075 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2077 return log_error_errno(errno
, "Failed to open device node we just created '%s': %m", i
->path
);
2079 /* Validate type before change ownership below */
2080 if (fstat(fd
, &st
) < 0)
2081 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2083 if (((st
.st_mode
^ file_type
) & S_IFMT
) != 0)
2084 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Device node we just created is not a device node, refusing.");
2086 creation
= CREATION_FORCE
;
2088 log_warning("\"%s\" already exists and is not a device node.", i
->path
);
2093 log_debug("%s %s device node \"%s\" %u:%u.",
2094 creation_mode_verb_to_string(creation
),
2095 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
2096 i
->path
, major(i
->mode
), minor(i
->mode
));
2098 return fd_set_perms(i
, fd
, i
->path
, &st
, creation
);
2102 "We lack permissions, possibly because of cgroup configuration; "
2103 "skipping creation of device node '%s'.", i
->path
);
2107 static int create_fifo(Item
*i
) {
2108 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2109 _cleanup_free_
char *bn
= NULL
;
2110 CreationMode creation
;
2115 assert(i
->type
== CREATE_FIFO
);
2117 r
= path_extract_filename(i
->path
, &bn
);
2119 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2120 if (r
== O_DIRECTORY
)
2121 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating FIFO, is a directory.", i
->path
);
2123 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2128 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2129 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2130 mac_selinux_create_file_clear();
2133 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2135 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
2136 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2139 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
); /* original error! */
2141 return log_error_errno(errno
, "Failed to open FIFO we just created %s: %m", i
->path
);
2144 if (fstat(fd
, &st
) < 0)
2145 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2147 if (!S_ISFIFO(st
.st_mode
)) {
2149 if (i
->append_or_force
) {
2150 fd
= safe_close(fd
);
2153 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2154 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
2155 mac_selinux_create_file_clear();
2157 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2158 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2160 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2162 mac_selinux_create_file_prepare(i
->path
, S_IFIFO
);
2163 r
= RET_NERRNO(mkfifoat(pfd
, bn
, i
->mode
));
2164 mac_selinux_create_file_clear();
2167 return log_error_errno(r
, "Failed to create FIFO %s: %m", i
->path
);
2169 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2171 return log_error_errno(errno
, "Failed to open FIFO we just created '%s': %m", i
->path
);
2173 /* Validate type before change ownership below */
2174 if (fstat(fd
, &st
) < 0)
2175 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2177 if (!S_ISFIFO(st
.st_mode
))
2178 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "FIFO inode we just created is not a FIFO, refusing.");
2180 creation
= CREATION_FORCE
;
2182 log_warning("\"%s\" already exists and is not a FIFO.", i
->path
);
2187 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2189 return fd_set_perms(i
, fd
, i
->path
, &st
, creation
);
2192 static int create_symlink(Item
*i
) {
2193 _cleanup_close_
int pfd
= -EBADF
, fd
= -EBADF
;
2194 _cleanup_free_
char *bn
= NULL
;
2195 CreationMode creation
;
2202 r
= path_extract_filename(i
->path
, &bn
);
2204 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", i
->path
);
2205 if (r
== O_DIRECTORY
)
2206 return log_error_errno(SYNTHETIC_ERRNO(EISDIR
), "Cannot open path '%s' for creating FIFO, is a directory.", i
->path
);
2208 pfd
= path_open_parent_safe(i
->path
, i
->allow_failure
);
2212 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2213 r
= RET_NERRNO(symlinkat(i
->argument
, pfd
, bn
));
2214 mac_selinux_create_file_clear();
2216 creation
= r
>= 0 ? CREATION_NORMAL
: CREATION_EXISTING
;
2218 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2221 return log_error_errno(r
, "Failed to create symlink '%s': %m", i
->path
); /* original error! */
2223 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2226 if (fstat(fd
, &st
) < 0)
2227 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2229 if (S_ISLNK(st
.st_mode
)) {
2230 _cleanup_free_
char *x
= NULL
;
2232 r
= readlinkat_malloc(fd
, "", &x
);
2234 return log_error_errno(r
, "readlinkat(%s) failed: %m", i
->path
);
2236 good
= streq(x
, i
->argument
);
2241 if (!i
->append_or_force
) {
2242 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2246 fd
= safe_close(fd
);
2248 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2249 r
= symlinkat_atomic_full(i
->argument
, pfd
, bn
, /* make_relative= */ false);
2250 mac_selinux_create_file_clear();
2251 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2252 r
= rm_rf_child(pfd
, bn
, REMOVE_PHYSICAL
);
2254 return log_error_errno(r
, "rm -rf %s failed: %m", i
->path
);
2256 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2257 r
= RET_NERRNO(symlinkat(i
->argument
, pfd
, i
->path
));
2258 mac_selinux_create_file_clear();
2261 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2263 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2265 return log_error_errno(errno
, "Failed to open symlink we just created '%s': %m", i
->path
);
2267 /* Validate type before change ownership below */
2268 if (fstat(fd
, &st
) < 0)
2269 return log_error_errno(errno
, "Failed to fstat(%s): %m", i
->path
);
2271 if (!S_ISLNK(st
.st_mode
))
2272 return log_error_errno(SYNTHETIC_ERRNO(EBADF
), "Symlink we just created is not a symlink, refusing.");
2274 creation
= CREATION_FORCE
;
2277 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2278 return fd_set_perms(i
, fd
, i
->path
, &st
, creation
);
2281 typedef int (*action_t
)(Item
*i
, const char *path
, CreationMode creation
);
2282 typedef int (*fdaction_t
)(Item
*i
, int fd
, const char *path
, const struct stat
*st
, CreationMode creation
);
2288 CreationMode creation
,
2289 fdaction_t action
) {
2298 if (fstat(fd
, &st
) < 0) {
2299 r
= log_error_errno(errno
, "fstat() on file failed: %m");
2303 /* This returns the first error we run into, but nevertheless tries to go on */
2304 r
= action(i
, fd
, path
, &st
, creation
);
2306 if (S_ISDIR(st
.st_mode
)) {
2307 _cleanup_closedir_
DIR *d
= NULL
;
2309 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2310 * reading the directory content. */
2311 d
= opendir(FORMAT_PROC_FD_PATH(fd
));
2313 log_error_errno(errno
, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd
));
2319 FOREACH_DIRENT_ALL(de
, d
, q
= -errno
; goto finish
) {
2322 if (dot_or_dot_dot(de
->d_name
))
2325 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
2327 q
= log_error_errno(errno
, "Failed to open() file '%s': %m", de
->d_name
);
2329 _cleanup_free_
char *de_path
= NULL
;
2331 de_path
= path_join(path
, de
->d_name
);
2335 /* Pass ownership of dirent fd over */
2336 q
= item_do(i
, de_fd
, de_path
, CREATION_EXISTING
, action
);
2339 if (q
< 0 && r
== 0)
2348 static int glob_item(Item
*i
, action_t action
) {
2349 _cleanup_globfree_ glob_t g
= {
2350 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
2354 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
2355 if (k
< 0 && k
!= -ENOENT
)
2356 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
2358 STRV_FOREACH(fn
, g
.gl_pathv
) {
2359 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2360 k
= action(i
, *fn
, CREATION_EXISTING
);
2361 if (k
< 0 && r
== 0)
2368 static int glob_item_recursively(Item
*i
, fdaction_t action
) {
2369 _cleanup_globfree_ glob_t g
= {
2370 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
2374 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
2375 if (k
< 0 && k
!= -ENOENT
)
2376 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
2378 STRV_FOREACH(fn
, g
.gl_pathv
) {
2379 _cleanup_close_
int fd
= -EBADF
;
2381 /* Make sure we won't trigger/follow file object (such as
2382 * device nodes, automounts, ...) pointed out by 'fn' with
2383 * O_PATH. Note, when O_PATH is used, flags other than
2384 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2386 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
2388 log_error_errno(errno
, "Opening '%s' failed: %m", *fn
);
2394 k
= item_do(i
, fd
, *fn
, CREATION_EXISTING
, action
);
2395 if (k
< 0 && r
== 0)
2398 /* we passed fd ownership to the previous call */
2405 static int rm_if_wrong_type_safe(
2408 const struct stat
*parent_st
, /* Only used if follow_links below is true. */
2411 _cleanup_free_
char *parent_name
= NULL
;
2412 bool follow_links
= !FLAGS_SET(flags
, AT_SYMLINK_NOFOLLOW
);
2417 assert((mode
& ~S_IFMT
) == 0);
2418 assert(!follow_links
|| parent_st
);
2419 assert((flags
& ~AT_SYMLINK_NOFOLLOW
) == 0);
2421 if (!filename_is_valid(name
))
2422 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "\"%s\" is not a valid filename.", name
);
2424 r
= fstatat_harder(parent_fd
, name
, &st
, flags
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2426 (void) fd_get_path(parent_fd
, &parent_name
);
2427 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_ERR
, r
,
2428 "Failed to stat \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2431 /* Fail before removing anything if this is an unsafe transition. */
2432 if (follow_links
&& unsafe_transition(parent_st
, &st
)) {
2433 (void) fd_get_path(parent_fd
, &parent_name
);
2434 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK
),
2435 "Unsafe transition from \"%s\" to \"%s\".", parent_name
, name
);
2438 if ((st
.st_mode
& S_IFMT
) == mode
)
2441 (void) fd_get_path(parent_fd
, &parent_name
);
2442 log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st
.st_mode
& S_IFMT
, strna(parent_name
), name
);
2444 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2445 * target, so make sure it is identified as a link and not a directory. */
2447 r
= fstatat_harder(parent_fd
, name
, &st
, AT_SYMLINK_NOFOLLOW
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2449 return log_error_errno(r
, "Failed to stat \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2452 /* Do not remove mount points. */
2453 r
= fd_is_mount_point(parent_fd
, name
, follow_links
? AT_SYMLINK_FOLLOW
: 0);
2455 (void) log_warning_errno(r
, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2456 strna(parent_name
), name
);
2458 return log_error_errno(SYNTHETIC_ERRNO(EBUSY
),
2459 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name
), name
);
2461 if ((st
.st_mode
& S_IFMT
) == S_IFDIR
) {
2462 _cleanup_close_
int child_fd
= -EBADF
;
2464 child_fd
= openat(parent_fd
, name
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2466 return log_error_errno(errno
, "Failed to open \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2468 r
= rm_rf_children(TAKE_FD(child_fd
), REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
, &st
);
2470 return log_error_errno(r
, "Failed to remove contents of \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2472 r
= unlinkat_harder(parent_fd
, name
, AT_REMOVEDIR
, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2474 r
= unlinkat_harder(parent_fd
, name
, 0, REMOVE_CHMOD
| REMOVE_CHMOD_RESTORE
);
2476 return log_error_errno(r
, "Failed to remove \"%s\" at \"%s\": %m", name
, strna(parent_name
));
2478 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2479 * context to other error messages that might follow. */
2483 /* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2484 static int mkdir_parents_rm_if_wrong_type(mode_t child_mode
, const char *path
) {
2485 _cleanup_close_
int parent_fd
= -EBADF
;
2486 struct stat parent_st
;
2491 assert((child_mode
& ~S_IFMT
) == 0);
2493 path_len
= strlen(path
);
2496 /* rm_if_wrong_type_safe already logs errors. */
2497 return child_mode
!= 0 ? rm_if_wrong_type_safe(child_mode
, AT_FDCWD
, NULL
, path
, AT_SYMLINK_NOFOLLOW
) : 0;
2499 if (child_mode
!= 0 && endswith(path
, "/"))
2500 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2501 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path
);
2503 /* Get the parent_fd and stat. */
2504 parent_fd
= openat(AT_FDCWD
, path_is_absolute(path
) ? "/" : ".", O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
);
2506 return log_error_errno(errno
, "Failed to open root: %m");
2508 if (fstat(parent_fd
, &parent_st
) < 0)
2509 return log_error_errno(errno
, "Failed to stat root: %m");
2511 /* Check every parent directory in the path, except the last component */
2512 for (const char *e
= path
;;) {
2513 _cleanup_close_
int next_fd
= -EBADF
;
2514 char t
[path_len
+ 1];
2517 /* Find the start of the next path component. */
2518 s
= e
+ strspn(e
, "/");
2519 /* Find the end of the next path component. */
2520 e
= s
+ strcspn(s
, "/");
2522 /* Copy the path component to t so it can be a null terminated string. */
2523 *((char*) mempcpy(t
, s
, e
- s
)) = 0;
2525 /* Is this the last component? If so, then check the type */
2527 return child_mode
!= 0 ? rm_if_wrong_type_safe(child_mode
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
) : 0;
2529 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, 0);
2530 /* Remove dangling symlinks. */
2532 r
= rm_if_wrong_type_safe(S_IFDIR
, parent_fd
, &parent_st
, t
, AT_SYMLINK_NOFOLLOW
);
2535 r
= mkdirat_label(parent_fd
, t
, 0755);
2537 _cleanup_free_
char *parent_name
= NULL
;
2539 (void) fd_get_path(parent_fd
, &parent_name
);
2540 return log_error_errno(r
, "Failed to mkdir \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2543 /* rm_if_wrong_type_safe already logs errors. */
2546 next_fd
= RET_NERRNO(openat(parent_fd
, t
, O_NOCTTY
| O_CLOEXEC
| O_DIRECTORY
));
2548 _cleanup_free_
char *parent_name
= NULL
;
2550 (void) fd_get_path(parent_fd
, &parent_name
);
2551 return log_error_errno(next_fd
, "Failed to open \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2553 r
= RET_NERRNO(fstat(next_fd
, &parent_st
));
2555 _cleanup_free_
char *parent_name
= NULL
;
2557 (void) fd_get_path(parent_fd
, &parent_name
);
2558 return log_error_errno(r
, "Failed to stat \"%s\" at \"%s\": %m", t
, strnull(parent_name
));
2561 close_and_replace(parent_fd
, next_fd
);
2565 static int mkdir_parents_item(Item
*i
, mode_t child_mode
) {
2567 if (i
->try_replace
) {
2568 r
= mkdir_parents_rm_if_wrong_type(child_mode
, i
->path
);
2569 if (r
< 0 && r
!= -ENOENT
)
2573 (void) mkdir_parents_label(i
->path
, 0755);
2578 static int create_item(Item
*i
) {
2583 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
2588 case IGNORE_DIRECTORY_PATH
:
2590 case RECURSIVE_REMOVE_PATH
:
2595 r
= mkdir_parents_item(i
, S_IFREG
);
2599 if ((i
->type
== CREATE_FILE
&& i
->append_or_force
) || i
->type
== TRUNCATE_FILE
)
2600 r
= truncate_file(i
, i
->path
);
2602 r
= create_file(i
, i
->path
);
2608 r
= mkdir_parents_item(i
, 0);
2618 r
= glob_item(i
, write_one_file
);
2624 case CREATE_DIRECTORY
:
2625 case TRUNCATE_DIRECTORY
:
2626 r
= mkdir_parents_item(i
, S_IFDIR
);
2630 r
= create_directory(i
, i
->path
);
2635 case CREATE_SUBVOLUME
:
2636 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2637 case CREATE_SUBVOLUME_NEW_QUOTA
:
2638 r
= mkdir_parents_item(i
, S_IFDIR
);
2642 r
= create_subvolume(i
, i
->path
);
2647 case EMPTY_DIRECTORY
:
2648 r
= glob_item(i
, empty_directory
);
2654 r
= mkdir_parents_item(i
, S_IFIFO
);
2663 case CREATE_SYMLINK
:
2664 r
= mkdir_parents_item(i
, S_IFLNK
);
2668 r
= create_symlink(i
);
2674 case CREATE_BLOCK_DEVICE
:
2675 case CREATE_CHAR_DEVICE
:
2676 if (have_effective_cap(CAP_MKNOD
) <= 0) {
2677 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2678 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2680 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2684 r
= mkdir_parents_item(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2688 r
= create_device(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2696 r
= glob_item(i
, path_set_perms
);
2701 case RECURSIVE_RELABEL_PATH
:
2702 r
= glob_item_recursively(i
, fd_set_perms
);
2708 r
= glob_item(i
, path_set_xattrs
);
2713 case RECURSIVE_SET_XATTR
:
2714 r
= glob_item_recursively(i
, fd_set_xattrs
);
2720 r
= glob_item(i
, path_set_acls
);
2725 case RECURSIVE_SET_ACL
:
2726 r
= glob_item_recursively(i
, fd_set_acls
);
2732 r
= glob_item(i
, path_set_attribute
);
2737 case RECURSIVE_SET_ATTRIBUTE
:
2738 r
= glob_item_recursively(i
, fd_set_attribute
);
2747 static int remove_item_instance(Item
*i
, const char *instance
, CreationMode creation
) {
2755 if (remove(instance
) < 0 && errno
!= ENOENT
)
2756 return log_error_errno(errno
, "rm(%s): %m", instance
);
2760 case RECURSIVE_REMOVE_PATH
:
2761 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2762 log_debug("rm -rf \"%s\"", instance
);
2763 r
= rm_rf(instance
, REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
);
2764 if (r
< 0 && r
!= -ENOENT
)
2765 return log_error_errno(r
, "rm_rf(%s): %m", instance
);
2770 assert_not_reached();
2776 static int remove_item(Item
*i
) {
2781 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
2785 case TRUNCATE_DIRECTORY
:
2786 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2787 log_debug("rm -rf \"%s\"", i
->path
);
2788 r
= rm_rf(i
->path
, REMOVE_PHYSICAL
);
2789 if (r
< 0 && r
!= -ENOENT
)
2790 return log_error_errno(r
, "rm_rf(%s): %m", i
->path
);
2795 case RECURSIVE_REMOVE_PATH
:
2796 return glob_item(i
, remove_item_instance
);
2803 static char *age_by_to_string(AgeBy ab
, bool is_dir
) {
2804 static const char ab_map
[] = { 'a', 'b', 'c', 'm' };
2808 ret
= new(char, ELEMENTSOF(ab_map
) + 1);
2812 for (size_t i
= 0; i
< ELEMENTSOF(ab_map
); i
++)
2813 if (FLAGS_SET(ab
, 1U << i
))
2814 ret
[j
++] = is_dir
? ascii_toupper(ab_map
[i
]) : ab_map
[i
];
2820 static int clean_item_instance(
2822 const char* instance
,
2823 CreationMode creation
) {
2825 _cleanup_closedir_
DIR *d
= NULL
;
2826 STRUCT_STATX_DEFINE(sx
);
2835 n
= now(CLOCK_REALTIME
);
2839 cutoff
= n
- i
->age
;
2841 d
= opendir_nomod(instance
);
2843 if (IN_SET(errno
, ENOENT
, ENOTDIR
)) {
2844 log_debug_errno(errno
, "Directory \"%s\": %m", instance
);
2848 return log_error_errno(errno
, "Failed to open directory %s: %m", instance
);
2851 r
= statx_fallback(dirfd(d
), "", AT_EMPTY_PATH
, STATX_MODE
|STATX_INO
|STATX_ATIME
|STATX_MTIME
, &sx
);
2853 return log_error_errno(r
, "statx(%s) failed: %m", instance
);
2855 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
))
2856 mountpoint
= FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
);
2860 if (fstatat(dirfd(d
), "..", &ps
, AT_SYMLINK_NOFOLLOW
) != 0)
2861 return log_error_errno(errno
, "stat(%s/..) failed: %m", i
->path
);
2864 sx
.stx_dev_major
!= major(ps
.st_dev
) ||
2865 sx
.stx_dev_minor
!= minor(ps
.st_dev
) ||
2866 sx
.stx_ino
!= ps
.st_ino
;
2869 if (DEBUG_LOGGING
) {
2870 _cleanup_free_
char *ab_f
= NULL
, *ab_d
= NULL
;
2872 ab_f
= age_by_to_string(i
->age_by_file
, false);
2876 ab_d
= age_by_to_string(i
->age_by_dir
, true);
2880 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
2881 mountpoint
? "mount point" : "directory",
2883 FORMAT_TIMESTAMP_STYLE(cutoff
, TIMESTAMP_US
),
2887 return dir_cleanup(i
, instance
, d
,
2888 load_statx_timestamp_nsec(&sx
.stx_atime
),
2889 load_statx_timestamp_nsec(&sx
.stx_mtime
),
2890 cutoff
* NSEC_PER_USEC
,
2891 sx
.stx_dev_major
, sx
.stx_dev_minor
, mountpoint
,
2892 MAX_DEPTH
, i
->keep_first_level
,
2893 i
->age_by_file
, i
->age_by_dir
);
2896 static int clean_item(Item
*i
) {
2899 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
2902 case CREATE_DIRECTORY
:
2903 case CREATE_SUBVOLUME
:
2904 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2905 case CREATE_SUBVOLUME_NEW_QUOTA
:
2906 case TRUNCATE_DIRECTORY
:
2909 clean_item_instance(i
, i
->path
, CREATION_EXISTING
);
2911 case EMPTY_DIRECTORY
:
2912 case IGNORE_DIRECTORY_PATH
:
2913 return glob_item(i
, clean_item_instance
);
2919 static int process_item(Item
*i
, OperationMask operation
) {
2921 _cleanup_free_
char *_path
= NULL
;
2927 todo
= operation
& ~i
->done
;
2928 if (todo
== 0) /* Everything already done? */
2931 i
->done
|= operation
;
2934 if (string_is_glob(path
)) {
2935 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
2936 * for the non-glob part. */
2938 r
= glob_non_glob_prefix(path
, &_path
);
2939 if (r
< 0 && r
!= -ENOENT
)
2940 return log_debug_errno(r
, "Failed to deglob path: %m");
2945 r
= chase(path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_NONEXISTENT
|CHASE_WARN
, NULL
, NULL
);
2946 if (r
== -EREMOTE
) {
2947 log_notice_errno(r
, "Skipping %s", i
->path
); /* We log the configured path, to not confuse the user. */
2951 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
2953 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(i
) : 0;
2954 /* Failure can only be tolerated for create */
2955 if (i
->allow_failure
)
2958 q
= FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(i
) : 0;
2959 p
= FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(i
) : 0;
2966 static int process_item_array(ItemArray
*array
, OperationMask operation
) {
2972 /* Create any parent first. */
2973 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
2974 r
= process_item_array(array
->parent
, operation
& OPERATION_CREATE
);
2976 /* Clean up all children first */
2977 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
)) && !set_isempty(array
->children
)) {
2980 SET_FOREACH(c
, array
->children
) {
2983 k
= process_item_array(c
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
));
2984 if (k
< 0 && r
== 0)
2989 for (n
= 0; n
< array
->n_items
; n
++) {
2992 k
= process_item(array
->items
+ n
, operation
);
2993 if (k
< 0 && r
== 0)
3000 static void item_free_contents(Item
*i
) {
3004 free(i
->binary_argument
);
3005 strv_free(i
->xattrs
);
3009 acl_free(i
->acl_access
);
3011 if (i
->acl_access_exec
)
3012 acl_free(i
->acl_access_exec
);
3015 acl_free(i
->acl_default
);
3019 static ItemArray
* item_array_free(ItemArray
*a
) {
3025 for (n
= 0; n
< a
->n_items
; n
++)
3026 item_free_contents(a
->items
+ n
);
3028 set_free(a
->children
);
3033 static int item_compare(const Item
*a
, const Item
*b
) {
3034 /* Make sure that the ownership taking item is put first, so
3035 * that we first create the node, and then can adjust it */
3037 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
3039 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
3042 return CMP(a
->type
, b
->type
);
3045 static bool item_compatible(const Item
*a
, const Item
*b
) {
3048 assert(streq(a
->path
, b
->path
));
3050 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
3051 /* check if the items are the same */
3052 return memcmp_nn(item_binary_argument(a
), item_binary_argument_size(a
),
3053 item_binary_argument(b
), item_binary_argument_size(b
)) == 0 &&
3055 a
->uid_set
== b
->uid_set
&&
3057 a
->uid_only_create
== b
->uid_only_create
&&
3059 a
->gid_set
== b
->gid_set
&&
3061 a
->gid_only_create
== b
->gid_only_create
&&
3063 a
->mode_set
== b
->mode_set
&&
3064 a
->mode
== b
->mode
&&
3065 a
->mode_only_create
== b
->mode_only_create
&&
3067 a
->age_set
== b
->age_set
&&
3070 a
->age_by_file
== b
->age_by_file
&&
3071 a
->age_by_dir
== b
->age_by_dir
&&
3073 a
->mask_perms
== b
->mask_perms
&&
3075 a
->keep_first_level
== b
->keep_first_level
&&
3077 a
->major_minor
== b
->major_minor
;
3082 static bool should_include_path(const char *path
) {
3083 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
3084 if (path_startswith(path
, *prefix
)) {
3085 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
3090 STRV_FOREACH(prefix
, arg_include_prefixes
)
3091 if (path_startswith(path
, *prefix
)) {
3092 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
3096 /* no matches, so we should include this path only if we have no allow list at all */
3097 if (strv_isempty(arg_include_prefixes
))
3100 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
3104 static int specifier_expansion_from_arg(const Specifier
*specifier_table
, Item
*i
) {
3114 case CREATE_SYMLINK
:
3118 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
3121 l
= cunescape(i
->argument
, 0, &unescaped
);
3123 return log_error_errno(l
, "Failed to unescape parameter to write: %s", i
->argument
);
3125 r
= specifier_printf(unescaped
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &resolved
);
3129 return free_and_replace(i
->argument
, resolved
);
3132 case RECURSIVE_SET_XATTR
:
3133 STRV_FOREACH(xattr
, i
->xattrs
) {
3134 _cleanup_free_
char *resolved
= NULL
;
3136 r
= specifier_printf(*xattr
, SIZE_MAX
, specifier_table
, arg_root
, NULL
, &resolved
);
3140 free_and_replace(*xattr
, resolved
);
3149 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
3156 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
3157 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
3158 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
3159 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
3160 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
3161 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
3162 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
3163 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
3164 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
3166 k
= path_startswith(*path
, "/var/run/");
3167 if (isempty(k
)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
3170 n
= path_join("/run", k
);
3174 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
3175 * there's no immediate need for action by the user. However, in the interest of making things less confusing
3176 * to the user, let's still inform the user that these snippets should really be updated. */
3177 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
3178 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3181 free_and_replace(*path
, n
);
3186 static int find_uid(const char *user
, uid_t
*ret_uid
, Hashmap
**cache
) {
3192 /* First: parse as numeric UID string */
3193 r
= parse_uid(user
, ret_uid
);
3197 /* Second: pass to NSS if we are running "online" */
3199 return get_user_creds(&user
, ret_uid
, NULL
, NULL
, NULL
, 0);
3201 /* Third, synthesize "root" unconditionally */
3202 if (streq(user
, "root")) {
3207 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3208 return name_to_uid_offline(arg_root
, user
, ret_uid
, cache
);
3211 static int find_gid(const char *group
, gid_t
*ret_gid
, Hashmap
**cache
) {
3217 /* First: parse as numeric GID string */
3218 r
= parse_gid(group
, ret_gid
);
3222 /* Second: pass to NSS if we are running "online" */
3224 return get_group_creds(&group
, ret_gid
, 0);
3226 /* Third, synthesize "root" unconditionally */
3227 if (streq(group
, "root")) {
3232 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3233 return name_to_gid_offline(arg_root
, group
, ret_gid
, cache
);
3236 static int parse_age_by_from_arg(const char *age_by_str
, Item
*item
) {
3237 AgeBy ab_f
= 0, ab_d
= 0;
3239 static const struct {
3242 } age_by_types
[] = {
3243 { 'a', AGE_BY_ATIME
},
3244 { 'b', AGE_BY_BTIME
},
3245 { 'c', AGE_BY_CTIME
},
3246 { 'm', AGE_BY_MTIME
},
3252 if (isempty(age_by_str
))
3255 for (const char *s
= age_by_str
; *s
!= 0; s
++) {
3258 /* Ignore whitespace. */
3259 if (strchr(WHITESPACE
, *s
))
3262 for (i
= 0; i
< ELEMENTSOF(age_by_types
); i
++) {
3263 /* Check lower-case for files, upper-case for directories. */
3264 if (*s
== age_by_types
[i
].age_by_chr
) {
3265 ab_f
|= age_by_types
[i
].age_by_flag
;
3267 } else if (*s
== ascii_toupper(age_by_types
[i
].age_by_chr
)) {
3268 ab_d
|= age_by_types
[i
].age_by_flag
;
3273 /* Invalid character. */
3274 if (i
>= ELEMENTSOF(age_by_types
))
3279 if (ab_f
== 0 && ab_d
== 0)
3282 item
->age_by_file
= ab_f
> 0 ? ab_f
: AGE_BY_DEFAULT_FILE
;
3283 item
->age_by_dir
= ab_d
> 0 ? ab_d
: AGE_BY_DEFAULT_DIR
;
3288 static bool is_duplicated_item(ItemArray
*existing
, const Item
*i
) {
3293 for (size_t n
= 0; n
< existing
->n_items
; n
++) {
3294 const Item
*e
= existing
->items
+ n
;
3296 if (item_compatible(e
, i
))
3299 /* Only multiple 'w+' lines for the same path are allowed. */
3300 if (e
->type
!= WRITE_FILE
|| !e
->append_or_force
||
3301 i
->type
!= WRITE_FILE
|| !i
->append_or_force
)
3308 static int parse_line(
3312 bool *invalid_config
,
3313 Hashmap
**uid_cache
,
3314 Hashmap
**gid_cache
) {
3316 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
3317 _cleanup_(item_free_contents
) Item i
= {
3318 /* The "age-by" argument considers all file timestamp types by default. */
3319 .age_by_file
= AGE_BY_DEFAULT_FILE
,
3320 .age_by_dir
= AGE_BY_DEFAULT_DIR
,
3322 ItemArray
*existing
;
3325 bool append_or_force
= false, boot
= false, allow_failure
= false, try_replace
= false, unbase64
= false, from_cred
= false;
3331 const Specifier specifier_table
[] = {
3332 { 'a', specifier_architecture
, NULL
},
3333 { 'b', specifier_boot_id
, NULL
},
3334 { 'B', specifier_os_build_id
, NULL
},
3335 { 'H', specifier_hostname
, NULL
},
3336 { 'l', specifier_short_hostname
, NULL
},
3337 { 'm', specifier_machine_id
, NULL
},
3338 { 'o', specifier_os_id
, NULL
},
3339 { 'v', specifier_kernel_release
, NULL
},
3340 { 'w', specifier_os_version_id
, NULL
},
3341 { 'W', specifier_os_variant_id
, NULL
},
3343 { 'h', specifier_user_home
, NULL
},
3345 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
3346 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
3347 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
3348 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
3350 COMMON_CREDS_SPECIFIERS(arg_runtime_scope
),
3351 COMMON_TMP_SPECIFIERS
,
3355 r
= extract_many_words(
3367 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3368 /* invalid quoting and such or an unknown specifier */
3369 *invalid_config
= true;
3370 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to parse line: %m");
3372 *invalid_config
= true;
3373 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Syntax error.");
3376 if (!empty_or_dash(buffer
)) {
3377 i
.argument
= strdup(buffer
);
3382 if (isempty(action
)) {
3383 *invalid_config
= true;
3384 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Command too short '%s'.", action
);
3387 for (pos
= 1; action
[pos
]; pos
++) {
3388 if (action
[pos
] == '!' && !boot
)
3390 else if (action
[pos
] == '+' && !append_or_force
)
3391 append_or_force
= true;
3392 else if (action
[pos
] == '-' && !allow_failure
)
3393 allow_failure
= true;
3394 else if (action
[pos
] == '=' && !try_replace
)
3396 else if (action
[pos
] == '~' && !unbase64
)
3398 else if (action
[pos
] == '^' && !from_cred
)
3401 *invalid_config
= true;
3402 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Unknown modifiers in command '%s'", action
);
3406 if (boot
&& !arg_boot
) {
3407 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action
, path
);
3412 i
.append_or_force
= append_or_force
;
3413 i
.allow_failure
= allow_failure
;
3414 i
.try_replace
= try_replace
;
3416 r
= specifier_printf(path
, PATH_MAX
-1, specifier_table
, arg_root
, NULL
, &i
.path
);
3417 if (ERRNO_IS_NOINFO(r
))
3418 return log_unresolvable_specifier(fname
, line
);
3420 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3421 *invalid_config
= true;
3422 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", path
);
3425 r
= patch_var_run(fname
, line
, &i
.path
);
3429 if (!path_is_absolute(i
.path
)) {
3430 *invalid_config
= true;
3431 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3432 "Path '%s' not absolute.", i
.path
);
3435 path_simplify(i
.path
);
3439 case CREATE_DIRECTORY
:
3440 case CREATE_SUBVOLUME
:
3441 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
3442 case CREATE_SUBVOLUME_NEW_QUOTA
:
3443 case EMPTY_DIRECTORY
:
3444 case TRUNCATE_DIRECTORY
:
3447 case IGNORE_DIRECTORY_PATH
:
3449 case RECURSIVE_REMOVE_PATH
:
3452 case RECURSIVE_RELABEL_PATH
:
3459 "%c lines don't take argument fields, ignoring.",
3468 case CREATE_SYMLINK
:
3470 *invalid_config
= true;
3471 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for symlink targets.");
3477 *invalid_config
= true;
3478 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Write file requires argument.");
3484 *invalid_config
= true;
3485 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for copy sources.");
3489 case CREATE_CHAR_DEVICE
:
3490 case CREATE_BLOCK_DEVICE
:
3492 *invalid_config
= true;
3493 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for device node creation.");
3497 *invalid_config
= true;
3498 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Device file requires argument.");
3501 r
= parse_devnum(i
.argument
, &i
.major_minor
);
3503 *invalid_config
= true;
3504 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Can't parse device file major/minor '%s'.", i
.argument
);
3510 case RECURSIVE_SET_XATTR
:
3512 *invalid_config
= true;
3513 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for extended attributes.");
3516 *invalid_config
= true;
3517 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3518 "Set extended attribute requires argument.");
3520 r
= parse_xattrs_from_arg(&i
);
3526 case RECURSIVE_SET_ACL
:
3528 *invalid_config
= true;
3529 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for ACLs.");
3532 *invalid_config
= true;
3533 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3534 "Set ACLs requires argument.");
3536 r
= parse_acls_from_arg(&i
);
3542 case RECURSIVE_SET_ATTRIBUTE
:
3544 *invalid_config
= true;
3545 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "base64 decoding not supported for file attributes.");
3548 *invalid_config
= true;
3549 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3550 "Set file attribute requires argument.");
3552 r
= parse_attribute_from_arg(&i
);
3553 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3554 *invalid_config
= true;
3560 *invalid_config
= true;
3561 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
3562 "Unknown command type '%c'.", (char) i
.type
);
3565 if (!should_include_path(i
.path
))
3569 /* Do specifier expansion except if base64 mode is enabled */
3570 r
= specifier_expansion_from_arg(specifier_table
, &i
);
3571 if (ERRNO_IS_NOINFO(r
))
3572 return log_unresolvable_specifier(fname
, line
);
3574 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
3575 *invalid_config
= true;
3576 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to substitute specifiers in argument: %m");
3581 case CREATE_SYMLINK
:
3583 i
.argument
= path_join("/usr/share/factory", i
.path
);
3591 i
.argument
= path_join("/usr/share/factory", i
.path
);
3594 } else if (!path_is_absolute(i
.argument
)) {
3595 *invalid_config
= true;
3596 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Source path '%s' is not absolute.", i
.argument
);
3600 if (!empty_or_root(arg_root
)) {
3603 p
= path_join(arg_root
, i
.argument
);
3606 free_and_replace(i
.argument
, p
);
3609 path_simplify(i
.argument
);
3611 if (laccess(i
.argument
, F_OK
) == -ENOENT
) {
3612 /* Silently skip over lines where the source file is missing. */
3613 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Copy source path '%s' does not exist, skipping line.", i
.argument
);
3625 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
), "Reading from credential requested, but no credential name specified.");
3626 if (!credential_name_valid(i
.argument
))
3627 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EINVAL
), "Credential name not valid: %s", i
.argument
);
3629 r
= read_credential(i
.argument
, &i
.binary_argument
, &i
.binary_argument_size
);
3630 if (IN_SET(r
, -ENXIO
, -ENOENT
)) {
3631 /* Silently skip over lines that have no credentials passed */
3632 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0,
3633 "Credential '%s' not specified, skipping line.", i
.argument
);
3637 return log_error_errno(r
, "Failed to read credential '%s': %m", i
.argument
);
3640 /* If base64 decoding is requested, do so now */
3641 if (unbase64
&& item_binary_argument(&i
)) {
3642 _cleanup_free_
void *data
= NULL
;
3643 size_t data_size
= 0;
3645 r
= unbase64mem(item_binary_argument(&i
), item_binary_argument_size(&i
), &data
, &data_size
);
3647 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to base64 decode specified argument '%s': %m", i
.argument
);
3649 free_and_replace(i
.binary_argument
, data
);
3650 i
.binary_argument_size
= data_size
;
3653 if (!empty_or_root(arg_root
)) {
3656 p
= path_join(arg_root
, i
.path
);
3659 free_and_replace(i
.path
, p
);
3662 if (!empty_or_dash(user
)) {
3665 u
= startswith(user
, ":");
3667 i
.uid_only_create
= true;
3671 r
= find_uid(u
, &i
.uid
, uid_cache
);
3673 *invalid_config
= true;
3674 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve user '%s': %m", u
);
3680 if (!empty_or_dash(group
)) {
3683 g
= startswith(group
, ":");
3685 i
.gid_only_create
= true;
3689 r
= find_gid(g
, &i
.gid
, gid_cache
);
3691 *invalid_config
= true;
3692 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve group '%s'.", g
);
3698 if (!empty_or_dash(mode
)) {
3702 for (mm
= mode
;; mm
++) {
3704 i
.mask_perms
= true;
3705 else if (*mm
== ':')
3706 i
.mode_only_create
= true;
3711 r
= parse_mode(mm
, &m
);
3713 *invalid_config
= true;
3714 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid mode '%s'.", mode
);
3720 i
.mode
= IN_SET(i
.type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
3722 if (!empty_or_dash(age
)) {
3723 const char *a
= age
;
3724 _cleanup_free_
char *seconds
= NULL
, *age_by
= NULL
;
3727 i
.keep_first_level
= true;
3731 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3732 r
= split_pair(a
, ":", &age_by
, &seconds
);
3735 if (r
< 0 && r
!= -EINVAL
)
3736 return log_error_errno(r
, "Failed to parse age-by for '%s': %m", age
);
3738 /* We found a ":", parse the "age-by" part. */
3739 r
= parse_age_by_from_arg(age_by
, &i
);
3743 *invalid_config
= true;
3744 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age-by '%s'.", age_by
);
3747 /* For parsing the "age" part, after the ":". */
3751 r
= parse_sec(a
, &i
.age
);
3753 *invalid_config
= true;
3754 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age '%s'.", a
);
3760 h
= needs_glob(i
.type
) ? globs
: items
;
3762 existing
= ordered_hashmap_get(h
, i
.path
);
3764 if (is_duplicated_item(existing
, &i
)) {
3765 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0,
3766 "Duplicate line for path \"%s\", ignoring.", i
.path
);
3770 existing
= new0(ItemArray
, 1);
3774 r
= ordered_hashmap_put(h
, i
.path
, existing
);
3781 if (!GREEDY_REALLOC(existing
->items
, existing
->n_items
+ 1))
3784 existing
->items
[existing
->n_items
++] = TAKE_STRUCT(i
);
3786 /* Sort item array, to enforce stable ordering of application */
3787 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
3792 static int cat_config(char **config_dirs
, char **args
) {
3793 _cleanup_strv_free_
char **files
= NULL
;
3796 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
3800 return cat_files(NULL
, files
, 0);
3803 static int exclude_default_prefixes(void) {
3806 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3807 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3808 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3809 * all kinds of files created/adjusted underneath these mount points. */
3811 r
= strv_extend_strv(
3812 &arg_exclude_prefixes
,
3824 static int help(void) {
3825 _cleanup_free_
char *link
= NULL
;
3828 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
3832 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3833 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3834 " -h --help Show this help\n"
3835 " --user Execute user configuration\n"
3836 " --version Show package version\n"
3837 " --cat-config Show configuration files\n"
3838 " --create Create marked files/directories\n"
3839 " --clean Clean up marked directories\n"
3840 " --remove Remove marked files/directories\n"
3841 " --boot Execute actions only safe at boot\n"
3842 " --prefix=PATH Only apply rules with the specified prefix\n"
3843 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3844 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3845 " --root=PATH Operate on an alternate filesystem root\n"
3846 " --image=PATH Operate on disk image as filesystem root\n"
3847 " --image-policy=POLICY Specify disk image dissection policy\n"
3848 " --replace=PATH Treat arguments as replacement for PATH\n"
3849 " --no-pager Do not pipe output into a pager\n"
3850 "\nSee the %s for details.\n",
3851 program_invocation_short_name
,
3859 static int parse_argv(int argc
, char *argv
[]) {
3862 ARG_VERSION
= 0x100,
3878 static const struct option options
[] = {
3879 { "help", no_argument
, NULL
, 'h' },
3880 { "user", no_argument
, NULL
, ARG_USER
},
3881 { "version", no_argument
, NULL
, ARG_VERSION
},
3882 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
3883 { "create", no_argument
, NULL
, ARG_CREATE
},
3884 { "clean", no_argument
, NULL
, ARG_CLEAN
},
3885 { "remove", no_argument
, NULL
, ARG_REMOVE
},
3886 { "boot", no_argument
, NULL
, ARG_BOOT
},
3887 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
3888 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
3889 { "root", required_argument
, NULL
, ARG_ROOT
},
3890 { "image", required_argument
, NULL
, ARG_IMAGE
},
3891 { "image-policy", required_argument
, NULL
, ARG_IMAGE_POLICY
},
3892 { "replace", required_argument
, NULL
, ARG_REPLACE
},
3893 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
3902 while ((c
= getopt_long(argc
, argv
, "hE", options
, NULL
)) >= 0)
3912 case ARG_CAT_CONFIG
:
3913 arg_cat_config
= true;
3917 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
3921 arg_operation
|= OPERATION_CREATE
;
3925 arg_operation
|= OPERATION_CLEAN
;
3929 arg_operation
|= OPERATION_REMOVE
;
3937 if (strv_push(&arg_include_prefixes
, optarg
) < 0)
3941 case ARG_EXCLUDE_PREFIX
:
3942 if (strv_push(&arg_exclude_prefixes
, optarg
) < 0)
3947 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_root
);
3954 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3955 "This systemd-tmpfiles version is compiled without support for --image=.");
3957 r
= parse_path_argument(optarg
, /* suppress_root= */ false, &arg_image
);
3961 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
3965 r
= exclude_default_prefixes();
3971 case ARG_IMAGE_POLICY
:
3972 r
= parse_image_policy_argument(optarg
, &arg_image_policy
);
3978 if (!path_is_absolute(optarg
) ||
3979 !endswith(optarg
, ".conf"))
3980 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3981 "The argument to --replace= must an absolute path to a config file");
3983 arg_replace
= optarg
;
3987 arg_pager_flags
|= PAGER_DISABLE
;
3994 assert_not_reached();
3997 if (arg_operation
== 0 && !arg_cat_config
)
3998 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3999 "You need to specify at least one of --clean, --create or --remove.");
4001 if (arg_replace
&& arg_cat_config
)
4002 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4003 "Option --replace= is not supported with --cat-config");
4005 if (arg_replace
&& optind
>= argc
)
4006 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4007 "When --replace= is given, some configuration items must be specified");
4009 if (arg_root
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
)
4010 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
4011 "Combination of --user and --root= is not supported.");
4013 if (arg_image
&& arg_root
)
4014 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
4019 static int read_config_file(
4023 bool *invalid_config
) {
4025 _cleanup_(hashmap_freep
) Hashmap
*uid_cache
= NULL
, *gid_cache
= NULL
;
4026 _cleanup_fclose_
FILE *_f
= NULL
;
4027 _cleanup_free_
char *pp
= NULL
;
4035 if (streq(fn
, "-")) {
4036 log_debug("Reading config from stdin%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4040 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &_f
, &pp
);
4042 if (ignore_enoent
&& r
== -ENOENT
) {
4043 log_debug_errno(r
, "Failed to open \"%s\", ignoring: %m", fn
);
4047 return log_error_errno(r
, "Failed to open '%s': %m", fn
);
4050 log_debug("Reading config file \"%s\"%s", pp
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4056 _cleanup_free_
char *line
= NULL
;
4057 bool invalid_line
= false;
4061 k
= read_line(f
, LONG_LINE_MAX
, &line
);
4063 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
4070 if (IN_SET(*l
, 0, '#'))
4073 k
= parse_line(fn
, v
, l
, &invalid_line
, &uid_cache
, &gid_cache
);
4076 /* Allow reporting with a special code if the caller requested this */
4077 *invalid_config
= true;
4079 /* The first error becomes our return value */
4084 /* we have to determine age parameter for each entry of type X */
4085 ORDERED_HASHMAP_FOREACH(ia
, globs
)
4086 for (size_t ni
= 0; ni
< ia
->n_items
; ni
++) {
4088 Item
*i
= ia
->items
+ ni
, *candidate_item
= NULL
;
4090 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
4093 ORDERED_HASHMAP_FOREACH(ja
, items
)
4094 for (size_t nj
= 0; nj
< ja
->n_items
; nj
++) {
4095 Item
*j
= ja
->items
+ nj
;
4097 if (!IN_SET(j
->type
, CREATE_DIRECTORY
,
4100 CREATE_SUBVOLUME_INHERIT_QUOTA
,
4101 CREATE_SUBVOLUME_NEW_QUOTA
))
4104 if (path_equal(j
->path
, i
->path
)) {
4110 ? (path_startswith(j
->path
, candidate_item
->path
) && fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)
4111 : path_startswith(i
->path
, j
->path
) != NULL
)
4115 if (candidate_item
&& candidate_item
->age_set
) {
4116 i
->age
= candidate_item
->age
;
4122 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
4130 static int parse_arguments(char **config_dirs
, char **args
, bool *invalid_config
) {
4133 STRV_FOREACH(arg
, args
) {
4134 r
= read_config_file(config_dirs
, *arg
, false, invalid_config
);
4142 static int read_config_files(char **config_dirs
, char **args
, bool *invalid_config
) {
4143 _cleanup_strv_free_
char **files
= NULL
;
4144 _cleanup_free_
char *p
= NULL
;
4147 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
4151 STRV_FOREACH(f
, files
)
4152 if (p
&& path_equal(*f
, p
)) {
4153 log_debug("Parsing arguments at position \"%s\"%s", *f
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
4155 r
= parse_arguments(config_dirs
, args
, invalid_config
);
4159 /* Just warn, ignore result otherwise.
4160 * read_config_file() has some debug output, so no need to print anything. */
4161 (void) read_config_file(config_dirs
, *f
, true, invalid_config
);
4166 static int read_credential_lines(bool *invalid_config
) {
4167 _cleanup_free_
char *j
= NULL
;
4171 r
= get_credentials_dir(&d
);
4175 return log_error_errno(r
, "Failed to get credentials directory: %m");
4177 j
= path_join(d
, "tmpfiles.extra");
4181 (void) read_config_file(/* config_dirs= */ NULL
, j
, /* ignore_enoent= */ true, invalid_config
);
4185 static int link_parent(ItemArray
*a
) {
4192 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
4193 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
4194 * before their children, and clean up/remove children before their parents. */
4196 if (a
->n_items
<= 0)
4199 path
= a
->items
[0].path
;
4200 prefix
= newa(char, strlen(path
) + 1);
4201 PATH_FOREACH_PREFIX(prefix
, path
) {
4204 j
= ordered_hashmap_get(items
, prefix
);
4206 j
= ordered_hashmap_get(globs
, prefix
);
4208 r
= set_ensure_put(&j
->children
, NULL
, a
);
4220 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
4221 ItemArray
, item_array_free
);
4223 static int run(int argc
, char *argv
[]) {
4225 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
4226 _cleanup_(umount_and_rmdir_and_freep
) char *unlink_dir
= NULL
;
4228 _cleanup_strv_free_
char **config_dirs
= NULL
;
4229 bool invalid_config
= false;
4232 PHASE_REMOVE_AND_CLEAN
,
4238 r
= parse_argv(argc
, argv
);
4244 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4245 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4246 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4247 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4248 * and output a nice and friendly warning. */
4249 if (proc_mounted() == 0)
4250 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS
),
4251 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4252 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4254 /* Descending down file system trees might take a lot of fds */
4255 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
4257 switch (arg_runtime_scope
) {
4259 case RUNTIME_SCOPE_USER
:
4260 r
= user_config_paths(&config_dirs
);
4262 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
4265 case RUNTIME_SCOPE_SYSTEM
:
4266 config_dirs
= strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
4272 assert_not_reached();
4275 if (DEBUG_LOGGING
) {
4276 _cleanup_free_
char *t
= NULL
;
4278 STRV_FOREACH(i
, config_dirs
) {
4279 _cleanup_free_
char *j
= NULL
;
4281 j
= path_join(arg_root
, *i
);
4285 if (!strextend(&t
, "\n\t", j
))
4289 log_debug("Looking for configuration files in (higher priority first):%s", t
);
4292 if (arg_cat_config
) {
4293 pager_open(arg_pager_flags
);
4295 return cat_config(config_dirs
, argv
+ optind
);
4300 r
= mac_selinux_init();
4308 r
= mount_image_privately_interactively(
4311 DISSECT_IMAGE_GENERIC_ROOT
|
4312 DISSECT_IMAGE_REQUIRE_ROOT
|
4313 DISSECT_IMAGE_VALIDATE_OS
|
4314 DISSECT_IMAGE_RELAX_VAR_CHECK
|
4315 DISSECT_IMAGE_FSCK
|
4316 DISSECT_IMAGE_GROWFS
,
4318 /* ret_dir_fd= */ NULL
,
4323 arg_root
= strdup(unlink_dir
);
4331 items
= ordered_hashmap_new(&item_array_hash_ops
);
4332 globs
= ordered_hashmap_new(&item_array_hash_ops
);
4333 if (!items
|| !globs
)
4336 /* If command line arguments are specified along with --replace, read all
4337 * configuration files and insert the positional arguments at the specified
4338 * place. Otherwise, if command line arguments are specified, execute just
4339 * them, and finally, without --replace= or any positional arguments, just
4340 * read configuration and execute it.
4342 if (arg_replace
|| optind
>= argc
)
4343 r
= read_config_files(config_dirs
, argv
+ optind
, &invalid_config
);
4345 r
= parse_arguments(config_dirs
, argv
+ optind
, &invalid_config
);
4349 r
= read_credential_lines(&invalid_config
);
4353 /* Let's now link up all child/parent relationships */
4354 ORDERED_HASHMAP_FOREACH(a
, items
) {
4359 ORDERED_HASHMAP_FOREACH(a
, globs
) {
4365 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
4366 * operations. i.e. that we first clean out the platform we then build on. */
4367 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
4370 if (phase
== PHASE_REMOVE_AND_CLEAN
)
4371 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
4372 else if (phase
== PHASE_CREATE
)
4373 op
= arg_operation
& OPERATION_CREATE
;
4375 assert_not_reached();
4377 if (op
== 0) /* Nothing requested in this phase */
4380 /* The non-globbing ones usually create things, hence we apply them first */
4381 ORDERED_HASHMAP_FOREACH(a
, items
) {
4382 k
= process_item_array(a
, op
);
4383 if (k
< 0 && r
>= 0)
4387 /* The globbing ones usually alter things, hence we apply them second. */
4388 ORDERED_HASHMAP_FOREACH(a
, globs
) {
4389 k
= process_item_array(a
, op
);
4390 if (k
< 0 && r
>= 0)
4395 if (ERRNO_IS_RESOURCE(r
))
4400 return EX_CANTCREAT
;
4404 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);