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'
93 bool keep_first_level:1;
96 static Hashmap *items = NULL, *globs = NULL;
97 static Set *unix_sockets = NULL;
99 static bool arg_create = false;
100 static bool arg_clean = false;
101 static bool arg_remove = false;
103 static const char *arg_prefix = NULL;
105 static const char * const conf_file_dirs[] = {
108 "/usr/local/lib/tmpfiles.d",
109 "/usr/lib/tmpfiles.d",
110 #ifdef HAVE_SPLIT_USR
116 #define MAX_DEPTH 256
118 static bool needs_glob(ItemType t) {
119 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
122 static struct Item* find_glob(Hashmap *h, const char *match) {
126 HASHMAP_FOREACH(j, h, i)
127 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
133 static void load_unix_sockets(void) {
140 /* We maintain a cache of the sockets we found in
141 * /proc/net/unix to speed things up a little. */
143 unix_sockets = set_new(string_hash_func, string_compare_func);
147 f = fopen("/proc/net/unix", "re");
152 if (!fgets(line, sizeof(line), f))
159 if (!fgets(line, sizeof(line), f))
164 p = strchr(line, ':');
172 p += strspn(p, WHITESPACE);
173 p += strcspn(p, WHITESPACE); /* skip one more word */
174 p += strspn(p, WHITESPACE);
183 path_kill_slashes(s);
185 k = set_put(unix_sockets, s);
198 set_free_free(unix_sockets);
205 static bool unix_socket_alive(const char *fn) {
211 return !!set_get(unix_sockets, (char*) fn);
213 /* We don't know, so assume yes */
217 static int dir_cleanup(
220 const struct stat *ds,
225 bool keep_this_level)
228 struct timespec times[2];
229 bool deleted = false;
230 char *sub_path = NULL;
233 while ((dent = readdir(d))) {
237 if (streq(dent->d_name, ".") ||
238 streq(dent->d_name, ".."))
241 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
243 if (errno != ENOENT) {
244 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
251 /* Stay on the same filesystem */
252 if (s.st_dev != rootdev)
255 /* Do not delete read-only files owned by root */
256 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
262 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
263 log_error("Out of memory.");
268 /* Is there an item configured for this path? */
269 if (hashmap_get(items, sub_path))
272 if (find_glob(globs, sub_path))
275 if (S_ISDIR(s.st_mode)) {
278 streq(dent->d_name, "lost+found") &&
283 log_warning("Reached max depth on %s.", sub_path);
288 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
289 if (sub_dir == NULL) {
290 if (errno != ENOENT) {
291 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
298 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
305 /* Note: if you are wondering why we don't
306 * support the sticky bit for excluding
307 * directories from cleaning like we do it for
308 * other file system objects: well, the sticky
309 * bit already has a meaning for directories,
310 * so we don't want to overload that. */
315 /* Ignore ctime, we change it when deleting */
316 age = MAX(timespec_load(&s.st_mtim),
317 timespec_load(&s.st_atim));
321 log_debug("rmdir '%s'\n", sub_path);
323 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
324 if (errno != ENOENT && errno != ENOTEMPTY) {
325 log_error("rmdir(%s): %m", sub_path);
331 /* Skip files for which the sticky bit is
332 * set. These are semantics we define, and are
333 * unknown elsewhere. See XDG_RUNTIME_DIR
334 * specification for details. */
335 if (s.st_mode & S_ISVTX)
338 if (mountpoint && S_ISREG(s.st_mode)) {
339 if (streq(dent->d_name, ".journal") &&
343 if (streq(dent->d_name, "aquota.user") ||
344 streq(dent->d_name, "aquota.group"))
348 /* Ignore sockets that are listed in /proc/net/unix */
349 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
352 /* Ignore device nodes */
353 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
356 /* Keep files on this level around if this is
361 age = MAX3(timespec_load(&s.st_mtim),
362 timespec_load(&s.st_atim),
363 timespec_load(&s.st_ctim));
368 log_debug("unlink '%s'\n", sub_path);
370 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
371 if (errno != ENOENT) {
372 log_error("unlink(%s): %m", sub_path);
383 /* Restore original directory timestamps */
384 times[0] = ds->st_atim;
385 times[1] = ds->st_mtim;
387 if (futimens(dirfd(d), times) < 0)
388 log_error("utimensat(%s): %m", p);
396 static int clean_item(Item *i) {
405 if (i->type != CREATE_DIRECTORY &&
406 i->type != TRUNCATE_DIRECTORY &&
407 i->type != IGNORE_PATH)
410 if (!i->age_set || i->age <= 0)
413 n = now(CLOCK_REALTIME);
419 d = opendir(i->path);
424 log_error("Failed to open directory %s: %m", i->path);
428 if (fstat(dirfd(d), &s) < 0) {
429 log_error("stat(%s) failed: %m", i->path);
434 if (!S_ISDIR(s.st_mode)) {
435 log_error("%s is not a directory.", i->path);
440 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
441 log_error("stat(%s/..) failed: %m", i->path);
446 mountpoint = s.st_dev != ps.st_dev ||
447 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
449 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH, i->keep_first_level);
458 static int item_set_perms(Item *i, const char *path) {
459 /* not using i->path directly because it may be a glob */
461 if (chmod(path, i->mode) < 0) {
462 log_error("chmod(%s) failed: %m", path);
466 if (i->uid_set || i->gid_set)
468 i->uid_set ? i->uid : (uid_t) -1,
469 i->gid_set ? i->gid : (gid_t) -1) < 0) {
471 log_error("chown(%s) failed: %m", path);
475 return label_fix(path, false, false);
478 static int recursive_relabel_children(Item *i, const char *path) {
482 /* This returns the first error we run into, but nevertheless
487 return errno == ENOENT ? 0 : -errno;
490 struct dirent buf, *de;
495 r = readdir_r(d, &buf, &de);
505 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
508 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
514 if (de->d_type == DT_UNKNOWN) {
517 if (lstat(entry_path, &st) < 0) {
518 if (ret == 0 && errno != ENOENT)
524 is_dir = S_ISDIR(st.st_mode);
527 is_dir = de->d_type == DT_DIR;
529 r = item_set_perms(i, entry_path);
531 if (ret == 0 && r != -ENOENT)
538 r = recursive_relabel_children(i, entry_path);
539 if (r < 0 && ret == 0)
551 static int recursive_relabel(Item *i, const char *path) {
555 r = item_set_perms(i, path);
559 if (lstat(path, &st) < 0)
562 if (S_ISDIR(st.st_mode))
563 r = recursive_relabel_children(i, path);
568 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
576 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
578 if (k != GLOB_NOMATCH) {
582 log_error("glob(%s) failed: %m", i->path);
587 STRV_FOREACH(fn, g.gl_pathv)
588 if ((k = action(i, *fn)) < 0)
595 static int create_item(Item *i) {
606 case RECURSIVE_REMOVE_PATH:
614 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
615 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
618 label_context_set(i->path, S_IFREG);
619 fd = open(i->path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
621 label_context_clear();
626 if (i->type == WRITE_FILE && errno == ENOENT)
629 log_error("Failed to create file %s: %m", i->path);
636 struct iovec iovec[2];
637 static const char new_line = '\n';
639 l = strlen(i->argument);
642 iovec[0].iov_base = i->argument;
643 iovec[0].iov_len = l;
645 iovec[1].iov_base = (void*) &new_line;
646 iovec[1].iov_len = 1;
648 n = writev(fd, iovec, 2);
650 /* It's OK if we don't write the trailing
651 * newline, hence we check for l, instead of
652 * l+1 here. Files in /sys often refuse
653 * writing of the trailing newline. */
654 if (n < 0 || (size_t) n < l) {
655 log_error("Failed to write file %s: %s", i->path, n < 0 ? strerror(-n) : "Short write");
656 close_nointr_nofail(fd);
657 return n < 0 ? n : -EIO;
661 close_nointr_nofail(fd);
663 if (stat(i->path, &st) < 0) {
664 log_error("stat(%s) failed: %m", i->path);
668 if (!S_ISREG(st.st_mode)) {
669 log_error("%s is not a file.", i->path);
673 r = item_set_perms(i, i->path);
680 case TRUNCATE_DIRECTORY:
681 case CREATE_DIRECTORY:
684 mkdir_parents_label(i->path, 0755);
685 r = mkdir(i->path, i->mode);
688 if (r < 0 && errno != EEXIST) {
689 log_error("Failed to create directory %s: %m", i->path);
693 if (stat(i->path, &st) < 0) {
694 log_error("stat(%s) failed: %m", i->path);
698 if (!S_ISDIR(st.st_mode)) {
699 log_error("%s is not a directory.", i->path);
703 r = item_set_perms(i, i->path);
712 r = mkfifo(i->path, i->mode);
715 if (r < 0 && errno != EEXIST) {
716 log_error("Failed to create fifo %s: %m", i->path);
720 if (stat(i->path, &st) < 0) {
721 log_error("stat(%s) failed: %m", i->path);
725 if (!S_ISFIFO(st.st_mode)) {
726 log_error("%s is not a fifo.", i->path);
730 r = item_set_perms(i, i->path);
736 case CREATE_SYMLINK: {
739 label_context_set(i->path, S_IFLNK);
740 r = symlink(i->argument, i->path);
742 label_context_clear();
745 if (r < 0 && errno != EEXIST) {
746 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
750 r = readlink_malloc(i->path, &x);
752 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
756 if (!streq(i->argument, x)) {
758 log_error("%s is not the right symlinks.", i->path);
766 case CREATE_BLOCK_DEVICE:
767 case CREATE_CHAR_DEVICE: {
768 mode_t file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
771 label_context_set(i->path, file_type);
772 r = mknod(i->path, i->mode | file_type, i->major_minor);
774 label_context_clear();
778 if (r < 0 && errno != EEXIST) {
779 log_error("Failed to create device node %s: %m", i->path);
783 if (stat(i->path, &st) < 0) {
784 log_error("stat(%s) failed: %m", i->path);
788 if ((st.st_mode & S_IFMT) != file_type) {
789 log_error("%s is not a device node.", i->path);
793 r = item_set_perms(i, i->path);
802 r = glob_item(i, item_set_perms);
807 case RECURSIVE_RELABEL_PATH:
809 r = glob_item(i, recursive_relabel);
814 log_debug("%s created successfully.", i->path);
819 static int remove_item_instance(Item *i, const char *instance) {
828 case CREATE_DIRECTORY:
831 case CREATE_BLOCK_DEVICE:
832 case CREATE_CHAR_DEVICE:
835 case RECURSIVE_RELABEL_PATH:
840 if (remove(instance) < 0 && errno != ENOENT) {
841 log_error("remove(%s): %m", instance);
847 case TRUNCATE_DIRECTORY:
848 case RECURSIVE_REMOVE_PATH:
849 /* FIXME: we probably should use dir_cleanup() here
850 * instead of rm_rf() so that 'x' is honoured. */
851 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
852 if (r < 0 && r != -ENOENT) {
853 log_error("rm_rf(%s): %s", instance, strerror(-r));
863 static int remove_item(Item *i) {
872 case CREATE_DIRECTORY:
875 case CREATE_CHAR_DEVICE:
876 case CREATE_BLOCK_DEVICE:
879 case RECURSIVE_RELABEL_PATH:
884 case TRUNCATE_DIRECTORY:
885 case RECURSIVE_REMOVE_PATH:
886 r = glob_item(i, remove_item_instance);
893 static int process_item(Item *i) {
898 r = arg_create ? create_item(i) : 0;
899 q = arg_remove ? remove_item(i) : 0;
900 p = arg_clean ? clean_item(i) : 0;
911 static void item_free(Item *i) {
919 static bool item_equal(Item *a, Item *b) {
923 if (!streq_ptr(a->path, b->path))
926 if (a->type != b->type)
929 if (a->uid_set != b->uid_set ||
930 (a->uid_set && a->uid != b->uid))
933 if (a->gid_set != b->gid_set ||
934 (a->gid_set && a->gid != b->gid))
937 if (a->mode_set != b->mode_set ||
938 (a->mode_set && a->mode != b->mode))
941 if (a->age_set != b->age_set ||
942 (a->age_set && a->age != b->age))
945 if ((a->type == CREATE_FILE ||
946 a->type == TRUNCATE_FILE ||
947 a->type == WRITE_FILE ||
948 a->type == CREATE_SYMLINK) &&
949 !streq_ptr(a->argument, b->argument))
952 if ((a->type == CREATE_CHAR_DEVICE ||
953 a->type == CREATE_BLOCK_DEVICE) &&
954 a->major_minor != b->major_minor)
960 static int parse_line(const char *fname, unsigned line, const char *buffer) {
962 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
973 log_error("Out of memory.");
992 log_error("[%s:%u] Syntax error.", fname, line);
998 n += strspn(buffer+n, WHITESPACE);
999 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1000 i->argument = unquote(buffer+n, "\"");
1002 log_error("Out of memory.");
1012 case CREATE_DIRECTORY:
1013 case TRUNCATE_DIRECTORY:
1017 case RECURSIVE_REMOVE_PATH:
1019 case RECURSIVE_RELABEL_PATH:
1022 case CREATE_SYMLINK:
1024 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1032 log_error("[%s:%u] Write file requires argument.", fname, line);
1038 case CREATE_CHAR_DEVICE:
1039 case CREATE_BLOCK_DEVICE: {
1040 unsigned major, minor;
1043 log_error("[%s:%u] Device file requires argument.", fname, line);
1048 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1049 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1054 i->major_minor = makedev(major, minor);
1059 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1066 if (!path_is_absolute(i->path)) {
1067 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1072 path_kill_slashes(i->path);
1074 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1079 if (user && !streq(user, "-")) {
1080 const char *u = user;
1082 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1084 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1091 if (group && !streq(group, "-")) {
1092 const char *g = group;
1094 r = get_group_creds(&g, &i->gid);
1096 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1103 if (mode && !streq(mode, "-")) {
1106 if (sscanf(mode, "%o", &m) != 1) {
1107 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1116 i->type == CREATE_DIRECTORY ||
1117 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1119 if (age && !streq(age, "-")) {
1120 const char *a = age;
1123 i->keep_first_level = true;
1127 if (parse_usec(a, &i->age) < 0) {
1128 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1136 h = needs_glob(i->type) ? globs : items;
1138 existing = hashmap_get(h, i->path);
1141 /* Two identical items are fine */
1142 if (!item_equal(existing, i))
1143 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1149 r = hashmap_put(h, i->path, i);
1151 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1170 static int help(void) {
1172 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1173 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1174 " -h --help Show this help\n"
1175 " --create Create marked files/directories\n"
1176 " --clean Clean up marked directories\n"
1177 " --remove Remove marked files/directories\n"
1178 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1179 program_invocation_short_name);
1184 static int parse_argv(int argc, char *argv[]) {
1193 static const struct option options[] = {
1194 { "help", no_argument, NULL, 'h' },
1195 { "create", no_argument, NULL, ARG_CREATE },
1196 { "clean", no_argument, NULL, ARG_CLEAN },
1197 { "remove", no_argument, NULL, ARG_REMOVE },
1198 { "prefix", required_argument, NULL, ARG_PREFIX },
1199 { NULL, 0, NULL, 0 }
1207 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1228 arg_prefix = optarg;
1235 log_error("Unknown option code %c", c);
1240 if (!arg_clean && !arg_create && !arg_remove) {
1241 log_error("You need to specify at least one of --clean, --create or --remove.");
1248 static int read_config_file(const char *fn, bool ignore_enoent) {
1255 f = fopen(fn, "re");
1258 if (ignore_enoent && errno == ENOENT)
1261 log_error("Failed to open %s: %m", fn);
1265 log_debug("apply: %s\n", fn);
1267 char line[LINE_MAX], *l;
1270 if (!(fgets(line, sizeof(line), f)))
1276 if (*l == '#' || *l == 0)
1279 if ((k = parse_line(fn, v, l)) < 0)
1285 log_error("Failed to read from file %s: %m", fn);
1295 static char *resolve_fragment(const char *fragment, const char **search_paths) {
1297 char *resolved_path;
1299 if (is_path(fragment))
1300 return strdup(fragment);
1302 STRV_FOREACH(p, search_paths) {
1303 resolved_path = strjoin(*p, "/", fragment, NULL);
1304 if (resolved_path == NULL) {
1305 log_error("Out of memory.");
1309 if (access(resolved_path, F_OK) == 0)
1310 return resolved_path;
1312 free(resolved_path);
1319 int main(int argc, char *argv[]) {
1324 r = parse_argv(argc, argv);
1326 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1328 log_set_target(LOG_TARGET_AUTO);
1329 log_parse_environment();
1336 items = hashmap_new(string_hash_func, string_compare_func);
1337 globs = hashmap_new(string_hash_func, string_compare_func);
1339 if (!items || !globs) {
1340 log_error("Out of memory.");
1347 if (optind < argc) {
1350 for (j = optind; j < argc; j++) {
1353 fragment = resolve_fragment(argv[j], (const char**) conf_file_dirs);
1355 log_error("Failed to find a %s file: %m", argv[j]);
1359 if (read_config_file(fragment, false) < 0)
1367 r = conf_files_list_strv(&files, ".conf",
1368 (const char **) conf_file_dirs);
1370 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1375 STRV_FOREACH(f, files) {
1376 if (read_config_file(*f, true) < 0)
1383 HASHMAP_FOREACH(i, globs, iterator)
1386 HASHMAP_FOREACH(i, items, iterator)
1390 while ((i = hashmap_steal_first(items)))
1393 while ((i = hashmap_steal_first(globs)))
1396 hashmap_free(items);
1397 hashmap_free(globs);
1399 set_free_free(unix_sockets);