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, /var/run and
51 * /var/lock which are volatile and hence need to be recreated on
55 /* These ones take file names */
58 CREATE_DIRECTORY = 'd',
59 TRUNCATE_DIRECTORY = 'D',
61 /* These ones take globs */
64 RECURSIVE_REMOVE_PATH = 'R'
82 static Hashmap *items = NULL, *globs = NULL;
84 static bool arg_create = false;
85 static bool arg_clean = false;
86 static bool arg_remove = false;
90 static bool needs_glob(int t) {
91 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH;
94 static struct Item* find_glob(Hashmap *h, const char *match) {
98 HASHMAP_FOREACH(j, h, i)
99 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
105 static int dir_cleanup(
108 const struct stat *ds,
115 struct timespec times[2];
116 bool deleted = false;
117 char *sub_path = NULL;
120 while ((dent = readdir(d))) {
124 if (streq(dent->d_name, ".") ||
125 streq(dent->d_name, ".."))
128 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
130 if (errno != ENOENT) {
131 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
138 /* Stay on the same filesystem */
139 if (s.st_dev != rootdev)
142 /* Do not delete read-only files owned by root */
143 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
149 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
150 log_error("Out of memory");
155 /* Is there an item configured for this path? */
156 if (hashmap_get(items, sub_path))
159 if (find_glob(globs, sub_path))
162 if (S_ISDIR(s.st_mode)) {
165 streq(dent->d_name, "lost+found") &&
170 log_warning("Reached max depth on %s.", sub_path);
175 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
176 if (sub_dir == NULL) {
177 if (errno != ENOENT) {
178 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
185 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
192 /* Ignore ctime, we change it when deleting */
193 age = MAX(timespec_load(&s.st_mtim),
194 timespec_load(&s.st_atim));
198 log_debug("rmdir '%s'\n", sub_path);
200 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
201 if (errno != ENOENT && errno != ENOTEMPTY) {
202 log_error("rmdir(%s): %m", sub_path);
208 /* Skip files for which the sticky bit is
209 * set. These are semantics we define, and are
210 * unknown elsewhere. See XDG_RUNTIME_DIR
211 * specification for details. */
212 if (s.st_mode & S_ISVTX)
216 if (streq(dent->d_name, ".journal") &&
220 if (streq(dent->d_name, "aquota.user") ||
221 streq(dent->d_name, "aquota.group"))
225 age = MAX3(timespec_load(&s.st_mtim),
226 timespec_load(&s.st_atim),
227 timespec_load(&s.st_ctim));
232 log_debug("unlink '%s'\n", sub_path);
234 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
235 if (errno != ENOENT) {
236 log_error("unlink(%s): %m", sub_path);
247 /* Restore original directory timestamps */
248 times[0] = ds->st_atim;
249 times[1] = ds->st_mtim;
251 if (futimens(dirfd(d), times) < 0)
252 log_error("utimensat(%s): %m", p);
260 static int clean_item(Item *i) {
269 if (i->type != CREATE_DIRECTORY &&
270 i->type != TRUNCATE_DIRECTORY &&
271 i->type != IGNORE_PATH)
274 if (!i->age_set || i->age <= 0)
277 n = now(CLOCK_REALTIME);
283 d = opendir(i->path);
288 log_error("Failed to open directory %s: %m", i->path);
292 if (fstat(dirfd(d), &s) < 0) {
293 log_error("stat(%s) failed: %m", i->path);
298 if (!S_ISDIR(s.st_mode)) {
299 log_error("%s is not a directory.", i->path);
304 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
305 log_error("stat(%s/..) failed: %m", i->path);
310 mountpoint = s.st_dev != ps.st_dev ||
311 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
313 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
322 static int create_item(Item *i) {
333 case RECURSIVE_REMOVE_PATH:
340 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
341 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
345 log_error("Failed to create file %s: %m", i->path);
350 if (fstat(fd, &st) < 0) {
351 log_error("stat(%s) failed: %m", i->path);
356 if (!S_ISREG(st.st_mode)) {
357 log_error("%s is not a file.", i->path);
363 if (fchmod(fd, i->mode) < 0) {
364 log_error("chmod(%s) failed: %m", i->path);
369 if (i->uid_set || i->gid_set)
371 i->uid_set ? i->uid : (uid_t) -1,
372 i->gid_set ? i->gid : (gid_t) -1) < 0) {
373 log_error("chown(%s) failed: %m", i->path);
380 case TRUNCATE_DIRECTORY:
381 case CREATE_DIRECTORY:
384 r = mkdir(i->path, i->mode);
387 if (r < 0 && errno != EEXIST) {
388 log_error("Failed to create directory %s: %m", i->path);
393 if (stat(i->path, &st) < 0) {
394 log_error("stat(%s) failed: %m", i->path);
399 if (!S_ISDIR(st.st_mode)) {
400 log_error("%s is not a directory.", i->path);
406 if (chmod(i->path, i->mode) < 0) {
407 log_error("chmod(%s) failed: %m", i->path);
412 if (i->uid_set || i->gid_set)
414 i->uid_set ? i->uid : (uid_t) -1,
415 i->gid_set ? i->gid : (gid_t) -1) < 0) {
417 log_error("chown(%s) failed: %m", i->path);
425 if ((r = label_fix(i->path)) < 0)
428 log_debug("%s created successfully.", i->path);
432 close_nointr_nofail(fd);
437 static int remove_item(Item *i, const char *instance) {
446 case CREATE_DIRECTORY:
451 if (remove(instance) < 0 && errno != ENOENT) {
452 log_error("remove(%s): %m", instance);
458 case TRUNCATE_DIRECTORY:
459 case RECURSIVE_REMOVE_PATH:
460 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
462 log_error("rm_rf(%s): %s", instance, strerror(-r));
472 static int remove_item_glob(Item *i) {
479 case CREATE_DIRECTORY:
484 case TRUNCATE_DIRECTORY:
485 case RECURSIVE_REMOVE_PATH: {
493 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
495 if (k != GLOB_NOMATCH) {
499 log_error("glob(%s) failed: %m", i->path);
504 STRV_FOREACH(fn, g.gl_pathv)
505 if ((k = remove_item(i, *fn)) < 0)
516 static int process_item(Item *i) {
521 r = arg_create ? create_item(i) : 0;
522 q = arg_remove ? remove_item_glob(i) : 0;
523 p = arg_clean ? clean_item(i) : 0;
534 static void item_free(Item *i) {
541 static int parse_line(const char *fname, unsigned line, const char *buffer, const char *prefix) {
543 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
550 if (!(i = new0(Item, 1))) {
551 log_error("Out of memory");
568 log_error("[%s:%u] Syntax error.", fname, line);
573 if (i->type != CREATE_FILE &&
574 i->type != TRUNCATE_FILE &&
575 i->type != CREATE_DIRECTORY &&
576 i->type != TRUNCATE_DIRECTORY &&
577 i->type != IGNORE_PATH &&
578 i->type != REMOVE_PATH &&
579 i->type != RECURSIVE_REMOVE_PATH) {
580 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
585 if (!path_is_absolute(i->path)) {
586 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
591 path_kill_slashes(i->path);
593 if (prefix && !path_startswith(i->path, prefix)) {
598 if (user && !streq(user, "-")) {
602 if (streq(user, "root") || streq(user, "0"))
604 else if (safe_atolu(user, &lu) >= 0)
606 else if ((p = getpwnam(user)))
609 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
617 if (group && !streq(group, "-")) {
621 if (streq(group, "root") || streq(group, "0"))
623 else if (safe_atolu(group, &lu) >= 0)
625 else if ((g = getgrnam(group)))
628 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
636 if (mode && !streq(mode, "-")) {
639 if (sscanf(mode, "%o", &m) != 1) {
640 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
648 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
650 if (age && !streq(age, "-")) {
651 if (parse_usec(age, &i->age) < 0) {
652 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
660 if ((r = hashmap_put(needs_glob(i->type) ? globs : items, i->path, i)) < 0) {
662 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
667 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
686 static int scandir_filter(const struct dirent *d) {
689 if (ignore_file(d->d_name))
692 if (d->d_type != DT_REG &&
696 return endswith(d->d_name, ".conf");
699 static int help(void) {
701 printf("%s [OPTIONS...]\n\n"
702 "Create and clean up temporary directories.\n\n"
703 " -h --help Show this help\n"
704 " --create Create marked files/directories\n"
705 " --clean Clean up marked directories\n"
706 " --remove Remove marked files/directories\n",
707 program_invocation_short_name);
712 static int parse_argv(int argc, char *argv[]) {
720 static const struct option options[] = {
721 { "help", no_argument, NULL, 'h' },
722 { "create", no_argument, NULL, ARG_CREATE },
723 { "clean", no_argument, NULL, ARG_CLEAN },
724 { "remove", no_argument, NULL, ARG_REMOVE },
733 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
757 log_error("Unknown option code %c", c);
762 if (!arg_clean && !arg_create && !arg_remove) {
770 int main(int argc, char *argv[]) {
771 struct dirent **de = NULL;
773 const char *prefix = NULL;
777 if ((r = parse_argv(argc, argv)) <= 0)
778 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
781 prefix = argv[optind];
785 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
786 log_parse_environment();
791 items = hashmap_new(string_hash_func, string_compare_func);
792 globs = hashmap_new(string_hash_func, string_compare_func);
794 if (!items || !globs) {
795 log_error("Out of memory");
800 if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
805 log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
814 for (j = 0; j < n; j++) {
820 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
824 log_error("Failed to allocate file name.");
829 if (!(f = fopen(fn, "re"))) {
831 if (errno != ENOENT) {
832 log_error("Failed to open %s: %m", fn);
842 char line[LINE_MAX], *l;
844 if (!(fgets(line, sizeof(line), f)))
850 if (*l == '#' || *l == 0)
853 if (parse_line(fn, v, l, prefix) < 0)
859 log_error("Failed to read from file %s: %m", fn);
869 HASHMAP_FOREACH(i, globs, iterator)
870 if (process_item(i) < 0)
873 HASHMAP_FOREACH(i, items, iterator)
874 if (process_item(i) < 0)
878 while ((i = hashmap_steal_first(items)))