1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
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"
29 #include "dissect-image.h"
33 #include "format-util.h"
35 #include "glob-util.h"
40 #include "main-func.h"
41 #include "missing_stat.h"
42 #include "missing_syscall.h"
44 #include "mount-util.h"
45 #include "mountpoint-util.h"
46 #include "offline-passwd.h"
48 #include "parse-util.h"
49 #include "path-lookup.h"
50 #include "path-util.h"
51 #include "pretty-print.h"
52 #include "rlimit-util.h"
54 #include "selinux-util.h"
56 #include "sort-util.h"
57 #include "specifier.h"
58 #include "stat-util.h"
59 #include "stdio-util.h"
60 #include "string-table.h"
61 #include "string-util.h"
63 #include "terminal-util.h"
64 #include "umask-util.h"
65 #include "user-util.h"
67 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
68 * them in the file system. This is intended to be used to create
69 * properly owned directories beneath /tmp, /var/tmp, /run, which are
70 * volatile and hence need to be recreated on bootup. */
72 typedef enum OperationMask
{
73 OPERATION_CREATE
= 1 << 0,
74 OPERATION_REMOVE
= 1 << 1,
75 OPERATION_CLEAN
= 1 << 2,
78 typedef enum ItemType
{
79 /* These ones take file names */
81 TRUNCATE_FILE
= 'F', /* deprecated: use f+ */
82 CREATE_DIRECTORY
= 'd',
83 TRUNCATE_DIRECTORY
= 'D',
84 CREATE_SUBVOLUME
= 'v',
85 CREATE_SUBVOLUME_INHERIT_QUOTA
= 'q',
86 CREATE_SUBVOLUME_NEW_QUOTA
= 'Q',
89 CREATE_CHAR_DEVICE
= 'c',
90 CREATE_BLOCK_DEVICE
= 'b',
93 /* These ones take globs */
95 EMPTY_DIRECTORY
= 'e',
97 RECURSIVE_SET_XATTR
= 'T',
99 RECURSIVE_SET_ACL
= 'A',
101 RECURSIVE_SET_ATTRIBUTE
= 'H',
103 IGNORE_DIRECTORY_PATH
= 'X',
105 RECURSIVE_REMOVE_PATH
= 'R',
107 RECURSIVE_RELABEL_PATH
= 'Z',
108 ADJUST_MODE
= 'm', /* legacy, 'z' is identical to this */
111 typedef struct Item
{
127 unsigned attribute_value
;
128 unsigned attribute_mask
;
135 bool attribute_set
:1;
137 bool keep_first_level
:1;
139 bool append_or_force
:1;
141 bool allow_failure
:1;
146 typedef struct ItemArray
{
151 struct ItemArray
*parent
;
155 typedef enum DirectoryType
{
163 static bool arg_cat_config
= false;
164 static bool arg_user
= false;
165 static OperationMask arg_operation
= 0;
166 static bool arg_boot
= false;
167 static PagerFlags arg_pager_flags
= 0;
169 static char **arg_include_prefixes
= NULL
;
170 static char **arg_exclude_prefixes
= NULL
;
171 static char *arg_root
= NULL
;
172 static char *arg_image
= NULL
;
173 static char *arg_replace
= NULL
;
175 #define MAX_DEPTH 256
177 static OrderedHashmap
*items
= NULL
, *globs
= NULL
;
178 static Set
*unix_sockets
= NULL
;
180 STATIC_DESTRUCTOR_REGISTER(items
, ordered_hashmap_freep
);
181 STATIC_DESTRUCTOR_REGISTER(globs
, ordered_hashmap_freep
);
182 STATIC_DESTRUCTOR_REGISTER(unix_sockets
, set_free_freep
);
183 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes
, freep
);
184 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes
, freep
);
185 STATIC_DESTRUCTOR_REGISTER(arg_root
, freep
);
186 STATIC_DESTRUCTOR_REGISTER(arg_image
, freep
);
188 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
);
189 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
);
191 static const Specifier specifier_table
[] = {
192 { 'a', specifier_architecture
, NULL
},
193 { 'b', specifier_boot_id
, NULL
},
194 { 'B', specifier_os_build_id
, NULL
},
195 { 'H', specifier_host_name
, NULL
},
196 { 'l', specifier_short_host_name
, NULL
},
197 { 'm', specifier_machine_id_safe
, NULL
},
198 { 'o', specifier_os_id
, NULL
},
199 { 'v', specifier_kernel_release
, NULL
},
200 { 'w', specifier_os_version_id
, NULL
},
201 { 'W', specifier_os_variant_id
, NULL
},
203 { 'h', specifier_user_home
, NULL
},
205 { 'C', specifier_directory
, UINT_TO_PTR(DIRECTORY_CACHE
) },
206 { 'L', specifier_directory
, UINT_TO_PTR(DIRECTORY_LOGS
) },
207 { 'S', specifier_directory
, UINT_TO_PTR(DIRECTORY_STATE
) },
208 { 't', specifier_directory
, UINT_TO_PTR(DIRECTORY_RUNTIME
) },
210 COMMON_CREDS_SPECIFIERS
,
212 COMMON_TMP_SPECIFIERS
,
216 static int specifier_machine_id_safe(char specifier
, const void *data
, const void *userdata
, char **ret
) {
219 /* If /etc/machine_id is missing or empty (e.g. in a chroot environment)
220 * return a recognizable error so that the caller can skip the rule
223 r
= specifier_machine_id(specifier
, data
, userdata
, ret
);
224 if (IN_SET(r
, -ENOENT
, -ENOMEDIUM
))
230 static int specifier_directory(char specifier
, const void *data
, const void *userdata
, char **ret
) {
236 static const struct table_entry paths_system
[] = {
237 [DIRECTORY_RUNTIME
] = { SD_PATH_SYSTEM_RUNTIME
},
238 [DIRECTORY_STATE
] = { SD_PATH_SYSTEM_STATE_PRIVATE
},
239 [DIRECTORY_CACHE
] = { SD_PATH_SYSTEM_STATE_CACHE
},
240 [DIRECTORY_LOGS
] = { SD_PATH_SYSTEM_STATE_LOGS
},
243 static const struct table_entry paths_user
[] = {
244 [DIRECTORY_RUNTIME
] = { SD_PATH_USER_RUNTIME
},
245 [DIRECTORY_STATE
] = { SD_PATH_USER_CONFIGURATION
},
246 [DIRECTORY_CACHE
] = { SD_PATH_USER_STATE_CACHE
},
247 [DIRECTORY_LOGS
] = { SD_PATH_USER_CONFIGURATION
, "log" },
251 const struct table_entry
*paths
;
253 assert_cc(ELEMENTSOF(paths_system
) == ELEMENTSOF(paths_user
));
254 paths
= arg_user
? paths_user
: paths_system
;
256 i
= PTR_TO_UINT(data
);
257 assert(i
< ELEMENTSOF(paths_system
));
259 return sd_path_lookup(paths
[i
].type
, paths
[i
].suffix
, ret
);
262 static int log_unresolvable_specifier(const char *filename
, unsigned line
) {
263 static bool notified
= false;
265 /* In system mode, this is called when /etc is not fully initialized (e.g.
266 * in a chroot environment) where some specifiers are unresolvable. In user
267 * mode, this is called when some variables are not defined. These cases are
268 * not considered as an error so log at LOG_NOTICE only for the first time
269 * and then downgrade this to LOG_DEBUG for the rest. */
272 notified
? LOG_DEBUG
: LOG_NOTICE
,
274 "Failed to resolve specifier: %s, skipping",
275 arg_user
? "Required $XDG_... variable not defined" : "uninitialized /etc detected");
278 log_notice("All rules containing unresolvable specifiers will be skipped.");
284 static int user_config_paths(char*** ret
) {
285 _cleanup_strv_free_
char **config_dirs
= NULL
, **data_dirs
= NULL
;
286 _cleanup_free_
char *persistent_config
= NULL
, *runtime_config
= NULL
, *data_home
= NULL
;
287 _cleanup_strv_free_
char **res
= NULL
;
290 r
= xdg_user_dirs(&config_dirs
, &data_dirs
);
294 r
= xdg_user_config_dir(&persistent_config
, "/user-tmpfiles.d");
295 if (r
< 0 && r
!= -ENXIO
)
298 r
= xdg_user_runtime_dir(&runtime_config
, "/user-tmpfiles.d");
299 if (r
< 0 && r
!= -ENXIO
)
302 r
= xdg_user_data_dir(&data_home
, "/user-tmpfiles.d");
303 if (r
< 0 && r
!= -ENXIO
)
306 r
= strv_extend_strv_concat(&res
, config_dirs
, "/user-tmpfiles.d");
310 r
= strv_extend(&res
, persistent_config
);
314 r
= strv_extend(&res
, runtime_config
);
318 r
= strv_extend(&res
, data_home
);
322 r
= strv_extend_strv_concat(&res
, data_dirs
, "/user-tmpfiles.d");
326 r
= path_strv_make_absolute_cwd(res
);
330 *ret
= TAKE_PTR(res
);
334 static bool needs_glob(ItemType t
) {
338 IGNORE_DIRECTORY_PATH
,
340 RECURSIVE_REMOVE_PATH
,
344 RECURSIVE_RELABEL_PATH
,
350 RECURSIVE_SET_ATTRIBUTE
);
353 static bool takes_ownership(ItemType t
) {
361 CREATE_SUBVOLUME_INHERIT_QUOTA
,
362 CREATE_SUBVOLUME_NEW_QUOTA
,
370 IGNORE_DIRECTORY_PATH
,
372 RECURSIVE_REMOVE_PATH
);
375 static struct Item
* find_glob(OrderedHashmap
*h
, const char *match
) {
378 ORDERED_HASHMAP_FOREACH(j
, h
) {
381 for (n
= 0; n
< j
->n_items
; n
++) {
382 Item
*item
= j
->items
+ n
;
384 if (fnmatch(item
->path
, match
, FNM_PATHNAME
|FNM_PERIOD
) == 0)
392 static int load_unix_sockets(void) {
393 _cleanup_set_free_free_ Set
*sockets
= NULL
;
394 _cleanup_fclose_
FILE *f
= NULL
;
400 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
402 sockets
= set_new(&path_hash_ops
);
406 f
= fopen("/proc/net/unix", "re");
408 return log_full_errno(errno
== ENOENT
? LOG_DEBUG
: LOG_WARNING
, errno
,
409 "Failed to open /proc/net/unix, ignoring: %m");
412 r
= read_line(f
, LONG_LINE_MAX
, NULL
);
414 return log_warning_errno(r
, "Failed to skip /proc/net/unix header line: %m");
416 return log_warning_errno(SYNTHETIC_ERRNO(EIO
), "Premature end of file reading /proc/net/unix.");
419 _cleanup_free_
char *line
= NULL
, *s
= NULL
;
422 r
= read_line(f
, LONG_LINE_MAX
, &line
);
424 return log_warning_errno(r
, "Failed to read /proc/net/unix line, ignoring: %m");
425 if (r
== 0) /* EOF */
428 p
= strchr(line
, ':');
436 p
+= strspn(p
, WHITESPACE
);
437 p
+= strcspn(p
, WHITESPACE
); /* skip one more word */
438 p
+= strspn(p
, WHITESPACE
);
447 path_simplify(s
, false);
449 r
= set_consume(sockets
, s
);
453 return log_warning_errno(r
, "Failed to add AF_UNIX socket to set, ignoring: %m");
458 unix_sockets
= TAKE_PTR(sockets
);
462 static bool unix_socket_alive(const char *fn
) {
465 if (load_unix_sockets() < 0)
466 return true; /* We don't know, so assume yes */
468 return !!set_get(unix_sockets
, (char*) fn
);
471 static DIR* xopendirat_nomod(int dirfd
, const char *path
) {
474 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
|O_NOATIME
);
478 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
482 dir
= xopendirat(dirfd
, path
, O_NOFOLLOW
);
484 log_debug_errno(errno
, "Cannot open %sdirectory \"%s\": %m", dirfd
== AT_FDCWD
? "" : "sub", path
);
489 static DIR* opendir_nomod(const char *path
) {
490 return xopendirat_nomod(AT_FDCWD
, path
);
493 static inline nsec_t
load_statx_timestamp_nsec(const struct statx_timestamp
*ts
) {
497 return NSEC_INFINITY
;
499 if ((nsec_t
) ts
->tv_sec
>= (UINT64_MAX
- ts
->tv_nsec
) / NSEC_PER_SEC
)
500 return NSEC_INFINITY
;
502 return ts
->tv_sec
* NSEC_PER_SEC
+ ts
->tv_nsec
;
505 static int dir_cleanup(
509 nsec_t self_atime_nsec
,
510 nsec_t self_mtime_nsec
,
516 bool keep_this_level
) {
518 bool deleted
= false;
522 FOREACH_DIRENT_ALL(dent
, d
, break) {
523 _cleanup_free_
char *sub_path
= NULL
;
524 nsec_t atime_nsec
, mtime_nsec
, ctime_nsec
, btime_nsec
;
526 if (dot_or_dot_dot(dent
->d_name
))
529 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
530 * explicitly where we are looking at a mount point, for free as side information. Determining
531 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
532 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
533 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
534 * while on older kernels's well do traditional st_dev based detection of mount points.
536 * Using statx() for detecting mount points also has the benfit that we handle weird file
537 * systems such as overlayfs better where each file is originating from a different
540 STRUCT_STATX_DEFINE(sx
);
543 dirfd(d
), dent
->d_name
,
544 AT_SYMLINK_NOFOLLOW
|AT_NO_AUTOMOUNT
,
545 STATX_TYPE
|STATX_MODE
|STATX_UID
|STATX_ATIME
|STATX_MTIME
|STATX_CTIME
|STATX_BTIME
,
550 /* FUSE, NFS mounts, SELinux might return EACCES */
551 r
= log_full_errno(errno
== EACCES
? LOG_DEBUG
: LOG_ERR
, errno
,
552 "statx(%s/%s) failed: %m", p
, dent
->d_name
);
556 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
)) {
557 /* Yay, we have the mount point API, use it */
558 if (FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
)) {
559 log_debug("Ignoring \"%s/%s\": different mount points.", p
, dent
->d_name
);
563 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
564 * back to traditional stx_dev checking. */
565 if (sx
.stx_dev_major
!= rootdev_major
||
566 sx
.stx_dev_minor
!= rootdev_minor
) {
567 log_debug("Ignoring \"%s/%s\": different filesystem.", p
, dent
->d_name
);
571 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
572 * major/minors. This type of query is not supported on all kernels or filesystem types
574 if (S_ISDIR(sx
.stx_mode
)) {
577 q
= fd_is_mount_point(dirfd(d
), dent
->d_name
, 0);
579 log_debug_errno(q
, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p
, dent
->d_name
);
581 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p
, dent
->d_name
);
587 atime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_ATIME
) ? load_statx_timestamp_nsec(&sx
.stx_atime
) : 0;
588 mtime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_MTIME
) ? load_statx_timestamp_nsec(&sx
.stx_mtime
) : 0;
589 ctime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_CTIME
) ? load_statx_timestamp_nsec(&sx
.stx_ctime
) : 0;
590 btime_nsec
= FLAGS_SET(sx
.stx_mask
, STATX_BTIME
) ? load_statx_timestamp_nsec(&sx
.stx_btime
) : 0;
592 sub_path
= path_join(p
, dent
->d_name
);
598 /* Is there an item configured for this path? */
599 if (ordered_hashmap_get(items
, sub_path
)) {
600 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path
);
604 if (find_glob(globs
, sub_path
)) {
605 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path
);
609 if (S_ISDIR(sx
.stx_mode
)) {
610 _cleanup_closedir_
DIR *sub_dir
= NULL
;
613 streq(dent
->d_name
, "lost+found") &&
615 log_debug("Ignoring directory \"%s\".", sub_path
);
620 log_warning("Reached max depth on \"%s\".", sub_path
);
624 sub_dir
= xopendirat_nomod(dirfd(d
), dent
->d_name
);
627 r
= log_warning_errno(errno
, "Opening directory \"%s\" failed, ignoring: %m", sub_path
);
632 if (flock(dirfd(sub_dir
), LOCK_EX
|LOCK_NB
) < 0) {
633 log_debug_errno(errno
, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p
);
639 atime_nsec
, mtime_nsec
, cutoff_nsec
,
640 rootdev_major
, rootdev_minor
,
641 false, maxdepth
-1, false);
646 /* Note: if you are wondering why we don't support the sticky bit for excluding
647 * directories from cleaning like we do it for other file system objects: well, the
648 * sticky bit already has a meaning for directories, so we don't want to overload
651 if (keep_this_level
) {
652 log_debug("Keeping directory \"%s\".", sub_path
);
656 /* Ignore ctime, we change it when deleting */
657 if (mtime_nsec
!= NSEC_INFINITY
&& mtime_nsec
>= cutoff_nsec
) {
658 char a
[FORMAT_TIMESTAMP_MAX
];
659 /* Follows spelling in stat(1). */
660 log_debug("Directory \"%s\": modify time %s is too new.",
662 format_timestamp_style(a
, sizeof(a
), mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
666 if (atime_nsec
!= NSEC_INFINITY
&& atime_nsec
>= cutoff_nsec
) {
667 char a
[FORMAT_TIMESTAMP_MAX
];
668 log_debug("Directory \"%s\": access time %s is too new.",
670 format_timestamp_style(a
, sizeof(a
), atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
674 if (btime_nsec
!= NSEC_INFINITY
&& btime_nsec
>= cutoff_nsec
) {
675 char a
[FORMAT_TIMESTAMP_MAX
];
676 log_debug("Directory \"%s\": birth time %s is too new.",
678 format_timestamp_style(a
, sizeof(a
), btime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
682 log_debug("Removing directory \"%s\".", sub_path
);
683 if (unlinkat(dirfd(d
), dent
->d_name
, AT_REMOVEDIR
) < 0)
684 if (!IN_SET(errno
, ENOENT
, ENOTEMPTY
))
685 r
= log_warning_errno(errno
, "Failed to remove directory \"%s\", ignoring: %m", sub_path
);
688 /* Skip files for which the sticky bit is set. These are semantics we define, and are
689 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
690 if (sx
.stx_mode
& S_ISVTX
) {
691 log_debug("Skipping \"%s\": sticky bit set.", sub_path
);
696 S_ISREG(sx
.stx_mode
) &&
698 STR_IN_SET(dent
->d_name
,
702 log_debug("Skipping \"%s\".", sub_path
);
706 /* Ignore sockets that are listed in /proc/net/unix */
707 if (S_ISSOCK(sx
.stx_mode
) && unix_socket_alive(sub_path
)) {
708 log_debug("Skipping \"%s\": live socket.", sub_path
);
712 /* Ignore device nodes */
713 if (S_ISCHR(sx
.stx_mode
) || S_ISBLK(sx
.stx_mode
)) {
714 log_debug("Skipping \"%s\": a device.", sub_path
);
718 /* Keep files on this level around if this is requested */
719 if (keep_this_level
) {
720 log_debug("Keeping \"%s\".", sub_path
);
724 if (mtime_nsec
!= NSEC_INFINITY
&& mtime_nsec
>= cutoff_nsec
) {
725 char a
[FORMAT_TIMESTAMP_MAX
];
726 /* Follows spelling in stat(1). */
727 log_debug("File \"%s\": modify time %s is too new.",
729 format_timestamp_style(a
, sizeof(a
), mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
733 if (atime_nsec
!= NSEC_INFINITY
&& atime_nsec
>= cutoff_nsec
) {
734 char a
[FORMAT_TIMESTAMP_MAX
];
735 log_debug("File \"%s\": access time %s is too new.",
737 format_timestamp_style(a
, sizeof(a
), atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
741 if (ctime_nsec
!= NSEC_INFINITY
&& ctime_nsec
>= cutoff_nsec
) {
742 char a
[FORMAT_TIMESTAMP_MAX
];
743 log_debug("File \"%s\": change time %s is too new.",
745 format_timestamp_style(a
, sizeof(a
), ctime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
749 if (btime_nsec
!= NSEC_INFINITY
&& btime_nsec
>= cutoff_nsec
) {
750 char a
[FORMAT_TIMESTAMP_MAX
];
751 log_debug("File \"%s\": birth time %s is too new.",
753 format_timestamp_style(a
, sizeof(a
), btime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
757 log_debug("Removing \"%s\".", sub_path
);
758 if (unlinkat(dirfd(d
), dent
->d_name
, 0) < 0)
760 r
= log_warning_errno(errno
, "Failed to remove \"%s\", ignoring: %m", sub_path
);
768 char a
[FORMAT_TIMESTAMP_MAX
], m
[FORMAT_TIMESTAMP_MAX
];
769 struct timespec ts
[2];
771 log_debug("Restoring access and modification time on \"%s\": %s, %s",
773 format_timestamp_style(a
, sizeof(a
), self_atime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
),
774 format_timestamp_style(m
, sizeof(m
), self_mtime_nsec
/ NSEC_PER_USEC
, TIMESTAMP_US
));
776 timespec_store_nsec(ts
+ 0, self_atime_nsec
);
777 timespec_store_nsec(ts
+ 1, self_mtime_nsec
);
779 /* Restore original directory timestamps */
780 if (futimens(dirfd(d
), ts
) < 0)
781 log_warning_errno(errno
, "Failed to revert timestamps of '%s', ignoring: %m", p
);
787 static bool dangerous_hardlinks(void) {
788 _cleanup_free_
char *value
= NULL
;
789 static int cached
= -1;
792 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
793 * what the upstream default is. */
798 r
= read_one_line_file("/proc/sys/fs/protected_hardlinks", &value
);
800 log_debug_errno(r
, "Failed to read fs.protected_hardlinks sysctl: %m");
804 r
= parse_boolean(value
);
806 log_debug_errno(r
, "Failed to parse fs.protected_hardlinks sysctl: %m");
814 static bool hardlink_vulnerable(const struct stat
*st
) {
817 return !S_ISDIR(st
->st_mode
) && st
->st_nlink
> 1 && dangerous_hardlinks();
820 static mode_t
process_mask_perms(mode_t mode
, mode_t current
) {
822 if ((current
& 0111) == 0)
824 if ((current
& 0222) == 0)
826 if ((current
& 0444) == 0)
828 if (!S_ISDIR(current
))
829 mode
&= ~07000; /* remove sticky/sgid/suid bit, unless directory */
834 static int fd_set_perms(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
844 if (!i
->mode_set
&& !i
->uid_set
&& !i
->gid_set
)
848 if (fstat(fd
, &stbuf
) < 0)
849 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
853 if (hardlink_vulnerable(st
))
854 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
855 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
858 /* Do we need a chown()? */
860 (i
->uid_set
&& i
->uid
!= st
->st_uid
) ||
861 (i
->gid_set
&& i
->gid
!= st
->st_gid
);
863 /* Calculate the mode to apply */
864 new_mode
= i
->mode_set
? (i
->mask_perms
?
865 process_mask_perms(i
->mode
, st
->st_mode
) :
867 (st
->st_mode
& 07777);
869 if (i
->mode_set
&& do_chown
) {
870 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
871 * the new mode. That way there's no time window where the file exists under the old owner
872 * with more than the old access modes — and not under the new owner with more than the new
873 * access modes either. */
875 if (S_ISLNK(st
->st_mode
))
876 log_debug("Skipping temporary mode fix for symlink %s.", path
);
878 mode_t m
= new_mode
& st
->st_mode
; /* Mask new mode by old mode */
880 if (((m
^ st
->st_mode
) & 07777) == 0)
881 log_debug("\"%s\" matches temporary mode %o already.", path
, m
);
883 log_debug("Temporarily changing \"%s\" to mode %o.", path
, m
);
884 r
= fchmod_opath(fd
, m
);
886 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
892 log_debug("Changing \"%s\" to owner "UID_FMT
":"GID_FMT
,
894 i
->uid_set
? i
->uid
: UID_INVALID
,
895 i
->gid_set
? i
->gid
: GID_INVALID
);
899 i
->uid_set
? i
->uid
: UID_INVALID
,
900 i
->gid_set
? i
->gid
: GID_INVALID
,
902 return log_error_errno(errno
, "fchownat() of %s failed: %m", path
);
905 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
906 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
907 if (i
->mode_set
|| do_chown
) {
908 if (S_ISLNK(st
->st_mode
))
909 log_debug("Skipping mode fix for symlink %s.", path
);
911 /* Check if the chmod() is unnecessary. Note that if we did a chown() before we always
912 * chmod() here again, since it might have mangled the bits. */
913 if (!do_chown
&& ((new_mode
^ st
->st_mode
) & 07777) == 0)
914 log_debug("\"%s\" matches mode %o already.", path
, new_mode
);
916 log_debug("Changing \"%s\" to mode %o.", path
, new_mode
);
917 r
= fchmod_opath(fd
, new_mode
);
919 return log_error_errno(r
, "fchmod() of %s failed: %m", path
);
925 return label_fix(path
, 0);
928 static int path_open_parent_safe(const char *path
) {
929 _cleanup_free_
char *dn
= NULL
;
932 if (path_equal(path
, "/") || !path_is_normalized(path
))
933 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
934 "Failed to open parent of '%s': invalid path.",
937 dn
= dirname_malloc(path
);
941 r
= chase_symlinks(dn
, arg_root
, CHASE_SAFE
|CHASE_WARN
, NULL
, &fd
);
942 if (r
< 0 && r
!= -ENOLINK
)
943 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
945 return r
< 0 ? r
: fd
;
948 static int path_open_safe(const char *path
) {
951 /* path_open_safe() returns a file descriptor opened with O_PATH after
952 * verifying that the path doesn't contain unsafe transitions, except
953 * for its final component as the function does not follow symlink. */
957 if (!path_is_normalized(path
))
958 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
959 "Failed to open invalid path '%s'.",
962 r
= chase_symlinks(path
, arg_root
, CHASE_SAFE
|CHASE_WARN
|CHASE_NOFOLLOW
, NULL
, &fd
);
963 if (r
< 0 && r
!= -ENOLINK
)
964 return log_error_errno(r
, "Failed to validate path %s: %m", path
);
966 return r
< 0 ? r
: fd
;
969 static int path_set_perms(Item
*i
, const char *path
) {
970 _cleanup_close_
int fd
= -1;
975 fd
= path_open_safe(path
);
979 return fd_set_perms(i
, fd
, path
, NULL
);
982 static int parse_xattrs_from_arg(Item
*i
) {
992 _cleanup_free_
char *name
= NULL
, *value
= NULL
, *xattr
= NULL
;
994 r
= extract_first_word(&p
, &xattr
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_CUNESCAPE
);
996 log_warning_errno(r
, "Failed to parse extended attribute '%s', ignoring: %m", p
);
1000 r
= split_pair(xattr
, "=", &name
, &value
);
1002 log_warning_errno(r
, "Failed to parse extended attribute, ignoring: %s", xattr
);
1006 if (isempty(name
) || isempty(value
)) {
1007 log_warning("Malformed extended attribute found, ignoring: %s", xattr
);
1011 if (strv_push_pair(&i
->xattrs
, name
, value
) < 0)
1014 name
= value
= NULL
;
1020 static int fd_set_xattrs(Item
*i
, int fd
, const char *path
, const struct stat
*st
) {
1021 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1022 char **name
, **value
;
1028 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1030 STRV_FOREACH_PAIR(name
, value
, i
->xattrs
) {
1031 log_debug("Setting extended attribute '%s=%s' on %s.", *name
, *value
, path
);
1032 if (setxattr(procfs_path
, *name
, *value
, strlen(*value
), 0) < 0)
1033 return log_error_errno(errno
, "Setting extended attribute %s=%s on %s failed: %m",
1034 *name
, *value
, path
);
1039 static int path_set_xattrs(Item
*i
, const char *path
) {
1040 _cleanup_close_
int fd
= -1;
1045 fd
= path_open_safe(path
);
1049 return fd_set_xattrs(i
, fd
, path
, NULL
);
1052 static int parse_acls_from_arg(Item
*item
) {
1058 /* If append_or_force (= modify) is set, we will not modify the acl
1059 * afterwards, so the mask can be added now if necessary. */
1061 r
= parse_acl(item
->argument
, &item
->acl_access
, &item
->acl_default
, !item
->append_or_force
);
1063 log_warning_errno(r
, "Failed to parse ACL \"%s\": %m. Ignoring", item
->argument
);
1065 log_warning("ACLs are not supported. Ignoring.");
1072 static int path_set_acl(const char *path
, const char *pretty
, acl_type_t type
, acl_t acl
, bool modify
) {
1073 _cleanup_(acl_free_charpp
) char *t
= NULL
;
1074 _cleanup_(acl_freep
) acl_t dup
= NULL
;
1077 /* Returns 0 for success, positive error if already warned,
1078 * negative error otherwise. */
1081 r
= acls_for_file(path
, type
, acl
, &dup
);
1085 r
= calc_acl_mask_if_needed(&dup
);
1093 /* the mask was already added earlier if needed */
1096 r
= add_base_acls_if_needed(&dup
, path
);
1100 t
= acl_to_any_text(dup
, NULL
, ',', TEXT_ABBREVIATE
);
1101 log_debug("Setting %s ACL %s on %s.",
1102 type
== ACL_TYPE_ACCESS
? "access" : "default",
1105 r
= acl_set_file(path
, type
, dup
);
1107 if (ERRNO_IS_NOT_SUPPORTED(errno
))
1108 /* No error if filesystem doesn't support ACLs. Return negative. */
1111 /* Return positive to indicate we already warned */
1112 return -log_error_errno(errno
,
1113 "Setting %s ACL \"%s\" on %s failed: %m",
1114 type
== ACL_TYPE_ACCESS
? "access" : "default",
1121 static int fd_set_acls(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1124 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1132 if (fstat(fd
, &stbuf
) < 0)
1133 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1137 if (hardlink_vulnerable(st
))
1138 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
1139 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1142 if (S_ISLNK(st
->st_mode
)) {
1143 log_debug("Skipping ACL fix for symlink %s.", path
);
1147 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1149 if (item
->acl_access
)
1150 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_ACCESS
, item
->acl_access
, item
->append_or_force
);
1152 /* set only default acls to folders */
1153 if (r
== 0 && item
->acl_default
&& S_ISDIR(st
->st_mode
))
1154 r
= path_set_acl(procfs_path
, path
, ACL_TYPE_DEFAULT
, item
->acl_default
, item
->append_or_force
);
1156 if (ERRNO_IS_NOT_SUPPORTED(r
)) {
1157 log_debug_errno(r
, "ACLs not supported by file system at %s", path
);
1162 return -r
; /* already warned */
1164 /* The above procfs paths don't work if /proc is not mounted. */
1165 if (r
== -ENOENT
&& proc_mounted() == 0)
1169 return log_error_errno(r
, "ACL operation on \"%s\" failed: %m", path
);
1174 static int path_set_acls(Item
*item
, const char *path
) {
1177 _cleanup_close_
int fd
= -1;
1182 fd
= path_open_safe(path
);
1186 r
= fd_set_acls(item
, fd
, path
, NULL
);
1191 static int parse_attribute_from_arg(Item
*item
) {
1193 static const struct {
1197 { 'A', FS_NOATIME_FL
}, /* do not update atime */
1198 { 'S', FS_SYNC_FL
}, /* Synchronous updates */
1199 { 'D', FS_DIRSYNC_FL
}, /* dirsync behaviour (directories only) */
1200 { 'a', FS_APPEND_FL
}, /* writes to file may only append */
1201 { 'c', FS_COMPR_FL
}, /* Compress file */
1202 { 'd', FS_NODUMP_FL
}, /* do not dump file */
1203 { 'e', FS_EXTENT_FL
}, /* Extents */
1204 { 'i', FS_IMMUTABLE_FL
}, /* Immutable file */
1205 { 'j', FS_JOURNAL_DATA_FL
}, /* Reserved for ext3 */
1206 { 's', FS_SECRM_FL
}, /* Secure deletion */
1207 { 'u', FS_UNRM_FL
}, /* Undelete */
1208 { 't', FS_NOTAIL_FL
}, /* file tail should not be merged */
1209 { 'T', FS_TOPDIR_FL
}, /* Top of directory hierarchies */
1210 { 'C', FS_NOCOW_FL
}, /* Do not cow file */
1211 { 'P', FS_PROJINHERIT_FL
}, /* Inherit the quota project ID */
1220 unsigned value
= 0, mask
= 0;
1230 } else if (*p
== '-') {
1233 } else if (*p
== '=') {
1239 if (isempty(p
) && mode
!= MODE_SET
)
1240 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1241 "Setting file attribute on '%s' needs an attribute specification.",
1244 for (; p
&& *p
; p
++) {
1247 for (i
= 0; i
< ELEMENTSOF(attributes
); i
++)
1248 if (*p
== attributes
[i
].character
)
1251 if (i
>= ELEMENTSOF(attributes
))
1252 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1253 "Unknown file attribute '%c' on '%s'.",
1256 v
= attributes
[i
].value
;
1258 SET_FLAG(value
, v
, IN_SET(mode
, MODE_ADD
, MODE_SET
));
1263 if (mode
== MODE_SET
)
1264 mask
|= CHATTR_ALL_FL
;
1268 item
->attribute_mask
= mask
;
1269 item
->attribute_value
= value
;
1270 item
->attribute_set
= true;
1275 static int fd_set_attribute(Item
*item
, int fd
, const char *path
, const struct stat
*st
) {
1276 _cleanup_close_
int procfs_fd
= -1;
1285 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1289 if (fstat(fd
, &stbuf
) < 0)
1290 return log_error_errno(errno
, "fstat(%s) failed: %m", path
);
1294 /* Issuing the file attribute ioctls on device nodes is not
1295 * safe, as that will be delivered to the drivers, not the
1296 * file system containing the device node. */
1297 if (!S_ISREG(st
->st_mode
) && !S_ISDIR(st
->st_mode
))
1298 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1299 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1302 f
= item
->attribute_value
& item
->attribute_mask
;
1304 /* Mask away directory-specific flags */
1305 if (!S_ISDIR(st
->st_mode
))
1306 f
&= ~FS_DIRSYNC_FL
;
1308 procfs_fd
= fd_reopen(fd
, O_RDONLY
|O_CLOEXEC
|O_NOATIME
);
1310 return log_error_errno(procfs_fd
, "Failed to re-open '%s': %m", path
);
1312 unsigned previous
, current
;
1313 r
= chattr_full(NULL
, procfs_fd
, f
, item
->attribute_mask
, &previous
, ¤t
, true);
1315 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1316 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1317 path
, previous
, current
, (previous
& ~item
->attribute_mask
) | (f
& item
->attribute_mask
));
1319 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1320 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1321 path
, item
->attribute_value
, item
->attribute_mask
);
1326 static int path_set_attribute(Item
*item
, const char *path
) {
1327 _cleanup_close_
int fd
= -1;
1329 if (!item
->attribute_set
|| item
->attribute_mask
== 0)
1332 fd
= path_open_safe(path
);
1336 return fd_set_attribute(item
, fd
, path
, NULL
);
1339 static int write_one_file(Item
*i
, const char *path
) {
1340 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1346 assert(i
->argument
);
1347 assert(i
->type
== WRITE_FILE
);
1349 /* Validate the path and keep the fd on the directory for opening the
1350 * file so we're sure that it can't be changed behind our back. */
1351 dir_fd
= path_open_parent_safe(path
);
1355 bn
= basename(path
);
1357 /* Follows symlinks */
1358 fd
= openat(dir_fd
, bn
,
1359 O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
|(i
->append_or_force
? O_APPEND
: 0),
1362 if (errno
== ENOENT
) {
1363 log_debug_errno(errno
, "Not writing missing file \"%s\": %m", path
);
1367 if (i
->allow_failure
)
1368 return log_debug_errno(errno
, "Failed to open file \"%s\", ignoring: %m", path
);
1370 return log_error_errno(errno
, "Failed to open file \"%s\": %m", path
);
1373 /* 'w' is allowed to write into any kind of files. */
1374 log_debug("Writing to \"%s\".", path
);
1376 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1378 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1380 return fd_set_perms(i
, fd
, path
, NULL
);
1383 static int create_file(Item
*i
, const char *path
) {
1384 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1385 struct stat stbuf
, *st
= NULL
;
1391 assert(i
->type
== CREATE_FILE
);
1393 /* 'f' operates on regular files exclusively. */
1395 /* Validate the path and keep the fd on the directory for opening the
1396 * file so we're sure that it can't be changed behind our back. */
1397 dir_fd
= path_open_parent_safe(path
);
1401 bn
= basename(path
);
1403 RUN_WITH_UMASK(0000) {
1404 mac_selinux_create_file_prepare(path
, S_IFREG
);
1405 fd
= openat(dir_fd
, bn
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1406 mac_selinux_create_file_clear();
1410 /* Even on a read-only filesystem, open(2) returns EEXIST if the
1411 * file already exists. It returns EROFS only if it needs to
1412 * create the file. */
1413 if (errno
!= EEXIST
)
1414 return log_error_errno(errno
, "Failed to create file %s: %m", path
);
1416 /* Re-open the file. At that point it must exist since open(2)
1417 * failed with EEXIST. We still need to check if the perms/mode
1418 * need to be changed. For read-only filesystems, we let
1419 * fd_set_perms() report the error if the perms need to be
1421 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1423 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1425 if (fstat(fd
, &stbuf
) < 0)
1426 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1428 if (!S_ISREG(stbuf
.st_mode
))
1429 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1430 "%s exists and is not a regular file.",
1436 log_debug("\"%s\" has been created.", path
);
1439 log_debug("Writing to \"%s\".", path
);
1441 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1443 return log_error_errno(r
, "Failed to write file \"%s\": %m", path
);
1447 return fd_set_perms(i
, fd
, path
, st
);
1450 static int truncate_file(Item
*i
, const char *path
) {
1451 _cleanup_close_
int fd
= -1, dir_fd
= -1;
1452 struct stat stbuf
, *st
= NULL
;
1459 assert(i
->type
== TRUNCATE_FILE
|| (i
->type
== CREATE_FILE
&& i
->append_or_force
));
1461 /* We want to operate on regular file exclusively especially since
1462 * O_TRUNC is unspecified if the file is neither a regular file nor a
1463 * fifo nor a terminal device. Therefore we first open the file and make
1464 * sure it's a regular one before truncating it. */
1466 /* Validate the path and keep the fd on the directory for opening the
1467 * file so we're sure that it can't be changed behind our back. */
1468 dir_fd
= path_open_parent_safe(path
);
1472 bn
= basename(path
);
1474 RUN_WITH_UMASK(0000) {
1475 mac_selinux_create_file_prepare(path
, S_IFREG
);
1476 fd
= openat(dir_fd
, bn
, O_CREAT
|O_NOFOLLOW
|O_NONBLOCK
|O_CLOEXEC
|O_WRONLY
|O_NOCTTY
, i
->mode
);
1477 mac_selinux_create_file_clear();
1482 return log_error_errno(errno
, "Failed to open/create file %s: %m", path
);
1484 /* On a read-only filesystem, we don't want to fail if the
1485 * target is already empty and the perms are set. So we still
1486 * proceed with the sanity checks and let the remaining
1487 * operations fail with EROFS if they try to modify the target
1490 fd
= openat(dir_fd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
, i
->mode
);
1492 if (errno
== ENOENT
)
1493 return log_error_errno(SYNTHETIC_ERRNO(EROFS
),
1494 "Cannot create file %s on a read-only file system.",
1497 return log_error_errno(errno
, "Failed to re-open file %s: %m", path
);
1503 if (fstat(fd
, &stbuf
) < 0)
1504 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1506 if (!S_ISREG(stbuf
.st_mode
))
1507 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1508 "%s exists and is not a regular file.",
1511 if (stbuf
.st_size
> 0) {
1512 if (ftruncate(fd
, 0) < 0) {
1513 r
= erofs
? -EROFS
: -errno
;
1514 return log_error_errno(r
, "Failed to truncate file %s: %m", path
);
1519 log_debug("\"%s\" has been created.", path
);
1522 log_debug("Writing to \"%s\".", path
);
1524 r
= loop_write(fd
, i
->argument
, strlen(i
->argument
), false);
1526 r
= erofs
? -EROFS
: r
;
1527 return log_error_errno(r
, "Failed to write file %s: %m", path
);
1531 return fd_set_perms(i
, fd
, path
, st
);
1534 static int copy_files(Item
*i
) {
1535 _cleanup_close_
int dfd
= -1, fd
= -1;
1539 log_debug("Copying tree \"%s\" to \"%s\".", i
->argument
, i
->path
);
1541 bn
= basename(i
->path
);
1543 /* Validate the path and use the returned directory fd for copying the
1544 * target so we're sure that the path can't be changed behind our
1546 dfd
= path_open_parent_safe(i
->path
);
1550 r
= copy_tree_at(AT_FDCWD
, i
->argument
,
1552 i
->uid_set
? i
->uid
: UID_INVALID
,
1553 i
->gid_set
? i
->gid
: GID_INVALID
,
1554 COPY_REFLINK
| COPY_MERGE_EMPTY
| COPY_MAC_CREATE
| COPY_HARDLINKS
);
1558 /* If the target already exists on read-only filesystems, trying
1559 * to create the target will not fail with EEXIST but with
1561 if (r
== -EROFS
&& faccessat(dfd
, bn
, F_OK
, AT_SYMLINK_NOFOLLOW
) == 0)
1565 return log_error_errno(r
, "Failed to copy files to %s: %m", i
->path
);
1567 if (stat(i
->argument
, &a
) < 0)
1568 return log_error_errno(errno
, "stat(%s) failed: %m", i
->argument
);
1570 if (fstatat(dfd
, bn
, &b
, AT_SYMLINK_NOFOLLOW
) < 0)
1571 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1573 if ((a
.st_mode
^ b
.st_mode
) & S_IFMT
) {
1574 log_debug("Can't copy to %s, file exists already and is of different type", i
->path
);
1579 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1581 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1583 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1591 _CREATION_MODE_INVALID
= -EINVAL
,
1594 static const char *const creation_mode_verb_table
[_CREATION_MODE_MAX
] = {
1595 [CREATION_NORMAL
] = "Created",
1596 [CREATION_EXISTING
] = "Found existing",
1597 [CREATION_FORCE
] = "Created replacement",
1600 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb
, CreationMode
);
1602 static int create_directory_or_subvolume(const char *path
, mode_t mode
, bool subvol
, CreationMode
*creation
) {
1603 _cleanup_close_
int pfd
= -1;
1612 pfd
= path_open_parent_safe(path
);
1617 if (btrfs_is_subvol(empty_to_root(arg_root
)) <= 0)
1619 /* Don't create a subvolume unless the root directory is
1620 * one, too. We do this under the assumption that if the
1621 * root directory is just a plain directory (i.e. very
1622 * light-weight), we shouldn't try to split it up into
1623 * subvolumes (i.e. more heavy-weight). Thus, chroot()
1624 * environments and suchlike will get a full brtfs
1625 * subvolume set up below their tree only if they
1626 * specifically set up a btrfs subvolume for the root
1631 RUN_WITH_UMASK((~mode
) & 0777)
1632 r
= btrfs_subvol_make_fd(pfd
, basename(path
));
1637 if (!subvol
|| r
== -ENOTTY
)
1638 RUN_WITH_UMASK(0000)
1639 r
= mkdirat_label(pfd
, basename(path
), mode
);
1644 if (!IN_SET(r
, -EEXIST
, -EROFS
))
1645 return log_error_errno(r
, "Failed to create directory or subvolume \"%s\": %m", path
);
1648 if (k
== -ENOENT
&& r
== -EROFS
)
1649 return log_error_errno(r
, "%s does not exist and cannot be created as the file system is read-only.", path
);
1651 return log_error_errno(k
, "Failed to check if %s exists: %m", path
);
1653 log_warning("\"%s\" already exists and is not a directory.", path
);
1657 *creation
= CREATION_EXISTING
;
1659 *creation
= CREATION_NORMAL
;
1661 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(*creation
), path
);
1663 r
= openat(pfd
, basename(path
), O_NOCTTY
|O_CLOEXEC
|O_DIRECTORY
);
1665 return log_error_errno(errno
, "Failed to open directory '%s': %m", basename(path
));
1670 static int create_directory(Item
*i
, const char *path
) {
1671 _cleanup_close_
int fd
= -1;
1674 assert(IN_SET(i
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
));
1676 fd
= create_directory_or_subvolume(path
, i
->mode
, false, NULL
);
1682 return fd_set_perms(i
, fd
, path
, NULL
);
1685 static int create_subvolume(Item
*i
, const char *path
) {
1686 _cleanup_close_
int fd
= -1;
1687 CreationMode creation
;
1691 assert(IN_SET(i
->type
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
));
1693 fd
= create_directory_or_subvolume(path
, i
->mode
, true, &creation
);
1699 if (creation
== CREATION_NORMAL
&&
1700 IN_SET(i
->type
, CREATE_SUBVOLUME_NEW_QUOTA
, CREATE_SUBVOLUME_INHERIT_QUOTA
)) {
1701 r
= btrfs_subvol_auto_qgroup_fd(fd
, 0, i
->type
== CREATE_SUBVOLUME_NEW_QUOTA
);
1703 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i
->path
);
1704 else if (r
== -EROFS
)
1705 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i
->path
);
1706 else if (r
== -ENOTCONN
)
1707 log_debug_errno(r
, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i
->path
);
1709 q
= log_error_errno(r
, "Failed to adjust quota for subvolume \"%s\": %m", i
->path
);
1711 log_debug("Adjusted quota for subvolume \"%s\".", i
->path
);
1713 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i
->path
);
1716 r
= fd_set_perms(i
, fd
, path
, NULL
);
1717 if (q
< 0) /* prefer the quota change error from above */
1723 static int empty_directory(Item
*i
, const char *path
) {
1727 assert(i
->type
== EMPTY_DIRECTORY
);
1729 r
= is_dir(path
, false);
1731 /* Option "e" operates only on existing objects. Do not
1732 * print errors about non-existent files or directories */
1733 log_debug("Skipping missing directory: %s", path
);
1737 return log_error_errno(r
, "is_dir() failed on path %s: %m", path
);
1739 return log_error_errno(SYNTHETIC_ERRNO(EEXIST
),
1740 "'%s' already exists and is not a directory.",
1743 return path_set_perms(i
, path
);
1746 static int create_device(Item
*i
, mode_t file_type
) {
1747 _cleanup_close_
int dfd
= -1, fd
= -1;
1748 CreationMode creation
;
1753 assert(IN_SET(file_type
, S_IFBLK
, S_IFCHR
));
1755 bn
= basename(i
->path
);
1757 /* Validate the path and use the returned directory fd for copying the
1758 * target so we're sure that the path can't be changed behind our
1760 dfd
= path_open_parent_safe(i
->path
);
1764 RUN_WITH_UMASK(0000) {
1765 mac_selinux_create_file_prepare(i
->path
, file_type
);
1766 r
= mknodat(dfd
, bn
, i
->mode
| file_type
, i
->major_minor
);
1767 mac_selinux_create_file_clear();
1773 if (errno
== EPERM
) {
1774 log_debug("We lack permissions, possibly because of cgroup configuration; "
1775 "skipping creation of device node %s.", i
->path
);
1779 if (errno
!= EEXIST
)
1780 return log_error_errno(errno
, "Failed to create device node %s: %m", i
->path
);
1782 if (fstatat(dfd
, bn
, &st
, 0) < 0)
1783 return log_error_errno(errno
, "stat(%s) failed: %m", i
->path
);
1785 if ((st
.st_mode
& S_IFMT
) != file_type
) {
1787 if (i
->append_or_force
) {
1789 RUN_WITH_UMASK(0000) {
1790 mac_selinux_create_file_prepare(i
->path
, file_type
);
1791 /* FIXME: need to introduce mknodat_atomic() */
1792 r
= mknod_atomic(i
->path
, i
->mode
| file_type
, i
->major_minor
);
1793 mac_selinux_create_file_clear();
1797 return log_error_errno(r
, "Failed to create device node \"%s\": %m", i
->path
);
1798 creation
= CREATION_FORCE
;
1800 log_debug("%s is not a device node.", i
->path
);
1804 creation
= CREATION_EXISTING
;
1806 creation
= CREATION_NORMAL
;
1808 log_debug("%s %s device node \"%s\" %u:%u.",
1809 creation_mode_verb_to_string(creation
),
1810 i
->type
== CREATE_BLOCK_DEVICE
? "block" : "char",
1811 i
->path
, major(i
->mode
), minor(i
->mode
));
1813 fd
= openat(dfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1815 return log_error_errno(errno
, "Failed to openat(%s): %m", i
->path
);
1817 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1820 static int create_fifo(Item
*i
, const char *path
) {
1821 _cleanup_close_
int pfd
= -1, fd
= -1;
1822 CreationMode creation
;
1827 pfd
= path_open_parent_safe(path
);
1831 bn
= basename(path
);
1833 RUN_WITH_UMASK(0000) {
1834 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1835 r
= mkfifoat(pfd
, bn
, i
->mode
);
1836 mac_selinux_create_file_clear();
1840 if (errno
!= EEXIST
)
1841 return log_error_errno(errno
, "Failed to create fifo %s: %m", path
);
1843 if (fstatat(pfd
, bn
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
1844 return log_error_errno(errno
, "stat(%s) failed: %m", path
);
1846 if (!S_ISFIFO(st
.st_mode
)) {
1848 if (i
->append_or_force
) {
1849 RUN_WITH_UMASK(0000) {
1850 mac_selinux_create_file_prepare(path
, S_IFIFO
);
1851 r
= mkfifoat_atomic(pfd
, bn
, i
->mode
);
1852 mac_selinux_create_file_clear();
1856 return log_error_errno(r
, "Failed to create fifo %s: %m", path
);
1857 creation
= CREATION_FORCE
;
1859 log_warning("\"%s\" already exists and is not a fifo.", path
);
1863 creation
= CREATION_EXISTING
;
1865 creation
= CREATION_NORMAL
;
1867 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation
), path
);
1869 fd
= openat(pfd
, bn
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1871 return log_error_errno(errno
, "Failed to openat(%s): %m", path
);
1873 return fd_set_perms(i
, fd
, i
->path
, NULL
);
1876 typedef int (*action_t
)(Item
*i
, const char *path
);
1877 typedef int (*fdaction_t
)(Item
*i
, int fd
, const char *path
, const struct stat
*st
);
1879 static int item_do(Item
*i
, int fd
, const char *path
, fdaction_t action
) {
1887 if (fstat(fd
, &st
) < 0) {
1888 r
= log_error_errno(errno
, "fstat() on file failed: %m");
1892 /* This returns the first error we run into, but nevertheless
1894 r
= action(i
, fd
, path
, &st
);
1896 if (S_ISDIR(st
.st_mode
)) {
1897 char procfs_path
[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1898 _cleanup_closedir_
DIR *d
= NULL
;
1901 /* The passed 'fd' was opened with O_PATH. We need to convert
1902 * it into a 'regular' fd before reading the directory content. */
1903 xsprintf(procfs_path
, "/proc/self/fd/%i", fd
);
1905 d
= opendir(procfs_path
);
1907 log_error_errno(errno
, "Failed to opendir() '%s': %m", procfs_path
);
1913 FOREACH_DIRENT_ALL(de
, d
, q
= -errno
; goto finish
) {
1916 if (dot_or_dot_dot(de
->d_name
))
1919 de_fd
= openat(fd
, de
->d_name
, O_NOFOLLOW
|O_CLOEXEC
|O_PATH
);
1921 q
= log_error_errno(errno
, "Failed to open() file '%s': %m", de
->d_name
);
1923 _cleanup_free_
char *de_path
= NULL
;
1925 de_path
= path_join(path
, de
->d_name
);
1929 /* Pass ownership of dirent fd over */
1930 q
= item_do(i
, de_fd
, de_path
, action
);
1933 if (q
< 0 && r
== 0)
1942 static int glob_item(Item
*i
, action_t action
) {
1943 _cleanup_globfree_ glob_t g
= {
1944 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1949 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1950 if (k
< 0 && k
!= -ENOENT
)
1951 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1953 STRV_FOREACH(fn
, g
.gl_pathv
) {
1955 if (k
< 0 && r
== 0)
1962 static int glob_item_recursively(Item
*i
, fdaction_t action
) {
1963 _cleanup_globfree_ glob_t g
= {
1964 .gl_opendir
= (void *(*)(const char *)) opendir_nomod
,
1969 k
= safe_glob(i
->path
, GLOB_NOSORT
|GLOB_BRACE
, &g
);
1970 if (k
< 0 && k
!= -ENOENT
)
1971 return log_error_errno(k
, "glob(%s) failed: %m", i
->path
);
1973 STRV_FOREACH(fn
, g
.gl_pathv
) {
1974 _cleanup_close_
int fd
= -1;
1976 /* Make sure we won't trigger/follow file object (such as
1977 * device nodes, automounts, ...) pointed out by 'fn' with
1978 * O_PATH. Note, when O_PATH is used, flags other than
1979 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1981 fd
= open(*fn
, O_CLOEXEC
|O_NOFOLLOW
|O_PATH
);
1983 log_error_errno(errno
, "Opening '%s' failed: %m", *fn
);
1989 k
= item_do(i
, fd
, *fn
, action
);
1990 if (k
< 0 && r
== 0)
1993 /* we passed fd ownership to the previous call */
2000 static int create_item(Item
*i
) {
2001 CreationMode creation
;
2006 log_debug("Running create action for entry %c %s", (char) i
->type
, i
->path
);
2011 case IGNORE_DIRECTORY_PATH
:
2013 case RECURSIVE_REMOVE_PATH
:
2018 RUN_WITH_UMASK(0000)
2019 (void) mkdir_parents_label(i
->path
, 0755);
2021 if ((i
->type
== CREATE_FILE
&& i
->append_or_force
) || i
->type
== TRUNCATE_FILE
)
2022 r
= truncate_file(i
, i
->path
);
2024 r
= create_file(i
, i
->path
);
2031 RUN_WITH_UMASK(0000)
2032 (void) mkdir_parents_label(i
->path
, 0755);
2040 r
= glob_item(i
, write_one_file
);
2046 case CREATE_DIRECTORY
:
2047 case TRUNCATE_DIRECTORY
:
2048 RUN_WITH_UMASK(0000)
2049 (void) mkdir_parents_label(i
->path
, 0755);
2051 r
= create_directory(i
, i
->path
);
2056 case CREATE_SUBVOLUME
:
2057 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2058 case CREATE_SUBVOLUME_NEW_QUOTA
:
2059 RUN_WITH_UMASK(0000)
2060 (void) mkdir_parents_label(i
->path
, 0755);
2062 r
= create_subvolume(i
, i
->path
);
2067 case EMPTY_DIRECTORY
:
2068 r
= glob_item(i
, empty_directory
);
2074 RUN_WITH_UMASK(0000)
2075 (void) mkdir_parents_label(i
->path
, 0755);
2077 r
= create_fifo(i
, i
->path
);
2082 case CREATE_SYMLINK
: {
2083 RUN_WITH_UMASK(0000)
2084 (void) mkdir_parents_label(i
->path
, 0755);
2086 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2087 r
= symlink(i
->argument
, i
->path
);
2088 mac_selinux_create_file_clear();
2091 _cleanup_free_
char *x
= NULL
;
2093 if (errno
!= EEXIST
)
2094 return log_error_errno(errno
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2096 r
= readlink_malloc(i
->path
, &x
);
2097 if (r
< 0 || !streq(i
->argument
, x
)) {
2099 if (i
->append_or_force
) {
2100 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2101 r
= symlink_atomic(i
->argument
, i
->path
);
2102 mac_selinux_create_file_clear();
2104 if (IN_SET(r
, -EISDIR
, -EEXIST
, -ENOTEMPTY
)) {
2105 r
= rm_rf(i
->path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
2107 return log_error_errno(r
, "rm -fr %s failed: %m", i
->path
);
2109 mac_selinux_create_file_prepare(i
->path
, S_IFLNK
);
2110 r
= symlink(i
->argument
, i
->path
) < 0 ? -errno
: 0;
2111 mac_selinux_create_file_clear();
2114 return log_error_errno(r
, "symlink(%s, %s) failed: %m", i
->argument
, i
->path
);
2116 creation
= CREATION_FORCE
;
2118 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i
->path
);
2122 creation
= CREATION_EXISTING
;
2125 creation
= CREATION_NORMAL
;
2126 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation
), i
->path
);
2130 case CREATE_BLOCK_DEVICE
:
2131 case CREATE_CHAR_DEVICE
:
2132 if (have_effective_cap(CAP_MKNOD
) == 0) {
2133 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2134 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2136 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i
->path
);
2140 RUN_WITH_UMASK(0000)
2141 (void) mkdir_parents_label(i
->path
, 0755);
2143 r
= create_device(i
, i
->type
== CREATE_BLOCK_DEVICE
? S_IFBLK
: S_IFCHR
);
2151 r
= glob_item(i
, path_set_perms
);
2156 case RECURSIVE_RELABEL_PATH
:
2157 r
= glob_item_recursively(i
, fd_set_perms
);
2163 r
= glob_item(i
, path_set_xattrs
);
2168 case RECURSIVE_SET_XATTR
:
2169 r
= glob_item_recursively(i
, fd_set_xattrs
);
2175 r
= glob_item(i
, path_set_acls
);
2180 case RECURSIVE_SET_ACL
:
2181 r
= glob_item_recursively(i
, fd_set_acls
);
2187 r
= glob_item(i
, path_set_attribute
);
2192 case RECURSIVE_SET_ATTRIBUTE
:
2193 r
= glob_item_recursively(i
, fd_set_attribute
);
2202 static int remove_item_instance(Item
*i
, const char *instance
) {
2210 if (remove(instance
) < 0 && errno
!= ENOENT
)
2211 return log_error_errno(errno
, "rm(%s): %m", instance
);
2215 case RECURSIVE_REMOVE_PATH
:
2216 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2217 log_debug("rm -rf \"%s\"", instance
);
2218 r
= rm_rf(instance
, REMOVE_ROOT
|REMOVE_SUBVOLUME
|REMOVE_PHYSICAL
);
2219 if (r
< 0 && r
!= -ENOENT
)
2220 return log_error_errno(r
, "rm_rf(%s): %m", instance
);
2225 assert_not_reached("wut?");
2231 static int remove_item(Item
*i
) {
2236 log_debug("Running remove action for entry %c %s", (char) i
->type
, i
->path
);
2240 case TRUNCATE_DIRECTORY
:
2241 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2242 log_debug("rm -rf \"%s\"", i
->path
);
2243 r
= rm_rf(i
->path
, REMOVE_PHYSICAL
);
2244 if (r
< 0 && r
!= -ENOENT
)
2245 return log_error_errno(r
, "rm_rf(%s): %m", i
->path
);
2250 case RECURSIVE_REMOVE_PATH
:
2251 return glob_item(i
, remove_item_instance
);
2258 static int clean_item_instance(Item
*i
, const char* instance
) {
2259 char timestamp
[FORMAT_TIMESTAMP_MAX
];
2260 _cleanup_closedir_
DIR *d
= NULL
;
2261 STRUCT_STATX_DEFINE(sx
);
2270 n
= now(CLOCK_REALTIME
);
2274 cutoff
= n
- i
->age
;
2276 d
= opendir_nomod(instance
);
2278 if (IN_SET(errno
, ENOENT
, ENOTDIR
)) {
2279 log_debug_errno(errno
, "Directory \"%s\": %m", instance
);
2283 return log_error_errno(errno
, "Failed to open directory %s: %m", instance
);
2286 r
= statx_fallback(dirfd(d
), "", AT_EMPTY_PATH
, STATX_MODE
|STATX_INO
|STATX_ATIME
|STATX_MTIME
, &sx
);
2288 return log_error_errno(r
, "statx(%s) failed: %m", instance
);
2290 if (FLAGS_SET(sx
.stx_attributes_mask
, STATX_ATTR_MOUNT_ROOT
))
2291 mountpoint
= FLAGS_SET(sx
.stx_attributes
, STATX_ATTR_MOUNT_ROOT
);
2295 if (fstatat(dirfd(d
), "..", &ps
, AT_SYMLINK_NOFOLLOW
) != 0)
2296 return log_error_errno(errno
, "stat(%s/..) failed: %m", i
->path
);
2299 sx
.stx_dev_major
!= major(ps
.st_dev
) ||
2300 sx
.stx_dev_minor
!= minor(ps
.st_dev
) ||
2301 sx
.stx_ino
!= ps
.st_ino
;
2304 log_debug("Cleanup threshold for %s \"%s\" is %s",
2305 mountpoint
? "mount point" : "directory",
2307 format_timestamp_style(timestamp
, sizeof(timestamp
), cutoff
, TIMESTAMP_US
));
2309 return dir_cleanup(i
, instance
, d
,
2310 load_statx_timestamp_nsec(&sx
.stx_atime
),
2311 load_statx_timestamp_nsec(&sx
.stx_mtime
),
2312 cutoff
* NSEC_PER_USEC
,
2313 sx
.stx_dev_major
, sx
.stx_dev_minor
, mountpoint
,
2314 MAX_DEPTH
, i
->keep_first_level
);
2317 static int clean_item(Item
*i
) {
2320 log_debug("Running clean action for entry %c %s", (char) i
->type
, i
->path
);
2323 case CREATE_DIRECTORY
:
2324 case CREATE_SUBVOLUME
:
2325 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2326 case CREATE_SUBVOLUME_NEW_QUOTA
:
2327 case TRUNCATE_DIRECTORY
:
2330 clean_item_instance(i
, i
->path
);
2332 case EMPTY_DIRECTORY
:
2333 case IGNORE_DIRECTORY_PATH
:
2334 return glob_item(i
, clean_item_instance
);
2340 static int process_item(Item
*i
, OperationMask operation
) {
2346 todo
= operation
& ~i
->done
;
2347 if (todo
== 0) /* Everything already done? */
2350 i
->done
|= operation
;
2352 r
= chase_symlinks(i
->path
, arg_root
, CHASE_NO_AUTOFS
|CHASE_WARN
, NULL
, NULL
);
2353 if (r
== -EREMOTE
) {
2354 log_notice_errno(r
, "Skipping %s", i
->path
);
2358 log_debug_errno(r
, "Failed to determine whether '%s' is below autofs, ignoring: %m", i
->path
);
2360 r
= FLAGS_SET(operation
, OPERATION_CREATE
) ? create_item(i
) : 0;
2361 /* Failure can only be tolerated for create */
2362 if (i
->allow_failure
)
2365 q
= FLAGS_SET(operation
, OPERATION_REMOVE
) ? remove_item(i
) : 0;
2366 p
= FLAGS_SET(operation
, OPERATION_CLEAN
) ? clean_item(i
) : 0;
2373 static int process_item_array(ItemArray
*array
, OperationMask operation
) {
2379 /* Create any parent first. */
2380 if (FLAGS_SET(operation
, OPERATION_CREATE
) && array
->parent
)
2381 r
= process_item_array(array
->parent
, operation
& OPERATION_CREATE
);
2383 /* Clean up all children first */
2384 if ((operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
)) && !set_isempty(array
->children
)) {
2387 SET_FOREACH(c
, array
->children
) {
2390 k
= process_item_array(c
, operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
));
2391 if (k
< 0 && r
== 0)
2396 for (n
= 0; n
< array
->n_items
; n
++) {
2399 k
= process_item(array
->items
+ n
, operation
);
2400 if (k
< 0 && r
== 0)
2407 static void item_free_contents(Item
*i
) {
2411 strv_free(i
->xattrs
);
2414 acl_free(i
->acl_access
);
2415 acl_free(i
->acl_default
);
2419 static ItemArray
* item_array_free(ItemArray
*a
) {
2425 for (n
= 0; n
< a
->n_items
; n
++)
2426 item_free_contents(a
->items
+ n
);
2428 set_free(a
->children
);
2433 static int item_compare(const Item
*a
, const Item
*b
) {
2434 /* Make sure that the ownership taking item is put first, so
2435 * that we first create the node, and then can adjust it */
2437 if (takes_ownership(a
->type
) && !takes_ownership(b
->type
))
2439 if (!takes_ownership(a
->type
) && takes_ownership(b
->type
))
2442 return CMP(a
->type
, b
->type
);
2445 static bool item_compatible(Item
*a
, Item
*b
) {
2448 assert(streq(a
->path
, b
->path
));
2450 if (takes_ownership(a
->type
) && takes_ownership(b
->type
))
2451 /* check if the items are the same */
2452 return streq_ptr(a
->argument
, b
->argument
) &&
2454 a
->uid_set
== b
->uid_set
&&
2457 a
->gid_set
== b
->gid_set
&&
2460 a
->mode_set
== b
->mode_set
&&
2461 a
->mode
== b
->mode
&&
2463 a
->age_set
== b
->age_set
&&
2466 a
->mask_perms
== b
->mask_perms
&&
2468 a
->keep_first_level
== b
->keep_first_level
&&
2470 a
->major_minor
== b
->major_minor
;
2475 static bool should_include_path(const char *path
) {
2478 STRV_FOREACH(prefix
, arg_exclude_prefixes
)
2479 if (path_startswith(path
, *prefix
)) {
2480 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2485 STRV_FOREACH(prefix
, arg_include_prefixes
)
2486 if (path_startswith(path
, *prefix
)) {
2487 log_debug("Entry \"%s\" matches include prefix \"%s\".", path
, *prefix
);
2491 /* no matches, so we should include this path only if we have no allow list at all */
2492 if (strv_isempty(arg_include_prefixes
))
2495 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path
);
2499 static int specifier_expansion_from_arg(Item
*i
) {
2500 _cleanup_free_
char *unescaped
= NULL
, *resolved
= NULL
;
2511 case CREATE_SYMLINK
:
2515 r
= cunescape(i
->argument
, 0, &unescaped
);
2517 return log_error_errno(r
, "Failed to unescape parameter to write: %s", i
->argument
);
2519 r
= specifier_printf(unescaped
, specifier_table
, NULL
, &resolved
);
2523 free_and_replace(i
->argument
, resolved
);
2527 case RECURSIVE_SET_XATTR
:
2528 STRV_FOREACH(xattr
, i
->xattrs
) {
2529 r
= specifier_printf(*xattr
, specifier_table
, NULL
, &resolved
);
2533 free_and_replace(*xattr
, resolved
);
2543 static int patch_var_run(const char *fname
, unsigned line
, char **path
) {
2550 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2551 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2552 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2553 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2554 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2555 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2556 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2557 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2558 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2560 k
= path_startswith(*path
, "/var/run/");
2561 if (isempty(k
)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2564 n
= path_join("/run", k
);
2568 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2569 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2570 * to the user, let's still inform the user that these snippets should really be updated. */
2571 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
);
2573 free_and_replace(*path
, n
);
2578 static int find_uid(const char *user
, uid_t
*ret_uid
, Hashmap
**cache
) {
2584 /* First: parse as numeric UID string */
2585 r
= parse_uid(user
, ret_uid
);
2589 /* Second: pass to NSS if we are running "online" */
2591 return get_user_creds(&user
, ret_uid
, NULL
, NULL
, NULL
, 0);
2593 /* Third, synthesize "root" unconditionally */
2594 if (streq(user
, "root")) {
2599 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
2600 return name_to_uid_offline(arg_root
, user
, ret_uid
, cache
);
2603 static int find_gid(const char *group
, gid_t
*ret_gid
, Hashmap
**cache
) {
2609 /* First: parse as numeric GID string */
2610 r
= parse_gid(group
, ret_gid
);
2614 /* Second: pass to NSS if we are running "online" */
2616 return get_group_creds(&group
, ret_gid
, 0);
2618 /* Third, synthesize "root" unconditionally */
2619 if (streq(group
, "root")) {
2624 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
2625 return name_to_gid_offline(arg_root
, group
, ret_gid
, cache
);
2628 static int parse_line(
2632 bool *invalid_config
,
2633 Hashmap
**uid_cache
,
2634 Hashmap
**gid_cache
) {
2636 _cleanup_free_
char *action
= NULL
, *mode
= NULL
, *user
= NULL
, *group
= NULL
, *age
= NULL
, *path
= NULL
;
2637 _cleanup_(item_free_contents
) Item i
= {};
2638 ItemArray
*existing
;
2641 bool append_or_force
= false, boot
= false, allow_failure
= false;
2647 r
= extract_many_words(
2659 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2660 /* invalid quoting and such or an unknown specifier */
2661 *invalid_config
= true;
2662 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to parse line: %m");
2664 *invalid_config
= true;
2665 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Syntax error.");
2668 if (!empty_or_dash(buffer
)) {
2669 i
.argument
= strdup(buffer
);
2674 if (isempty(action
)) {
2675 *invalid_config
= true;
2676 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Command too short '%s'.", action
);
2679 for (pos
= 1; action
[pos
]; pos
++) {
2680 if (action
[pos
] == '!' && !boot
)
2682 else if (action
[pos
] == '+' && !append_or_force
)
2683 append_or_force
= true;
2684 else if (action
[pos
] == '-' && !allow_failure
)
2685 allow_failure
= true;
2687 *invalid_config
= true;
2688 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Unknown modifiers in command '%s'", action
);
2692 if (boot
&& !arg_boot
) {
2693 log_syntax(NULL
, LOG_DEBUG
, fname
, line
, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action
, path
);
2698 i
.append_or_force
= append_or_force
;
2699 i
.allow_failure
= allow_failure
;
2701 r
= specifier_printf(path
, specifier_table
, NULL
, &i
.path
);
2703 return log_unresolvable_specifier(fname
, line
);
2705 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2706 *invalid_config
= true;
2707 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to replace specifiers in '%s': %m", path
);
2710 r
= patch_var_run(fname
, line
, &i
.path
);
2716 case CREATE_DIRECTORY
:
2717 case CREATE_SUBVOLUME
:
2718 case CREATE_SUBVOLUME_INHERIT_QUOTA
:
2719 case CREATE_SUBVOLUME_NEW_QUOTA
:
2720 case EMPTY_DIRECTORY
:
2721 case TRUNCATE_DIRECTORY
:
2724 case IGNORE_DIRECTORY_PATH
:
2726 case RECURSIVE_REMOVE_PATH
:
2729 case RECURSIVE_RELABEL_PATH
:
2731 log_syntax(NULL
, LOG_WARNING
, fname
, line
, 0, "%c lines don't take argument fields, ignoring.", i
.type
);
2739 case CREATE_SYMLINK
:
2741 i
.argument
= path_join("/usr/share/factory", i
.path
);
2749 *invalid_config
= true;
2750 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Write file requires argument.");
2756 i
.argument
= path_join("/usr/share/factory", i
.path
);
2760 } else if (!path_is_absolute(i
.argument
)) {
2761 *invalid_config
= true;
2762 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Source path '%s' is not absolute.", i
.argument
);
2766 if (!empty_or_root(arg_root
)) {
2769 p
= path_join(arg_root
, i
.argument
);
2772 free_and_replace(i
.argument
, p
);
2775 path_simplify(i
.argument
, false);
2778 case CREATE_CHAR_DEVICE
:
2779 case CREATE_BLOCK_DEVICE
:
2781 *invalid_config
= true;
2782 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
), "Device file requires argument.");
2785 r
= parse_dev(i
.argument
, &i
.major_minor
);
2787 *invalid_config
= true;
2788 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Can't parse device file major/minor '%s'.", i
.argument
);
2794 case RECURSIVE_SET_XATTR
:
2796 *invalid_config
= true;
2797 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2798 "Set extended attribute requires argument.");
2800 r
= parse_xattrs_from_arg(&i
);
2806 case RECURSIVE_SET_ACL
:
2808 *invalid_config
= true;
2809 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2810 "Set ACLs requires argument.");
2812 r
= parse_acls_from_arg(&i
);
2818 case RECURSIVE_SET_ATTRIBUTE
:
2820 *invalid_config
= true;
2821 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2822 "Set file attribute requires argument.");
2824 r
= parse_attribute_from_arg(&i
);
2825 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2826 *invalid_config
= true;
2832 *invalid_config
= true;
2833 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2834 "Unknown command type '%c'.", (char) i
.type
);
2837 if (!path_is_absolute(i
.path
)) {
2838 *invalid_config
= true;
2839 return log_syntax(NULL
, LOG_ERR
, fname
, line
, SYNTHETIC_ERRNO(EBADMSG
),
2840 "Path '%s' not absolute.", i
.path
);
2843 path_simplify(i
.path
, false);
2845 if (!should_include_path(i
.path
))
2848 r
= specifier_expansion_from_arg(&i
);
2850 return log_unresolvable_specifier(fname
, line
);
2852 if (IN_SET(r
, -EINVAL
, -EBADSLT
))
2853 *invalid_config
= true;
2854 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to substitute specifiers in argument: %m");
2857 if (!empty_or_root(arg_root
)) {
2860 p
= path_join(arg_root
, i
.path
);
2863 free_and_replace(i
.path
, p
);
2866 if (!empty_or_dash(user
)) {
2867 r
= find_uid(user
, &i
.uid
, uid_cache
);
2869 *invalid_config
= true;
2870 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve user '%s': %m", user
);
2876 if (!empty_or_dash(group
)) {
2877 r
= find_gid(group
, &i
.gid
, gid_cache
);
2879 *invalid_config
= true;
2880 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Failed to resolve group '%s'.", group
);
2886 if (!empty_or_dash(mode
)) {
2887 const char *mm
= mode
;
2891 i
.mask_perms
= true;
2895 r
= parse_mode(mm
, &m
);
2897 *invalid_config
= true;
2898 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid mode '%s'.", mode
);
2904 i
.mode
= IN_SET(i
.type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
) ? 0755 : 0644;
2906 if (!empty_or_dash(age
)) {
2907 const char *a
= age
;
2910 i
.keep_first_level
= true;
2914 r
= parse_sec(a
, &i
.age
);
2916 *invalid_config
= true;
2917 return log_syntax(NULL
, LOG_ERR
, fname
, line
, r
, "Invalid age '%s'.", age
);
2923 h
= needs_glob(i
.type
) ? globs
: items
;
2925 existing
= ordered_hashmap_get(h
, i
.path
);
2929 for (n
= 0; n
< existing
->n_items
; n
++) {
2930 if (!item_compatible(existing
->items
+ n
, &i
) && !i
.append_or_force
) {
2931 log_syntax(NULL
, LOG_NOTICE
, fname
, line
, 0, "Duplicate line for path \"%s\", ignoring.", i
.path
);
2936 existing
= new0(ItemArray
, 1);
2940 r
= ordered_hashmap_put(h
, i
.path
, existing
);
2947 if (!GREEDY_REALLOC(existing
->items
, existing
->allocated
, existing
->n_items
+ 1))
2950 existing
->items
[existing
->n_items
++] = i
;
2951 i
= (struct Item
) {};
2953 /* Sort item array, to enforce stable ordering of application */
2954 typesafe_qsort(existing
->items
, existing
->n_items
, item_compare
);
2959 static int cat_config(char **config_dirs
, char **args
) {
2960 _cleanup_strv_free_
char **files
= NULL
;
2963 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, NULL
);
2967 return cat_files(NULL
, files
, 0);
2970 static int exclude_default_prefixes(void) {
2973 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
2974 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
2975 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
2976 * all kinds of files created/adjusted underneath these mount points. */
2978 r
= strv_extend_strv(
2979 &arg_exclude_prefixes
,
2991 static int help(void) {
2992 _cleanup_free_
char *link
= NULL
;
2995 r
= terminal_urlify_man("systemd-tmpfiles", "8", &link
);
2999 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3000 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3001 " -h --help Show this help\n"
3002 " --user Execute user configuration\n"
3003 " --version Show package version\n"
3004 " --cat-config Show configuration files\n"
3005 " --create Create marked files/directories\n"
3006 " --clean Clean up marked directories\n"
3007 " --remove Remove marked files/directories\n"
3008 " --boot Execute actions only safe at boot\n"
3009 " --prefix=PATH Only apply rules with the specified prefix\n"
3010 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3011 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3012 " --root=PATH Operate on an alternate filesystem root\n"
3013 " --image=PATH Operate on disk image as filesystem root\n"
3014 " --replace=PATH Treat arguments as replacement for PATH\n"
3015 " --no-pager Do not pipe output into a pager\n"
3016 "\nSee the %s for details.\n",
3017 program_invocation_short_name
,
3025 static int parse_argv(int argc
, char *argv
[]) {
3028 ARG_VERSION
= 0x100,
3043 static const struct option options
[] = {
3044 { "help", no_argument
, NULL
, 'h' },
3045 { "user", no_argument
, NULL
, ARG_USER
},
3046 { "version", no_argument
, NULL
, ARG_VERSION
},
3047 { "cat-config", no_argument
, NULL
, ARG_CAT_CONFIG
},
3048 { "create", no_argument
, NULL
, ARG_CREATE
},
3049 { "clean", no_argument
, NULL
, ARG_CLEAN
},
3050 { "remove", no_argument
, NULL
, ARG_REMOVE
},
3051 { "boot", no_argument
, NULL
, ARG_BOOT
},
3052 { "prefix", required_argument
, NULL
, ARG_PREFIX
},
3053 { "exclude-prefix", required_argument
, NULL
, ARG_EXCLUDE_PREFIX
},
3054 { "root", required_argument
, NULL
, ARG_ROOT
},
3055 { "image", required_argument
, NULL
, ARG_IMAGE
},
3056 { "replace", required_argument
, NULL
, ARG_REPLACE
},
3057 { "no-pager", no_argument
, NULL
, ARG_NO_PAGER
},
3066 while ((c
= getopt_long(argc
, argv
, "hE", options
, NULL
)) >= 0)
3076 case ARG_CAT_CONFIG
:
3077 arg_cat_config
= true;
3085 arg_operation
|= OPERATION_CREATE
;
3089 arg_operation
|= OPERATION_CLEAN
;
3093 arg_operation
|= OPERATION_REMOVE
;
3101 if (strv_push(&arg_include_prefixes
, optarg
) < 0)
3105 case ARG_EXCLUDE_PREFIX
:
3106 if (strv_push(&arg_exclude_prefixes
, optarg
) < 0)
3111 r
= parse_path_argument_and_warn(optarg
, /* suppress_root= */ false, &arg_root
);
3118 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
3119 "This systemd-tmpfiles version is compiled without support for --image=.");
3121 r
= parse_path_argument_and_warn(optarg
, /* suppress_root= */ false, &arg_image
);
3125 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
3129 r
= exclude_default_prefixes();
3136 if (!path_is_absolute(optarg
) ||
3137 !endswith(optarg
, ".conf"))
3138 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3139 "The argument to --replace= must an absolute path to a config file");
3141 arg_replace
= optarg
;
3145 arg_pager_flags
|= PAGER_DISABLE
;
3152 assert_not_reached("Unhandled option");
3155 if (arg_operation
== 0 && !arg_cat_config
)
3156 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3157 "You need to specify at least one of --clean, --create or --remove.");
3159 if (arg_replace
&& arg_cat_config
)
3160 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3161 "Option --replace= is not supported with --cat-config");
3163 if (arg_replace
&& optind
>= argc
)
3164 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3165 "When --replace= is given, some configuration items must be specified");
3167 if (arg_root
&& arg_user
)
3168 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
3169 "Combination of --user and --root= is not supported.");
3171 if (arg_image
&& arg_root
)
3172 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Please specify either --root= or --image=, the combination of both is not supported.");
3177 static int read_config_file(char **config_dirs
, const char *fn
, bool ignore_enoent
, bool *invalid_config
) {
3178 _cleanup_(hashmap_freep
) Hashmap
*uid_cache
= NULL
, *gid_cache
= NULL
;
3179 _cleanup_fclose_
FILE *_f
= NULL
;
3187 if (streq(fn
, "-")) {
3188 log_debug("Reading config from stdin…");
3192 r
= search_and_fopen(fn
, "re", arg_root
, (const char**) config_dirs
, &_f
);
3194 if (ignore_enoent
&& r
== -ENOENT
) {
3195 log_debug_errno(r
, "Failed to open \"%s\", ignoring: %m", fn
);
3199 return log_error_errno(r
, "Failed to open '%s': %m", fn
);
3201 log_debug("Reading config file \"%s\"…", fn
);
3206 _cleanup_free_
char *line
= NULL
;
3207 bool invalid_line
= false;
3211 k
= read_line(f
, LONG_LINE_MAX
, &line
);
3213 return log_error_errno(k
, "Failed to read '%s': %m", fn
);
3220 if (IN_SET(*l
, 0, '#'))
3223 k
= parse_line(fn
, v
, l
, &invalid_line
, &uid_cache
, &gid_cache
);
3226 /* Allow reporting with a special code if the caller requested this */
3227 *invalid_config
= true;
3229 /* The first error becomes our return value */
3234 /* we have to determine age parameter for each entry of type X */
3235 ORDERED_HASHMAP_FOREACH(i
, globs
) {
3236 Item
*j
, *candidate_item
= NULL
;
3238 if (i
->type
!= IGNORE_DIRECTORY_PATH
)
3241 ORDERED_HASHMAP_FOREACH(j
, items
) {
3242 if (!IN_SET(j
->type
, CREATE_DIRECTORY
, TRUNCATE_DIRECTORY
, CREATE_SUBVOLUME
, CREATE_SUBVOLUME_INHERIT_QUOTA
, CREATE_SUBVOLUME_NEW_QUOTA
))
3245 if (path_equal(j
->path
, i
->path
)) {
3250 if ((!candidate_item
&& path_startswith(i
->path
, j
->path
)) ||
3251 (candidate_item
&& path_startswith(j
->path
, candidate_item
->path
) && (fnmatch(i
->path
, j
->path
, FNM_PATHNAME
| FNM_PERIOD
) == 0)))
3255 if (candidate_item
&& candidate_item
->age_set
) {
3256 i
->age
= candidate_item
->age
;
3262 log_error_errno(errno
, "Failed to read from file %s: %m", fn
);
3270 static int parse_arguments(char **config_dirs
, char **args
, bool *invalid_config
) {
3274 STRV_FOREACH(arg
, args
) {
3275 r
= read_config_file(config_dirs
, *arg
, false, invalid_config
);
3283 static int read_config_files(char **config_dirs
, char **args
, bool *invalid_config
) {
3284 _cleanup_strv_free_
char **files
= NULL
;
3285 _cleanup_free_
char *p
= NULL
;
3289 r
= conf_files_list_with_replacement(arg_root
, config_dirs
, arg_replace
, &files
, &p
);
3293 STRV_FOREACH(f
, files
)
3294 if (p
&& path_equal(*f
, p
)) {
3295 log_debug("Parsing arguments at position \"%s\"…", *f
);
3297 r
= parse_arguments(config_dirs
, args
, invalid_config
);
3301 /* Just warn, ignore result otherwise.
3302 * read_config_file() has some debug output, so no need to print anything. */
3303 (void) read_config_file(config_dirs
, *f
, true, invalid_config
);
3308 static int link_parent(ItemArray
*a
) {
3315 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
3316 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3317 * before their children, and clean up/remove children before their parents. */
3319 if (a
->n_items
<= 0)
3322 path
= a
->items
[0].path
;
3323 prefix
= newa(char, strlen(path
) + 1);
3324 PATH_FOREACH_PREFIX(prefix
, path
) {
3327 j
= ordered_hashmap_get(items
, prefix
);
3329 j
= ordered_hashmap_get(globs
, prefix
);
3331 r
= set_ensure_put(&j
->children
, NULL
, a
);
3343 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops
, char, string_hash_func
, string_compare_func
,
3344 ItemArray
, item_array_free
);
3346 static int run(int argc
, char *argv
[]) {
3348 _cleanup_(loop_device_unrefp
) LoopDevice
*loop_device
= NULL
;
3349 _cleanup_(decrypted_image_unrefp
) DecryptedImage
*decrypted_image
= NULL
;
3350 _cleanup_(umount_and_rmdir_and_freep
) char *unlink_dir
= NULL
;
3352 _cleanup_strv_free_
char **config_dirs
= NULL
;
3353 bool invalid_config
= false;
3356 PHASE_REMOVE_AND_CLEAN
,
3362 r
= parse_argv(argc
, argv
);
3368 /* Descending down file system trees might take a lot of fds */
3369 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE
);
3372 r
= user_config_paths(&config_dirs
);
3374 return log_error_errno(r
, "Failed to initialize configuration directory list: %m");
3376 config_dirs
= strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
3381 if (DEBUG_LOGGING
) {
3382 _cleanup_free_
char *t
= NULL
;
3385 STRV_FOREACH(i
, config_dirs
) {
3386 _cleanup_free_
char *j
= NULL
;
3388 j
= path_join(arg_root
, *i
);
3392 if (!strextend(&t
, "\n\t", j
))
3396 log_debug("Looking for configuration files in (higher priority first):%s", t
);
3399 if (arg_cat_config
) {
3400 (void) pager_open(arg_pager_flags
);
3402 return cat_config(config_dirs
, argv
+ optind
);
3407 r
= mac_selinux_init();
3415 r
= mount_image_privately_interactively(
3417 DISSECT_IMAGE_REQUIRE_ROOT
|DISSECT_IMAGE_VALIDATE_OS
|DISSECT_IMAGE_RELAX_VAR_CHECK
|DISSECT_IMAGE_FSCK
,
3424 arg_root
= strdup(unlink_dir
);
3432 items
= ordered_hashmap_new(&item_array_hash_ops
);
3433 globs
= ordered_hashmap_new(&item_array_hash_ops
);
3434 if (!items
|| !globs
)
3437 /* If command line arguments are specified along with --replace, read all
3438 * configuration files and insert the positional arguments at the specified
3439 * place. Otherwise, if command line arguments are specified, execute just
3440 * them, and finally, without --replace= or any positional arguments, just
3441 * read configuration and execute it.
3443 if (arg_replace
|| optind
>= argc
)
3444 r
= read_config_files(config_dirs
, argv
+ optind
, &invalid_config
);
3446 r
= parse_arguments(config_dirs
, argv
+ optind
, &invalid_config
);
3450 /* Let's now link up all child/parent relationships */
3451 ORDERED_HASHMAP_FOREACH(a
, items
) {
3456 ORDERED_HASHMAP_FOREACH(a
, globs
) {
3462 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
3463 * operations. i.e. that we first clean out the platform we then build on. */
3464 for (phase
= 0; phase
< _PHASE_MAX
; phase
++) {
3467 if (phase
== PHASE_REMOVE_AND_CLEAN
)
3468 op
= arg_operation
& (OPERATION_REMOVE
|OPERATION_CLEAN
);
3469 else if (phase
== PHASE_CREATE
)
3470 op
= arg_operation
& OPERATION_CREATE
;
3472 assert_not_reached("unexpected phase");
3474 if (op
== 0) /* Nothing requested in this phase */
3477 /* The non-globbing ones usually create things, hence we apply them first */
3478 ORDERED_HASHMAP_FOREACH(a
, items
) {
3479 k
= process_item_array(a
, op
);
3480 if (k
< 0 && r
>= 0)
3484 /* The globbing ones usually alter things, hence we apply them second. */
3485 ORDERED_HASHMAP_FOREACH(a
, globs
) {
3486 k
= process_item_array(a
, op
);
3487 if (k
< 0 && r
>= 0)
3492 if (ERRNO_IS_RESOURCE(r
))
3497 return EX_CANTCREAT
;
3501 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);