/* Limited tmpfiles.d implementation * * Copyright (c) 2025 Joachim Wiberg * * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _LIBITE_LITE # include #else # include #endif #include "helpers.h" #include "log.h" #include "util.h" int debug; int create_flag = 0; int clean_flag = 0; int remove_flag = 0; int boot_flag = 0; int dry_run = 0; int cat_config = 0; #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 const char *prefixes[MAX_EXCLUDES]; static int num_prefixes; static void add_prefix(const char *prefix) { if (prefix[0] && num_prefixes < MAX_EXCLUDES) prefixes[num_prefixes++] = prefix; } /* Whole path components, /dev is not a prefix of /devices */ static int below(const char *path, const char *prefix) { size_t len = strlen(prefix); while (len > 1 && prefix[len - 1] == '/') len--; return !strncmp(path, prefix, len) && (len == 1 || !path[len] || path[len] == '/'); } /* Not below a --prefix, when there is one, or below an --exclude-prefix */ static int excluded(const char *path) { int i; for (i = 0; i < num_prefixes; i++) { if (below(path, prefixes[i])) break; } if (num_prefixes && i == num_prefixes) return 1; for (i = 0; i < num_excludes; i++) { if (below(path, 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 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); } static int copy_errno; static void copy_fail(void) { if (!copy_errno) copy_errno = errno; } /* Owner before mode, as in perm_set(). Not root when run by hand */ static void copy_perm(int fd, const struct stat *st) { if ((fchownat(fd, "", st->st_uid, st->st_gid, AT_EMPTY_PATH) && errno != EPERM) || fd_chmod(fd, st->st_mode & 07777)) copy_fail(); } static void copy_file(int sdir, const char *sname, int ddir, const char *dname, const struct stat *st) { struct timespec tv[2] = { st->st_atim, st->st_mtim }; char buf[BUFSIZ]; ssize_t len = -1; int in, out; in = openat(sdir, sname, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (in < 0) { copy_fail(); return; } out = openat(ddir, dname, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600); if (out < 0) { if (errno != EEXIST) copy_fail(); close(in); return; } while ((len = read(in, buf, sizeof(buf))) > 0) { for (ssize_t off = 0, num; off < len; off += num) { num = write(out, &buf[off], len - off); if (num < 0) { len = -1; goto done; } } } done: if (len < 0) copy_fail(); else copy_perm(out, st); futimens(out, tv); close(in); close(out); } /* * Copy @sname in the directory @sdir to @dname in @ddir, with all that * is below it. What exists at the destination is left as it is, and * only a real directory there is gone into, never a link to one. */ static void copy_node(int sdir, const char *sname, int ddir, const char *dname) { char target[PATH_MAX]; int sfd, dfd, created; struct dirent *d; struct stat st; ssize_t len; DIR *dir; if (fstatat(sdir, sname, &st, AT_SYMLINK_NOFOLLOW)) { copy_fail(); return; } switch (st.st_mode & S_IFMT) { case S_IFDIR: break; case S_IFREG: copy_file(sdir, sname, ddir, dname, &st); return; case S_IFLNK: len = readlinkat(sdir, sname, target, sizeof(target) - 1); if (len < 0) { copy_fail(); return; } target[len] = 0; if (symlinkat(target, ddir, dname)) { if (errno != EEXIST) copy_fail(); return; } if (fchownat(ddir, dname, st.st_uid, st.st_gid, AT_SYMLINK_NOFOLLOW) && errno != EPERM) copy_fail(); return; default: if (mknodat(ddir, dname, (st.st_mode & S_IFMT) | 0600, st.st_rdev)) { if (errno != EEXIST) copy_fail(); return; } dfd = openat(ddir, dname, O_PATH | O_NOFOLLOW | O_CLOEXEC); if (dfd < 0) { copy_fail(); return; } copy_perm(dfd, &st); close(dfd); return; } created = !mkdirat(ddir, dname, 0700); if (!created && errno != EEXIST) { copy_fail(); return; } dfd = openat(ddir, dname, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (dfd < 0) { if (created) copy_fail(); return; } sfd = openat(sdir, sname, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); dir = sfd < 0 ? NULL : fdopendir(sfd); if (!dir) { copy_fail(); if (sfd >= 0) close(sfd); close(dfd); return; } while ((d = readdir(dir))) { if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) continue; copy_node(sfd, d->d_name, dfd, d->d_name); } closedir(dir); if (created) copy_perm(dfd, &st); close(dfd); } /* * Copy @src, of which @st tells the kind, to @dst. Links are not * followed. A file is not copied when @dst exists. A directory is * when @dst is missing or an empty directory, with @merge also when * @dst has something in it, to add what is missing. */ static int copy_tree(const char *src, const struct stat *st, char *dst, int merge) { struct stat dt; if (!lstat(dst, &dt)) { if (!S_ISDIR(st->st_mode) || !S_ISDIR(dt.st_mode)) return 0; if (!merge && !is_dir_empty(dst)) return 0; } mkparent(dst, 0755); copy_errno = 0; copy_node(AT_FDCWD, src, AT_FDCWD, dst); if (copy_errno) { errno = copy_errno; return -1; } return 0; } 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 (isxdigit((unsigned char)c)) 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]; } /* Decode Base64 in place, returns the length or -1 when @str is not Base64 */ static ssize_t b64_decode(char *str) { static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; unsigned int acc = 0; char *out = str; int bits = 0; for (char *in = str; *in; in++) { const char *ptr; if (isspace((unsigned char)*in)) continue; if (*in == '=') { if (in[strspn(in, "=\t ")]) return -1; break; } ptr = strchr(tbl, *in); if (!ptr) return -1; acc = acc << 6 | (ptr - tbl); bits += 6; if (bits >= 8) { bits -= 8; *out++ = acc >> bits; } } return out - str; } /* Write @arg with its escapes resolved, or the @len bytes of it when @len is not -1 */ static void write_arg(FILE *fp, char *arg, ssize_t len) { char *p; if (!arg) return; if (len >= 0) { fwrite(arg, sizeof(char), len, fp); return; } while (*arg && (p = strchr(arg, '\\'))) { fwrite(arg, sizeof(char), p - arg, fp); p++; if (!*p) { /* A backslash that ends the argument */ arg = p - 1; break; } 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); } /* Timestamps of a file to go by when cleaning, those of a directory are shifted up */ #define AGE_ATIME 0x01 #define AGE_BTIME 0x02 #define AGE_CTIME 0x04 #define AGE_MTIME 0x08 #define AGE_DIR 4 struct age { time_t sec; int below; /* ~, keep what is right in the directory */ unsigned by; }; /* * Parse the age of an entry, e.g. "10d", "1h30m", "~2w", or "aAmM:1d". * A number without a unit is in seconds. Returns -1 when there is no * age, "-" or NULL, or when it cannot be read. */ static int parse_age(const char *str, struct age *age) { const struct { const char *unit; unsigned long long usec; } units[] = { { "us", 1ULL }, { "ms", 1000ULL }, { "s", 1000000ULL }, { "", 1000000ULL }, { "m", 60 * 1000000ULL }, { "min", 60 * 1000000ULL }, { "h", 3600 * 1000000ULL }, { "d", 86400 * 1000000ULL }, { "w", 7 * 86400 * 1000000ULL }, }; /* The change time of a directory is set by the cleaning itself */ const unsigned file = AGE_ATIME | AGE_BTIME | AGE_CTIME | AGE_MTIME; const unsigned dir = (AGE_ATIME | AGE_BTIME | AGE_MTIME) << AGE_DIR; unsigned long long usec = 0; const char *ptr; if (!str || !strcmp(str, "-")) return -1; age->by = 0; age->below = 0; ptr = strchr(str, ':'); if (ptr) { const char *flags = "abcmABCM"; if (ptr == str) return -1; for (; str < ptr; str++) { const char *flag = strchr(flags, *str); if (!flag) return -1; age->by |= 1 << (flag - flags); } str++; } /* Never none at all, that would remove everything */ if (!(age->by & file)) age->by |= file; if (!(age->by & ~file)) age->by |= dir; if (*str == '~') { age->below = 1; str++; } do { unsigned long long val; size_t i, len; char *end; if (!isdigit((unsigned char)*str)) return -1; errno = 0; val = strtoull(str, &end, 10); if (errno) return -1; len = strcspn(end, "0123456789"); for (i = 0; i < NELEMS(units); i++) { if (strlen(units[i].unit) == len && !strncmp(end, units[i].unit, len)) break; } if (i == NELEMS(units) || val > (ULLONG_MAX - usec) / units[i].usec) return -1; usec += val * units[i].usec; str = end + len; } while (*str); /* Capped, time_t may be 32 bits. Older than the epoch is never cleaned */ usec = usec / 1000000 + !!(usec % 1000000); age->sec = usec > INT32_MAX ? INT32_MAX : usec; return 0; } /** * 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 */ /* * 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 const char *keep_own; /* Entry that cleans what it keeps, by its own age */ 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 (keep_own && !strcmp(k->pattern, keep_own)) continue; 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 struct age clean_age; static time_t clean_now; /* The file system may not have a birth time, then it is not looked at */ static time_t btime(const char *path) { #ifdef HAVE_STATX struct statx stx; if (statx(AT_FDCWD, path, AT_SYMLINK_NOFOLLOW, STATX_BTIME, &stx) || !(stx.stx_mask & STATX_BTIME)) return 0; return stx.stx_btime.tv_sec; #else (void)path; return 0; #endif } static int do_clean(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftw) { unsigned by; /* Skip the root directory itself */ if (ftw->level == 0) return 0; if (clean_age.below && ftw->level == 1) return 0; /* Kept as long as one of the chosen timestamps is newer than the age */ by = clean_age.by; if (tflag == FTW_D || tflag == FTW_DP || tflag == FTW_DNR) by >>= AGE_DIR; if (clean_age.sec) { time_t then = clean_now - clean_age.sec; if ((by & AGE_MTIME) && sb->st_mtime > then) return 0; if ((by & AGE_ATIME) && sb->st_atime > then) return 0; if ((by & AGE_CTIME) && sb->st_ctime > then) return 0; if ((by & AGE_BTIME) && btime(fpath) > then) return 0; } if (kept(fpath)) return 0; if (remove(fpath) && errno != ENOENT && errno != EBUSY && errno != ENOTEMPTY) warn("Failed cleaning %s", fpath); return 0; } static int clean_dir(const char *path) { if (fisdir(path)) nftw(path, do_clean, 20, FTW_DEPTH | FTW_PHYS | FTW_MOUNT); 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_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; int num; }; struct acl_xattr { struct posix_acl_xattr_header hdr; struct posix_acl_xattr_entry e[]; }; 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) { e = reallocarray(acl->e, acl->num + 1, sizeof(*e)); if (!e) return -1; acl->e = e; 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; int rc = -1; len = getxattr(path, name, NULL, 0); if (len < 0) return errno == ENODATA ? 0 : -1; buf = malloc(len + sizeof(*buf)); if (!buf) return -1; len = getxattr(path, name, buf, len); if (len < 0) { if (errno == ENODATA) rc = 0; goto done; } if (len < (ssize_t)sizeof(buf->hdr) || le32toh(buf->hdr.a_version) != POSIX_ACL_XATTR_VERSION) { errno = EINVAL; goto done; } len = (len - sizeof(buf->hdr)) / sizeof(buf->e[0]); for (ssize_t i = 0; i < len; i++) { if (acl_set(acl, le16toh(buf->e[i].e_tag), le32toh(buf->e[i].e_id), le16toh(buf->e[i].e_perm))) goto done; } rc = 0; done: free(buf); return rc; } 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) { size_t len = sizeof(struct acl_xattr) + acl->num * sizeof(struct posix_acl_xattr_entry); struct acl_xattr *buf; int rc; buf = malloc(len); if (!buf) return -1; 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); } rc = setxattr(path, name, buf, len, 0); free(buf); return rc; } /* * 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; int rc = -1; if (acl_read(path, name, &old)) goto done; for (int i = 0; modify && i < old.num; i++) { if (acl_set(&acl, old.e[i].tag, old.e[i].id, old.e[i].perm)) goto done; } 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)) goto done; } 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])) goto done; } 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)) goto done; rc = acl_write(path, name, &acl); done: free(acl.e); free(old.e); return rc; } /* 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; rc = -1; goto done; } if (glob(pattern, GLOB_NOESCAPE, NULL, &gl)) goto done; 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); done: free(access.e); free(def.e); return rc; } /* * For the entries that take a glob and have a recursive form. @fn * and @what are global, nftw() cannot pass user data. */ static int (*tree_fn)(const char *path); static const char *tree_what; static int tree_cb(const char *path, const struct stat *st, int tflag, struct FTW *ftw) { (void)tflag; (void)ftw; /* None of this is for a link, and what it points to is not ours to change */ if (!S_ISLNK(st->st_mode) && tree_fn(path)) warn("Failed setting %s on %s", tree_what, path); return 0; } static int tree_do(const char *pattern, int (*fn)(const char *), const char *what, int recursive) { glob_t gl; if (glob(pattern, GLOB_NOESCAPE, NULL, &gl)) return 0; tree_fn = fn; tree_what = what; for (size_t i = 0; i < gl.gl_pathc; i++) { struct stat st; if (recursive) nftw(gl.gl_pathv[i], tree_cb, 20, FTW_PHYS); else if (!lstat(gl.gl_pathv[i], &st)) tree_cb(gl.gl_pathv[i], &st, 0, NULL); } globfree(&gl); return 0; } /* Extended attributes of a t or T entry, see xattr_parse() */ #define XATTR_MAX 16 static struct { char *name; char *value; } xattrs[XATTR_MAX]; static int num_xattrs; /* * NAME=VALUE pairs with space between, cut up where they are in @arg. * A value may be in quotes, and a backslash takes the next character * as it is. */ static int xattr_parse(char *arg) { num_xattrs = 0; while (arg && *arg) { char quote = 0, *out; arg += strspn(arg, "\t "); if (!*arg) break; if (num_xattrs == XATTR_MAX) goto inval; xattrs[num_xattrs].name = arg; arg = strchr(arg, '='); if (!arg || arg == xattrs[num_xattrs].name) goto inval; *arg++ = 0; if (strpbrk(xattrs[num_xattrs].name, "\t ")) goto inval; xattrs[num_xattrs++].value = out = arg; for (; *arg; arg++) { if (*arg == '\\' && arg[1]) *out++ = *++arg; else if (quote && *arg == quote) quote = 0; else if (!quote && (*arg == '"' || *arg == '\'')) quote = *arg; else if (!quote && (*arg == ' ' || *arg == '\t')) break; else *out++ = *arg; } if (*arg) arg++; *out = 0; if (quote) goto inval; } if (num_xattrs) return 0; inval: errno = EINVAL; return -1; } static int xattr_path(const char *path) { for (int i = 0; i < num_xattrs; i++) { if (lsetxattr(path, xattrs[i].name, xattrs[i].value, strlen(xattrs[i].value), 0)) return -1; } return 0; } /* File attributes of an h or H entry, as in chattr(1) */ static const struct { char c; unsigned flag; } attrs[] = { { 'A', FS_NOATIME_FL }, { 'a', FS_APPEND_FL }, { 'c', FS_COMPR_FL }, { 'C', FS_NOCOW_FL }, { 'd', FS_NODUMP_FL }, { 'D', FS_DIRSYNC_FL }, { 'e', FS_EXTENT_FL }, { 'i', FS_IMMUTABLE_FL }, { 'j', FS_JOURNAL_DATA_FL }, { 'P', FS_PROJINHERIT_FL }, { 's', FS_SECRM_FL }, { 'S', FS_SYNC_FL }, { 't', FS_NOTAIL_FL }, { 'T', FS_TOPDIR_FL }, { 'u', FS_UNRM_FL }, }; static unsigned attr_flags; static char attr_op; /* [+-=]LETTERS, to add, which is the default, remove, or set just these */ static int attr_parse(const char *arg) { attr_flags = 0; attr_op = '+'; if (arg && strchr("+-=", *arg)) attr_op = *arg++; for (; arg && *arg; arg++) { size_t i; for (i = 0; i < NELEMS(attrs); i++) { if (attrs[i].c == *arg) break; } if (i == NELEMS(attrs)) break; attr_flags |= attrs[i].flag; } if (arg && !*arg && (attr_flags || attr_op == '=')) return 0; errno = EINVAL; return -1; } /* * Only files and directories have them, anything else is left alone, * and never opened: that starts a watchdog and rewinds a tape. */ static int attr_path(const char *path) { unsigned all = 0, flags, old; struct stat st; int fd, rc; if (lstat(path, &st) || (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))) return 0; fd = open(path, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) return -1; /* = leaves what is not in the table, and extents, which cannot be taken away */ for (size_t i = 0; i < NELEMS(attrs); i++) all |= attrs[i].flag; all &= ~FS_EXTENT_FL; rc = ioctl(fd, FS_IOC_GETFLAGS, &old); if (!rc) { if (attr_op == '+') flags = old | attr_flags; else if (attr_op == '-') flags = old & ~attr_flags; else flags = (old & ~all) | attr_flags; if (flags != old) rc = ioctl(fd, FS_IOC_SETFLAGS, &flags); } close(fd); /* Not every file system has file attributes */ if (rc && (errno == ENOTTY || errno == EOPNOTSUPP || errno == ENOSYS)) rc = 0; return rc; } /* First line of @file, without @strip characters, empty when it cannot be read */ static char *specifier_file(const char *file, const char *strip, char *buf, size_t len) { size_t i = 0; FILE *fp; int c; fp = fopen(file, "r"); if (fp) { while ((c = fgetc(fp)) != EOF && c != '\n' && i < len - 1) { if (!strchr(strip, c)) buf[i++] = c; } fclose(fp); } buf[i] = 0; return buf; } /* Value of @key in os-release, empty when it is not there, as in tmpfiles.d(5) */ static char *specifier_os(const char *key, char *buf, size_t len) { char line[256]; FILE *fp; buf[0] = 0; fp = fopen("/etc/os-release", "r"); if (!fp) fp = fopen("/usr/lib/os-release", "r"); if (!fp) return buf; while (fgets(line, sizeof(line), fp)) { char *val; line[strcspn(line, "\n")] = 0; val = fgetval(line, key, "="); if (val) { strlcpy(buf, val, len); free(val); break; } } fclose(fp); return buf; } /* The name tmpfiles.d(5) has for the architecture, NULL when not known */ static const char *specifier_arch(const char *machine) { /* By prefix, uname has armv7l, armv5tejl, and the like. First match wins */ static const char *names[][2] = { { "x86_64", "x86-64" }, { "i386", "x86" }, { "i486", "x86" }, { "i586", "x86" }, { "i686", "x86" }, { "aarch64_be", "arm64-be" }, { "aarch64", "arm64" }, { "arm", "arm" }, { "riscv64", "riscv64" }, { "riscv32", "riscv32" }, { "ppc64le", "ppc64-le" }, { "ppc64", "ppc64" }, { "ppcle", "ppc-le" }, { "ppc", "ppc" }, { "mips64", "mips64" }, { "mips", "mips" }, { "s390x", "s390x" }, { "s390", "s390" }, { "sparc64", "sparc64" }, { "sparc", "sparc" }, { "loongarch64", "loongarch64" }, { "alpha", "alpha" }, { "ia64", "ia64" }, { "m68k", "m68k" }, }; static char name[16]; for (size_t i = 0; i < NELEMS(names); i++) { size_t len = strlen(names[i][0]); if (strncmp(machine, names[i][0], len)) continue; /* uname does not tell: armv7b is big endian, mips is either */ strlcpy(name, names[i][1], sizeof(name)); if (!strcmp(name, "arm") && machine[strlen(machine) - 1] == 'b') strlcat(name, "-be", sizeof(name)); #if __BYTE_ORDER == __LITTLE_ENDIAN if (!strncmp(name, "mips", 4)) strlcat(name, "-le", sizeof(name)); #endif return name; } return NULL; } /* As in systemd, the first of these that names a directory */ static const char *specifier_tmp(const char *fallback) { static const char *env[] = { "TMPDIR", "TEMP", "TMP" }; for (size_t i = 0; i < NELEMS(env); i++) { const char *dir = getenv(env[i]); if (dir && dir[0] == '/' && fisdir(dir)) return dir; } return fallback; } /* * The % specifiers of tmpfiles.d(5). tmpfiles runs as root, so the * user ones are fixed. Returns NULL for one that is unknown or has * no value. */ static const char *specifier(char c, char *buf, size_t len) { struct utsname uts; switch (c) { case '%': return "%"; case 'C': return "/var/cache"; case 'g': return "root"; case 'G': return "0"; case 'h': return "/root"; case 'L': return "/var/log"; case 'S': return "/var/lib"; case 't': return "/run"; case 'T': return specifier_tmp("/tmp"); case 'u': return "root"; case 'U': return "0"; case 'V': return specifier_tmp("/var/tmp"); case 'b': specifier_file("/proc/sys/kernel/random/boot_id", "-", buf, len); break; case 'm': specifier_file("/etc/machine-id", "", buf, len); break; case 'H': case 'l': if (gethostname(buf, len)) return NULL; buf[len - 1] = 0; if (c == 'l') buf[strcspn(buf, ".")] = 0; break; case 'v': if (uname(&uts)) return NULL; strlcpy(buf, uts.release, len); break; case 'a': if (uname(&uts)) return NULL; return specifier_arch(uts.machine); case 'A': return specifier_os("IMAGE_VERSION", buf, len); case 'B': return specifier_os("BUILD_ID", buf, len); case 'M': return specifier_os("IMAGE_ID", buf, len); case 'o': return specifier_os("ID", buf, len); case 'w': return specifier_os("VERSION_ID", buf, len); case 'W': return specifier_os("VARIANT_ID", buf, len); default: return NULL; } return buf[0] ? buf : NULL; } /* Expand the specifiers in @str to @buf, NULL when one fails or @buf is too small */ static char *expand(const char *str, char *buf, size_t len) { char val[256]; size_t n = 0; for (; *str; str++) { const char *ptr = str; size_t num = 1; if (*str == '%') { /* Also for a % that ends the string, do not step past it */ ptr = specifier(*++str, val, sizeof(val)); if (!ptr) return NULL; num = strlen(ptr); } if (n + num >= len) return NULL; memcpy(&buf[n], ptr, num); n += num; } buf[n] = 0; return buf; } /* * For the = modifier: remove @path when it is of another kind than * @fmt, and what is in place of a directory above it. A link to a * directory is fine there, when it is root's. */ static void replace_kind(const char *path, mode_t fmt) { char *copy = strdupa(path); struct stat st; /* Nothing is removed by a path that may lead somewhere else */ if (strstr(path, "/./") || strstr(path, "/../")) return; for (size_t len = strlen(copy); len > 1 && copy[len - 1] == '/'; len--) copy[len - 1] = 0; if (!copy[1] || fnmatch("*/.", copy, 0) == 0 || fnmatch("*/..", copy, 0) == 0) return; for (char *ptr = strchr(©[1], '/'); ptr; ptr = strchr(&ptr[1], '/')) { *ptr = 0; if (!lstat(copy, &st) && !S_ISDIR(st.st_mode)) { if (!fisdir(copy)) erase(copy); else if (st.st_uid != 0) return; /* Link to a directory, and not root's */ } *ptr = '/'; } if (lstat(copy, &st) || (st.st_mode & S_IFMT) == fmt) return; if (S_ISDIR(st.st_mode)) rmrf(copy); else erase(copy); } /* * Next field of @line, NULL when there are no more, a quote is left * open, or the field is empty or has a NUL. Quotes and backslash * escapes are resolved in place, so a path can have a space. */ static char *field(char **line) { static const char from[] = "abfnrtvs", to[] = "\a\b\f\n\r\t\v "; char *in = *line, *out, *start; char quote = 0; int nul = 0; in += strspn(in, "\t "); if (!*in) return NULL; for (start = out = in; *in; in++) { const char *ptr; if (quote) { if (*in == quote) { quote = 0; continue; } } else if (*in == '"' || *in == '\'') { quote = *in; continue; } else if (*in == ' ' || *in == '\t') { in++; break; } if (*in != '\\' || !in[1]) { *out++ = *in; continue; } in++; if (*in == 'x' && isxdigit((unsigned char)in[1]) && isxdigit((unsigned char)in[2])) { char hex[3] = { in[1], in[2], 0 }; *out = strtoul(hex, NULL, 16); nul |= !*out++; in += 2; } else if (*in >= '0' && *in <= '3' && in[1] >= '0' && in[1] <= '7' && in[2] >= '0' && in[2] <= '7') { *out = (in[0] - '0') << 6 | (in[1] - '0') << 3 | (in[2] - '0'); nul |= !*out++; in += 2; } else if ((ptr = strchr(from, *in))) { *out++ = to[ptr - from]; } else { *out++ = *in; } } *out = 0; *line = in; if (quote || nul || out == start) { warnx("Missing end quote, or an empty field, skipping %s", start); return NULL; } return start; } /* One line of a file, read by parse() and run by tmpfiles() */ struct entry { char *type; /* As written, the modifiers after the letter */ char *path; char *key; /* The path with no // and no / at the end */ struct perm perm; char *age, *arg; ssize_t arglen; /* Of an argument that was in Base64, else -1 */ int plus, kind; unsigned sum; /* Of the line, to tell if two are the same */ int done; }; static struct entry *entries; static size_t num_entries; static const char *conf; /* File being read */ static char *path_key(const char *path) { char *key, *out; key = out = strdup(path); if (!key) return NULL; for (; *path; path++) { if (path[0] != '/' || path[1] != '/') *out++ = *path; } while (out > &key[1] && out[-1] == '/') out--; *out = 0; return key; } /* Types that take a glob. They change what the others make, and are run after them */ static int globs(const struct entry *e) { return !!strchr("aAehHrRtTwxXzZ", e->type[0]); } static unsigned line_sum(const char *str, unsigned sum) { for (; *str; str++) { if ((*str == ' ' || *str == '\t') && (str[1] == ' ' || str[1] == '\t' || !str[1])) continue; sum = sum * 33 + (*str == '\t' ? ' ' : *str); } return sum; } /* * As in tmpfiles.d(5), the first entry for a path is the one that * counts. Among those that make the path, and among those that take * a glob and are not only there to set something on it. A w+ entry * always counts, it adds to the file. */ static int duplicate(const struct entry *e) { const char *types = globs(e) ? "erRwxX" : "bcCdDfFlLp"; if (!strchr(types, e->type[0]) || (e->type[0] == 'w' && e->plus)) return 0; for (size_t i = 0; i < num_entries; i++) { const struct entry *o = &entries[i]; if (!strchr(types, o->type[0]) || strcmp(o->key, e->key)) continue; if (o->sum != e->sum && (debug || dry_run)) warnx("%s: %s already has an entry, skipping this %s one", conf, e->path, e->type); return 1; } return 0; } /* * 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 * * Returns -1 for a line that is not kept as an entry. The entry of one * that is points into @line. */ static int parse(char *line) { char pathbuf[PATH_MAX], argbuf[1024]; struct entry e = { .arglen = -1 }; struct entry *tmp; char *token, *user, *group, *end; char *xpath = NULL, *xarg = NULL; int boot = 0, b64 = 0; e.type = field(&line); if (!e.type || e.type[0] == '#') return -1; for (char *mod = &e.type[1]; *mod; mod++) { if (*mod == '+') e.plus = 1; else if (*mod == '!') boot = 1; else if (*mod == '~') b64 = 1; else if (*mod == '=') e.kind = 1; else if (*mod == '?' && e.type[0] == 'L') e.type[0] = 'l'; /* What Finit has had as l */ else if (*mod == '^') return -1; /* Argument is a credential, there are none */ } if (boot && !boot_flag) return -1; /* No btrfs subvolumes, a plain directory as tmpfiles.d(5) has for other file systems */ if (strchr("vqQ", e.type[0])) e.type[0] = 'd'; e.path = field(&line); if (!e.path) return -1; if (!strchr("aAbcCdDefFhHlLprRtTwxXzZ", e.type[0])) { warnx("Unsupported tmpfiles command '%s', skipping %s", e.type, e.path); return -1; } if (strchr(e.path, '%')) { char *ptr = expand(e.path, pathbuf, sizeof(pathbuf)); if (!ptr) { warnx("Unsupported specifier or too long, skipping %s", e.path); return -1; } e.path = pathbuf; } if (e.path[0] != '/') { warnx("Path is not absolute, skipping %s", e.path); return -1; } if (excluded(e.path)) return -1; e.sum = line_sum(line, line_sum(e.type, 0)); token = field(&line); if (token) { for (; *token == '~' || *token == ':'; token++) { if (*token == '~') e.perm.mask = 1; else e.perm.new_mode = 1; } errno = 0; e.perm.mode = strtoul(token, &end, 8); if (errno || end == token) e.perm.mode = 0; } user = field(&line); if (user && user[0] == ':') { e.perm.new_uid = 1; user++; } if (user && !strcmp(user, "-")) user = NULL; group = field(&line); if (group && group[0] == ':') { e.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 */ e.perm.uid = parse_uid(user); if (user && e.perm.uid < 0) { if (debug) warnx("Unknown user %s, skipping %s", user, e.path); return -1; } e.perm.gid = parse_gid(group); if (group && e.perm.gid < 0 && debug) warnx("Unknown group %s, not setting the group of %s", group, e.path); e.age = field(&line); e.arg = line + strspn(line, "\t "); if (!e.arg[0] || !strcmp(e.arg, "-")) e.arg = NULL; if (b64) { if (e.arg && strchr("fFw", e.type[0])) e.arglen = b64_decode(e.arg); if (e.arg && e.arglen < 0) { warnx("Argument is not Base64, or not one to decode, skipping %s", e.path); return -1; } } else if (e.arg && strchr(e.arg, '%') && strchr("CfFlLtTw", e.type[0])) { e.arg = expand(e.arg, argbuf, sizeof(argbuf)); if (!e.arg) { warnx("Unsupported specifier in argument or too long, skipping %s", e.path); return -1; } } if (e.path == pathbuf) e.path = xpath = strdup(pathbuf); if (e.arg == argbuf && !(e.arg = xarg = strdup(argbuf))) e.path = NULL; e.key = e.path ? path_key(e.path) : NULL; tmp = reallocarray(entries, num_entries + 1, sizeof(e)); if (!e.key || !tmp) err(1, "Failed reading entry"); entries = tmp; if (duplicate(&e)) { free(e.key); if (e.path == xpath) free(xpath); if (e.arg == xarg) free(xarg); return -1; } entries[num_entries++] = e; /* Cleaning needs every x and X entry before the first one is run */ if (clean_flag && (e.type[0] == 'x' || e.type[0] == 'X')) keep_add(e.path, e.type[0] == 'X'); return 0; } static void tmpfiles(struct entry *e) { char *type = e->type, *path = e->path, *age = e->age, *arg = e->arg; char *dst = NULL, *opts = ""; struct perm perm = e->perm; ssize_t arglen = e->arglen; mode_t kind = e->kind; int plus = e->plus; struct stat st, ast; int major, minor; int strc, rc = 0; FILE *fp = NULL; char buf[1024]; glob_t gl; if (dry_run) { if (remove_flag && strchr("DrR", type[0])) printf("remove %s %s\n", type, path); if (clean_flag && strchr("CdDexX", type[0]) && !parse_age(age, &clean_age)) printf("clean %s %s, older than %s\n", type, path, age); if (create_flag && !strchr("rRxX", type[0])) printf("create %s %s%s%s\n", type, path, arg && arglen < 0 ? " " : "", arg && arglen < 0 ? arg : ""); return; } if (kind && create_flag) { switch (type[0]) { case 'b': kind = S_IFBLK; break; case 'c': kind = S_IFCHR; break; case 'd': case 'D': kind = S_IFDIR; break; case 'f': case 'F': kind = S_IFREG; break; case 'L': kind = S_IFLNK; break; case 'p': kind = S_IFIFO; break; default: kind = 0; break; } if (kind) replace_kind(path, kind); } 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': case 'h': case 'H': case 't': case 'T': 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; } } /* age-based cleanup logic */ if (clean_flag && strchr("CdDexX", type[0]) && !parse_age(age, &clean_age)) { clean_now = time(NULL); /* Only e, x, and X take a glob, and nothing is older than the epoch */ if (clean_age.sec > clean_now) { ; } else if (type[0] == 'x' || type[0] == 'X') { /* As keep_add() has it */ for (size_t len = strlen(path); len > 1 && path[len - 1] == '/'; len--) path[len - 1] = 0; keep_own = path; glob_do(path, clean_dir); keep_own = NULL; } else if (type[0] == 'e') { glob_do(path, clean_dir); } else { clean_dir(path); } } // 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 (lstat(arg, &ast)) break; rc = copy_tree(arg, &ast, path, plus); if (!rc && !lstat(path, &st) && !S_ISLNK(st.st_mode) && !((st.st_mode ^ ast.st_mode) & S_IFMT) && 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); /* A link to a directory is not followed, and nothing to warn about */ if (!rc && perm_path(path, &perm, strc, O_RDONLY | O_DIRECTORY) && !(errno == ENOTDIR && !lstat(path, &ast) && S_ISLNK(ast.st_mode))) 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, arglen); if (strc && !perm.mode) perm.mode = 0644; if (perm_set(fd, &perm, strc)) warn("Failed setting mode/owner on %s", path); rc = fclose(fp); break; } case 'h': case 'H': rc = attr_parse(arg); if (!rc) rc = tree_do(path, attr_path, "file attributes", type[0] == 'H'); break; case 't': case 'T': rc = xattr_parse(arg); if (!rc) rc = tree_do(path, xattr_path, "extended attributes", type[0] == 'T'); 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++) { int fd; /* Not truncated, as in tmpfiles.d(5) */ fd = open(gl.gl_pathv[i], O_WRONLY | O_NOCTTY | O_CLOEXEC | (plus ? O_APPEND : 0)); if (fd < 0) continue; fp = fdopen(fd, plus ? "a" : "w"); if (!fp) { close(fd); continue; } write_arg(fp, arg, arglen); 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; } } if (dst) free(dst); if (rc) warn("Failed %s operation on path %s", type, path); } /* * A path is created after those above it, and removed or cleaned * after those below it, wherever in the files they are. */ static void run_entry(struct entry *e, int create) { if (e->done) return; e->done = 1; for (size_t i = 0; i < num_entries; i++) { struct entry *o = &entries[i]; if (o->done || !strcmp(o->key, e->key)) continue; if (create ? !globs(o) && below(e->key, o->key) : below(o->key, e->key)) run_entry(o, create); } tmpfiles(e); } static void run_entries(int create) { for (size_t i = 0; i < num_entries; i++) entries[i].done = 0; for (int glob = 0; glob < 2; glob++) { for (size_t i = 0; i < num_entries; i++) { if (globs(&entries[i]) == glob) run_entry(&entries[i], create); } } } static void process_file(const char *fn) { FILE *fp = stdin; if (strcmp(fn, "-")) { fp = fopen(fn, "r"); if (!fp) { warn("Failed to open %s", fn); return; } } conf = fn; if (cat_config) { printf("# %s\n", fn); fcopyfile(fp, stdout); puts(""); } while (!cat_config && !feof(fp)) { /* No comment character, a # is only a comment at the start of a line */ const char delim[3] = { '\\', '\\', 0 }; char *line; line = fparseln(fp, NULL, NULL, delim, 0); if (!line) continue; if (parse(line)) free(line); } if (fp != stdin) fclose(fp); } static int by_name(const void *a, const void *b) { return strcmp(basenm(*(char **)a), basenm(*(char **)b)); } 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, for its own files and for the configure prefix. * A file overrides one of the same name in a directory before * its own, and what is left is read in order of the file names, * whatever directory they are in. */ 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; size_t i, j, cnt = 0; char **list; glob_t gl; for (i = 0; i < NELEMS(dir); i++) { glob(dir[i], flags, NULL, &gl); flags |= GLOB_APPEND; } list = calloc(gl.gl_pathc + 1, sizeof(char *)); if (!list) err(1, "Failed listing files"); for (i = 0; i < gl.gl_pathc; i++) { for (j = i + 1; j < gl.gl_pathc; j++) { if (!strcmp(basenm(gl.gl_pathv[i]), basenm(gl.gl_pathv[j]))) break; } if (j == gl.gl_pathc) list[cnt++] = gl.gl_pathv[i]; } qsort(list, cnt, sizeof(char *), by_name); for (i = 0; i < cnt; i++) process_file(list[i]); free(list); 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" " --cat-config Show the files that would be read, and exit\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" " -n, --dry-run Only show the entries that would be run\n" " -E Exclude /dev, /proc, /run, and /sys\n" " --exclude-prefix=PFX Ignore rules for paths starting with PFX\n" " --graceful Does nothing, an unknown user or group is never an error\n" " --prefix=PFX Only apply 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. A CONFIGFILE of - is read\n" "from standard input.\n" "\n"); return rc; } enum { OPT_EXCLUDE_PREFIX = 256, OPT_BOOT, OPT_PREFIX, OPT_CAT_CONFIG, OPT_GRACEFUL, }; int main(int argc, char *argv[]) { struct option long_options[] = { { "boot", 0, NULL, OPT_BOOT }, { "cat-config", 0, NULL, OPT_CAT_CONFIG }, { "clean", 0, NULL, 'C' }, { "create", 0, NULL, 'c' }, { "debug", 0, NULL, 'd' }, { "dry-run", 0, NULL, 'n' }, { "exclude-prefix", 1, NULL, OPT_EXCLUDE_PREFIX }, { "graceful", 0, NULL, OPT_GRACEFUL }, { "prefix", 1, NULL, OPT_PREFIX }, { "remove", 0, NULL, 'r' }, { "help", 0, NULL, 'h' }, { NULL, 0, NULL, 0 } }; int c; while ((c = getopt_long(argc, argv, "CcdnrEh?", long_options, NULL)) != EOF) { switch(c) { case 'C': clean_flag = 1; break; case 'c': create_flag = 1; break; case 'd': debug = 1; break; case 'n': dry_run = 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_PREFIX: add_prefix(optarg); break; case OPT_CAT_CONFIG: cat_config = 1; break; case OPT_GRACEFUL: 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 (!cat_config && create_flag + clean_flag + remove_flag == 0) { fprintf(stderr, "You need to specify at least one of --clean, --create, or --remove.\n"); return 1; } process(argc - optind, &argv[optind]); /* Remove and clean first, or an r entry takes what an f entry above it made */ if (clean_flag || remove_flag) { int create = create_flag; create_flag = 0; run_entries(0); create_flag = create; clean_flag = remove_flag = 0; } if (create_flag) run_entries(1); return 0; } /** * Local Variables: * indent-tabs-mode: t * c-file-style: "linux" * End: */