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;
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 int dir_cleanup(
110 const struct stat *ds,
117 struct timespec times[2];
118 bool deleted = false;
119 char *sub_path = NULL;
122 while ((dent = readdir(d))) {
126 if (streq(dent->d_name, ".") ||
127 streq(dent->d_name, ".."))
130 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
132 if (errno != ENOENT) {
133 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
140 /* Stay on the same filesystem */
141 if (s.st_dev != rootdev)
144 /* Do not delete read-only files owned by root */
145 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
151 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
152 log_error("Out of memory");
157 /* Is there an item configured for this path? */
158 if (hashmap_get(items, sub_path))
161 if (find_glob(globs, sub_path))
164 if (S_ISDIR(s.st_mode)) {
167 streq(dent->d_name, "lost+found") &&
172 log_warning("Reached max depth on %s.", sub_path);
177 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
178 if (sub_dir == NULL) {
179 if (errno != ENOENT) {
180 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
187 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
194 /* Ignore ctime, we change it when deleting */
195 age = MAX(timespec_load(&s.st_mtim),
196 timespec_load(&s.st_atim));
200 log_debug("rmdir '%s'\n", sub_path);
202 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
203 if (errno != ENOENT && errno != ENOTEMPTY) {
204 log_error("rmdir(%s): %m", sub_path);
210 /* Skip files for which the sticky bit is
211 * set. These are semantics we define, and are
212 * unknown elsewhere. See XDG_RUNTIME_DIR
213 * specification for details. */
214 if (s.st_mode & S_ISVTX)
218 if (streq(dent->d_name, ".journal") &&
222 if (streq(dent->d_name, "aquota.user") ||
223 streq(dent->d_name, "aquota.group"))
227 age = MAX3(timespec_load(&s.st_mtim),
228 timespec_load(&s.st_atim),
229 timespec_load(&s.st_ctim));
234 log_debug("unlink '%s'\n", sub_path);
236 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
237 if (errno != ENOENT) {
238 log_error("unlink(%s): %m", sub_path);
249 /* Restore original directory timestamps */
250 times[0] = ds->st_atim;
251 times[1] = ds->st_mtim;
253 if (futimens(dirfd(d), times) < 0)
254 log_error("utimensat(%s): %m", p);
262 static int clean_item(Item *i) {
271 if (i->type != CREATE_DIRECTORY &&
272 i->type != TRUNCATE_DIRECTORY &&
273 i->type != IGNORE_PATH)
276 if (!i->age_set || i->age <= 0)
279 n = now(CLOCK_REALTIME);
285 d = opendir(i->path);
290 log_error("Failed to open directory %s: %m", i->path);
294 if (fstat(dirfd(d), &s) < 0) {
295 log_error("stat(%s) failed: %m", i->path);
300 if (!S_ISDIR(s.st_mode)) {
301 log_error("%s is not a directory.", i->path);
306 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
307 log_error("stat(%s/..) failed: %m", i->path);
312 mountpoint = s.st_dev != ps.st_dev ||
313 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
315 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
324 static int create_item(Item *i) {
335 case RECURSIVE_REMOVE_PATH:
342 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
343 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
347 log_error("Failed to create file %s: %m", i->path);
352 if (fstat(fd, &st) < 0) {
353 log_error("stat(%s) failed: %m", i->path);
358 if (!S_ISREG(st.st_mode)) {
359 log_error("%s is not a file.", i->path);
365 if (fchmod(fd, i->mode) < 0) {
366 log_error("chmod(%s) failed: %m", i->path);
371 if (i->uid_set || i->gid_set)
373 i->uid_set ? i->uid : (uid_t) -1,
374 i->gid_set ? i->gid : (gid_t) -1) < 0) {
375 log_error("chown(%s) failed: %m", i->path);
382 case TRUNCATE_DIRECTORY:
383 case CREATE_DIRECTORY:
386 r = mkdir(i->path, i->mode);
389 if (r < 0 && errno != EEXIST) {
390 log_error("Failed to create directory %s: %m", i->path);
395 if (stat(i->path, &st) < 0) {
396 log_error("stat(%s) failed: %m", i->path);
401 if (!S_ISDIR(st.st_mode)) {
402 log_error("%s is not a directory.", i->path);
408 if (chmod(i->path, i->mode) < 0) {
409 log_error("chmod(%s) failed: %m", i->path);
414 if (i->uid_set || i->gid_set)
416 i->uid_set ? i->uid : (uid_t) -1,
417 i->gid_set ? i->gid : (gid_t) -1) < 0) {
419 log_error("chown(%s) failed: %m", i->path);
427 if ((r = label_fix(i->path)) < 0)
430 log_debug("%s created successfully.", i->path);
434 close_nointr_nofail(fd);
439 static int remove_item(Item *i, const char *instance) {
448 case CREATE_DIRECTORY:
453 if (remove(instance) < 0 && errno != ENOENT) {
454 log_error("remove(%s): %m", instance);
460 case TRUNCATE_DIRECTORY:
461 case RECURSIVE_REMOVE_PATH:
462 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
464 log_error("rm_rf(%s): %s", instance, strerror(-r));
474 static int remove_item_glob(Item *i) {
481 case CREATE_DIRECTORY:
486 case TRUNCATE_DIRECTORY:
487 case RECURSIVE_REMOVE_PATH: {
495 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
497 if (k != GLOB_NOMATCH) {
501 log_error("glob(%s) failed: %m", i->path);
506 STRV_FOREACH(fn, g.gl_pathv)
507 if ((k = remove_item(i, *fn)) < 0)
518 static int process_item(Item *i) {
523 r = arg_create ? create_item(i) : 0;
524 q = arg_remove ? remove_item_glob(i) : 0;
525 p = arg_clean ? clean_item(i) : 0;
536 static void item_free(Item *i) {
543 static int parse_line(const char *fname, unsigned line, const char *buffer) {
545 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
552 if (!(i = new0(Item, 1))) {
553 log_error("Out of memory");
570 log_error("[%s:%u] Syntax error.", fname, line);
575 if (i->type != CREATE_FILE &&
576 i->type != TRUNCATE_FILE &&
577 i->type != CREATE_DIRECTORY &&
578 i->type != TRUNCATE_DIRECTORY &&
579 i->type != IGNORE_PATH &&
580 i->type != REMOVE_PATH &&
581 i->type != RECURSIVE_REMOVE_PATH) {
582 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
587 if (!path_is_absolute(i->path)) {
588 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
593 path_kill_slashes(i->path);
595 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
600 if (user && !streq(user, "-")) {
604 if (streq(user, "root") || streq(user, "0"))
606 else if (safe_atolu(user, &lu) >= 0)
608 else if ((p = getpwnam(user)))
611 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
619 if (group && !streq(group, "-")) {
623 if (streq(group, "root") || streq(group, "0"))
625 else if (safe_atolu(group, &lu) >= 0)
627 else if ((g = getgrnam(group)))
630 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
638 if (mode && !streq(mode, "-")) {
641 if (sscanf(mode, "%o", &m) != 1) {
642 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
650 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
652 if (age && !streq(age, "-")) {
653 if (parse_usec(age, &i->age) < 0) {
654 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
662 if ((r = hashmap_put(needs_glob(i->type) ? globs : items, i->path, i)) < 0) {
664 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
669 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
688 static int scandir_filter(const struct dirent *d) {
691 if (ignore_file(d->d_name))
694 if (d->d_type != DT_REG &&
698 return endswith(d->d_name, ".conf");
701 static int help(void) {
703 printf("%s [OPTIONS...] [CONFIGURATION FILE]\n\n"
704 "Create and clean up temporary files and directories.\n\n"
705 " -h --help Show this help\n"
706 " --create Create marked files/directories\n"
707 " --clean Clean up marked directories\n"
708 " --remove Remove marked files/directories\n"
709 " --prefix=PATH Only apply rules that apply to paths\n",
710 program_invocation_short_name);
715 static int parse_argv(int argc, char *argv[]) {
724 static const struct option options[] = {
725 { "help", no_argument, NULL, 'h' },
726 { "create", no_argument, NULL, ARG_CREATE },
727 { "clean", no_argument, NULL, ARG_CLEAN },
728 { "remove", no_argument, NULL, ARG_REMOVE },
729 { "prefix", required_argument, NULL, ARG_PREFIX },
738 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
766 log_error("Unknown option code %c", c);
771 if (!arg_clean && !arg_create && !arg_remove) {
772 log_error("You need to specify at leat one of --clean, --create or --remove.");
779 static int read_config_file(const char *fn, bool ignore_enoent) {
786 if (!(f = fopen(fn, "re"))) {
788 if (ignore_enoent && errno == ENOENT)
791 log_error("Failed to open %s: %m", fn);
796 char line[LINE_MAX], *l;
799 if (!(fgets(line, sizeof(line), f)))
805 if (*l == '#' || *l == 0)
808 if ((k = parse_line(fn, v, l)) < 0)
814 log_error("Failed to read from file %s: %m", fn);
824 int main(int argc, char *argv[]) {
829 if ((r = parse_argv(argc, argv)) <= 0)
830 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
832 log_set_target(LOG_TARGET_AUTO);
833 log_parse_environment();
838 items = hashmap_new(string_hash_func, string_compare_func);
839 globs = hashmap_new(string_hash_func, string_compare_func);
841 if (!items || !globs) {
842 log_error("Out of memory");
852 for (j = optind; j < argc; j++)
853 if (read_config_file(argv[j], false) < 0)
858 struct dirent **de = NULL;
860 if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
862 if (errno != ENOENT) {
863 log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
870 for (j = 0; j < n; j++) {
874 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
878 log_error("Failed to allocate file name.");
883 if (read_config_file(fn, true) < 0)
892 HASHMAP_FOREACH(i, globs, iterator)
893 if (process_item(i) < 0)
896 HASHMAP_FOREACH(i, items, iterator)
897 if (process_item(i) < 0)
901 while ((i = hashmap_steal_first(items)))