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',
66 RECURSIVE_RELABEL_PATH = 'Z'
84 static Hashmap *items = NULL, *globs = NULL;
85 static Set *unix_sockets = NULL;
87 static bool arg_create = false;
88 static bool arg_clean = false;
89 static bool arg_remove = false;
91 static const char *arg_prefix = NULL;
95 static bool needs_glob(ItemType t) {
96 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
99 static struct Item* find_glob(Hashmap *h, const char *match) {
103 HASHMAP_FOREACH(j, h, i)
104 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
110 static void load_unix_sockets(void) {
117 /* We maintain a cache of the sockets we found in
118 * /proc/net/unix to speed things up a little. */
120 unix_sockets = set_new(string_hash_func, string_compare_func);
124 f = fopen("/proc/net/unix", "re");
129 if (!fgets(line, sizeof(line), f))
136 if (!fgets(line, sizeof(line), f))
141 p = strchr(line, ':');
149 p += strspn(p, WHITESPACE);
150 p += strcspn(p, WHITESPACE); /* skip one more word */
151 p += strspn(p, WHITESPACE);
160 path_kill_slashes(s);
162 k = set_put(unix_sockets, s);
175 set_free_free(unix_sockets);
182 static bool unix_socket_alive(const char *fn) {
188 return !!set_get(unix_sockets, (char*) fn);
190 /* We don't know, so assume yes */
194 static int dir_cleanup(
197 const struct stat *ds,
204 struct timespec times[2];
205 bool deleted = false;
206 char *sub_path = NULL;
209 while ((dent = readdir(d))) {
213 if (streq(dent->d_name, ".") ||
214 streq(dent->d_name, ".."))
217 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
219 if (errno != ENOENT) {
220 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
227 /* Stay on the same filesystem */
228 if (s.st_dev != rootdev)
231 /* Do not delete read-only files owned by root */
232 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
238 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
239 log_error("Out of memory");
244 /* Is there an item configured for this path? */
245 if (hashmap_get(items, sub_path))
248 if (find_glob(globs, sub_path))
251 if (S_ISDIR(s.st_mode)) {
254 streq(dent->d_name, "lost+found") &&
259 log_warning("Reached max depth on %s.", sub_path);
264 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
265 if (sub_dir == NULL) {
266 if (errno != ENOENT) {
267 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
274 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
281 /* Ignore ctime, we change it when deleting */
282 age = MAX(timespec_load(&s.st_mtim),
283 timespec_load(&s.st_atim));
287 log_debug("rmdir '%s'\n", sub_path);
289 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
290 if (errno != ENOENT && errno != ENOTEMPTY) {
291 log_error("rmdir(%s): %m", sub_path);
297 /* Skip files for which the sticky bit is
298 * set. These are semantics we define, and are
299 * unknown elsewhere. See XDG_RUNTIME_DIR
300 * specification for details. */
301 if (s.st_mode & S_ISVTX)
304 if (mountpoint && S_ISREG(s.st_mode)) {
305 if (streq(dent->d_name, ".journal") &&
309 if (streq(dent->d_name, "aquota.user") ||
310 streq(dent->d_name, "aquota.group"))
314 /* Ignore sockets that are listed in /proc/net/unix */
315 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
318 /* Ignore device nodes */
319 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
322 age = MAX3(timespec_load(&s.st_mtim),
323 timespec_load(&s.st_atim),
324 timespec_load(&s.st_ctim));
329 log_debug("unlink '%s'\n", sub_path);
331 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
332 if (errno != ENOENT) {
333 log_error("unlink(%s): %m", sub_path);
344 /* Restore original directory timestamps */
345 times[0] = ds->st_atim;
346 times[1] = ds->st_mtim;
348 if (futimens(dirfd(d), times) < 0)
349 log_error("utimensat(%s): %m", p);
357 static int clean_item(Item *i) {
366 if (i->type != CREATE_DIRECTORY &&
367 i->type != TRUNCATE_DIRECTORY &&
368 i->type != IGNORE_PATH)
371 if (!i->age_set || i->age <= 0)
374 n = now(CLOCK_REALTIME);
380 d = opendir(i->path);
385 log_error("Failed to open directory %s: %m", i->path);
389 if (fstat(dirfd(d), &s) < 0) {
390 log_error("stat(%s) failed: %m", i->path);
395 if (!S_ISDIR(s.st_mode)) {
396 log_error("%s is not a directory.", i->path);
401 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
402 log_error("stat(%s/..) failed: %m", i->path);
407 mountpoint = s.st_dev != ps.st_dev ||
408 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
410 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
419 static int item_set_perms(Item *i, const char *path) {
420 /* not using i->path directly because it may be a glob */
422 if (chmod(path, i->mode) < 0) {
423 log_error("chmod(%s) failed: %m", path);
427 if (i->uid_set || i->gid_set)
429 i->uid_set ? i->uid : (uid_t) -1,
430 i->gid_set ? i->gid : (gid_t) -1) < 0) {
432 log_error("chown(%s) failed: %m", path);
436 return label_fix(path, false);
439 static int recursive_relabel_children(Item *i, const char *path) {
443 /* This returns the first error we run into, but nevertheless
448 return errno == ENOENT ? 0 : -errno;
451 struct dirent buf, *de;
456 r = readdir_r(d, &buf, &de);
466 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
469 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
475 if (de->d_type == DT_UNKNOWN) {
478 if (lstat(entry_path, &st) < 0) {
479 if (ret == 0 && errno != ENOENT)
485 is_dir = S_ISDIR(st.st_mode);
488 is_dir = de->d_type == DT_DIR;
490 r = item_set_perms(i, entry_path);
492 if (ret == 0 && r != -ENOENT)
499 r = recursive_relabel_children(i, entry_path);
500 if (r < 0 && ret == 0)
512 static int recursive_relabel(Item *i, const char *path) {
516 r = item_set_perms(i, path);
520 if (lstat(path, &st) < 0)
523 if (S_ISDIR(st.st_mode))
524 r = recursive_relabel_children(i, path);
529 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
537 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
539 if (k != GLOB_NOMATCH) {
543 log_error("glob(%s) failed: %m", i->path);
548 STRV_FOREACH(fn, g.gl_pathv)
549 if ((k = action(i, *fn)) < 0)
556 static int create_item(Item *i) {
567 case RECURSIVE_REMOVE_PATH:
571 case TRUNCATE_FILE: {
575 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
576 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
580 log_error("Failed to create file %s: %m", i->path);
584 close_nointr_nofail(fd);
586 if (stat(i->path, &st) < 0) {
587 log_error("stat(%s) failed: %m", i->path);
591 if (!S_ISREG(st.st_mode)) {
592 log_error("%s is not a file.", i->path);
596 r = item_set_perms(i, i->path);
603 case TRUNCATE_DIRECTORY:
604 case CREATE_DIRECTORY:
607 mkdir_parents(i->path, 0755);
608 r = mkdir(i->path, i->mode);
611 if (r < 0 && errno != EEXIST) {
612 log_error("Failed to create directory %s: %m", i->path);
616 if (stat(i->path, &st) < 0) {
617 log_error("stat(%s) failed: %m", i->path);
621 if (!S_ISDIR(st.st_mode)) {
622 log_error("%s is not a directory.", i->path);
626 r = item_set_perms(i, i->path);
635 r = mkfifo(i->path, i->mode);
638 if (r < 0 && errno != EEXIST) {
639 log_error("Failed to create fifo %s: %m", i->path);
643 if (stat(i->path, &st) < 0) {
644 log_error("stat(%s) failed: %m", i->path);
648 if (!S_ISFIFO(st.st_mode)) {
649 log_error("%s is not a fifo.", i->path);
653 r = item_set_perms(i, i->path);
661 r = glob_item(i, item_set_perms);
666 case RECURSIVE_RELABEL_PATH:
668 r = glob_item(i, recursive_relabel);
673 log_debug("%s created successfully.", i->path);
678 static int remove_item_instance(Item *i, const char *instance) {
687 case CREATE_DIRECTORY:
691 case RECURSIVE_RELABEL_PATH:
695 if (remove(instance) < 0 && errno != ENOENT) {
696 log_error("remove(%s): %m", instance);
702 case TRUNCATE_DIRECTORY:
703 case RECURSIVE_REMOVE_PATH:
704 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
706 log_error("rm_rf(%s): %s", instance, strerror(-r));
716 static int remove_item(Item *i) {
725 case CREATE_DIRECTORY:
729 case RECURSIVE_RELABEL_PATH:
733 case TRUNCATE_DIRECTORY:
734 case RECURSIVE_REMOVE_PATH:
735 r = glob_item(i, remove_item_instance);
742 static int process_item(Item *i) {
747 r = arg_create ? create_item(i) : 0;
748 q = arg_remove ? remove_item(i) : 0;
749 p = arg_clean ? clean_item(i) : 0;
760 static void item_free(Item *i) {
767 static bool item_equal(Item *a, Item *b) {
771 if (!streq_ptr(a->path, b->path))
774 if (a->type != b->type)
777 if (a->uid_set != b->uid_set ||
778 (a->uid_set && a->uid != b->uid))
781 if (a->gid_set != b->gid_set ||
782 (a->gid_set && a->gid != b->gid))
785 if (a->mode_set != b->mode_set ||
786 (a->mode_set && a->mode != b->mode))
789 if (a->age_set != b->age_set ||
790 (a->age_set && a->age != b->age))
796 static int parse_line(const char *fname, unsigned line, const char *buffer) {
798 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
807 if (!(i = new0(Item, 1))) {
808 log_error("Out of memory");
825 log_error("[%s:%u] Syntax error.", fname, line);
833 case CREATE_DIRECTORY:
834 case TRUNCATE_DIRECTORY:
838 case RECURSIVE_REMOVE_PATH:
840 case RECURSIVE_RELABEL_PATH:
843 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
849 if (!path_is_absolute(i->path)) {
850 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
855 path_kill_slashes(i->path);
857 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
862 if (user && !streq(user, "-")) {
863 const char *u = user;
865 r = get_user_creds(&u, &i->uid, NULL, NULL);
867 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
874 if (group && !streq(group, "-")) {
875 const char *g = group;
877 r = get_group_creds(&g, &i->gid);
879 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
886 if (mode && !streq(mode, "-")) {
889 if (sscanf(mode, "%o", &m) != 1) {
890 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
898 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
900 if (age && !streq(age, "-")) {
901 if (parse_usec(age, &i->age) < 0) {
902 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
910 h = needs_glob(i->type) ? globs : items;
912 if ((existing = hashmap_get(h, i->path))) {
914 /* Two identical items are fine */
915 if (!item_equal(existing, i))
916 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
922 if ((r = hashmap_put(h, i->path, i)) < 0) {
923 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
942 static int help(void) {
944 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
945 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
946 " -h --help Show this help\n"
947 " --create Create marked files/directories\n"
948 " --clean Clean up marked directories\n"
949 " --remove Remove marked files/directories\n"
950 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
951 program_invocation_short_name);
956 static int parse_argv(int argc, char *argv[]) {
965 static const struct option options[] = {
966 { "help", no_argument, NULL, 'h' },
967 { "create", no_argument, NULL, ARG_CREATE },
968 { "clean", no_argument, NULL, ARG_CLEAN },
969 { "remove", no_argument, NULL, ARG_REMOVE },
970 { "prefix", required_argument, NULL, ARG_PREFIX },
979 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1000 arg_prefix = optarg;
1007 log_error("Unknown option code %c", c);
1012 if (!arg_clean && !arg_create && !arg_remove) {
1013 log_error("You need to specify at least one of --clean, --create or --remove.");
1020 static int read_config_file(const char *fn, bool ignore_enoent) {
1027 if (!(f = fopen(fn, "re"))) {
1029 if (ignore_enoent && errno == ENOENT)
1032 log_error("Failed to open %s: %m", fn);
1036 log_debug("apply: %s\n", fn);
1038 char line[LINE_MAX], *l;
1041 if (!(fgets(line, sizeof(line), f)))
1047 if (*l == '#' || *l == 0)
1050 if ((k = parse_line(fn, v, l)) < 0)
1056 log_error("Failed to read from file %s: %m", fn);
1066 int main(int argc, char *argv[]) {
1071 r = parse_argv(argc, argv);
1073 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1075 log_set_target(LOG_TARGET_AUTO);
1076 log_parse_environment();
1083 items = hashmap_new(string_hash_func, string_compare_func);
1084 globs = hashmap_new(string_hash_func, string_compare_func);
1086 if (!items || !globs) {
1087 log_error("Out of memory");
1094 if (optind < argc) {
1097 for (j = optind; j < argc; j++)
1098 if (read_config_file(argv[j], false) < 0)
1104 r = conf_files_list(&files, ".conf",
1107 "/usr/local/lib/tmpfiles.d",
1108 "/usr/lib/tmpfiles.d",
1112 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1116 STRV_FOREACH(f, files) {
1117 if (read_config_file(*f, true) < 0)
1124 HASHMAP_FOREACH(i, globs, iterator)
1127 HASHMAP_FOREACH(i, items, iterator)
1131 while ((i = hashmap_steal_first(items)))
1134 while ((i = hashmap_steal_first(globs)))
1137 hashmap_free(items);
1138 hashmap_free(globs);
1140 set_free_free(unix_sockets);