1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering, Kay Sievers
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
37 #include <sys/types.h>
38 #include <sys/param.h>
41 #include <sys/xattr.h>
48 #include "path-util.h"
52 #include "conf-files.h"
53 #include "capability.h"
54 #include "specifier.h"
57 #include "selinux-util.h"
58 #include "btrfs-util.h"
60 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
61 * them in the file system. This is intended to be used to create
62 * properly owned directories beneath /tmp, /var/tmp, /run, which are
63 * volatile and hence need to be recreated on bootup. */
65 typedef enum ItemType {
66 /* These ones take file names */
69 CREATE_DIRECTORY = 'd',
70 TRUNCATE_DIRECTORY = 'D',
71 CREATE_SUBVOLUME = 'v',
74 CREATE_CHAR_DEVICE = 'c',
75 CREATE_BLOCK_DEVICE = 'b',
79 /* These ones take globs */
82 IGNORE_DIRECTORY_PATH = 'X',
84 RECURSIVE_REMOVE_PATH = 'R',
85 ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
87 RECURSIVE_RELABEL_PATH = 'Z',
109 bool keep_first_level:1;
116 static bool arg_create = false;
117 static bool arg_clean = false;
118 static bool arg_remove = false;
119 static bool arg_boot = false;
121 static char **arg_include_prefixes = NULL;
122 static char **arg_exclude_prefixes = NULL;
123 static char *arg_root = NULL;
125 static const char conf_file_dirs[] = CONF_DIRS_NULSTR("tmpfiles");
127 #define MAX_DEPTH 256
129 static Hashmap *items = NULL, *globs = NULL;
130 static Set *unix_sockets = NULL;
132 static bool needs_glob(ItemType t) {
136 IGNORE_DIRECTORY_PATH,
138 RECURSIVE_REMOVE_PATH,
141 RECURSIVE_RELABEL_PATH);
144 static struct Item* find_glob(Hashmap *h, const char *match) {
148 HASHMAP_FOREACH(j, h, i)
149 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
155 static void load_unix_sockets(void) {
156 _cleanup_fclose_ FILE *f = NULL;
162 /* We maintain a cache of the sockets we found in
163 * /proc/net/unix to speed things up a little. */
165 unix_sockets = set_new(&string_hash_ops);
169 f = fopen("/proc/net/unix", "re");
174 if (!fgets(line, sizeof(line), f))
181 if (!fgets(line, sizeof(line), f))
186 p = strchr(line, ':');
194 p += strspn(p, WHITESPACE);
195 p += strcspn(p, WHITESPACE); /* skip one more word */
196 p += strspn(p, WHITESPACE);
205 path_kill_slashes(s);
207 k = set_consume(unix_sockets, s);
208 if (k < 0 && k != -EEXIST)
215 set_free_free(unix_sockets);
219 static bool unix_socket_alive(const char *fn) {
225 return !!set_get(unix_sockets, (char*) fn);
227 /* We don't know, so assume yes */
231 static int dir_is_mount_point(DIR *d, const char *subdir) {
233 union file_handle_union h = {
234 .handle.handle_bytes = MAX_HANDLE_SZ
237 int mount_id_parent, mount_id;
240 r_p = name_to_handle_at(dirfd(d), ".", &h.handle, &mount_id_parent, 0);
244 h.handle.handle_bytes = MAX_HANDLE_SZ;
245 r = name_to_handle_at(dirfd(d), subdir, &h.handle, &mount_id, 0);
249 /* got no handle; make no assumptions, return error */
250 if (r_p < 0 && r < 0)
253 /* got both handles; if they differ, it is a mount point */
254 if (r_p >= 0 && r >= 0)
255 return mount_id_parent != mount_id;
257 /* got only one handle; assume different mount points if one
258 * of both queries was not supported by the filesystem */
259 if (r_p == -ENOSYS || r_p == -EOPNOTSUPP || r == -ENOSYS || r == -EOPNOTSUPP)
268 static int dir_cleanup(
272 const struct stat *ds,
277 bool keep_this_level) {
280 struct timespec times[2];
281 bool deleted = false;
284 while ((dent = readdir(d))) {
287 _cleanup_free_ char *sub_path = NULL;
289 if (streq(dent->d_name, ".") ||
290 streq(dent->d_name, ".."))
293 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
297 /* FUSE, NFS mounts, SELinux might return EACCES */
299 log_debug_errno(errno, "stat(%s/%s) failed: %m", p, dent->d_name);
301 log_error_errno(errno, "stat(%s/%s) failed: %m", p, dent->d_name);
306 /* Stay on the same filesystem */
307 if (s.st_dev != rootdev)
310 /* Try to detect bind mounts of the same filesystem instance; they
311 * do not differ in device major/minors. This type of query is not
312 * supported on all kernels or filesystem types though. */
313 if (S_ISDIR(s.st_mode) && dir_is_mount_point(d, dent->d_name) > 0)
316 /* Do not delete read-only files owned by root */
317 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
320 sub_path = strjoin(p, "/", dent->d_name, NULL);
326 /* Is there an item configured for this path? */
327 if (hashmap_get(items, sub_path))
330 if (find_glob(globs, sub_path))
333 if (S_ISDIR(s.st_mode)) {
336 streq(dent->d_name, "lost+found") &&
341 log_warning("Reached max depth on %s.", sub_path);
343 _cleanup_closedir_ DIR *sub_dir;
346 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
348 if (errno != ENOENT) {
349 log_error_errno(errno, "opendir(%s/%s) failed: %m", p, dent->d_name);
356 q = dir_cleanup(i, sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
361 /* Note: if you are wondering why we don't
362 * support the sticky bit for excluding
363 * directories from cleaning like we do it for
364 * other file system objects: well, the sticky
365 * bit already has a meaning for directories,
366 * so we don't want to overload that. */
371 /* Ignore ctime, we change it when deleting */
372 age = MAX(timespec_load(&s.st_mtim),
373 timespec_load(&s.st_atim));
377 if (i->type != IGNORE_DIRECTORY_PATH || !streq(dent->d_name, p)) {
378 log_debug("rmdir '%s'", sub_path);
380 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
381 if (errno != ENOENT && errno != ENOTEMPTY) {
382 log_error_errno(errno, "rmdir(%s): %m", sub_path);
389 /* Skip files for which the sticky bit is
390 * set. These are semantics we define, and are
391 * unknown elsewhere. See XDG_RUNTIME_DIR
392 * specification for details. */
393 if (s.st_mode & S_ISVTX)
396 if (mountpoint && S_ISREG(s.st_mode)) {
397 if (streq(dent->d_name, ".journal") &&
401 if (streq(dent->d_name, "aquota.user") ||
402 streq(dent->d_name, "aquota.group"))
406 /* Ignore sockets that are listed in /proc/net/unix */
407 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
410 /* Ignore device nodes */
411 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
414 /* Keep files on this level around if this is
419 age = MAX3(timespec_load(&s.st_mtim),
420 timespec_load(&s.st_atim),
421 timespec_load(&s.st_ctim));
426 log_debug("unlink '%s'", sub_path);
428 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
429 if (errno != ENOENT) {
430 log_error_errno(errno, "unlink(%s): %m", sub_path);
441 /* Restore original directory timestamps */
442 times[0] = ds->st_atim;
443 times[1] = ds->st_mtim;
445 if (futimens(dirfd(d), times) < 0)
446 log_error_errno(errno, "utimensat(%s): %m", p);
452 static int item_set_perms(Item *i, const char *path) {
459 st_valid = stat(path, &st) == 0;
461 /* not using i->path directly because it may be a glob */
465 if (i->mask_perms && st_valid) {
466 if (!(st.st_mode & 0111))
468 if (!(st.st_mode & 0222))
470 if (!(st.st_mode & 0444))
472 if (!S_ISDIR(st.st_mode))
473 m &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
476 if (!st_valid || m != (st.st_mode & 07777)) {
477 if (chmod(path, m) < 0)
478 return log_error_errno(errno, "chmod(%s) failed: %m", path);
482 if ((!st_valid || (i->uid != st.st_uid || i->gid != st.st_gid)) &&
483 (i->uid_set || i->gid_set))
485 i->uid_set ? i->uid : UID_INVALID,
486 i->gid_set ? i->gid : GID_INVALID) < 0) {
488 log_error_errno(errno, "chown(%s) failed: %m", path);
492 return label_fix(path, false, false);
495 static int get_xattrs_from_arg(Item *i) {
503 log_error("%s: Argument can't be empty!", i->path);
508 while ((r = unquote_first_word(&p, &xattr, false)) > 0) {
509 _cleanup_free_ char *tmp = NULL, *name = NULL, *value = NULL;
510 r = split_pair(xattr, "=", &name, &value);
512 log_warning("Illegal xattr found: \"%s\" - ignoring.", xattr);
517 if (streq(name, "") || streq(value, "")) {
518 log_warning("Malformed xattr found: \"%s=%s\" - ignoring.", name, value);
521 tmp = unquote(value, "\"");
525 value = cunescape(tmp);
528 if (strv_consume_pair(&i->xattrs, name, value) < 0)
536 static int item_set_xattrs(Item *i, const char *path) {
537 char **name, **value;
542 if (strv_isempty(i->xattrs))
545 STRV_FOREACH_PAIR(name, value, i->xattrs) {
548 if (lsetxattr(path, *name, *value, n, 0) < 0) {
549 log_error("Setting extended attribute %s=%s on %s failed: %m", *name, *value, path);
556 static int write_one_file(Item *i, const char *path) {
557 _cleanup_close_ int fd = -1;
564 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND|O_NOFOLLOW :
565 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC|O_NOFOLLOW : 0;
567 RUN_WITH_UMASK(0000) {
568 mac_selinux_create_file_prepare(path, S_IFREG);
569 fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode);
570 mac_selinux_create_file_clear();
574 if (i->type == WRITE_FILE && errno == ENOENT)
577 log_error_errno(errno, "Failed to create file %s: %m", path);
582 _cleanup_free_ char *unescaped;
586 unescaped = cunescape(i->argument);
590 l = strlen(unescaped);
591 n = write(fd, unescaped, l);
593 if (n < 0 || (size_t) n < l) {
594 log_error("Failed to write file %s: %s", path, n < 0 ? strerror(-n) : "Short write");
595 return n < 0 ? n : -EIO;
601 if (stat(path, &st) < 0)
602 return log_error_errno(errno, "stat(%s) failed: %m", path);
604 if (!S_ISREG(st.st_mode)) {
605 log_error("%s is not a file.", path);
609 r = item_set_perms(i, path);
613 r = item_set_xattrs(i, i->path);
620 static int item_set_perms_children(Item *i, const char *path) {
621 _cleanup_closedir_ DIR *d;
627 /* This returns the first error we run into, but nevertheless
632 return errno == ENOENT || errno == ENOTDIR ? 0 : -errno;
635 _cleanup_free_ char *p = NULL;
642 if (errno != 0 && r == 0)
648 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
651 p = strjoin(path, "/", de->d_name, NULL);
655 q = item_set_perms(i, p);
656 if (q < 0 && q != -ENOENT && r == 0)
659 if (IN_SET(de->d_type, DT_UNKNOWN, DT_DIR)) {
660 q = item_set_perms_children(i, p);
669 static int item_set_perms_recursive(Item *i, const char *path) {
675 r = item_set_perms(i, path);
679 q = item_set_perms_children(i, path);
686 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
687 _cleanup_globfree_ glob_t g = {};
692 k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
693 if (k != 0 && k != GLOB_NOMATCH) {
697 log_error_errno(errno, "glob(%s) failed: %m", i->path);
701 STRV_FOREACH(fn, g.gl_pathv) {
710 static int create_item(Item *i) {
719 case IGNORE_DIRECTORY_PATH:
721 case RECURSIVE_REMOVE_PATH:
726 r = write_one_file(i, i->path);
732 r = copy_tree(i->argument, i->path, false);
737 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
739 if (stat(i->argument, &a) < 0)
740 return log_error_errno(errno, "stat(%s) failed: %m", i->argument);
742 if (stat(i->path, &b) < 0)
743 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
745 if ((a.st_mode ^ b.st_mode) & S_IFMT) {
746 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
751 r = item_set_perms(i, i->path);
758 r = glob_item(i, write_one_file);
764 case CREATE_DIRECTORY:
765 case TRUNCATE_DIRECTORY:
766 case CREATE_SUBVOLUME:
769 mkdir_parents_label(i->path, 0755);
771 if (i->type == CREATE_SUBVOLUME) {
772 RUN_WITH_UMASK((~i->mode) & 0777)
773 r = btrfs_subvol_make(i->path);
777 if (i->type == CREATE_DIRECTORY || i->type == TRUNCATE_DIRECTORY || r == -ENOTTY) {
779 r = mkdir_label(i->path, i->mode);
784 return log_error_errno(r, "Failed to create directory or subvolume %s: %m", i->path);
786 if (stat(i->path, &st) < 0)
787 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
789 if (!S_ISDIR(st.st_mode)) {
790 log_debug("%s already exists and is not a directory.", i->path);
795 r = item_set_perms(i, i->path);
799 r = item_set_xattrs(i, i->path);
807 RUN_WITH_UMASK(0000) {
808 mac_selinux_create_file_prepare(i->path, S_IFIFO);
809 r = mkfifo(i->path, i->mode);
810 mac_selinux_create_file_clear();
815 return log_error_errno(errno, "Failed to create fifo %s: %m", i->path);
817 if (stat(i->path, &st) < 0)
818 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
820 if (!S_ISFIFO(st.st_mode)) {
824 RUN_WITH_UMASK(0000) {
825 mac_selinux_create_file_prepare(i->path, S_IFIFO);
826 r = mkfifo_atomic(i->path, i->mode);
827 mac_selinux_create_file_clear();
831 return log_error_errno(r, "Failed to create fifo %s: %m", i->path);
833 log_debug("%s is not a fifo.", i->path);
839 r = item_set_perms(i, i->path);
843 r = item_set_xattrs(i, i->path);
851 mac_selinux_create_file_prepare(i->path, S_IFLNK);
852 r = symlink(i->argument, i->path);
853 mac_selinux_create_file_clear();
856 _cleanup_free_ char *x = NULL;
859 return log_error_errno(errno, "symlink(%s, %s) failed: %m", i->argument, i->path);
861 r = readlink_malloc(i->path, &x);
862 if (r < 0 || !streq(i->argument, x)) {
865 mac_selinux_create_file_prepare(i->path, S_IFLNK);
866 r = symlink_atomic(i->argument, i->path);
867 mac_selinux_create_file_clear();
870 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
872 log_debug("%s is not a symlink or does not point to the correct path.", i->path);
878 r = item_set_xattrs(i, i->path);
884 case CREATE_BLOCK_DEVICE:
885 case CREATE_CHAR_DEVICE: {
888 if (have_effective_cap(CAP_MKNOD) == 0) {
889 /* In a container we lack CAP_MKNOD. We
890 shouldn't attempt to create the device node in
891 that case to avoid noise, and we don't support
892 virtualized devices in containers anyway. */
894 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
898 file_type = i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR;
900 RUN_WITH_UMASK(0000) {
901 mac_selinux_create_file_prepare(i->path, file_type);
902 r = mknod(i->path, i->mode | file_type, i->major_minor);
903 mac_selinux_create_file_clear();
907 if (errno == EPERM) {
908 log_debug("We lack permissions, possibly because of cgroup configuration; "
909 "skipping creation of device node %s.", i->path);
914 return log_error_errno(errno, "Failed to create device node %s: %m", i->path);
916 if (stat(i->path, &st) < 0)
917 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
919 if ((st.st_mode & S_IFMT) != file_type) {
923 RUN_WITH_UMASK(0000) {
924 mac_selinux_create_file_prepare(i->path, file_type);
925 r = mknod_atomic(i->path, i->mode | file_type, i->major_minor);
926 mac_selinux_create_file_clear();
930 return log_error_errno(r, "Failed to create device node %s: %m", i->path);
932 log_debug("%s is not a device node.", i->path);
938 r = item_set_perms(i, i->path);
942 r = item_set_xattrs(i, i->path);
952 r = glob_item(i, item_set_perms);
957 case RECURSIVE_RELABEL_PATH:
959 r = glob_item(i, item_set_perms_recursive);
965 r = item_set_xattrs(i, i->path);
971 log_debug("%s created successfully.", i->path);
976 static int remove_item_instance(Item *i, const char *instance) {
985 case CREATE_DIRECTORY:
986 case CREATE_SUBVOLUME:
989 case CREATE_BLOCK_DEVICE:
990 case CREATE_CHAR_DEVICE:
992 case IGNORE_DIRECTORY_PATH:
995 case RECURSIVE_RELABEL_PATH:
1002 if (remove(instance) < 0 && errno != ENOENT)
1003 return log_error_errno(errno, "remove(%s): %m", instance);
1007 case TRUNCATE_DIRECTORY:
1008 case RECURSIVE_REMOVE_PATH:
1009 /* FIXME: we probably should use dir_cleanup() here
1010 * instead of rm_rf() so that 'x' is honoured. */
1011 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
1012 if (r < 0 && r != -ENOENT)
1013 return log_error_errno(r, "rm_rf(%s): %m", instance);
1021 static int remove_item(Item *i) {
1030 case CREATE_DIRECTORY:
1031 case CREATE_SUBVOLUME:
1033 case CREATE_SYMLINK:
1034 case CREATE_CHAR_DEVICE:
1035 case CREATE_BLOCK_DEVICE:
1037 case IGNORE_DIRECTORY_PATH:
1040 case RECURSIVE_RELABEL_PATH:
1047 case TRUNCATE_DIRECTORY:
1048 case RECURSIVE_REMOVE_PATH:
1049 r = glob_item(i, remove_item_instance);
1056 static int clean_item_instance(Item *i, const char* instance) {
1057 _cleanup_closedir_ DIR *d = NULL;
1068 n = now(CLOCK_REALTIME);
1072 cutoff = n - i->age;
1074 d = opendir(instance);
1076 if (errno == ENOENT || errno == ENOTDIR)
1079 log_error_errno(errno, "Failed to open directory %s: %m", i->path);
1083 if (fstat(dirfd(d), &s) < 0)
1084 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
1086 if (!S_ISDIR(s.st_mode)) {
1087 log_error("%s is not a directory.", i->path);
1091 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
1092 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
1094 mountpoint = s.st_dev != ps.st_dev ||
1095 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
1097 r = dir_cleanup(i, instance, d, &s, cutoff, s.st_dev, mountpoint,
1098 MAX_DEPTH, i->keep_first_level);
1102 static int clean_item(Item *i) {
1108 case CREATE_DIRECTORY:
1109 case CREATE_SUBVOLUME:
1110 case TRUNCATE_DIRECTORY:
1113 clean_item_instance(i, i->path);
1115 case IGNORE_DIRECTORY_PATH:
1116 r = glob_item(i, clean_item_instance);
1125 static int process_item(Item *i) {
1127 _cleanup_free_ char *prefix = NULL;
1136 prefix = malloc(strlen(i->path) + 1);
1140 PATH_FOREACH_PREFIX(prefix, i->path) {
1143 j = hashmap_get(items, prefix);
1147 s = process_item(j);
1148 if (s < 0 && t == 0)
1153 r = arg_create ? create_item(i) : 0;
1154 q = arg_remove ? remove_item(i) : 0;
1155 p = arg_clean ? clean_item(i) : 0;
1163 static void item_free(Item *i) {
1170 strv_free(i->xattrs);
1174 DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1176 static bool item_equal(Item *a, Item *b) {
1180 if (!streq_ptr(a->path, b->path))
1183 if (a->type != b->type)
1186 if (a->uid_set != b->uid_set ||
1187 (a->uid_set && a->uid != b->uid))
1190 if (a->gid_set != b->gid_set ||
1191 (a->gid_set && a->gid != b->gid))
1194 if (a->mode_set != b->mode_set ||
1195 (a->mode_set && a->mode != b->mode))
1198 if (a->age_set != b->age_set ||
1199 (a->age_set && a->age != b->age))
1202 if ((a->type == CREATE_FILE ||
1203 a->type == TRUNCATE_FILE ||
1204 a->type == WRITE_FILE ||
1205 a->type == CREATE_SYMLINK ||
1206 a->type == COPY_FILES) &&
1207 !streq_ptr(a->argument, b->argument))
1210 if ((a->type == CREATE_CHAR_DEVICE ||
1211 a->type == CREATE_BLOCK_DEVICE) &&
1212 a->major_minor != b->major_minor)
1218 static bool should_include_path(const char *path) {
1221 STRV_FOREACH(prefix, arg_exclude_prefixes)
1222 if (path_startswith(path, *prefix))
1225 STRV_FOREACH(prefix, arg_include_prefixes)
1226 if (path_startswith(path, *prefix))
1229 /* no matches, so we should include this path only if we
1230 * have no whitelist at all */
1231 return strv_length(arg_include_prefixes) == 0;
1234 static int parse_line(const char *fname, unsigned line, const char *buffer) {
1236 static const Specifier specifier_table[] = {
1237 { 'm', specifier_machine_id, NULL },
1238 { 'b', specifier_boot_id, NULL },
1239 { 'H', specifier_host_name, NULL },
1240 { 'v', specifier_kernel_release, NULL },
1244 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
1245 _cleanup_(item_freep) Item *i = NULL;
1256 "%ms %ms %ms %ms %ms %ms %n",
1265 log_error("[%s:%u] Syntax error.", fname, line);
1269 if (isempty(action)) {
1270 log_error("[%s:%u] Command too short '%s'.", fname, line, action);
1274 if (strlen(action) > 1 && !in_charset(action+1, "!+")) {
1275 log_error("[%s:%u] Unknown modifiers in command '%s'", fname, line, action);
1279 if (strchr(action+1, '!') && !arg_boot)
1288 i->force = !!strchr(action+1, '+');
1290 r = specifier_printf(path, specifier_table, NULL, &i->path);
1292 log_error("[%s:%u] Failed to replace specifiers: %s", fname, line, path);
1297 n += strspn(buffer+n, WHITESPACE);
1298 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1299 i->argument = unquote(buffer+n, "\"");
1309 case CREATE_DIRECTORY:
1310 case CREATE_SUBVOLUME:
1311 case TRUNCATE_DIRECTORY:
1314 case IGNORE_DIRECTORY_PATH:
1316 case RECURSIVE_REMOVE_PATH:
1319 case RECURSIVE_RELABEL_PATH:
1322 case CREATE_SYMLINK:
1324 i->argument = strappend("/usr/share/factory", i->path);
1332 log_error("[%s:%u] Write file requires argument.", fname, line);
1339 i->argument = strappend("/usr/share/factory", i->path);
1344 if (!path_is_absolute(i->argument)) {
1345 log_error("[%s:%u] Source path is not absolute.", fname, line);
1349 path_kill_slashes(i->argument);
1352 case CREATE_CHAR_DEVICE:
1353 case CREATE_BLOCK_DEVICE: {
1354 unsigned major, minor;
1357 log_error("[%s:%u] Device file requires argument.", fname, line);
1361 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1362 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1366 i->major_minor = makedev(major, minor);
1372 log_error("[%s:%u] Set extended attribute requires argument.", fname, line);
1375 r = get_xattrs_from_arg(i);
1381 log_error("[%s:%u] Unknown command type '%c'.", fname, line, type);
1387 if (!path_is_absolute(i->path)) {
1388 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1392 path_kill_slashes(i->path);
1394 if (!should_include_path(i->path))
1400 p = strappend(arg_root, i->path);
1408 if (user && !streq(user, "-")) {
1409 const char *u = user;
1411 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1413 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1420 if (group && !streq(group, "-")) {
1421 const char *g = group;
1423 r = get_group_creds(&g, &i->gid);
1425 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1432 if (mode && !streq(mode, "-")) {
1433 const char *mm = mode;
1437 i->mask_perms = true;
1441 if (sscanf(mm, "%o", &m) != 1) {
1442 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1450 i->type == CREATE_DIRECTORY ||
1451 i->type == CREATE_SUBVOLUME ||
1452 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1454 if (age && !streq(age, "-")) {
1455 const char *a = age;
1458 i->keep_first_level = true;
1462 if (parse_sec(a, &i->age) < 0) {
1463 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1470 h = needs_glob(i->type) ? globs : items;
1472 existing = hashmap_get(h, i->path);
1474 if (i->type == SET_XATTR) {
1475 r = strv_extend_strv(&existing->xattrs, i->xattrs);
1479 } else if (existing->type == SET_XATTR) {
1480 r = strv_extend_strv(&i->xattrs, existing->xattrs);
1483 r = hashmap_replace(h, i->path, i);
1485 log_error("Failed to replace item for %s.", i->path);
1488 item_free(existing);
1490 /* Two identical items are fine */
1491 if (!item_equal(existing, i))
1492 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1496 r = hashmap_put(h, i->path, i);
1498 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1503 i = NULL; /* avoid cleanup */
1508 static void help(void) {
1509 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1510 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1511 " -h --help Show this help\n"
1512 " --version Show package version\n"
1513 " --create Create marked files/directories\n"
1514 " --clean Clean up marked directories\n"
1515 " --remove Remove marked files/directories\n"
1516 " --boot Execute actions only safe at boot\n"
1517 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n"
1518 " --exclude-prefix=PATH Ignore rules that apply to paths with the specified prefix\n"
1519 " --root=PATH Operate on an alternate filesystem root\n",
1520 program_invocation_short_name);
1523 static int parse_argv(int argc, char *argv[]) {
1526 ARG_VERSION = 0x100,
1536 static const struct option options[] = {
1537 { "help", no_argument, NULL, 'h' },
1538 { "version", no_argument, NULL, ARG_VERSION },
1539 { "create", no_argument, NULL, ARG_CREATE },
1540 { "clean", no_argument, NULL, ARG_CLEAN },
1541 { "remove", no_argument, NULL, ARG_REMOVE },
1542 { "boot", no_argument, NULL, ARG_BOOT },
1543 { "prefix", required_argument, NULL, ARG_PREFIX },
1544 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
1545 { "root", required_argument, NULL, ARG_ROOT },
1554 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
1563 puts(PACKAGE_STRING);
1564 puts(SYSTEMD_FEATURES);
1584 if (strv_push(&arg_include_prefixes, optarg) < 0)
1588 case ARG_EXCLUDE_PREFIX:
1589 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
1595 arg_root = path_make_absolute_cwd(optarg);
1599 path_kill_slashes(arg_root);
1606 assert_not_reached("Unhandled option");
1609 if (!arg_clean && !arg_create && !arg_remove) {
1610 log_error("You need to specify at least one of --clean, --create or --remove.");
1617 static int read_config_file(const char *fn, bool ignore_enoent) {
1618 _cleanup_fclose_ FILE *f = NULL;
1619 char line[LINE_MAX];
1627 r = search_and_fopen_nulstr(fn, "re", arg_root, conf_file_dirs, &f);
1629 if (ignore_enoent && r == -ENOENT)
1632 return log_error_errno(r, "Failed to open '%s', ignoring: %m", fn);
1635 FOREACH_LINE(line, f, break) {
1642 if (*l == '#' || *l == 0)
1645 k = parse_line(fn, v, l);
1646 if (k < 0 && r == 0)
1650 /* we have to determine age parameter for each entry of type X */
1651 HASHMAP_FOREACH(i, globs, iterator) {
1653 Item *j, *candidate_item = NULL;
1655 if (i->type != IGNORE_DIRECTORY_PATH)
1658 HASHMAP_FOREACH(j, items, iter) {
1659 if (j->type != CREATE_DIRECTORY && j->type != TRUNCATE_DIRECTORY && j->type != CREATE_SUBVOLUME)
1662 if (path_equal(j->path, i->path)) {
1667 if ((!candidate_item && path_startswith(i->path, j->path)) ||
1668 (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
1672 if (candidate_item && candidate_item->age_set) {
1673 i->age = candidate_item->age;
1679 log_error_errno(errno, "Failed to read from file %s: %m", fn);
1687 int main(int argc, char *argv[]) {
1692 r = parse_argv(argc, argv);
1696 log_set_target(LOG_TARGET_AUTO);
1697 log_parse_environment();
1702 mac_selinux_init(NULL);
1704 items = hashmap_new(&string_hash_ops);
1705 globs = hashmap_new(&string_hash_ops);
1707 if (!items || !globs) {
1714 if (optind < argc) {
1717 for (j = optind; j < argc; j++) {
1718 k = read_config_file(argv[j], false);
1719 if (k < 0 && r == 0)
1724 _cleanup_strv_free_ char **files = NULL;
1727 r = conf_files_list_nulstr(&files, ".conf", arg_root, conf_file_dirs);
1729 log_error_errno(r, "Failed to enumerate tmpfiles.d files: %m");
1733 STRV_FOREACH(f, files) {
1734 k = read_config_file(*f, true);
1735 if (k < 0 && r == 0)
1740 HASHMAP_FOREACH(i, globs, iterator) {
1741 k = process_item(i);
1742 if (k < 0 && r == 0)
1746 HASHMAP_FOREACH(i, items, iterator) {
1747 k = process_item(i);
1748 if (k < 0 && r == 0)
1753 while ((i = hashmap_steal_first(items)))
1756 while ((i = hashmap_steal_first(globs)))
1759 hashmap_free(items);
1760 hashmap_free(globs);
1762 free(arg_include_prefixes);
1763 free(arg_exclude_prefixes);
1766 set_free_free(unix_sockets);
1768 mac_selinux_finish();
1770 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;