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 write_one_file(Item *i, const char *path) {
484 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND :
485 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC : 0;
488 label_context_set(path, S_IFREG);
489 fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW, i->mode);
491 label_context_clear();
496 if (i->type == WRITE_FILE && errno == ENOENT)
499 log_error("Failed to create file %s: %m", path);
506 struct iovec iovec[2];
507 static const char new_line = '\n';
509 l = strlen(i->argument);
512 iovec[0].iov_base = i->argument;
513 iovec[0].iov_len = l;
515 iovec[1].iov_base = (void*) &new_line;
516 iovec[1].iov_len = 1;
518 n = writev(fd, iovec, 2);
520 /* It's OK if we don't write the trailing
521 * newline, hence we check for l, instead of
522 * l+1 here. Files in /sys often refuse
523 * writing of the trailing newline. */
524 if (n < 0 || (size_t) n < l) {
525 log_error("Failed to write file %s: %s", path, n < 0 ? strerror(-n) : "Short write");
526 close_nointr_nofail(fd);
527 return n < 0 ? n : -EIO;
531 if (stat(path, &st) < 0) {
532 log_error("stat(%s) failed: %m", path);
536 if (!S_ISREG(st.st_mode)) {
537 log_error("%s is not a file.", path);
541 r = item_set_perms(i, path);
548 static int recursive_relabel_children(Item *i, const char *path) {
552 /* This returns the first error we run into, but nevertheless
557 return errno == ENOENT ? 0 : -errno;
560 struct dirent buf, *de;
565 r = readdir_r(d, &buf, &de);
575 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
578 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
584 if (de->d_type == DT_UNKNOWN) {
587 if (lstat(entry_path, &st) < 0) {
588 if (ret == 0 && errno != ENOENT)
594 is_dir = S_ISDIR(st.st_mode);
597 is_dir = de->d_type == DT_DIR;
599 r = item_set_perms(i, entry_path);
601 if (ret == 0 && r != -ENOENT)
608 r = recursive_relabel_children(i, entry_path);
609 if (r < 0 && ret == 0)
621 static int recursive_relabel(Item *i, const char *path) {
625 r = item_set_perms(i, path);
629 if (lstat(path, &st) < 0)
632 if (S_ISDIR(st.st_mode))
633 r = recursive_relabel_children(i, path);
638 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
646 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
648 if (k != GLOB_NOMATCH) {
652 log_error("glob(%s) failed: %m", i->path);
657 STRV_FOREACH(fn, g.gl_pathv)
658 if ((k = action(i, *fn)) < 0)
665 static int create_item(Item *i) {
676 case RECURSIVE_REMOVE_PATH:
682 r = glob_item(i, write_one_file);
688 case TRUNCATE_DIRECTORY:
689 case CREATE_DIRECTORY:
692 mkdir_parents_label(i->path, 0755);
693 r = mkdir(i->path, i->mode);
696 if (r < 0 && errno != EEXIST) {
697 log_error("Failed to create directory %s: %m", i->path);
701 if (stat(i->path, &st) < 0) {
702 log_error("stat(%s) failed: %m", i->path);
706 if (!S_ISDIR(st.st_mode)) {
707 log_error("%s is not a directory.", i->path);
711 r = item_set_perms(i, i->path);
720 r = mkfifo(i->path, i->mode);
723 if (r < 0 && errno != EEXIST) {
724 log_error("Failed to create fifo %s: %m", i->path);
728 if (stat(i->path, &st) < 0) {
729 log_error("stat(%s) failed: %m", i->path);
733 if (!S_ISFIFO(st.st_mode)) {
734 log_error("%s is not a fifo.", i->path);
738 r = item_set_perms(i, i->path);
744 case CREATE_SYMLINK: {
747 label_context_set(i->path, S_IFLNK);
748 r = symlink(i->argument, i->path);
750 label_context_clear();
753 if (r < 0 && errno != EEXIST) {
754 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
758 r = readlink_malloc(i->path, &x);
760 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
764 if (!streq(i->argument, x)) {
766 log_error("%s is not the right symlinks.", i->path);
774 case CREATE_BLOCK_DEVICE:
775 case CREATE_CHAR_DEVICE: {
778 if (have_effective_cap(CAP_MKNOD) == 0) {
779 /* In a container we lack CAP_MKNOD. We
780 shouldnt attempt to create the device node in
781 that case to avoid noise, and we don't support
782 virtualized devices in containers anyway. */
784 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
788 file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
791 label_context_set(i->path, file_type);
792 r = mknod(i->path, i->mode | file_type, i->major_minor);
794 label_context_clear();
798 if (r < 0 && errno != EEXIST) {
799 log_error("Failed to create device node %s: %m", i->path);
803 if (stat(i->path, &st) < 0) {
804 log_error("stat(%s) failed: %m", i->path);
808 if ((st.st_mode & S_IFMT) != file_type) {
809 log_error("%s is not a device node.", i->path);
813 r = item_set_perms(i, i->path);
822 r = glob_item(i, item_set_perms);
827 case RECURSIVE_RELABEL_PATH:
829 r = glob_item(i, recursive_relabel);
834 log_debug("%s created successfully.", i->path);
839 static int remove_item_instance(Item *i, const char *instance) {
848 case CREATE_DIRECTORY:
851 case CREATE_BLOCK_DEVICE:
852 case CREATE_CHAR_DEVICE:
855 case RECURSIVE_RELABEL_PATH:
860 if (remove(instance) < 0 && errno != ENOENT) {
861 log_error("remove(%s): %m", instance);
867 case TRUNCATE_DIRECTORY:
868 case RECURSIVE_REMOVE_PATH:
869 /* FIXME: we probably should use dir_cleanup() here
870 * instead of rm_rf() so that 'x' is honoured. */
871 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
872 if (r < 0 && r != -ENOENT) {
873 log_error("rm_rf(%s): %s", instance, strerror(-r));
883 static int remove_item(Item *i) {
892 case CREATE_DIRECTORY:
895 case CREATE_CHAR_DEVICE:
896 case CREATE_BLOCK_DEVICE:
899 case RECURSIVE_RELABEL_PATH:
904 case TRUNCATE_DIRECTORY:
905 case RECURSIVE_REMOVE_PATH:
906 r = glob_item(i, remove_item_instance);
913 static int process_item(Item *i) {
918 r = arg_create ? create_item(i) : 0;
919 q = arg_remove ? remove_item(i) : 0;
920 p = arg_clean ? clean_item(i) : 0;
931 static void item_free(Item *i) {
939 static bool item_equal(Item *a, Item *b) {
943 if (!streq_ptr(a->path, b->path))
946 if (a->type != b->type)
949 if (a->uid_set != b->uid_set ||
950 (a->uid_set && a->uid != b->uid))
953 if (a->gid_set != b->gid_set ||
954 (a->gid_set && a->gid != b->gid))
957 if (a->mode_set != b->mode_set ||
958 (a->mode_set && a->mode != b->mode))
961 if (a->age_set != b->age_set ||
962 (a->age_set && a->age != b->age))
965 if ((a->type == CREATE_FILE ||
966 a->type == TRUNCATE_FILE ||
967 a->type == WRITE_FILE ||
968 a->type == CREATE_SYMLINK) &&
969 !streq_ptr(a->argument, b->argument))
972 if ((a->type == CREATE_CHAR_DEVICE ||
973 a->type == CREATE_BLOCK_DEVICE) &&
974 a->major_minor != b->major_minor)
980 static int parse_line(const char *fname, unsigned line, const char *buffer) {
982 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
1010 log_error("[%s:%u] Syntax error.", fname, line);
1016 n += strspn(buffer+n, WHITESPACE);
1017 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1018 i->argument = unquote(buffer+n, "\"");
1028 case CREATE_DIRECTORY:
1029 case TRUNCATE_DIRECTORY:
1033 case RECURSIVE_REMOVE_PATH:
1035 case RECURSIVE_RELABEL_PATH:
1038 case CREATE_SYMLINK:
1040 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1048 log_error("[%s:%u] Write file requires argument.", fname, line);
1054 case CREATE_CHAR_DEVICE:
1055 case CREATE_BLOCK_DEVICE: {
1056 unsigned major, minor;
1059 log_error("[%s:%u] Device file requires argument.", fname, line);
1064 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1065 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1070 i->major_minor = makedev(major, minor);
1075 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1082 if (!path_is_absolute(i->path)) {
1083 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1088 path_kill_slashes(i->path);
1090 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1095 if (user && !streq(user, "-")) {
1096 const char *u = user;
1098 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1100 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1107 if (group && !streq(group, "-")) {
1108 const char *g = group;
1110 r = get_group_creds(&g, &i->gid);
1112 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1119 if (mode && !streq(mode, "-")) {
1122 if (sscanf(mode, "%o", &m) != 1) {
1123 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1132 i->type == CREATE_DIRECTORY ||
1133 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1135 if (age && !streq(age, "-")) {
1136 const char *a = age;
1139 i->keep_first_level = true;
1143 if (parse_usec(a, &i->age) < 0) {
1144 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1152 h = needs_glob(i->type) ? globs : items;
1154 existing = hashmap_get(h, i->path);
1157 /* Two identical items are fine */
1158 if (!item_equal(existing, i))
1159 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1165 r = hashmap_put(h, i->path, i);
1167 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1186 static int help(void) {
1188 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1189 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1190 " -h --help Show this help\n"
1191 " --create Create marked files/directories\n"
1192 " --clean Clean up marked directories\n"
1193 " --remove Remove marked files/directories\n"
1194 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1195 program_invocation_short_name);
1200 static int parse_argv(int argc, char *argv[]) {
1209 static const struct option options[] = {
1210 { "help", no_argument, NULL, 'h' },
1211 { "create", no_argument, NULL, ARG_CREATE },
1212 { "clean", no_argument, NULL, ARG_CLEAN },
1213 { "remove", no_argument, NULL, ARG_REMOVE },
1214 { "prefix", required_argument, NULL, ARG_PREFIX },
1215 { NULL, 0, NULL, 0 }
1223 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1244 arg_prefix = optarg;
1251 log_error("Unknown option code %c", c);
1256 if (!arg_clean && !arg_create && !arg_remove) {
1257 log_error("You need to specify at least one of --clean, --create or --remove.");
1264 static int read_config_file(const char *fn, bool ignore_enoent) {
1271 f = fopen(fn, "re");
1274 if (ignore_enoent && errno == ENOENT)
1277 log_error("Failed to open %s: %m", fn);
1281 log_debug("apply: %s\n", fn);
1283 char line[LINE_MAX], *l;
1286 if (!(fgets(line, sizeof(line), f)))
1292 if (*l == '#' || *l == 0)
1295 if ((k = parse_line(fn, v, l)) < 0)
1301 log_error("Failed to read from file %s: %m", fn);
1311 static char *resolve_fragment(const char *fragment, const char **search_paths) {
1313 char *resolved_path;
1315 if (is_path(fragment))
1316 return strdup(fragment);
1318 STRV_FOREACH(p, search_paths) {
1319 resolved_path = strjoin(*p, "/", fragment, NULL);
1320 if (resolved_path == NULL) {
1325 if (access(resolved_path, F_OK) == 0)
1326 return resolved_path;
1328 free(resolved_path);
1335 int main(int argc, char *argv[]) {
1340 r = parse_argv(argc, argv);
1342 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1344 log_set_target(LOG_TARGET_AUTO);
1345 log_parse_environment();
1352 items = hashmap_new(string_hash_func, string_compare_func);
1353 globs = hashmap_new(string_hash_func, string_compare_func);
1355 if (!items || !globs) {
1363 if (optind < argc) {
1366 for (j = optind; j < argc; j++) {
1369 fragment = resolve_fragment(argv[j], (const char**) conf_file_dirs);
1371 log_error("Failed to find a %s file: %m", argv[j]);
1375 if (read_config_file(fragment, false) < 0)
1383 r = conf_files_list_strv(&files, ".conf",
1384 (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);