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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU 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>
48 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
49 * them in the file system. This is intended to be used to create
50 * properly owned directories beneath /tmp, /var/tmp, /run, which are
51 * volatile and hence need to be recreated on bootup. */
53 typedef enum ItemType {
54 /* These ones take file names */
57 CREATE_DIRECTORY = 'd',
58 TRUNCATE_DIRECTORY = 'D',
61 CREATE_CHAR_DEVICE = 'c',
62 CREATE_BLOCK_DEVICE = 'b',
64 /* These ones take globs */
67 RECURSIVE_REMOVE_PATH = 'R',
69 RECURSIVE_RELABEL_PATH = 'Z'
90 static Hashmap *items = NULL, *globs = NULL;
91 static Set *unix_sockets = NULL;
93 static bool arg_create = false;
94 static bool arg_clean = false;
95 static bool arg_remove = false;
97 static const char *arg_prefix = NULL;
101 static bool needs_glob(ItemType t) {
102 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
105 static struct Item* find_glob(Hashmap *h, const char *match) {
109 HASHMAP_FOREACH(j, h, i)
110 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
116 static void load_unix_sockets(void) {
123 /* We maintain a cache of the sockets we found in
124 * /proc/net/unix to speed things up a little. */
126 unix_sockets = set_new(string_hash_func, string_compare_func);
130 f = fopen("/proc/net/unix", "re");
135 if (!fgets(line, sizeof(line), f))
142 if (!fgets(line, sizeof(line), f))
147 p = strchr(line, ':');
155 p += strspn(p, WHITESPACE);
156 p += strcspn(p, WHITESPACE); /* skip one more word */
157 p += strspn(p, WHITESPACE);
166 path_kill_slashes(s);
168 k = set_put(unix_sockets, s);
181 set_free_free(unix_sockets);
188 static bool unix_socket_alive(const char *fn) {
194 return !!set_get(unix_sockets, (char*) fn);
196 /* We don't know, so assume yes */
200 static int dir_cleanup(
203 const struct stat *ds,
210 struct timespec times[2];
211 bool deleted = false;
212 char *sub_path = NULL;
215 while ((dent = readdir(d))) {
219 if (streq(dent->d_name, ".") ||
220 streq(dent->d_name, ".."))
223 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
225 if (errno != ENOENT) {
226 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
233 /* Stay on the same filesystem */
234 if (s.st_dev != rootdev)
237 /* Do not delete read-only files owned by root */
238 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
244 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
245 log_error("Out of memory");
250 /* Is there an item configured for this path? */
251 if (hashmap_get(items, sub_path))
254 if (find_glob(globs, sub_path))
257 if (S_ISDIR(s.st_mode)) {
260 streq(dent->d_name, "lost+found") &&
265 log_warning("Reached max depth on %s.", sub_path);
270 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
271 if (sub_dir == NULL) {
272 if (errno != ENOENT) {
273 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
280 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
287 /* Ignore ctime, we change it when deleting */
288 age = MAX(timespec_load(&s.st_mtim),
289 timespec_load(&s.st_atim));
293 log_debug("rmdir '%s'\n", sub_path);
295 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
296 if (errno != ENOENT && errno != ENOTEMPTY) {
297 log_error("rmdir(%s): %m", sub_path);
303 /* Skip files for which the sticky bit is
304 * set. These are semantics we define, and are
305 * unknown elsewhere. See XDG_RUNTIME_DIR
306 * specification for details. */
307 if (s.st_mode & S_ISVTX)
310 if (mountpoint && S_ISREG(s.st_mode)) {
311 if (streq(dent->d_name, ".journal") &&
315 if (streq(dent->d_name, "aquota.user") ||
316 streq(dent->d_name, "aquota.group"))
320 /* Ignore sockets that are listed in /proc/net/unix */
321 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
324 /* Ignore device nodes */
325 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
328 age = MAX3(timespec_load(&s.st_mtim),
329 timespec_load(&s.st_atim),
330 timespec_load(&s.st_ctim));
335 log_debug("unlink '%s'\n", sub_path);
337 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
338 if (errno != ENOENT) {
339 log_error("unlink(%s): %m", sub_path);
350 /* Restore original directory timestamps */
351 times[0] = ds->st_atim;
352 times[1] = ds->st_mtim;
354 if (futimens(dirfd(d), times) < 0)
355 log_error("utimensat(%s): %m", p);
363 static int clean_item(Item *i) {
372 if (i->type != CREATE_DIRECTORY &&
373 i->type != TRUNCATE_DIRECTORY &&
374 i->type != IGNORE_PATH)
377 if (!i->age_set || i->age <= 0)
380 n = now(CLOCK_REALTIME);
386 d = opendir(i->path);
391 log_error("Failed to open directory %s: %m", i->path);
395 if (fstat(dirfd(d), &s) < 0) {
396 log_error("stat(%s) failed: %m", i->path);
401 if (!S_ISDIR(s.st_mode)) {
402 log_error("%s is not a directory.", i->path);
407 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
408 log_error("stat(%s/..) failed: %m", i->path);
413 mountpoint = s.st_dev != ps.st_dev ||
414 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
416 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
425 static int item_set_perms(Item *i, const char *path) {
426 /* not using i->path directly because it may be a glob */
428 if (chmod(path, i->mode) < 0) {
429 log_error("chmod(%s) failed: %m", path);
433 if (i->uid_set || i->gid_set)
435 i->uid_set ? i->uid : (uid_t) -1,
436 i->gid_set ? i->gid : (gid_t) -1) < 0) {
438 log_error("chown(%s) failed: %m", path);
442 return label_fix(path, false);
445 static int recursive_relabel_children(Item *i, const char *path) {
449 /* This returns the first error we run into, but nevertheless
454 return errno == ENOENT ? 0 : -errno;
457 struct dirent buf, *de;
462 r = readdir_r(d, &buf, &de);
472 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
475 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
481 if (de->d_type == DT_UNKNOWN) {
484 if (lstat(entry_path, &st) < 0) {
485 if (ret == 0 && errno != ENOENT)
491 is_dir = S_ISDIR(st.st_mode);
494 is_dir = de->d_type == DT_DIR;
496 r = item_set_perms(i, entry_path);
498 if (ret == 0 && r != -ENOENT)
505 r = recursive_relabel_children(i, entry_path);
506 if (r < 0 && ret == 0)
518 static int recursive_relabel(Item *i, const char *path) {
522 r = item_set_perms(i, path);
526 if (lstat(path, &st) < 0)
529 if (S_ISDIR(st.st_mode))
530 r = recursive_relabel_children(i, path);
535 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
543 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
545 if (k != GLOB_NOMATCH) {
549 log_error("glob(%s) failed: %m", i->path);
554 STRV_FOREACH(fn, g.gl_pathv)
555 if ((k = action(i, *fn)) < 0)
562 static int create_item(Item *i) {
573 case RECURSIVE_REMOVE_PATH:
577 case TRUNCATE_FILE: {
581 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
582 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
586 log_error("Failed to create file %s: %m", i->path);
590 close_nointr_nofail(fd);
592 if (stat(i->path, &st) < 0) {
593 log_error("stat(%s) failed: %m", i->path);
597 if (!S_ISREG(st.st_mode)) {
598 log_error("%s is not a file.", i->path);
602 r = item_set_perms(i, i->path);
609 case TRUNCATE_DIRECTORY:
610 case CREATE_DIRECTORY:
613 mkdir_parents(i->path, 0755);
614 r = mkdir(i->path, i->mode);
617 if (r < 0 && errno != EEXIST) {
618 log_error("Failed to create directory %s: %m", i->path);
622 if (stat(i->path, &st) < 0) {
623 log_error("stat(%s) failed: %m", i->path);
627 if (!S_ISDIR(st.st_mode)) {
628 log_error("%s is not a directory.", i->path);
632 r = item_set_perms(i, i->path);
641 r = mkfifo(i->path, i->mode);
644 if (r < 0 && errno != EEXIST) {
645 log_error("Failed to create fifo %s: %m", i->path);
649 if (stat(i->path, &st) < 0) {
650 log_error("stat(%s) failed: %m", i->path);
654 if (!S_ISFIFO(st.st_mode)) {
655 log_error("%s is not a fifo.", i->path);
659 r = item_set_perms(i, i->path);
665 case CREATE_SYMLINK: {
668 r = symlink(i->argument, i->path);
669 if (r < 0 && errno != EEXIST) {
670 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
674 r = readlink_malloc(i->path, &x);
676 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
680 if (!streq(i->argument, x)) {
682 log_error("%s is not the right symlinks.", i->path);
690 case CREATE_BLOCK_DEVICE:
691 case CREATE_CHAR_DEVICE: {
694 r = mknod(i->path, i->mode | (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR), i->major_minor);
697 if (r < 0 && errno != EEXIST) {
698 log_error("Failed to create device node %s: %m", i->path);
702 if (stat(i->path, &st) < 0) {
703 log_error("stat(%s) failed: %m", i->path);
707 if (i->type == CREATE_BLOCK_DEVICE ? !S_ISBLK(st.st_mode) : !S_ISCHR(st.st_mode)) {
708 log_error("%s is not a device node.", i->path);
712 r = item_set_perms(i, i->path);
721 r = glob_item(i, item_set_perms);
726 case RECURSIVE_RELABEL_PATH:
728 r = glob_item(i, recursive_relabel);
733 log_debug("%s created successfully.", i->path);
738 static int remove_item_instance(Item *i, const char *instance) {
747 case CREATE_DIRECTORY:
750 case CREATE_BLOCK_DEVICE:
751 case CREATE_CHAR_DEVICE:
754 case RECURSIVE_RELABEL_PATH:
758 if (remove(instance) < 0 && errno != ENOENT) {
759 log_error("remove(%s): %m", instance);
765 case TRUNCATE_DIRECTORY:
766 case RECURSIVE_REMOVE_PATH:
767 r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
768 if (r < 0 && r != -ENOENT) {
769 log_error("rm_rf(%s): %s", instance, strerror(-r));
779 static int remove_item(Item *i) {
788 case CREATE_DIRECTORY:
791 case CREATE_CHAR_DEVICE:
792 case CREATE_BLOCK_DEVICE:
795 case RECURSIVE_RELABEL_PATH:
799 case TRUNCATE_DIRECTORY:
800 case RECURSIVE_REMOVE_PATH:
801 r = glob_item(i, remove_item_instance);
808 static int process_item(Item *i) {
813 r = arg_create ? create_item(i) : 0;
814 q = arg_remove ? remove_item(i) : 0;
815 p = arg_clean ? clean_item(i) : 0;
826 static void item_free(Item *i) {
834 static bool item_equal(Item *a, Item *b) {
838 if (!streq_ptr(a->path, b->path))
841 if (a->type != b->type)
844 if (a->uid_set != b->uid_set ||
845 (a->uid_set && a->uid != b->uid))
848 if (a->gid_set != b->gid_set ||
849 (a->gid_set && a->gid != b->gid))
852 if (a->mode_set != b->mode_set ||
853 (a->mode_set && a->mode != b->mode))
856 if (a->age_set != b->age_set ||
857 (a->age_set && a->age != b->age))
860 if (a->type == CREATE_SYMLINK &&
861 !streq(a->argument, b->argument))
864 if ((a->type == CREATE_CHAR_DEVICE ||
865 a->type == CREATE_BLOCK_DEVICE) &&
866 a->major_minor != b->major_minor)
872 static int parse_line(const char *fname, unsigned line, const char *buffer) {
874 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
885 log_error("Out of memory");
904 log_error("[%s:%u] Syntax error.", fname, line);
913 case CREATE_DIRECTORY:
914 case TRUNCATE_DIRECTORY:
918 case RECURSIVE_REMOVE_PATH:
920 case RECURSIVE_RELABEL_PATH:
925 log_error("[%s:%u] Symlink file requires argument.", fname, line);
931 case CREATE_CHAR_DEVICE:
932 case CREATE_BLOCK_DEVICE: {
933 unsigned major, minor;
936 log_error("[%s:%u] Device file requires argument.", fname, line);
941 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
942 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
947 i->major_minor = makedev(major, minor);
952 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
959 if (!path_is_absolute(i->path)) {
960 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
965 path_kill_slashes(i->path);
967 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
972 if (user && !streq(user, "-")) {
973 const char *u = user;
975 r = get_user_creds(&u, &i->uid, NULL, NULL);
977 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
984 if (group && !streq(group, "-")) {
985 const char *g = group;
987 r = get_group_creds(&g, &i->gid);
989 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
996 if (mode && !streq(mode, "-")) {
999 if (sscanf(mode, "%o", &m) != 1) {
1000 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1009 i->type == CREATE_DIRECTORY ||
1010 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1012 if (age && !streq(age, "-")) {
1013 if (parse_usec(age, &i->age) < 0) {
1014 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1022 h = needs_glob(i->type) ? globs : items;
1024 existing = hashmap_get(h, i->path);
1027 /* Two identical items are fine */
1028 if (!item_equal(existing, i))
1029 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1035 r = hashmap_put(h, i->path, i);
1037 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1056 static int help(void) {
1058 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1059 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1060 " -h --help Show this help\n"
1061 " --create Create marked files/directories\n"
1062 " --clean Clean up marked directories\n"
1063 " --remove Remove marked files/directories\n"
1064 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1065 program_invocation_short_name);
1070 static int parse_argv(int argc, char *argv[]) {
1079 static const struct option options[] = {
1080 { "help", no_argument, NULL, 'h' },
1081 { "create", no_argument, NULL, ARG_CREATE },
1082 { "clean", no_argument, NULL, ARG_CLEAN },
1083 { "remove", no_argument, NULL, ARG_REMOVE },
1084 { "prefix", required_argument, NULL, ARG_PREFIX },
1085 { NULL, 0, NULL, 0 }
1093 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1114 arg_prefix = optarg;
1121 log_error("Unknown option code %c", c);
1126 if (!arg_clean && !arg_create && !arg_remove) {
1127 log_error("You need to specify at least one of --clean, --create or --remove.");
1134 static int read_config_file(const char *fn, bool ignore_enoent) {
1141 f = fopen(fn, "re");
1144 if (ignore_enoent && errno == ENOENT)
1147 log_error("Failed to open %s: %m", fn);
1151 log_debug("apply: %s\n", fn);
1153 char line[LINE_MAX], *l;
1156 if (!(fgets(line, sizeof(line), f)))
1162 if (*l == '#' || *l == 0)
1165 if ((k = parse_line(fn, v, l)) < 0)
1171 log_error("Failed to read from file %s: %m", fn);
1181 int main(int argc, char *argv[]) {
1186 r = parse_argv(argc, argv);
1188 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1190 log_set_target(LOG_TARGET_AUTO);
1191 log_parse_environment();
1198 items = hashmap_new(string_hash_func, string_compare_func);
1199 globs = hashmap_new(string_hash_func, string_compare_func);
1201 if (!items || !globs) {
1202 log_error("Out of memory");
1209 if (optind < argc) {
1212 for (j = optind; j < argc; j++)
1213 if (read_config_file(argv[j], false) < 0)
1219 r = conf_files_list(&files, ".conf",
1222 "/usr/local/lib/tmpfiles.d",
1223 "/usr/lib/tmpfiles.d",
1227 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1231 STRV_FOREACH(f, files) {
1232 if (read_config_file(*f, true) < 0)
1239 HASHMAP_FOREACH(i, globs, iterator)
1242 HASHMAP_FOREACH(i, items, iterator)
1246 while ((i = hashmap_steal_first(items)))
1249 while ((i = hashmap_steal_first(globs)))
1252 hashmap_free(items);
1253 hashmap_free(globs);
1255 set_free_free(unix_sockets);