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 */
58 CREATE_DIRECTORY = 'd',
59 TRUNCATE_DIRECTORY = 'D',
62 CREATE_CHAR_DEVICE = 'c',
63 CREATE_BLOCK_DEVICE = 'b',
65 /* These ones take globs */
68 RECURSIVE_REMOVE_PATH = 'R',
70 RECURSIVE_RELABEL_PATH = 'Z'
91 static Hashmap *items = NULL, *globs = NULL;
92 static Set *unix_sockets = NULL;
94 static bool arg_create = false;
95 static bool arg_clean = false;
96 static bool arg_remove = false;
98 static const char *arg_prefix = NULL;
100 #define MAX_DEPTH 256
102 static bool needs_glob(ItemType t) {
103 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RELABEL_PATH || t == RECURSIVE_RELABEL_PATH;
106 static struct Item* find_glob(Hashmap *h, const char *match) {
110 HASHMAP_FOREACH(j, h, i)
111 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
117 static void load_unix_sockets(void) {
124 /* We maintain a cache of the sockets we found in
125 * /proc/net/unix to speed things up a little. */
127 unix_sockets = set_new(string_hash_func, string_compare_func);
131 f = fopen("/proc/net/unix", "re");
136 if (!fgets(line, sizeof(line), f))
143 if (!fgets(line, sizeof(line), f))
148 p = strchr(line, ':');
156 p += strspn(p, WHITESPACE);
157 p += strcspn(p, WHITESPACE); /* skip one more word */
158 p += strspn(p, WHITESPACE);
167 path_kill_slashes(s);
169 k = set_put(unix_sockets, s);
182 set_free_free(unix_sockets);
189 static bool unix_socket_alive(const char *fn) {
195 return !!set_get(unix_sockets, (char*) fn);
197 /* We don't know, so assume yes */
201 static int dir_cleanup(
204 const struct stat *ds,
211 struct timespec times[2];
212 bool deleted = false;
213 char *sub_path = NULL;
216 while ((dent = readdir(d))) {
220 if (streq(dent->d_name, ".") ||
221 streq(dent->d_name, ".."))
224 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
226 if (errno != ENOENT) {
227 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
234 /* Stay on the same filesystem */
235 if (s.st_dev != rootdev)
238 /* Do not delete read-only files owned by root */
239 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
245 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
246 log_error("Out of memory");
251 /* Is there an item configured for this path? */
252 if (hashmap_get(items, sub_path))
255 if (find_glob(globs, sub_path))
258 if (S_ISDIR(s.st_mode)) {
261 streq(dent->d_name, "lost+found") &&
266 log_warning("Reached max depth on %s.", sub_path);
271 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
272 if (sub_dir == NULL) {
273 if (errno != ENOENT) {
274 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
281 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
288 /* Ignore ctime, we change it when deleting */
289 age = MAX(timespec_load(&s.st_mtim),
290 timespec_load(&s.st_atim));
294 log_debug("rmdir '%s'\n", sub_path);
296 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
297 if (errno != ENOENT && errno != ENOTEMPTY) {
298 log_error("rmdir(%s): %m", sub_path);
304 /* Skip files for which the sticky bit is
305 * set. These are semantics we define, and are
306 * unknown elsewhere. See XDG_RUNTIME_DIR
307 * specification for details. */
308 if (s.st_mode & S_ISVTX)
311 if (mountpoint && S_ISREG(s.st_mode)) {
312 if (streq(dent->d_name, ".journal") &&
316 if (streq(dent->d_name, "aquota.user") ||
317 streq(dent->d_name, "aquota.group"))
321 /* Ignore sockets that are listed in /proc/net/unix */
322 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
325 /* Ignore device nodes */
326 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
329 age = MAX3(timespec_load(&s.st_mtim),
330 timespec_load(&s.st_atim),
331 timespec_load(&s.st_ctim));
336 log_debug("unlink '%s'\n", sub_path);
338 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
339 if (errno != ENOENT) {
340 log_error("unlink(%s): %m", sub_path);
351 /* Restore original directory timestamps */
352 times[0] = ds->st_atim;
353 times[1] = ds->st_mtim;
355 if (futimens(dirfd(d), times) < 0)
356 log_error("utimensat(%s): %m", p);
364 static int clean_item(Item *i) {
373 if (i->type != CREATE_DIRECTORY &&
374 i->type != TRUNCATE_DIRECTORY &&
375 i->type != IGNORE_PATH)
378 if (!i->age_set || i->age <= 0)
381 n = now(CLOCK_REALTIME);
387 d = opendir(i->path);
392 log_error("Failed to open directory %s: %m", i->path);
396 if (fstat(dirfd(d), &s) < 0) {
397 log_error("stat(%s) failed: %m", i->path);
402 if (!S_ISDIR(s.st_mode)) {
403 log_error("%s is not a directory.", i->path);
408 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
409 log_error("stat(%s/..) failed: %m", i->path);
414 mountpoint = s.st_dev != ps.st_dev ||
415 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
417 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
426 static int item_set_perms(Item *i, const char *path) {
427 /* not using i->path directly because it may be a glob */
429 if (chmod(path, i->mode) < 0) {
430 log_error("chmod(%s) failed: %m", path);
434 if (i->uid_set || i->gid_set)
436 i->uid_set ? i->uid : (uid_t) -1,
437 i->gid_set ? i->gid : (gid_t) -1) < 0) {
439 log_error("chown(%s) failed: %m", path);
443 return label_fix(path, false);
446 static int recursive_relabel_children(Item *i, const char *path) {
450 /* This returns the first error we run into, but nevertheless
455 return errno == ENOENT ? 0 : -errno;
458 struct dirent buf, *de;
463 r = readdir_r(d, &buf, &de);
473 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
476 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
482 if (de->d_type == DT_UNKNOWN) {
485 if (lstat(entry_path, &st) < 0) {
486 if (ret == 0 && errno != ENOENT)
492 is_dir = S_ISDIR(st.st_mode);
495 is_dir = de->d_type == DT_DIR;
497 r = item_set_perms(i, entry_path);
499 if (ret == 0 && r != -ENOENT)
506 r = recursive_relabel_children(i, entry_path);
507 if (r < 0 && ret == 0)
519 static int recursive_relabel(Item *i, const char *path) {
523 r = item_set_perms(i, path);
527 if (lstat(path, &st) < 0)
530 if (S_ISDIR(st.st_mode))
531 r = recursive_relabel_children(i, path);
536 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
544 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
546 if (k != GLOB_NOMATCH) {
550 log_error("glob(%s) failed: %m", i->path);
555 STRV_FOREACH(fn, g.gl_pathv)
556 if ((k = action(i, *fn)) < 0)
563 static int create_item(Item *i) {
574 case RECURSIVE_REMOVE_PATH:
582 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
583 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
586 fd = open(i->path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
590 if (i->type == WRITE_FILE && errno == ENOENT)
593 log_error("Failed to create file %s: %m", i->path);
600 struct iovec iovec[2];
601 static const char new_line = '\n';
603 l = strlen(i->argument);
606 iovec[0].iov_base = i->argument;
607 iovec[0].iov_len = l;
609 iovec[1].iov_base = (void*) &new_line;
610 iovec[1].iov_len = 1;
612 n = writev(fd, iovec, 2);
613 if (n < 0 || (size_t) n != l+1) {
614 log_error("Failed to write file %s: %s", i->path, n < 0 ? strerror(-n) : "Short");
615 close_nointr_nofail(fd);
616 return n < 0 ? n : -EIO;
620 close_nointr_nofail(fd);
622 if (stat(i->path, &st) < 0) {
623 log_error("stat(%s) failed: %m", i->path);
627 if (!S_ISREG(st.st_mode)) {
628 log_error("%s is not a file.", i->path);
632 r = item_set_perms(i, i->path);
639 case TRUNCATE_DIRECTORY:
640 case CREATE_DIRECTORY:
643 mkdir_parents(i->path, 0755);
644 r = mkdir(i->path, i->mode);
647 if (r < 0 && errno != EEXIST) {
648 log_error("Failed to create directory %s: %m", i->path);
652 if (stat(i->path, &st) < 0) {
653 log_error("stat(%s) failed: %m", i->path);
657 if (!S_ISDIR(st.st_mode)) {
658 log_error("%s is not a directory.", i->path);
662 r = item_set_perms(i, i->path);
671 r = mkfifo(i->path, i->mode);
674 if (r < 0 && errno != EEXIST) {
675 log_error("Failed to create fifo %s: %m", i->path);
679 if (stat(i->path, &st) < 0) {
680 log_error("stat(%s) failed: %m", i->path);
684 if (!S_ISFIFO(st.st_mode)) {
685 log_error("%s is not a fifo.", i->path);
689 r = item_set_perms(i, i->path);
695 case CREATE_SYMLINK: {
698 r = symlink(i->argument, i->path);
699 if (r < 0 && errno != EEXIST) {
700 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
704 r = readlink_malloc(i->path, &x);
706 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
710 if (!streq(i->argument, x)) {
712 log_error("%s is not the right symlinks.", i->path);
720 case CREATE_BLOCK_DEVICE:
721 case CREATE_CHAR_DEVICE: {
724 r = mknod(i->path, i->mode | (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR), i->major_minor);
727 if (r < 0 && errno != EEXIST) {
728 log_error("Failed to create device node %s: %m", i->path);
732 if (stat(i->path, &st) < 0) {
733 log_error("stat(%s) failed: %m", i->path);
737 if (i->type == CREATE_BLOCK_DEVICE ? !S_ISBLK(st.st_mode) : !S_ISCHR(st.st_mode)) {
738 log_error("%s is not a device node.", i->path);
742 r = item_set_perms(i, i->path);
751 r = glob_item(i, item_set_perms);
756 case RECURSIVE_RELABEL_PATH:
758 r = glob_item(i, recursive_relabel);
763 log_debug("%s created successfully.", i->path);
768 static int remove_item_instance(Item *i, const char *instance) {
777 case CREATE_DIRECTORY:
780 case CREATE_BLOCK_DEVICE:
781 case CREATE_CHAR_DEVICE:
784 case RECURSIVE_RELABEL_PATH:
789 if (remove(instance) < 0 && errno != ENOENT) {
790 log_error("remove(%s): %m", instance);
796 case TRUNCATE_DIRECTORY:
797 case RECURSIVE_REMOVE_PATH:
798 r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
799 if (r < 0 && r != -ENOENT) {
800 log_error("rm_rf(%s): %s", instance, strerror(-r));
810 static int remove_item(Item *i) {
819 case CREATE_DIRECTORY:
822 case CREATE_CHAR_DEVICE:
823 case CREATE_BLOCK_DEVICE:
826 case RECURSIVE_RELABEL_PATH:
831 case TRUNCATE_DIRECTORY:
832 case RECURSIVE_REMOVE_PATH:
833 r = glob_item(i, remove_item_instance);
840 static int process_item(Item *i) {
845 r = arg_create ? create_item(i) : 0;
846 q = arg_remove ? remove_item(i) : 0;
847 p = arg_clean ? clean_item(i) : 0;
858 static void item_free(Item *i) {
866 static bool item_equal(Item *a, Item *b) {
870 if (!streq_ptr(a->path, b->path))
873 if (a->type != b->type)
876 if (a->uid_set != b->uid_set ||
877 (a->uid_set && a->uid != b->uid))
880 if (a->gid_set != b->gid_set ||
881 (a->gid_set && a->gid != b->gid))
884 if (a->mode_set != b->mode_set ||
885 (a->mode_set && a->mode != b->mode))
888 if (a->age_set != b->age_set ||
889 (a->age_set && a->age != b->age))
892 if ((a->type == CREATE_FILE ||
893 a->type == TRUNCATE_FILE ||
894 a->type == WRITE_FILE ||
895 a->type == CREATE_SYMLINK) &&
896 !streq_ptr(a->argument, b->argument))
899 if ((a->type == CREATE_CHAR_DEVICE ||
900 a->type == CREATE_BLOCK_DEVICE) &&
901 a->major_minor != b->major_minor)
907 static int parse_line(const char *fname, unsigned line, const char *buffer) {
909 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
920 log_error("Out of memory");
939 log_error("[%s:%u] Syntax error.", fname, line);
945 n += strspn(buffer+n, WHITESPACE);
946 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
947 i->argument = unquote(buffer+n, "\"");
949 log_error("Out of memory");
959 case CREATE_DIRECTORY:
960 case TRUNCATE_DIRECTORY:
964 case RECURSIVE_REMOVE_PATH:
966 case RECURSIVE_RELABEL_PATH:
971 log_error("[%s:%u] Symlink file requires argument.", fname, line);
979 log_error("[%s:%u] Write file requires argument.", fname, line);
985 case CREATE_CHAR_DEVICE:
986 case CREATE_BLOCK_DEVICE: {
987 unsigned major, minor;
990 log_error("[%s:%u] Device file requires argument.", fname, line);
995 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
996 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1001 i->major_minor = makedev(major, minor);
1006 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1013 if (!path_is_absolute(i->path)) {
1014 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1019 path_kill_slashes(i->path);
1021 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1026 if (user && !streq(user, "-")) {
1027 const char *u = user;
1029 r = get_user_creds(&u, &i->uid, NULL, NULL);
1031 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1038 if (group && !streq(group, "-")) {
1039 const char *g = group;
1041 r = get_group_creds(&g, &i->gid);
1043 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1050 if (mode && !streq(mode, "-")) {
1053 if (sscanf(mode, "%o", &m) != 1) {
1054 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1063 i->type == CREATE_DIRECTORY ||
1064 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1066 if (age && !streq(age, "-")) {
1067 if (parse_usec(age, &i->age) < 0) {
1068 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1076 h = needs_glob(i->type) ? globs : items;
1078 existing = hashmap_get(h, i->path);
1081 /* Two identical items are fine */
1082 if (!item_equal(existing, i))
1083 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1089 r = hashmap_put(h, i->path, i);
1091 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1110 static int help(void) {
1112 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1113 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1114 " -h --help Show this help\n"
1115 " --create Create marked files/directories\n"
1116 " --clean Clean up marked directories\n"
1117 " --remove Remove marked files/directories\n"
1118 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1119 program_invocation_short_name);
1124 static int parse_argv(int argc, char *argv[]) {
1133 static const struct option options[] = {
1134 { "help", no_argument, NULL, 'h' },
1135 { "create", no_argument, NULL, ARG_CREATE },
1136 { "clean", no_argument, NULL, ARG_CLEAN },
1137 { "remove", no_argument, NULL, ARG_REMOVE },
1138 { "prefix", required_argument, NULL, ARG_PREFIX },
1139 { NULL, 0, NULL, 0 }
1147 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1168 arg_prefix = optarg;
1175 log_error("Unknown option code %c", c);
1180 if (!arg_clean && !arg_create && !arg_remove) {
1181 log_error("You need to specify at least one of --clean, --create or --remove.");
1188 static int read_config_file(const char *fn, bool ignore_enoent) {
1195 f = fopen(fn, "re");
1198 if (ignore_enoent && errno == ENOENT)
1201 log_error("Failed to open %s: %m", fn);
1205 log_debug("apply: %s\n", fn);
1207 char line[LINE_MAX], *l;
1210 if (!(fgets(line, sizeof(line), f)))
1216 if (*l == '#' || *l == 0)
1219 if ((k = parse_line(fn, v, l)) < 0)
1225 log_error("Failed to read from file %s: %m", fn);
1235 int main(int argc, char *argv[]) {
1240 r = parse_argv(argc, argv);
1242 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1244 log_set_target(LOG_TARGET_AUTO);
1245 log_parse_environment();
1252 items = hashmap_new(string_hash_func, string_compare_func);
1253 globs = hashmap_new(string_hash_func, string_compare_func);
1255 if (!items || !globs) {
1256 log_error("Out of memory");
1263 if (optind < argc) {
1266 for (j = optind; j < argc; j++)
1267 if (read_config_file(argv[j], false) < 0)
1273 r = conf_files_list(&files, ".conf",
1276 "/usr/local/lib/tmpfiles.d",
1277 "/usr/lib/tmpfiles.d",
1281 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1285 STRV_FOREACH(f, files) {
1286 if (read_config_file(*f, true) < 0)
1293 HASHMAP_FOREACH(i, globs, iterator)
1296 HASHMAP_FOREACH(i, items, iterator)
1300 while ((i = hashmap_steal_first(items)))
1303 while ((i = hashmap_steal_first(globs)))
1306 hashmap_free(items);
1307 hashmap_free(globs);
1309 set_free_free(unix_sockets);