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, O_NOFOLLOW);
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);
185 /* Skip files for which the sticky bit is
186 * set. These are semantics we define, and are
187 * unknown elsewhere. See XDG_RUNTIME_DIR
188 * specification for details. */
189 if (s.st_mode & S_ISVTX)
193 if (streq(dent->d_name, ".journal") &&
197 if (streq(dent->d_name, "aquota.user") ||
198 streq(dent->d_name, "aquota.group"))
202 age = MAX3(timespec_load(&s.st_mtim),
203 timespec_load(&s.st_atim),
204 timespec_load(&s.st_ctim));
209 log_debug("unlink '%s'\n", sub_path);
211 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
212 if (errno != ENOENT) {
213 log_error("unlink(%s): %m", sub_path);
224 /* Restore original directory timestamps */
225 times[0] = ds->st_atim;
226 times[1] = ds->st_mtim;
228 if (futimens(dirfd(d), times) < 0)
229 log_error("utimensat(%s): %m", p);
237 static int clean_item(Item *i) {
246 if (i->type != CREATE_DIRECTORY &&
247 i->type != TRUNCATE_DIRECTORY &&
248 i->type != IGNORE_PATH)
251 if (!i->age_set || i->age <= 0)
254 n = now(CLOCK_REALTIME);
260 d = opendir(i->path);
265 log_error("Failed to open directory %s: %m", i->path);
269 if (fstat(dirfd(d), &s) < 0) {
270 log_error("stat(%s) failed: %m", i->path);
275 if (!S_ISDIR(s.st_mode)) {
276 log_error("%s is not a directory.", i->path);
281 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
282 log_error("stat(%s/..) failed: %m", i->path);
287 mountpoint = s.st_dev != ps.st_dev ||
288 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
290 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
299 static int create_item(Item *i) {
310 case RECURSIVE_REMOVE_PATH:
317 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
318 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
322 log_error("Failed to create file %s: %m", i->path);
327 if (fstat(fd, &st) < 0) {
328 log_error("stat(%s) failed: %m", i->path);
333 if (!S_ISREG(st.st_mode)) {
334 log_error("%s is not a file.", i->path);
340 if (fchmod(fd, i->mode) < 0) {
341 log_error("chmod(%s) failed: %m", i->path);
346 if (i->uid_set || i->gid_set)
348 i->uid_set ? i->uid : (uid_t) -1,
349 i->gid_set ? i->gid : (gid_t) -1) < 0) {
350 log_error("chown(%s) failed: %m", i->path);
357 case TRUNCATE_DIRECTORY:
358 case CREATE_DIRECTORY:
361 r = mkdir(i->path, i->mode);
364 if (r < 0 && errno != EEXIST) {
365 log_error("Failed to create directory %s: %m", i->path);
370 if (stat(i->path, &st) < 0) {
371 log_error("stat(%s) failed: %m", i->path);
376 if (!S_ISDIR(st.st_mode)) {
377 log_error("%s is not a directory.", i->path);
383 if (chmod(i->path, i->mode) < 0) {
384 log_error("chmod(%s) failed: %m", i->path);
389 if (i->uid_set || i->gid_set)
391 i->uid_set ? i->uid : (uid_t) -1,
392 i->gid_set ? i->gid : (gid_t) -1) < 0) {
394 log_error("chown(%s) failed: %m", i->path);
402 if ((r = label_fix(i->path)) < 0)
405 log_debug("%s created successfully.", i->path);
409 close_nointr_nofail(fd);
414 static int remove_item(Item *i) {
423 case CREATE_DIRECTORY:
428 if (remove(i->path) < 0 && errno != ENOENT) {
429 log_error("remove(%s): %m", i->path);
435 case TRUNCATE_DIRECTORY:
436 case RECURSIVE_REMOVE_PATH:
437 if ((r = rm_rf(i->path, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
439 log_error("rm_rf(%s): %s", i->path, strerror(-r));
449 static int process_item(Item *i) {
454 r = arg_create ? create_item(i) : 0;
455 q = arg_remove ? remove_item(i) : 0;
456 p = arg_clean ? clean_item(i) : 0;
467 static void item_free(Item *i) {
474 static int parse_line(const char *fname, unsigned line, const char *buffer, const char *prefix) {
476 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
483 if (!(i = new0(Item, 1))) {
484 log_error("Out of memory");
488 if ((n = sscanf(buffer,
501 log_error("[%s:%u] Syntax error.", fname, line);
506 if (i->type != CREATE_FILE &&
507 i->type != TRUNCATE_FILE &&
508 i->type != CREATE_DIRECTORY &&
509 i->type != TRUNCATE_DIRECTORY &&
510 i->type != IGNORE_PATH &&
511 i->type != REMOVE_PATH &&
512 i->type != RECURSIVE_REMOVE_PATH) {
513 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
518 if (!path_is_absolute(i->path)) {
519 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
524 path_kill_slashes(i->path);
526 if (prefix && !path_startswith(i->path, prefix)) {
531 if (user && !streq(user, "-")) {
535 if (streq(user, "root") || streq(user, "0"))
537 else if (safe_atolu(user, &lu) >= 0)
539 else if ((p = getpwnam(user)))
542 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
550 if (group && !streq(group, "-")) {
554 if (streq(group, "root") || streq(group, "0"))
556 else if (safe_atolu(group, &lu) >= 0)
558 else if ((g = getgrnam(group)))
561 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
569 if (mode && !streq(mode, "-")) {
572 if (sscanf(mode, "%o", &m) != 1) {
573 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
581 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
583 if (age && !streq(age, "-")) {
584 if (parse_usec(age, &i->age) < 0) {
585 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
593 if ((r = hashmap_put(items, i->path, i)) < 0) {
595 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
600 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
619 static int scandir_filter(const struct dirent *d) {
622 if (ignore_file(d->d_name))
625 if (d->d_type != DT_REG &&
629 return endswith(d->d_name, ".conf");
632 static int help(void) {
634 printf("%s [OPTIONS...]\n\n"
635 "Create and clean up temporary directories.\n\n"
636 " -h --help Show this help\n"
637 " --create Create marked files/directories\n"
638 " --clean Clean up marked directories\n"
639 " --remove Remove marked files/directories\n",
640 program_invocation_short_name);
645 static int parse_argv(int argc, char *argv[]) {
653 static const struct option options[] = {
654 { "help", no_argument, NULL, 'h' },
655 { "create", no_argument, NULL, ARG_CREATE },
656 { "clean", no_argument, NULL, ARG_CLEAN },
657 { "remove", no_argument, NULL, ARG_REMOVE },
666 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
690 log_error("Unknown option code %c", c);
695 if (!arg_clean && !arg_create && !arg_remove) {
703 int main(int argc, char *argv[]) {
704 struct dirent **de = NULL;
706 const char *prefix = NULL;
710 if ((r = parse_argv(argc, argv)) <= 0)
711 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
714 prefix = argv[optind];
718 log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
719 log_parse_environment();
724 if (!(items = hashmap_new(string_hash_func, string_compare_func))) {
725 log_error("Out of memory");
730 if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
735 log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
744 for (j = 0; j < n; j++) {
750 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
754 log_error("Failed to allocate file name.");
759 if (!(f = fopen(fn, "re"))) {
761 if (errno != ENOENT) {
762 log_error("Failed to open %s: %m", fn);
772 char line[LINE_MAX], *l;
774 if (!(fgets(line, sizeof(line), f)))
780 if (*l == '#' || *l == 0)
783 if (parse_line(fn, v, l, prefix) < 0)
789 log_error("Failed to read from file %s: %m", fn);
799 HASHMAP_FOREACH(i, items, iterator)
800 if (process_item(i) < 0)
804 while ((i = hashmap_steal_first(items)))