1 /* SPDX-License-Identifier: LGPL-2.1+ */
15 #include <sys/xattr.h>
23 #include "alloc-util.h"
24 #include "btrfs-util.h"
25 #include "capability-util.h"
26 #include "chattr-util.h"
27 #include "conf-files.h"
30 #include "dirent-util.h"
34 #include "format-util.h"
36 #include "glob-util.h"
41 #include "main-func.h"
43 #include "mountpoint-util.h"
45 #include "parse-util.h"
46 #include "path-lookup.h"
47 #include "path-util.h"
48 #include "pretty-print.h"
49 #include "rlimit-util.h"
51 #include "selinux-util.h"
53 #include "sort-util.h"
54 #include "specifier.h"
55 #include "stat-util.h"
56 #include "stdio-util.h"
57 #include "string-table.h"
58 #include "string-util.h"
60 #include "umask-util.h"
61 #include "user-util.h"
63 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
64 * them in the file system. This is intended to be used to create
65 * properly owned directories beneath /tmp, /var/tmp, /run, which are
66 * volatile and hence need to be recreated on bootup. */
68 typedef enum OperationMask
{
69 OPERATION_CREATE
= 1 << 0,
70 OPERATION_REMOVE
= 1 << 1,
71 OPERATION_CLEAN
= 1 << 2,
74 typedef enum ItemType
{
75 /* These ones take file names */
78 CREATE_DIRECTORY
= 'd',
79 TRUNCATE_DIRECTORY
= 'D',
80 CREATE_SUBVOLUME
= 'v',
81 CREATE_SUBVOLUME_INHERIT_QUOTA
= 'q',
82 CREATE_SUBVOLUME_NEW_QUOTA
= 'Q',
85 CREATE_CHAR_DEVICE
= 'c',
86 CREATE_BLOCK_DEVICE
= 'b',
89 /* These ones take globs */
91 EMPTY_DIRECTORY
= 'e',
93 RECURSIVE_SET_XATTR
= 'T',
95 RECURSIVE_SET_ACL
= 'A',
97 RECURSIVE_SET_ATTRIBUTE
= 'H',
99 IGNORE_DIRECTORY_PATH
= 'X',
101 RECURSIVE_REMOVE_PATH
= 'R',
103 RECURSIVE_RELABEL_PATH
= 'Z',
104 ADJUST_MODE
= 'm', /* legacy, 'z' is identical to this */
107 typedef struct Item
{
123 unsigned attribute_value
;
124 unsigned attribute_mask
;
131 bool attribute_set
:1;
133 bool keep_first_level
:1;
135 bool append_or_force
:1;
137 bool allow_failure
:1;
142 typedef struct ItemArray
{
147 struct ItemArray
*parent
;
151 typedef enum DirectoryType
{
159 static bool arg_cat_config
= false;
160 static bool arg_user
= false;
161 static OperationMask arg_operation
= 0;
162 static bool arg_boot
= false;
163 static PagerFlags arg_pager_flags
= 0;
165 static char **arg_include_prefixes
= NULL
;
166 static char **arg_exclude_prefixes
= NULL
;
167 static char *arg_root
= NULL
;
168 static char *arg_replace
= NULL
;
170 #define MAX_DEPTH 256
172 static OrderedHashmap
*items
= NULL
, *globs
= NULL
;
173 static Set
*unix_sockets
= NULL
;
175 STATIC_DESTRUCTOR_REGISTER(items
, ordered_hashmap_freep
);
176 STATIC_DESTRUCTOR_REGISTER(globs
, ordered_hashmap_freep
);
177 STATIC_DESTRUCTOR_REGISTER(unix_sockets
, set_free_freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes
, freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes
, freep
);
180 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
182 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
);
183 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
);
185 static const Specifier specifier_table
[] = {
186 { 'm', specifier_machine_id_safe
, NULL
},
187 { 'b', specifier_boot_id
, NULL
},
188 { 'H', specifier_host_name
, NULL
},
189 { 'v', specifier_kernel_release
, NULL
},
191 { 'g', specifier_group_name
, NULL
},
192 { 'G', specifier_group_id
, NULL
},
193 { 'U', specifier_user_id
, NULL
},
194 { 'u', specifier_user_name
, NULL
},
195 { 'h', specifier_user_home
, NULL
},
197 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
198 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
199 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
200 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
201 { 'T', specifier_tmp_dir
, NULL
},
202 { 'V', specifier_var_tmp_dir
, NULL
},
206 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
) {
209 /* If /etc/machine_id is missing or empty (e.g. in a chroot environment)
210 * return a recognizable error so that the caller can skip the rule
213 r
= specifier_machine_id(specifier
, data
, userdata
, ret
);
214 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
))
220 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
) {
226 static const struct table_entry paths_system
[] = {
227 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
228 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
229 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
230 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
233 static const struct table_entry paths_user
[] = {
234 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
235 [DIRECTORY_STATE
] = { SD_PATH_USER_CONFIGURATION
},
236 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
237 [DIRECTORY_LOGS
] = { SD_PATH_USER_CONFIGURATION
, "log" },
241 const struct table_entry
*paths
;
243 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
244 paths
= arg_user
? paths_user
: paths_system
;
246 i
= PTR_TO_UINT(data
);
247 assert(i
< ELEMENTSOF(paths_system
));
249 return sd_path_home(paths
[i
].type
, paths
[i
].suffix
, ret
);
252 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
253 static bool notified
= false;
255 /* In system mode, this is called when /etc is not fully initialized (e.g.
256 * in a chroot environment) where some specifiers are unresolvable. In user
257 * mode, this is called when some variables are not defined. These cases are
258 * not considered as an error so log at LOG_NOTICE only for the first time
259 * and then downgrade this to LOG_DEBUG for the rest. */
261 log_full(notified
? LOG_DEBUG
: LOG_NOTICE
,
262 "[%s:%u] Failed to resolve specifier: %s, skipping",
264 arg_user
? "Required $XDG_... variable not defined" : "uninitialized /etc detected");
267 log_notice("All rules containing unresolvable specifiers will be skipped.");
273 static int user_config_paths(char*** ret
) {
274 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
275 _cleanup_free_
char *persistent_config
= NULL
, *runtime_config
= NULL
, *data_home
= NULL
;
276 _cleanup_strv_free_
char **res
= NULL
;
279 r
= xdg_user_dirs(&config_dirs
, &data_dirs
);
283 r
= xdg_user_config_dir(&persistent_config
, "/user-tmpfiles.d");
284 if (r
< 0 && r
!= -ENXIO
)
287 r
= xdg_user_runtime_dir(&runtime_config
, "/user-tmpfiles.d");
288 if (r
< 0 && r
!= -ENXIO
)
291 r
= xdg_user_data_dir(&data_home
, "/user-tmpfiles.d");
292 if (r
< 0 && r
!= -ENXIO
)
295 r
= strv_extend_strv_concat(&res
, config_dirs
, "/user-tmpfiles.d");
299 r
= strv_extend(&res
, persistent_config
);
303 r
= strv_extend(&res
, runtime_config
);
307 r
= strv_extend(&res
, data_home
);
311 r
= strv_extend_strv_concat(&res
, data_dirs
, "/user-tmpfiles.d");
315 r
= path_strv_make_absolute_cwd(res
);
319 *ret
= TAKE_PTR(res
);
323 static bool needs_glob(ItemType t
) {
327 IGNORE_DIRECTORY_PATH
,
329 RECURSIVE_REMOVE_PATH
,
333 RECURSIVE_RELABEL_PATH
,
339 RECURSIVE_SET_ATTRIBUTE
);
342 static bool takes_ownership(ItemType t
) {
350 CREATE_SUBVOLUME_INHERIT_QUOTA
,
351 CREATE_SUBVOLUME_NEW_QUOTA
,
359 IGNORE_DIRECTORY_PATH
,
361 RECURSIVE_REMOVE_PATH
);
364 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
368 ORDERED_HASHMAP_FOREACH(j
, h
, i
) {
371 for (n
= 0; n
< j
->n_items
; n
++) {
372 Item
*item
= j
->items
+ n
;
374 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
382 static int load_unix_sockets(void) {
383 _cleanup_set_free_free_ Set
*sockets
= NULL
;
384 _cleanup_fclose_
FILE *f
= NULL
;
390 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
392 sockets
= set_new(&path_hash_ops
);
396 f
= fopen("/proc/net/unix", "re");
398 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
399 "Failed to open /proc/net/unix, ignoring: %m");
402 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
404 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
406 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
409 _cleanup_free_
char *line
= NULL
, *s
= NULL
;
412 r
= read_line(f
, LONG_LINE_MAX
, &line
);
414 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
415 if (r
== 0) /* EOF */
418 p
= strchr(line
, ':');
426 p
+= strspn(p
, WHITESPACE
);
427 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
428 p
+= strspn(p
, WHITESPACE
);
437 path_simplify(s
, false);
439 r
= set_consume(sockets
, s
);
443 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
448 unix_sockets
= TAKE_PTR(sockets
);
452 static bool unix_socket_alive(const char *fn
) {
455 if (load_unix_sockets() < 0)
456 return true; /* We don't know, so assume yes */
458 return !!set_get(unix_sockets
, (char*) fn
);
461 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
464 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
468 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
472 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
474 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
479 static DIR* opendir_nomod(const char *path
) {
480 return xopendirat_nomod(AT_FDCWD
, path
);
483 static int dir_cleanup(
487 const struct stat
*ds
,
492 bool keep_this_level
) {
495 bool deleted
= false;
498 FOREACH_DIRENT_ALL(dent
, d
, break) {
501 _cleanup_free_
char *sub_path
= NULL
;
503 if (dot_or_dot_dot(dent
->d_name
))
506 if (fstatat(dirfd(d
), dent
->d_name
, &s
, AT_SYMLINK_NOFOLLOW
) < 0) {
510 /* FUSE, NFS mounts, SELinux might return EACCES */
511 r
= log_full_errno(errno
== EACCES
? LOG_DEBUG
: LOG_ERR
, errno
,
512 "stat(%s/%s) failed: %m", p
, dent
->d_name
);
516 /* Stay on the same filesystem */
517 if (s
.st_dev
!= rootdev
) {
518 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, dent
->d_name
);
522 /* Try to detect bind mounts of the same filesystem instance; they
523 * do not differ in device major/minors. This type of query is not
524 * supported on all kernels or filesystem types though. */
525 if (S_ISDIR(s
.st_mode
)) {
528 q
= fd_is_mount_point(dirfd(d
), dent
->d_name
, 0);
530 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, dent
->d_name
);
532 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, dent
->d_name
);
537 sub_path
= path_join(p
, dent
->d_name
);
543 /* Is there an item configured for this path? */
544 if (ordered_hashmap_get(items
, sub_path
)) {
545 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
549 if (find_glob(globs
, sub_path
)) {
550 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
554 if (S_ISDIR(s
.st_mode
)) {
555 _cleanup_closedir_
DIR *sub_dir
= NULL
;
558 streq(dent
->d_name
, "lost+found") &&
560 log_debug("Ignoring directory \"%s\".", sub_path
);
565 log_warning("Reached max depth on \"%s\".", sub_path
);
569 sub_dir
= xopendirat_nomod(dirfd(d
), dent
->d_name
);
572 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
577 if (flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
578 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p
);
582 q
= dir_cleanup(i
, sub_path
, sub_dir
, &s
, cutoff
, rootdev
, false, maxdepth
-1, false);
587 /* Note: if you are wondering why we don't support the sticky bit for excluding
588 * directories from cleaning like we do it for other file system objects: well, the
589 * sticky bit already has a meaning for directories, so we don't want to overload
592 if (keep_this_level
) {
593 log_debug("Keeping directory \"%s\".", sub_path
);
597 /* Ignore ctime, we change it when deleting */
598 age
= timespec_load(&s
.st_mtim
);
600 char a
[FORMAT_TIMESTAMP_MAX
];
601 /* Follows spelling in stat(1). */
602 log_debug("Directory \"%s\": modify time %s is too new.",
604 format_timestamp_us(a
, sizeof(a
), age
));
608 age
= timespec_load(&s
.st_atim
);
610 char a
[FORMAT_TIMESTAMP_MAX
];
611 log_debug("Directory \"%s\": access time %s is too new.",
613 format_timestamp_us(a
, sizeof(a
), age
));
617 log_debug("Removing directory \"%s\".", sub_path
);
618 if (unlinkat(dirfd(d
), dent
->d_name
, AT_REMOVEDIR
) < 0)
619 if (!IN_SET(errno
, ENOENT
, ENOTEMPTY
))
620 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
623 /* Skip files for which the sticky bit is set. These are semantics we define, and are
624 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
625 if (s
.st_mode
& S_ISVTX
) {
626 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
631 S_ISREG(s
.st_mode
) &&
633 STR_IN_SET(dent
->d_name
,
637 log_debug("Skipping \"%s\".", sub_path
);
641 /* Ignore sockets that are listed in /proc/net/unix */
642 if (S_ISSOCK(s
.st_mode
) && unix_socket_alive(sub_path
)) {
643 log_debug("Skipping \"%s\": live socket.", sub_path
);
647 /* Ignore device nodes */
648 if (S_ISCHR(s
.st_mode
) || S_ISBLK(s
.st_mode
)) {
649 log_debug("Skipping \"%s\": a device.", sub_path
);
653 /* Keep files on this level around if this is requested */
654 if (keep_this_level
) {
655 log_debug("Keeping \"%s\".", sub_path
);
659 age
= timespec_load(&s
.st_mtim
);
661 char a
[FORMAT_TIMESTAMP_MAX
];
662 /* Follows spelling in stat(1). */
663 log_debug("File \"%s\": modify time %s is too new.",
665 format_timestamp_us(a
, sizeof(a
), age
));
669 age
= timespec_load(&s
.st_atim
);
671 char a
[FORMAT_TIMESTAMP_MAX
];
672 log_debug("File \"%s\": access time %s is too new.",
674 format_timestamp_us(a
, sizeof(a
), age
));
678 age
= timespec_load(&s
.st_ctim
);
680 char a
[FORMAT_TIMESTAMP_MAX
];
681 log_debug("File \"%s\": change time %s is too new.",
683 format_timestamp_us(a
, sizeof(a
), age
));
687 log_debug("Removing \"%s\".", sub_path
);
688 if (unlinkat(dirfd(d
), dent
->d_name
, 0) < 0)
690 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
698 char a
[FORMAT_TIMESTAMP_MAX
], b
[FORMAT_TIMESTAMP_MAX
];
701 age1
= timespec_load(&ds
->st_atim
);
702 age2
= timespec_load(&ds
->st_mtim
);
704 log_debug("Restoring access and modification time on \"%s\": %s, %s",
706 format_timestamp_us(a
, sizeof(a
), age1
),
707 format_timestamp_us(b
, sizeof(b
), age2
));
709 /* Restore original directory timestamps */
710 if (futimens(dirfd(d
), (struct timespec
[]) {
713 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
719 static bool dangerous_hardlinks(void) {
720 _cleanup_free_
char *value
= NULL
;
721 static int cached
= -1;
724 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
725 * what the upstream default is. */
730 r
= read_one_line_file("/proc/sys/fs/protected_hardlinks", &value
);
732 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl: %m");
736 r
= parse_boolean(value
);
738 log_debug_errno(r
, "Failed to parse fs.protected_hardlinks sysctl: %m");
746 static bool hardlink_vulnerable(const struct stat
*st
) {
749 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && dangerous_hardlinks();
752 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
754 if ((current
& 0111) == 0)
756 if ((current
& 0222) == 0)
758 if ((current
& 0444) == 0)
760 if (!S_ISDIR(current
))
761 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
766 static int fd_set_perms(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
775 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
779 if (fstat(fd
, &stbuf
) < 0)
780 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
784 if (hardlink_vulnerable(st
))
785 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
786 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
789 /* Do we need a chown()? */
791 (i
->uid_set
&& i
->uid
!= st
->st_uid
) ||
792 (i
->gid_set
&& i
->gid
!= st
->st_gid
);
794 /* Calculate the mode to apply */
795 new_mode
= i
->mode_set
? (i
->mask_perms
?
796 process_mask_perms(i
->mode
, st
->st_mode
) :
798 (st
->st_mode
& 07777);
800 if (i
->mode_set
&& do_chown
) {
801 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
802 * the new mode. That way there's no time window where the file exists under the old owner
803 * with more than the old access modes — and not under the new owner with more than the new
804 * access modes either. */
806 if (S_ISLNK(st
->st_mode
))
807 log_debug("Skipping temporary mode fix for symlink %s.", path
);
809 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
811 if (((m
^ st
->st_mode
) & 07777) == 0)
812 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
814 log_debug("Temporarily changing \"%s\" to mode %o.", path
, m
);
815 if (fchmod_opath(fd
, m
) < 0)
816 return log_error_errno(errno
, "fchmod() of %s failed: %m", path
);
822 log_debug("Changing \"%s\" to owner "UID_FMT
":"GID_FMT
,
824 i
->uid_set
? i
->uid
: UID_INVALID
,
825 i
->gid_set
? i
->gid
: GID_INVALID
);
829 i
->uid_set
? i
->uid
: UID_INVALID
,
830 i
->gid_set
? i
->gid
: GID_INVALID
,
832 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
835 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
836 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
837 if (i
->mode_set
|| do_chown
) {
838 if (S_ISLNK(st
->st_mode
))
839 log_debug("Skipping mode fix for symlink %s.", path
);
841 /* Check if the chmod() is unnecessary. Note that if we did a chown() before we always
842 * chmod() here again, since it might have mangled the bits. */
843 if (!do_chown
&& ((new_mode
^ st
->st_mode
) & 07777) == 0)
844 log_debug("\"%s\" matches mode %o already.", path
, new_mode
);
846 log_debug("Changing \"%s\" to mode %o.", path
, new_mode
);
847 if (fchmod_opath(fd
, new_mode
) < 0)
848 return log_error_errno(errno
, "fchmod() of %s failed: %m", path
);
854 return label_fix(path
, 0);
857 static int path_open_parent_safe(const char *path
) {
858 _cleanup_free_
char *dn
= NULL
;
861 if (path_equal(path
, "/") || !path_is_normalized(path
))
862 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
863 "Failed to open parent of '%s': invalid path.",
866 dn
= dirname_malloc(path
);
870 r
= chase_symlinks(dn
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
871 if (r
< 0 && r
!= -ENOLINK
)
872 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
874 return r
< 0 ? r
: fd
;
877 static int path_open_safe(const char *path
) {
880 /* path_open_safe() returns a file descriptor opened with O_PATH after
881 * verifying that the path doesn't contain unsafe transitions, except
882 * for its final component as the function does not follow symlink. */
886 if (!path_is_normalized(path
))
887 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
888 "Failed to open invalid path '%s'.",
891 r
= chase_symlinks(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
892 if (r
< 0 && r
!= -ENOLINK
)
893 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
895 return r
< 0 ? r
: fd
;
898 static int path_set_perms(Item
*i
, const char *path
) {
899 _cleanup_close_
int fd
= -1;
904 fd
= path_open_safe(path
);
908 return fd_set_perms(i
, fd
, path
, NULL
);
911 static int parse_xattrs_from_arg(Item
*i
) {
921 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
923 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
925 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
929 r
= split_pair(xattr
, "=", &name
, &value
);
931 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
935 if (isempty(name
) || isempty(value
)) {
936 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
940 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
949 static int fd_set_xattrs(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
950 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
951 char **name
, **value
;
957 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
959 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
960 log_debug("Setting extended attribute '%s=%s' on %s.", *name
, *value
, path
);
961 if (setxattr(procfs_path
, *name
, *value
, strlen(*value
), 0) < 0)
962 return log_error_errno(errno
, "Setting extended attribute %s=%s on %s failed: %m",
963 *name
, *value
, path
);
968 static int path_set_xattrs(Item
*i
, const char *path
) {
969 _cleanup_close_
int fd
= -1;
974 fd
= path_open_safe(path
);
978 return fd_set_xattrs(i
, fd
, path
, NULL
);
981 static int parse_acls_from_arg(Item
*item
) {
987 /* If append_or_force (= modify) is set, we will not modify the acl
988 * afterwards, so the mask can be added now if necessary. */
990 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_default
, !item
->append_or_force
);
992 log_warning_errno(r
, "Failed to parse ACL \"%s\": %m. Ignoring", item
->argument
);
994 log_warning_errno(SYNTHETIC_ERRNO(ENOSYS
), "ACLs are not supported. Ignoring");
1001 static int path_set_acl(const char *path
, const char *pretty
, acl_type_t type
, acl_t acl
, bool modify
) {
1002 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1003 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1006 /* Returns 0 for success, positive error if already warned,
1007 * negative error otherwise. */
1010 r
= acls_for_file(path
, type
, acl
, &dup
);
1014 r
= calc_acl_mask_if_needed(&dup
);
1022 /* the mask was already added earlier if needed */
1025 r
= add_base_acls_if_needed(&dup
, path
);
1029 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1030 log_debug("Setting %s ACL %s on %s.",
1031 type
== ACL_TYPE_ACCESS
? "access" : "default",
1034 r
= acl_set_file(path
, type
, dup
);
1036 /* Return positive to indicate we already warned */
1037 return -log_error_errno(errno
,
1038 "Setting %s ACL \"%s\" on %s failed: %m",
1039 type
== ACL_TYPE_ACCESS
? "access" : "default",
1046 static int fd_set_acls(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1049 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1057 if (fstat(fd
, &stbuf
) < 0)
1058 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1062 if (hardlink_vulnerable(st
))
1063 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1064 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1067 if (S_ISLNK(st
->st_mode
)) {
1068 log_debug("Skipping ACL fix for symlink %s.", path
);
1072 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1074 if (item
->acl_access
)
1075 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1077 /* set only default acls to folders */
1078 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1079 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1082 return -r
; /* already warned */
1083 if (r
== -EOPNOTSUPP
) {
1084 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1088 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1093 static int path_set_acls(Item
*item
, const char *path
) {
1096 _cleanup_close_
int fd
= -1;
1101 fd
= path_open_safe(path
);
1105 r
= fd_set_acls(item
, fd
, path
, NULL
);
1110 static int parse_attribute_from_arg(Item
*item
) {
1112 static const struct {
1116 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1117 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1118 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1119 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1120 { 'c', FS_COMPR_FL
}, /* Compress file */
1121 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1122 { 'e', FS_EXTENT_FL
}, /* Extents */
1123 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1124 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1125 { 's', FS_SECRM_FL
}, /* Secure deletion */
1126 { 'u', FS_UNRM_FL
}, /* Undelete */
1127 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1128 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1129 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1130 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1139 unsigned value
= 0, mask
= 0;
1149 } else if (*p
== '-') {
1152 } else if (*p
== '=') {
1158 if (isempty(p
) && mode
!= MODE_SET
)
1159 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1160 "Setting file attribute on '%s' needs an attribute specification.",
1163 for (; p
&& *p
; p
++) {
1166 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1167 if (*p
== attributes
[i
].character
)
1170 if (i
>= ELEMENTSOF(attributes
))
1171 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1172 "Unknown file attribute '%c' on '%s'.",
1175 v
= attributes
[i
].value
;
1177 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1182 if (mode
== MODE_SET
)
1183 mask
|= CHATTR_ALL_FL
;
1187 item
->attribute_mask
= mask
;
1188 item
->attribute_value
= value
;
1189 item
->attribute_set
= true;
1194 static int fd_set_attribute(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1195 _cleanup_close_
int procfs_fd
= -1;
1204 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1208 if (fstat(fd
, &stbuf
) < 0)
1209 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1213 /* Issuing the file attribute ioctls on device nodes is not
1214 * safe, as that will be delivered to the drivers, not the
1215 * file system containing the device node. */
1216 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1217 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1218 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1221 f
= item
->attribute_value
& item
->attribute_mask
;
1223 /* Mask away directory-specific flags */
1224 if (!S_ISDIR(st
->st_mode
))
1225 f
&= ~FS_DIRSYNC_FL
;
1227 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1229 return log_error_errno(procfs_fd
, "Failed to re-open '%s': %m", path
);
1231 r
= chattr_fd(procfs_fd
, f
, item
->attribute_mask
, NULL
);
1233 log_full_errno(IN_SET(r
, -ENOTTY
, -EOPNOTSUPP
) ? LOG_DEBUG
: LOG_WARNING
,
1235 "Cannot set file attribute for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1236 path
, item
->attribute_value
, item
->attribute_mask
);
1241 static int path_set_attribute(Item
*item
, const char *path
) {
1242 _cleanup_close_
int fd
= -1;
1244 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1247 fd
= path_open_safe(path
);
1251 return fd_set_attribute(item
, fd
, path
, NULL
);
1254 static int write_one_file(Item
*i
, const char *path
) {
1255 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1261 assert(i
->argument
);
1262 assert(i
->type
== WRITE_FILE
);
1264 /* Validate the path and keep the fd on the directory for opening the
1265 * file so we're sure that it can't be changed behind our back. */
1266 dir_fd
= path_open_parent_safe(path
);
1270 bn
= basename(path
);
1272 flags
= O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
;
1274 /* Follows symlinks */
1275 fd
= openat(dir_fd
, bn
, i
->append_or_force
? flags
|O_APPEND
: flags
, i
->mode
);
1277 if (errno
== ENOENT
) {
1278 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1281 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1284 /* 'w' is allowed to write into any kind of files. */
1285 log_debug("Writing to \"%s\".", path
);
1287 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1289 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1291 return fd_set_perms(i
, fd
, path
, NULL
);
1294 static int create_file(Item
*i
, const char *path
) {
1295 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1296 struct stat stbuf
, *st
= NULL
;
1302 assert(i
->type
== CREATE_FILE
);
1304 /* 'f' operates on regular files exclusively. */
1306 /* Validate the path and keep the fd on the directory for opening the
1307 * file so we're sure that it can't be changed behind our back. */
1308 dir_fd
= path_open_parent_safe(path
);
1312 bn
= basename(path
);
1314 RUN_WITH_UMASK(0000) {
1315 mac_selinux_create_file_prepare(path
, S_IFREG
);
1316 fd
= openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1317 mac_selinux_create_file_clear();
1321 /* Even on a read-only filesystem, open(2) returns EEXIST if the
1322 * file already exists. It returns EROFS only if it needs to
1323 * create the file. */
1324 if (errno
!= EEXIST
)
1325 return log_error_errno(errno
, "Failed to create file %s: %m", path
);
1327 /* Re-open the file. At that point it must exist since open(2)
1328 * failed with EEXIST. We still need to check if the perms/mode
1329 * need to be changed. For read-only filesystems, we let
1330 * fd_set_perms() report the error if the perms need to be
1332 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1334 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1336 if (fstat(fd
, &stbuf
) < 0)
1337 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1339 if (!S_ISREG(stbuf
.st_mode
)) {
1340 log_error("%s exists and is not a regular file.", path
);
1347 log_debug("\"%s\" has been created.", path
);
1350 log_debug("Writing to \"%s\".", path
);
1352 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1354 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1358 return fd_set_perms(i
, fd
, path
, st
);
1361 static int truncate_file(Item
*i
, const char *path
) {
1362 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1363 struct stat stbuf
, *st
= NULL
;
1370 assert(i
->type
== TRUNCATE_FILE
);
1372 /* We want to operate on regular file exclusively especially since
1373 * O_TRUNC is unspecified if the file is neither a regular file nor a
1374 * fifo nor a terminal device. Therefore we first open the file and make
1375 * sure it's a regular one before truncating it. */
1377 /* Validate the path and keep the fd on the directory for opening the
1378 * file so we're sure that it can't be changed behind our back. */
1379 dir_fd
= path_open_parent_safe(path
);
1383 bn
= basename(path
);
1385 RUN_WITH_UMASK(0000) {
1386 mac_selinux_create_file_prepare(path
, S_IFREG
);
1387 fd
= openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1388 mac_selinux_create_file_clear();
1393 return log_error_errno(errno
, "Failed to open/create file %s: %m", path
);
1395 /* On a read-only filesystem, we don't want to fail if the
1396 * target is already empty and the perms are set. So we still
1397 * proceed with the sanity checks and let the remaining
1398 * operations fail with EROFS if they try to modify the target
1401 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1403 if (errno
== ENOENT
) {
1404 log_error("Cannot create file %s on a read-only file system.", path
);
1408 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1414 if (fstat(fd
, &stbuf
) < 0)
1415 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1417 if (!S_ISREG(stbuf
.st_mode
)) {
1418 log_error("%s exists and is not a regular file.", path
);
1422 if (stbuf
.st_size
> 0) {
1423 if (ftruncate(fd
, 0) < 0) {
1424 r
= erofs
? -EROFS
: -errno
;
1425 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1430 log_debug("\"%s\" has been created.", path
);
1433 log_debug("Writing to \"%s\".", path
);
1435 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1437 r
= erofs
? -EROFS
: r
;
1438 return log_error_errno(r
, "Failed to write file %s: %m", path
);
1442 return fd_set_perms(i
, fd
, path
, st
);
1445 static int copy_files(Item
*i
) {
1446 _cleanup_close_
int dfd
= -1, fd
= -1;
1450 log_debug("Copying tree \"%s\" to \"%s\".", i
->argument
, i
->path
);
1452 bn
= basename(i
->path
);
1454 /* Validate the path and use the returned directory fd for copying the
1455 * target so we're sure that the path can't be changed behind our
1457 dfd
= path_open_parent_safe(i
->path
);
1461 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1463 i
->uid_set
? i
->uid
: UID_INVALID
,
1464 i
->gid_set
? i
->gid
: GID_INVALID
,
1465 COPY_REFLINK
| COPY_MERGE_EMPTY
);
1469 /* If the target already exists on read-only filesystems, trying
1470 * to create the target will not fail with EEXIST but with
1472 if (r
== -EROFS
&& faccessat(dfd
, bn
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0)
1476 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1478 if (stat(i
->argument
, &a
) < 0)
1479 return log_error_errno(errno
, "stat(%s) failed: %m", i
->argument
);
1481 if (fstatat(dfd
, bn
, &b
, AT_SYMLINK_NOFOLLOW
) < 0)
1482 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1484 if ((a
.st_mode
^ b
.st_mode
) & S_IFMT
) {
1485 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1490 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1492 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1494 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1502 _CREATION_MODE_INVALID
= -1
1505 static const char *const creation_mode_verb_table
[_CREATION_MODE_MAX
] = {
1506 [CREATION_NORMAL
] = "Created",
1507 [CREATION_EXISTING
] = "Found existing",
1508 [CREATION_FORCE
] = "Created replacement",
1511 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb
, CreationMode
);
1513 static int create_directory_or_subvolume(const char *path
, mode_t mode
, bool subvol
, CreationMode
*creation
) {
1514 _cleanup_close_
int pfd
= -1;
1523 pfd
= path_open_parent_safe(path
);
1528 if (btrfs_is_subvol(empty_to_root(arg_root
)) <= 0)
1530 /* Don't create a subvolume unless the root directory is
1531 * one, too. We do this under the assumption that if the
1532 * root directory is just a plain directory (i.e. very
1533 * light-weight), we shouldn't try to split it up into
1534 * subvolumes (i.e. more heavy-weight). Thus, chroot()
1535 * environments and suchlike will get a full brtfs
1536 * subvolume set up below their tree only if they
1537 * specifically set up a btrfs subvolume for the root
1542 RUN_WITH_UMASK((~mode
) & 0777)
1543 r
= btrfs_subvol_make_fd(pfd
, basename(path
));
1548 if (!subvol
|| r
== -ENOTTY
)
1549 RUN_WITH_UMASK(0000)
1550 r
= mkdirat_label(pfd
, basename(path
), mode
);
1555 if (!IN_SET(r
, -EEXIST
, -EROFS
))
1556 return log_error_errno(r
, "Failed to create directory or subvolume \"%s\": %m", path
);
1559 if (k
== -ENOENT
&& r
== -EROFS
)
1560 return log_error_errno(r
, "%s does not exist and cannot be created as the file system is read-only.", path
);
1562 return log_error_errno(k
, "Failed to check if %s exists: %m", path
);
1564 log_warning("\"%s\" already exists and is not a directory.", path
);
1568 *creation
= CREATION_EXISTING
;
1570 *creation
= CREATION_NORMAL
;
1572 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(*creation
), path
);
1574 r
= openat(pfd
, basename(path
), O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
1576 return log_error_errno(errno
, "Failed to open directory '%s': %m", basename(path
));
1581 static int create_directory(Item
*i
, const char *path
) {
1582 _cleanup_close_
int fd
= -1;
1585 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
1587 fd
= create_directory_or_subvolume(path
, i
->mode
, false, NULL
);
1593 return fd_set_perms(i
, fd
, path
, NULL
);
1596 static int create_subvolume(Item
*i
, const char *path
) {
1597 _cleanup_close_
int fd
= -1;
1598 CreationMode creation
;
1602 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
1604 fd
= create_directory_or_subvolume(path
, i
->mode
, true, &creation
);
1610 if (creation
== CREATION_NORMAL
&&
1611 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
1612 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
1614 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
1615 else if (r
== -EROFS
)
1616 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
1617 else if (r
== -ENOPROTOOPT
)
1618 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
1620 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
1622 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
1624 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
1627 r
= fd_set_perms(i
, fd
, path
, NULL
);
1628 if (q
< 0) /* prefer the quota change error from above */
1634 static int empty_directory(Item
*i
, const char *path
) {
1638 assert(i
->type
== EMPTY_DIRECTORY
);
1640 r
= is_dir(path
, false);
1642 /* Option "e" operates only on existing objects. Do not
1643 * print errors about non-existent files or directories */
1644 log_debug("Skipping missing directory: %s", path
);
1648 return log_error_errno(r
, "is_dir() failed on path %s: %m", path
);
1650 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1651 "'%s' already exists and is not a directory.",
1654 return path_set_perms(i
, path
);
1657 static int create_device(Item
*i
, mode_t file_type
) {
1658 _cleanup_close_
int dfd
= -1, fd
= -1;
1659 CreationMode creation
;
1664 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
1666 bn
= basename(i
->path
);
1668 /* Validate the path and use the returned directory fd for copying the
1669 * target so we're sure that the path can't be changed behind our
1671 dfd
= path_open_parent_safe(i
->path
);
1675 RUN_WITH_UMASK(0000) {
1676 mac_selinux_create_file_prepare(i
->path
, file_type
);
1677 r
= mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
1678 mac_selinux_create_file_clear();
1684 if (errno
== EPERM
) {
1685 log_debug("We lack permissions, possibly because of cgroup configuration; "
1686 "skipping creation of device node %s.", i
->path
);
1690 if (errno
!= EEXIST
)
1691 return log_error_errno(errno
, "Failed to create device node %s: %m", i
->path
);
1693 if (fstatat(dfd
, bn
, &st
, 0) < 0)
1694 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1696 if ((st
.st_mode
& S_IFMT
) != file_type
) {
1698 if (i
->append_or_force
) {
1700 RUN_WITH_UMASK(0000) {
1701 mac_selinux_create_file_prepare(i
->path
, file_type
);
1702 /* FIXME: need to introduce mknodat_atomic() */
1703 r
= mknod_atomic(i
->path
, i
->mode
| file_type
, i
->major_minor
);
1704 mac_selinux_create_file_clear();
1708 return log_error_errno(r
, "Failed to create device node \"%s\": %m", i
->path
);
1709 creation
= CREATION_FORCE
;
1711 log_debug("%s is not a device node.", i
->path
);
1715 creation
= CREATION_EXISTING
;
1717 creation
= CREATION_NORMAL
;
1719 log_debug("%s %s device node \"%s\" %u:%u.",
1720 creation_mode_verb_to_string(creation
),
1721 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
1722 i
->path
, major(i
->mode
), minor(i
->mode
));
1724 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1726 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1728 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1731 static int create_fifo(Item
*i
, const char *path
) {
1732 _cleanup_close_
int pfd
= -1, fd
= -1;
1733 CreationMode creation
;
1738 pfd
= path_open_parent_safe(path
);
1742 bn
= basename(path
);
1744 RUN_WITH_UMASK(0000) {
1745 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1746 r
= mkfifoat(pfd
, bn
, i
->mode
);
1747 mac_selinux_create_file_clear();
1751 if (errno
!= EEXIST
)
1752 return log_error_errno(errno
, "Failed to create fifo %s: %m", path
);
1754 if (fstatat(pfd
, bn
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
1755 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1757 if (!S_ISFIFO(st
.st_mode
)) {
1759 if (i
->append_or_force
) {
1760 RUN_WITH_UMASK(0000) {
1761 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1762 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
1763 mac_selinux_create_file_clear();
1767 return log_error_errno(r
, "Failed to create fifo %s: %m", path
);
1768 creation
= CREATION_FORCE
;
1770 log_warning("\"%s\" already exists and is not a fifo.", path
);
1774 creation
= CREATION_EXISTING
;
1776 creation
= CREATION_NORMAL
;
1778 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), path
);
1780 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1782 return log_error_errno(errno
, "Failed to openat(%s): %m", path
);
1784 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1787 typedef int (*action_t
)(Item
*i
, const char *path
);
1788 typedef int (*fdaction_t
)(Item
*i
, int fd
, const char *path
, const struct stat
*st
);
1790 static int item_do(Item
*i
, int fd
, const char *path
, fdaction_t action
) {
1798 if (fstat(fd
, &st
) < 0) {
1799 r
= log_error_errno(errno
, "fstat() on file failed: %m");
1803 /* This returns the first error we run into, but nevertheless
1805 r
= action(i
, fd
, path
, &st
);
1807 if (S_ISDIR(st
.st_mode
)) {
1808 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1809 _cleanup_closedir_
DIR *d
= NULL
;
1812 /* The passed 'fd' was opened with O_PATH. We need to convert
1813 * it into a 'regular' fd before reading the directory content. */
1814 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1816 d
= opendir(procfs_path
);
1818 log_error_errno(errno
, "Failed to opendir() '%s': %m", procfs_path
);
1824 FOREACH_DIRENT_ALL(de
, d
, q
= -errno
; goto finish
) {
1827 if (dot_or_dot_dot(de
->d_name
))
1830 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1832 q
= log_error_errno(errno
, "Failed to open() file '%s': %m", de
->d_name
);
1834 _cleanup_free_
char *de_path
= NULL
;
1836 de_path
= path_join(path
, de
->d_name
);
1840 /* Pass ownership of dirent fd over */
1841 q
= item_do(i
, de_fd
, de_path
, action
);
1844 if (q
< 0 && r
== 0)
1853 static int glob_item(Item
*i
, action_t action
) {
1854 _cleanup_globfree_ glob_t g
= {
1855 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1860 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1861 if (k
< 0 && k
!= -ENOENT
)
1862 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1864 STRV_FOREACH(fn
, g
.gl_pathv
) {
1866 if (k
< 0 && r
== 0)
1873 static int glob_item_recursively(Item
*i
, fdaction_t action
) {
1874 _cleanup_globfree_ glob_t g
= {
1875 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1880 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1881 if (k
< 0 && k
!= -ENOENT
)
1882 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1884 STRV_FOREACH(fn
, g
.gl_pathv
) {
1885 _cleanup_close_
int fd
= -1;
1887 /* Make sure we won't trigger/follow file object (such as
1888 * device nodes, automounts, ...) pointed out by 'fn' with
1889 * O_PATH. Note, when O_PATH is used, flags other than
1890 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1892 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
1894 log_error_errno(errno
, "Opening '%s' failed: %m", *fn
);
1900 k
= item_do(i
, fd
, *fn
, action
);
1901 if (k
< 0 && r
== 0)
1904 /* we passed fd ownership to the previous call */
1911 static int create_item(Item
*i
) {
1912 CreationMode creation
;
1917 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
1922 case IGNORE_DIRECTORY_PATH
:
1924 case RECURSIVE_REMOVE_PATH
:
1928 RUN_WITH_UMASK(0000)
1929 (void) mkdir_parents_label(i
->path
, 0755);
1931 r
= create_file(i
, i
->path
);
1937 RUN_WITH_UMASK(0000)
1938 (void) mkdir_parents_label(i
->path
, 0755);
1940 r
= truncate_file(i
, i
->path
);
1946 RUN_WITH_UMASK(0000)
1947 (void) mkdir_parents_label(i
->path
, 0755);
1955 r
= glob_item(i
, write_one_file
);
1961 case CREATE_DIRECTORY
:
1962 case TRUNCATE_DIRECTORY
:
1963 RUN_WITH_UMASK(0000)
1964 (void) mkdir_parents_label(i
->path
, 0755);
1966 r
= create_directory(i
, i
->path
);
1971 case CREATE_SUBVOLUME
:
1972 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
1973 case CREATE_SUBVOLUME_NEW_QUOTA
:
1974 RUN_WITH_UMASK(0000)
1975 (void) mkdir_parents_label(i
->path
, 0755);
1977 r
= create_subvolume(i
, i
->path
);
1982 case EMPTY_DIRECTORY
:
1983 r
= glob_item(i
, empty_directory
);
1989 RUN_WITH_UMASK(0000)
1990 (void) mkdir_parents_label(i
->path
, 0755);
1992 r
= create_fifo(i
, i
->path
);
1997 case CREATE_SYMLINK
: {
1998 RUN_WITH_UMASK(0000)
1999 (void) mkdir_parents_label(i
->path
, 0755);
2001 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2002 r
= symlink(i
->argument
, i
->path
);
2003 mac_selinux_create_file_clear();
2006 _cleanup_free_
char *x
= NULL
;
2008 if (errno
!= EEXIST
)
2009 return log_error_errno(errno
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2011 r
= readlink_malloc(i
->path
, &x
);
2012 if (r
< 0 || !streq(i
->argument
, x
)) {
2014 if (i
->append_or_force
) {
2015 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2016 r
= symlink_atomic(i
->argument
, i
->path
);
2017 mac_selinux_create_file_clear();
2019 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2020 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
2022 return log_error_errno(r
, "rm -fr %s failed: %m", i
->path
);
2024 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2025 r
= symlink(i
->argument
, i
->path
) < 0 ? -errno
: 0;
2026 mac_selinux_create_file_clear();
2029 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2031 creation
= CREATION_FORCE
;
2033 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2037 creation
= CREATION_EXISTING
;
2040 creation
= CREATION_NORMAL
;
2041 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2045 case CREATE_BLOCK_DEVICE
:
2046 case CREATE_CHAR_DEVICE
:
2047 if (have_effective_cap(CAP_MKNOD
) == 0) {
2048 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2049 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2051 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2055 RUN_WITH_UMASK(0000)
2056 (void) mkdir_parents_label(i
->path
, 0755);
2058 r
= create_device(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2066 r
= glob_item(i
, path_set_perms
);
2071 case RECURSIVE_RELABEL_PATH
:
2072 r
= glob_item_recursively(i
, fd_set_perms
);
2078 r
= glob_item(i
, path_set_xattrs
);
2083 case RECURSIVE_SET_XATTR
:
2084 r
= glob_item_recursively(i
, fd_set_xattrs
);
2090 r
= glob_item(i
, path_set_acls
);
2095 case RECURSIVE_SET_ACL
:
2096 r
= glob_item_recursively(i
, fd_set_acls
);
2102 r
= glob_item(i
, path_set_attribute
);
2107 case RECURSIVE_SET_ATTRIBUTE
:
2108 r
= glob_item_recursively(i
, fd_set_attribute
);
2117 static int remove_item_instance(Item
*i
, const char *instance
) {
2125 if (remove(instance
) < 0 && errno
!= ENOENT
)
2126 return log_error_errno(errno
, "rm(%s): %m", instance
);
2130 case RECURSIVE_REMOVE_PATH
:
2131 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2132 log_debug("rm -rf \"%s\"", instance
);
2133 r
= rm_rf(instance
, REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
);
2134 if (r
< 0 && r
!= -ENOENT
)
2135 return log_error_errno(r
, "rm_rf(%s): %m", instance
);
2140 assert_not_reached("wut?");
2146 static int remove_item(Item
*i
) {
2151 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
2155 case TRUNCATE_DIRECTORY
:
2156 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2157 log_debug("rm -rf \"%s\"", i
->path
);
2158 r
= rm_rf(i
->path
, REMOVE_PHYSICAL
);
2159 if (r
< 0 && r
!= -ENOENT
)
2160 return log_error_errno(r
, "rm_rf(%s): %m", i
->path
);
2165 case RECURSIVE_REMOVE_PATH
:
2166 return glob_item(i
, remove_item_instance
);
2173 static int clean_item_instance(Item
*i
, const char* instance
) {
2174 _cleanup_closedir_
DIR *d
= NULL
;
2178 char timestamp
[FORMAT_TIMESTAMP_MAX
];
2185 n
= now(CLOCK_REALTIME
);
2189 cutoff
= n
- i
->age
;
2191 d
= opendir_nomod(instance
);
2193 if (IN_SET(errno
, ENOENT
, ENOTDIR
)) {
2194 log_debug_errno(errno
, "Directory \"%s\": %m", instance
);
2198 return log_error_errno(errno
, "Failed to open directory %s: %m", instance
);
2201 if (fstat(dirfd(d
), &s
) < 0)
2202 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
2204 if (!S_ISDIR(s
.st_mode
))
2205 return log_error_errno(SYNTHETIC_ERRNO(ENOTDIR
),
2206 "%s is not a directory.", i
->path
);
2208 if (fstatat(dirfd(d
), "..", &ps
, AT_SYMLINK_NOFOLLOW
) != 0)
2209 return log_error_errno(errno
, "stat(%s/..) failed: %m", i
->path
);
2211 mountpoint
= s
.st_dev
!= ps
.st_dev
|| s
.st_ino
== ps
.st_ino
;
2213 log_debug("Cleanup threshold for %s \"%s\" is %s",
2214 mountpoint
? "mount point" : "directory",
2216 format_timestamp_us(timestamp
, sizeof(timestamp
), cutoff
));
2218 return dir_cleanup(i
, instance
, d
, &s
, cutoff
, s
.st_dev
, mountpoint
,
2219 MAX_DEPTH
, i
->keep_first_level
);
2222 static int clean_item(Item
*i
) {
2225 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
2228 case CREATE_DIRECTORY
:
2229 case CREATE_SUBVOLUME
:
2230 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2231 case CREATE_SUBVOLUME_NEW_QUOTA
:
2232 case TRUNCATE_DIRECTORY
:
2235 clean_item_instance(i
, i
->path
);
2237 case EMPTY_DIRECTORY
:
2238 case IGNORE_DIRECTORY_PATH
:
2239 return glob_item(i
, clean_item_instance
);
2245 static int process_item(Item
*i
, OperationMask operation
) {
2251 todo
= operation
& ~i
->done
;
2252 if (todo
== 0) /* Everything already done? */
2255 i
->done
|= operation
;
2257 r
= chase_symlinks(i
->path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_WARN
, NULL
, NULL
);
2258 if (r
== -EREMOTE
) {
2259 log_notice_errno(r
, "Skipping %s", i
->path
);
2263 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
2265 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(i
) : 0;
2266 /* Failure can only be tolerated for create */
2267 if (i
->allow_failure
)
2270 q
= FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(i
) : 0;
2271 p
= FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(i
) : 0;
2278 static int process_item_array(ItemArray
*array
, OperationMask operation
) {
2284 /* Create any parent first. */
2285 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
2286 r
= process_item_array(array
->parent
, operation
& OPERATION_CREATE
);
2288 /* Clean up all children first */
2289 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
)) && !set_isempty(array
->children
)) {
2293 SET_FOREACH(c
, array
->children
, i
) {
2296 k
= process_item_array(c
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
));
2297 if (k
< 0 && r
== 0)
2302 for (n
= 0; n
< array
->n_items
; n
++) {
2305 k
= process_item(array
->items
+ n
, operation
);
2306 if (k
< 0 && r
== 0)
2313 static void item_free_contents(Item
*i
) {
2317 strv_free(i
->xattrs
);
2320 acl_free(i
->acl_access
);
2321 acl_free(i
->acl_default
);
2325 static ItemArray
* item_array_free(ItemArray
*a
) {
2331 for (n
= 0; n
< a
->n_items
; n
++)
2332 item_free_contents(a
->items
+ n
);
2334 set_free(a
->children
);
2339 static int item_compare(const Item
*a
, const Item
*b
) {
2340 /* Make sure that the ownership taking item is put first, so
2341 * that we first create the node, and then can adjust it */
2343 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
2345 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
2348 return CMP(a
->type
, b
->type
);
2351 static bool item_compatible(Item
*a
, Item
*b
) {
2354 assert(streq(a
->path
, b
->path
));
2356 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
2357 /* check if the items are the same */
2358 return streq_ptr(a
->argument
, b
->argument
) &&
2360 a
->uid_set
== b
->uid_set
&&
2363 a
->gid_set
== b
->gid_set
&&
2366 a
->mode_set
== b
->mode_set
&&
2367 a
->mode
== b
->mode
&&
2369 a
->age_set
== b
->age_set
&&
2372 a
->mask_perms
== b
->mask_perms
&&
2374 a
->keep_first_level
== b
->keep_first_level
&&
2376 a
->major_minor
== b
->major_minor
;
2381 static bool should_include_path(const char *path
) {
2384 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
2385 if (path_startswith(path
, *prefix
)) {
2386 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2391 STRV_FOREACH(prefix
, arg_include_prefixes
)
2392 if (path_startswith(path
, *prefix
)) {
2393 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
2397 /* no matches, so we should include this path only if we
2398 * have no whitelist at all */
2399 if (strv_isempty(arg_include_prefixes
))
2402 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
2406 static int specifier_expansion_from_arg(Item
*i
) {
2407 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
2418 case CREATE_SYMLINK
:
2422 r
= cunescape(i
->argument
, 0, &unescaped
);
2424 return log_error_errno(r
, "Failed to unescape parameter to write: %s", i
->argument
);
2426 r
= specifier_printf(unescaped
, specifier_table
, NULL
, &resolved
);
2430 free_and_replace(i
->argument
, resolved
);
2434 case RECURSIVE_SET_XATTR
:
2437 STRV_FOREACH (xattr
, i
->xattrs
) {
2438 r
= specifier_printf(*xattr
, specifier_table
, NULL
, &resolved
);
2442 free_and_replace(*xattr
, resolved
);
2452 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
2459 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2460 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2461 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2462 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2463 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2464 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2465 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2466 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2467 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2469 k
= path_startswith(*path
, "/var/run/");
2470 if (isempty(k
)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2473 n
= path_join("/run", k
);
2477 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2478 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2479 * to the user, let's still inform the user that these snippets should really be updated. */
2480 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0, "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.", *path
, n
);
2482 free_and_replace(*path
, n
);
2487 static int parse_line(const char *fname
, unsigned line
, const char *buffer
, bool *invalid_config
) {
2489 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
2490 _cleanup_(item_free_contents
) Item i
= {};
2491 ItemArray
*existing
;
2494 bool append_or_force
= false, boot
= false, allow_failure
= false;
2500 r
= extract_many_words(
2512 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2513 /* invalid quoting and such or an unknown specifier */
2514 *invalid_config
= true;
2515 return log_error_errno(r
, "[%s:%u] Failed to parse line: %m", fname
, line
);
2517 *invalid_config
= true;
2518 log_error("[%s:%u] Syntax error.", fname
, line
);
2522 if (!empty_or_dash(buffer
)) {
2523 i
.argument
= strdup(buffer
);
2528 if (isempty(action
)) {
2529 *invalid_config
= true;
2530 log_error("[%s:%u] Command too short '%s'.", fname
, line
, action
);
2534 for (pos
= 1; action
[pos
]; pos
++) {
2535 if (action
[pos
] == '!' && !boot
)
2537 else if (action
[pos
] == '+' && !append_or_force
)
2538 append_or_force
= true;
2539 else if (action
[pos
] == '-' && !allow_failure
)
2540 allow_failure
= true;
2542 *invalid_config
= true;
2543 log_error("[%s:%u] Unknown modifiers in command '%s'",
2544 fname
, line
, action
);
2549 if (boot
&& !arg_boot
) {
2550 log_debug("Ignoring entry %s \"%s\" because --boot is not specified.",
2556 i
.append_or_force
= append_or_force
;
2557 i
.allow_failure
= allow_failure
;
2559 r
= specifier_printf(path
, specifier_table
, NULL
, &i
.path
);
2561 return log_unresolvable_specifier(fname
, line
);
2563 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2564 *invalid_config
= true;
2565 return log_error_errno(r
, "[%s:%u] Failed to replace specifiers: %s", fname
, line
, path
);
2568 r
= patch_var_run(fname
, line
, &i
.path
);
2574 case CREATE_DIRECTORY
:
2575 case CREATE_SUBVOLUME
:
2576 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2577 case CREATE_SUBVOLUME_NEW_QUOTA
:
2578 case EMPTY_DIRECTORY
:
2579 case TRUNCATE_DIRECTORY
:
2582 case IGNORE_DIRECTORY_PATH
:
2584 case RECURSIVE_REMOVE_PATH
:
2587 case RECURSIVE_RELABEL_PATH
:
2589 log_warning("[%s:%u] %c lines don't take argument fields, ignoring.", fname
, line
, i
.type
);
2597 case CREATE_SYMLINK
:
2599 i
.argument
= path_join("/usr/share/factory", i
.path
);
2607 *invalid_config
= true;
2608 log_error("[%s:%u] Write file requires argument.", fname
, line
);
2615 i
.argument
= path_join(arg_root
, "/usr/share/factory", i
.path
);
2619 } else if (!path_is_absolute(i
.argument
)) {
2620 *invalid_config
= true;
2621 log_error("[%s:%u] Source path is not absolute.", fname
, line
);
2624 } else if (arg_root
) {
2627 p
= path_join(arg_root
, i
.argument
);
2630 free_and_replace(i
.argument
, p
);
2633 path_simplify(i
.argument
, false);
2636 case CREATE_CHAR_DEVICE
:
2637 case CREATE_BLOCK_DEVICE
:
2639 *invalid_config
= true;
2640 log_error("[%s:%u] Device file requires argument.", fname
, line
);
2644 r
= parse_dev(i
.argument
, &i
.major_minor
);
2646 *invalid_config
= true;
2647 log_error_errno(r
, "[%s:%u] Can't parse device file major/minor '%s'.", fname
, line
, i
.argument
);
2654 case RECURSIVE_SET_XATTR
:
2656 *invalid_config
= true;
2657 log_error("[%s:%u] Set extended attribute requires argument.", fname
, line
);
2660 r
= parse_xattrs_from_arg(&i
);
2666 case RECURSIVE_SET_ACL
:
2668 *invalid_config
= true;
2669 log_error("[%s:%u] Set ACLs requires argument.", fname
, line
);
2672 r
= parse_acls_from_arg(&i
);
2678 case RECURSIVE_SET_ATTRIBUTE
:
2680 *invalid_config
= true;
2681 log_error("[%s:%u] Set file attribute requires argument.", fname
, line
);
2684 r
= parse_attribute_from_arg(&i
);
2685 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2686 *invalid_config
= true;
2692 log_error("[%s:%u] Unknown command type '%c'.", fname
, line
, (char) i
.type
);
2693 *invalid_config
= true;
2697 if (!path_is_absolute(i
.path
)) {
2698 log_error("[%s:%u] Path '%s' not absolute.", fname
, line
, i
.path
);
2699 *invalid_config
= true;
2703 path_simplify(i
.path
, false);
2705 if (!should_include_path(i
.path
))
2708 r
= specifier_expansion_from_arg(&i
);
2710 return log_unresolvable_specifier(fname
, line
);
2712 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2713 *invalid_config
= true;
2714 return log_error_errno(r
, "[%s:%u] Failed to substitute specifiers in argument: %m",
2721 p
= path_join(arg_root
, i
.path
);
2724 free_and_replace(i
.path
, p
);
2727 if (!empty_or_dash(user
)) {
2728 const char *u
= user
;
2730 r
= get_user_creds(&u
, &i
.uid
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
2732 *invalid_config
= true;
2733 return log_error_errno(r
, "[%s:%u] Unknown user '%s'.", fname
, line
, user
);
2739 if (!empty_or_dash(group
)) {
2740 const char *g
= group
;
2742 r
= get_group_creds(&g
, &i
.gid
, USER_CREDS_ALLOW_MISSING
);
2744 *invalid_config
= true;
2745 log_error("[%s:%u] Unknown group '%s'.", fname
, line
, group
);
2752 if (!empty_or_dash(mode
)) {
2753 const char *mm
= mode
;
2757 i
.mask_perms
= true;
2761 if (parse_mode(mm
, &m
) < 0) {
2762 *invalid_config
= true;
2763 log_error("[%s:%u] Invalid mode '%s'.", fname
, line
, mode
);
2770 i
.mode
= IN_SET(i
.type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
2772 if (!empty_or_dash(age
)) {
2773 const char *a
= age
;
2776 i
.keep_first_level
= true;
2780 if (parse_sec(a
, &i
.age
) < 0) {
2781 *invalid_config
= true;
2782 log_error("[%s:%u] Invalid age '%s'.", fname
, line
, age
);
2789 h
= needs_glob(i
.type
) ? globs
: items
;
2791 existing
= ordered_hashmap_get(h
, i
.path
);
2795 for (n
= 0; n
< existing
->n_items
; n
++) {
2796 if (!item_compatible(existing
->items
+ n
, &i
) && !i
.append_or_force
) {
2797 log_notice("[%s:%u] Duplicate line for path \"%s\", ignoring.",
2798 fname
, line
, i
.path
);
2803 existing
= new0(ItemArray
, 1);
2807 r
= ordered_hashmap_put(h
, i
.path
, existing
);
2814 if (!GREEDY_REALLOC(existing
->items
, existing
->allocated
, existing
->n_items
+ 1))
2817 existing
->items
[existing
->n_items
++] = i
;
2818 i
= (struct Item
) {};
2820 /* Sort item array, to enforce stable ordering of application */
2821 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
2826 static int cat_config(char **config_dirs
, char **args
) {
2827 _cleanup_strv_free_
char **files
= NULL
;
2830 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
2834 return cat_files(NULL
, files
, 0);
2837 static int help(void) {
2838 _cleanup_free_
char *link
= NULL
;
2841 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
2845 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2846 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
2847 " -h --help Show this help\n"
2848 " --user Execute user configuration\n"
2849 " --version Show package version\n"
2850 " --cat-config Show configuration files\n"
2851 " --create Create marked files/directories\n"
2852 " --clean Clean up marked directories\n"
2853 " --remove Remove marked files/directories\n"
2854 " --boot Execute actions only safe at boot\n"
2855 " --prefix=PATH Only apply rules with the specified prefix\n"
2856 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
2857 " --root=PATH Operate on an alternate filesystem root\n"
2858 " --replace=PATH Treat arguments as replacement for PATH\n"
2859 " --no-pager Do not pipe output into a pager\n"
2860 "\nSee the %s for details.\n"
2861 , program_invocation_short_name
2868 static int parse_argv(int argc
, char *argv
[]) {
2871 ARG_VERSION
= 0x100,
2885 static const struct option options
[] = {
2886 { "help", no_argument
, NULL
, 'h' },
2887 { "user", no_argument
, NULL
, ARG_USER
},
2888 { "version", no_argument
, NULL
, ARG_VERSION
},
2889 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
2890 { "create", no_argument
, NULL
, ARG_CREATE
},
2891 { "clean", no_argument
, NULL
, ARG_CLEAN
},
2892 { "remove", no_argument
, NULL
, ARG_REMOVE
},
2893 { "boot", no_argument
, NULL
, ARG_BOOT
},
2894 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
2895 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
2896 { "root", required_argument
, NULL
, ARG_ROOT
},
2897 { "replace", required_argument
, NULL
, ARG_REPLACE
},
2898 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2907 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2917 case ARG_CAT_CONFIG
:
2918 arg_cat_config
= true;
2926 arg_operation
|= OPERATION_CREATE
;
2930 arg_operation
|= OPERATION_CLEAN
;
2934 arg_operation
|= OPERATION_REMOVE
;
2942 if (strv_push(&arg_include_prefixes
, optarg
) < 0)
2946 case ARG_EXCLUDE_PREFIX
:
2947 if (strv_push(&arg_exclude_prefixes
, optarg
) < 0)
2952 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
2958 if (!path_is_absolute(optarg
) ||
2959 !endswith(optarg
, ".conf"))
2960 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2961 "The argument to --replace= must an absolute path to a config file");
2963 arg_replace
= optarg
;
2967 arg_pager_flags
|= PAGER_DISABLE
;
2974 assert_not_reached("Unhandled option");
2977 if (arg_operation
== 0 && !arg_cat_config
)
2978 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2979 "You need to specify at least one of --clean, --create or --remove.");
2981 if (arg_replace
&& arg_cat_config
)
2982 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2983 "Option --replace= is not supported with --cat-config");
2985 if (arg_replace
&& optind
>= argc
)
2986 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
2987 "When --replace= is given, some configuration items must be specified");
2992 static int read_config_file(char **config_dirs
, const char *fn
, bool ignore_enoent
, bool *invalid_config
) {
2993 _cleanup_fclose_
FILE *_f
= NULL
;
3002 if (streq(fn
, "-")) {
3003 log_debug("Reading config from stdin…");
3007 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &_f
);
3009 if (ignore_enoent
&& r
== -ENOENT
) {
3010 log_debug_errno(r
, "Failed to open \"%s\", ignoring: %m", fn
);
3014 return log_error_errno(r
, "Failed to open '%s': %m", fn
);
3016 log_debug("Reading config file \"%s\"…", fn
);
3021 _cleanup_free_
char *line
= NULL
;
3022 bool invalid_line
= false;
3026 k
= read_line(f
, LONG_LINE_MAX
, &line
);
3028 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
3035 if (IN_SET(*l
, 0, '#'))
3038 k
= parse_line(fn
, v
, l
, &invalid_line
);
3041 /* Allow reporting with a special code if the caller requested this */
3042 *invalid_config
= true;
3044 /* The first error becomes our return value */
3049 /* we have to determine age parameter for each entry of type X */
3050 ORDERED_HASHMAP_FOREACH(i
, globs
, iterator
) {
3052 Item
*j
, *candidate_item
= NULL
;
3054 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
3057 ORDERED_HASHMAP_FOREACH(j
, items
, iter
) {
3058 if (!IN_SET(j
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
))
3061 if (path_equal(j
->path
, i
->path
)) {
3066 if ((!candidate_item
&& path_startswith(i
->path
, j
->path
)) ||
3067 (candidate_item
&& path_startswith(j
->path
, candidate_item
->path
) && (fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)))
3071 if (candidate_item
&& candidate_item
->age_set
) {
3072 i
->age
= candidate_item
->age
;
3078 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
3086 static int parse_arguments(char **config_dirs
, char **args
, bool *invalid_config
) {
3090 STRV_FOREACH(arg
, args
) {
3091 r
= read_config_file(config_dirs
, *arg
, false, invalid_config
);
3099 static int read_config_files(char **config_dirs
, char **args
, bool *invalid_config
) {
3100 _cleanup_strv_free_
char **files
= NULL
;
3101 _cleanup_free_
char *p
= NULL
;
3105 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
3109 STRV_FOREACH(f
, files
)
3110 if (p
&& path_equal(*f
, p
)) {
3111 log_debug("Parsing arguments at position \"%s\"…", *f
);
3113 r
= parse_arguments(config_dirs
, args
, invalid_config
);
3117 /* Just warn, ignore result otherwise.
3118 * read_config_file() has some debug output, so no need to print anything. */
3119 (void) read_config_file(config_dirs
, *f
, true, invalid_config
);
3124 static int link_parent(ItemArray
*a
) {
3131 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
3132 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3133 * before their children, and clean up/remove children before their parents. */
3135 if (a
->n_items
<= 0)
3138 path
= a
->items
[0].path
;
3139 prefix
= newa(char, strlen(path
) + 1);
3140 PATH_FOREACH_PREFIX(prefix
, path
) {
3143 j
= ordered_hashmap_get(items
, prefix
);
3145 j
= ordered_hashmap_get(globs
, prefix
);
3147 r
= set_ensure_allocated(&j
->children
, NULL
);
3151 r
= set_put(j
->children
, a
);
3163 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
3164 ItemArray
, item_array_free
);
3166 static int run(int argc
, char *argv
[]) {
3167 _cleanup_strv_free_
char **config_dirs
= NULL
;
3168 bool invalid_config
= false;
3172 PHASE_REMOVE_AND_CLEAN
,
3178 r
= parse_argv(argc
, argv
);
3182 log_setup_service();
3184 /* Descending down file system trees might take a lot of fds */
3185 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
3188 r
= user_config_paths(&config_dirs
);
3190 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
3192 config_dirs
= strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
3197 if (DEBUG_LOGGING
) {
3198 _cleanup_free_
char *t
= NULL
;
3200 t
= strv_join(config_dirs
, "\n\t");
3202 log_debug("Looking for configuration files in (higher priority first):\n\t%s", t
);
3205 if (arg_cat_config
) {
3206 (void) pager_open(arg_pager_flags
);
3208 return cat_config(config_dirs
, argv
+ optind
);
3215 items
= ordered_hashmap_new(&item_array_hash_ops
);
3216 globs
= ordered_hashmap_new(&item_array_hash_ops
);
3217 if (!items
|| !globs
)
3220 /* If command line arguments are specified along with --replace, read all
3221 * configuration files and insert the positional arguments at the specified
3222 * place. Otherwise, if command line arguments are specified, execute just
3223 * them, and finally, without --replace= or any positional arguments, just
3224 * read configuration and execute it.
3226 if (arg_replace
|| optind
>= argc
)
3227 r
= read_config_files(config_dirs
, argv
+ optind
, &invalid_config
);
3229 r
= parse_arguments(config_dirs
, argv
+ optind
, &invalid_config
);
3233 /* Let's now link up all child/parent relationships */
3234 ORDERED_HASHMAP_FOREACH(a
, items
, iterator
) {
3239 ORDERED_HASHMAP_FOREACH(a
, globs
, iterator
) {
3245 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
3246 * operations. i.e. that we first clean out the platform we then build on. */
3247 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
3250 if (phase
== PHASE_REMOVE_AND_CLEAN
)
3251 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
3252 else if (phase
== PHASE_CREATE
)
3253 op
= arg_operation
& OPERATION_CREATE
;
3255 assert_not_reached("unexpected phase");
3257 if (op
== 0) /* Nothing requested in this phase */
3260 /* The non-globbing ones usually create things, hence we apply them first */
3261 ORDERED_HASHMAP_FOREACH(a
, items
, iterator
) {
3262 k
= process_item_array(a
, op
);
3263 if (k
< 0 && r
>= 0)
3267 /* The globbing ones usually alter things, hence we apply them second. */
3268 ORDERED_HASHMAP_FOREACH(a
, globs
, iterator
) {
3269 k
= process_item_array(a
, op
);
3270 if (k
< 0 && r
>= 0)
3275 if (ERRNO_IS_RESOURCE(-r
))
3280 return EX_CANTCREAT
;
3284 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);