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 */
74 RECURSIVE_REMOVE_PATH = 'R',
76 RECURSIVE_RELABEL_PATH = 'Z'
96 bool keep_first_level:1;
99 static Hashmap *items = NULL, *globs = NULL;
100 static Set *unix_sockets = NULL;
102 static bool arg_create = false;
103 static bool arg_clean = false;
104 static bool arg_remove = false;
106 static const char *arg_prefix = NULL;
108 static const char * const conf_file_dirs[] = {
111 "/usr/local/lib/tmpfiles.d",
112 "/usr/lib/tmpfiles.d",
113 #ifdef HAVE_SPLIT_USR
119 #define MAX_DEPTH 256
121 static bool needs_glob(ItemType t) {
122 return t == IGNORE_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(
223 const struct stat *ds,
228 bool keep_this_level)
231 struct timespec times[2];
232 bool deleted = false;
233 char *sub_path = NULL;
236 while ((dent = readdir(d))) {
240 if (streq(dent->d_name, ".") ||
241 streq(dent->d_name, ".."))
244 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
246 if (errno != ENOENT) {
247 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
254 /* Stay on the same filesystem */
255 if (s.st_dev != rootdev)
258 /* Do not delete read-only files owned by root */
259 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
265 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
270 /* Is there an item configured for this path? */
271 if (hashmap_get(items, sub_path))
274 if (find_glob(globs, sub_path))
277 if (S_ISDIR(s.st_mode)) {
280 streq(dent->d_name, "lost+found") &&
285 log_warning("Reached max depth on %s.", sub_path);
290 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
291 if (sub_dir == NULL) {
292 if (errno != ENOENT) {
293 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
300 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
307 /* Note: if you are wondering why we don't
308 * support the sticky bit for excluding
309 * directories from cleaning like we do it for
310 * other file system objects: well, the sticky
311 * bit already has a meaning for directories,
312 * so we don't want to overload that. */
317 /* Ignore ctime, we change it when deleting */
318 age = MAX(timespec_load(&s.st_mtim),
319 timespec_load(&s.st_atim));
323 log_debug("rmdir '%s'\n", sub_path);
325 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
326 if (errno != ENOENT && errno != ENOTEMPTY) {
327 log_error("rmdir(%s): %m", sub_path);
333 /* Skip files for which the sticky bit is
334 * set. These are semantics we define, and are
335 * unknown elsewhere. See XDG_RUNTIME_DIR
336 * specification for details. */
337 if (s.st_mode & S_ISVTX)
340 if (mountpoint && S_ISREG(s.st_mode)) {
341 if (streq(dent->d_name, ".journal") &&
345 if (streq(dent->d_name, "aquota.user") ||
346 streq(dent->d_name, "aquota.group"))
350 /* Ignore sockets that are listed in /proc/net/unix */
351 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
354 /* Ignore device nodes */
355 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
358 /* Keep files on this level around if this is
363 age = MAX3(timespec_load(&s.st_mtim),
364 timespec_load(&s.st_atim),
365 timespec_load(&s.st_ctim));
370 log_debug("unlink '%s'\n", sub_path);
372 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
373 if (errno != ENOENT) {
374 log_error("unlink(%s): %m", sub_path);
385 /* Restore original directory timestamps */
386 times[0] = ds->st_atim;
387 times[1] = ds->st_mtim;
389 if (futimens(dirfd(d), times) < 0)
390 log_error("utimensat(%s): %m", p);
398 static int clean_item(Item *i) {
407 if (i->type != CREATE_DIRECTORY &&
408 i->type != TRUNCATE_DIRECTORY &&
409 i->type != IGNORE_PATH)
415 n = now(CLOCK_REALTIME);
421 d = opendir(i->path);
426 log_error("Failed to open directory %s: %m", i->path);
430 if (fstat(dirfd(d), &s) < 0) {
431 log_error("stat(%s) failed: %m", i->path);
436 if (!S_ISDIR(s.st_mode)) {
437 log_error("%s is not a directory.", i->path);
442 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
443 log_error("stat(%s/..) failed: %m", i->path);
448 mountpoint = s.st_dev != ps.st_dev ||
449 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
451 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH, i->keep_first_level);
460 static int item_set_perms(Item *i, const char *path) {
461 /* not using i->path directly because it may be a glob */
463 if (chmod(path, i->mode) < 0) {
464 log_error("chmod(%s) failed: %m", path);
468 if (i->uid_set || i->gid_set)
470 i->uid_set ? i->uid : (uid_t) -1,
471 i->gid_set ? i->gid : (gid_t) -1) < 0) {
473 log_error("chown(%s) failed: %m", path);
477 return label_fix(path, false, false);
480 static int write_one_file(Item *i, const char *path) {
485 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
486 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
489 label_context_set(path, S_IFREG);
490 fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
492 label_context_clear();
497 if (i->type == WRITE_FILE && errno == ENOENT)
500 log_error("Failed to create file %s: %m", path);
507 _cleanup_free_ char *unescaped;
509 unescaped = cunescape(i->argument);
510 if (unescaped == NULL) {
511 close_nointr_nofail(fd);
515 l = strlen(unescaped);
516 n = write(fd, unescaped, l);
518 if (n < 0 || (size_t) n < l) {
519 log_error("Failed to write file %s: %s", path, n < 0 ? strerror(-n) : "Short write");
520 close_nointr_nofail(fd);
521 return n < 0 ? n : -EIO;
525 close_nointr_nofail(fd);
527 if (stat(path, &st) < 0) {
528 log_error("stat(%s) failed: %m", path);
532 if (!S_ISREG(st.st_mode)) {
533 log_error("%s is not a file.", path);
537 r = item_set_perms(i, path);
544 static int recursive_relabel_children(Item *i, const char *path) {
548 /* This returns the first error we run into, but nevertheless
553 return errno == ENOENT ? 0 : -errno;
557 union dirent_storage buf;
562 r = readdir_r(d, &buf.de, &de);
572 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
575 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
581 if (de->d_type == DT_UNKNOWN) {
584 if (lstat(entry_path, &st) < 0) {
585 if (ret == 0 && errno != ENOENT)
591 is_dir = S_ISDIR(st.st_mode);
594 is_dir = de->d_type == DT_DIR;
596 r = item_set_perms(i, entry_path);
598 if (ret == 0 && r != -ENOENT)
605 r = recursive_relabel_children(i, entry_path);
606 if (r < 0 && ret == 0)
618 static int recursive_relabel(Item *i, const char *path) {
622 r = item_set_perms(i, path);
626 if (lstat(path, &st) < 0)
629 if (S_ISDIR(st.st_mode))
630 r = recursive_relabel_children(i, path);
635 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
643 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
645 if (k != GLOB_NOMATCH) {
649 log_error("glob(%s) failed: %m", i->path);
654 STRV_FOREACH(fn, g.gl_pathv)
655 if ((k = action(i, *fn)) < 0)
662 static int create_item(Item *i) {
673 case RECURSIVE_REMOVE_PATH:
678 r = write_one_file(i, i->path);
683 r = glob_item(i, write_one_file);
689 case TRUNCATE_DIRECTORY:
690 case CREATE_DIRECTORY:
693 mkdir_parents_label(i->path, 0755);
694 r = mkdir(i->path, i->mode);
697 if (r < 0 && errno != EEXIST) {
698 log_error("Failed to create directory %s: %m", i->path);
702 if (stat(i->path, &st) < 0) {
703 log_error("stat(%s) failed: %m", i->path);
707 if (!S_ISDIR(st.st_mode)) {
708 log_error("%s is not a directory.", i->path);
712 r = item_set_perms(i, i->path);
721 r = mkfifo(i->path, i->mode);
724 if (r < 0 && errno != EEXIST) {
725 log_error("Failed to create fifo %s: %m", i->path);
729 if (stat(i->path, &st) < 0) {
730 log_error("stat(%s) failed: %m", i->path);
734 if (!S_ISFIFO(st.st_mode)) {
735 log_error("%s is not a fifo.", i->path);
739 r = item_set_perms(i, i->path);
745 case CREATE_SYMLINK: {
748 label_context_set(i->path, S_IFLNK);
749 r = symlink(i->argument, i->path);
751 label_context_clear();
754 if (r < 0 && errno != EEXIST) {
755 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
759 r = readlink_malloc(i->path, &x);
761 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
765 if (!streq(i->argument, x)) {
767 log_error("%s is not the right symlinks.", i->path);
775 case CREATE_BLOCK_DEVICE:
776 case CREATE_CHAR_DEVICE: {
779 if (have_effective_cap(CAP_MKNOD) == 0) {
780 /* In a container we lack CAP_MKNOD. We
781 shouldnt attempt to create the device node in
782 that case to avoid noise, and we don't support
783 virtualized devices in containers anyway. */
785 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
789 file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
792 label_context_set(i->path, file_type);
793 r = mknod(i->path, i->mode | file_type, i->major_minor);
795 label_context_clear();
799 if (r < 0 && errno != EEXIST) {
800 log_error("Failed to create device node %s: %m", i->path);
804 if (stat(i->path, &st) < 0) {
805 log_error("stat(%s) failed: %m", i->path);
809 if ((st.st_mode & S_IFMT) != file_type) {
810 log_error("%s is not a device node.", i->path);
814 r = item_set_perms(i, i->path);
823 r = glob_item(i, item_set_perms);
828 case RECURSIVE_RELABEL_PATH:
830 r = glob_item(i, recursive_relabel);
835 log_debug("%s created successfully.", i->path);
840 static int remove_item_instance(Item *i, const char *instance) {
849 case CREATE_DIRECTORY:
852 case CREATE_BLOCK_DEVICE:
853 case CREATE_CHAR_DEVICE:
856 case RECURSIVE_RELABEL_PATH:
861 if (remove(instance) < 0 && errno != ENOENT) {
862 log_error("remove(%s): %m", instance);
868 case TRUNCATE_DIRECTORY:
869 case RECURSIVE_REMOVE_PATH:
870 /* FIXME: we probably should use dir_cleanup() here
871 * instead of rm_rf() so that 'x' is honoured. */
872 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
873 if (r < 0 && r != -ENOENT) {
874 log_error("rm_rf(%s): %s", instance, strerror(-r));
884 static int remove_item(Item *i) {
893 case CREATE_DIRECTORY:
896 case CREATE_CHAR_DEVICE:
897 case CREATE_BLOCK_DEVICE:
900 case RECURSIVE_RELABEL_PATH:
905 case TRUNCATE_DIRECTORY:
906 case RECURSIVE_REMOVE_PATH:
907 r = glob_item(i, remove_item_instance);
914 static int process_item(Item *i) {
919 r = arg_create ? create_item(i) : 0;
920 q = arg_remove ? remove_item(i) : 0;
921 p = arg_clean ? clean_item(i) : 0;
932 static void item_free(Item *i) {
940 static bool item_equal(Item *a, Item *b) {
944 if (!streq_ptr(a->path, b->path))
947 if (a->type != b->type)
950 if (a->uid_set != b->uid_set ||
951 (a->uid_set && a->uid != b->uid))
954 if (a->gid_set != b->gid_set ||
955 (a->gid_set && a->gid != b->gid))
958 if (a->mode_set != b->mode_set ||
959 (a->mode_set && a->mode != b->mode))
962 if (a->age_set != b->age_set ||
963 (a->age_set && a->age != b->age))
966 if ((a->type == CREATE_FILE ||
967 a->type == TRUNCATE_FILE ||
968 a->type == WRITE_FILE ||
969 a->type == CREATE_SYMLINK) &&
970 !streq_ptr(a->argument, b->argument))
973 if ((a->type == CREATE_CHAR_DEVICE ||
974 a->type == CREATE_BLOCK_DEVICE) &&
975 a->major_minor != b->major_minor)
981 static int parse_line(const char *fname, unsigned line, const char *buffer) {
983 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
1011 log_error("[%s:%u] Syntax error.", fname, line);
1017 n += strspn(buffer+n, WHITESPACE);
1018 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1019 i->argument = unquote(buffer+n, "\"");
1029 case CREATE_DIRECTORY:
1030 case TRUNCATE_DIRECTORY:
1034 case RECURSIVE_REMOVE_PATH:
1036 case RECURSIVE_RELABEL_PATH:
1039 case CREATE_SYMLINK:
1041 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1049 log_error("[%s:%u] Write file requires argument.", fname, line);
1055 case CREATE_CHAR_DEVICE:
1056 case CREATE_BLOCK_DEVICE: {
1057 unsigned major, minor;
1060 log_error("[%s:%u] Device file requires argument.", fname, line);
1065 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1066 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1071 i->major_minor = makedev(major, minor);
1076 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1083 if (!path_is_absolute(i->path)) {
1084 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1089 path_kill_slashes(i->path);
1091 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1096 if (user && !streq(user, "-")) {
1097 const char *u = user;
1099 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1101 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1108 if (group && !streq(group, "-")) {
1109 const char *g = group;
1111 r = get_group_creds(&g, &i->gid);
1113 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1120 if (mode && !streq(mode, "-")) {
1123 if (sscanf(mode, "%o", &m) != 1) {
1124 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1133 i->type == CREATE_DIRECTORY ||
1134 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1136 if (age && !streq(age, "-")) {
1137 const char *a = age;
1140 i->keep_first_level = true;
1144 if (parse_usec(a, &i->age) < 0) {
1145 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1153 h = needs_glob(i->type) ? globs : items;
1155 existing = hashmap_get(h, i->path);
1158 /* Two identical items are fine */
1159 if (!item_equal(existing, i))
1160 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1166 r = hashmap_put(h, i->path, i);
1168 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1187 static int help(void) {
1189 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1190 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1191 " -h --help Show this help\n"
1192 " --create Create marked files/directories\n"
1193 " --clean Clean up marked directories\n"
1194 " --remove Remove marked files/directories\n"
1195 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1196 program_invocation_short_name);
1201 static int parse_argv(int argc, char *argv[]) {
1210 static const struct option options[] = {
1211 { "help", no_argument, NULL, 'h' },
1212 { "create", no_argument, NULL, ARG_CREATE },
1213 { "clean", no_argument, NULL, ARG_CLEAN },
1214 { "remove", no_argument, NULL, ARG_REMOVE },
1215 { "prefix", required_argument, NULL, ARG_PREFIX },
1216 { NULL, 0, NULL, 0 }
1224 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1245 arg_prefix = optarg;
1252 log_error("Unknown option code %c", c);
1257 if (!arg_clean && !arg_create && !arg_remove) {
1258 log_error("You need to specify at least one of --clean, --create or --remove.");
1265 static int read_config_file(const char *fn, bool ignore_enoent) {
1272 f = fopen(fn, "re");
1275 if (ignore_enoent && errno == ENOENT)
1278 log_error("Failed to open %s: %m", fn);
1282 log_debug("apply: %s\n", fn);
1284 char line[LINE_MAX], *l;
1287 if (!(fgets(line, sizeof(line), f)))
1293 if (*l == '#' || *l == 0)
1296 if ((k = parse_line(fn, v, l)) < 0)
1302 log_error("Failed to read from file %s: %m", fn);
1312 static char *resolve_fragment(const char *fragment, const char **search_paths) {
1314 char *resolved_path;
1316 if (is_path(fragment))
1317 return strdup(fragment);
1319 STRV_FOREACH(p, search_paths) {
1320 resolved_path = strjoin(*p, "/", fragment, NULL);
1321 if (resolved_path == NULL) {
1326 if (access(resolved_path, F_OK) == 0)
1327 return resolved_path;
1329 free(resolved_path);
1336 int main(int argc, char *argv[]) {
1341 r = parse_argv(argc, argv);
1343 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1345 log_set_target(LOG_TARGET_AUTO);
1346 log_parse_environment();
1353 items = hashmap_new(string_hash_func, string_compare_func);
1354 globs = hashmap_new(string_hash_func, string_compare_func);
1356 if (!items || !globs) {
1364 if (optind < argc) {
1367 for (j = optind; j < argc; j++) {
1370 fragment = resolve_fragment(argv[j], (const char **)conf_file_dirs);
1372 log_error("Failed to find a %s file: %m", argv[j]);
1376 if (read_config_file(fragment, false) < 0)
1384 r = conf_files_list_strv(&files, ".conf", (const char **)conf_file_dirs);
1386 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1391 STRV_FOREACH(f, files) {
1392 if (read_config_file(*f, true) < 0)
1399 HASHMAP_FOREACH(i, globs, iterator)
1402 HASHMAP_FOREACH(i, items, iterator)
1406 while ((i = hashmap_steal_first(items)))
1409 while ((i = hashmap_steal_first(globs)))
1412 hashmap_free(items);
1413 hashmap_free(globs);
1415 set_free_free(unix_sockets);