HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/tmpfiles/tmpfiles.c
Git blob: c4caa0b857918b2141bedc1762e40c4e54e030a4
Lines 1–1000 of 5,453
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <fnmatch.h>
#include <sys/file.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>
#include "sd-json.h"
#include "sd-path.h"
#include "acl-util.h"
#include "alloc-util.h"
#include "bitfield.h"
#include "btrfs-util.h"
#include "build.h"
#include "capability-list.h"
#include "capability-util.h"
#include "chase.h"
#include "chattr-util.h"
#include "conf-files.h"
#include "constants.h"
#include "copy.h"
#include "creds-util.h"
#include "devnum-util.h"
#include "dirent-util.h"
#include "dissect-image.h"
#include "dlopen-note.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "fs-util.h"
#include "glob-util.h"
#include "hexdecoct.h"
#include "image-policy.h"
#include "io-util.h"
#include "label-util.h"
#include "log.h"
#include "loop-util.h"
#include "main-func.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "offline-passwd.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-lookup.h"
#include "path-util.h"
#include "pretty-print.h"
#include "rlimit-util.h"
#include "rm-rf.h"
#include "selinux-util.h"
#include "set.h"
#include "sort-util.h"
#include "specifier.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "sysctl-util.h"
#include "time-util.h"
#include "umask-util.h"
#include "user-util.h"
#include "verbs.h"
#include "virt.h"
#include "xattr-util.h"
/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
* them in the file system. This is intended to be used to create
* properly owned directories beneath /tmp, /var/tmp, /run, which are
* volatile and hence need to be recreated on bootup. */
typedef enum OperationMask {
OPERATION_CREATE = 1 << 0,
OPERATION_REMOVE = 1 << 1,
OPERATION_CLEAN = 1 << 2,
OPERATION_PURGE = 1 << 3,
} OperationMask;
typedef enum ItemType {
/* These ones take file names */
CREATE_FILE = 'f',
TRUNCATE_FILE = 'F', /* deprecated: use f+ */
CREATE_DIRECTORY = 'd',
TRUNCATE_DIRECTORY = 'D',
CREATE_SUBVOLUME = 'v',
CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
CREATE_SUBVOLUME_NEW_QUOTA = 'Q',
CREATE_FIFO = 'p',
CREATE_SYMLINK = 'L',
CREATE_CHAR_DEVICE = 'c',
CREATE_BLOCK_DEVICE = 'b',
COPY_FILES = 'C',
/* These ones take globs */
WRITE_FILE = 'w',
EMPTY_DIRECTORY = 'e',
SET_XATTR = 't',
RECURSIVE_SET_XATTR = 'T',
SET_ACL = 'a',
RECURSIVE_SET_ACL = 'A',
SET_FCAPS = 'k',
RECURSIVE_SET_FCAPS = 'K',
SET_ATTRIBUTE = 'h',
RECURSIVE_SET_ATTRIBUTE = 'H',
IGNORE_PATH = 'x',
IGNORE_DIRECTORY_PATH = 'X',
REMOVE_PATH = 'r',
RECURSIVE_REMOVE_PATH = 'R',
RELABEL_PATH = 'z',
RECURSIVE_RELABEL_PATH = 'Z',
ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
} ItemType;
typedef enum AgeBy {
AGE_BY_ATIME = 1 << 0,
AGE_BY_BTIME = 1 << 1,
AGE_BY_CTIME = 1 << 2,
AGE_BY_MTIME = 1 << 3,
/* All file timestamp types are checked by default. */
AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
AGE_BY_DEFAULT_DIR = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME,
} AgeBy;
typedef struct FCapsPatch {
uint64_t mask;
uint64_t set;
} FCapsPatch;
typedef struct FCapsUpdate {
uid_t rootuid;
FCapsPatch inheritable;
FCapsPatch permitted;
FCapsPatch effective;
} FCapsUpdate;
typedef struct Item {
ItemType type;
char *path;
char *argument;
void *binary_argument; /* set if binary data, in which case it takes precedence over 'argument' */
size_t binary_argument_size;
char **xattrs;
#if HAVE_ACL
acl_t acl_access;
acl_t acl_access_exec;
acl_t acl_default;
#endif
FCapsUpdate fcaps;
uid_t uid;
gid_t gid;
mode_t mode;
usec_t age;
AgeBy age_by_file, age_by_dir;
dev_t major_minor;
unsigned attribute_value;
unsigned attribute_mask;
bool uid_set:1;
bool gid_set:1;
bool mode_set:1;
bool uid_only_create:1;
bool gid_only_create:1;
bool mode_only_create:1;
bool age_set:1;
bool mask_perms:1;
bool attribute_set:1;
bool keep_first_level:1;
bool append_or_force:1;
bool allow_failure:1;
bool try_replace:1;
bool purge:1;
bool ignore_if_target_missing:1;
bool fcaps_set:1;
OperationMask done;
} Item;
typedef struct ItemArray {
Item *items;
size_t n_items;
struct ItemArray *parent;
Set *children;
} ItemArray;
typedef enum DirectoryType {
DIRECTORY_RUNTIME,
DIRECTORY_STATE,
DIRECTORY_CACHE,
DIRECTORY_LOGS,
DIRECTORY_SHARED,
_DIRECTORY_TYPE_MAX,
} DirectoryType;
typedef enum {
CREATION_NORMAL,
CREATION_EXISTING,
CREATION_FORCE,
_CREATION_MODE_MAX,
_CREATION_MODE_INVALID = -EINVAL,
} CreationMode;
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
static bool arg_dry_run = false;
static bool arg_inline = false;
static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
static OperationMask arg_operation = 0;
static bool arg_boot = false;
static bool arg_graceful = false;
static PagerFlags arg_pager_flags = 0;
static char **arg_include_prefixes = NULL;
static char **arg_exclude_prefixes = NULL;
static char *arg_root = NULL;
static char *arg_image = NULL;
static const char *arg_replace = NULL;
static ImagePolicy *arg_image_policy = NULL;
static LabelContext *arg_label_context = NULL;
#define MAX_DEPTH 256
typedef struct Context {
OrderedHashmap *items;
OrderedHashmap *globs;
Set *unix_sockets;
Hashmap *uid_cache;
Hashmap *gid_cache;
} Context;
STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
STATIC_DESTRUCTOR_REGISTER(arg_label_context, mac_label_context_freep);
COMMAND(
"systemd-tmpfiles\0",
"Create, delete, and clean up files and directories.",
.argspec = "[CONFIGURATION FILE…]\0",
.man_pages = "systemd-tmpfiles(8)\0",
.pager_flags = &arg_pager_flags,
);
static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
[CREATION_NORMAL] = "Created",
[CREATION_EXISTING] = "Found existing",
[CREATION_FORCE] = "Created replacement",
};
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
static void context_done(Context *c) {
assert(c);
ordered_hashmap_free(c->items);
ordered_hashmap_free(c->globs);
set_free(c->unix_sockets);
hashmap_free(c->uid_cache);
hashmap_free(c->gid_cache);
}
/* Different kinds of errors that mean that information is not available in the environment. */
static bool ERRNO_IS_NEG_NOINFO(intmax_t r) {
return IN_SET(r,
-EUNATCH, /* os-release or machine-id missing */
-ENOMEDIUM, /* machine-id or another file empty */
-ENOPKG, /* machine-id is uninitialized */
-ENXIO); /* env var is unset */
}
static int specifier_directory(
char specifier,
const void *data,
const char *root,
const void *userdata,
char **ret) {
struct table_entry {
uint64_t type;
const char *suffix;
};
static const struct table_entry paths_system[] = {
[DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME },
[DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE },
[DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE },
[DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS },
[DIRECTORY_SHARED] = { SD_PATH_SYSTEM_SHARED },
};
static const struct table_entry paths_user[] = {
[DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME },
[DIRECTORY_STATE] = { SD_PATH_USER_STATE_PRIVATE },
[DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE },
[DIRECTORY_LOGS] = { SD_PATH_USER_STATE_PRIVATE, "log" },
[DIRECTORY_SHARED] = { SD_PATH_USER_SHARED },
};
const struct table_entry *paths;
_cleanup_free_ char *p = NULL;
unsigned i;
int r;
assert(ret);
assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
paths = arg_runtime_scope == RUNTIME_SCOPE_USER ? paths_user : paths_system;
i = PTR_TO_UINT(data);
assert(i < ELEMENTSOF(paths_system));
r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
if (r < 0)
return r;
*ret = TAKE_PTR(p);
return 0;
}
static int log_unresolvable_specifier(const char *filename, unsigned line) {
static bool notified = false;
/* In system mode, this is called when /etc is not fully initialized and some specifiers are
* unresolvable. In user mode, this is called when some variables are not defined. These cases are
* not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
* to LOG_DEBUG for the rest.
*
* If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
* always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
* expectation that machine-id and other files will be populated.
*/
int log_level = notified || arg_root || running_in_chroot() > 0 ?
LOG_DEBUG : LOG_NOTICE;
log_syntax(NULL,
log_level,
filename, line, 0,
"Failed to resolve specifier: %s, skipping.",
arg_runtime_scope == RUNTIME_SCOPE_USER ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
if (!notified)
log_full(log_level,
"All rules containing unresolvable specifiers will be skipped.");
notified = true;
return 0;
}
#define log_action(would, doing, fmt, ...) \
log_full(arg_dry_run ? LOG_INFO : LOG_DEBUG, \
fmt, \
arg_dry_run ? (would) : (doing), \
__VA_ARGS__)
static int user_config_paths(char ***ret) {
_cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
_cleanup_free_ char *runtime_config = NULL;
int r;
assert(ret);
/* Combined user-specific and global dirs */
r = user_search_dirs("/user-tmpfiles.d", &config_dirs, &data_dirs);
if (r < 0)
return r;
r = xdg_user_runtime_dir("/user-tmpfiles.d", &runtime_config);
if (r < 0 && !ERRNO_IS_NEG_NOINFO(r))
return r;
r = strv_consume(&config_dirs, TAKE_PTR(runtime_config));
if (r < 0)
return r;
r = strv_extend_strv_consume(&config_dirs, TAKE_PTR(data_dirs), /* filter_duplicates= */ true);
if (r < 0)
return r;
r = path_strv_make_absolute_cwd(config_dirs);
if (r < 0)
return r;
*ret = TAKE_PTR(config_dirs);
return 0;
}
static bool needs_purge(ItemType t) {
return IN_SET(t,
CREATE_FILE,
TRUNCATE_FILE,
CREATE_DIRECTORY,
TRUNCATE_DIRECTORY,
CREATE_SUBVOLUME,
CREATE_SUBVOLUME_INHERIT_QUOTA,
CREATE_SUBVOLUME_NEW_QUOTA,
CREATE_FIFO,
CREATE_SYMLINK,
CREATE_CHAR_DEVICE,
CREATE_BLOCK_DEVICE,
COPY_FILES,
WRITE_FILE,
EMPTY_DIRECTORY);
}
static bool needs_glob(ItemType t) {
return IN_SET(t,
WRITE_FILE,
EMPTY_DIRECTORY,
SET_XATTR,
RECURSIVE_SET_XATTR,
SET_ACL,
RECURSIVE_SET_ACL,
SET_FCAPS,
RECURSIVE_SET_FCAPS,
SET_ATTRIBUTE,
RECURSIVE_SET_ATTRIBUTE,
IGNORE_PATH,
IGNORE_DIRECTORY_PATH,
REMOVE_PATH,
RECURSIVE_REMOVE_PATH,
RELABEL_PATH,
RECURSIVE_RELABEL_PATH,
ADJUST_MODE);
}
static bool takes_ownership(ItemType t) {
return IN_SET(t,
CREATE_FILE,
TRUNCATE_FILE,
CREATE_DIRECTORY,
TRUNCATE_DIRECTORY,
CREATE_SUBVOLUME,
CREATE_SUBVOLUME_INHERIT_QUOTA,
CREATE_SUBVOLUME_NEW_QUOTA,
CREATE_FIFO,
CREATE_SYMLINK,
CREATE_CHAR_DEVICE,
CREATE_BLOCK_DEVICE,
COPY_FILES,
WRITE_FILE,
EMPTY_DIRECTORY,
IGNORE_PATH,
IGNORE_DIRECTORY_PATH,
REMOVE_PATH,
RECURSIVE_REMOVE_PATH);
}
static bool supports_ignore_if_target_missing(ItemType t) {
return t == CREATE_SYMLINK;
}
static struct Item* find_glob(OrderedHashmap *h, const char *match) {
ItemArray *j;
ORDERED_HASHMAP_FOREACH(j, h)
FOREACH_ARRAY(item, j->items, j->n_items)
if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
return item;
return NULL;
}
static int load_unix_sockets(Context *c) {
_cleanup_set_free_ Set *sockets = NULL;
_cleanup_fclose_ FILE *f = NULL;
int r;
if (c->unix_sockets)
return 0;
/* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
f = fopen("/proc/net/unix", "re");
if (!f)
return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
"Failed to open %s, ignoring: %m", "/proc/net/unix");
/* Skip header */
r = read_line(f, LONG_LINE_MAX, NULL);
if (r < 0)
return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
if (r == 0)
return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
for (;;) {
_cleanup_free_ char *line = NULL;
char *p;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
if (r == 0) /* EOF */
break;
p = strchr(line, ':');
if (!p)
continue;
if (strlen(p) < 37)
continue;
p += 37;
p += strspn(p, WHITESPACE);
p += strcspn(p, WHITESPACE); /* skip one more word */
p += strspn(p, WHITESPACE);
if (!path_is_absolute(p))
continue;
r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
if (r < 0)
return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
}
c->unix_sockets = TAKE_PTR(sockets);
return 1;
}
static bool unix_socket_alive(Context *c, const char *fn) {
assert(c);
assert(fn);
if (load_unix_sockets(c) < 0)
return true; /* We don't know, so assume yes */
return set_contains(c->unix_sockets, fn);
}
/* Accessors for the argument in binary format */
static const void* item_binary_argument(const Item *i) {
assert(i);
return i->binary_argument ?: i->argument;
}
static size_t item_binary_argument_size(const Item *i) {
assert(i);
return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
}
static DIR* xopendirat_nomod(int dirfd, const char *path) {
DIR *dir;
dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
if (dir)
return dir;
if (!IN_SET(errno, ENOENT, ELOOP))
log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
if (!ERRNO_IS_PRIVILEGE(errno))
return NULL;
dir = xopendirat(dirfd, path, O_NOFOLLOW);
if (!dir)
log_debug_errno(errno, "Cannot open %sdirectory \"%s\" with or without O_NOATIME: %m", dirfd == AT_FDCWD ? "" : "sub", path);
return dir;
}
static DIR* opendir_nomod(const char *path) {
return xopendirat_nomod(AT_FDCWD, path);
}
static int opendir_and_stat(
const char *path,
DIR **ret,
struct statx *ret_sx,
bool *ret_mountpoint) {
_cleanup_closedir_ DIR *d = NULL;
struct statx sx;
int r;
assert(path);
assert(ret);
assert(ret_sx);
assert(ret_mountpoint);
/* Do opendir() and statx() on the directory.
* Return 1 if successful, 0 if file doesn't exist or is not a directory,
* negative errno otherwise.
*/
d = opendir_nomod(path);
if (!d) {
bool ignore = IN_SET(errno, ENOENT, ENOTDIR);
r = log_full_errno(ignore ? LOG_DEBUG : LOG_ERR,
errno, "Failed to open directory %s: %m", path);
if (!ignore)
return r;
*ret = NULL;
*ret_sx = (struct statx) {};
*ret_mountpoint = false;
return 0;
}
r = xstatx_full(dirfd(d),
/* path= */ NULL,
AT_EMPTY_PATH,
/* xstatx_flags= */ 0,
STATX_MODE|STATX_INO,
STATX_ATIME|STATX_MTIME,
STATX_ATTR_MOUNT_ROOT,
&sx);
if (r < 0)
return log_error_errno(r, "statx(%s) failed: %m", path);
*ret_mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
*ret = TAKE_PTR(d);
*ret_sx = sx;
return 1;
}
static bool needs_cleanup(
nsec_t atime,
nsec_t btime,
nsec_t ctime,
nsec_t mtime,
nsec_t cutoff,
const char *sub_path,
AgeBy age_by,
bool is_dir) {
if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
/* Follows spelling in stat(1). */
log_debug("%s \"%s\": modify time %s is too new.",
is_dir ? "Directory" : "File",
sub_path,
FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
return false;
}
if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
log_debug("%s \"%s\": access time %s is too new.",
is_dir ? "Directory" : "File",
sub_path,
FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
return false;
}
/*
* Note: Unless explicitly specified by the user, "ctime" is ignored
* by default for directories, because we change it when deleting.
*/
if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
log_debug("%s \"%s\": change time %s is too new.",
is_dir ? "Directory" : "File",
sub_path,
FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
return false;
}
if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
log_debug("%s \"%s\": birth time %s is too new.",
is_dir ? "Directory" : "File",
sub_path,
FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
return false;
}
return true;
}
static int dir_cleanup(
Context *c,
Item *i,
const char *p,
DIR *d,
nsec_t self_atime_nsec,
nsec_t self_mtime_nsec,
nsec_t cutoff_nsec,
dev_t rootdev_major,
dev_t rootdev_minor,
bool mountpoint,
int maxdepth,
bool keep_this_level,
AgeBy age_by_file,
AgeBy age_by_dir) {
bool deleted = false;
int r = 0;
assert(c);
assert(i);
assert(d);
FOREACH_DIRENT_ALL(de, d, break) {
_cleanup_free_ char *sub_path = NULL;
nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
if (dot_or_dot_dot(de->d_name))
continue;
struct statx sx;
int k = xstatx_full(dirfd(d), de->d_name,
AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
/* xstatx_flags= */ 0,
STATX_TYPE|STATX_MODE|STATX_UID,
STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
STATX_ATTR_MOUNT_ROOT,
&sx);
if (k == -ENOENT)
continue;
if (k < 0) {
/* FUSE, NFS mounts, SELinux might return EACCES */
log_full_errno(k == -EACCES ? LOG_DEBUG : LOG_ERR, k,
"statx(%s/%s) failed: %m", p, de->d_name);
continue;
}
if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
continue;
}
atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? statx_timestamp_load_nsec(&sx.stx_atime) : NSEC_INFINITY;
mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? statx_timestamp_load_nsec(&sx.stx_mtime) : NSEC_INFINITY;
ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? statx_timestamp_load_nsec(&sx.stx_ctime) : NSEC_INFINITY;
btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? statx_timestamp_load_nsec(&sx.stx_btime) : NSEC_INFINITY;
sub_path = path_join(p, de->d_name);
if (!sub_path) {
r = log_oom();
goto finish;
}
/* Is there an item configured for this path? */
if (ordered_hashmap_get(c->items, sub_path)) {
log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
continue;
}
if (find_glob(c->globs, sub_path)) {
log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
continue;
}
if (S_ISDIR(sx.stx_mode)) {
_cleanup_closedir_ DIR *sub_dir = NULL;
if (mountpoint &&
streq(de->d_name, "lost+found") &&
sx.stx_uid == 0) {
log_debug("Ignoring directory \"%s\".", sub_path);
continue;
}
if (maxdepth <= 0)
log_warning("Reached max depth on \"%s\".", sub_path);
else {
int q;
sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
if (!sub_dir) {
if (errno != ENOENT)
r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
continue;
}
if (!arg_dry_run &&
flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
log_debug_errno(errno, "Couldn't acquire exclusive BSD lock on directory \"%s\", skipping: %m", sub_path);
continue;
}
q = dir_cleanup(c, i,
sub_path, sub_dir,
atime_nsec, mtime_nsec, cutoff_nsec,
rootdev_major, rootdev_minor,
false, maxdepth-1, false,
age_by_file, age_by_dir);
if (q < 0)
r = q;
}
/* Note: if you are wondering why we don't support the sticky bit for excluding
* directories from cleaning like we do it for other file system objects: well, the
* sticky bit already has a meaning for directories, so we don't want to overload
* that. */
if (keep_this_level) {
log_debug("Keeping directory \"%s\".", sub_path);
continue;
}
/*
* Check the file timestamps of an entry against the
* given cutoff time; delete if it is older.
*/
if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
cutoff_nsec, sub_path, age_by_dir, true))
continue;
log_action("Would remove", "Removing", "%s directory \"%s\"", sub_path);
if (!arg_dry_run &&
unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0) {
if (errno == ENOTEMPTY)
continue;
if (errno != ENOENT)
r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
}
deleted = true;
} else {
_cleanup_close_ int fd = -EBADF; /* This file descriptor is defined here so that the
* lock that is taken below is only dropped _after_
* the unlink operation has finished. */
/* Skip files for which the sticky bit is set. These are semantics we define, and are
* unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
if (sx.stx_mode & S_ISVTX) {
log_debug("Skipping \"%s\": sticky bit set.", sub_path);
continue;
}
if (mountpoint &&
S_ISREG(sx.stx_mode) &&
sx.stx_uid == 0 &&
STR_IN_SET(de->d_name,
".journal",
"aquota.user",
"aquota.group")) {
log_debug("Skipping \"%s\".", sub_path);
continue;
}
/* Ignore sockets that are listed in /proc/net/unix */
if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(c, sub_path)) {
log_debug("Skipping \"%s\": live socket.", sub_path);
continue;
}
/* Ignore device nodes */
if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
log_debug("Skipping \"%s\": a device.", sub_path);
continue;
}
/* Keep files on this level if this was requested */
if (keep_this_level) {
log_debug("Keeping \"%s\".", sub_path);
continue;
}
if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
cutoff_nsec, sub_path, age_by_file, false))
continue;
if (!arg_dry_run) {
fd = xopenat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME|O_NONBLOCK|O_NOCTTY);
if (fd < 0 && !IN_SET(fd, -ENOENT, -ELOOP))
log_warning_errno(fd, "Opening file \"%s\" failed, proceeding without lock: %m", sub_path);
if (fd >= 0 && flock(fd, LOCK_EX|LOCK_NB) < 0 && errno == EAGAIN) {
log_debug_errno(errno, "Couldn't acquire exclusive BSD lock on file \"%s\", skipping: %m", sub_path);
continue;
}
}
log_action("Would remove", "Removing", "%s \"%s\"", sub_path);
if (!arg_dry_run &&
unlinkat(dirfd(d), de->d_name, 0) < 0 &&
errno != ENOENT)
r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
deleted = true;
}
}
finish:
if (deleted && (self_atime_nsec < NSEC_INFINITY || self_mtime_nsec < NSEC_INFINITY)) {
struct timespec ts[2];
log_action("Would restore", "Restoring",
"%s access and modification time on \"%s\": %s, %s",
p,
self_atime_nsec != NSEC_INFINITY
? FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US)
: "(omitted)",
self_mtime_nsec != NSEC_INFINITY
? FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US)
: "(omitted)");
ts[0] = self_atime_nsec != NSEC_INFINITY
? *TIMESPEC_STORE_NSEC(self_atime_nsec)
: TIMESPEC_OMIT;
ts[1] = self_mtime_nsec != NSEC_INFINITY
? *TIMESPEC_STORE_NSEC(self_mtime_nsec)
: TIMESPEC_OMIT;
/* Restore original directory timestamps */
if (!arg_dry_run &&
futimens(dirfd(d), ts) < 0)
log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
}
return r;
}
static bool hardlinks_protected(void) {
static int cached = -1;
int r;
/* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off,
* as that's what the kernel default is.
* Note that we ship 50-default.conf where it is enabled, but better be safe than sorry. */
if (cached >= 0)
return cached;
int v;
r = sysctl_read_int("fs/protected_hardlinks", &v);
if (r < 0) {
log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl, assuming disabled: %m");
return false;
}
cached = v > 0;
return cached;
}
static bool hardlink_vulnerable(const struct stat *st) {
assert(st);
return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && !hardlinks_protected();
}
static mode_t process_mask_perms(mode_t mode, mode_t current) {
if ((current & 0111) == 0)
mode &= ~0111;
if ((current & 0222) == 0)
mode &= ~0222;
if ((current & 0444) == 0)
mode &= ~0444;
if (!S_ISDIR(current))
mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
return mode;
}
static int fd_set_perms(
Context *c,
Item *i,
int fd,
const char *path,
const struct stat *st,
CreationMode creation) {
bool do_chown, do_chmod;
struct stat stbuf;
mode_t new_mode;
uid_t new_uid;
gid_t new_gid;
int r;
assert(c);
assert(i);
assert(fd >= 0);
assert(path);
if (!i->mode_set && !i->uid_set && !i->gid_set)
goto shortcut;
if (!st) {
if (fstat(fd, &stbuf) < 0)
return log_error_errno(errno, "fstat(%s) failed: %m", path);
st = &stbuf;
}
if (hardlink_vulnerable(st))
return log_error_errno(SYNTHETIC_ERRNO(EPERM),
"Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
path);
new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;