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',
60 /* These ones take globs */
63 RECURSIVE_REMOVE_PATH = 'R'
81 static Hashmap *items = NULL, *globs = NULL;
82 static Set *unix_sockets = NULL;
84 static bool arg_create = false;
85 static bool arg_clean = false;
86 static bool arg_remove = false;
88 static const char *arg_prefix = NULL;
92 static bool needs_glob(int t) {
93 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH;
96 static struct Item* find_glob(Hashmap *h, const char *match) {
100 HASHMAP_FOREACH(j, h, i)
101 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
107 static void load_unix_sockets(void) {
114 /* We maintain a cache of the sockets we found in
115 * /proc/net/unix to speed things up a little. */
117 if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
120 if (!(f = fopen("/proc/net/unix", "re")))
123 if (!(fgets(line, sizeof(line), f)))
130 if (!(fgets(line, sizeof(line), f)))
135 if (strlen(line) < 53)
139 p += strspn(p, WHITESPACE);
140 p += strcspn(p, WHITESPACE);
141 p += strspn(p, WHITESPACE);
146 if (!(s = strdup(p)))
149 path_kill_slashes(s);
151 if ((k = set_put(unix_sockets, s)) < 0) {
162 set_free_free(unix_sockets);
169 static bool unix_socket_alive(const char *fn) {
175 return !!set_get(unix_sockets, (char*) fn);
177 /* We don't know, so assume yes */
181 static int dir_cleanup(
184 const struct stat *ds,
191 struct timespec times[2];
192 bool deleted = false;
193 char *sub_path = NULL;
196 while ((dent = readdir(d))) {
200 if (streq(dent->d_name, ".") ||
201 streq(dent->d_name, ".."))
204 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
206 if (errno != ENOENT) {
207 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
214 /* Stay on the same filesystem */
215 if (s.st_dev != rootdev)
218 /* Do not delete read-only files owned by root */
219 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
225 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
226 log_error("Out of memory");
231 /* Is there an item configured for this path? */
232 if (hashmap_get(items, sub_path))
235 if (find_glob(globs, sub_path))
238 if (S_ISDIR(s.st_mode)) {
241 streq(dent->d_name, "lost+found") &&
246 log_warning("Reached max depth on %s.", sub_path);
251 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
252 if (sub_dir == NULL) {
253 if (errno != ENOENT) {
254 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
261 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
268 /* Ignore ctime, we change it when deleting */
269 age = MAX(timespec_load(&s.st_mtim),
270 timespec_load(&s.st_atim));
274 log_debug("rmdir '%s'\n", sub_path);
276 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
277 if (errno != ENOENT && errno != ENOTEMPTY) {
278 log_error("rmdir(%s): %m", sub_path);
284 /* Skip files for which the sticky bit is
285 * set. These are semantics we define, and are
286 * unknown elsewhere. See XDG_RUNTIME_DIR
287 * specification for details. */
288 if (s.st_mode & S_ISVTX)
291 if (mountpoint && S_ISREG(s.st_mode)) {
292 if (streq(dent->d_name, ".journal") &&
296 if (streq(dent->d_name, "aquota.user") ||
297 streq(dent->d_name, "aquota.group"))
301 /* Ignore sockets that are listed in /proc/net/unix */
302 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
305 /* Ignore device nodes */
306 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
309 age = MAX3(timespec_load(&s.st_mtim),
310 timespec_load(&s.st_atim),
311 timespec_load(&s.st_ctim));
316 log_debug("unlink '%s'\n", sub_path);
318 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
319 if (errno != ENOENT) {
320 log_error("unlink(%s): %m", sub_path);
331 /* Restore original directory timestamps */
332 times[0] = ds->st_atim;
333 times[1] = ds->st_mtim;
335 if (futimens(dirfd(d), times) < 0)
336 log_error("utimensat(%s): %m", p);
344 static int clean_item(Item *i) {
353 if (i->type != CREATE_DIRECTORY &&
354 i->type != TRUNCATE_DIRECTORY &&
355 i->type != IGNORE_PATH)
358 if (!i->age_set || i->age <= 0)
361 n = now(CLOCK_REALTIME);
367 d = opendir(i->path);
372 log_error("Failed to open directory %s: %m", i->path);
376 if (fstat(dirfd(d), &s) < 0) {
377 log_error("stat(%s) failed: %m", i->path);
382 if (!S_ISDIR(s.st_mode)) {
383 log_error("%s is not a directory.", i->path);
388 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
389 log_error("stat(%s/..) failed: %m", i->path);
394 mountpoint = s.st_dev != ps.st_dev ||
395 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
397 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
406 static int create_item(Item *i) {
417 case RECURSIVE_REMOVE_PATH:
424 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
425 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
429 log_error("Failed to create file %s: %m", i->path);
434 if (fstat(fd, &st) < 0) {
435 log_error("stat(%s) failed: %m", i->path);
440 if (!S_ISREG(st.st_mode)) {
441 log_error("%s is not a file.", i->path);
447 if (fchmod(fd, i->mode) < 0) {
448 log_error("chmod(%s) failed: %m", i->path);
453 if (i->uid_set || i->gid_set)
455 i->uid_set ? i->uid : (uid_t) -1,
456 i->gid_set ? i->gid : (gid_t) -1) < 0) {
457 log_error("chown(%s) failed: %m", i->path);
464 case TRUNCATE_DIRECTORY:
465 case CREATE_DIRECTORY:
468 mkdir_parents(i->path, 0755);
469 r = mkdir(i->path, i->mode);
472 if (r < 0 && errno != EEXIST) {
473 log_error("Failed to create directory %s: %m", i->path);
478 if (stat(i->path, &st) < 0) {
479 log_error("stat(%s) failed: %m", i->path);
484 if (!S_ISDIR(st.st_mode)) {
485 log_error("%s is not a directory.", i->path);
491 if (chmod(i->path, i->mode) < 0) {
492 log_error("chmod(%s) failed: %m", i->path);
497 if (i->uid_set || i->gid_set)
499 i->uid_set ? i->uid : (uid_t) -1,
500 i->gid_set ? i->gid : (gid_t) -1) < 0) {
502 log_error("chown(%s) failed: %m", i->path);
510 if ((r = label_fix(i->path, false)) < 0)
513 log_debug("%s created successfully.", i->path);
517 close_nointr_nofail(fd);
522 static int remove_item(Item *i, const char *instance) {
531 case CREATE_DIRECTORY:
536 if (remove(instance) < 0 && errno != ENOENT) {
537 log_error("remove(%s): %m", instance);
543 case TRUNCATE_DIRECTORY:
544 case RECURSIVE_REMOVE_PATH:
545 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
547 log_error("rm_rf(%s): %s", instance, strerror(-r));
557 static int remove_item_glob(Item *i) {
564 case CREATE_DIRECTORY:
569 case TRUNCATE_DIRECTORY:
570 case RECURSIVE_REMOVE_PATH: {
578 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
580 if (k != GLOB_NOMATCH) {
584 log_error("glob(%s) failed: %m", i->path);
589 STRV_FOREACH(fn, g.gl_pathv)
590 if ((k = remove_item(i, *fn)) < 0)
601 static int process_item(Item *i) {
606 r = arg_create ? create_item(i) : 0;
607 q = arg_remove ? remove_item_glob(i) : 0;
608 p = arg_clean ? clean_item(i) : 0;
619 static void item_free(Item *i) {
626 static bool item_equal(Item *a, Item *b) {
630 if (!streq_ptr(a->path, b->path))
633 if (a->type != b->type)
636 if (a->uid_set != b->uid_set ||
637 (a->uid_set && a->uid != b->uid))
640 if (a->gid_set != b->gid_set ||
641 (a->gid_set && a->gid != b->gid))
644 if (a->mode_set != b->mode_set ||
645 (a->mode_set && a->mode != b->mode))
648 if (a->age_set != b->age_set ||
649 (a->age_set && a->age != b->age))
655 static int parse_line(const char *fname, unsigned line, const char *buffer) {
657 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
665 if (!(i = new0(Item, 1))) {
666 log_error("Out of memory");
683 log_error("[%s:%u] Syntax error.", fname, line);
688 if (i->type != CREATE_FILE &&
689 i->type != TRUNCATE_FILE &&
690 i->type != CREATE_DIRECTORY &&
691 i->type != TRUNCATE_DIRECTORY &&
692 i->type != IGNORE_PATH &&
693 i->type != REMOVE_PATH &&
694 i->type != RECURSIVE_REMOVE_PATH) {
695 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
700 if (!path_is_absolute(i->path)) {
701 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
706 path_kill_slashes(i->path);
708 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
713 if (user && !streq(user, "-")) {
717 if (streq(user, "root") || streq(user, "0"))
719 else if (safe_atolu(user, &lu) >= 0)
721 else if ((p = getpwnam(user)))
724 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
732 if (group && !streq(group, "-")) {
736 if (streq(group, "root") || streq(group, "0"))
738 else if (safe_atolu(group, &lu) >= 0)
740 else if ((g = getgrnam(group)))
743 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
751 if (mode && !streq(mode, "-")) {
754 if (sscanf(mode, "%o", &m) != 1) {
755 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
763 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
765 if (age && !streq(age, "-")) {
766 if (parse_usec(age, &i->age) < 0) {
767 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
775 h = needs_glob(i->type) ? globs : items;
777 if ((existing = hashmap_get(h, i->path))) {
779 /* Two identical items are fine */
780 if (!item_equal(existing, i))
781 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
787 if ((r = hashmap_put(h, i->path, i)) < 0) {
788 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
807 static int help(void) {
809 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
810 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
811 " -h --help Show this help\n"
812 " --create Create marked files/directories\n"
813 " --clean Clean up marked directories\n"
814 " --remove Remove marked files/directories\n"
815 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
816 program_invocation_short_name);
821 static int parse_argv(int argc, char *argv[]) {
830 static const struct option options[] = {
831 { "help", no_argument, NULL, 'h' },
832 { "create", no_argument, NULL, ARG_CREATE },
833 { "clean", no_argument, NULL, ARG_CLEAN },
834 { "remove", no_argument, NULL, ARG_REMOVE },
835 { "prefix", required_argument, NULL, ARG_PREFIX },
844 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
872 log_error("Unknown option code %c", c);
877 if (!arg_clean && !arg_create && !arg_remove) {
878 log_error("You need to specify at least one of --clean, --create or --remove.");
885 static int read_config_file(const char *fn, bool ignore_enoent) {
892 if (!(f = fopen(fn, "re"))) {
894 if (ignore_enoent && errno == ENOENT)
897 log_error("Failed to open %s: %m", fn);
901 log_debug("apply: %s\n", fn);
903 char line[LINE_MAX], *l;
906 if (!(fgets(line, sizeof(line), f)))
912 if (*l == '#' || *l == 0)
915 if ((k = parse_line(fn, v, l)) < 0)
921 log_error("Failed to read from file %s: %m", fn);
931 int main(int argc, char *argv[]) {
936 if ((r = parse_argv(argc, argv)) <= 0)
937 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
939 log_set_target(LOG_TARGET_AUTO);
940 log_parse_environment();
945 items = hashmap_new(string_hash_func, string_compare_func);
946 globs = hashmap_new(string_hash_func, string_compare_func);
948 if (!items || !globs) {
949 log_error("Out of memory");
959 for (j = optind; j < argc; j++)
960 if (read_config_file(argv[j], false) < 0)
966 r = conf_files_list(&files, ".conf",
969 "/usr/local/lib/tmpfiles.d",
970 "/usr/lib/tmpfiles.d",
974 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
978 STRV_FOREACH(f, files) {
979 if (read_config_file(*f, true) < 0)
988 HASHMAP_FOREACH(i, globs, iterator)
989 if (process_item(i) < 0)
992 HASHMAP_FOREACH(i, items, iterator)
993 if (process_item(i) < 0)
997 while ((i = hashmap_steal_first(items)))
1000 while ((i = hashmap_steal_first(globs)))
1003 hashmap_free(items);
1004 hashmap_free(globs);
1006 set_free_free(unix_sockets);