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;
83 static Set *unix_sockets = NULL;
85 static bool arg_create = false;
86 static bool arg_clean = false;
87 static bool arg_remove = false;
89 static const char *arg_prefix = NULL;
93 static bool needs_glob(int t) {
94 return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH;
97 static struct Item* find_glob(Hashmap *h, const char *match) {
101 HASHMAP_FOREACH(j, h, i)
102 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
108 static void load_unix_sockets(void) {
115 /* We maintain a cache of the sockets we found in
116 * /proc/net/unix to speed things up a little. */
118 if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
121 if (!(f = fopen("/proc/net/unix", "re")))
124 if (!(fgets(line, sizeof(line), f)))
131 if (!(fgets(line, sizeof(line), f)))
136 if (strlen(line) < 53)
140 p += strspn(p, WHITESPACE);
141 p += strcspn(p, WHITESPACE);
142 p += strspn(p, WHITESPACE);
147 if (!(s = strdup(p)))
150 path_kill_slashes(s);
152 if ((k = set_put(unix_sockets, s)) < 0) {
163 set_free_free(unix_sockets);
170 static bool unix_socket_alive(const char *fn) {
176 return !!set_get(unix_sockets, (char*) fn);
178 /* We don't know, so assume yes */
182 static int dir_cleanup(
185 const struct stat *ds,
192 struct timespec times[2];
193 bool deleted = false;
194 char *sub_path = NULL;
197 while ((dent = readdir(d))) {
201 if (streq(dent->d_name, ".") ||
202 streq(dent->d_name, ".."))
205 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
207 if (errno != ENOENT) {
208 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
215 /* Stay on the same filesystem */
216 if (s.st_dev != rootdev)
219 /* Do not delete read-only files owned by root */
220 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
226 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
227 log_error("Out of memory");
232 /* Is there an item configured for this path? */
233 if (hashmap_get(items, sub_path))
236 if (find_glob(globs, sub_path))
239 if (S_ISDIR(s.st_mode)) {
242 streq(dent->d_name, "lost+found") &&
247 log_warning("Reached max depth on %s.", sub_path);
252 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
253 if (sub_dir == NULL) {
254 if (errno != ENOENT) {
255 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
262 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
269 /* Ignore ctime, we change it when deleting */
270 age = MAX(timespec_load(&s.st_mtim),
271 timespec_load(&s.st_atim));
275 log_debug("rmdir '%s'\n", sub_path);
277 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
278 if (errno != ENOENT && errno != ENOTEMPTY) {
279 log_error("rmdir(%s): %m", sub_path);
285 /* Skip files for which the sticky bit is
286 * set. These are semantics we define, and are
287 * unknown elsewhere. See XDG_RUNTIME_DIR
288 * specification for details. */
289 if (s.st_mode & S_ISVTX)
292 if (mountpoint && S_ISREG(s.st_mode)) {
293 if (streq(dent->d_name, ".journal") &&
297 if (streq(dent->d_name, "aquota.user") ||
298 streq(dent->d_name, "aquota.group"))
302 /* Ignore sockets that are listed in /proc/net/unix */
303 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
306 age = MAX3(timespec_load(&s.st_mtim),
307 timespec_load(&s.st_atim),
308 timespec_load(&s.st_ctim));
313 log_debug("unlink '%s'\n", sub_path);
315 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
316 if (errno != ENOENT) {
317 log_error("unlink(%s): %m", sub_path);
328 /* Restore original directory timestamps */
329 times[0] = ds->st_atim;
330 times[1] = ds->st_mtim;
332 if (futimens(dirfd(d), times) < 0)
333 log_error("utimensat(%s): %m", p);
341 static int clean_item(Item *i) {
350 if (i->type != CREATE_DIRECTORY &&
351 i->type != TRUNCATE_DIRECTORY &&
352 i->type != IGNORE_PATH)
355 if (!i->age_set || i->age <= 0)
358 n = now(CLOCK_REALTIME);
364 d = opendir(i->path);
369 log_error("Failed to open directory %s: %m", i->path);
373 if (fstat(dirfd(d), &s) < 0) {
374 log_error("stat(%s) failed: %m", i->path);
379 if (!S_ISDIR(s.st_mode)) {
380 log_error("%s is not a directory.", i->path);
385 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
386 log_error("stat(%s/..) failed: %m", i->path);
391 mountpoint = s.st_dev != ps.st_dev ||
392 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
394 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
403 static int create_item(Item *i) {
414 case RECURSIVE_REMOVE_PATH:
421 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
422 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
426 log_error("Failed to create file %s: %m", i->path);
431 if (fstat(fd, &st) < 0) {
432 log_error("stat(%s) failed: %m", i->path);
437 if (!S_ISREG(st.st_mode)) {
438 log_error("%s is not a file.", i->path);
444 if (fchmod(fd, i->mode) < 0) {
445 log_error("chmod(%s) failed: %m", i->path);
450 if (i->uid_set || i->gid_set)
452 i->uid_set ? i->uid : (uid_t) -1,
453 i->gid_set ? i->gid : (gid_t) -1) < 0) {
454 log_error("chown(%s) failed: %m", i->path);
461 case TRUNCATE_DIRECTORY:
462 case CREATE_DIRECTORY:
465 r = mkdir(i->path, i->mode);
468 if (r < 0 && errno != EEXIST) {
469 log_error("Failed to create directory %s: %m", i->path);
474 if (stat(i->path, &st) < 0) {
475 log_error("stat(%s) failed: %m", i->path);
480 if (!S_ISDIR(st.st_mode)) {
481 log_error("%s is not a directory.", i->path);
487 if (chmod(i->path, i->mode) < 0) {
488 log_error("chmod(%s) failed: %m", i->path);
493 if (i->uid_set || i->gid_set)
495 i->uid_set ? i->uid : (uid_t) -1,
496 i->gid_set ? i->gid : (gid_t) -1) < 0) {
498 log_error("chown(%s) failed: %m", i->path);
506 if ((r = label_fix(i->path)) < 0)
509 log_debug("%s created successfully.", i->path);
513 close_nointr_nofail(fd);
518 static int remove_item(Item *i, const char *instance) {
527 case CREATE_DIRECTORY:
532 if (remove(instance) < 0 && errno != ENOENT) {
533 log_error("remove(%s): %m", instance);
539 case TRUNCATE_DIRECTORY:
540 case RECURSIVE_REMOVE_PATH:
541 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
543 log_error("rm_rf(%s): %s", instance, strerror(-r));
553 static int remove_item_glob(Item *i) {
560 case CREATE_DIRECTORY:
565 case TRUNCATE_DIRECTORY:
566 case RECURSIVE_REMOVE_PATH: {
574 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
576 if (k != GLOB_NOMATCH) {
580 log_error("glob(%s) failed: %m", i->path);
585 STRV_FOREACH(fn, g.gl_pathv)
586 if ((k = remove_item(i, *fn)) < 0)
597 static int process_item(Item *i) {
602 r = arg_create ? create_item(i) : 0;
603 q = arg_remove ? remove_item_glob(i) : 0;
604 p = arg_clean ? clean_item(i) : 0;
615 static void item_free(Item *i) {
622 static int parse_line(const char *fname, unsigned line, const char *buffer) {
624 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
631 if (!(i = new0(Item, 1))) {
632 log_error("Out of memory");
649 log_error("[%s:%u] Syntax error.", fname, line);
654 if (i->type != CREATE_FILE &&
655 i->type != TRUNCATE_FILE &&
656 i->type != CREATE_DIRECTORY &&
657 i->type != TRUNCATE_DIRECTORY &&
658 i->type != IGNORE_PATH &&
659 i->type != REMOVE_PATH &&
660 i->type != RECURSIVE_REMOVE_PATH) {
661 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
666 if (!path_is_absolute(i->path)) {
667 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
672 path_kill_slashes(i->path);
674 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
679 if (user && !streq(user, "-")) {
683 if (streq(user, "root") || streq(user, "0"))
685 else if (safe_atolu(user, &lu) >= 0)
687 else if ((p = getpwnam(user)))
690 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
698 if (group && !streq(group, "-")) {
702 if (streq(group, "root") || streq(group, "0"))
704 else if (safe_atolu(group, &lu) >= 0)
706 else if ((g = getgrnam(group)))
709 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
717 if (mode && !streq(mode, "-")) {
720 if (sscanf(mode, "%o", &m) != 1) {
721 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
729 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
731 if (age && !streq(age, "-")) {
732 if (parse_usec(age, &i->age) < 0) {
733 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
741 if ((r = hashmap_put(needs_glob(i->type) ? globs : items, i->path, i)) < 0) {
743 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
748 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
767 static int scandir_filter(const struct dirent *d) {
770 if (ignore_file(d->d_name))
773 if (d->d_type != DT_REG &&
777 return endswith(d->d_name, ".conf");
780 static int help(void) {
782 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
783 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
784 " -h --help Show this help\n"
785 " --create Create marked files/directories\n"
786 " --clean Clean up marked directories\n"
787 " --remove Remove marked files/directories\n"
788 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
789 program_invocation_short_name);
794 static int parse_argv(int argc, char *argv[]) {
803 static const struct option options[] = {
804 { "help", no_argument, NULL, 'h' },
805 { "create", no_argument, NULL, ARG_CREATE },
806 { "clean", no_argument, NULL, ARG_CLEAN },
807 { "remove", no_argument, NULL, ARG_REMOVE },
808 { "prefix", required_argument, NULL, ARG_PREFIX },
817 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
845 log_error("Unknown option code %c", c);
850 if (!arg_clean && !arg_create && !arg_remove) {
851 log_error("You need to specify at leat one of --clean, --create or --remove.");
858 static int read_config_file(const char *fn, bool ignore_enoent) {
865 if (!(f = fopen(fn, "re"))) {
867 if (ignore_enoent && errno == ENOENT)
870 log_error("Failed to open %s: %m", fn);
875 char line[LINE_MAX], *l;
878 if (!(fgets(line, sizeof(line), f)))
884 if (*l == '#' || *l == 0)
887 if ((k = parse_line(fn, v, l)) < 0)
893 log_error("Failed to read from file %s: %m", fn);
903 int main(int argc, char *argv[]) {
908 if ((r = parse_argv(argc, argv)) <= 0)
909 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
911 log_set_target(LOG_TARGET_AUTO);
912 log_parse_environment();
917 items = hashmap_new(string_hash_func, string_compare_func);
918 globs = hashmap_new(string_hash_func, string_compare_func);
920 if (!items || !globs) {
921 log_error("Out of memory");
931 for (j = optind; j < argc; j++)
932 if (read_config_file(argv[j], false) < 0)
937 struct dirent **de = NULL;
939 if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
941 if (errno != ENOENT) {
942 log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
949 for (j = 0; j < n; j++) {
953 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
957 log_error("Failed to allocate file name.");
962 if (read_config_file(fn, true) < 0)
971 HASHMAP_FOREACH(i, globs, iterator)
972 if (process_item(i) < 0)
975 HASHMAP_FOREACH(i, items, iterator)
976 if (process_item(i) < 0)
980 while ((i = hashmap_steal_first(items)))
983 while ((i = hashmap_steal_first(globs)))
989 set_free_free(unix_sockets);