Files
finit/src/tmpfiles.c
T
Joachim Wiberg 74da582488 tmpfiles: set the owner before the mode
An entry that sets both setuid or setgid and another owner lost the
bit again:

    f /usr/libexec/helper 4755 app app

The mode was set first, and a change of owner drops setuid and setgid
from a file.  A second run put it back, the owner was right by then.

Change the owner first.  A mode that is not in the entry is put back
the same way.  Also, a mode that ~ masks down to 0 is now set, 0 was
taken for no mode.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-20 18:03:31 +01:00

1459 lines
30 KiB
C

/* Limited tmpfiles.d implementation
*
* Copyright (c) 2025 Joachim Wiberg <troglobit@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "config.h" /* Generated by configure script */
#include <dirent.h>
#include <endian.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <ftw.h>
#include <getopt.h>
#include <glob.h>
#include <libgen.h>
#include <grp.h>
#include <pwd.h>
#include <sys/sysmacros.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/xattr.h>
#include <linux/posix_acl.h>
#include <linux/posix_acl_xattr.h>
#ifdef _LIBITE_LITE
# include <libite/lite.h>
#else
# include <lite/lite.h>
#endif
#include "log.h"
#include "util.h"
int debug;
int create_flag = 0;
int clean_flag = 0;
int remove_flag = 0;
int boot_flag = 0;
/* Set for the first of two passes, the second one does the complaining */
static int quiet;
#define MAX_EXCLUDES 32
static const char *exclude_prefixes[MAX_EXCLUDES];
static int num_excludes;
static void add_exclude_prefix(const char *prefix)
{
if (num_excludes < MAX_EXCLUDES)
exclude_prefixes[num_excludes++] = prefix;
}
static int excluded(const char *path)
{
for (int i = 0; i < num_excludes; i++) {
if (!strncmp(path, exclude_prefixes[i], strlen(exclude_prefixes[i])))
return 1;
}
return 0;
}
static int is_dir_empty(const char *path)
{
struct dirent **namelist = NULL;
int num;
num = scandir(path, &namelist, NULL, NULL);
if (num < 0)
return 0;
for (int i = 0; i < num; i++)
free(namelist[i]);
free(namelist);
return num >= 3;
}
static int glob_do(const char *path, int (*cb)(const char *))
{
int rc = 0;
glob_t gl;
rc = glob(path, GLOB_NOESCAPE, NULL, &gl);
if (rc) {
if (rc == GLOB_NOMATCH) {
errno = ENOENT;
return -1;
}
return 0;
}
for (size_t i = 0; i < gl.gl_pathc; i++)
rc += cb(gl.gl_pathv[i]);
globfree(&gl);
return rc;
}
static int parse_mm(char *arg, int *major, int *minor)
{
char *ptr;
if (!arg) {
inval:
errno = EINVAL;
return -1;
}
ptr = strchr(arg, ':');
if (!ptr)
goto inval;
*ptr++ = 0;
*major = atonum(arg);
*minor = atonum(ptr);
if (*major < 0 || *minor < 0)
goto inval;
return 0;
}
static void mkparent(char *path, mode_t mode)
{
mkpath(dirname(strdupa(path)), mode);
}
static char *write_hex(FILE *fp, char *p)
{
unsigned char val;
char num[4], *ptr;
int i, len = 0;
for (i = 0; p[i] && len < 2; i++) {
char c = p[i];
if ((c >= '0' && c <= '7') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F'))
num[len++] = c;
else
break;
}
num[len] = 0;
if (len == 0) {
fputs("x", fp);
return p;
}
errno = 0;
val = strtoul(num, &ptr, 16);
if (errno || ptr == num)
goto end;
fputc(val & 0xff, fp);
end:
return &p[i];
}
static char *write_num(FILE *fp, char *p)
{
unsigned char val;
char num[4], *ptr;
int i, len = 0;
for (i = 0; p[i] && len < 3; i++) {
char c = p[i];
if (c >= '0' && c <= '7')
num[len++] = c;
else
break;
}
num[len] = 0;
if (len == 0)
return p;
errno = 0;
val = strtoul(num, &ptr, 8);
if (errno || ptr == num)
goto end;
fputc(val & 0xff, fp);
end:
return &p[i];
}
static void write_arg(FILE *fp, char *arg)
{
char *p;
if (!arg)
return;
while (*arg && (p = strchr(arg, '\\'))) {
fwrite(arg, sizeof(char), p - arg, fp);
*p++ = 0;
switch (*p) {
case '\\':
fputc('\\', fp);
arg = p + 1;
break;
case '\'':
fputc('\'', fp);
arg = p + 1;
break;
case '"':
fputc('"', fp);
arg = p + 1;
break;
case 'a':
fputc('\a', fp);
arg = p + 1;
break;
case 'b':
fputc('\b', fp);
arg = p + 1;
break;
case 'e':
fputc('\e', fp);
arg = p + 1;
break;
case 'n':
fputc('\n', fp);
arg = p + 1;
break;
case 't':
fputc('\t', fp);
arg = p + 1;
break;
case 'x':
arg = write_hex(fp, &p[1]);
break;
case '0' ... '7':
arg = write_num(fp, p);
break;
default:
fputc(*p, fp);
arg = p + 1;
break;
}
}
fputs(arg, fp);
}
/**
* Parse age string and return age in seconds.
* Returns -1 on invalid/empty age ("-" or NULL).
* Examples: "10d" = 864000, "1w" = 604800, "2h" = 7200
*/
static time_t parse_age(const char *age)
{
time_t val;
char *end;
if (!age || !strcmp(age, "-"))
return -1;
errno = 0;
val = strtoul(age, &end, 10);
if (errno || end == age)
return -1;
switch (*end) {
case 'w':
val *= 7;
/* fallthrough */
case 'd':
val *= 24;
/* fallthrough */
case 'h':
val *= 60;
/* fallthrough */
case 'm':
val *= 60;
/* fallthrough */
case 's':
case '\0':
break;
default:
return -1; /* unknown suffix */
}
return val;
}
/**
* Parse user string - supports both names and numeric UIDs.
* Returns UID on success, -1 on failure or when no user is given.
*/
static int parse_uid(const char *user)
{
long val;
if (!user)
return -1;
/* Check if it's a numeric UID */
val = atonum(user);
if (val >= 0)
return val;
/* Not numeric, look up by name */
return getuser(user, NULL);
}
/**
* Parse group string - supports both names and numeric GIDs.
* Returns GID on success, -1 on failure or when no group is given.
*/
static int parse_gid(const char *group)
{
long val;
if (!group)
return -1;
/* Check if it's a numeric GID */
val = atonum(group);
if (val >= 0)
return val;
/* Not numeric, look up by name */
return getgroup(group);
}
/* Mode and owner of an entry, mode 0 and id -1 when not given */
struct perm {
mode_t mode;
int uid, gid;
int mask; /* ~, see perm_set() */
int new_mode, new_uid, new_gid; /* :, only for a path the entry creates */
};
/* Also for an fd opened with O_PATH, which fchmod() does not take */
static int fd_chmod(int fd, mode_t mode)
{
char proc[32];
if (!fchmod(fd, mode))
return 0;
if (errno != EBADF)
return -1;
snprintf(proc, sizeof(proc), "/proc/self/fd/%d", fd);
return chmod(proc, mode);
}
/*
* Set mode and owner on an open fd, only what differs is touched, the
* path may be immutable. @created tells if the entry made the path.
*/
static int perm_set(int fd, const struct perm *p, int created)
{
int uid = p->uid, gid = p->gid;
int chowned = 0;
struct stat st;
mode_t mode;
if (fstat(fd, &st))
return -1;
if (S_ISLNK(st.st_mode))
return 0;
mode = st.st_mode & 07777;
if (p->mode && (created || !p->new_mode)) {
mode = p->mode;
/* Keep read, write, and execute only where the path has it for someone */
if (p->mask && !created) {
for (mode_t bits = 0111; bits <= 0444; bits <<= 1) {
if (!(st.st_mode & bits))
mode &= ~bits;
}
if (!S_ISDIR(st.st_mode))
mode &= ~07000;
}
}
if (!created) {
if (p->new_uid)
uid = -1;
if (p->new_gid)
gid = -1;
}
if ((uid != -1 && st.st_uid != (uid_t)uid) || (gid != -1 && st.st_gid != (gid_t)gid)) {
if (fchownat(fd, "", uid, gid, AT_EMPTY_PATH))
return -1;
chowned = 1;
}
/* A change of owner drops setuid and setgid, so the mode goes last */
if ((st.st_mode & 07777) != mode || (chowned && (mode & 06000)))
return fd_chmod(fd, mode);
return 0;
}
/* Never follows a link at @path, see also dirperm() */
static int perm_path(const char *path, const struct perm *p, int created, int flags)
{
int fd, rc;
fd = open(path, flags | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
return -1;
rc = perm_set(fd, p, created);
close(fd);
return rc;
}
/* Global for perm_cb(), nftw() cannot pass user data */
static const struct perm *perm_tree;
static int perm_cb(const char *path, const struct stat *st, int tflag, struct FTW *ftw)
{
(void)st; (void)tflag; (void)ftw;
if (perm_path(path, perm_tree, 0, O_PATH))
warn("Failed setting mode/owner on %s", path);
return 0;
}
/* What the x and X entries keep from being cleaned */
struct keep {
char *pattern;
int self; /* X, the path but not what is in it */
};
static struct keep *keeps;
static int num_keeps;
static int collect; /* Pass that only gathers the above */
static void keep_add(const char *pattern, int self)
{
struct keep *k;
k = realloc(keeps, (num_keeps + 1) * sizeof(*k));
if (!k)
return;
keeps = k;
k = &keeps[num_keeps];
k->pattern = strdup(pattern);
k->self = self;
if (!k->pattern)
return;
/* The paths from nftw() have no slash at the end */
for (size_t len = strlen(k->pattern); len > 1 && k->pattern[len - 1] == '/'; len--)
k->pattern[len - 1] = 0;
num_keeps++;
}
static int kept(const char *path)
{
for (int i = 0; i < num_keeps; i++) {
struct keep *k = &keeps[i];
if (!fnmatch(k->pattern, path, FNM_PATHNAME | (k->self ? 0 : FNM_LEADING_DIR)))
return 1;
}
return 0;
}
/* Globals for do_clean() callback - nftw doesn't support user data */
static time_t clean_age;
static time_t clean_now;
static int do_clean(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw)
{
int is_dir;
/* Skip the root directory itself */
if (ftw->level == 0)
return 0;
is_dir = (tflag == FTW_D || tflag == FTW_DP);
/*
* Conservative cleanup matching systemd-tmpfiles behavior:
* - Files: keep if ANY of atime, ctime, mtime is recent
* - Directories: keep if ANY of atime, mtime is recent (ctime
* excluded because cleanup itself updates directory ctime)
* - Age 0 removes everything, whatever the timestamps
*/
if (clean_age) {
if (clean_now - sb->st_mtime < clean_age)
return 0; /* mtime is too new, keep it */
if (clean_now - sb->st_atime < clean_age)
return 0; /* atime is too new, keep it */
if (!is_dir && clean_now - sb->st_ctime < clean_age)
return 0; /* ctime is too new, keep it (files only) */
}
if (kept(fpath))
return 0;
if (remove(fpath) && errno != ENOENT && errno != EBUSY && errno != ENOTEMPTY)
warn("Failed cleaning %s", fpath);
return 0;
}
/*
* POSIX ACLs for the a and A entries. Set straight
* through the system.posix_acl_* extended attributes, in the kernel's
* own format, so there is no need for libacl.
*/
#define ACL_MAX 32
#define ACL_COND_EXEC 0x100 /* X, execute only for a directory or an executable */
struct ace {
int tag;
unsigned id;
int perm;
};
struct acl {
struct ace e[ACL_MAX];
int num;
};
struct acl_xattr {
struct posix_acl_xattr_header hdr;
struct posix_acl_xattr_entry e[ACL_MAX];
};
static struct ace *acl_find(struct acl *acl, int tag, unsigned id)
{
for (int i = 0; i < acl->num; i++) {
if (acl->e[i].tag == tag && acl->e[i].id == id)
return &acl->e[i];
}
return NULL;
}
static int acl_set(struct acl *acl, int tag, unsigned id, int perm)
{
struct ace *e = acl_find(acl, tag, id);
if (!e) {
if (acl->num == ACL_MAX) {
errno = ENOSPC;
return -1;
}
e = &acl->e[acl->num++];
e->tag = tag;
e->id = id;
}
e->perm = perm;
return 0;
}
static int acl_parse_perm(const char *str)
{
int perm = 0;
if (str[0] >= '0' && str[0] <= '7' && !str[1])
return str[0] - '0';
for (; *str; str++) {
switch (*str) {
case 'r': perm |= ACL_READ; break;
case 'w': perm |= ACL_WRITE; break;
case 'x': perm |= ACL_EXECUTE; break;
case 'X': perm |= ACL_COND_EXEC; break;
case '-': break;
default:
return -1;
}
}
return perm;
}
/* [d[efault]:]u[ser]|g[roup]|m[ask]|o[ther]:[NAME|ID]:PERMS */
static int acl_parse_entry(char *str, struct acl *access, struct acl *def)
{
struct acl *acl = access;
char *tag, *name, *perms;
unsigned id = ACL_UNDEFINED_ID;
int perm, type;
long val;
tag = strsep(&str, ":");
if (!strcmp(tag, "d") || !strcmp(tag, "default")) {
acl = def;
tag = strsep(&str, ":");
}
name = strsep(&str, ":");
perms = strsep(&str, ":");
if (!perms) { /* m:rwx and o:rx, without the empty name */
perms = name;
name = "";
}
if (!tag || !perms || str)
return -1;
perm = acl_parse_perm(perms);
if (perm < 0)
return -1;
if (!strcmp(tag, "u") || !strcmp(tag, "user"))
type = name[0] ? ACL_USER : ACL_USER_OBJ;
else if (!strcmp(tag, "g") || !strcmp(tag, "group"))
type = name[0] ? ACL_GROUP : ACL_GROUP_OBJ;
else if (!strcmp(tag, "m") || !strcmp(tag, "mask"))
type = ACL_MASK;
else if (!strcmp(tag, "o") || !strcmp(tag, "other"))
type = ACL_OTHER;
else
return -1;
if (name[0]) {
if (type != ACL_USER && type != ACL_GROUP)
return -1;
if (type == ACL_USER)
val = parse_uid(name);
else if ((val = atonum(name)) < 0)
val = getgroup(name);
if (val < 0)
return -1;
id = val;
}
return acl_set(acl, type, id, perm);
}
static int acl_parse(char *arg, struct acl *access, struct acl *def)
{
char *entry;
while ((entry = strsep(&arg, ", \t"))) {
if (!entry[0])
continue;
if (acl_parse_entry(entry, access, def))
return -1;
}
return 0;
}
/* No ACL is fine, one that cannot be read must not be replaced */
static int acl_read(const char *path, const char *name, struct acl *acl)
{
struct acl_xattr buf;
ssize_t len;
len = getxattr(path, name, &buf, sizeof(buf));
if (len < 0)
return errno == ENODATA ? 0 : -1;
if (len < (ssize_t)sizeof(buf.hdr) || le32toh(buf.hdr.a_version) != POSIX_ACL_XATTR_VERSION) {
errno = EINVAL;
return -1;
}
acl->num = (len - sizeof(buf.hdr)) / sizeof(buf.e[0]);
for (int i = 0; i < acl->num; i++) {
acl->e[i].tag = le16toh(buf.e[i].e_tag);
acl->e[i].perm = le16toh(buf.e[i].e_perm);
acl->e[i].id = le32toh(buf.e[i].e_id);
}
return 0;
}
static int acl_cmp(const void *a, const void *b)
{
const struct ace *x = a, *y = b;
if (x->tag != y->tag)
return x->tag - y->tag;
return (x->id > y->id) - (x->id < y->id);
}
static int acl_write(const char *path, const char *name, struct acl *acl)
{
struct acl_xattr buf;
qsort(acl->e, acl->num, sizeof(acl->e[0]), acl_cmp);
buf.hdr.a_version = htole32(POSIX_ACL_XATTR_VERSION);
for (int i = 0; i < acl->num; i++) {
buf.e[i].e_tag = htole16(acl->e[i].tag);
buf.e[i].e_perm = htole16(acl->e[i].perm);
buf.e[i].e_id = htole32(acl->e[i].id);
}
return setxattr(path, name, &buf, sizeof(buf.hdr) + acl->num * sizeof(buf.e[0]), 0);
}
/*
* Set the entries in @new on @path, on top of the ACL it has when
* @modify is set. What a complete ACL needs and @new lacks comes from
* the ACL it has, or else the mode in @st, and the mask is made to
* cover every named entry.
*/
static int acl_apply(const char *path, const char *name, const struct acl *new, int modify,
const struct stat *st)
{
const int base[][2] = {
{ ACL_USER_OBJ, (st->st_mode >> 6) & 7 },
{ ACL_GROUP_OBJ, (st->st_mode >> 3) & 7 },
{ ACL_OTHER, st->st_mode & 7 },
};
struct acl acl = { 0 }, old = { 0 };
int mask = 0, named = 0, has_mask = 0;
if (acl_read(path, name, &old))
return -1;
if (modify)
acl = old;
for (int i = 0; i < new->num; i++) {
const struct ace *e = &new->e[i];
int perm = e->perm & 7;
if ((e->perm & ACL_COND_EXEC) && (S_ISDIR(st->st_mode) || (st->st_mode & 0111)))
perm |= ACL_EXECUTE;
if (e->tag == ACL_MASK)
has_mask = 1;
if (acl_set(&acl, e->tag, e->id, perm))
return -1;
}
for (size_t i = 0; i < NELEMS(base); i++) {
struct ace *e = acl_find(&old, base[i][0], ACL_UNDEFINED_ID);
if (!acl_find(&acl, base[i][0], ACL_UNDEFINED_ID) &&
acl_set(&acl, base[i][0], ACL_UNDEFINED_ID, e ? e->perm : base[i][1]))
return -1;
}
for (int i = 0; i < acl.num; i++) {
if (acl.e[i].tag == ACL_USER || acl.e[i].tag == ACL_GROUP)
named = 1;
if (acl.e[i].tag & (ACL_USER | ACL_GROUP_OBJ | ACL_GROUP))
mask |= acl.e[i].perm;
}
if (named && !has_mask && acl_set(&acl, ACL_MASK, ACL_UNDEFINED_ID, mask))
return -1;
return acl_write(path, name, &acl);
}
/* Globals for acl_cb(), nftw() cannot pass user data */
static const struct acl *acl_access, *acl_default;
static int acl_modify;
static int acl_path(const char *path)
{
char proc[32];
struct stat st;
int fd, rc = 0;
/* Through /proc so a link at @path is never followed */
fd = open(path, O_PATH | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
return -1;
snprintf(proc, sizeof(proc), "/proc/self/fd/%d", fd);
if (fstat(fd, &st)) {
rc = -1;
} else if (!S_ISLNK(st.st_mode)) {
if (acl_access->num)
rc = acl_apply(proc, "system.posix_acl_access", acl_access, acl_modify, &st);
if (!rc && acl_default->num && S_ISDIR(st.st_mode))
rc = acl_apply(proc, "system.posix_acl_default", acl_default, acl_modify, &st);
}
close(fd);
return rc;
}
static int acl_cb(const char *path, const struct stat *st, int tflag, struct FTW *ftw)
{
(void)st; (void)tflag; (void)ftw;
if (acl_path(path))
warn("Failed setting ACL on %s", path);
return 0;
}
static int acl_entry(const char *pattern, char *arg, int recursive, int modify)
{
struct acl access = { 0 }, def = { 0 };
glob_t gl;
int rc = 0;
if (!arg || acl_parse(arg, &access, &def)) {
errno = EINVAL;
return -1;
}
if (glob(pattern, GLOB_NOESCAPE, NULL, &gl))
return 0;
acl_access = &access;
acl_default = &def;
acl_modify = modify;
for (size_t i = 0; i < gl.gl_pathc; i++) {
if (recursive)
nftw(gl.gl_pathv[i], acl_cb, 20, FTW_PHYS);
else
rc |= acl_path(gl.gl_pathv[i]);
}
globfree(&gl);
return rc;
}
/*
* The configuration format is one line per path, containing type, path,
* mode, ownership, age, and argument fields. The lines are separated by
* newlines, the fields by whitespace:
*
* #Type Path Mode User Group Age Argument…
* d /run/user 0755 root root 10d -
* L /tmp/foobar - - - - /dev/null
*
* https://www.freedesktop.org/software/systemd/man/tmpfiles.d.html
*/
static void tmpfiles(char *line)
{
char *type, *path, *token, *user, *group, *age, *arg;
char *dst = NULL, *opts = "";
struct stat st, ast;
int major, minor;
int strc, rc = 0;
struct perm perm = { 0 };
int plus = 0, boot = 0;
FILE *fp = NULL;
char buf[1024];
glob_t gl;
type = strtok(line, "\t ");
if (!type)
return;
for (char *mod = &type[1]; *mod; mod++) {
if (*mod == '+')
plus = 1;
else if (*mod == '!')
boot = 1;
}
if (boot && !boot_flag)
return;
path = strtok(NULL, "\t ");
if (!path)
return;
if (strchr(path, '%')) {
if (!quiet)
warnx("Path name specifiers unsupported, skipping %s", path);
return;
}
if (excluded(path))
return;
if (collect) {
if (type[0] == 'x' || type[0] == 'X')
keep_add(path, type[0] == 'X');
return;
}
token = strtok(NULL, "\t ");
if (token) {
for (; *token == '~' || *token == ':'; token++) {
if (*token == '~')
perm.mask = 1;
else
perm.new_mode = 1;
}
errno = 0;
perm.mode = strtoul(token, &arg, 8);
if (errno || arg == token)
perm.mode = 0;
}
user = strtok(NULL, "\t ");
if (user && user[0] == ':') {
perm.new_uid = 1;
user++;
}
if (user && !strcmp(user, "-"))
user = NULL;
group = strtok(NULL, "\t ");
if (group && group[0] == ':') {
perm.new_gid = 1;
group++;
}
if (group && !strcmp(group, "-"))
group = NULL;
/*
* Quiet about it, Finit's own files have entries for users of
* services that may not be installed, and for the utmp group
*/
perm.uid = parse_uid(user);
if (user && perm.uid < 0) {
if (debug)
warnx("Unknown user %s, skipping %s", user, path);
return;
}
perm.gid = parse_gid(group);
if (group && perm.gid < 0 && debug)
warnx("Unknown group %s, not setting the group of %s", group, path);
age = strtok(NULL, "\t ");
arg = strtok(NULL, "\n");
if (arg) {
arg += strspn(arg, "\t ");
if (!arg[0] || !strcmp(arg, "-"))
arg = NULL;
}
strc = stat(path, &st);
// file and directory removal logic
if (remove_flag) {
switch (type[0]) {
case 'a':
case 'A':
case 'b':
case 'c':
case 'C':
case 'd':
break;
case 'D':
rmcontents(path);
break;
case 'e':
case 'f':
case 'F':
case 'l': /* Finit extension, like 'L' but only if target exists */
case 'L':
case 'p':
break;
case 'r':
rc = glob_do(path, erase);
if (rc && errno == ENOENT)
rc = 0;
break;
case 'R':
rc = glob_do(path, rmrf);
break;
case 'w':
break;
case 'X':
case 'x':
/* see kept(), used with --clean */
break;
case 'Z':
case 'z':
break;
default:
if (!quiet)
warnx("Unsupported tmpfiles command '%s', skipping %s", type, path);
return;
}
}
/* age-based cleanup logic */
if (clean_flag) {
time_t max_age = parse_age(age);
/* Only process if age is specified */
if (max_age >= 0) {
switch (type[0]) {
case 'd':
case 'D':
case 'e':
if (!fisdir(path))
break;
clean_age = max_age;
clean_now = time(NULL);
nftw(path, do_clean, 20, FTW_DEPTH | FTW_PHYS | FTW_MOUNT);
break;
default:
break;
}
}
}
// file & directory creation logic
if (create_flag) {
switch (type[0]) {
case 'a':
case 'A':
rc = acl_entry(path, arg, type[0] == 'A', plus);
break;
case 'b':
rc = parse_mm(arg, &major, &minor);
if (rc)
break;
if (!strc && plus) {
erase(path);
strc = -1;
}
if (strc) {
mkparent(path, 0755);
rc = blkdev(path, perm.mode ?: 0644, major, minor);
} else if (!S_ISBLK(st.st_mode)) {
break;
}
if (!rc && perm_path(path, &perm, strc, O_PATH))
warn("Failed setting mode/owner on %s", path);
break;
case 'c':
rc = parse_mm(arg, &major, &minor);
if (rc)
break;
if (!strc && plus) {
erase(path);
strc = -1;
}
if (strc) {
mkparent(path, 0755);
rc = chardev(path, perm.mode ?: 0644, major, minor);
} else if (!S_ISCHR(st.st_mode)) {
break;
}
if (!rc && perm_path(path, &perm, strc, O_PATH))
warn("Failed setting mode/owner on %s", path);
break;
case 'C':
if (!arg) {
paste(buf, sizeof(buf), "/usr/share/factory", path);
arg = buf;
}
if (fisdir(path) && !is_dir_empty(path))
break;
if (fisdir(arg) && !fisslashdir(arg)) {
size_t len = strlen(arg) + 2;
dst = malloc(len);
if (!dst)
break;
snprintf(dst, len, "%s/", arg);
arg = dst;
}
mkparent(path, 0755);
rc = rsync(arg, path, LITE_FOPT_KEEP_MTIME, NULL);
if (rc && errno == ENOENT)
rc = 0;
else if (!rc && (strc || S_ISDIR(st.st_mode)) && perm_path(path, &perm, strc, O_PATH))
warn("Failed setting mode/owner on %s", path);
break;
case 'd':
case 'D': {
mode_t omask;
mkparent(path, 0755);
omask = umask(0);
rc = makedir(path, perm.mode ?: 0755);
if (!rc && perm_path(path, &perm, strc, O_RDONLY | O_DIRECTORY))
warn("Failed setting mode/owner on %s", path);
umask(omask);
break;
}
case 'e':
if (glob(path, GLOB_NOESCAPE, NULL, &gl))
break;
for (size_t i = 0; i < gl.gl_pathc; i++) {
char *p = gl.gl_pathv[i];
/* skip non-directories */
if (perm_path(p, &perm, 0, O_RDONLY | O_DIRECTORY) && errno != ENOTDIR)
warn("Failed setting mode/owner on %s", p);
}
globfree(&gl);
break;
case 'f':
case 'F': {
int flags = O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC;
int fd;
if (plus || type[0] == 'F') {
flags |= O_TRUNC; /* create or truncate */
} else {
if (!strc) { /* create only if missing */
if (perm_path(path, &perm, 0, O_PATH))
warn("Failed setting mode/owner on %s", path);
break;
}
flags |= O_EXCL;
}
mkparent(path, 0755);
fd = open(path, flags, 0666);
if (fd < 0) {
if (errno != EEXIST)
warn("Failed creating %s", path);
break;
}
fp = fdopen(fd, "w");
if (!fp) {
close(fd);
break;
}
write_arg(fp, arg);
if (perm_set(fd, &perm, strc))
warn("Failed setting mode/owner on %s", path);
rc = fclose(fp);
break;
}
case 'l': /* Finit extension, like 'L' but only if target exists */
if (!arg) {
paste(buf, sizeof(buf), "/usr/share/factory", path);
if (stat(buf, &ast))
break;
} else if (arg[0] != '/') {
char *tmp;
tmp = dirname(strdupa(path));
paste(buf, sizeof(buf), tmp, arg);
dst = realpath(buf, NULL);
if (!dst)
break;
if (stat(dst, &ast))
break;
} else {
if (stat(arg, &ast))
break;
}
/* fallthrough */
case 'L':
if (!strc) {
if (!plus)
break;
if (fisdir(path))
rmrf(path);
else
erase(path);
}
mkparent(path, 0755);
if (!arg) {
paste(buf, sizeof(buf), "/usr/share/factory", path);
arg = buf;
}
rc = ln(arg, path);
if (rc && errno == EEXIST)
rc = 0;
break;
case 'p':
if (!strc && plus) {
erase(path);
strc = -1;
}
if (strc) {
mkparent(path, 0755);
rc = mkfifo(path, perm.mode ?: 0644);
} else if (!S_ISFIFO(st.st_mode)) {
break;
}
if (!rc && perm_path(path, &perm, strc, O_PATH))
warn("Failed setting mode/owner on %s", path);
break;
case 'r':
case 'R':
break;
case 'w':
if (!arg)
break;
if (glob(path, GLOB_NOESCAPE, NULL, &gl))
break;
for (size_t i = 0; i < gl.gl_pathc; i++) {
fp = fopen(gl.gl_pathv[i], plus ? "a" : "w");
if (fp) {
write_arg(fp, arg);
rc = fclose(fp);
}
}
globfree(&gl);
break;
case 'X':
case 'x':
/* see kept(), used with --clean */
break;
case 'Z':
opts = "-R";
/* fallthrough */
case 'z':
if (glob(path, GLOB_NOESCAPE, NULL, &gl))
break;
for (size_t i = 0; i < gl.gl_pathc; i++) {
char *p = gl.gl_pathv[i];
if (type[0] == 'Z') {
/* Nothing to set, no need to walk the tree */
if (perm.mode || perm.uid != -1 || perm.gid != -1) {
perm_tree = &perm;
nftw(p, perm_cb, 20, FTW_PHYS);
}
} else if (perm_path(p, &perm, 0, O_PATH)) {
warn("Failed setting mode/owner on %s", p);
}
if (whichp("restorecon"))
systemf("restorecon %s %s", opts, p);
}
globfree(&gl);
break;
default:
if (!quiet)
warnx("Unsupported tmpfiles command '%s', skipping %s", type, path);
return;
}
}
if (dst)
free(dst);
if (rc)
warn("Failed %s operation on path %s", type, path);
}
static void process_file(const char *fn)
{
FILE *fp;
fp = fopen(fn, "r");
if (!fp) {
warn("Failed to open %s", fn);
return;
}
while (!feof(fp)) {
char *line;
line = fparseln(fp, NULL, NULL, NULL, FPARSELN_UNESCCOMM);
if (!line)
continue;
tmpfiles(line);
free(line);
}
fclose(fp);
}
static void process(int num, char *file[])
{
/* If config files specified on command line, process only those */
if (num) {
for (int i = 0; i < num; i++)
process_file(file[i]);
return;
}
/*
* No config files specified, process standard tmpfiles.d directories.
*
* Only the three last tmpfiles.d/ directories are defined in
* tmpfiles.d(5) as system search paths. Finit adds two more
* before that to have Finit specific ones sorted first, and
* a configure prefix specific one after that for user needs.
*/
/* in priority order */
char *dir[] = {
FINIT_TMPFILES "/*.conf",
TMPFILES_PATH_ "/*.conf",
"/usr/lib/tmpfiles.d/*.conf",
"/run/tmpfiles.d/*.conf",
"/etc/tmpfiles.d/*.conf", /* local admin overrides */
};
int flags = GLOB_NOESCAPE;
glob_t gl;
size_t i;
for (i = 0; i < NELEMS(dir); i++) {
glob(dir[i], flags, NULL, &gl);
flags |= GLOB_APPEND;
}
for (i = 0; i < gl.gl_pathc; i++) {
char *fn = gl.gl_pathv[i];
size_t j;
/* check for overrides */
for (j = i + 1; j < gl.gl_pathc; j++) {
if (strcmp(basenm(fn), basenm(gl.gl_pathv[j])))
continue;
fn = NULL;
break;
}
if (!fn)
continue; /* skip, override exists */
process_file(fn);
}
globfree(&gl);
}
static int usage(int rc)
{
fprintf(stderr,
"Usage: tmpfiles [OPTIONS] [CONFIGFILE...]\n"
"\n"
"Options:\n"
" --boot Also run boot-only entries, marked with !\n"
" -C, --clean Clean files and directories based on age\n"
" -c, --create Create files and directories\n"
" -d, --debug Show developer debug messages\n"
" -E Exclude /dev, /proc, /run, and /sys\n"
" --exclude-prefix=PFX Ignore rules for paths starting with PFX\n"
" -r, --remove Remove files and directories marked for removal\n"
" -h, --help This help text\n"
"\n"
"If no CONFIGFILE is specified, all *.conf files in the standard\n"
"tmpfiles.d directories are processed.\n"
"\n");
return rc;
}
enum {
OPT_EXCLUDE_PREFIX = 256,
OPT_BOOT,
};
int main(int argc, char *argv[])
{
struct option long_options[] = {
{ "boot", 0, NULL, OPT_BOOT },
{ "clean", 0, NULL, 'C' },
{ "create", 0, NULL, 'c' },
{ "debug", 0, NULL, 'd' },
{ "exclude-prefix", 1, NULL, OPT_EXCLUDE_PREFIX },
{ "remove", 0, NULL, 'r' },
{ "help", 0, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
int c;
while ((c = getopt_long(argc, argv, "CcdrEh?", long_options, NULL)) != EOF) {
switch(c) {
case 'C':
clean_flag = 1;
break;
case 'c':
create_flag = 1;
break;
case 'd':
debug = 1;
break;
case 'E':
add_exclude_prefix("/dev");
add_exclude_prefix("/proc");
add_exclude_prefix("/run");
add_exclude_prefix("/sys");
break;
case OPT_BOOT:
boot_flag = 1;
break;
case OPT_EXCLUDE_PREFIX:
add_exclude_prefix(optarg);
break;
case 'r':
remove_flag = 1;
break;
case 'h':
case '?':
return usage(0);
default:
return usage(1);
}
}
if (create_flag + clean_flag + remove_flag == 0) {
fprintf(stderr, "You need to specify at least one of --clean, --create, or --remove.\n");
return 1;
}
/* Cleaning needs every x and X entry, also those in files not yet read */
if (clean_flag) {
collect = quiet = 1;
process(argc - optind, &argv[optind]);
collect = quiet = 0;
}
/* Remove and clean first, or an r entry takes what an f entry above it made */
if (create_flag && (clean_flag || remove_flag)) {
create_flag = 0;
quiet = 1;
process(argc - optind, &argv[optind]);
create_flag = 1;
quiet = 0;
clean_flag = remove_flag = 0;
}
process(argc - optind, &argv[optind]);
return 0;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/