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, /run, which are
51 * volatile and hence need to be recreated on bootup. */
53 typedef enum ItemType {
54 /* These ones take file names */
57 CREATE_DIRECTORY = 'd',
58 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(ItemType 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) {
164 set_free_free(unix_sockets);
171 static bool unix_socket_alive(const char *fn) {
177 return !!set_get(unix_sockets, (char*) fn);
179 /* We don't know, so assume yes */
183 static int dir_cleanup(
186 const struct stat *ds,
193 struct timespec times[2];
194 bool deleted = false;
195 char *sub_path = NULL;
198 while ((dent = readdir(d))) {
202 if (streq(dent->d_name, ".") ||
203 streq(dent->d_name, ".."))
206 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
208 if (errno != ENOENT) {
209 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
216 /* Stay on the same filesystem */
217 if (s.st_dev != rootdev)
220 /* Do not delete read-only files owned by root */
221 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
227 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
228 log_error("Out of memory");
233 /* Is there an item configured for this path? */
234 if (hashmap_get(items, sub_path))
237 if (find_glob(globs, sub_path))
240 if (S_ISDIR(s.st_mode)) {
243 streq(dent->d_name, "lost+found") &&
248 log_warning("Reached max depth on %s.", sub_path);
253 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
254 if (sub_dir == NULL) {
255 if (errno != ENOENT) {
256 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
263 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
270 /* Ignore ctime, we change it when deleting */
271 age = MAX(timespec_load(&s.st_mtim),
272 timespec_load(&s.st_atim));
276 log_debug("rmdir '%s'\n", sub_path);
278 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
279 if (errno != ENOENT && errno != ENOTEMPTY) {
280 log_error("rmdir(%s): %m", sub_path);
286 /* Skip files for which the sticky bit is
287 * set. These are semantics we define, and are
288 * unknown elsewhere. See XDG_RUNTIME_DIR
289 * specification for details. */
290 if (s.st_mode & S_ISVTX)
293 if (mountpoint && S_ISREG(s.st_mode)) {
294 if (streq(dent->d_name, ".journal") &&
298 if (streq(dent->d_name, "aquota.user") ||
299 streq(dent->d_name, "aquota.group"))
303 /* Ignore sockets that are listed in /proc/net/unix */
304 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
307 /* Ignore device nodes */
308 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
311 age = MAX3(timespec_load(&s.st_mtim),
312 timespec_load(&s.st_atim),
313 timespec_load(&s.st_ctim));
318 log_debug("unlink '%s'\n", sub_path);
320 if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
321 if (errno != ENOENT) {
322 log_error("unlink(%s): %m", sub_path);
333 /* Restore original directory timestamps */
334 times[0] = ds->st_atim;
335 times[1] = ds->st_mtim;
337 if (futimens(dirfd(d), times) < 0)
338 log_error("utimensat(%s): %m", p);
346 static int clean_item(Item *i) {
355 if (i->type != CREATE_DIRECTORY &&
356 i->type != TRUNCATE_DIRECTORY &&
357 i->type != IGNORE_PATH)
360 if (!i->age_set || i->age <= 0)
363 n = now(CLOCK_REALTIME);
369 d = opendir(i->path);
374 log_error("Failed to open directory %s: %m", i->path);
378 if (fstat(dirfd(d), &s) < 0) {
379 log_error("stat(%s) failed: %m", i->path);
384 if (!S_ISDIR(s.st_mode)) {
385 log_error("%s is not a directory.", i->path);
390 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
391 log_error("stat(%s/..) failed: %m", i->path);
396 mountpoint = s.st_dev != ps.st_dev ||
397 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
399 r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
408 static int item_set_perms(Item *i) {
410 if (chmod(i->path, i->mode) < 0) {
411 log_error("chmod(%s) failed: %m", i->path);
415 if (i->uid_set || i->gid_set)
417 i->uid_set ? i->uid : (uid_t) -1,
418 i->gid_set ? i->gid : (gid_t) -1) < 0) {
420 log_error("chown(%s) failed: %m", i->path);
424 return label_fix(i->path, false);
427 static int create_item(Item *i) {
438 case RECURSIVE_REMOVE_PATH:
442 case TRUNCATE_FILE: {
446 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
447 (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
451 log_error("Failed to create file %s: %m", i->path);
455 close_nointr_nofail(fd);
457 if (stat(i->path, &st) < 0) {
458 log_error("stat(%s) failed: %m", i->path);
462 if (!S_ISREG(st.st_mode)) {
463 log_error("%s is not a file.", i->path);
467 r = item_set_perms(i);
474 case TRUNCATE_DIRECTORY:
475 case CREATE_DIRECTORY:
478 mkdir_parents(i->path, 0755);
479 r = mkdir(i->path, i->mode);
482 if (r < 0 && errno != EEXIST) {
483 log_error("Failed to create directory %s: %m", i->path);
487 if (stat(i->path, &st) < 0) {
488 log_error("stat(%s) failed: %m", i->path);
492 if (!S_ISDIR(st.st_mode)) {
493 log_error("%s is not a directory.", i->path);
497 r = item_set_perms(i);
506 r = mkfifo(i->path, i->mode);
509 if (r < 0 && errno != EEXIST) {
510 log_error("Failed to create fifo %s: %m", i->path);
514 if (stat(i->path, &st) < 0) {
515 log_error("stat(%s) failed: %m", i->path);
519 if (!S_ISFIFO(st.st_mode)) {
520 log_error("%s is not a fifo.", i->path);
524 r = item_set_perms(i);
531 log_debug("%s created successfully.", i->path);
536 static int remove_item_instance(Item *i, const char *instance) {
545 case CREATE_DIRECTORY:
551 if (remove(instance) < 0 && errno != ENOENT) {
552 log_error("remove(%s): %m", instance);
558 case TRUNCATE_DIRECTORY:
559 case RECURSIVE_REMOVE_PATH:
560 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
562 log_error("rm_rf(%s): %s", instance, strerror(-r));
572 static int remove_item(Item *i) {
579 case CREATE_DIRECTORY:
585 case TRUNCATE_DIRECTORY:
586 case RECURSIVE_REMOVE_PATH: {
594 if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
596 if (k != GLOB_NOMATCH) {
600 log_error("glob(%s) failed: %m", i->path);
605 STRV_FOREACH(fn, g.gl_pathv)
606 if ((k = remove_item_instance(i, *fn)) < 0)
617 static int process_item(Item *i) {
622 r = arg_create ? create_item(i) : 0;
623 q = arg_remove ? remove_item(i) : 0;
624 p = arg_clean ? clean_item(i) : 0;
635 static void item_free(Item *i) {
642 static bool item_equal(Item *a, Item *b) {
646 if (!streq_ptr(a->path, b->path))
649 if (a->type != b->type)
652 if (a->uid_set != b->uid_set ||
653 (a->uid_set && a->uid != b->uid))
656 if (a->gid_set != b->gid_set ||
657 (a->gid_set && a->gid != b->gid))
660 if (a->mode_set != b->mode_set ||
661 (a->mode_set && a->mode != b->mode))
664 if (a->age_set != b->age_set ||
665 (a->age_set && a->age != b->age))
671 static int parse_line(const char *fname, unsigned line, const char *buffer) {
673 char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
682 if (!(i = new0(Item, 1))) {
683 log_error("Out of memory");
700 log_error("[%s:%u] Syntax error.", fname, line);
706 if (i->type != CREATE_FILE &&
707 i->type != TRUNCATE_FILE &&
708 i->type != CREATE_DIRECTORY &&
709 i->type != TRUNCATE_DIRECTORY &&
710 i->type != CREATE_FIFO &&
711 i->type != IGNORE_PATH &&
712 i->type != REMOVE_PATH &&
713 i->type != RECURSIVE_REMOVE_PATH) {
714 log_error("[%s:%u] Unknown file type '%c'.", fname, line, i->type);
719 if (!path_is_absolute(i->path)) {
720 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
725 path_kill_slashes(i->path);
727 if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
732 if (user && !streq(user, "-")) {
733 const char *u = user;
735 r = get_user_creds(&u, &i->uid, NULL, NULL);
737 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
744 if (group && !streq(group, "-")) {
745 const char *g = group;
747 r = get_group_creds(&g, &i->gid);
749 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
756 if (mode && !streq(mode, "-")) {
759 if (sscanf(mode, "%o", &m) != 1) {
760 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
768 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
770 if (age && !streq(age, "-")) {
771 if (parse_usec(age, &i->age) < 0) {
772 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
780 h = needs_glob(i->type) ? globs : items;
782 if ((existing = hashmap_get(h, i->path))) {
784 /* Two identical items are fine */
785 if (!item_equal(existing, i))
786 log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
792 if ((r = hashmap_put(h, i->path, i)) < 0) {
793 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
812 static int help(void) {
814 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
815 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
816 " -h --help Show this help\n"
817 " --create Create marked files/directories\n"
818 " --clean Clean up marked directories\n"
819 " --remove Remove marked files/directories\n"
820 " --prefix=PATH Only apply rules that apply to paths with the specified prefix\n",
821 program_invocation_short_name);
826 static int parse_argv(int argc, char *argv[]) {
835 static const struct option options[] = {
836 { "help", no_argument, NULL, 'h' },
837 { "create", no_argument, NULL, ARG_CREATE },
838 { "clean", no_argument, NULL, ARG_CLEAN },
839 { "remove", no_argument, NULL, ARG_REMOVE },
840 { "prefix", required_argument, NULL, ARG_PREFIX },
849 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
877 log_error("Unknown option code %c", c);
882 if (!arg_clean && !arg_create && !arg_remove) {
883 log_error("You need to specify at least one of --clean, --create or --remove.");
890 static int read_config_file(const char *fn, bool ignore_enoent) {
897 if (!(f = fopen(fn, "re"))) {
899 if (ignore_enoent && errno == ENOENT)
902 log_error("Failed to open %s: %m", fn);
906 log_debug("apply: %s\n", fn);
908 char line[LINE_MAX], *l;
911 if (!(fgets(line, sizeof(line), f)))
917 if (*l == '#' || *l == 0)
920 if ((k = parse_line(fn, v, l)) < 0)
926 log_error("Failed to read from file %s: %m", fn);
936 int main(int argc, char *argv[]) {
941 if ((r = parse_argv(argc, argv)) <= 0)
942 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
944 log_set_target(LOG_TARGET_AUTO);
945 log_parse_environment();
952 items = hashmap_new(string_hash_func, string_compare_func);
953 globs = hashmap_new(string_hash_func, string_compare_func);
955 if (!items || !globs) {
956 log_error("Out of memory");
966 for (j = optind; j < argc; j++)
967 if (read_config_file(argv[j], false) < 0)
973 r = conf_files_list(&files, ".conf",
976 "/usr/local/lib/tmpfiles.d",
977 "/usr/lib/tmpfiles.d",
981 log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
985 STRV_FOREACH(f, files) {
986 if (read_config_file(*f, true) < 0)
993 HASHMAP_FOREACH(i, globs, iterator)
996 HASHMAP_FOREACH(i, items, iterator)
1000 while ((i = hashmap_steal_first(items)))
1003 while ((i = hashmap_steal_first(globs)))
1006 hashmap_free(items);
1007 hashmap_free(globs);
1009 set_free_free(unix_sockets);