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. */
54 /* These ones take file names */
57 CREATE_DIRECTORY = 'd',
58 TRUNCATE_DIRECTORY = 'D',
61 /* These ones take globs */
64 RECURSIVE_REMOVE_PATH = 'R'
82 static Hashmap *items = NULL, *globs = NULL;
83 static Set *unix_sockets = NULL;
85 static bool arg_create = false;
86 static bool arg_clean = false;
87 static bool arg_remove = false;
89 static const char *arg_prefix = NULL;
93 static bool needs_glob(int t) {
94 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH;
97 static struct Item* find_glob(Hashmap *h, const char *match) {
101 HASHMAP_FOREACH(j, h, i)
102 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
108 static void load_unix_sockets(void) {
115 /* We maintain a cache of the sockets we found in
116 * /proc/net/unix to speed things up a little. */
118 if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
121 if (!(f = fopen("/proc/net/unix", "re")))
124 if (!(fgets(line, sizeof(line), f)))
131 if (!(fgets(line, sizeof(line), f)))
136 if (strlen(line) < 53)
140 p += strspn(p, WHITESPACE);
141 p += strcspn(p, WHITESPACE);
142 p += strspn(p, WHITESPACE);
147 if (!(s = strdup(p)))
150 path_kill_slashes(s);
152 if ((k = set_put(unix_sockets, s)) < 0) {
163 set_free_free(unix_sockets);
170 static bool unix_socket_alive(const char *fn) {
176 return !!set_get(unix_sockets, (char*) fn);
178 /* We don't know, so assume yes */
182 static int dir_cleanup(
185 const struct stat *ds,
192 struct timespec times[2];
193 bool deleted = false;
194 char *sub_path = NULL;
197 while ((dent = readdir(d))) {
201 if (streq(dent->d_name, ".") ||
202 streq(dent->d_name, ".."))
205 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
207 if (errno != ENOENT) {
208 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
215 /* Stay on the same filesystem */
216 if (s.st_dev != rootdev)
219 /* Do not delete read-only files owned by root */
220 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
226 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
227 log_error("Out of memory");
232 /* Is there an item configured for this path? */
233 if (hashmap_get(items, sub_path))
236 if (find_glob(globs, sub_path))
239 if (S_ISDIR(s.st_mode)) {
242 streq(dent->d_name, "lost+found") &&
247 log_warning("Reached max depth on %s.", sub_path);
252 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
253 if (sub_dir == NULL) {
254 if (errno != ENOENT) {
255 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
262 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
269 /* Ignore ctime, we change it when deleting */
270 age = MAX(timespec_load(&s.st_mtim),
271 timespec_load(&s.st_atim));
275 log_debug("rmdir '%s'\n", sub_path);
277 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
278 if (errno != ENOENT && errno != ENOTEMPTY) {
279 log_error("rmdir(%s): %m", sub_path);
285 /* Skip files for which the sticky bit is
286 * set. These are semantics we define, and are
287 * unknown elsewhere. See XDG_RUNTIME_DIR
288 * specification for details. */
289 if (s.st_mode & S_ISVTX)
292 if (mountpoint && S_ISREG(s.st_mode)) {
293 if (streq(dent->d_name, ".journal") &&
297 if (streq(dent->d_name, "aquota.user") ||
298 streq(dent->d_name, "aquota.group"))
302 /* Ignore sockets that are listed in /proc/net/unix */
303 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
306 /* Ignore device nodes */
307 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
310 age = MAX3(timespec_load(&s.st_mtim),
311 timespec_load(&s.st_atim),
312 timespec_load(&s.st_ctim));
317 log_debug("unlink '%s'\n", sub_path);
319 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
320 if (errno != ENOENT) {
321 log_error("unlink(%s): %m", sub_path);
332 /* Restore original directory timestamps */
333 times[0] = ds->st_atim;
334 times[1] = ds->st_mtim;
336 if (futimens(dirfd(d), times) < 0)
337 log_error("utimensat(%s): %m", p);
345 static int clean_item(Item *i) {
354 if (i->type != CREATE_DIRECTORY &&
355 i->type != TRUNCATE_DIRECTORY &&
356 i->type != IGNORE_PATH)
359 if (!i->age_set || i->age <= 0)
362 n = now(CLOCK_REALTIME);
368 d = opendir(i->path);
373 log_error("Failed to open directory %s: %m", i->path);
377 if (fstat(dirfd(d), &s) < 0) {
378 log_error("stat(%s) failed: %m", i->path);
383 if (!S_ISDIR(s.st_mode)) {
384 log_error("%s is not a directory.", i->path);
389 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
390 log_error("stat(%s/..) failed: %m", i->path);
395 mountpoint = s.st_dev != ps.st_dev ||
396 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
398 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
407 static int create_item(Item *i) {
418 case RECURSIVE_REMOVE_PATH:
425 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
426 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
430 log_error("Failed to create file %s: %m", i->path);
435 if (fstat(fd, &st) < 0) {
436 log_error("stat(%s) failed: %m", i->path);
441 if (!S_ISREG(st.st_mode)) {
442 log_error("%s is not a file.", i->path);
448 if (fchmod(fd, i->mode) < 0) {
449 log_error("chmod(%s) failed: %m", i->path);
454 if (i->uid_set || i->gid_set)
456 i->uid_set ? i->uid : (uid_t) -1,
457 i->gid_set ? i->gid : (gid_t) -1) < 0) {
458 log_error("chown(%s) failed: %m", i->path);
465 case TRUNCATE_DIRECTORY:
466 case CREATE_DIRECTORY:
469 mkdir_parents(i->path, 0755);
470 r = mkdir(i->path, i->mode);
473 if (r < 0 && errno != EEXIST) {
474 log_error("Failed to create directory %s: %m", i->path);
479 if (stat(i->path, &st) < 0) {
480 log_error("stat(%s) failed: %m", i->path);
485 if (!S_ISDIR(st.st_mode)) {
486 log_error("%s is not a directory.", i->path);
492 if (chmod(i->path, i->mode) < 0) {
493 log_error("chmod(%s) failed: %m", i->path);
498 if (i->uid_set || i->gid_set)
500 i->uid_set ? i->uid : (uid_t) -1,
501 i->gid_set ? i->gid : (gid_t) -1) < 0) {
503 log_error("chown(%s) failed: %m", i->path);
513 r = mkfifo(i->path, i->mode);
516 if (r < 0 && errno != EEXIST) {
517 log_error("Failed to create fifo %s: %m", i->path);
522 if (stat(i->path, &st) < 0) {
523 log_error("stat(%s) failed: %m", i->path);
528 if (!S_ISFIFO(st.st_mode)) {
529 log_error("%s is not a fifo.", i->path);
535 if (chmod(i->path, i->mode) < 0) {
536 log_error("chmod(%s) failed: %m", i->path);
541 if (i->uid_set || i->gid_set)
543 i->uid_set ? i->uid : (uid_t) -1,
544 i->gid_set ? i->gid : (gid_t) -1) < 0) {
545 log_error("chown(%s) failed: %m", i->path);
553 if ((r = label_fix(i->path, false)) < 0)
556 log_debug("%s created successfully.", i->path);
560 close_nointr_nofail(fd);
565 static int remove_item(Item *i, const char *instance) {
574 case CREATE_DIRECTORY:
580 if (remove(instance) < 0 && errno != ENOENT) {
581 log_error("remove(%s): %m", instance);
587 case TRUNCATE_DIRECTORY:
588 case RECURSIVE_REMOVE_PATH:
589 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
591 log_error("rm_rf(%s): %s", instance, strerror(-r));
601 static int remove_item_glob(Item *i) {
608 case CREATE_DIRECTORY:
614 case TRUNCATE_DIRECTORY:
615 case RECURSIVE_REMOVE_PATH: {
623 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
625 if (k != GLOB_NOMATCH) {
629 log_error("glob(%s) failed: %m", i->path);
634 STRV_FOREACH(fn, g.gl_pathv)
635 if ((k = remove_item(i, *fn)) < 0)
646 static int process_item(Item *i) {
651 r = arg_create ? create_item(i) : 0;
652 q = arg_remove ? remove_item_glob(i) : 0;
653 p = arg_clean ? clean_item(i) : 0;
664 static void item_free(Item *i) {
671 static bool item_equal(Item *a, Item *b) {
675 if (!streq_ptr(a->path, b->path))
678 if (a->type != b->type)
681 if (a->uid_set != b->uid_set ||
682 (a->uid_set && a->uid != b->uid))
685 if (a->gid_set != b->gid_set ||
686 (a->gid_set && a->gid != b->gid))
689 if (a->mode_set != b->mode_set ||
690 (a->mode_set && a->mode != b->mode))
693 if (a->age_set != b->age_set ||
694 (a->age_set && a->age != b->age))
700 static int parse_line(const char *fname, unsigned line, const char *buffer) {
702 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
710 if (!(i = new0(Item, 1))) {
711 log_error("Out of memory");
728 log_error("[%s:%u] Syntax error.", fname, line);
733 if (i->type != CREATE_FILE &&
734 i->type != TRUNCATE_FILE &&
735 i->type != CREATE_DIRECTORY &&
736 i->type != TRUNCATE_DIRECTORY &&
737 i->type != CREATE_FIFO &&
738 i->type != IGNORE_PATH &&
739 i->type != REMOVE_PATH &&
740 i->type != RECURSIVE_REMOVE_PATH) {
741 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
746 if (!path_is_absolute(i->path)) {
747 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
752 path_kill_slashes(i->path);
754 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
759 if (user && !streq(user, "-")) {
760 const char *u = user;
762 r = get_user_creds(&u, &i->uid, NULL, NULL);
764 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
771 if (group && !streq(group, "-")) {
772 const char *g = group;
774 r = get_group_creds(&g, &i->gid);
776 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
783 if (mode && !streq(mode, "-")) {
786 if (sscanf(mode, "%o", &m) != 1) {
787 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
795 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
797 if (age && !streq(age, "-")) {
798 if (parse_usec(age, &i->age) < 0) {
799 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
807 h = needs_glob(i->type) ? globs : items;
809 if ((existing = hashmap_get(h, i->path))) {
811 /* Two identical items are fine */
812 if (!item_equal(existing, i))
813 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
819 if ((r = hashmap_put(h, i->path, i)) < 0) {
820 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
839 static int help(void) {
841 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
842 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
843 " -h --help Show this help\n"
844 " --create Create marked files/directories\n"
845 " --clean Clean up marked directories\n"
846 " --remove Remove marked files/directories\n"
847 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
848 program_invocation_short_name);
853 static int parse_argv(int argc, char *argv[]) {
862 static const struct option options[] = {
863 { "help", no_argument, NULL, 'h' },
864 { "create", no_argument, NULL, ARG_CREATE },
865 { "clean", no_argument, NULL, ARG_CLEAN },
866 { "remove", no_argument, NULL, ARG_REMOVE },
867 { "prefix", required_argument, NULL, ARG_PREFIX },
876 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
904 log_error("Unknown option code %c", c);
909 if (!arg_clean && !arg_create && !arg_remove) {
910 log_error("You need to specify at least one of --clean, --create or --remove.");
917 static int read_config_file(const char *fn, bool ignore_enoent) {
924 if (!(f = fopen(fn, "re"))) {
926 if (ignore_enoent && errno == ENOENT)
929 log_error("Failed to open %s: %m", fn);
933 log_debug("apply: %s\n", fn);
935 char line[LINE_MAX], *l;
938 if (!(fgets(line, sizeof(line), f)))
944 if (*l == '#' || *l == 0)
947 if ((k = parse_line(fn, v, l)) < 0)
953 log_error("Failed to read from file %s: %m", fn);
963 int main(int argc, char *argv[]) {
968 if ((r = parse_argv(argc, argv)) <= 0)
969 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
971 log_set_target(LOG_TARGET_AUTO);
972 log_parse_environment();
979 items = hashmap_new(string_hash_func, string_compare_func);
980 globs = hashmap_new(string_hash_func, string_compare_func);
982 if (!items || !globs) {
983 log_error("Out of memory");
993 for (j = optind; j < argc; j++)
994 if (read_config_file(argv[j], false) < 0)
1000 r = conf_files_list(&files, ".conf",
1003 "/usr/local/lib/tmpfiles.d",
1004 "/usr/lib/tmpfiles.d",
1008 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1012 STRV_FOREACH(f, files) {
1013 if (read_config_file(*f, true) < 0)
1020 HASHMAP_FOREACH(i, globs, iterator)
1023 HASHMAP_FOREACH(i, items, iterator)
1027 while ((i = hashmap_steal_first(items)))
1030 while ((i = hashmap_steal_first(globs)))
1033 hashmap_free(items);
1034 hashmap_free(globs);
1036 set_free_free(unix_sockets);