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>
46 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
47 * them in the file system. This is intended to be used to create
48 * properly owned directories beneath /tmp, /var/tmp, /var/run and
49 * /var/lock which are volatile and hence need to be recreated on
55 CREATE_DIRECTORY = 'd',
56 TRUNCATE_DIRECTORY = 'D',
59 RECURSIVE_REMOVE_PATH = 'R'
77 static Hashmap *items = NULL;
79 static bool arg_create = false;
80 static bool arg_clean = false;
81 static bool arg_remove = false;
85 static int dir_cleanup(
88 const struct stat *ds,
95 struct timespec times[2];
97 char *sub_path = NULL;
100 while ((dent = readdir(d))) {
104 if (streq(dent->d_name, ".") ||
105 streq(dent->d_name, ".."))
108 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
110 if (errno != ENOENT) {
111 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
118 /* Stay on the same filesystem */
119 if (s.st_dev != rootdev)
122 /* Do not delete read-only files owned by root */
123 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
129 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
130 log_error("Out of memory");
135 /* Is there an item configured for this path? */
136 if (hashmap_get(items, sub_path))
139 if (S_ISDIR(s.st_mode)) {
142 streq(dent->d_name, "lost+found") &&
147 log_warning("Reached max depth on %s.", sub_path);
152 sub_dir = xopendirat(dirfd(d), dent->d_name);
153 if (sub_dir == NULL) {
154 if (errno != ENOENT) {
155 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
162 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
169 /* Ignore ctime, we change it when deleting */
170 age = MAX(timespec_load(&s.st_mtim),
171 timespec_load(&s.st_atim));
175 log_debug("rmdir '%s'\n", sub_path);
177 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
178 if (errno != ENOENT && errno != ENOTEMPTY) {
179 log_error("rmdir(%s): %m", sub_path);
186 if (streq(dent->d_name, ".journal") &&
190 if (streq(dent->d_name, "aquota.user") ||
191 streq(dent->d_name, "aquota.group"))
195 age = MAX3(timespec_load(&s.st_mtim),
196 timespec_load(&s.st_atim),
197 timespec_load(&s.st_ctim));
202 log_debug("unlink '%s'\n", sub_path);
204 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
205 if (errno != ENOENT) {
206 log_error("unlink(%s): %m", sub_path);
217 /* Restore original directory timestamps */
218 times[0] = ds->st_atim;
219 times[1] = ds->st_mtim;
221 if (futimens(dirfd(d), times) < 0)
222 log_error("utimensat(%s): %m", p);
230 static int clean_item(Item *i) {
239 if (i->type != CREATE_DIRECTORY &&
240 i->type != TRUNCATE_DIRECTORY &&
241 i->type != IGNORE_PATH)
244 if (!i->age_set || i->age <= 0)
247 n = now(CLOCK_REALTIME);
253 d = opendir(i->path);
258 log_error("Failed to open directory %s: %m", i->path);
262 if (fstat(dirfd(d), &s) < 0) {
263 log_error("stat(%s) failed: %m", i->path);
268 if (!S_ISDIR(s.st_mode)) {
269 log_error("%s is not a directory.", i->path);
274 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
275 log_error("stat(%s/..) failed: %m", i->path);
280 mountpoint = s.st_dev != ps.st_dev ||
281 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
283 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
292 static int create_item(Item *i) {
303 case RECURSIVE_REMOVE_PATH:
310 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
311 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
315 log_error("Failed to create file %s: %m", i->path);
320 if (fstat(fd, &st) < 0) {
321 log_error("stat(%s) failed: %m", i->path);
326 if (!S_ISREG(st.st_mode)) {
327 log_error("%s is not a file.", i->path);
333 if (fchmod(fd, i->mode) < 0) {
334 log_error("chmod(%s) failed: %m", i->path);
339 if (i->uid_set || i->gid_set)
341 i->uid_set ? i->uid : (uid_t) -1,
342 i->gid_set ? i->gid : (gid_t) -1) < 0) {
343 log_error("chown(%s) failed: %m", i->path);
350 case TRUNCATE_DIRECTORY:
351 case CREATE_DIRECTORY:
354 r = mkdir(i->path, i->mode);
357 if (r < 0 && errno != EEXIST) {
358 log_error("Failed to create directory %s: %m", i->path);
363 if (stat(i->path, &st) < 0) {
364 log_error("stat(%s) failed: %m", i->path);
369 if (!S_ISDIR(st.st_mode)) {
370 log_error("%s is not a directory.", i->path);
376 if (chmod(i->path, i->mode) < 0) {
377 log_error("chmod(%s) failed: %m", i->path);
382 if (i->uid_set || i->gid_set)
384 i->uid_set ? i->uid : (uid_t) -1,
385 i->gid_set ? i->gid : (gid_t) -1) < 0) {
387 log_error("chown(%s) failed: %m", i->path);
395 if ((r = label_fix(i->path)) < 0)
398 log_debug("%s created successfully.", i->path);
402 close_nointr_nofail(fd);
407 static int remove_item(Item *i) {
416 case CREATE_DIRECTORY:
421 if (remove(i->path) < 0 && errno != ENOENT) {
422 log_error("remove(%s): %m", i->path);
428 case TRUNCATE_DIRECTORY:
429 case RECURSIVE_REMOVE_PATH:
430 if ((r = rm_rf(i->path, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
432 log_error("rm_rf(%s): %s", i->path, strerror(-r));
442 static int process_item(Item *i) {
447 r = arg_create ? create_item(i) : 0;
448 q = arg_remove ? remove_item(i) : 0;
449 p = arg_clean ? clean_item(i) : 0;
460 static void item_free(Item *i) {
467 static int parse_line(const char *fname, unsigned line, const char *buffer, const char *prefix) {
469 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
476 if (!(i = new0(Item, 1))) {
477 log_error("Out of memory");
481 if ((n = sscanf(buffer,
494 log_error("[%s:%u] Syntax error.", fname, line);
499 if (i->type != CREATE_FILE &&
500 i->type != TRUNCATE_FILE &&
501 i->type != CREATE_DIRECTORY &&
502 i->type != TRUNCATE_DIRECTORY &&
503 i->type != IGNORE_PATH &&
504 i->type != REMOVE_PATH &&
505 i->type != RECURSIVE_REMOVE_PATH) {
506 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
511 if (!path_is_absolute(i->path)) {
512 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
517 path_kill_slashes(i->path);
519 if (prefix && !path_startswith(i->path, prefix)) {
524 if (user && !streq(user, "-")) {
528 if (streq(user, "root") || streq(user, "0"))
530 else if (safe_atolu(user, &lu) >= 0)
532 else if ((p = getpwnam(user)))
535 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
543 if (group && !streq(group, "-")) {
547 if (streq(group, "root") || streq(group, "0"))
549 else if (safe_atolu(group, &lu) >= 0)
551 else if ((g = getgrnam(group)))
554 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
562 if (mode && !streq(mode, "-")) {
565 if (sscanf(mode, "%o", &m) != 1) {
566 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
574 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
576 if (age && !streq(age, "-")) {
577 if (parse_usec(age, &i->age) < 0) {
578 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
586 if ((r = hashmap_put(items, i->path, i)) < 0) {
587 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
606 static int scandir_filter(const struct dirent *d) {
609 if (ignore_file(d->d_name))
612 if (d->d_type != DT_REG &&
616 return endswith(d->d_name, ".conf");
619 static int help(void) {
621 printf("%s [OPTIONS...]\n\n"
622 "Create and clean up temporary directories.\n\n"
623 " -h --help Show this help\n"
624 " --create Create marked files/directories\n"
625 " --clean Clean up marked directories\n"
626 " --remove Remove marked files/directories\n",
627 program_invocation_short_name);
632 static int parse_argv(int argc, char *argv[]) {
640 static const struct option options[] = {
641 { "help", no_argument, NULL, 'h' },
642 { "create", no_argument, NULL, ARG_CREATE },
643 { "clean", no_argument, NULL, ARG_CLEAN },
644 { "remove", no_argument, NULL, ARG_REMOVE },
653 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
677 log_error("Unknown option code %c", c);
682 if (!arg_clean && !arg_create && !arg_remove) {
690 int main(int argc, char *argv[]) {
691 struct dirent **de = NULL;
693 const char *prefix = NULL;
697 if ((r = parse_argv(argc, argv)) <= 0)
698 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
701 prefix = argv[optind];
705 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
706 log_parse_environment();
711 if (!(items = hashmap_new(string_hash_func, string_compare_func))) {
712 log_error("Out of memory");
717 if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
722 log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
731 for (j = 0; j < n; j++) {
737 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
741 log_error("Failed to allocate file name.");
746 if (!(f = fopen(fn, "re"))) {
748 if (errno != ENOENT) {
749 log_error("Failed to open %s: %m", fn);
759 char line[LINE_MAX], *l;
761 if (!(fgets(line, sizeof(line), f)))
767 if (*l == '#' || *l == 0)
770 if (parse_line(fn, v, l, prefix) < 0)
776 log_error("Failed to read from file %s: %m", fn);
786 HASHMAP_FOREACH(i, items, iterator)
787 if (process_item(i) < 0)
791 while ((i = hashmap_steal_first(items)))