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) {
164 set_free_free(unix_sockets);
171 static bool unix_socket_alive(const char *fn) {
177 return !!set_get(unix_sockets, (char*) fn);
179 /* We don't know, so assume yes */
183 static int dir_cleanup(
186 const struct stat *ds,
193 struct timespec times[2];
194 bool deleted = false;
195 char *sub_path = NULL;
198 while ((dent = readdir(d))) {
202 if (streq(dent->d_name, ".") ||
203 streq(dent->d_name, ".."))
206 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
208 if (errno != ENOENT) {
209 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
216 /* Stay on the same filesystem */
217 if (s.st_dev != rootdev)
220 /* Do not delete read-only files owned by root */
221 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
227 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
228 log_error("Out of memory");
233 /* Is there an item configured for this path? */
234 if (hashmap_get(items, sub_path))
237 if (find_glob(globs, sub_path))
240 if (S_ISDIR(s.st_mode)) {
243 streq(dent->d_name, "lost+found") &&
248 log_warning("Reached max depth on %s.", sub_path);
253 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
254 if (sub_dir == NULL) {
255 if (errno != ENOENT) {
256 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
263 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
270 /* Ignore ctime, we change it when deleting */
271 age = MAX(timespec_load(&s.st_mtim),
272 timespec_load(&s.st_atim));
276 log_debug("rmdir '%s'\n", sub_path);
278 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
279 if (errno != ENOENT && errno != ENOTEMPTY) {
280 log_error("rmdir(%s): %m", sub_path);
286 /* Skip files for which the sticky bit is
287 * set. These are semantics we define, and are
288 * unknown elsewhere. See XDG_RUNTIME_DIR
289 * specification for details. */
290 if (s.st_mode & S_ISVTX)
293 if (mountpoint && S_ISREG(s.st_mode)) {
294 if (streq(dent->d_name, ".journal") &&
298 if (streq(dent->d_name, "aquota.user") ||
299 streq(dent->d_name, "aquota.group"))
303 /* Ignore sockets that are listed in /proc/net/unix */
304 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
307 /* Ignore device nodes */
308 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
311 age = MAX3(timespec_load(&s.st_mtim),
312 timespec_load(&s.st_atim),
313 timespec_load(&s.st_ctim));
318 log_debug("unlink '%s'\n", sub_path);
320 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
321 if (errno != ENOENT) {
322 log_error("unlink(%s): %m", sub_path);
333 /* Restore original directory timestamps */
334 times[0] = ds->st_atim;
335 times[1] = ds->st_mtim;
337 if (futimens(dirfd(d), times) < 0)
338 log_error("utimensat(%s): %m", p);
346 static int clean_item(Item *i) {
355 if (i->type != CREATE_DIRECTORY &&
356 i->type != TRUNCATE_DIRECTORY &&
357 i->type != IGNORE_PATH)
360 if (!i->age_set || i->age <= 0)
363 n = now(CLOCK_REALTIME);
369 d = opendir(i->path);
374 log_error("Failed to open directory %s: %m", i->path);
378 if (fstat(dirfd(d), &s) < 0) {
379 log_error("stat(%s) failed: %m", i->path);
384 if (!S_ISDIR(s.st_mode)) {
385 log_error("%s is not a directory.", i->path);
390 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
391 log_error("stat(%s/..) failed: %m", i->path);
396 mountpoint = s.st_dev != ps.st_dev ||
397 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
399 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
408 static int create_item(Item *i) {
419 case RECURSIVE_REMOVE_PATH:
426 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
427 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
431 log_error("Failed to create file %s: %m", i->path);
436 if (fstat(fd, &st) < 0) {
437 log_error("stat(%s) failed: %m", i->path);
442 if (!S_ISREG(st.st_mode)) {
443 log_error("%s is not a file.", i->path);
449 if (fchmod(fd, i->mode) < 0) {
450 log_error("chmod(%s) failed: %m", i->path);
455 if (i->uid_set || i->gid_set)
457 i->uid_set ? i->uid : (uid_t) -1,
458 i->gid_set ? i->gid : (gid_t) -1) < 0) {
459 log_error("chown(%s) failed: %m", i->path);
466 case TRUNCATE_DIRECTORY:
467 case CREATE_DIRECTORY:
470 mkdir_parents(i->path, 0755);
471 r = mkdir(i->path, i->mode);
474 if (r < 0 && errno != EEXIST) {
475 log_error("Failed to create directory %s: %m", i->path);
480 if (stat(i->path, &st) < 0) {
481 log_error("stat(%s) failed: %m", i->path);
486 if (!S_ISDIR(st.st_mode)) {
487 log_error("%s is not a directory.", i->path);
493 if (chmod(i->path, i->mode) < 0) {
494 log_error("chmod(%s) failed: %m", i->path);
499 if (i->uid_set || i->gid_set)
501 i->uid_set ? i->uid : (uid_t) -1,
502 i->gid_set ? i->gid : (gid_t) -1) < 0) {
504 log_error("chown(%s) failed: %m", i->path);
514 r = mkfifo(i->path, i->mode);
517 if (r < 0 && errno != EEXIST) {
518 log_error("Failed to create fifo %s: %m", i->path);
523 if (stat(i->path, &st) < 0) {
524 log_error("stat(%s) failed: %m", i->path);
529 if (!S_ISFIFO(st.st_mode)) {
530 log_error("%s is not a fifo.", i->path);
536 if (chmod(i->path, i->mode) < 0) {
537 log_error("chmod(%s) failed: %m", i->path);
542 if (i->uid_set || i->gid_set)
544 i->uid_set ? i->uid : (uid_t) -1,
545 i->gid_set ? i->gid : (gid_t) -1) < 0) {
546 log_error("chown(%s) failed: %m", i->path);
554 if ((r = label_fix(i->path, false)) < 0)
557 log_debug("%s created successfully.", i->path);
561 close_nointr_nofail(fd);
566 static int remove_item(Item *i, const char *instance) {
575 case CREATE_DIRECTORY:
581 if (remove(instance) < 0 && errno != ENOENT) {
582 log_error("remove(%s): %m", instance);
588 case TRUNCATE_DIRECTORY:
589 case RECURSIVE_REMOVE_PATH:
590 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
592 log_error("rm_rf(%s): %s", instance, strerror(-r));
602 static int remove_item_glob(Item *i) {
609 case CREATE_DIRECTORY:
615 case TRUNCATE_DIRECTORY:
616 case RECURSIVE_REMOVE_PATH: {
624 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
626 if (k != GLOB_NOMATCH) {
630 log_error("glob(%s) failed: %m", i->path);
635 STRV_FOREACH(fn, g.gl_pathv)
636 if ((k = remove_item(i, *fn)) < 0)
647 static int process_item(Item *i) {
652 r = arg_create ? create_item(i) : 0;
653 q = arg_remove ? remove_item_glob(i) : 0;
654 p = arg_clean ? clean_item(i) : 0;
665 static void item_free(Item *i) {
672 static bool item_equal(Item *a, Item *b) {
676 if (!streq_ptr(a->path, b->path))
679 if (a->type != b->type)
682 if (a->uid_set != b->uid_set ||
683 (a->uid_set && a->uid != b->uid))
686 if (a->gid_set != b->gid_set ||
687 (a->gid_set && a->gid != b->gid))
690 if (a->mode_set != b->mode_set ||
691 (a->mode_set && a->mode != b->mode))
694 if (a->age_set != b->age_set ||
695 (a->age_set && a->age != b->age))
701 static int parse_line(const char *fname, unsigned line, const char *buffer) {
703 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
711 if (!(i = new0(Item, 1))) {
712 log_error("Out of memory");
729 log_error("[%s:%u] Syntax error.", fname, line);
734 if (i->type != CREATE_FILE &&
735 i->type != TRUNCATE_FILE &&
736 i->type != CREATE_DIRECTORY &&
737 i->type != TRUNCATE_DIRECTORY &&
738 i->type != CREATE_FIFO &&
739 i->type != IGNORE_PATH &&
740 i->type != REMOVE_PATH &&
741 i->type != RECURSIVE_REMOVE_PATH) {
742 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
747 if (!path_is_absolute(i->path)) {
748 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
753 path_kill_slashes(i->path);
755 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
760 if (user && !streq(user, "-")) {
761 const char *u = user;
763 r = get_user_creds(&u, &i->uid, NULL, NULL);
765 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
772 if (group && !streq(group, "-")) {
773 const char *g = group;
775 r = get_group_creds(&g, &i->gid);
777 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
784 if (mode && !streq(mode, "-")) {
787 if (sscanf(mode, "%o", &m) != 1) {
788 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
796 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
798 if (age && !streq(age, "-")) {
799 if (parse_usec(age, &i->age) < 0) {
800 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
808 h = needs_glob(i->type) ? globs : items;
810 if ((existing = hashmap_get(h, i->path))) {
812 /* Two identical items are fine */
813 if (!item_equal(existing, i))
814 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
820 if ((r = hashmap_put(h, i->path, i)) < 0) {
821 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
840 static int help(void) {
842 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
843 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
844 " -h --help Show this help\n"
845 " --create Create marked files/directories\n"
846 " --clean Clean up marked directories\n"
847 " --remove Remove marked files/directories\n"
848 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
849 program_invocation_short_name);
854 static int parse_argv(int argc, char *argv[]) {
863 static const struct option options[] = {
864 { "help", no_argument, NULL, 'h' },
865 { "create", no_argument, NULL, ARG_CREATE },
866 { "clean", no_argument, NULL, ARG_CLEAN },
867 { "remove", no_argument, NULL, ARG_REMOVE },
868 { "prefix", required_argument, NULL, ARG_PREFIX },
877 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
905 log_error("Unknown option code %c", c);
910 if (!arg_clean && !arg_create && !arg_remove) {
911 log_error("You need to specify at least one of --clean, --create or --remove.");
918 static int read_config_file(const char *fn, bool ignore_enoent) {
925 if (!(f = fopen(fn, "re"))) {
927 if (ignore_enoent && errno == ENOENT)
930 log_error("Failed to open %s: %m", fn);
934 log_debug("apply: %s\n", fn);
936 char line[LINE_MAX], *l;
939 if (!(fgets(line, sizeof(line), f)))
945 if (*l == '#' || *l == 0)
948 if ((k = parse_line(fn, v, l)) < 0)
954 log_error("Failed to read from file %s: %m", fn);
964 int main(int argc, char *argv[]) {
969 if ((r = parse_argv(argc, argv)) <= 0)
970 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
972 log_set_target(LOG_TARGET_AUTO);
973 log_parse_environment();
980 items = hashmap_new(string_hash_func, string_compare_func);
981 globs = hashmap_new(string_hash_func, string_compare_func);
983 if (!items || !globs) {
984 log_error("Out of memory");
994 for (j = optind; j < argc; j++)
995 if (read_config_file(argv[j], false) < 0)
1001 r = conf_files_list(&files, ".conf",
1004 "/usr/local/lib/tmpfiles.d",
1005 "/usr/lib/tmpfiles.d",
1009 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1013 STRV_FOREACH(f, files) {
1014 if (read_config_file(*f, true) < 0)
1021 HASHMAP_FOREACH(i, globs, iterator)
1024 HASHMAP_FOREACH(i, items, iterator)
1028 while ((i = hashmap_steal_first(items)))
1031 while ((i = hashmap_steal_first(globs)))
1034 hashmap_free(items);
1035 hashmap_free(globs);
1037 set_free_free(unix_sockets);