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 if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
123 if (!(f = fopen("/proc/net/unix", "re")))
126 if (!(fgets(line, sizeof(line), f)))
133 if (!(fgets(line, sizeof(line), f)))
138 if (strlen(line) < 53)
142 p += strspn(p, WHITESPACE);
143 p += strcspn(p, WHITESPACE);
144 p += strspn(p, WHITESPACE);
149 if (!(s = strdup(p)))
152 path_kill_slashes(s);
154 if ((k = set_put(unix_sockets, s)) < 0) {
166 set_free_free(unix_sockets);
173 static bool unix_socket_alive(const char *fn) {
179 return !!set_get(unix_sockets, (char*) fn);
181 /* We don't know, so assume yes */
185 static int dir_cleanup(
188 const struct stat *ds,
195 struct timespec times[2];
196 bool deleted = false;
197 char *sub_path = NULL;
200 while ((dent = readdir(d))) {
204 if (streq(dent->d_name, ".") ||
205 streq(dent->d_name, ".."))
208 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
210 if (errno != ENOENT) {
211 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
218 /* Stay on the same filesystem */
219 if (s.st_dev != rootdev)
222 /* Do not delete read-only files owned by root */
223 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
229 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
230 log_error("Out of memory");
235 /* Is there an item configured for this path? */
236 if (hashmap_get(items, sub_path))
239 if (find_glob(globs, sub_path))
242 if (S_ISDIR(s.st_mode)) {
245 streq(dent->d_name, "lost+found") &&
250 log_warning("Reached max depth on %s.", sub_path);
255 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
256 if (sub_dir == NULL) {
257 if (errno != ENOENT) {
258 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
265 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
272 /* Ignore ctime, we change it when deleting */
273 age = MAX(timespec_load(&s.st_mtim),
274 timespec_load(&s.st_atim));
278 log_debug("rmdir '%s'\n", sub_path);
280 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
281 if (errno != ENOENT && errno != ENOTEMPTY) {
282 log_error("rmdir(%s): %m", sub_path);
288 /* Skip files for which the sticky bit is
289 * set. These are semantics we define, and are
290 * unknown elsewhere. See XDG_RUNTIME_DIR
291 * specification for details. */
292 if (s.st_mode & S_ISVTX)
295 if (mountpoint && S_ISREG(s.st_mode)) {
296 if (streq(dent->d_name, ".journal") &&
300 if (streq(dent->d_name, "aquota.user") ||
301 streq(dent->d_name, "aquota.group"))
305 /* Ignore sockets that are listed in /proc/net/unix */
306 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
309 /* Ignore device nodes */
310 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
313 age = MAX3(timespec_load(&s.st_mtim),
314 timespec_load(&s.st_atim),
315 timespec_load(&s.st_ctim));
320 log_debug("unlink '%s'\n", sub_path);
322 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
323 if (errno != ENOENT) {
324 log_error("unlink(%s): %m", sub_path);
335 /* Restore original directory timestamps */
336 times[0] = ds->st_atim;
337 times[1] = ds->st_mtim;
339 if (futimens(dirfd(d), times) < 0)
340 log_error("utimensat(%s): %m", p);
348 static int clean_item(Item *i) {
357 if (i->type != CREATE_DIRECTORY &&
358 i->type != TRUNCATE_DIRECTORY &&
359 i->type != IGNORE_PATH)
362 if (!i->age_set || i->age <= 0)
365 n = now(CLOCK_REALTIME);
371 d = opendir(i->path);
376 log_error("Failed to open directory %s: %m", i->path);
380 if (fstat(dirfd(d), &s) < 0) {
381 log_error("stat(%s) failed: %m", i->path);
386 if (!S_ISDIR(s.st_mode)) {
387 log_error("%s is not a directory.", i->path);
392 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
393 log_error("stat(%s/..) failed: %m", i->path);
398 mountpoint = s.st_dev != ps.st_dev ||
399 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
401 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
410 static int item_set_perms(Item *i, const char *path) {
411 /* not using i->path directly because it may be a glob */
413 if (chmod(path, i->mode) < 0) {
414 log_error("chmod(%s) failed: %m", path);
418 if (i->uid_set || i->gid_set)
420 i->uid_set ? i->uid : (uid_t) -1,
421 i->gid_set ? i->gid : (gid_t) -1) < 0) {
423 log_error("chown(%s) failed: %m", path);
427 return label_fix(path, false);
430 static int recursive_relabel_children(Item *i, const char *path) {
434 /* This returns the first error we run into, but nevertheless
439 return errno == ENOENT ? 0 : -errno;
442 struct dirent buf, *de;
447 r = readdir_r(d, &buf, &de);
457 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
460 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
466 if (de->d_type == DT_UNKNOWN) {
469 if (lstat(entry_path, &st) < 0) {
470 if (ret == 0 && errno != ENOENT)
476 is_dir = S_ISDIR(st.st_mode);
479 is_dir = de->d_type == DT_DIR;
481 r = item_set_perms(i, entry_path);
483 if (ret == 0 && r != -ENOENT)
490 r = recursive_relabel_children(i, entry_path);
491 if (r < 0 && ret == 0)
503 static int recursive_relabel(Item *i, const char *path) {
507 r = item_set_perms(i, path);
511 if (lstat(path, &st) < 0)
514 if (S_ISDIR(st.st_mode))
515 r = recursive_relabel_children(i, path);
520 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
528 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
530 if (k != GLOB_NOMATCH) {
534 log_error("glob(%s) failed: %m", i->path);
539 STRV_FOREACH(fn, g.gl_pathv)
540 if ((k = action(i, *fn)) < 0)
547 static int create_item(Item *i) {
558 case RECURSIVE_REMOVE_PATH:
562 case TRUNCATE_FILE: {
566 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
567 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
571 log_error("Failed to create file %s: %m", i->path);
575 close_nointr_nofail(fd);
577 if (stat(i->path, &st) < 0) {
578 log_error("stat(%s) failed: %m", i->path);
582 if (!S_ISREG(st.st_mode)) {
583 log_error("%s is not a file.", i->path);
587 r = item_set_perms(i, i->path);
594 case TRUNCATE_DIRECTORY:
595 case CREATE_DIRECTORY:
598 mkdir_parents(i->path, 0755);
599 r = mkdir(i->path, i->mode);
602 if (r < 0 && errno != EEXIST) {
603 log_error("Failed to create directory %s: %m", i->path);
607 if (stat(i->path, &st) < 0) {
608 log_error("stat(%s) failed: %m", i->path);
612 if (!S_ISDIR(st.st_mode)) {
613 log_error("%s is not a directory.", i->path);
617 r = item_set_perms(i, i->path);
626 r = mkfifo(i->path, i->mode);
629 if (r < 0 && errno != EEXIST) {
630 log_error("Failed to create fifo %s: %m", i->path);
634 if (stat(i->path, &st) < 0) {
635 log_error("stat(%s) failed: %m", i->path);
639 if (!S_ISFIFO(st.st_mode)) {
640 log_error("%s is not a fifo.", i->path);
644 r = item_set_perms(i, i->path);
652 r = glob_item(i, item_set_perms);
657 case RECURSIVE_RELABEL_PATH:
659 r = glob_item(i, recursive_relabel);
664 log_debug("%s created successfully.", i->path);
669 static int remove_item_instance(Item *i, const char *instance) {
678 case CREATE_DIRECTORY:
682 case RECURSIVE_RELABEL_PATH:
686 if (remove(instance) < 0 && errno != ENOENT) {
687 log_error("remove(%s): %m", instance);
693 case TRUNCATE_DIRECTORY:
694 case RECURSIVE_REMOVE_PATH:
695 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
697 log_error("rm_rf(%s): %s", instance, strerror(-r));
707 static int remove_item(Item *i) {
716 case CREATE_DIRECTORY:
720 case RECURSIVE_RELABEL_PATH:
724 case TRUNCATE_DIRECTORY:
725 case RECURSIVE_REMOVE_PATH:
726 r = glob_item(i, remove_item_instance);
733 static int process_item(Item *i) {
738 r = arg_create ? create_item(i) : 0;
739 q = arg_remove ? remove_item(i) : 0;
740 p = arg_clean ? clean_item(i) : 0;
751 static void item_free(Item *i) {
758 static bool item_equal(Item *a, Item *b) {
762 if (!streq_ptr(a->path, b->path))
765 if (a->type != b->type)
768 if (a->uid_set != b->uid_set ||
769 (a->uid_set && a->uid != b->uid))
772 if (a->gid_set != b->gid_set ||
773 (a->gid_set && a->gid != b->gid))
776 if (a->mode_set != b->mode_set ||
777 (a->mode_set && a->mode != b->mode))
780 if (a->age_set != b->age_set ||
781 (a->age_set && a->age != b->age))
787 static int parse_line(const char *fname, unsigned line, const char *buffer) {
789 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
798 if (!(i = new0(Item, 1))) {
799 log_error("Out of memory");
816 log_error("[%s:%u] Syntax error.", fname, line);
824 case CREATE_DIRECTORY:
825 case TRUNCATE_DIRECTORY:
829 case RECURSIVE_REMOVE_PATH:
831 case RECURSIVE_RELABEL_PATH:
834 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
840 if (!path_is_absolute(i->path)) {
841 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
846 path_kill_slashes(i->path);
848 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
853 if (user && !streq(user, "-")) {
854 const char *u = user;
856 r = get_user_creds(&u, &i->uid, NULL, NULL);
858 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
865 if (group && !streq(group, "-")) {
866 const char *g = group;
868 r = get_group_creds(&g, &i->gid);
870 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
877 if (mode && !streq(mode, "-")) {
880 if (sscanf(mode, "%o", &m) != 1) {
881 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
889 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
891 if (age && !streq(age, "-")) {
892 if (parse_usec(age, &i->age) < 0) {
893 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
901 h = needs_glob(i->type) ? globs : items;
903 if ((existing = hashmap_get(h, i->path))) {
905 /* Two identical items are fine */
906 if (!item_equal(existing, i))
907 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
913 if ((r = hashmap_put(h, i->path, i)) < 0) {
914 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
933 static int help(void) {
935 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
936 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
937 " -h --help Show this help\n"
938 " --create Create marked files/directories\n"
939 " --clean Clean up marked directories\n"
940 " --remove Remove marked files/directories\n"
941 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
942 program_invocation_short_name);
947 static int parse_argv(int argc, char *argv[]) {
956 static const struct option options[] = {
957 { "help", no_argument, NULL, 'h' },
958 { "create", no_argument, NULL, ARG_CREATE },
959 { "clean", no_argument, NULL, ARG_CLEAN },
960 { "remove", no_argument, NULL, ARG_REMOVE },
961 { "prefix", required_argument, NULL, ARG_PREFIX },
970 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
998 log_error("Unknown option code %c", c);
1003 if (!arg_clean && !arg_create && !arg_remove) {
1004 log_error("You need to specify at least one of --clean, --create or --remove.");
1011 static int read_config_file(const char *fn, bool ignore_enoent) {
1018 if (!(f = fopen(fn, "re"))) {
1020 if (ignore_enoent && errno == ENOENT)
1023 log_error("Failed to open %s: %m", fn);
1027 log_debug("apply: %s\n", fn);
1029 char line[LINE_MAX], *l;
1032 if (!(fgets(line, sizeof(line), f)))
1038 if (*l == '#' || *l == 0)
1041 if ((k = parse_line(fn, v, l)) < 0)
1047 log_error("Failed to read from file %s: %m", fn);
1057 int main(int argc, char *argv[]) {
1062 if ((r = parse_argv(argc, argv)) <= 0)
1063 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1065 log_set_target(LOG_TARGET_AUTO);
1066 log_parse_environment();
1073 items = hashmap_new(string_hash_func, string_compare_func);
1074 globs = hashmap_new(string_hash_func, string_compare_func);
1076 if (!items || !globs) {
1077 log_error("Out of memory");
1084 if (optind < argc) {
1087 for (j = optind; j < argc; j++)
1088 if (read_config_file(argv[j], false) < 0)
1094 r = conf_files_list(&files, ".conf",
1097 "/usr/local/lib/tmpfiles.d",
1098 "/usr/lib/tmpfiles.d",
1102 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1106 STRV_FOREACH(f, files) {
1107 if (read_config_file(*f, true) < 0)
1114 HASHMAP_FOREACH(i, globs, iterator)
1117 HASHMAP_FOREACH(i, items, iterator)
1121 while ((i = hashmap_steal_first(items)))
1124 while ((i = hashmap_steal_first(globs)))
1127 hashmap_free(items);
1128 hashmap_free(globs);
1130 set_free_free(unix_sockets);