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 item_set_perms(Item *i, const char *path) {
410 /* not using i->path directly because it may be a glob */
412 if (chmod(path, i->mode) < 0) {
413 log_error("chmod(%s) failed: %m", path);
417 if (i->uid_set || i->gid_set)
419 i->uid_set ? i->uid : (uid_t) -1,
420 i->gid_set ? i->gid : (gid_t) -1) < 0) {
422 log_error("chown(%s) failed: %m", path);
426 return label_fix(path, false);
429 static int recursive_relabel_children(Item *i, const char *path) {
433 /* This returns the first error we run into, but nevertheless
438 return errno == ENOENT ? 0 : -errno;
441 struct dirent buf, *de;
446 r = readdir_r(d, &buf, &de);
456 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
459 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
465 if (de->d_type == DT_UNKNOWN) {
468 if (lstat(entry_path, &st) < 0) {
469 if (ret == 0 && errno != ENOENT)
475 is_dir = S_ISDIR(st.st_mode);
478 is_dir = de->d_type == DT_DIR;
480 r = item_set_perms(i, entry_path);
482 if (ret == 0 && r != -ENOENT)
489 r = recursive_relabel_children(i, entry_path);
490 if (r < 0 && ret == 0)
502 static int recursive_relabel(Item *i, const char *path) {
506 r = item_set_perms(i, path);
510 if (lstat(path, &st) < 0)
513 if (S_ISDIR(st.st_mode))
514 r = recursive_relabel_children(i, path);
519 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
527 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
529 if (k != GLOB_NOMATCH) {
533 log_error("glob(%s) failed: %m", i->path);
538 STRV_FOREACH(fn, g.gl_pathv)
539 if ((k = action(i, *fn)) < 0)
546 static int create_item(Item *i) {
557 case RECURSIVE_REMOVE_PATH:
561 case TRUNCATE_FILE: {
565 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
566 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
570 log_error("Failed to create file %s: %m", i->path);
574 close_nointr_nofail(fd);
576 if (stat(i->path, &st) < 0) {
577 log_error("stat(%s) failed: %m", i->path);
581 if (!S_ISREG(st.st_mode)) {
582 log_error("%s is not a file.", i->path);
586 r = item_set_perms(i, i->path);
593 case TRUNCATE_DIRECTORY:
594 case CREATE_DIRECTORY:
597 mkdir_parents(i->path, 0755);
598 r = mkdir(i->path, i->mode);
601 if (r < 0 && errno != EEXIST) {
602 log_error("Failed to create directory %s: %m", i->path);
606 if (stat(i->path, &st) < 0) {
607 log_error("stat(%s) failed: %m", i->path);
611 if (!S_ISDIR(st.st_mode)) {
612 log_error("%s is not a directory.", i->path);
616 r = item_set_perms(i, i->path);
625 r = mkfifo(i->path, i->mode);
628 if (r < 0 && errno != EEXIST) {
629 log_error("Failed to create fifo %s: %m", i->path);
633 if (stat(i->path, &st) < 0) {
634 log_error("stat(%s) failed: %m", i->path);
638 if (!S_ISFIFO(st.st_mode)) {
639 log_error("%s is not a fifo.", i->path);
643 r = item_set_perms(i, i->path);
649 case RECURSIVE_RELABEL_PATH:
651 r = glob_item(i, recursive_relabel);
656 log_debug("%s created successfully.", i->path);
661 static int remove_item_instance(Item *i, const char *instance) {
670 case CREATE_DIRECTORY:
673 case RECURSIVE_RELABEL_PATH:
677 if (remove(instance) < 0 && errno != ENOENT) {
678 log_error("remove(%s): %m", instance);
684 case TRUNCATE_DIRECTORY:
685 case RECURSIVE_REMOVE_PATH:
686 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
688 log_error("rm_rf(%s): %s", instance, strerror(-r));
698 static int remove_item(Item *i) {
707 case CREATE_DIRECTORY:
710 case RECURSIVE_RELABEL_PATH:
714 case TRUNCATE_DIRECTORY:
715 case RECURSIVE_REMOVE_PATH:
716 r = glob_item(i, remove_item_instance);
723 static int process_item(Item *i) {
728 r = arg_create ? create_item(i) : 0;
729 q = arg_remove ? remove_item(i) : 0;
730 p = arg_clean ? clean_item(i) : 0;
741 static void item_free(Item *i) {
748 static bool item_equal(Item *a, Item *b) {
752 if (!streq_ptr(a->path, b->path))
755 if (a->type != b->type)
758 if (a->uid_set != b->uid_set ||
759 (a->uid_set && a->uid != b->uid))
762 if (a->gid_set != b->gid_set ||
763 (a->gid_set && a->gid != b->gid))
766 if (a->mode_set != b->mode_set ||
767 (a->mode_set && a->mode != b->mode))
770 if (a->age_set != b->age_set ||
771 (a->age_set && a->age != b->age))
777 static int parse_line(const char *fname, unsigned line, const char *buffer) {
779 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
788 if (!(i = new0(Item, 1))) {
789 log_error("Out of memory");
806 log_error("[%s:%u] Syntax error.", fname, line);
811 if (type != CREATE_FILE &&
812 type != TRUNCATE_FILE &&
813 type != CREATE_DIRECTORY &&
814 type != TRUNCATE_DIRECTORY &&
815 type != CREATE_FIFO &&
816 type != IGNORE_PATH &&
817 type != REMOVE_PATH &&
818 type != RECURSIVE_REMOVE_PATH &&
819 type != RECURSIVE_RELABEL_PATH) {
820 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
826 if (!path_is_absolute(i->path)) {
827 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
832 path_kill_slashes(i->path);
834 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
839 if (user && !streq(user, "-")) {
840 const char *u = user;
842 r = get_user_creds(&u, &i->uid, NULL, NULL);
844 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
851 if (group && !streq(group, "-")) {
852 const char *g = group;
854 r = get_group_creds(&g, &i->gid);
856 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
863 if (mode && !streq(mode, "-")) {
866 if (sscanf(mode, "%o", &m) != 1) {
867 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
875 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
877 if (age && !streq(age, "-")) {
878 if (parse_usec(age, &i->age) < 0) {
879 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
887 h = needs_glob(i->type) ? globs : items;
889 if ((existing = hashmap_get(h, i->path))) {
891 /* Two identical items are fine */
892 if (!item_equal(existing, i))
893 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
899 if ((r = hashmap_put(h, i->path, i)) < 0) {
900 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
919 static int help(void) {
921 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
922 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
923 " -h --help Show this help\n"
924 " --create Create marked files/directories\n"
925 " --clean Clean up marked directories\n"
926 " --remove Remove marked files/directories\n"
927 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
928 program_invocation_short_name);
933 static int parse_argv(int argc, char *argv[]) {
942 static const struct option options[] = {
943 { "help", no_argument, NULL, 'h' },
944 { "create", no_argument, NULL, ARG_CREATE },
945 { "clean", no_argument, NULL, ARG_CLEAN },
946 { "remove", no_argument, NULL, ARG_REMOVE },
947 { "prefix", required_argument, NULL, ARG_PREFIX },
956 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
984 log_error("Unknown option code %c", c);
989 if (!arg_clean && !arg_create && !arg_remove) {
990 log_error("You need to specify at least one of --clean, --create or --remove.");
997 static int read_config_file(const char *fn, bool ignore_enoent) {
1004 if (!(f = fopen(fn, "re"))) {
1006 if (ignore_enoent && errno == ENOENT)
1009 log_error("Failed to open %s: %m", fn);
1013 log_debug("apply: %s\n", fn);
1015 char line[LINE_MAX], *l;
1018 if (!(fgets(line, sizeof(line), f)))
1024 if (*l == '#' || *l == 0)
1027 if ((k = parse_line(fn, v, l)) < 0)
1033 log_error("Failed to read from file %s: %m", fn);
1043 int main(int argc, char *argv[]) {
1048 if ((r = parse_argv(argc, argv)) <= 0)
1049 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1051 log_set_target(LOG_TARGET_AUTO);
1052 log_parse_environment();
1059 items = hashmap_new(string_hash_func, string_compare_func);
1060 globs = hashmap_new(string_hash_func, string_compare_func);
1062 if (!items || !globs) {
1063 log_error("Out of memory");
1070 if (optind < argc) {
1073 for (j = optind; j < argc; j++)
1074 if (read_config_file(argv[j], false) < 0)
1080 r = conf_files_list(&files, ".conf",
1083 "/usr/local/lib/tmpfiles.d",
1084 "/usr/lib/tmpfiles.d",
1088 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1092 STRV_FOREACH(f, files) {
1093 if (read_config_file(*f, true) < 0)
1100 HASHMAP_FOREACH(i, globs, iterator)
1103 HASHMAP_FOREACH(i, items, iterator)
1107 while ((i = hashmap_steal_first(items)))
1110 while ((i = hashmap_steal_first(globs)))
1113 hashmap_free(items);
1114 hashmap_free(globs);
1116 set_free_free(unix_sockets);