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);
621 /* It's OK if we don't write the trailing
622 * newline, hence we check for l, instead of
623 * l+1 here. Files in /sys often refuse
624 * writing of the trailing newline. */
625 if (n < 0 || (size_t) n < l) {
626 log_error("Failed to write file %s: %s", i->path, n < 0 ? strerror(-n) : "Short write");
627 close_nointr_nofail(fd);
628 return n < 0 ? n : -EIO;
632 close_nointr_nofail(fd);
634 if (stat(i->path, &st) < 0) {
635 log_error("stat(%s) failed: %m", i->path);
639 if (!S_ISREG(st.st_mode)) {
640 log_error("%s is not a file.", i->path);
644 r = item_set_perms(i, i->path);
651 case TRUNCATE_DIRECTORY:
652 case CREATE_DIRECTORY:
655 mkdir_parents_label(i->path, 0755);
656 r = mkdir(i->path, i->mode);
659 if (r < 0 && errno != EEXIST) {
660 log_error("Failed to create directory %s: %m", i->path);
664 if (stat(i->path, &st) < 0) {
665 log_error("stat(%s) failed: %m", i->path);
669 if (!S_ISDIR(st.st_mode)) {
670 log_error("%s is not a directory.", i->path);
674 r = item_set_perms(i, i->path);
683 r = mkfifo(i->path, i->mode);
686 if (r < 0 && errno != EEXIST) {
687 log_error("Failed to create fifo %s: %m", i->path);
691 if (stat(i->path, &st) < 0) {
692 log_error("stat(%s) failed: %m", i->path);
696 if (!S_ISFIFO(st.st_mode)) {
697 log_error("%s is not a fifo.", i->path);
701 r = item_set_perms(i, i->path);
707 case CREATE_SYMLINK: {
710 label_context_set(i->path, S_IFLNK);
711 r = symlink(i->argument, i->path);
713 label_context_clear();
716 if (r < 0 && errno != EEXIST) {
717 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
721 r = readlink_malloc(i->path, &x);
723 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
727 if (!streq(i->argument, x)) {
729 log_error("%s is not the right symlinks.", i->path);
737 case CREATE_BLOCK_DEVICE:
738 case CREATE_CHAR_DEVICE: {
741 label_context_set(i->path, CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
742 r = mknod(i->path, i->mode | (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR), i->major_minor);
744 label_context_clear();
748 if (r < 0 && errno != EEXIST) {
749 log_error("Failed to create device node %s: %m", i->path);
753 if (stat(i->path, &st) < 0) {
754 log_error("stat(%s) failed: %m", i->path);
758 if (i->type == CREATE_BLOCK_DEVICE ? !S_ISBLK(st.st_mode) : !S_ISCHR(st.st_mode)) {
759 log_error("%s is not a device node.", i->path);
763 r = item_set_perms(i, i->path);
772 r = glob_item(i, item_set_perms);
777 case RECURSIVE_RELABEL_PATH:
779 r = glob_item(i, recursive_relabel);
784 log_debug("%s created successfully.", i->path);
789 static int remove_item_instance(Item *i, const char *instance) {
798 case CREATE_DIRECTORY:
801 case CREATE_BLOCK_DEVICE:
802 case CREATE_CHAR_DEVICE:
805 case RECURSIVE_RELABEL_PATH:
810 if (remove(instance) < 0 && errno != ENOENT) {
811 log_error("remove(%s): %m", instance);
817 case TRUNCATE_DIRECTORY:
818 case RECURSIVE_REMOVE_PATH:
819 r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
820 if (r < 0 && r != -ENOENT) {
821 log_error("rm_rf(%s): %s", instance, strerror(-r));
831 static int remove_item(Item *i) {
840 case CREATE_DIRECTORY:
843 case CREATE_CHAR_DEVICE:
844 case CREATE_BLOCK_DEVICE:
847 case RECURSIVE_RELABEL_PATH:
852 case TRUNCATE_DIRECTORY:
853 case RECURSIVE_REMOVE_PATH:
854 r = glob_item(i, remove_item_instance);
861 static int process_item(Item *i) {
866 r = arg_create ? create_item(i) : 0;
867 q = arg_remove ? remove_item(i) : 0;
868 p = arg_clean ? clean_item(i) : 0;
879 static void item_free(Item *i) {
887 static bool item_equal(Item *a, Item *b) {
891 if (!streq_ptr(a->path, b->path))
894 if (a->type != b->type)
897 if (a->uid_set != b->uid_set ||
898 (a->uid_set && a->uid != b->uid))
901 if (a->gid_set != b->gid_set ||
902 (a->gid_set && a->gid != b->gid))
905 if (a->mode_set != b->mode_set ||
906 (a->mode_set && a->mode != b->mode))
909 if (a->age_set != b->age_set ||
910 (a->age_set && a->age != b->age))
913 if ((a->type == CREATE_FILE ||
914 a->type == TRUNCATE_FILE ||
915 a->type == WRITE_FILE ||
916 a->type == CREATE_SYMLINK) &&
917 !streq_ptr(a->argument, b->argument))
920 if ((a->type == CREATE_CHAR_DEVICE ||
921 a->type == CREATE_BLOCK_DEVICE) &&
922 a->major_minor != b->major_minor)
928 static int parse_line(const char *fname, unsigned line, const char *buffer) {
930 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
941 log_error("Out of memory");
960 log_error("[%s:%u] Syntax error.", fname, line);
966 n += strspn(buffer+n, WHITESPACE);
967 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
968 i->argument = unquote(buffer+n, "\"");
970 log_error("Out of memory");
980 case CREATE_DIRECTORY:
981 case TRUNCATE_DIRECTORY:
985 case RECURSIVE_REMOVE_PATH:
987 case RECURSIVE_RELABEL_PATH:
992 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1000 log_error("[%s:%u] Write file requires argument.", fname, line);
1006 case CREATE_CHAR_DEVICE:
1007 case CREATE_BLOCK_DEVICE: {
1008 unsigned major, minor;
1011 log_error("[%s:%u] Device file requires argument.", fname, line);
1016 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1017 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1022 i->major_minor = makedev(major, minor);
1027 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1034 if (!path_is_absolute(i->path)) {
1035 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1040 path_kill_slashes(i->path);
1042 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1047 if (user && !streq(user, "-")) {
1048 const char *u = user;
1050 r = get_user_creds(&u, &i->uid, NULL, NULL);
1052 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1059 if (group && !streq(group, "-")) {
1060 const char *g = group;
1062 r = get_group_creds(&g, &i->gid);
1064 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1071 if (mode && !streq(mode, "-")) {
1074 if (sscanf(mode, "%o", &m) != 1) {
1075 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1084 i->type == CREATE_DIRECTORY ||
1085 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1087 if (age && !streq(age, "-")) {
1088 if (parse_usec(age, &i->age) < 0) {
1089 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1097 h = needs_glob(i->type) ? globs : items;
1099 existing = hashmap_get(h, i->path);
1102 /* Two identical items are fine */
1103 if (!item_equal(existing, i))
1104 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1110 r = hashmap_put(h, i->path, i);
1112 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1131 static int help(void) {
1133 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1134 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1135 " -h --help Show this help\n"
1136 " --create Create marked files/directories\n"
1137 " --clean Clean up marked directories\n"
1138 " --remove Remove marked files/directories\n"
1139 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1140 program_invocation_short_name);
1145 static int parse_argv(int argc, char *argv[]) {
1154 static const struct option options[] = {
1155 { "help", no_argument, NULL, 'h' },
1156 { "create", no_argument, NULL, ARG_CREATE },
1157 { "clean", no_argument, NULL, ARG_CLEAN },
1158 { "remove", no_argument, NULL, ARG_REMOVE },
1159 { "prefix", required_argument, NULL, ARG_PREFIX },
1160 { NULL, 0, NULL, 0 }
1168 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1189 arg_prefix = optarg;
1196 log_error("Unknown option code %c", c);
1201 if (!arg_clean && !arg_create && !arg_remove) {
1202 log_error("You need to specify at least one of --clean, --create or --remove.");
1209 static int read_config_file(const char *fn, bool ignore_enoent) {
1216 f = fopen(fn, "re");
1219 if (ignore_enoent && errno == ENOENT)
1222 log_error("Failed to open %s: %m", fn);
1226 log_debug("apply: %s\n", fn);
1228 char line[LINE_MAX], *l;
1231 if (!(fgets(line, sizeof(line), f)))
1237 if (*l == '#' || *l == 0)
1240 if ((k = parse_line(fn, v, l)) < 0)
1246 log_error("Failed to read from file %s: %m", fn);
1256 int main(int argc, char *argv[]) {
1261 r = parse_argv(argc, argv);
1263 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1265 log_set_target(LOG_TARGET_AUTO);
1266 log_parse_environment();
1273 items = hashmap_new(string_hash_func, string_compare_func);
1274 globs = hashmap_new(string_hash_func, string_compare_func);
1276 if (!items || !globs) {
1277 log_error("Out of memory");
1284 if (optind < argc) {
1287 for (j = optind; j < argc; j++)
1288 if (read_config_file(argv[j], false) < 0)
1294 r = conf_files_list(&files, ".conf",
1297 "/usr/local/lib/tmpfiles.d",
1298 "/usr/lib/tmpfiles.d",
1301 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1306 STRV_FOREACH(f, files) {
1307 if (read_config_file(*f, true) < 0)
1314 HASHMAP_FOREACH(i, globs, iterator)
1317 HASHMAP_FOREACH(i, items, iterator)
1321 while ((i = hashmap_steal_first(items)))
1324 while ((i = hashmap_steal_first(globs)))
1327 hashmap_free(items);
1328 hashmap_free(globs);
1330 set_free_free(unix_sockets);