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>
41 #include <sys/capability.h>
47 #include "path-util.h"
51 #include "conf-files.h"
52 #include "capability.h"
54 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
55 * them in the file system. This is intended to be used to create
56 * properly owned directories beneath /tmp, /var/tmp, /run, which are
57 * volatile and hence need to be recreated on bootup. */
59 typedef enum ItemType {
60 /* These ones take file names */
64 CREATE_DIRECTORY = 'd',
65 TRUNCATE_DIRECTORY = 'D',
68 CREATE_CHAR_DEVICE = 'c',
69 CREATE_BLOCK_DEVICE = 'b',
71 /* These ones take globs */
73 IGNORE_DIRECTORY_PATH = 'X',
75 RECURSIVE_REMOVE_PATH = 'R',
77 RECURSIVE_RELABEL_PATH = 'Z'
97 bool keep_first_level:1;
100 static Hashmap *items = NULL, *globs = NULL;
101 static Set *unix_sockets = NULL;
103 static bool arg_create = false;
104 static bool arg_clean = false;
105 static bool arg_remove = false;
107 static const char *arg_prefix = NULL;
109 static const char conf_file_dirs[] =
112 "/usr/local/lib/tmpfiles.d\0"
113 "/usr/lib/tmpfiles.d\0"
114 #ifdef HAVE_SPLIT_USR
119 #define MAX_DEPTH 256
121 static bool needs_glob(ItemType t) {
122 return t == IGNORE_PATH || t == IGNORE_DIRECTORY_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
125 static struct Item* find_glob(Hashmap *h, const char *match) {
129 HASHMAP_FOREACH(j, h, i)
130 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
136 static void load_unix_sockets(void) {
143 /* We maintain a cache of the sockets we found in
144 * /proc/net/unix to speed things up a little. */
146 unix_sockets = set_new(string_hash_func, string_compare_func);
150 f = fopen("/proc/net/unix", "re");
155 if (!fgets(line, sizeof(line), f))
162 if (!fgets(line, sizeof(line), f))
167 p = strchr(line, ':');
175 p += strspn(p, WHITESPACE);
176 p += strcspn(p, WHITESPACE); /* skip one more word */
177 p += strspn(p, WHITESPACE);
186 path_kill_slashes(s);
188 k = set_put(unix_sockets, s);
201 set_free_free(unix_sockets);
208 static bool unix_socket_alive(const char *fn) {
214 return !!set_get(unix_sockets, (char*) fn);
216 /* We don't know, so assume yes */
220 static int dir_cleanup(
224 const struct stat *ds,
229 bool keep_this_level)
232 struct timespec times[2];
233 bool deleted = false;
234 char *sub_path = NULL;
237 while ((dent = readdir(d))) {
241 if (streq(dent->d_name, ".") ||
242 streq(dent->d_name, ".."))
245 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
247 if (errno != ENOENT) {
248 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
255 /* Stay on the same filesystem */
256 if (s.st_dev != rootdev)
259 /* Do not delete read-only files owned by root */
260 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
266 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
271 /* Is there an item configured for this path? */
272 if (hashmap_get(items, sub_path))
275 if (find_glob(globs, sub_path))
278 if (S_ISDIR(s.st_mode)) {
281 streq(dent->d_name, "lost+found") &&
286 log_warning("Reached max depth on %s.", sub_path);
291 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
292 if (sub_dir == NULL) {
293 if (errno != ENOENT) {
294 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
301 q = dir_cleanup(i, sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
308 /* Note: if you are wondering why we don't
309 * support the sticky bit for excluding
310 * directories from cleaning like we do it for
311 * other file system objects: well, the sticky
312 * bit already has a meaning for directories,
313 * so we don't want to overload that. */
318 /* Ignore ctime, we change it when deleting */
319 age = MAX(timespec_load(&s.st_mtim),
320 timespec_load(&s.st_atim));
324 if (!i->type == IGNORE_DIRECTORY_PATH || !streq(dent->d_name, p)) {
325 log_debug("rmdir '%s'\n", sub_path);
327 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
328 if (errno != ENOENT && errno != ENOTEMPTY) {
329 log_error("rmdir(%s): %m", sub_path);
336 /* Skip files for which the sticky bit is
337 * set. These are semantics we define, and are
338 * unknown elsewhere. See XDG_RUNTIME_DIR
339 * specification for details. */
340 if (s.st_mode & S_ISVTX)
343 if (mountpoint && S_ISREG(s.st_mode)) {
344 if (streq(dent->d_name, ".journal") &&
348 if (streq(dent->d_name, "aquota.user") ||
349 streq(dent->d_name, "aquota.group"))
353 /* Ignore sockets that are listed in /proc/net/unix */
354 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
357 /* Ignore device nodes */
358 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
361 /* Keep files on this level around if this is
366 age = MAX3(timespec_load(&s.st_mtim),
367 timespec_load(&s.st_atim),
368 timespec_load(&s.st_ctim));
373 log_debug("unlink '%s'\n", sub_path);
375 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
376 if (errno != ENOENT) {
377 log_error("unlink(%s): %m", sub_path);
388 /* Restore original directory timestamps */
389 times[0] = ds->st_atim;
390 times[1] = ds->st_mtim;
392 if (futimens(dirfd(d), times) < 0)
393 log_error("utimensat(%s): %m", p);
401 static int item_set_perms(Item *i, const char *path) {
402 /* not using i->path directly because it may be a glob */
404 if (chmod(path, i->mode) < 0) {
405 log_error("chmod(%s) failed: %m", path);
409 if (i->uid_set || i->gid_set)
411 i->uid_set ? i->uid : (uid_t) -1,
412 i->gid_set ? i->gid : (gid_t) -1) < 0) {
414 log_error("chown(%s) failed: %m", path);
418 return label_fix(path, false, false);
421 static int write_one_file(Item *i, const char *path) {
426 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
427 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
430 label_context_set(path, S_IFREG);
431 fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
433 label_context_clear();
438 if (i->type == WRITE_FILE && errno == ENOENT)
441 log_error("Failed to create file %s: %m", path);
448 _cleanup_free_ char *unescaped;
450 unescaped = cunescape(i->argument);
451 if (unescaped == NULL) {
452 close_nointr_nofail(fd);
456 l = strlen(unescaped);
457 n = write(fd, unescaped, l);
459 if (n < 0 || (size_t) n < l) {
460 log_error("Failed to write file %s: %s", path, n < 0 ? strerror(-n) : "Short write");
461 close_nointr_nofail(fd);
462 return n < 0 ? n : -EIO;
466 close_nointr_nofail(fd);
468 if (stat(path, &st) < 0) {
469 log_error("stat(%s) failed: %m", path);
473 if (!S_ISREG(st.st_mode)) {
474 log_error("%s is not a file.", path);
478 r = item_set_perms(i, path);
485 static int recursive_relabel_children(Item *i, const char *path) {
489 /* This returns the first error we run into, but nevertheless
494 return errno == ENOENT ? 0 : -errno;
498 union dirent_storage buf;
503 r = readdir_r(d, &buf.de, &de);
513 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
516 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
522 if (de->d_type == DT_UNKNOWN) {
525 if (lstat(entry_path, &st) < 0) {
526 if (ret == 0 && errno != ENOENT)
532 is_dir = S_ISDIR(st.st_mode);
535 is_dir = de->d_type == DT_DIR;
537 r = item_set_perms(i, entry_path);
539 if (ret == 0 && r != -ENOENT)
546 r = recursive_relabel_children(i, entry_path);
547 if (r < 0 && ret == 0)
559 static int recursive_relabel(Item *i, const char *path) {
563 r = item_set_perms(i, path);
567 if (lstat(path, &st) < 0)
570 if (S_ISDIR(st.st_mode))
571 r = recursive_relabel_children(i, path);
576 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
584 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
586 if (k != GLOB_NOMATCH) {
590 log_error("glob(%s) failed: %m", i->path);
595 STRV_FOREACH(fn, g.gl_pathv)
596 if ((k = action(i, *fn)) < 0)
603 static int create_item(Item *i) {
613 case IGNORE_DIRECTORY_PATH:
615 case RECURSIVE_REMOVE_PATH:
620 r = write_one_file(i, i->path);
625 r = glob_item(i, write_one_file);
631 case TRUNCATE_DIRECTORY:
632 case CREATE_DIRECTORY:
635 mkdir_parents_label(i->path, 0755);
636 r = mkdir(i->path, i->mode);
639 if (r < 0 && errno != EEXIST) {
640 log_error("Failed to create directory %s: %m", i->path);
644 if (stat(i->path, &st) < 0) {
645 log_error("stat(%s) failed: %m", i->path);
649 if (!S_ISDIR(st.st_mode)) {
650 log_error("%s is not a directory.", i->path);
654 r = item_set_perms(i, i->path);
663 r = mkfifo(i->path, i->mode);
666 if (r < 0 && errno != EEXIST) {
667 log_error("Failed to create fifo %s: %m", i->path);
671 if (stat(i->path, &st) < 0) {
672 log_error("stat(%s) failed: %m", i->path);
676 if (!S_ISFIFO(st.st_mode)) {
677 log_error("%s is not a fifo.", i->path);
681 r = item_set_perms(i, i->path);
687 case CREATE_SYMLINK: {
690 label_context_set(i->path, S_IFLNK);
691 r = symlink(i->argument, i->path);
693 label_context_clear();
696 if (r < 0 && errno != EEXIST) {
697 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
701 r = readlink_malloc(i->path, &x);
703 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
707 if (!streq(i->argument, x)) {
709 log_error("%s is not the right symlinks.", i->path);
717 case CREATE_BLOCK_DEVICE:
718 case CREATE_CHAR_DEVICE: {
721 if (have_effective_cap(CAP_MKNOD) == 0) {
722 /* In a container we lack CAP_MKNOD. We
723 shouldnt attempt to create the device node in
724 that case to avoid noise, and we don't support
725 virtualized devices in containers anyway. */
727 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
731 file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
734 label_context_set(i->path, file_type);
735 r = mknod(i->path, i->mode | file_type, i->major_minor);
737 label_context_clear();
741 if (r < 0 && errno != EEXIST) {
742 log_error("Failed to create device node %s: %m", i->path);
746 if (stat(i->path, &st) < 0) {
747 log_error("stat(%s) failed: %m", i->path);
751 if ((st.st_mode & S_IFMT) != file_type) {
752 log_error("%s is not a device node.", i->path);
756 r = item_set_perms(i, i->path);
765 r = glob_item(i, item_set_perms);
770 case RECURSIVE_RELABEL_PATH:
772 r = glob_item(i, recursive_relabel);
777 log_debug("%s created successfully.", i->path);
782 static int remove_item_instance(Item *i, const char *instance) {
791 case CREATE_DIRECTORY:
794 case CREATE_BLOCK_DEVICE:
795 case CREATE_CHAR_DEVICE:
797 case IGNORE_DIRECTORY_PATH:
799 case RECURSIVE_RELABEL_PATH:
804 if (remove(instance) < 0 && errno != ENOENT) {
805 log_error("remove(%s): %m", instance);
811 case TRUNCATE_DIRECTORY:
812 case RECURSIVE_REMOVE_PATH:
813 /* FIXME: we probably should use dir_cleanup() here
814 * instead of rm_rf() so that 'x' is honoured. */
815 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
816 if (r < 0 && r != -ENOENT) {
817 log_error("rm_rf(%s): %s", instance, strerror(-r));
827 static int remove_item(Item *i) {
836 case CREATE_DIRECTORY:
839 case CREATE_CHAR_DEVICE:
840 case CREATE_BLOCK_DEVICE:
842 case IGNORE_DIRECTORY_PATH:
844 case RECURSIVE_RELABEL_PATH:
849 case TRUNCATE_DIRECTORY:
850 case RECURSIVE_REMOVE_PATH:
851 r = glob_item(i, remove_item_instance);
858 static int clean_item_instance(Item *i, const char* instance) {
870 n = now(CLOCK_REALTIME);
876 d = opendir(instance);
878 if (errno == ENOENT || errno == ENOTDIR)
881 log_error("Failed to open directory %s: %m", i->path);
885 if (fstat(dirfd(d), &s) < 0) {
886 log_error("stat(%s) failed: %m", i->path);
891 if (!S_ISDIR(s.st_mode)) {
892 log_error("%s is not a directory.", i->path);
897 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
898 log_error("stat(%s/..) failed: %m", i->path);
903 mountpoint = s.st_dev != ps.st_dev ||
904 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
906 r = dir_cleanup(i, instance, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH, i->keep_first_level);
915 static int clean_item(Item *i) {
921 case CREATE_DIRECTORY:
922 case TRUNCATE_DIRECTORY:
924 clean_item_instance(i, i->path);
926 case IGNORE_DIRECTORY_PATH:
927 r = glob_item(i, clean_item_instance);
936 static int process_item(Item *i) {
941 r = arg_create ? create_item(i) : 0;
942 q = arg_remove ? remove_item(i) : 0;
943 p = arg_clean ? clean_item(i) : 0;
954 static void item_free(Item *i) {
962 static bool item_equal(Item *a, Item *b) {
966 if (!streq_ptr(a->path, b->path))
969 if (a->type != b->type)
972 if (a->uid_set != b->uid_set ||
973 (a->uid_set && a->uid != b->uid))
976 if (a->gid_set != b->gid_set ||
977 (a->gid_set && a->gid != b->gid))
980 if (a->mode_set != b->mode_set ||
981 (a->mode_set && a->mode != b->mode))
984 if (a->age_set != b->age_set ||
985 (a->age_set && a->age != b->age))
988 if ((a->type == CREATE_FILE ||
989 a->type == TRUNCATE_FILE ||
990 a->type == WRITE_FILE ||
991 a->type == CREATE_SYMLINK) &&
992 !streq_ptr(a->argument, b->argument))
995 if ((a->type == CREATE_CHAR_DEVICE ||
996 a->type == CREATE_BLOCK_DEVICE) &&
997 a->major_minor != b->major_minor)
1003 static int parse_line(const char *fname, unsigned line, const char *buffer) {
1005 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
1033 log_error("[%s:%u] Syntax error.", fname, line);
1039 n += strspn(buffer+n, WHITESPACE);
1040 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1041 i->argument = unquote(buffer+n, "\"");
1051 case CREATE_DIRECTORY:
1052 case TRUNCATE_DIRECTORY:
1055 case IGNORE_DIRECTORY_PATH:
1057 case RECURSIVE_REMOVE_PATH:
1059 case RECURSIVE_RELABEL_PATH:
1062 case CREATE_SYMLINK:
1064 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1072 log_error("[%s:%u] Write file requires argument.", fname, line);
1078 case CREATE_CHAR_DEVICE:
1079 case CREATE_BLOCK_DEVICE: {
1080 unsigned major, minor;
1083 log_error("[%s:%u] Device file requires argument.", fname, line);
1088 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1089 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1094 i->major_minor = makedev(major, minor);
1099 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1106 if (!path_is_absolute(i->path)) {
1107 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1112 path_kill_slashes(i->path);
1114 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1119 if (user && !streq(user, "-")) {
1120 const char *u = user;
1122 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1124 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1131 if (group && !streq(group, "-")) {
1132 const char *g = group;
1134 r = get_group_creds(&g, &i->gid);
1136 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1143 if (mode && !streq(mode, "-")) {
1146 if (sscanf(mode, "%o", &m) != 1) {
1147 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1156 i->type == CREATE_DIRECTORY ||
1157 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1159 if (age && !streq(age, "-")) {
1160 const char *a = age;
1163 i->keep_first_level = true;
1167 if (parse_usec(a, &i->age) < 0) {
1168 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1176 h = needs_glob(i->type) ? globs : items;
1178 existing = hashmap_get(h, i->path);
1181 /* Two identical items are fine */
1182 if (!item_equal(existing, i))
1183 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1189 r = hashmap_put(h, i->path, i);
1191 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1210 static int help(void) {
1212 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1213 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1214 " -h --help Show this help\n"
1215 " --create Create marked files/directories\n"
1216 " --clean Clean up marked directories\n"
1217 " --remove Remove marked files/directories\n"
1218 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1219 program_invocation_short_name);
1224 static int parse_argv(int argc, char *argv[]) {
1233 static const struct option options[] = {
1234 { "help", no_argument, NULL, 'h' },
1235 { "create", no_argument, NULL, ARG_CREATE },
1236 { "clean", no_argument, NULL, ARG_CLEAN },
1237 { "remove", no_argument, NULL, ARG_REMOVE },
1238 { "prefix", required_argument, NULL, ARG_PREFIX },
1239 { NULL, 0, NULL, 0 }
1247 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1268 arg_prefix = optarg;
1275 log_error("Unknown option code %c", c);
1280 if (!arg_clean && !arg_create && !arg_remove) {
1281 log_error("You need to specify at least one of --clean, --create or --remove.");
1288 static int read_config_file(const char *fn, bool ignore_enoent) {
1297 r = search_and_fopen_nulstr(fn, "re", conf_file_dirs, &f);
1299 if (ignore_enoent && r == -ENOENT)
1302 log_error("Failed to open '%s', ignoring: %s", fn, strerror(-r));
1306 log_debug("apply: %s\n", fn);
1308 char line[LINE_MAX], *l;
1311 if (!(fgets(line, sizeof(line), f)))
1317 if (*l == '#' || *l == 0)
1320 if ((k = parse_line(fn, v, l)) < 0)
1325 /* we have to determine age parameter for each entry of type X */
1326 HASHMAP_FOREACH(i, globs, iterator) {
1328 Item *j, *candidate_item = NULL;
1330 if (i->type != IGNORE_DIRECTORY_PATH)
1333 HASHMAP_FOREACH(j, items, iter) {
1334 if (j->type != CREATE_DIRECTORY && j->type != TRUNCATE_DIRECTORY)
1337 if (path_equal(j->path, i->path)) {
1342 if ((!candidate_item && path_startswith(i->path, j->path)) ||
1343 (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
1347 if (candidate_item) {
1348 i->age = candidate_item->age;
1354 log_error("Failed to read from file %s: %m", fn);
1364 int main(int argc, char *argv[]) {
1369 r = parse_argv(argc, argv);
1371 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1373 log_set_target(LOG_TARGET_AUTO);
1374 log_parse_environment();
1381 items = hashmap_new(string_hash_func, string_compare_func);
1382 globs = hashmap_new(string_hash_func, string_compare_func);
1384 if (!items || !globs) {
1391 if (optind < argc) {
1394 for (j = optind; j < argc; j++) {
1395 k = read_config_file(argv[j], false);
1396 if (k < 0 && r == 0)
1401 _cleanup_strv_free_ char **files = NULL;
1404 r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
1406 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1410 STRV_FOREACH(f, files) {
1411 k = read_config_file(*f, true);
1412 if (k < 0 && r == 0)
1417 HASHMAP_FOREACH(i, globs, iterator)
1420 HASHMAP_FOREACH(i, items, iterator)
1424 while ((i = hashmap_steal_first(items)))
1427 while ((i = hashmap_steal_first(globs)))
1430 hashmap_free(items);
1431 hashmap_free(globs);
1433 set_free_free(unix_sockets);
1437 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;