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 close_nointr_nofail(fd);
533 if (stat(path, &st) < 0) {
534 log_error("stat(%s) failed: %m", path);
538 if (!S_ISREG(st.st_mode)) {
539 log_error("%s is not a file.", path);
543 r = item_set_perms(i, path);
550 static int recursive_relabel_children(Item *i, const char *path) {
554 /* This returns the first error we run into, but nevertheless
559 return errno == ENOENT ? 0 : -errno;
562 struct dirent buf, *de;
567 r = readdir_r(d, &buf, &de);
577 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
580 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
586 if (de->d_type == DT_UNKNOWN) {
589 if (lstat(entry_path, &st) < 0) {
590 if (ret == 0 && errno != ENOENT)
596 is_dir = S_ISDIR(st.st_mode);
599 is_dir = de->d_type == DT_DIR;
601 r = item_set_perms(i, entry_path);
603 if (ret == 0 && r != -ENOENT)
610 r = recursive_relabel_children(i, entry_path);
611 if (r < 0 && ret == 0)
623 static int recursive_relabel(Item *i, const char *path) {
627 r = item_set_perms(i, path);
631 if (lstat(path, &st) < 0)
634 if (S_ISDIR(st.st_mode))
635 r = recursive_relabel_children(i, path);
640 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
648 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
650 if (k != GLOB_NOMATCH) {
654 log_error("glob(%s) failed: %m", i->path);
659 STRV_FOREACH(fn, g.gl_pathv)
660 if ((k = action(i, *fn)) < 0)
667 static int create_item(Item *i) {
678 case RECURSIVE_REMOVE_PATH:
684 r = glob_item(i, write_one_file);
690 case TRUNCATE_DIRECTORY:
691 case CREATE_DIRECTORY:
694 mkdir_parents_label(i->path, 0755);
695 r = mkdir(i->path, i->mode);
698 if (r < 0 && errno != EEXIST) {
699 log_error("Failed to create directory %s: %m", i->path);
703 if (stat(i->path, &st) < 0) {
704 log_error("stat(%s) failed: %m", i->path);
708 if (!S_ISDIR(st.st_mode)) {
709 log_error("%s is not a directory.", i->path);
713 r = item_set_perms(i, i->path);
722 r = mkfifo(i->path, i->mode);
725 if (r < 0 && errno != EEXIST) {
726 log_error("Failed to create fifo %s: %m", i->path);
730 if (stat(i->path, &st) < 0) {
731 log_error("stat(%s) failed: %m", i->path);
735 if (!S_ISFIFO(st.st_mode)) {
736 log_error("%s is not a fifo.", i->path);
740 r = item_set_perms(i, i->path);
746 case CREATE_SYMLINK: {
749 label_context_set(i->path, S_IFLNK);
750 r = symlink(i->argument, i->path);
752 label_context_clear();
755 if (r < 0 && errno != EEXIST) {
756 log_error("symlink(%s, %s) failed: %m", i->argument, i->path);
760 r = readlink_malloc(i->path, &x);
762 log_error("readlink(%s) failed: %s", i->path, strerror(-r));
766 if (!streq(i->argument, x)) {
768 log_error("%s is not the right symlinks.", i->path);
776 case CREATE_BLOCK_DEVICE:
777 case CREATE_CHAR_DEVICE: {
780 if (have_effective_cap(CAP_MKNOD) == 0) {
781 /* In a container we lack CAP_MKNOD. We
782 shouldnt attempt to create the device node in
783 that case to avoid noise, and we don't support
784 virtualized devices in containers anyway. */
786 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
790 file_type = (i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
793 label_context_set(i->path, file_type);
794 r = mknod(i->path, i->mode | file_type, i->major_minor);
796 label_context_clear();
800 if (r < 0 && errno != EEXIST) {
801 log_error("Failed to create device node %s: %m", i->path);
805 if (stat(i->path, &st) < 0) {
806 log_error("stat(%s) failed: %m", i->path);
810 if ((st.st_mode & S_IFMT) != file_type) {
811 log_error("%s is not a device node.", i->path);
815 r = item_set_perms(i, i->path);
824 r = glob_item(i, item_set_perms);
829 case RECURSIVE_RELABEL_PATH:
831 r = glob_item(i, recursive_relabel);
836 log_debug("%s created successfully.", i->path);
841 static int remove_item_instance(Item *i, const char *instance) {
850 case CREATE_DIRECTORY:
853 case CREATE_BLOCK_DEVICE:
854 case CREATE_CHAR_DEVICE:
857 case RECURSIVE_RELABEL_PATH:
862 if (remove(instance) < 0 && errno != ENOENT) {
863 log_error("remove(%s): %m", instance);
869 case TRUNCATE_DIRECTORY:
870 case RECURSIVE_REMOVE_PATH:
871 /* FIXME: we probably should use dir_cleanup() here
872 * instead of rm_rf() so that 'x' is honoured. */
873 r = rm_rf_dangerous(instance, false, i->type == RECURSIVE_REMOVE_PATH, false);
874 if (r < 0 && r != -ENOENT) {
875 log_error("rm_rf(%s): %s", instance, strerror(-r));
885 static int remove_item(Item *i) {
894 case CREATE_DIRECTORY:
897 case CREATE_CHAR_DEVICE:
898 case CREATE_BLOCK_DEVICE:
901 case RECURSIVE_RELABEL_PATH:
906 case TRUNCATE_DIRECTORY:
907 case RECURSIVE_REMOVE_PATH:
908 r = glob_item(i, remove_item_instance);
915 static int process_item(Item *i) {
920 r = arg_create ? create_item(i) : 0;
921 q = arg_remove ? remove_item(i) : 0;
922 p = arg_clean ? clean_item(i) : 0;
933 static void item_free(Item *i) {
941 static bool item_equal(Item *a, Item *b) {
945 if (!streq_ptr(a->path, b->path))
948 if (a->type != b->type)
951 if (a->uid_set != b->uid_set ||
952 (a->uid_set && a->uid != b->uid))
955 if (a->gid_set != b->gid_set ||
956 (a->gid_set && a->gid != b->gid))
959 if (a->mode_set != b->mode_set ||
960 (a->mode_set && a->mode != b->mode))
963 if (a->age_set != b->age_set ||
964 (a->age_set && a->age != b->age))
967 if ((a->type == CREATE_FILE ||
968 a->type == TRUNCATE_FILE ||
969 a->type == WRITE_FILE ||
970 a->type == CREATE_SYMLINK) &&
971 !streq_ptr(a->argument, b->argument))
974 if ((a->type == CREATE_CHAR_DEVICE ||
975 a->type == CREATE_BLOCK_DEVICE) &&
976 a->major_minor != b->major_minor)
982 static int parse_line(const char *fname, unsigned line, const char *buffer) {
984 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
1012 log_error("[%s:%u] Syntax error.", fname, line);
1018 n += strspn(buffer+n, WHITESPACE);
1019 if (buffer[n] != 0 && (buffer[n] != '-' || buffer[n+1] != 0)) {
1020 i->argument = unquote(buffer+n, "\"");
1030 case CREATE_DIRECTORY:
1031 case TRUNCATE_DIRECTORY:
1035 case RECURSIVE_REMOVE_PATH:
1037 case RECURSIVE_RELABEL_PATH:
1040 case CREATE_SYMLINK:
1042 log_error("[%s:%u] Symlink file requires argument.", fname, line);
1050 log_error("[%s:%u] Write file requires argument.", fname, line);
1056 case CREATE_CHAR_DEVICE:
1057 case CREATE_BLOCK_DEVICE: {
1058 unsigned major, minor;
1061 log_error("[%s:%u] Device file requires argument.", fname, line);
1066 if (sscanf(i->argument, "%u:%u", &major, &minor) != 2) {
1067 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i->argument);
1072 i->major_minor = makedev(major, minor);
1077 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
1084 if (!path_is_absolute(i->path)) {
1085 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
1090 path_kill_slashes(i->path);
1092 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
1097 if (user && !streq(user, "-")) {
1098 const char *u = user;
1100 r = get_user_creds(&u, &i->uid, NULL, NULL, NULL);
1102 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
1109 if (group && !streq(group, "-")) {
1110 const char *g = group;
1112 r = get_group_creds(&g, &i->gid);
1114 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
1121 if (mode && !streq(mode, "-")) {
1124 if (sscanf(mode, "%o", &m) != 1) {
1125 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
1134 i->type == CREATE_DIRECTORY ||
1135 i->type == TRUNCATE_DIRECTORY ? 0755 : 0644;
1137 if (age && !streq(age, "-")) {
1138 const char *a = age;
1141 i->keep_first_level = true;
1145 if (parse_usec(a, &i->age) < 0) {
1146 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
1154 h = needs_glob(i->type) ? globs : items;
1156 existing = hashmap_get(h, i->path);
1159 /* Two identical items are fine */
1160 if (!item_equal(existing, i))
1161 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
1167 r = hashmap_put(h, i->path, i);
1169 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
1188 static int help(void) {
1190 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1191 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
1192 " -h --help Show this help\n"
1193 " --create Create marked files/directories\n"
1194 " --clean Clean up marked directories\n"
1195 " --remove Remove marked files/directories\n"
1196 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
1197 program_invocation_short_name);
1202 static int parse_argv(int argc, char *argv[]) {
1211 static const struct option options[] = {
1212 { "help", no_argument, NULL, 'h' },
1213 { "create", no_argument, NULL, ARG_CREATE },
1214 { "clean", no_argument, NULL, ARG_CLEAN },
1215 { "remove", no_argument, NULL, ARG_REMOVE },
1216 { "prefix", required_argument, NULL, ARG_PREFIX },
1217 { NULL, 0, NULL, 0 }
1225 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
1246 arg_prefix = optarg;
1253 log_error("Unknown option code %c", c);
1258 if (!arg_clean && !arg_create && !arg_remove) {
1259 log_error("You need to specify at least one of --clean, --create or --remove.");
1266 static int read_config_file(const char *fn, bool ignore_enoent) {
1273 f = fopen(fn, "re");
1276 if (ignore_enoent && errno == ENOENT)
1279 log_error("Failed to open %s: %m", fn);
1283 log_debug("apply: %s\n", fn);
1285 char line[LINE_MAX], *l;
1288 if (!(fgets(line, sizeof(line), f)))
1294 if (*l == '#' || *l == 0)
1297 if ((k = parse_line(fn, v, l)) < 0)
1303 log_error("Failed to read from file %s: %m", fn);
1313 static char *resolve_fragment(const char *fragment, const char **search_paths) {
1315 char *resolved_path;
1317 if (is_path(fragment))
1318 return strdup(fragment);
1320 STRV_FOREACH(p, search_paths) {
1321 resolved_path = strjoin(*p, "/", fragment, NULL);
1322 if (resolved_path == NULL) {
1327 if (access(resolved_path, F_OK) == 0)
1328 return resolved_path;
1330 free(resolved_path);
1337 int main(int argc, char *argv[]) {
1342 r = parse_argv(argc, argv);
1344 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1346 log_set_target(LOG_TARGET_AUTO);
1347 log_parse_environment();
1354 items = hashmap_new(string_hash_func, string_compare_func);
1355 globs = hashmap_new(string_hash_func, string_compare_func);
1357 if (!items || !globs) {
1365 if (optind < argc) {
1368 for (j = optind; j < argc; j++) {
1371 fragment = resolve_fragment(argv[j], (const char**) conf_file_dirs);
1373 log_error("Failed to find a %s file: %m", argv[j]);
1377 if (read_config_file(fragment, false) < 0)
1385 r = conf_files_list_strv(&files, ".conf",
1386 (const char **) conf_file_dirs);
1388 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1393 STRV_FOREACH(f, files) {
1394 if (read_config_file(*f, true) < 0)
1401 HASHMAP_FOREACH(i, globs, iterator)
1404 HASHMAP_FOREACH(i, items, iterator)
1408 while ((i = hashmap_steal_first(items)))
1411 while ((i = hashmap_steal_first(globs)))
1414 hashmap_free(items);
1415 hashmap_free(globs);
1417 set_free_free(unix_sockets);