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>
45 #include "path-util.h"
49 #include "conf-files.h"
51 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
52 * them in the file system. This is intended to be used to create
53 * properly owned directories beneath /tmp, /var/tmp, /run, which are
54 * volatile and hence need to be recreated on bootup. */
56 typedef enum ItemType {
57 /* These ones take file names */
61 CREATE_DIRECTORY = 'd',
62 TRUNCATE_DIRECTORY = 'D',
65 CREATE_CHAR_DEVICE = 'c',
66 CREATE_BLOCK_DEVICE = 'b',
68 /* These ones take globs */
71 RECURSIVE_REMOVE_PATH = 'R',
73 RECURSIVE_RELABEL_PATH = 'Z'
94 static Hashmap *items = NULL, *globs = NULL;
95 static Set *unix_sockets = NULL;
97 static bool arg_create = false;
98 static bool arg_clean = false;
99 static bool arg_remove = false;
101 static const char *arg_prefix = NULL;
103 #define MAX_DEPTH 256
105 static bool needs_glob(ItemType t) {
106 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
109 static struct Item* find_glob(Hashmap *h, const char *match) {
113 HASHMAP_FOREACH(j, h, i)
114 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
120 static void load_unix_sockets(void) {
127 /* We maintain a cache of the sockets we found in
128 * /proc/net/unix to speed things up a little. */
130 unix_sockets = set_new(string_hash_func, string_compare_func);
134 f = fopen("/proc/net/unix", "re");
139 if (!fgets(line, sizeof(line), f))
146 if (!fgets(line, sizeof(line), f))
151 p = strchr(line, ':');
159 p += strspn(p, WHITESPACE);
160 p += strcspn(p, WHITESPACE); /* skip one more word */
161 p += strspn(p, WHITESPACE);
170 path_kill_slashes(s);
172 k = set_put(unix_sockets, s);
185 set_free_free(unix_sockets);
192 static bool unix_socket_alive(const char *fn) {
198 return !!set_get(unix_sockets, (char*) fn);
200 /* We don't know, so assume yes */
204 static int dir_cleanup(
207 const struct stat *ds,
214 struct timespec times[2];
215 bool deleted = false;
216 char *sub_path = NULL;
219 while ((dent = readdir(d))) {
223 if (streq(dent->d_name, ".") ||
224 streq(dent->d_name, ".."))
227 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
229 if (errno != ENOENT) {
230 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
237 /* Stay on the same filesystem */
238 if (s.st_dev != rootdev)
241 /* Do not delete read-only files owned by root */
242 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
248 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
249 log_error("Out of memory");
254 /* Is there an item configured for this path? */
255 if (hashmap_get(items, sub_path))
258 if (find_glob(globs, sub_path))
261 if (S_ISDIR(s.st_mode)) {
264 streq(dent->d_name, "lost+found") &&
269 log_warning("Reached max depth on %s.", sub_path);
274 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
275 if (sub_dir == NULL) {
276 if (errno != ENOENT) {
277 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
284 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
291 /* Ignore ctime, we change it when deleting */
292 age = MAX(timespec_load(&s.st_mtim),
293 timespec_load(&s.st_atim));
297 log_debug("rmdir '%s'\n", sub_path);
299 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
300 if (errno != ENOENT && errno != ENOTEMPTY) {
301 log_error("rmdir(%s): %m", sub_path);
307 /* Skip files for which the sticky bit is
308 * set. These are semantics we define, and are
309 * unknown elsewhere. See XDG_RUNTIME_DIR
310 * specification for details. */
311 if (s.st_mode & S_ISVTX)
314 if (mountpoint && S_ISREG(s.st_mode)) {
315 if (streq(dent->d_name, ".journal") &&
319 if (streq(dent->d_name, "aquota.user") ||
320 streq(dent->d_name, "aquota.group"))
324 /* Ignore sockets that are listed in /proc/net/unix */
325 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
328 /* Ignore device nodes */
329 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
332 age = MAX3(timespec_load(&s.st_mtim),
333 timespec_load(&s.st_atim),
334 timespec_load(&s.st_ctim));
339 log_debug("unlink '%s'\n", sub_path);
341 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
342 if (errno != ENOENT) {
343 log_error("unlink(%s): %m", sub_path);
354 /* Restore original directory timestamps */
355 times[0] = ds->st_atim;
356 times[1] = ds->st_mtim;
358 if (futimens(dirfd(d), times) < 0)
359 log_error("utimensat(%s): %m", p);
367 static int clean_item(Item *i) {
376 if (i->type != CREATE_DIRECTORY &&
377 i->type != TRUNCATE_DIRECTORY &&
378 i->type != IGNORE_PATH)
381 if (!i->age_set || i->age <= 0)
384 n = now(CLOCK_REALTIME);
390 d = opendir(i->path);
395 log_error("Failed to open directory %s: %m", i->path);
399 if (fstat(dirfd(d), &s) < 0) {
400 log_error("stat(%s) failed: %m", i->path);
405 if (!S_ISDIR(s.st_mode)) {
406 log_error("%s is not a directory.", i->path);
411 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
412 log_error("stat(%s/..) failed: %m", i->path);
417 mountpoint = s.st_dev != ps.st_dev ||
418 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
420 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
429 static int item_set_perms(Item *i, const char *path) {
430 /* not using i->path directly because it may be a glob */
432 if (chmod(path, i->mode) < 0) {
433 log_error("chmod(%s) failed: %m", path);
437 if (i->uid_set || i->gid_set)
439 i->uid_set ? i->uid : (uid_t) -1,
440 i->gid_set ? i->gid : (gid_t) -1) < 0) {
442 log_error("chown(%s) failed: %m", path);
446 return label_fix(path, false);
449 static int recursive_relabel_children(Item *i, const char *path) {
453 /* This returns the first error we run into, but nevertheless
458 return errno == ENOENT ? 0 : -errno;
461 struct dirent buf, *de;
466 r = readdir_r(d, &buf, &de);
476 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
479 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
485 if (de->d_type == DT_UNKNOWN) {
488 if (lstat(entry_path, &st) < 0) {
489 if (ret == 0 && errno != ENOENT)
495 is_dir = S_ISDIR(st.st_mode);
498 is_dir = de->d_type == DT_DIR;
500 r = item_set_perms(i, entry_path);
502 if (ret == 0 && r != -ENOENT)
509 r = recursive_relabel_children(i, entry_path);
510 if (r < 0 && ret == 0)
522 static int recursive_relabel(Item *i, const char *path) {
526 r = item_set_perms(i, path);
530 if (lstat(path, &st) < 0)
533 if (S_ISDIR(st.st_mode))
534 r = recursive_relabel_children(i, path);
539 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
547 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
549 if (k != GLOB_NOMATCH) {
553 log_error("glob(%s) failed: %m", i->path);
558 STRV_FOREACH(fn, g.gl_pathv)
559 if ((k = action(i, *fn)) < 0)
566 static int create_item(Item *i) {
577 case RECURSIVE_REMOVE_PATH:
585 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
586 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
589 label_context_set(i->path, S_IFREG);
590 fd = open(i->path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
592 label_context_clear();
597 if (i->type == WRITE_FILE && errno == ENOENT)
600 log_error("Failed to create file %s: %m", i->path);
607 struct iovec iovec[2];
608 static const char new_line = '\n';
610 l = strlen(i->argument);
613 iovec[0].iov_base = i->argument;
614 iovec[0].iov_len = l;
616 iovec[1].iov_base = (void*) &new_line;
617 iovec[1].iov_len = 1;
619 n = writev(fd, iovec, 2);
620 if (n < 0 || (size_t) n != l+1) {
621 log_error("Failed to write file %s: %s", i->path, n < 0 ? strerror(-n) : "Short");
622 close_nointr_nofail(fd);
623 return n < 0 ? n : -EIO;
627 close_nointr_nofail(fd);
629 if (stat(i->path, &st) < 0) {
630 log_error("stat(%s) failed: %m", i->path);
634 if (!S_ISREG(st.st_mode)) {
635 log_error("%s is not a file.", i->path);
639 r = item_set_perms(i, i->path);
646 case TRUNCATE_DIRECTORY:
647 case CREATE_DIRECTORY:
650 mkdir_parents(i->path, 0755);
651 r = mkdir(i->path, i->mode);
654 if (r < 0 && errno != EEXIST) {
655 log_error("Failed to create directory %s: %m", i->path);
659 if (stat(i->path, &st) < 0) {
660 log_error("stat(%s) failed: %m", i->path);
664 if (!S_ISDIR(st.st_mode)) {
665 log_error("%s is not a directory.", i->path);
669 r = item_set_perms(i, i->path);
678 r = mkfifo(i->path, i->mode);
681 if (r < 0 && errno != EEXIST) {
682 log_error("Failed to create fifo %s: %m", i->path);
686 if (stat(i->path, &st) < 0) {
687 log_error("stat(%s) failed: %m", i->path);
691 if (!S_ISFIFO(st.st_mode)) {
692 log_error("%s is not a fifo.", i->path);
696 r = item_set_perms(i, i->path);
702 case CREATE_SYMLINK: {
705 label_context_set(i->path, S_IFLNK);
706 r = symlink(i->argument, i->path);
708 label_context_clear();
711 if (r < 0 && errno != EEXIST) {
712 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
716 r = readlink_malloc(i->path, &x);
718 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
722 if (!streq(i->argument, x)) {
724 log_error("%s is not the right symlinks.", i->path);
732 case CREATE_BLOCK_DEVICE:
733 case CREATE_CHAR_DEVICE: {
736 label_context_set(i->path, CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
737 r = mknod(i->path, i->mode | (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR), i->major_minor);
739 label_context_clear();
743 if (r < 0 && errno != EEXIST) {
744 log_error("Failed to create device node %s: %m", i->path);
748 if (stat(i->path, &st) < 0) {
749 log_error("stat(%s) failed: %m", i->path);
753 if (i->type == CREATE_BLOCK_DEVICE ? !S_ISBLK(st.st_mode) : !S_ISCHR(st.st_mode)) {
754 log_error("%s is not a device node.", i->path);
758 r = item_set_perms(i, i->path);
767 r = glob_item(i, item_set_perms);
772 case RECURSIVE_RELABEL_PATH:
774 r = glob_item(i, recursive_relabel);
779 log_debug("%s created successfully.", i->path);
784 static int remove_item_instance(Item *i, const char *instance) {
793 case CREATE_DIRECTORY:
796 case CREATE_BLOCK_DEVICE:
797 case CREATE_CHAR_DEVICE:
800 case RECURSIVE_RELABEL_PATH:
805 if (remove(instance) < 0 && errno != ENOENT) {
806 log_error("remove(%s): %m", instance);
812 case TRUNCATE_DIRECTORY:
813 case RECURSIVE_REMOVE_PATH:
814 r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
815 if (r < 0 && r != -ENOENT) {
816 log_error("rm_rf(%s): %s", instance, strerror(-r));
826 static int remove_item(Item *i) {
835 case CREATE_DIRECTORY:
838 case CREATE_CHAR_DEVICE:
839 case CREATE_BLOCK_DEVICE:
842 case RECURSIVE_RELABEL_PATH:
847 case TRUNCATE_DIRECTORY:
848 case RECURSIVE_REMOVE_PATH:
849 r = glob_item(i, remove_item_instance);
856 static int process_item(Item *i) {
861 r = arg_create ? create_item(i) : 0;
862 q = arg_remove ? remove_item(i) : 0;
863 p = arg_clean ? clean_item(i) : 0;
874 static void item_free(Item *i) {
882 static bool item_equal(Item *a, Item *b) {
886 if (!streq_ptr(a->path, b->path))
889 if (a->type != b->type)
892 if (a->uid_set != b->uid_set ||
893 (a->uid_set && a->uid != b->uid))
896 if (a->gid_set != b->gid_set ||
897 (a->gid_set && a->gid != b->gid))
900 if (a->mode_set != b->mode_set ||
901 (a->mode_set && a->mode != b->mode))
904 if (a->age_set != b->age_set ||
905 (a->age_set && a->age != b->age))
908 if ((a->type == CREATE_FILE ||
909 a->type == TRUNCATE_FILE ||
910 a->type == WRITE_FILE ||
911 a->type == CREATE_SYMLINK) &&
912 !streq_ptr(a->argument, b->argument))
915 if ((a->type == CREATE_CHAR_DEVICE ||
916 a->type == CREATE_BLOCK_DEVICE) &&
917 a->major_minor != b->major_minor)
923 static int parse_line(const char *fname, unsigned line, const char *buffer) {
925 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
936 log_error("Out of memory");
955 log_error("[%s:%u] Syntax error.", fname, line);
961 n += strspn(buffer+n, WHITESPACE);
962 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
963 i->argument = unquote(buffer+n, "\"");
965 log_error("Out of memory");
975 case CREATE_DIRECTORY:
976 case TRUNCATE_DIRECTORY:
980 case RECURSIVE_REMOVE_PATH:
982 case RECURSIVE_RELABEL_PATH:
987 log_error("[%s:%u] Symlink file requires argument.", fname, line);
995 log_error("[%s:%u] Write file requires argument.", fname, line);
1001 case CREATE_CHAR_DEVICE:
1002 case CREATE_BLOCK_DEVICE: {
1003 unsigned major, minor;
1006 log_error("[%s:%u] Device file requires argument.", fname, line);
1011 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1012 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1017 i->major_minor = makedev(major, minor);
1022 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1029 if (!path_is_absolute(i->path)) {
1030 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1035 path_kill_slashes(i->path);
1037 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1042 if (user && !streq(user, "-")) {
1043 const char *u = user;
1045 r = get_user_creds(&u, &i->uid, NULL, NULL);
1047 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1054 if (group && !streq(group, "-")) {
1055 const char *g = group;
1057 r = get_group_creds(&g, &i->gid);
1059 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1066 if (mode && !streq(mode, "-")) {
1069 if (sscanf(mode, "%o", &m) != 1) {
1070 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1079 i->type == CREATE_DIRECTORY ||
1080 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1082 if (age && !streq(age, "-")) {
1083 if (parse_usec(age, &i->age) < 0) {
1084 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1092 h = needs_glob(i->type) ? globs : items;
1094 existing = hashmap_get(h, i->path);
1097 /* Two identical items are fine */
1098 if (!item_equal(existing, i))
1099 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1105 r = hashmap_put(h, i->path, i);
1107 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1126 static int help(void) {
1128 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1129 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1130 " -h --help Show this help\n"
1131 " --create Create marked files/directories\n"
1132 " --clean Clean up marked directories\n"
1133 " --remove Remove marked files/directories\n"
1134 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1135 program_invocation_short_name);
1140 static int parse_argv(int argc, char *argv[]) {
1149 static const struct option options[] = {
1150 { "help", no_argument, NULL, 'h' },
1151 { "create", no_argument, NULL, ARG_CREATE },
1152 { "clean", no_argument, NULL, ARG_CLEAN },
1153 { "remove", no_argument, NULL, ARG_REMOVE },
1154 { "prefix", required_argument, NULL, ARG_PREFIX },
1155 { NULL, 0, NULL, 0 }
1163 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1184 arg_prefix = optarg;
1191 log_error("Unknown option code %c", c);
1196 if (!arg_clean && !arg_create && !arg_remove) {
1197 log_error("You need to specify at least one of --clean, --create or --remove.");
1204 static int read_config_file(const char *fn, bool ignore_enoent) {
1211 f = fopen(fn, "re");
1214 if (ignore_enoent && errno == ENOENT)
1217 log_error("Failed to open %s: %m", fn);
1221 log_debug("apply: %s\n", fn);
1223 char line[LINE_MAX], *l;
1226 if (!(fgets(line, sizeof(line), f)))
1232 if (*l == '#' || *l == 0)
1235 if ((k = parse_line(fn, v, l)) < 0)
1241 log_error("Failed to read from file %s: %m", fn);
1251 int main(int argc, char *argv[]) {
1256 r = parse_argv(argc, argv);
1258 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1260 log_set_target(LOG_TARGET_AUTO);
1261 log_parse_environment();
1268 items = hashmap_new(string_hash_func, string_compare_func);
1269 globs = hashmap_new(string_hash_func, string_compare_func);
1271 if (!items || !globs) {
1272 log_error("Out of memory");
1279 if (optind < argc) {
1282 for (j = optind; j < argc; j++)
1283 if (read_config_file(argv[j], false) < 0)
1289 r = conf_files_list(&files, ".conf",
1292 "/usr/local/lib/tmpfiles.d",
1293 "/usr/lib/tmpfiles.d",
1296 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1301 STRV_FOREACH(f, files) {
1302 if (read_config_file(*f, true) < 0)
1309 HASHMAP_FOREACH(i, globs, iterator)
1312 HASHMAP_FOREACH(i, items, iterator)
1316 while ((i = hashmap_steal_first(items)))
1319 while ((i = hashmap_steal_first(globs)))
1322 hashmap_free(items);
1323 hashmap_free(globs);
1325 set_free_free(unix_sockets);