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>
46 #include "path-util.h"
50 #include "conf-files.h"
51 #include "capability.h"
53 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
54 * them in the file system. This is intended to be used to create
55 * properly owned directories beneath /tmp, /var/tmp, /run, which are
56 * volatile and hence need to be recreated on bootup. */
58 typedef enum ItemType {
59 /* These ones take file names */
63 CREATE_DIRECTORY = 'd',
64 TRUNCATE_DIRECTORY = 'D',
67 CREATE_CHAR_DEVICE = 'c',
68 CREATE_BLOCK_DEVICE = 'b',
70 /* These ones take globs */
73 RECURSIVE_REMOVE_PATH = 'R',
75 RECURSIVE_RELABEL_PATH = 'Z'
95 bool keep_first_level:1;
98 static Hashmap *items = NULL, *globs = NULL;
99 static Set *unix_sockets = NULL;
101 static bool arg_create = false;
102 static bool arg_clean = false;
103 static bool arg_remove = false;
105 static const char *arg_prefix = NULL;
107 static const char * const conf_file_dirs[] = {
110 "/usr/local/lib/tmpfiles.d",
111 "/usr/lib/tmpfiles.d",
112 #ifdef HAVE_SPLIT_USR
118 #define MAX_DEPTH 256
120 static bool needs_glob(ItemType t) {
121 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
124 static struct Item* find_glob(Hashmap *h, const char *match) {
128 HASHMAP_FOREACH(j, h, i)
129 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
135 static void load_unix_sockets(void) {
142 /* We maintain a cache of the sockets we found in
143 * /proc/net/unix to speed things up a little. */
145 unix_sockets = set_new(string_hash_func, string_compare_func);
149 f = fopen("/proc/net/unix", "re");
154 if (!fgets(line, sizeof(line), f))
161 if (!fgets(line, sizeof(line), f))
166 p = strchr(line, ':');
174 p += strspn(p, WHITESPACE);
175 p += strcspn(p, WHITESPACE); /* skip one more word */
176 p += strspn(p, WHITESPACE);
185 path_kill_slashes(s);
187 k = set_put(unix_sockets, s);
200 set_free_free(unix_sockets);
207 static bool unix_socket_alive(const char *fn) {
213 return !!set_get(unix_sockets, (char*) fn);
215 /* We don't know, so assume yes */
219 static int dir_cleanup(
222 const struct stat *ds,
227 bool keep_this_level)
230 struct timespec times[2];
231 bool deleted = false;
232 char *sub_path = NULL;
235 while ((dent = readdir(d))) {
239 if (streq(dent->d_name, ".") ||
240 streq(dent->d_name, ".."))
243 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
245 if (errno != ENOENT) {
246 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
253 /* Stay on the same filesystem */
254 if (s.st_dev != rootdev)
257 /* Do not delete read-only files owned by root */
258 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
264 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
269 /* Is there an item configured for this path? */
270 if (hashmap_get(items, sub_path))
273 if (find_glob(globs, sub_path))
276 if (S_ISDIR(s.st_mode)) {
279 streq(dent->d_name, "lost+found") &&
284 log_warning("Reached max depth on %s.", sub_path);
289 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW|O_NOATIME);
290 if (sub_dir == NULL) {
291 if (errno != ENOENT) {
292 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
299 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
306 /* Note: if you are wondering why we don't
307 * support the sticky bit for excluding
308 * directories from cleaning like we do it for
309 * other file system objects: well, the sticky
310 * bit already has a meaning for directories,
311 * so we don't want to overload that. */
316 /* Ignore ctime, we change it when deleting */
317 age = MAX(timespec_load(&s.st_mtim),
318 timespec_load(&s.st_atim));
322 log_debug("rmdir '%s'\n", sub_path);
324 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
325 if (errno != ENOENT && errno != ENOTEMPTY) {
326 log_error("rmdir(%s): %m", sub_path);
332 /* Skip files for which the sticky bit is
333 * set. These are semantics we define, and are
334 * unknown elsewhere. See XDG_RUNTIME_DIR
335 * specification for details. */
336 if (s.st_mode & S_ISVTX)
339 if (mountpoint && S_ISREG(s.st_mode)) {
340 if (streq(dent->d_name, ".journal") &&
344 if (streq(dent->d_name, "aquota.user") ||
345 streq(dent->d_name, "aquota.group"))
349 /* Ignore sockets that are listed in /proc/net/unix */
350 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
353 /* Ignore device nodes */
354 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
357 /* Keep files on this level around if this is
362 age = MAX3(timespec_load(&s.st_mtim),
363 timespec_load(&s.st_atim),
364 timespec_load(&s.st_ctim));
369 log_debug("unlink '%s'\n", sub_path);
371 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
372 if (errno != ENOENT) {
373 log_error("unlink(%s): %m", sub_path);
384 /* Restore original directory timestamps */
385 times[0] = ds->st_atim;
386 times[1] = ds->st_mtim;
388 if (futimens(dirfd(d), times) < 0)
389 log_error("utimensat(%s): %m", p);
397 static int clean_item(Item *i) {
406 if (i->type != CREATE_DIRECTORY &&
407 i->type != TRUNCATE_DIRECTORY &&
408 i->type != IGNORE_PATH)
411 if (!i->age_set || i->age <= 0)
414 n = now(CLOCK_REALTIME);
420 d = opendir(i->path);
425 log_error("Failed to open directory %s: %m", i->path);
429 if (fstat(dirfd(d), &s) < 0) {
430 log_error("stat(%s) failed: %m", i->path);
435 if (!S_ISDIR(s.st_mode)) {
436 log_error("%s is not a directory.", i->path);
441 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
442 log_error("stat(%s/..) failed: %m", i->path);
447 mountpoint = s.st_dev != ps.st_dev ||
448 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
450 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH, i->keep_first_level);
459 static int item_set_perms(Item *i, const char *path) {
460 /* not using i->path directly because it may be a glob */
462 if (chmod(path, i->mode) < 0) {
463 log_error("chmod(%s) failed: %m", path);
467 if (i->uid_set || i->gid_set)
469 i->uid_set ? i->uid : (uid_t) -1,
470 i->gid_set ? i->gid : (gid_t) -1) < 0) {
472 log_error("chown(%s) failed: %m", path);
476 return label_fix(path, false, false);
479 static int recursive_relabel_children(Item *i, const char *path) {
483 /* This returns the first error we run into, but nevertheless
488 return errno == ENOENT ? 0 : -errno;
491 struct dirent buf, *de;
496 r = readdir_r(d, &buf, &de);
506 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
509 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
515 if (de->d_type == DT_UNKNOWN) {
518 if (lstat(entry_path, &st) < 0) {
519 if (ret == 0 && errno != ENOENT)
525 is_dir = S_ISDIR(st.st_mode);
528 is_dir = de->d_type == DT_DIR;
530 r = item_set_perms(i, entry_path);
532 if (ret == 0 && r != -ENOENT)
539 r = recursive_relabel_children(i, entry_path);
540 if (r < 0 && ret == 0)
552 static int recursive_relabel(Item *i, const char *path) {
556 r = item_set_perms(i, path);
560 if (lstat(path, &st) < 0)
563 if (S_ISDIR(st.st_mode))
564 r = recursive_relabel_children(i, path);
569 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
577 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
579 if (k != GLOB_NOMATCH) {
583 log_error("glob(%s) failed: %m", i->path);
588 STRV_FOREACH(fn, g.gl_pathv)
589 if ((k = action(i, *fn)) < 0)
596 static int create_item(Item *i) {
607 case RECURSIVE_REMOVE_PATH:
615 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
616 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
619 label_context_set(i->path, S_IFREG);
620 fd = open(i->path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
622 label_context_clear();
627 if (i->type == WRITE_FILE && errno == ENOENT)
630 log_error("Failed to create file %s: %m", i->path);
637 struct iovec iovec[2];
638 static const char new_line = '\n';
640 l = strlen(i->argument);
643 iovec[0].iov_base = i->argument;
644 iovec[0].iov_len = l;
646 iovec[1].iov_base = (void*) &new_line;
647 iovec[1].iov_len = 1;
649 n = writev(fd, iovec, 2);
651 /* It's OK if we don't write the trailing
652 * newline, hence we check for l, instead of
653 * l+1 here. Files in /sys often refuse
654 * writing of the trailing newline. */
655 if (n < 0 || (size_t) n < l) {
656 log_error("Failed to write file %s: %s", i->path, n < 0 ? strerror(-n) : "Short write");
657 close_nointr_nofail(fd);
658 return n < 0 ? n : -EIO;
662 close_nointr_nofail(fd);
664 if (stat(i->path, &st) < 0) {
665 log_error("stat(%s) failed: %m", i->path);
669 if (!S_ISREG(st.st_mode)) {
670 log_error("%s is not a file.", i->path);
674 r = item_set_perms(i, i->path);
681 case TRUNCATE_DIRECTORY:
682 case CREATE_DIRECTORY:
685 mkdir_parents_label(i->path, 0755);
686 r = mkdir(i->path, i->mode);
689 if (r < 0 && errno != EEXIST) {
690 log_error("Failed to create directory %s: %m", i->path);
694 if (stat(i->path, &st) < 0) {
695 log_error("stat(%s) failed: %m", i->path);
699 if (!S_ISDIR(st.st_mode)) {
700 log_error("%s is not a directory.", i->path);
704 r = item_set_perms(i, i->path);
713 r = mkfifo(i->path, i->mode);
716 if (r < 0 && errno != EEXIST) {
717 log_error("Failed to create fifo %s: %m", i->path);
721 if (stat(i->path, &st) < 0) {
722 log_error("stat(%s) failed: %m", i->path);
726 if (!S_ISFIFO(st.st_mode)) {
727 log_error("%s is not a fifo.", i->path);
731 r = item_set_perms(i, i->path);
737 case CREATE_SYMLINK: {
740 label_context_set(i->path, S_IFLNK);
741 r = symlink(i->argument, i->path);
743 label_context_clear();
746 if (r < 0 && errno != EEXIST) {
747 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
751 r = readlink_malloc(i->path, &x);
753 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
757 if (!streq(i->argument, x)) {
759 log_error("%s is not the right symlinks.", i->path);
767 case CREATE_BLOCK_DEVICE:
768 case CREATE_CHAR_DEVICE: {
771 if (have_effective_cap(CAP_MKNOD) == 0) {
772 /* In a container we lack CAP_MKNOD. We
773 shouldnt attempt to create the device node in
774 that case to avoid noise, and we don't support
775 virtualized devices in containers anyway. */
777 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
781 file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
784 label_context_set(i->path, file_type);
785 r = mknod(i->path, i->mode | file_type, i->major_minor);
787 label_context_clear();
791 if (r < 0 && errno != EEXIST) {
792 log_error("Failed to create device node %s: %m", i->path);
796 if (stat(i->path, &st) < 0) {
797 log_error("stat(%s) failed: %m", i->path);
801 if ((st.st_mode & S_IFMT) != file_type) {
802 log_error("%s is not a device node.", i->path);
806 r = item_set_perms(i, i->path);
815 r = glob_item(i, item_set_perms);
820 case RECURSIVE_RELABEL_PATH:
822 r = glob_item(i, recursive_relabel);
827 log_debug("%s created successfully.", i->path);
832 static int remove_item_instance(Item *i, const char *instance) {
841 case CREATE_DIRECTORY:
844 case CREATE_BLOCK_DEVICE:
845 case CREATE_CHAR_DEVICE:
848 case RECURSIVE_RELABEL_PATH:
853 if (remove(instance) < 0 && errno != ENOENT) {
854 log_error("remove(%s): %m", instance);
860 case TRUNCATE_DIRECTORY:
861 case RECURSIVE_REMOVE_PATH:
862 /* FIXME: we probably should use dir_cleanup() here
863 * instead of rm_rf() so that 'x' is honoured. */
864 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
865 if (r < 0 && r != -ENOENT) {
866 log_error("rm_rf(%s): %s", instance, strerror(-r));
876 static int remove_item(Item *i) {
885 case CREATE_DIRECTORY:
888 case CREATE_CHAR_DEVICE:
889 case CREATE_BLOCK_DEVICE:
892 case RECURSIVE_RELABEL_PATH:
897 case TRUNCATE_DIRECTORY:
898 case RECURSIVE_REMOVE_PATH:
899 r = glob_item(i, remove_item_instance);
906 static int process_item(Item *i) {
911 r = arg_create ? create_item(i) : 0;
912 q = arg_remove ? remove_item(i) : 0;
913 p = arg_clean ? clean_item(i) : 0;
924 static void item_free(Item *i) {
932 static bool item_equal(Item *a, Item *b) {
936 if (!streq_ptr(a->path, b->path))
939 if (a->type != b->type)
942 if (a->uid_set != b->uid_set ||
943 (a->uid_set && a->uid != b->uid))
946 if (a->gid_set != b->gid_set ||
947 (a->gid_set && a->gid != b->gid))
950 if (a->mode_set != b->mode_set ||
951 (a->mode_set && a->mode != b->mode))
954 if (a->age_set != b->age_set ||
955 (a->age_set && a->age != b->age))
958 if ((a->type == CREATE_FILE ||
959 a->type == TRUNCATE_FILE ||
960 a->type == WRITE_FILE ||
961 a->type == CREATE_SYMLINK) &&
962 !streq_ptr(a->argument, b->argument))
965 if ((a->type == CREATE_CHAR_DEVICE ||
966 a->type == CREATE_BLOCK_DEVICE) &&
967 a->major_minor != b->major_minor)
973 static int parse_line(const char *fname, unsigned line, const char *buffer) {
975 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
1003 log_error("[%s:%u] Syntax error.", fname, line);
1009 n += strspn(buffer+n, WHITESPACE);
1010 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1011 i->argument = unquote(buffer+n, "\"");
1021 case CREATE_DIRECTORY:
1022 case TRUNCATE_DIRECTORY:
1026 case RECURSIVE_REMOVE_PATH:
1028 case RECURSIVE_RELABEL_PATH:
1031 case CREATE_SYMLINK:
1033 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1041 log_error("[%s:%u] Write file requires argument.", fname, line);
1047 case CREATE_CHAR_DEVICE:
1048 case CREATE_BLOCK_DEVICE: {
1049 unsigned major, minor;
1052 log_error("[%s:%u] Device file requires argument.", fname, line);
1057 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1058 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1063 i->major_minor = makedev(major, minor);
1068 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1075 if (!path_is_absolute(i->path)) {
1076 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1081 path_kill_slashes(i->path);
1083 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1088 if (user && !streq(user, "-")) {
1089 const char *u = user;
1091 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1093 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1100 if (group && !streq(group, "-")) {
1101 const char *g = group;
1103 r = get_group_creds(&g, &i->gid);
1105 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1112 if (mode && !streq(mode, "-")) {
1115 if (sscanf(mode, "%o", &m) != 1) {
1116 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1125 i->type == CREATE_DIRECTORY ||
1126 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1128 if (age && !streq(age, "-")) {
1129 const char *a = age;
1132 i->keep_first_level = true;
1136 if (parse_usec(a, &i->age) < 0) {
1137 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1145 h = needs_glob(i->type) ? globs : items;
1147 existing = hashmap_get(h, i->path);
1150 /* Two identical items are fine */
1151 if (!item_equal(existing, i))
1152 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1158 r = hashmap_put(h, i->path, i);
1160 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1179 static int help(void) {
1181 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1182 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1183 " -h --help Show this help\n"
1184 " --create Create marked files/directories\n"
1185 " --clean Clean up marked directories\n"
1186 " --remove Remove marked files/directories\n"
1187 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1188 program_invocation_short_name);
1193 static int parse_argv(int argc, char *argv[]) {
1202 static const struct option options[] = {
1203 { "help", no_argument, NULL, 'h' },
1204 { "create", no_argument, NULL, ARG_CREATE },
1205 { "clean", no_argument, NULL, ARG_CLEAN },
1206 { "remove", no_argument, NULL, ARG_REMOVE },
1207 { "prefix", required_argument, NULL, ARG_PREFIX },
1208 { NULL, 0, NULL, 0 }
1216 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1237 arg_prefix = optarg;
1244 log_error("Unknown option code %c", c);
1249 if (!arg_clean && !arg_create && !arg_remove) {
1250 log_error("You need to specify at least one of --clean, --create or --remove.");
1257 static int read_config_file(const char *fn, bool ignore_enoent) {
1264 f = fopen(fn, "re");
1267 if (ignore_enoent && errno == ENOENT)
1270 log_error("Failed to open %s: %m", fn);
1274 log_debug("apply: %s\n", fn);
1276 char line[LINE_MAX], *l;
1279 if (!(fgets(line, sizeof(line), f)))
1285 if (*l == '#' || *l == 0)
1288 if ((k = parse_line(fn, v, l)) < 0)
1294 log_error("Failed to read from file %s: %m", fn);
1304 static char *resolve_fragment(const char *fragment, const char **search_paths) {
1306 char *resolved_path;
1308 if (is_path(fragment))
1309 return strdup(fragment);
1311 STRV_FOREACH(p, search_paths) {
1312 resolved_path = strjoin(*p, "/", fragment, NULL);
1313 if (resolved_path == NULL) {
1318 if (access(resolved_path, F_OK) == 0)
1319 return resolved_path;
1321 free(resolved_path);
1328 int main(int argc, char *argv[]) {
1333 r = parse_argv(argc, argv);
1335 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1337 log_set_target(LOG_TARGET_AUTO);
1338 log_parse_environment();
1345 items = hashmap_new(string_hash_func, string_compare_func);
1346 globs = hashmap_new(string_hash_func, string_compare_func);
1348 if (!items || !globs) {
1356 if (optind < argc) {
1359 for (j = optind; j < argc; j++) {
1362 fragment = resolve_fragment(argv[j], (const char**) conf_file_dirs);
1364 log_error("Failed to find a %s file: %m", argv[j]);
1368 if (read_config_file(fragment, false) < 0)
1376 r = conf_files_list_strv(&files, ".conf",
1377 (const char **) conf_file_dirs);
1379 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1384 STRV_FOREACH(f, files) {
1385 if (read_config_file(*f, true) < 0)
1392 HASHMAP_FOREACH(i, globs, iterator)
1395 HASHMAP_FOREACH(i, items, iterator)
1399 while ((i = hashmap_steal_first(items)))
1402 while ((i = hashmap_steal_first(globs)))
1405 hashmap_free(items);
1406 hashmap_free(globs);
1408 set_free_free(unix_sockets);