1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/xattr.h>
21 #include "alloc-util.h"
22 #include "btrfs-util.h"
23 #include "capability-util.h"
24 #include "chattr-util.h"
25 #include "conf-files.h"
28 #include "dirent-util.h"
32 #include "format-util.h"
34 #include "glob-util.h"
39 #include "main-func.h"
41 #include "mountpoint-util.h"
42 #include "offline-passwd.h"
44 #include "parse-util.h"
45 #include "path-lookup.h"
46 #include "path-util.h"
47 #include "pretty-print.h"
48 #include "rlimit-util.h"
50 #include "selinux-util.h"
52 #include "sort-util.h"
53 #include "specifier.h"
54 #include "stat-util.h"
55 #include "stdio-util.h"
56 #include "string-table.h"
57 #include "string-util.h"
59 #include "umask-util.h"
60 #include "user-util.h"
62 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
63 * them in the file system. This is intended to be used to create
64 * properly owned directories beneath /tmp, /var/tmp, /run, which are
65 * volatile and hence need to be recreated on bootup. */
67 typedef enum OperationMask
{
68 OPERATION_CREATE
= 1 << 0,
69 OPERATION_REMOVE
= 1 << 1,
70 OPERATION_CLEAN
= 1 << 2,
73 typedef enum ItemType
{
74 /* These ones take file names */
76 TRUNCATE_FILE
= 'F', /* deprecated: use f+ */
77 CREATE_DIRECTORY
= 'd',
78 TRUNCATE_DIRECTORY
= 'D',
79 CREATE_SUBVOLUME
= 'v',
80 CREATE_SUBVOLUME_INHERIT_QUOTA
= 'q',
81 CREATE_SUBVOLUME_NEW_QUOTA
= 'Q',
84 CREATE_CHAR_DEVICE
= 'c',
85 CREATE_BLOCK_DEVICE
= 'b',
88 /* These ones take globs */
90 EMPTY_DIRECTORY
= 'e',
92 RECURSIVE_SET_XATTR
= 'T',
94 RECURSIVE_SET_ACL
= 'A',
96 RECURSIVE_SET_ATTRIBUTE
= 'H',
98 IGNORE_DIRECTORY_PATH
= 'X',
100 RECURSIVE_REMOVE_PATH
= 'R',
102 RECURSIVE_RELABEL_PATH
= 'Z',
103 ADJUST_MODE
= 'm', /* legacy, 'z' is identical to this */
106 typedef struct Item
{
122 unsigned attribute_value
;
123 unsigned attribute_mask
;
130 bool attribute_set
:1;
132 bool keep_first_level
:1;
134 bool append_or_force
:1;
136 bool allow_failure
:1;
141 typedef struct ItemArray
{
146 struct ItemArray
*parent
;
150 typedef enum DirectoryType
{
158 static bool arg_cat_config
= false;
159 static bool arg_user
= false;
160 static OperationMask arg_operation
= 0;
161 static bool arg_boot
= false;
162 static PagerFlags arg_pager_flags
= 0;
164 static char **arg_include_prefixes
= NULL
;
165 static char **arg_exclude_prefixes
= NULL
;
166 static char *arg_root
= NULL
;
167 static char *arg_replace
= NULL
;
169 #define MAX_DEPTH 256
171 static OrderedHashmap
*items
= NULL
, *globs
= NULL
;
172 static Set
*unix_sockets
= NULL
;
174 STATIC_DESTRUCTOR_REGISTER(items
, ordered_hashmap_freep
);
175 STATIC_DESTRUCTOR_REGISTER(globs
, ordered_hashmap_freep
);
176 STATIC_DESTRUCTOR_REGISTER(unix_sockets
, set_free_freep
);
177 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes
, freep
);
178 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes
, freep
);
179 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
181 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
);
182 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
);
184 static const Specifier specifier_table
[] = {
185 { 'm', specifier_machine_id_safe
, NULL
},
186 { 'b', specifier_boot_id
, NULL
},
187 { 'H', specifier_host_name
, NULL
},
188 { 'v', specifier_kernel_release
, NULL
},
189 { 'a', specifier_architecture
, NULL
},
190 { 'o', specifier_os_id
, NULL
},
191 { 'w', specifier_os_version_id
, NULL
},
192 { 'B', specifier_os_build_id
, NULL
},
193 { 'W', specifier_os_variant_id
, NULL
},
195 { 'g', specifier_group_name
, NULL
},
196 { 'G', specifier_group_id
, NULL
},
197 { 'U', specifier_user_id
, NULL
},
198 { 'u', specifier_user_name
, NULL
},
199 { 'h', specifier_user_home
, NULL
},
201 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
202 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
203 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
204 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
205 { 'T', specifier_tmp_dir
, NULL
},
206 { 'V', specifier_var_tmp_dir
, NULL
},
210 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
) {
213 /* If /etc/machine_id is missing or empty (e.g. in a chroot environment)
214 * return a recognizable error so that the caller can skip the rule
217 r
= specifier_machine_id(specifier
, data
, userdata
, ret
);
218 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
))
224 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
) {
230 static const struct table_entry paths_system
[] = {
231 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
232 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
233 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
234 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
237 static const struct table_entry paths_user
[] = {
238 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
239 [DIRECTORY_STATE
] = { SD_PATH_USER_CONFIGURATION
},
240 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
241 [DIRECTORY_LOGS
] = { SD_PATH_USER_CONFIGURATION
, "log" },
245 const struct table_entry
*paths
;
247 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
248 paths
= arg_user
? paths_user
: paths_system
;
250 i
= PTR_TO_UINT(data
);
251 assert(i
< ELEMENTSOF(paths_system
));
253 return sd_path_lookup(paths
[i
].type
, paths
[i
].suffix
, ret
);
256 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
257 static bool notified
= false;
259 /* In system mode, this is called when /etc is not fully initialized (e.g.
260 * in a chroot environment) where some specifiers are unresolvable. In user
261 * mode, this is called when some variables are not defined. These cases are
262 * not considered as an error so log at LOG_NOTICE only for the first time
263 * and then downgrade this to LOG_DEBUG for the rest. */
266 notified
? LOG_DEBUG
: LOG_NOTICE
,
268 "Failed to resolve specifier: %s, skipping",
269 arg_user
? "Required $XDG_... variable not defined" : "uninitialized /etc detected");
272 log_notice("All rules containing unresolvable specifiers will be skipped.");
278 static int user_config_paths(char*** ret
) {
279 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
280 _cleanup_free_
char *persistent_config
= NULL
, *runtime_config
= NULL
, *data_home
= NULL
;
281 _cleanup_strv_free_
char **res
= NULL
;
284 r
= xdg_user_dirs(&config_dirs
, &data_dirs
);
288 r
= xdg_user_config_dir(&persistent_config
, "/user-tmpfiles.d");
289 if (r
< 0 && r
!= -ENXIO
)
292 r
= xdg_user_runtime_dir(&runtime_config
, "/user-tmpfiles.d");
293 if (r
< 0 && r
!= -ENXIO
)
296 r
= xdg_user_data_dir(&data_home
, "/user-tmpfiles.d");
297 if (r
< 0 && r
!= -ENXIO
)
300 r
= strv_extend_strv_concat(&res
, config_dirs
, "/user-tmpfiles.d");
304 r
= strv_extend(&res
, persistent_config
);
308 r
= strv_extend(&res
, runtime_config
);
312 r
= strv_extend(&res
, data_home
);
316 r
= strv_extend_strv_concat(&res
, data_dirs
, "/user-tmpfiles.d");
320 r
= path_strv_make_absolute_cwd(res
);
324 *ret
= TAKE_PTR(res
);
328 static bool needs_glob(ItemType t
) {
332 IGNORE_DIRECTORY_PATH
,
334 RECURSIVE_REMOVE_PATH
,
338 RECURSIVE_RELABEL_PATH
,
344 RECURSIVE_SET_ATTRIBUTE
);
347 static bool takes_ownership(ItemType t
) {
355 CREATE_SUBVOLUME_INHERIT_QUOTA
,
356 CREATE_SUBVOLUME_NEW_QUOTA
,
364 IGNORE_DIRECTORY_PATH
,
366 RECURSIVE_REMOVE_PATH
);
369 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
373 ORDERED_HASHMAP_FOREACH(j
, h
, i
) {
376 for (n
= 0; n
< j
->n_items
; n
++) {
377 Item
*item
= j
->items
+ n
;
379 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
387 static int load_unix_sockets(void) {
388 _cleanup_set_free_free_ Set
*sockets
= NULL
;
389 _cleanup_fclose_
FILE *f
= NULL
;
395 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
397 sockets
= set_new(&path_hash_ops
);
401 f
= fopen("/proc/net/unix", "re");
403 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
404 "Failed to open /proc/net/unix, ignoring: %m");
407 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
409 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
411 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
414 _cleanup_free_
char *line
= NULL
, *s
= NULL
;
417 r
= read_line(f
, LONG_LINE_MAX
, &line
);
419 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
420 if (r
== 0) /* EOF */
423 p
= strchr(line
, ':');
431 p
+= strspn(p
, WHITESPACE
);
432 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
433 p
+= strspn(p
, WHITESPACE
);
442 path_simplify(s
, false);
444 r
= set_consume(sockets
, s
);
448 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
453 unix_sockets
= TAKE_PTR(sockets
);
457 static bool unix_socket_alive(const char *fn
) {
460 if (load_unix_sockets() < 0)
461 return true; /* We don't know, so assume yes */
463 return !!set_get(unix_sockets
, (char*) fn
);
466 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
469 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
473 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
477 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
479 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
484 static DIR* opendir_nomod(const char *path
) {
485 return xopendirat_nomod(AT_FDCWD
, path
);
488 static int dir_cleanup(
492 const struct stat
*ds
,
497 bool keep_this_level
) {
500 bool deleted
= false;
503 FOREACH_DIRENT_ALL(dent
, d
, break) {
506 _cleanup_free_
char *sub_path
= NULL
;
508 if (dot_or_dot_dot(dent
->d_name
))
511 if (fstatat(dirfd(d
), dent
->d_name
, &s
, AT_SYMLINK_NOFOLLOW
) < 0) {
515 /* FUSE, NFS mounts, SELinux might return EACCES */
516 r
= log_full_errno(errno
== EACCES
? LOG_DEBUG
: LOG_ERR
, errno
,
517 "stat(%s/%s) failed: %m", p
, dent
->d_name
);
521 /* Stay on the same filesystem */
522 if (s
.st_dev
!= rootdev
) {
523 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, dent
->d_name
);
527 /* Try to detect bind mounts of the same filesystem instance; they
528 * do not differ in device major/minors. This type of query is not
529 * supported on all kernels or filesystem types though. */
530 if (S_ISDIR(s
.st_mode
)) {
533 q
= fd_is_mount_point(dirfd(d
), dent
->d_name
, 0);
535 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, dent
->d_name
);
537 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, dent
->d_name
);
542 sub_path
= path_join(p
, dent
->d_name
);
548 /* Is there an item configured for this path? */
549 if (ordered_hashmap_get(items
, sub_path
)) {
550 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
554 if (find_glob(globs
, sub_path
)) {
555 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
559 if (S_ISDIR(s
.st_mode
)) {
560 _cleanup_closedir_
DIR *sub_dir
= NULL
;
563 streq(dent
->d_name
, "lost+found") &&
565 log_debug("Ignoring directory \"%s\".", sub_path
);
570 log_warning("Reached max depth on \"%s\".", sub_path
);
574 sub_dir
= xopendirat_nomod(dirfd(d
), dent
->d_name
);
577 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
582 if (flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
583 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p
);
587 q
= dir_cleanup(i
, sub_path
, sub_dir
, &s
, cutoff
, rootdev
, false, maxdepth
-1, false);
592 /* Note: if you are wondering why we don't support the sticky bit for excluding
593 * directories from cleaning like we do it for other file system objects: well, the
594 * sticky bit already has a meaning for directories, so we don't want to overload
597 if (keep_this_level
) {
598 log_debug("Keeping directory \"%s\".", sub_path
);
602 /* Ignore ctime, we change it when deleting */
603 age
= timespec_load(&s
.st_mtim
);
605 char a
[FORMAT_TIMESTAMP_MAX
];
606 /* Follows spelling in stat(1). */
607 log_debug("Directory \"%s\": modify time %s is too new.",
609 format_timestamp_us(a
, sizeof(a
), age
));
613 age
= timespec_load(&s
.st_atim
);
615 char a
[FORMAT_TIMESTAMP_MAX
];
616 log_debug("Directory \"%s\": access time %s is too new.",
618 format_timestamp_us(a
, sizeof(a
), age
));
622 log_debug("Removing directory \"%s\".", sub_path
);
623 if (unlinkat(dirfd(d
), dent
->d_name
, AT_REMOVEDIR
) < 0)
624 if (!IN_SET(errno
, ENOENT
, ENOTEMPTY
))
625 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
628 /* Skip files for which the sticky bit is set. These are semantics we define, and are
629 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
630 if (s
.st_mode
& S_ISVTX
) {
631 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
636 S_ISREG(s
.st_mode
) &&
638 STR_IN_SET(dent
->d_name
,
642 log_debug("Skipping \"%s\".", sub_path
);
646 /* Ignore sockets that are listed in /proc/net/unix */
647 if (S_ISSOCK(s
.st_mode
) && unix_socket_alive(sub_path
)) {
648 log_debug("Skipping \"%s\": live socket.", sub_path
);
652 /* Ignore device nodes */
653 if (S_ISCHR(s
.st_mode
) || S_ISBLK(s
.st_mode
)) {
654 log_debug("Skipping \"%s\": a device.", sub_path
);
658 /* Keep files on this level around if this is requested */
659 if (keep_this_level
) {
660 log_debug("Keeping \"%s\".", sub_path
);
664 age
= timespec_load(&s
.st_mtim
);
666 char a
[FORMAT_TIMESTAMP_MAX
];
667 /* Follows spelling in stat(1). */
668 log_debug("File \"%s\": modify time %s is too new.",
670 format_timestamp_us(a
, sizeof(a
), age
));
674 age
= timespec_load(&s
.st_atim
);
676 char a
[FORMAT_TIMESTAMP_MAX
];
677 log_debug("File \"%s\": access time %s is too new.",
679 format_timestamp_us(a
, sizeof(a
), age
));
683 age
= timespec_load(&s
.st_ctim
);
685 char a
[FORMAT_TIMESTAMP_MAX
];
686 log_debug("File \"%s\": change time %s is too new.",
688 format_timestamp_us(a
, sizeof(a
), age
));
692 log_debug("Removing \"%s\".", sub_path
);
693 if (unlinkat(dirfd(d
), dent
->d_name
, 0) < 0)
695 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
703 char a
[FORMAT_TIMESTAMP_MAX
], b
[FORMAT_TIMESTAMP_MAX
];
706 age1
= timespec_load(&ds
->st_atim
);
707 age2
= timespec_load(&ds
->st_mtim
);
709 log_debug("Restoring access and modification time on \"%s\": %s, %s",
711 format_timestamp_us(a
, sizeof(a
), age1
),
712 format_timestamp_us(b
, sizeof(b
), age2
));
714 /* Restore original directory timestamps */
715 if (futimens(dirfd(d
), (struct timespec
[]) {
718 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
724 static bool dangerous_hardlinks(void) {
725 _cleanup_free_
char *value
= NULL
;
726 static int cached
= -1;
729 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
730 * what the upstream default is. */
735 r
= read_one_line_file("/proc/sys/fs/protected_hardlinks", &value
);
737 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl: %m");
741 r
= parse_boolean(value
);
743 log_debug_errno(r
, "Failed to parse fs.protected_hardlinks sysctl: %m");
751 static bool hardlink_vulnerable(const struct stat
*st
) {
754 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && dangerous_hardlinks();
757 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
759 if ((current
& 0111) == 0)
761 if ((current
& 0222) == 0)
763 if ((current
& 0444) == 0)
765 if (!S_ISDIR(current
))
766 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
771 static int fd_set_perms(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
780 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
784 if (fstat(fd
, &stbuf
) < 0)
785 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
789 if (hardlink_vulnerable(st
))
790 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
791 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
794 /* Do we need a chown()? */
796 (i
->uid_set
&& i
->uid
!= st
->st_uid
) ||
797 (i
->gid_set
&& i
->gid
!= st
->st_gid
);
799 /* Calculate the mode to apply */
800 new_mode
= i
->mode_set
? (i
->mask_perms
?
801 process_mask_perms(i
->mode
, st
->st_mode
) :
803 (st
->st_mode
& 07777);
805 if (i
->mode_set
&& do_chown
) {
806 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
807 * the new mode. That way there's no time window where the file exists under the old owner
808 * with more than the old access modes — and not under the new owner with more than the new
809 * access modes either. */
811 if (S_ISLNK(st
->st_mode
))
812 log_debug("Skipping temporary mode fix for symlink %s.", path
);
814 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
816 if (((m
^ st
->st_mode
) & 07777) == 0)
817 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
819 log_debug("Temporarily changing \"%s\" to mode %o.", path
, m
);
820 if (fchmod_opath(fd
, m
) < 0)
821 return log_error_errno(errno
, "fchmod() of %s failed: %m", path
);
827 log_debug("Changing \"%s\" to owner "UID_FMT
":"GID_FMT
,
829 i
->uid_set
? i
->uid
: UID_INVALID
,
830 i
->gid_set
? i
->gid
: GID_INVALID
);
834 i
->uid_set
? i
->uid
: UID_INVALID
,
835 i
->gid_set
? i
->gid
: GID_INVALID
,
837 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
840 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
841 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
842 if (i
->mode_set
|| do_chown
) {
843 if (S_ISLNK(st
->st_mode
))
844 log_debug("Skipping mode fix for symlink %s.", path
);
846 /* Check if the chmod() is unnecessary. Note that if we did a chown() before we always
847 * chmod() here again, since it might have mangled the bits. */
848 if (!do_chown
&& ((new_mode
^ st
->st_mode
) & 07777) == 0)
849 log_debug("\"%s\" matches mode %o already.", path
, new_mode
);
851 log_debug("Changing \"%s\" to mode %o.", path
, new_mode
);
852 if (fchmod_opath(fd
, new_mode
) < 0)
853 return log_error_errno(errno
, "fchmod() of %s failed: %m", path
);
859 return label_fix(path
, 0);
862 static int path_open_parent_safe(const char *path
) {
863 _cleanup_free_
char *dn
= NULL
;
866 if (path_equal(path
, "/") || !path_is_normalized(path
))
867 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
868 "Failed to open parent of '%s': invalid path.",
871 dn
= dirname_malloc(path
);
875 r
= chase_symlinks(dn
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
876 if (r
< 0 && r
!= -ENOLINK
)
877 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
879 return r
< 0 ? r
: fd
;
882 static int path_open_safe(const char *path
) {
885 /* path_open_safe() returns a file descriptor opened with O_PATH after
886 * verifying that the path doesn't contain unsafe transitions, except
887 * for its final component as the function does not follow symlink. */
891 if (!path_is_normalized(path
))
892 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
893 "Failed to open invalid path '%s'.",
896 r
= chase_symlinks(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
897 if (r
< 0 && r
!= -ENOLINK
)
898 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
900 return r
< 0 ? r
: fd
;
903 static int path_set_perms(Item
*i
, const char *path
) {
904 _cleanup_close_
int fd
= -1;
909 fd
= path_open_safe(path
);
913 return fd_set_perms(i
, fd
, path
, NULL
);
916 static int parse_xattrs_from_arg(Item
*i
) {
926 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
928 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
930 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
934 r
= split_pair(xattr
, "=", &name
, &value
);
936 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
940 if (isempty(name
) || isempty(value
)) {
941 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
945 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
954 static int fd_set_xattrs(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
955 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
956 char **name
, **value
;
962 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
964 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
965 log_debug("Setting extended attribute '%s=%s' on %s.", *name
, *value
, path
);
966 if (setxattr(procfs_path
, *name
, *value
, strlen(*value
), 0) < 0)
967 return log_error_errno(errno
, "Setting extended attribute %s=%s on %s failed: %m",
968 *name
, *value
, path
);
973 static int path_set_xattrs(Item
*i
, const char *path
) {
974 _cleanup_close_
int fd
= -1;
979 fd
= path_open_safe(path
);
983 return fd_set_xattrs(i
, fd
, path
, NULL
);
986 static int parse_acls_from_arg(Item
*item
) {
992 /* If append_or_force (= modify) is set, we will not modify the acl
993 * afterwards, so the mask can be added now if necessary. */
995 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_default
, !item
->append_or_force
);
997 log_warning_errno(r
, "Failed to parse ACL \"%s\": %m. Ignoring", item
->argument
);
999 log_warning_errno(SYNTHETIC_ERRNO(ENOSYS
), "ACLs are not supported. Ignoring");
1006 static int path_set_acl(const char *path
, const char *pretty
, acl_type_t type
, acl_t acl
, bool modify
) {
1007 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1008 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1011 /* Returns 0 for success, positive error if already warned,
1012 * negative error otherwise. */
1015 r
= acls_for_file(path
, type
, acl
, &dup
);
1019 r
= calc_acl_mask_if_needed(&dup
);
1027 /* the mask was already added earlier if needed */
1030 r
= add_base_acls_if_needed(&dup
, path
);
1034 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1035 log_debug("Setting %s ACL %s on %s.",
1036 type
== ACL_TYPE_ACCESS
? "access" : "default",
1039 r
= acl_set_file(path
, type
, dup
);
1041 /* Return positive to indicate we already warned */
1042 return -log_error_errno(errno
,
1043 "Setting %s ACL \"%s\" on %s failed: %m",
1044 type
== ACL_TYPE_ACCESS
? "access" : "default",
1051 static int fd_set_acls(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1054 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1062 if (fstat(fd
, &stbuf
) < 0)
1063 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1067 if (hardlink_vulnerable(st
))
1068 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1069 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1072 if (S_ISLNK(st
->st_mode
)) {
1073 log_debug("Skipping ACL fix for symlink %s.", path
);
1077 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1079 if (item
->acl_access
)
1080 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1082 /* set only default acls to folders */
1083 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1084 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1087 return -r
; /* already warned */
1089 /* The above procfs paths don't work if /proc is not mounted. */
1090 if (r
== -ENOENT
&& proc_mounted() == 0)
1093 if (r
== -EOPNOTSUPP
) {
1094 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1098 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1103 static int path_set_acls(Item
*item
, const char *path
) {
1106 _cleanup_close_
int fd
= -1;
1111 fd
= path_open_safe(path
);
1115 r
= fd_set_acls(item
, fd
, path
, NULL
);
1120 static int parse_attribute_from_arg(Item
*item
) {
1122 static const struct {
1126 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1127 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1128 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1129 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1130 { 'c', FS_COMPR_FL
}, /* Compress file */
1131 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1132 { 'e', FS_EXTENT_FL
}, /* Extents */
1133 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1134 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1135 { 's', FS_SECRM_FL
}, /* Secure deletion */
1136 { 'u', FS_UNRM_FL
}, /* Undelete */
1137 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1138 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1139 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1140 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1149 unsigned value
= 0, mask
= 0;
1159 } else if (*p
== '-') {
1162 } else if (*p
== '=') {
1168 if (isempty(p
) && mode
!= MODE_SET
)
1169 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1170 "Setting file attribute on '%s' needs an attribute specification.",
1173 for (; p
&& *p
; p
++) {
1176 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1177 if (*p
== attributes
[i
].character
)
1180 if (i
>= ELEMENTSOF(attributes
))
1181 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1182 "Unknown file attribute '%c' on '%s'.",
1185 v
= attributes
[i
].value
;
1187 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1192 if (mode
== MODE_SET
)
1193 mask
|= CHATTR_ALL_FL
;
1197 item
->attribute_mask
= mask
;
1198 item
->attribute_value
= value
;
1199 item
->attribute_set
= true;
1204 static int fd_set_attribute(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1205 _cleanup_close_
int procfs_fd
= -1;
1214 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1218 if (fstat(fd
, &stbuf
) < 0)
1219 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1223 /* Issuing the file attribute ioctls on device nodes is not
1224 * safe, as that will be delivered to the drivers, not the
1225 * file system containing the device node. */
1226 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1227 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1228 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1231 f
= item
->attribute_value
& item
->attribute_mask
;
1233 /* Mask away directory-specific flags */
1234 if (!S_ISDIR(st
->st_mode
))
1235 f
&= ~FS_DIRSYNC_FL
;
1237 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1239 return log_error_errno(procfs_fd
, "Failed to re-open '%s': %m", path
);
1241 r
= chattr_fd(procfs_fd
, f
, item
->attribute_mask
, NULL
);
1243 log_full_errno(IN_SET(r
, -ENOTTY
, -EOPNOTSUPP
) ? LOG_DEBUG
: LOG_WARNING
,
1245 "Cannot set file attribute for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1246 path
, item
->attribute_value
, item
->attribute_mask
);
1251 static int path_set_attribute(Item
*item
, const char *path
) {
1252 _cleanup_close_
int fd
= -1;
1254 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1257 fd
= path_open_safe(path
);
1261 return fd_set_attribute(item
, fd
, path
, NULL
);
1264 static int write_one_file(Item
*i
, const char *path
) {
1265 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1271 assert(i
->argument
);
1272 assert(i
->type
== WRITE_FILE
);
1274 /* Validate the path and keep the fd on the directory for opening the
1275 * file so we're sure that it can't be changed behind our back. */
1276 dir_fd
= path_open_parent_safe(path
);
1280 bn
= basename(path
);
1282 flags
= O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
;
1284 /* Follows symlinks */
1285 fd
= openat(dir_fd
, bn
, i
->append_or_force
? flags
|O_APPEND
: flags
, i
->mode
);
1287 if (errno
== ENOENT
) {
1288 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1291 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1294 /* 'w' is allowed to write into any kind of files. */
1295 log_debug("Writing to \"%s\".", path
);
1297 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1299 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1301 return fd_set_perms(i
, fd
, path
, NULL
);
1304 static int create_file(Item
*i
, const char *path
) {
1305 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1306 struct stat stbuf
, *st
= NULL
;
1312 assert(i
->type
== CREATE_FILE
);
1314 /* 'f' operates on regular files exclusively. */
1316 /* Validate the path and keep the fd on the directory for opening the
1317 * file so we're sure that it can't be changed behind our back. */
1318 dir_fd
= path_open_parent_safe(path
);
1322 bn
= basename(path
);
1324 RUN_WITH_UMASK(0000) {
1325 mac_selinux_create_file_prepare(path
, S_IFREG
);
1326 fd
= openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1327 mac_selinux_create_file_clear();
1331 /* Even on a read-only filesystem, open(2) returns EEXIST if the
1332 * file already exists. It returns EROFS only if it needs to
1333 * create the file. */
1334 if (errno
!= EEXIST
)
1335 return log_error_errno(errno
, "Failed to create file %s: %m", path
);
1337 /* Re-open the file. At that point it must exist since open(2)
1338 * failed with EEXIST. We still need to check if the perms/mode
1339 * need to be changed. For read-only filesystems, we let
1340 * fd_set_perms() report the error if the perms need to be
1342 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1344 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1346 if (fstat(fd
, &stbuf
) < 0)
1347 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1349 if (!S_ISREG(stbuf
.st_mode
)) {
1350 log_error("%s exists and is not a regular file.", path
);
1357 log_debug("\"%s\" has been created.", path
);
1360 log_debug("Writing to \"%s\".", path
);
1362 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1364 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1368 return fd_set_perms(i
, fd
, path
, st
);
1371 static int truncate_file(Item
*i
, const char *path
) {
1372 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1373 struct stat stbuf
, *st
= NULL
;
1380 assert(i
->type
== TRUNCATE_FILE
|| (i
->type
== CREATE_FILE
&& i
->append_or_force
));
1382 /* We want to operate on regular file exclusively especially since
1383 * O_TRUNC is unspecified if the file is neither a regular file nor a
1384 * fifo nor a terminal device. Therefore we first open the file and make
1385 * sure it's a regular one before truncating it. */
1387 /* Validate the path and keep the fd on the directory for opening the
1388 * file so we're sure that it can't be changed behind our back. */
1389 dir_fd
= path_open_parent_safe(path
);
1393 bn
= basename(path
);
1395 RUN_WITH_UMASK(0000) {
1396 mac_selinux_create_file_prepare(path
, S_IFREG
);
1397 fd
= openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1398 mac_selinux_create_file_clear();
1403 return log_error_errno(errno
, "Failed to open/create file %s: %m", path
);
1405 /* On a read-only filesystem, we don't want to fail if the
1406 * target is already empty and the perms are set. So we still
1407 * proceed with the sanity checks and let the remaining
1408 * operations fail with EROFS if they try to modify the target
1411 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1413 if (errno
== ENOENT
) {
1414 log_error("Cannot create file %s on a read-only file system.", path
);
1418 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1424 if (fstat(fd
, &stbuf
) < 0)
1425 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1427 if (!S_ISREG(stbuf
.st_mode
)) {
1428 log_error("%s exists and is not a regular file.", path
);
1432 if (stbuf
.st_size
> 0) {
1433 if (ftruncate(fd
, 0) < 0) {
1434 r
= erofs
? -EROFS
: -errno
;
1435 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1440 log_debug("\"%s\" has been created.", path
);
1443 log_debug("Writing to \"%s\".", path
);
1445 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1447 r
= erofs
? -EROFS
: r
;
1448 return log_error_errno(r
, "Failed to write file %s: %m", path
);
1452 return fd_set_perms(i
, fd
, path
, st
);
1455 static int copy_files(Item
*i
) {
1456 _cleanup_close_
int dfd
= -1, fd
= -1;
1460 log_debug("Copying tree \"%s\" to \"%s\".", i
->argument
, i
->path
);
1462 bn
= basename(i
->path
);
1464 /* Validate the path and use the returned directory fd for copying the
1465 * target so we're sure that the path can't be changed behind our
1467 dfd
= path_open_parent_safe(i
->path
);
1471 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1473 i
->uid_set
? i
->uid
: UID_INVALID
,
1474 i
->gid_set
? i
->gid
: GID_INVALID
,
1475 COPY_REFLINK
| COPY_MERGE_EMPTY
| COPY_MAC_CREATE
);
1479 /* If the target already exists on read-only filesystems, trying
1480 * to create the target will not fail with EEXIST but with
1482 if (r
== -EROFS
&& faccessat(dfd
, bn
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0)
1486 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1488 if (stat(i
->argument
, &a
) < 0)
1489 return log_error_errno(errno
, "stat(%s) failed: %m", i
->argument
);
1491 if (fstatat(dfd
, bn
, &b
, AT_SYMLINK_NOFOLLOW
) < 0)
1492 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1494 if ((a
.st_mode
^ b
.st_mode
) & S_IFMT
) {
1495 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1500 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1502 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1504 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1512 _CREATION_MODE_INVALID
= -1
1515 static const char *const creation_mode_verb_table
[_CREATION_MODE_MAX
] = {
1516 [CREATION_NORMAL
] = "Created",
1517 [CREATION_EXISTING
] = "Found existing",
1518 [CREATION_FORCE
] = "Created replacement",
1521 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb
, CreationMode
);
1523 static int create_directory_or_subvolume(const char *path
, mode_t mode
, bool subvol
, CreationMode
*creation
) {
1524 _cleanup_close_
int pfd
= -1;
1533 pfd
= path_open_parent_safe(path
);
1538 if (btrfs_is_subvol(empty_to_root(arg_root
)) <= 0)
1540 /* Don't create a subvolume unless the root directory is
1541 * one, too. We do this under the assumption that if the
1542 * root directory is just a plain directory (i.e. very
1543 * light-weight), we shouldn't try to split it up into
1544 * subvolumes (i.e. more heavy-weight). Thus, chroot()
1545 * environments and suchlike will get a full brtfs
1546 * subvolume set up below their tree only if they
1547 * specifically set up a btrfs subvolume for the root
1552 RUN_WITH_UMASK((~mode
) & 0777)
1553 r
= btrfs_subvol_make_fd(pfd
, basename(path
));
1558 if (!subvol
|| r
== -ENOTTY
)
1559 RUN_WITH_UMASK(0000)
1560 r
= mkdirat_label(pfd
, basename(path
), mode
);
1565 if (!IN_SET(r
, -EEXIST
, -EROFS
))
1566 return log_error_errno(r
, "Failed to create directory or subvolume \"%s\": %m", path
);
1569 if (k
== -ENOENT
&& r
== -EROFS
)
1570 return log_error_errno(r
, "%s does not exist and cannot be created as the file system is read-only.", path
);
1572 return log_error_errno(k
, "Failed to check if %s exists: %m", path
);
1574 log_warning("\"%s\" already exists and is not a directory.", path
);
1578 *creation
= CREATION_EXISTING
;
1580 *creation
= CREATION_NORMAL
;
1582 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(*creation
), path
);
1584 r
= openat(pfd
, basename(path
), O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
1586 return log_error_errno(errno
, "Failed to open directory '%s': %m", basename(path
));
1591 static int create_directory(Item
*i
, const char *path
) {
1592 _cleanup_close_
int fd
= -1;
1595 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
1597 fd
= create_directory_or_subvolume(path
, i
->mode
, false, NULL
);
1603 return fd_set_perms(i
, fd
, path
, NULL
);
1606 static int create_subvolume(Item
*i
, const char *path
) {
1607 _cleanup_close_
int fd
= -1;
1608 CreationMode creation
;
1612 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
1614 fd
= create_directory_or_subvolume(path
, i
->mode
, true, &creation
);
1620 if (creation
== CREATION_NORMAL
&&
1621 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
1622 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
1624 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
1625 else if (r
== -EROFS
)
1626 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
1627 else if (r
== -ENOPROTOOPT
)
1628 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
1630 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
1632 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
1634 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
1637 r
= fd_set_perms(i
, fd
, path
, NULL
);
1638 if (q
< 0) /* prefer the quota change error from above */
1644 static int empty_directory(Item
*i
, const char *path
) {
1648 assert(i
->type
== EMPTY_DIRECTORY
);
1650 r
= is_dir(path
, false);
1652 /* Option "e" operates only on existing objects. Do not
1653 * print errors about non-existent files or directories */
1654 log_debug("Skipping missing directory: %s", path
);
1658 return log_error_errno(r
, "is_dir() failed on path %s: %m", path
);
1660 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1661 "'%s' already exists and is not a directory.",
1664 return path_set_perms(i
, path
);
1667 static int create_device(Item
*i
, mode_t file_type
) {
1668 _cleanup_close_
int dfd
= -1, fd
= -1;
1669 CreationMode creation
;
1674 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
1676 bn
= basename(i
->path
);
1678 /* Validate the path and use the returned directory fd for copying the
1679 * target so we're sure that the path can't be changed behind our
1681 dfd
= path_open_parent_safe(i
->path
);
1685 RUN_WITH_UMASK(0000) {
1686 mac_selinux_create_file_prepare(i
->path
, file_type
);
1687 r
= mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
1688 mac_selinux_create_file_clear();
1694 if (errno
== EPERM
) {
1695 log_debug("We lack permissions, possibly because of cgroup configuration; "
1696 "skipping creation of device node %s.", i
->path
);
1700 if (errno
!= EEXIST
)
1701 return log_error_errno(errno
, "Failed to create device node %s: %m", i
->path
);
1703 if (fstatat(dfd
, bn
, &st
, 0) < 0)
1704 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1706 if ((st
.st_mode
& S_IFMT
) != file_type
) {
1708 if (i
->append_or_force
) {
1710 RUN_WITH_UMASK(0000) {
1711 mac_selinux_create_file_prepare(i
->path
, file_type
);
1712 /* FIXME: need to introduce mknodat_atomic() */
1713 r
= mknod_atomic(i
->path
, i
->mode
| file_type
, i
->major_minor
);
1714 mac_selinux_create_file_clear();
1718 return log_error_errno(r
, "Failed to create device node \"%s\": %m", i
->path
);
1719 creation
= CREATION_FORCE
;
1721 log_debug("%s is not a device node.", i
->path
);
1725 creation
= CREATION_EXISTING
;
1727 creation
= CREATION_NORMAL
;
1729 log_debug("%s %s device node \"%s\" %u:%u.",
1730 creation_mode_verb_to_string(creation
),
1731 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
1732 i
->path
, major(i
->mode
), minor(i
->mode
));
1734 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1736 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1738 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1741 static int create_fifo(Item
*i
, const char *path
) {
1742 _cleanup_close_
int pfd
= -1, fd
= -1;
1743 CreationMode creation
;
1748 pfd
= path_open_parent_safe(path
);
1752 bn
= basename(path
);
1754 RUN_WITH_UMASK(0000) {
1755 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1756 r
= mkfifoat(pfd
, bn
, i
->mode
);
1757 mac_selinux_create_file_clear();
1761 if (errno
!= EEXIST
)
1762 return log_error_errno(errno
, "Failed to create fifo %s: %m", path
);
1764 if (fstatat(pfd
, bn
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
1765 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1767 if (!S_ISFIFO(st
.st_mode
)) {
1769 if (i
->append_or_force
) {
1770 RUN_WITH_UMASK(0000) {
1771 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1772 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
1773 mac_selinux_create_file_clear();
1777 return log_error_errno(r
, "Failed to create fifo %s: %m", path
);
1778 creation
= CREATION_FORCE
;
1780 log_warning("\"%s\" already exists and is not a fifo.", path
);
1784 creation
= CREATION_EXISTING
;
1786 creation
= CREATION_NORMAL
;
1788 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), path
);
1790 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1792 return log_error_errno(errno
, "Failed to openat(%s): %m", path
);
1794 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1797 typedef int (*action_t
)(Item
*i
, const char *path
);
1798 typedef int (*fdaction_t
)(Item
*i
, int fd
, const char *path
, const struct stat
*st
);
1800 static int item_do(Item
*i
, int fd
, const char *path
, fdaction_t action
) {
1808 if (fstat(fd
, &st
) < 0) {
1809 r
= log_error_errno(errno
, "fstat() on file failed: %m");
1813 /* This returns the first error we run into, but nevertheless
1815 r
= action(i
, fd
, path
, &st
);
1817 if (S_ISDIR(st
.st_mode
)) {
1818 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1819 _cleanup_closedir_
DIR *d
= NULL
;
1822 /* The passed 'fd' was opened with O_PATH. We need to convert
1823 * it into a 'regular' fd before reading the directory content. */
1824 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1826 d
= opendir(procfs_path
);
1828 log_error_errno(errno
, "Failed to opendir() '%s': %m", procfs_path
);
1834 FOREACH_DIRENT_ALL(de
, d
, q
= -errno
; goto finish
) {
1837 if (dot_or_dot_dot(de
->d_name
))
1840 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1842 q
= log_error_errno(errno
, "Failed to open() file '%s': %m", de
->d_name
);
1844 _cleanup_free_
char *de_path
= NULL
;
1846 de_path
= path_join(path
, de
->d_name
);
1850 /* Pass ownership of dirent fd over */
1851 q
= item_do(i
, de_fd
, de_path
, action
);
1854 if (q
< 0 && r
== 0)
1863 static int glob_item(Item
*i
, action_t action
) {
1864 _cleanup_globfree_ glob_t g
= {
1865 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1870 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1871 if (k
< 0 && k
!= -ENOENT
)
1872 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1874 STRV_FOREACH(fn
, g
.gl_pathv
) {
1876 if (k
< 0 && r
== 0)
1883 static int glob_item_recursively(Item
*i
, fdaction_t action
) {
1884 _cleanup_globfree_ glob_t g
= {
1885 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1890 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1891 if (k
< 0 && k
!= -ENOENT
)
1892 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1894 STRV_FOREACH(fn
, g
.gl_pathv
) {
1895 _cleanup_close_
int fd
= -1;
1897 /* Make sure we won't trigger/follow file object (such as
1898 * device nodes, automounts, ...) pointed out by 'fn' with
1899 * O_PATH. Note, when O_PATH is used, flags other than
1900 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1902 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
1904 log_error_errno(errno
, "Opening '%s' failed: %m", *fn
);
1910 k
= item_do(i
, fd
, *fn
, action
);
1911 if (k
< 0 && r
== 0)
1914 /* we passed fd ownership to the previous call */
1921 static int create_item(Item
*i
) {
1922 CreationMode creation
;
1927 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
1932 case IGNORE_DIRECTORY_PATH
:
1934 case RECURSIVE_REMOVE_PATH
:
1939 RUN_WITH_UMASK(0000)
1940 (void) mkdir_parents_label(i
->path
, 0755);
1942 if ((i
->type
== CREATE_FILE
&& i
->append_or_force
) || i
->type
== TRUNCATE_FILE
)
1943 r
= truncate_file(i
, i
->path
);
1945 r
= create_file(i
, i
->path
);
1952 RUN_WITH_UMASK(0000)
1953 (void) mkdir_parents_label(i
->path
, 0755);
1961 r
= glob_item(i
, write_one_file
);
1967 case CREATE_DIRECTORY
:
1968 case TRUNCATE_DIRECTORY
:
1969 RUN_WITH_UMASK(0000)
1970 (void) mkdir_parents_label(i
->path
, 0755);
1972 r
= create_directory(i
, i
->path
);
1977 case CREATE_SUBVOLUME
:
1978 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
1979 case CREATE_SUBVOLUME_NEW_QUOTA
:
1980 RUN_WITH_UMASK(0000)
1981 (void) mkdir_parents_label(i
->path
, 0755);
1983 r
= create_subvolume(i
, i
->path
);
1988 case EMPTY_DIRECTORY
:
1989 r
= glob_item(i
, empty_directory
);
1995 RUN_WITH_UMASK(0000)
1996 (void) mkdir_parents_label(i
->path
, 0755);
1998 r
= create_fifo(i
, i
->path
);
2003 case CREATE_SYMLINK
: {
2004 RUN_WITH_UMASK(0000)
2005 (void) mkdir_parents_label(i
->path
, 0755);
2007 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2008 r
= symlink(i
->argument
, i
->path
);
2009 mac_selinux_create_file_clear();
2012 _cleanup_free_
char *x
= NULL
;
2014 if (errno
!= EEXIST
)
2015 return log_error_errno(errno
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2017 r
= readlink_malloc(i
->path
, &x
);
2018 if (r
< 0 || !streq(i
->argument
, x
)) {
2020 if (i
->append_or_force
) {
2021 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2022 r
= symlink_atomic(i
->argument
, i
->path
);
2023 mac_selinux_create_file_clear();
2025 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2026 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
2028 return log_error_errno(r
, "rm -fr %s failed: %m", i
->path
);
2030 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2031 r
= symlink(i
->argument
, i
->path
) < 0 ? -errno
: 0;
2032 mac_selinux_create_file_clear();
2035 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2037 creation
= CREATION_FORCE
;
2039 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2043 creation
= CREATION_EXISTING
;
2046 creation
= CREATION_NORMAL
;
2047 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2051 case CREATE_BLOCK_DEVICE
:
2052 case CREATE_CHAR_DEVICE
:
2053 if (have_effective_cap(CAP_MKNOD
) == 0) {
2054 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2055 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2057 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2061 RUN_WITH_UMASK(0000)
2062 (void) mkdir_parents_label(i
->path
, 0755);
2064 r
= create_device(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2072 r
= glob_item(i
, path_set_perms
);
2077 case RECURSIVE_RELABEL_PATH
:
2078 r
= glob_item_recursively(i
, fd_set_perms
);
2084 r
= glob_item(i
, path_set_xattrs
);
2089 case RECURSIVE_SET_XATTR
:
2090 r
= glob_item_recursively(i
, fd_set_xattrs
);
2096 r
= glob_item(i
, path_set_acls
);
2101 case RECURSIVE_SET_ACL
:
2102 r
= glob_item_recursively(i
, fd_set_acls
);
2108 r
= glob_item(i
, path_set_attribute
);
2113 case RECURSIVE_SET_ATTRIBUTE
:
2114 r
= glob_item_recursively(i
, fd_set_attribute
);
2123 static int remove_item_instance(Item
*i
, const char *instance
) {
2131 if (remove(instance
) < 0 && errno
!= ENOENT
)
2132 return log_error_errno(errno
, "rm(%s): %m", instance
);
2136 case RECURSIVE_REMOVE_PATH
:
2137 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2138 log_debug("rm -rf \"%s\"", instance
);
2139 r
= rm_rf(instance
, REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
);
2140 if (r
< 0 && r
!= -ENOENT
)
2141 return log_error_errno(r
, "rm_rf(%s): %m", instance
);
2146 assert_not_reached("wut?");
2152 static int remove_item(Item
*i
) {
2157 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
2161 case TRUNCATE_DIRECTORY
:
2162 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2163 log_debug("rm -rf \"%s\"", i
->path
);
2164 r
= rm_rf(i
->path
, REMOVE_PHYSICAL
);
2165 if (r
< 0 && r
!= -ENOENT
)
2166 return log_error_errno(r
, "rm_rf(%s): %m", i
->path
);
2171 case RECURSIVE_REMOVE_PATH
:
2172 return glob_item(i
, remove_item_instance
);
2179 static int clean_item_instance(Item
*i
, const char* instance
) {
2180 _cleanup_closedir_
DIR *d
= NULL
;
2184 char timestamp
[FORMAT_TIMESTAMP_MAX
];
2191 n
= now(CLOCK_REALTIME
);
2195 cutoff
= n
- i
->age
;
2197 d
= opendir_nomod(instance
);
2199 if (IN_SET(errno
, ENOENT
, ENOTDIR
)) {
2200 log_debug_errno(errno
, "Directory \"%s\": %m", instance
);
2204 return log_error_errno(errno
, "Failed to open directory %s: %m", instance
);
2207 if (fstat(dirfd(d
), &s
) < 0)
2208 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
2210 if (!S_ISDIR(s
.st_mode
))
2211 return log_error_errno(SYNTHETIC_ERRNO(ENOTDIR
),
2212 "%s is not a directory.", i
->path
);
2214 if (fstatat(dirfd(d
), "..", &ps
, AT_SYMLINK_NOFOLLOW
) != 0)
2215 return log_error_errno(errno
, "stat(%s/..) failed: %m", i
->path
);
2217 mountpoint
= s
.st_dev
!= ps
.st_dev
|| s
.st_ino
== ps
.st_ino
;
2219 log_debug("Cleanup threshold for %s \"%s\" is %s",
2220 mountpoint
? "mount point" : "directory",
2222 format_timestamp_us(timestamp
, sizeof(timestamp
), cutoff
));
2224 return dir_cleanup(i
, instance
, d
, &s
, cutoff
, s
.st_dev
, mountpoint
,
2225 MAX_DEPTH
, i
->keep_first_level
);
2228 static int clean_item(Item
*i
) {
2231 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
2234 case CREATE_DIRECTORY
:
2235 case CREATE_SUBVOLUME
:
2236 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2237 case CREATE_SUBVOLUME_NEW_QUOTA
:
2238 case TRUNCATE_DIRECTORY
:
2241 clean_item_instance(i
, i
->path
);
2243 case EMPTY_DIRECTORY
:
2244 case IGNORE_DIRECTORY_PATH
:
2245 return glob_item(i
, clean_item_instance
);
2251 static int process_item(Item
*i
, OperationMask operation
) {
2257 todo
= operation
& ~i
->done
;
2258 if (todo
== 0) /* Everything already done? */
2261 i
->done
|= operation
;
2263 r
= chase_symlinks(i
->path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_WARN
, NULL
, NULL
);
2264 if (r
== -EREMOTE
) {
2265 log_notice_errno(r
, "Skipping %s", i
->path
);
2269 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
2271 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(i
) : 0;
2272 /* Failure can only be tolerated for create */
2273 if (i
->allow_failure
)
2276 q
= FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(i
) : 0;
2277 p
= FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(i
) : 0;
2284 static int process_item_array(ItemArray
*array
, OperationMask operation
) {
2290 /* Create any parent first. */
2291 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
2292 r
= process_item_array(array
->parent
, operation
& OPERATION_CREATE
);
2294 /* Clean up all children first */
2295 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
)) && !set_isempty(array
->children
)) {
2299 SET_FOREACH(c
, array
->children
, i
) {
2302 k
= process_item_array(c
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
));
2303 if (k
< 0 && r
== 0)
2308 for (n
= 0; n
< array
->n_items
; n
++) {
2311 k
= process_item(array
->items
+ n
, operation
);
2312 if (k
< 0 && r
== 0)
2319 static void item_free_contents(Item
*i
) {
2323 strv_free(i
->xattrs
);
2326 acl_free(i
->acl_access
);
2327 acl_free(i
->acl_default
);
2331 static ItemArray
* item_array_free(ItemArray
*a
) {
2337 for (n
= 0; n
< a
->n_items
; n
++)
2338 item_free_contents(a
->items
+ n
);
2340 set_free(a
->children
);
2345 static int item_compare(const Item
*a
, const Item
*b
) {
2346 /* Make sure that the ownership taking item is put first, so
2347 * that we first create the node, and then can adjust it */
2349 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
2351 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
2354 return CMP(a
->type
, b
->type
);
2357 static bool item_compatible(Item
*a
, Item
*b
) {
2360 assert(streq(a
->path
, b
->path
));
2362 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
2363 /* check if the items are the same */
2364 return streq_ptr(a
->argument
, b
->argument
) &&
2366 a
->uid_set
== b
->uid_set
&&
2369 a
->gid_set
== b
->gid_set
&&
2372 a
->mode_set
== b
->mode_set
&&
2373 a
->mode
== b
->mode
&&
2375 a
->age_set
== b
->age_set
&&
2378 a
->mask_perms
== b
->mask_perms
&&
2380 a
->keep_first_level
== b
->keep_first_level
&&
2382 a
->major_minor
== b
->major_minor
;
2387 static bool should_include_path(const char *path
) {
2390 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
2391 if (path_startswith(path
, *prefix
)) {
2392 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2397 STRV_FOREACH(prefix
, arg_include_prefixes
)
2398 if (path_startswith(path
, *prefix
)) {
2399 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
2403 /* no matches, so we should include this path only if we
2404 * have no whitelist at all */
2405 if (strv_isempty(arg_include_prefixes
))
2408 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
2412 static int specifier_expansion_from_arg(Item
*i
) {
2413 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
2424 case CREATE_SYMLINK
:
2428 r
= cunescape(i
->argument
, 0, &unescaped
);
2430 return log_error_errno(r
, "Failed to unescape parameter to write: %s", i
->argument
);
2432 r
= specifier_printf(unescaped
, specifier_table
, NULL
, &resolved
);
2436 free_and_replace(i
->argument
, resolved
);
2440 case RECURSIVE_SET_XATTR
:
2441 STRV_FOREACH(xattr
, i
->xattrs
) {
2442 r
= specifier_printf(*xattr
, specifier_table
, NULL
, &resolved
);
2446 free_and_replace(*xattr
, resolved
);
2456 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
2463 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2464 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2465 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2466 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2467 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2468 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2469 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2470 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2471 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2473 k
= path_startswith(*path
, "/var/run/");
2474 if (isempty(k
)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2477 n
= path_join("/run", k
);
2481 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2482 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2483 * to the user, let's still inform the user that these snippets should really be updated. */
2484 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
);
2486 free_and_replace(*path
, n
);
2491 static int find_uid(const char *user
, uid_t
*ret_uid
, Hashmap
**cache
) {
2497 /* First: parse as numeric UID string */
2498 r
= parse_uid(user
, ret_uid
);
2502 /* Second: pass to NSS if we are running "online" */
2504 return get_user_creds(&user
, ret_uid
, NULL
, NULL
, NULL
, 0);
2506 /* Third, synthesize "root" unconditionally */
2507 if (streq(user
, "root")) {
2512 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
2513 return name_to_uid_offline(arg_root
, user
, ret_uid
, cache
);
2516 static int find_gid(const char *group
, gid_t
*ret_gid
, Hashmap
**cache
) {
2522 /* First: parse as numeric GID string */
2523 r
= parse_gid(group
, ret_gid
);
2527 /* Second: pass to NSS if we are running "online" */
2529 return get_group_creds(&group
, ret_gid
, 0);
2531 /* Third, synthesize "root" unconditionally */
2532 if (streq(group
, "root")) {
2537 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
2538 return name_to_gid_offline(arg_root
, group
, ret_gid
, cache
);
2541 static int parse_line(
2545 bool *invalid_config
,
2546 Hashmap
**uid_cache
,
2547 Hashmap
**gid_cache
) {
2549 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
2550 _cleanup_(item_free_contents
) Item i
= {};
2551 ItemArray
*existing
;
2554 bool append_or_force
= false, boot
= false, allow_failure
= false;
2560 r
= extract_many_words(
2572 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2573 /* invalid quoting and such or an unknown specifier */
2574 *invalid_config
= true;
2575 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to parse line: %m");
2577 *invalid_config
= true;
2578 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Syntax error.");
2581 if (!empty_or_dash(buffer
)) {
2582 i
.argument
= strdup(buffer
);
2587 if (isempty(action
)) {
2588 *invalid_config
= true;
2589 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Command too short '%s'.", action
);
2592 for (pos
= 1; action
[pos
]; pos
++) {
2593 if (action
[pos
] == '!' && !boot
)
2595 else if (action
[pos
] == '+' && !append_or_force
)
2596 append_or_force
= true;
2597 else if (action
[pos
] == '-' && !allow_failure
)
2598 allow_failure
= true;
2600 *invalid_config
= true;
2601 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Unknown modifiers in command '%s'", action
);
2605 if (boot
&& !arg_boot
) {
2606 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action
, path
);
2611 i
.append_or_force
= append_or_force
;
2612 i
.allow_failure
= allow_failure
;
2614 r
= specifier_printf(path
, specifier_table
, NULL
, &i
.path
);
2616 return log_unresolvable_specifier(fname
, line
);
2618 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2619 *invalid_config
= true;
2620 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", path
);
2623 r
= patch_var_run(fname
, line
, &i
.path
);
2629 case CREATE_DIRECTORY
:
2630 case CREATE_SUBVOLUME
:
2631 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2632 case CREATE_SUBVOLUME_NEW_QUOTA
:
2633 case EMPTY_DIRECTORY
:
2634 case TRUNCATE_DIRECTORY
:
2637 case IGNORE_DIRECTORY_PATH
:
2639 case RECURSIVE_REMOVE_PATH
:
2642 case RECURSIVE_RELABEL_PATH
:
2644 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0, "%c lines don't take argument fields, ignoring.", i
.type
);
2652 case CREATE_SYMLINK
:
2654 i
.argument
= path_join("/usr/share/factory", i
.path
);
2662 *invalid_config
= true;
2663 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Write file requires argument.");
2669 i
.argument
= path_join(arg_root
, "/usr/share/factory", i
.path
);
2673 } else if (!path_is_absolute(i
.argument
)) {
2674 *invalid_config
= true;
2675 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Source path '%s' is not absolute.", i
.argument
);
2677 } else if (arg_root
) {
2680 p
= path_join(arg_root
, i
.argument
);
2683 free_and_replace(i
.argument
, p
);
2686 path_simplify(i
.argument
, false);
2689 case CREATE_CHAR_DEVICE
:
2690 case CREATE_BLOCK_DEVICE
:
2692 *invalid_config
= true;
2693 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Device file requires argument.");
2696 r
= parse_dev(i
.argument
, &i
.major_minor
);
2698 *invalid_config
= true;
2699 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Can't parse device file major/minor '%s'.", i
.argument
);
2705 case RECURSIVE_SET_XATTR
:
2707 *invalid_config
= true;
2708 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2709 "Set extended attribute requires argument.");
2711 r
= parse_xattrs_from_arg(&i
);
2717 case RECURSIVE_SET_ACL
:
2719 *invalid_config
= true;
2720 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2721 "Set ACLs requires argument.");
2723 r
= parse_acls_from_arg(&i
);
2729 case RECURSIVE_SET_ATTRIBUTE
:
2731 *invalid_config
= true;
2732 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2733 "Set file attribute requires argument.");
2735 r
= parse_attribute_from_arg(&i
);
2736 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2737 *invalid_config
= true;
2743 *invalid_config
= true;
2744 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2745 "Unknown command type '%c'.", (char) i
.type
);
2748 if (!path_is_absolute(i
.path
)) {
2749 *invalid_config
= true;
2750 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2751 "Path '%s' not absolute.", i
.path
);
2754 path_simplify(i
.path
, false);
2756 if (!should_include_path(i
.path
))
2759 r
= specifier_expansion_from_arg(&i
);
2761 return log_unresolvable_specifier(fname
, line
);
2763 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2764 *invalid_config
= true;
2765 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to substitute specifiers in argument: %m");
2771 p
= path_join(arg_root
, i
.path
);
2774 free_and_replace(i
.path
, p
);
2777 if (!empty_or_dash(user
)) {
2778 r
= find_uid(user
, &i
.uid
, uid_cache
);
2780 *invalid_config
= true;
2781 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve user '%s': %m", user
);
2787 if (!empty_or_dash(group
)) {
2788 r
= find_gid(group
, &i
.gid
, gid_cache
);
2790 *invalid_config
= true;
2791 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve group '%s'.", group
);
2797 if (!empty_or_dash(mode
)) {
2798 const char *mm
= mode
;
2802 i
.mask_perms
= true;
2806 r
= parse_mode(mm
, &m
);
2808 *invalid_config
= true;
2809 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid mode '%s'.", mode
);
2815 i
.mode
= IN_SET(i
.type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
2817 if (!empty_or_dash(age
)) {
2818 const char *a
= age
;
2821 i
.keep_first_level
= true;
2825 r
= parse_sec(a
, &i
.age
);
2827 *invalid_config
= true;
2828 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age '%s'.", age
);
2834 h
= needs_glob(i
.type
) ? globs
: items
;
2836 existing
= ordered_hashmap_get(h
, i
.path
);
2840 for (n
= 0; n
< existing
->n_items
; n
++) {
2841 if (!item_compatible(existing
->items
+ n
, &i
) && !i
.append_or_force
) {
2842 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0, "Duplicate line for path \"%s\", ignoring.", i
.path
);
2847 existing
= new0(ItemArray
, 1);
2851 r
= ordered_hashmap_put(h
, i
.path
, existing
);
2858 if (!GREEDY_REALLOC(existing
->items
, existing
->allocated
, existing
->n_items
+ 1))
2861 existing
->items
[existing
->n_items
++] = i
;
2862 i
= (struct Item
) {};
2864 /* Sort item array, to enforce stable ordering of application */
2865 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
2870 static int cat_config(char **config_dirs
, char **args
) {
2871 _cleanup_strv_free_
char **files
= NULL
;
2874 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
2878 return cat_files(NULL
, files
, 0);
2881 static int help(void) {
2882 _cleanup_free_
char *link
= NULL
;
2885 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
2889 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2890 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
2891 " -h --help Show this help\n"
2892 " --user Execute user configuration\n"
2893 " --version Show package version\n"
2894 " --cat-config Show configuration files\n"
2895 " --create Create marked files/directories\n"
2896 " --clean Clean up marked directories\n"
2897 " --remove Remove marked files/directories\n"
2898 " --boot Execute actions only safe at boot\n"
2899 " --prefix=PATH Only apply rules with the specified prefix\n"
2900 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
2901 " --root=PATH Operate on an alternate filesystem root\n"
2902 " --replace=PATH Treat arguments as replacement for PATH\n"
2903 " --no-pager Do not pipe output into a pager\n"
2904 "\nSee the %s for details.\n"
2905 , program_invocation_short_name
2912 static int parse_argv(int argc
, char *argv
[]) {
2915 ARG_VERSION
= 0x100,
2929 static const struct option options
[] = {
2930 { "help", no_argument
, NULL
, 'h' },
2931 { "user", no_argument
, NULL
, ARG_USER
},
2932 { "version", no_argument
, NULL
, ARG_VERSION
},
2933 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
2934 { "create", no_argument
, NULL
, ARG_CREATE
},
2935 { "clean", no_argument
, NULL
, ARG_CLEAN
},
2936 { "remove", no_argument
, NULL
, ARG_REMOVE
},
2937 { "boot", no_argument
, NULL
, ARG_BOOT
},
2938 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
2939 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
2940 { "root", required_argument
, NULL
, ARG_ROOT
},
2941 { "replace", required_argument
, NULL
, ARG_REPLACE
},
2942 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
2951 while ((c
= getopt_long(argc
, argv
, "h", options
, NULL
)) >= 0)
2961 case ARG_CAT_CONFIG
:
2962 arg_cat_config
= true;
2970 arg_operation
|= OPERATION_CREATE
;
2974 arg_operation
|= OPERATION_CLEAN
;
2978 arg_operation
|= OPERATION_REMOVE
;
2986 if (strv_push(&arg_include_prefixes
, optarg
) < 0)
2990 case ARG_EXCLUDE_PREFIX
:
2991 if (strv_push(&arg_exclude_prefixes
, optarg
) < 0)
2996 r
= parse_path_argument_and_warn(optarg
, true, &arg_root
);
3002 if (!path_is_absolute(optarg
) ||
3003 !endswith(optarg
, ".conf"))
3004 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3005 "The argument to --replace= must an absolute path to a config file");
3007 arg_replace
= optarg
;
3011 arg_pager_flags
|= PAGER_DISABLE
;
3018 assert_not_reached("Unhandled option");
3021 if (arg_operation
== 0 && !arg_cat_config
)
3022 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3023 "You need to specify at least one of --clean, --create or --remove.");
3025 if (arg_replace
&& arg_cat_config
)
3026 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3027 "Option --replace= is not supported with --cat-config");
3029 if (arg_replace
&& optind
>= argc
)
3030 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3031 "When --replace= is given, some configuration items must be specified");
3036 static int read_config_file(char **config_dirs
, const char *fn
, bool ignore_enoent
, bool *invalid_config
) {
3037 _cleanup_(hashmap_freep
) Hashmap
*uid_cache
= NULL
, *gid_cache
= NULL
;
3038 _cleanup_fclose_
FILE *_f
= NULL
;
3047 if (streq(fn
, "-")) {
3048 log_debug("Reading config from stdin…");
3052 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &_f
);
3054 if (ignore_enoent
&& r
== -ENOENT
) {
3055 log_debug_errno(r
, "Failed to open \"%s\", ignoring: %m", fn
);
3059 return log_error_errno(r
, "Failed to open '%s': %m", fn
);
3061 log_debug("Reading config file \"%s\"…", fn
);
3066 _cleanup_free_
char *line
= NULL
;
3067 bool invalid_line
= false;
3071 k
= read_line(f
, LONG_LINE_MAX
, &line
);
3073 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
3080 if (IN_SET(*l
, 0, '#'))
3083 k
= parse_line(fn
, v
, l
, &invalid_line
, &uid_cache
, &gid_cache
);
3086 /* Allow reporting with a special code if the caller requested this */
3087 *invalid_config
= true;
3089 /* The first error becomes our return value */
3094 /* we have to determine age parameter for each entry of type X */
3095 ORDERED_HASHMAP_FOREACH(i
, globs
, iterator
) {
3097 Item
*j
, *candidate_item
= NULL
;
3099 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
3102 ORDERED_HASHMAP_FOREACH(j
, items
, iter
) {
3103 if (!IN_SET(j
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
))
3106 if (path_equal(j
->path
, i
->path
)) {
3111 if ((!candidate_item
&& path_startswith(i
->path
, j
->path
)) ||
3112 (candidate_item
&& path_startswith(j
->path
, candidate_item
->path
) && (fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)))
3116 if (candidate_item
&& candidate_item
->age_set
) {
3117 i
->age
= candidate_item
->age
;
3123 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
3131 static int parse_arguments(char **config_dirs
, char **args
, bool *invalid_config
) {
3135 STRV_FOREACH(arg
, args
) {
3136 r
= read_config_file(config_dirs
, *arg
, false, invalid_config
);
3144 static int read_config_files(char **config_dirs
, char **args
, bool *invalid_config
) {
3145 _cleanup_strv_free_
char **files
= NULL
;
3146 _cleanup_free_
char *p
= NULL
;
3150 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
3154 STRV_FOREACH(f
, files
)
3155 if (p
&& path_equal(*f
, p
)) {
3156 log_debug("Parsing arguments at position \"%s\"…", *f
);
3158 r
= parse_arguments(config_dirs
, args
, invalid_config
);
3162 /* Just warn, ignore result otherwise.
3163 * read_config_file() has some debug output, so no need to print anything. */
3164 (void) read_config_file(config_dirs
, *f
, true, invalid_config
);
3169 static int link_parent(ItemArray
*a
) {
3176 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
3177 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3178 * before their children, and clean up/remove children before their parents. */
3180 if (a
->n_items
<= 0)
3183 path
= a
->items
[0].path
;
3184 prefix
= newa(char, strlen(path
) + 1);
3185 PATH_FOREACH_PREFIX(prefix
, path
) {
3188 j
= ordered_hashmap_get(items
, prefix
);
3190 j
= ordered_hashmap_get(globs
, prefix
);
3192 r
= set_ensure_allocated(&j
->children
, NULL
);
3196 r
= set_put(j
->children
, a
);
3208 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
3209 ItemArray
, item_array_free
);
3211 static int run(int argc
, char *argv
[]) {
3212 _cleanup_strv_free_
char **config_dirs
= NULL
;
3213 bool invalid_config
= false;
3217 PHASE_REMOVE_AND_CLEAN
,
3223 r
= parse_argv(argc
, argv
);
3227 log_setup_service();
3229 /* Descending down file system trees might take a lot of fds */
3230 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
3233 r
= user_config_paths(&config_dirs
);
3235 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
3237 config_dirs
= strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
3242 if (DEBUG_LOGGING
) {
3243 _cleanup_free_
char *t
= NULL
;
3245 t
= strv_join(config_dirs
, "\n\t");
3247 log_debug("Looking for configuration files in (higher priority first):\n\t%s", t
);
3250 if (arg_cat_config
) {
3251 (void) pager_open(arg_pager_flags
);
3253 return cat_config(config_dirs
, argv
+ optind
);
3260 items
= ordered_hashmap_new(&item_array_hash_ops
);
3261 globs
= ordered_hashmap_new(&item_array_hash_ops
);
3262 if (!items
|| !globs
)
3265 /* If command line arguments are specified along with --replace, read all
3266 * configuration files and insert the positional arguments at the specified
3267 * place. Otherwise, if command line arguments are specified, execute just
3268 * them, and finally, without --replace= or any positional arguments, just
3269 * read configuration and execute it.
3271 if (arg_replace
|| optind
>= argc
)
3272 r
= read_config_files(config_dirs
, argv
+ optind
, &invalid_config
);
3274 r
= parse_arguments(config_dirs
, argv
+ optind
, &invalid_config
);
3278 /* Let's now link up all child/parent relationships */
3279 ORDERED_HASHMAP_FOREACH(a
, items
, iterator
) {
3284 ORDERED_HASHMAP_FOREACH(a
, globs
, iterator
) {
3290 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
3291 * operations. i.e. that we first clean out the platform we then build on. */
3292 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
3295 if (phase
== PHASE_REMOVE_AND_CLEAN
)
3296 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
3297 else if (phase
== PHASE_CREATE
)
3298 op
= arg_operation
& OPERATION_CREATE
;
3300 assert_not_reached("unexpected phase");
3302 if (op
== 0) /* Nothing requested in this phase */
3305 /* The non-globbing ones usually create things, hence we apply them first */
3306 ORDERED_HASHMAP_FOREACH(a
, items
, iterator
) {
3307 k
= process_item_array(a
, op
);
3308 if (k
< 0 && r
>= 0)
3312 /* The globbing ones usually alter things, hence we apply them second. */
3313 ORDERED_HASHMAP_FOREACH(a
, globs
, iterator
) {
3314 k
= process_item_array(a
, op
);
3315 if (k
< 0 && r
>= 0)
3320 if (ERRNO_IS_RESOURCE(-r
))
3325 return EX_CANTCREAT
;
3329 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);