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 /* These ones take globs */
64 RECURSIVE_REMOVE_PATH = 'R',
65 RECURSIVE_RELABEL_PATH = 'Z'
83 static Hashmap *items = NULL, *globs = NULL;
84 static Set *unix_sockets = NULL;
86 static bool arg_create = false;
87 static bool arg_clean = false;
88 static bool arg_remove = false;
90 static const char *arg_prefix = NULL;
94 static bool needs_glob(ItemType t) {
95 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RECURSIVE_RELABEL_PATH;
98 static struct Item* find_glob(Hashmap *h, const char *match) {
102 HASHMAP_FOREACH(j, h, i)
103 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
109 static void load_unix_sockets(void) {
116 /* We maintain a cache of the sockets we found in
117 * /proc/net/unix to speed things up a little. */
119 if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
122 if (!(f = fopen("/proc/net/unix", "re")))
125 if (!(fgets(line, sizeof(line), f)))
132 if (!(fgets(line, sizeof(line), f)))
137 if (strlen(line) < 53)
141 p += strspn(p, WHITESPACE);
142 p += strcspn(p, WHITESPACE);
143 p += strspn(p, WHITESPACE);
148 if (!(s = strdup(p)))
151 path_kill_slashes(s);
153 if ((k = set_put(unix_sockets, s)) < 0) {
165 set_free_free(unix_sockets);
172 static bool unix_socket_alive(const char *fn) {
178 return !!set_get(unix_sockets, (char*) fn);
180 /* We don't know, so assume yes */
184 static int dir_cleanup(
187 const struct stat *ds,
194 struct timespec times[2];
195 bool deleted = false;
196 char *sub_path = NULL;
199 while ((dent = readdir(d))) {
203 if (streq(dent->d_name, ".") ||
204 streq(dent->d_name, ".."))
207 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
209 if (errno != ENOENT) {
210 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
217 /* Stay on the same filesystem */
218 if (s.st_dev != rootdev)
221 /* Do not delete read-only files owned by root */
222 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
228 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
229 log_error("Out of memory");
234 /* Is there an item configured for this path? */
235 if (hashmap_get(items, sub_path))
238 if (find_glob(globs, sub_path))
241 if (S_ISDIR(s.st_mode)) {
244 streq(dent->d_name, "lost+found") &&
249 log_warning("Reached max depth on %s.", sub_path);
254 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
255 if (sub_dir == NULL) {
256 if (errno != ENOENT) {
257 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
264 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
271 /* Ignore ctime, we change it when deleting */
272 age = MAX(timespec_load(&s.st_mtim),
273 timespec_load(&s.st_atim));
277 log_debug("rmdir '%s'\n", sub_path);
279 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
280 if (errno != ENOENT && errno != ENOTEMPTY) {
281 log_error("rmdir(%s): %m", sub_path);
287 /* Skip files for which the sticky bit is
288 * set. These are semantics we define, and are
289 * unknown elsewhere. See XDG_RUNTIME_DIR
290 * specification for details. */
291 if (s.st_mode & S_ISVTX)
294 if (mountpoint && S_ISREG(s.st_mode)) {
295 if (streq(dent->d_name, ".journal") &&
299 if (streq(dent->d_name, "aquota.user") ||
300 streq(dent->d_name, "aquota.group"))
304 /* Ignore sockets that are listed in /proc/net/unix */
305 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
308 /* Ignore device nodes */
309 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
312 age = MAX3(timespec_load(&s.st_mtim),
313 timespec_load(&s.st_atim),
314 timespec_load(&s.st_ctim));
319 log_debug("unlink '%s'\n", sub_path);
321 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
322 if (errno != ENOENT) {
323 log_error("unlink(%s): %m", sub_path);
334 /* Restore original directory timestamps */
335 times[0] = ds->st_atim;
336 times[1] = ds->st_mtim;
338 if (futimens(dirfd(d), times) < 0)
339 log_error("utimensat(%s): %m", p);
347 static int clean_item(Item *i) {
356 if (i->type != CREATE_DIRECTORY &&
357 i->type != TRUNCATE_DIRECTORY &&
358 i->type != IGNORE_PATH)
361 if (!i->age_set || i->age <= 0)
364 n = now(CLOCK_REALTIME);
370 d = opendir(i->path);
375 log_error("Failed to open directory %s: %m", i->path);
379 if (fstat(dirfd(d), &s) < 0) {
380 log_error("stat(%s) failed: %m", i->path);
385 if (!S_ISDIR(s.st_mode)) {
386 log_error("%s is not a directory.", i->path);
391 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
392 log_error("stat(%s/..) failed: %m", i->path);
397 mountpoint = s.st_dev != ps.st_dev ||
398 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
400 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
409 static int recursive_relabel_children(const char *path) {
413 /* This returns the first error we run into, but nevertheless
418 return errno == ENOENT ? 0 : -errno;
421 struct dirent buf, *de;
426 r = readdir_r(d, &buf, &de);
436 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
439 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
445 if (de->d_type == DT_UNKNOWN) {
448 if (lstat(entry_path, &st) < 0) {
449 if (ret == 0 && errno != ENOENT)
455 is_dir = S_ISDIR(st.st_mode);
458 is_dir = de->d_type == DT_DIR;
460 r = label_fix(entry_path, false);
462 if (ret == 0 && r != -ENOENT)
469 r = recursive_relabel_children(entry_path);
470 if (r < 0 && ret == 0)
482 static int recursive_relabel(Item *i, const char *path) {
486 r = label_fix(path, false);
490 if (lstat(path, &st) < 0)
493 if (S_ISDIR(st.st_mode))
494 r = recursive_relabel_children(path);
499 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
507 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
509 if (k != GLOB_NOMATCH) {
513 log_error("glob(%s) failed: %m", i->path);
518 STRV_FOREACH(fn, g.gl_pathv)
519 if ((k = action(i, *fn)) < 0)
526 static int item_set_perms(Item *i) {
528 if (chmod(i->path, i->mode) < 0) {
529 log_error("chmod(%s) failed: %m", i->path);
533 if (i->uid_set || i->gid_set)
535 i->uid_set ? i->uid : (uid_t) -1,
536 i->gid_set ? i->gid : (gid_t) -1) < 0) {
538 log_error("chown(%s) failed: %m", i->path);
542 return label_fix(i->path, false);
545 static int create_item(Item *i) {
556 case RECURSIVE_REMOVE_PATH:
560 case TRUNCATE_FILE: {
564 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
565 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
569 log_error("Failed to create file %s: %m", i->path);
573 close_nointr_nofail(fd);
575 if (stat(i->path, &st) < 0) {
576 log_error("stat(%s) failed: %m", i->path);
580 if (!S_ISREG(st.st_mode)) {
581 log_error("%s is not a file.", i->path);
585 r = item_set_perms(i);
592 case TRUNCATE_DIRECTORY:
593 case CREATE_DIRECTORY:
596 mkdir_parents(i->path, 0755);
597 r = mkdir(i->path, i->mode);
600 if (r < 0 && errno != EEXIST) {
601 log_error("Failed to create directory %s: %m", i->path);
605 if (stat(i->path, &st) < 0) {
606 log_error("stat(%s) failed: %m", i->path);
610 if (!S_ISDIR(st.st_mode)) {
611 log_error("%s is not a directory.", i->path);
615 r = item_set_perms(i);
624 r = mkfifo(i->path, i->mode);
627 if (r < 0 && errno != EEXIST) {
628 log_error("Failed to create fifo %s: %m", i->path);
632 if (stat(i->path, &st) < 0) {
633 log_error("stat(%s) failed: %m", i->path);
637 if (!S_ISFIFO(st.st_mode)) {
638 log_error("%s is not a fifo.", i->path);
642 r = item_set_perms(i);
648 case RECURSIVE_RELABEL_PATH:
650 r = glob_item(i, recursive_relabel);
655 log_debug("%s created successfully.", i->path);
660 static int remove_item_instance(Item *i, const char *instance) {
669 case CREATE_DIRECTORY:
672 case RECURSIVE_RELABEL_PATH:
676 if (remove(instance) < 0 && errno != ENOENT) {
677 log_error("remove(%s): %m", instance);
683 case TRUNCATE_DIRECTORY:
684 case RECURSIVE_REMOVE_PATH:
685 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
687 log_error("rm_rf(%s): %s", instance, strerror(-r));
697 static int remove_item(Item *i) {
706 case CREATE_DIRECTORY:
709 case RECURSIVE_RELABEL_PATH:
713 case TRUNCATE_DIRECTORY:
714 case RECURSIVE_REMOVE_PATH:
715 r = glob_item(i, remove_item_instance);
722 static int process_item(Item *i) {
727 r = arg_create ? create_item(i) : 0;
728 q = arg_remove ? remove_item(i) : 0;
729 p = arg_clean ? clean_item(i) : 0;
740 static void item_free(Item *i) {
747 static bool item_equal(Item *a, Item *b) {
751 if (!streq_ptr(a->path, b->path))
754 if (a->type != b->type)
757 if (a->uid_set != b->uid_set ||
758 (a->uid_set && a->uid != b->uid))
761 if (a->gid_set != b->gid_set ||
762 (a->gid_set && a->gid != b->gid))
765 if (a->mode_set != b->mode_set ||
766 (a->mode_set && a->mode != b->mode))
769 if (a->age_set != b->age_set ||
770 (a->age_set && a->age != b->age))
776 static int parse_line(const char *fname, unsigned line, const char *buffer) {
778 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
787 if (!(i = new0(Item, 1))) {
788 log_error("Out of memory");
805 log_error("[%s:%u] Syntax error.", fname, line);
810 if (type != CREATE_FILE &&
811 type != TRUNCATE_FILE &&
812 type != CREATE_DIRECTORY &&
813 type != TRUNCATE_DIRECTORY &&
814 type != CREATE_FIFO &&
815 type != IGNORE_PATH &&
816 type != REMOVE_PATH &&
817 type != RECURSIVE_REMOVE_PATH &&
818 type != RECURSIVE_RELABEL_PATH) {
819 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
825 if (!path_is_absolute(i->path)) {
826 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
831 path_kill_slashes(i->path);
833 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
838 if (user && !streq(user, "-")) {
839 const char *u = user;
841 r = get_user_creds(&u, &i->uid, NULL, NULL);
843 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
850 if (group && !streq(group, "-")) {
851 const char *g = group;
853 r = get_group_creds(&g, &i->gid);
855 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
862 if (mode && !streq(mode, "-")) {
865 if (sscanf(mode, "%o", &m) != 1) {
866 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
874 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
876 if (age && !streq(age, "-")) {
877 if (parse_usec(age, &i->age) < 0) {
878 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
886 h = needs_glob(i->type) ? globs : items;
888 if ((existing = hashmap_get(h, i->path))) {
890 /* Two identical items are fine */
891 if (!item_equal(existing, i))
892 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
898 if ((r = hashmap_put(h, i->path, i)) < 0) {
899 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
918 static int help(void) {
920 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
921 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
922 " -h --help Show this help\n"
923 " --create Create marked files/directories\n"
924 " --clean Clean up marked directories\n"
925 " --remove Remove marked files/directories\n"
926 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
927 program_invocation_short_name);
932 static int parse_argv(int argc, char *argv[]) {
941 static const struct option options[] = {
942 { "help", no_argument, NULL, 'h' },
943 { "create", no_argument, NULL, ARG_CREATE },
944 { "clean", no_argument, NULL, ARG_CLEAN },
945 { "remove", no_argument, NULL, ARG_REMOVE },
946 { "prefix", required_argument, NULL, ARG_PREFIX },
955 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
983 log_error("Unknown option code %c", c);
988 if (!arg_clean && !arg_create && !arg_remove) {
989 log_error("You need to specify at least one of --clean, --create or --remove.");
996 static int read_config_file(const char *fn, bool ignore_enoent) {
1003 if (!(f = fopen(fn, "re"))) {
1005 if (ignore_enoent && errno == ENOENT)
1008 log_error("Failed to open %s: %m", fn);
1012 log_debug("apply: %s\n", fn);
1014 char line[LINE_MAX], *l;
1017 if (!(fgets(line, sizeof(line), f)))
1023 if (*l == '#' || *l == 0)
1026 if ((k = parse_line(fn, v, l)) < 0)
1032 log_error("Failed to read from file %s: %m", fn);
1042 int main(int argc, char *argv[]) {
1047 if ((r = parse_argv(argc, argv)) <= 0)
1048 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1050 log_set_target(LOG_TARGET_AUTO);
1051 log_parse_environment();
1058 items = hashmap_new(string_hash_func, string_compare_func);
1059 globs = hashmap_new(string_hash_func, string_compare_func);
1061 if (!items || !globs) {
1062 log_error("Out of memory");
1069 if (optind < argc) {
1072 for (j = optind; j < argc; j++)
1073 if (read_config_file(argv[j], false) < 0)
1079 r = conf_files_list(&files, ".conf",
1082 "/usr/local/lib/tmpfiles.d",
1083 "/usr/lib/tmpfiles.d",
1087 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1091 STRV_FOREACH(f, files) {
1092 if (read_config_file(*f, true) < 0)
1099 HASHMAP_FOREACH(i, globs, iterator)
1102 HASHMAP_FOREACH(i, items, iterator)
1106 while ((i = hashmap_steal_first(items)))
1109 while ((i = hashmap_steal_first(globs)))
1112 hashmap_free(items);
1113 hashmap_free(globs);
1115 set_free_free(unix_sockets);