chiark / gitweb /
units: set TERM for gettys again, since they acquire a TTY on their own
[elogind.git] / src / tmpfiles.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering, Kay Sievers
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <limits.h>
28 #include <dirent.h>
29 #include <grp.h>
30 #include <pwd.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <stddef.h>
34 #include <getopt.h>
35 #include <stdbool.h>
36 #include <time.h>
37 #include <sys/types.h>
38 #include <sys/param.h>
39
40 #include "log.h"
41 #include "util.h"
42 #include "strv.h"
43 #include "label.h"
44 #include "set.h"
45
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
50  * bootup. */
51
52 enum {
53         CREATE_FILE = 'f',
54         TRUNCATE_FILE = 'F',
55         CREATE_DIRECTORY = 'd',
56         TRUNCATE_DIRECTORY = 'D',
57         IGNORE_PATH = 'x',
58         REMOVE_PATH = 'r',
59         RECURSIVE_REMOVE_PATH = 'R'
60 };
61
62 typedef struct Item {
63         char type;
64
65         char *path;
66         uid_t uid;
67         gid_t gid;
68         mode_t mode;
69         usec_t age;
70
71         bool uid_set:1;
72         bool gid_set:1;
73         bool mode_set:1;
74         bool age_set:1;
75 } Item;
76
77 static Hashmap *items = NULL;
78
79 static bool arg_create = false;
80 static bool arg_clean = false;
81 static bool arg_remove = false;
82
83 #define MAX_DEPTH 256
84
85 static int dir_cleanup(
86                 const char *p,
87                 DIR *d,
88                 const struct stat *ds,
89                 usec_t cutoff,
90                 dev_t rootdev,
91                 bool mountpoint,
92                 int maxdepth)
93 {
94         struct dirent *dent;
95         struct timespec times[2];
96         bool deleted = false;
97         char *sub_path = NULL;
98         int r = 0;
99
100         while ((dent = readdir(d))) {
101                 struct stat s;
102                 usec_t age;
103
104                 if (streq(dent->d_name, ".") ||
105                     streq(dent->d_name, ".."))
106                         continue;
107
108                 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
109
110                         if (errno != ENOENT) {
111                                 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
112                                 r = -errno;
113                         }
114
115                         continue;
116                 }
117
118                 /* Stay on the same filesystem */
119                 if (s.st_dev != rootdev)
120                         continue;
121
122                 /* Do not delete read-only files owned by root */
123                 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
124                         continue;
125
126                 free(sub_path);
127                 sub_path = NULL;
128
129                 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
130                         log_error("Out of memory");
131                         r = -ENOMEM;
132                         goto finish;
133                 }
134
135                 /* Is there an item configured for this path? */
136                 if (hashmap_get(items, sub_path))
137                         continue;
138
139                 if (S_ISDIR(s.st_mode)) {
140
141                         if (mountpoint &&
142                             streq(dent->d_name, "lost+found") &&
143                             s.st_uid == 0)
144                                 continue;
145
146                         if (maxdepth <= 0)
147                                 log_warning("Reached max depth on %s.", sub_path);
148                         else {
149                                 DIR *sub_dir;
150                                 int q;
151
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);
156                                                 r = -errno;
157                                         }
158
159                                         continue;
160                                 }
161
162                                 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
163                                 closedir(sub_dir);
164
165                                 if (q < 0)
166                                         r = q;
167                         }
168
169                         /* Ignore ctime, we change it when deleting */
170                         age = MAX(timespec_load(&s.st_mtim),
171                                   timespec_load(&s.st_atim));
172                         if (age >= cutoff)
173                                 continue;
174
175                         log_debug("rmdir '%s'\n", sub_path);
176
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);
180                                         r = -errno;
181                                 }
182                         }
183
184                 } else {
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)
190                                 continue;
191
192                         if (mountpoint) {
193                                 if (streq(dent->d_name, ".journal") &&
194                                     s.st_uid == 0)
195                                         continue;
196
197                                 if (streq(dent->d_name, "aquota.user") ||
198                                     streq(dent->d_name, "aquota.group"))
199                                         continue;
200                         }
201
202                         age = MAX3(timespec_load(&s.st_mtim),
203                                    timespec_load(&s.st_atim),
204                                    timespec_load(&s.st_ctim));
205
206                         if (age >= cutoff)
207                                 continue;
208
209                         log_debug("unlink '%s'\n", sub_path);
210
211                         if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
212                                 if (errno != ENOENT) {
213                                         log_error("unlink(%s): %m", sub_path);
214                                         r = -errno;
215                                 }
216                         }
217
218                         deleted = true;
219                 }
220         }
221
222 finish:
223         if (deleted) {
224                 /* Restore original directory timestamps */
225                 times[0] = ds->st_atim;
226                 times[1] = ds->st_mtim;
227
228                 if (futimens(dirfd(d), times) < 0)
229                         log_error("utimensat(%s): %m", p);
230         }
231
232         free(sub_path);
233
234         return r;
235 }
236
237 static int clean_item(Item *i) {
238         DIR *d;
239         struct stat s, ps;
240         bool mountpoint;
241         int r;
242         usec_t cutoff, n;
243
244         assert(i);
245
246         if (i->type != CREATE_DIRECTORY &&
247             i->type != TRUNCATE_DIRECTORY &&
248             i->type != IGNORE_PATH)
249                 return 0;
250
251         if (!i->age_set || i->age <= 0)
252                 return 0;
253
254         n = now(CLOCK_REALTIME);
255         if (n < i->age)
256                 return 0;
257
258         cutoff = n - i->age;
259
260         d = opendir(i->path);
261         if (!d) {
262                 if (errno == ENOENT)
263                         return 0;
264
265                 log_error("Failed to open directory %s: %m", i->path);
266                 return -errno;
267         }
268
269         if (fstat(dirfd(d), &s) < 0) {
270                 log_error("stat(%s) failed: %m", i->path);
271                 r = -errno;
272                 goto finish;
273         }
274
275         if (!S_ISDIR(s.st_mode)) {
276                 log_error("%s is not a directory.", i->path);
277                 r = -ENOTDIR;
278                 goto finish;
279         }
280
281         if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
282                 log_error("stat(%s/..) failed: %m", i->path);
283                 r = -errno;
284                 goto finish;
285         }
286
287         mountpoint = s.st_dev != ps.st_dev ||
288                      (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
289
290         r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
291
292 finish:
293         if (d)
294                 closedir(d);
295
296         return r;
297 }
298
299 static int create_item(Item *i) {
300         int fd = -1, r;
301         mode_t u;
302         struct stat st;
303
304         assert(i);
305
306         switch (i->type) {
307
308         case IGNORE_PATH:
309         case REMOVE_PATH:
310         case RECURSIVE_REMOVE_PATH:
311                 return 0;
312
313         case CREATE_FILE:
314         case TRUNCATE_FILE:
315
316                 u = umask(0);
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);
319                 umask(u);
320
321                 if (fd < 0) {
322                         log_error("Failed to create file %s: %m", i->path);
323                         r = -errno;
324                         goto finish;
325                 }
326
327                 if (fstat(fd, &st) < 0) {
328                         log_error("stat(%s) failed: %m", i->path);
329                         r = -errno;
330                         goto finish;
331                 }
332
333                 if (!S_ISREG(st.st_mode)) {
334                         log_error("%s is not a file.", i->path);
335                         r = -EEXIST;
336                         goto finish;
337                 }
338
339                 if (i->mode_set)
340                         if (fchmod(fd, i->mode) < 0) {
341                                 log_error("chmod(%s) failed: %m", i->path);
342                                 r = -errno;
343                                 goto finish;
344                         }
345
346                 if (i->uid_set || i->gid_set)
347                         if (fchown(fd,
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);
351                                 r = -errno;
352                                 goto finish;
353                         }
354
355                 break;
356
357         case TRUNCATE_DIRECTORY:
358         case CREATE_DIRECTORY:
359
360                 u = umask(0);
361                 r = mkdir(i->path, i->mode);
362                 umask(u);
363
364                 if (r < 0 && errno != EEXIST) {
365                         log_error("Failed to create directory %s: %m", i->path);
366                         r = -errno;
367                         goto finish;
368                 }
369
370                 if (stat(i->path, &st) < 0) {
371                         log_error("stat(%s) failed: %m", i->path);
372                         r = -errno;
373                         goto finish;
374                 }
375
376                 if (!S_ISDIR(st.st_mode)) {
377                         log_error("%s is not a directory.", i->path);
378                         r = -EEXIST;
379                         goto finish;
380                 }
381
382                 if (i->mode_set)
383                         if (chmod(i->path, i->mode) < 0) {
384                                 log_error("chmod(%s) failed: %m", i->path);
385                                 r = -errno;
386                                 goto finish;
387                         }
388
389                 if (i->uid_set || i->gid_set)
390                         if (chown(i->path,
391                                   i->uid_set ? i->uid : (uid_t) -1,
392                                   i->gid_set ? i->gid : (gid_t) -1) < 0) {
393
394                                 log_error("chown(%s) failed: %m", i->path);
395                                 r = -errno;
396                                 goto finish;
397                         }
398
399                 break;
400         }
401
402         if ((r = label_fix(i->path)) < 0)
403                 goto finish;
404
405         log_debug("%s created successfully.", i->path);
406
407 finish:
408         if (fd >= 0)
409                 close_nointr_nofail(fd);
410
411         return r;
412 }
413
414 static int remove_item(Item *i) {
415         int r;
416
417         assert(i);
418
419         switch (i->type) {
420
421         case CREATE_FILE:
422         case TRUNCATE_FILE:
423         case CREATE_DIRECTORY:
424         case IGNORE_PATH:
425                 break;
426
427         case REMOVE_PATH:
428                 if (remove(i->path) < 0 && errno != ENOENT) {
429                         log_error("remove(%s): %m", i->path);
430                         return -errno;
431                 }
432
433                 break;
434
435         case TRUNCATE_DIRECTORY:
436         case RECURSIVE_REMOVE_PATH:
437                 if ((r = rm_rf(i->path, false, i->type == RECURSIVE_REMOVE_PATH)) < 0 &&
438                     r != -ENOENT) {
439                         log_error("rm_rf(%s): %s", i->path, strerror(-r));
440                         return r;
441                 }
442
443                 break;
444         }
445
446         return 0;
447 }
448
449 static int process_item(Item *i) {
450         int r, q, p;
451
452         assert(i);
453
454         r = arg_create ? create_item(i) : 0;
455         q = arg_remove ? remove_item(i) : 0;
456         p = arg_clean ? clean_item(i) : 0;
457
458         if (r < 0)
459                 return r;
460
461         if (q < 0)
462                 return q;
463
464         return p;
465 }
466
467 static void item_free(Item *i) {
468         assert(i);
469
470         free(i->path);
471         free(i);
472 }
473
474 static int parse_line(const char *fname, unsigned line, const char *buffer, const char *prefix) {
475         Item *i;
476         char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
477         int r, n;
478
479         assert(fname);
480         assert(line >= 1);
481         assert(buffer);
482
483         if (!(i = new0(Item, 1))) {
484                 log_error("Out of memory");
485                 return -ENOMEM;
486         }
487
488         if ((n = sscanf(buffer,
489                         "%c "
490                         "%ms "
491                         "%ms "
492                         "%ms "
493                         "%ms "
494                         "%ms",
495                         &i->type,
496                         &i->path,
497                         &mode,
498                         &user,
499                         &group,
500                         &age)) < 2) {
501                 log_error("[%s:%u] Syntax error.", fname, line);
502                 r = -EIO;
503                 goto finish;
504         }
505
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);
514                 r = -EBADMSG;
515                 goto finish;
516         }
517
518         if (!path_is_absolute(i->path)) {
519                 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
520                 r = -EBADMSG;
521                 goto finish;
522         }
523
524         path_kill_slashes(i->path);
525
526         if (prefix && !path_startswith(i->path, prefix)) {
527                 r = 0;
528                 goto finish;
529         }
530
531         if (user && !streq(user, "-")) {
532                 unsigned long lu;
533                 struct passwd *p;
534
535                 if (streq(user, "root") || streq(user, "0"))
536                         i->uid = 0;
537                 else if (safe_atolu(user, &lu) >= 0)
538                         i->uid = (uid_t) lu;
539                 else if ((p = getpwnam(user)))
540                         i->uid = p->pw_uid;
541                 else {
542                         log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
543                         r = -ENOENT;
544                         goto finish;
545                 }
546
547                 i->uid_set = true;
548         }
549
550         if (group && !streq(group, "-")) {
551                 unsigned long lu;
552                 struct group *g;
553
554                 if (streq(group, "root") || streq(group, "0"))
555                         i->gid = 0;
556                 else if (safe_atolu(group, &lu) >= 0)
557                         i->gid = (gid_t) lu;
558                 else if ((g = getgrnam(group)))
559                         i->gid = g->gr_gid;
560                 else {
561                         log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
562                         r = -ENOENT;
563                         goto finish;
564                 }
565
566                 i->gid_set = true;
567         }
568
569         if (mode && !streq(mode, "-")) {
570                 unsigned m;
571
572                 if (sscanf(mode, "%o", &m) != 1) {
573                         log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
574                         r = -ENOENT;
575                         goto finish;
576                 }
577
578                 i->mode = m;
579                 i->mode_set = true;
580         } else
581                 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
582
583         if (age && !streq(age, "-")) {
584                 if (parse_usec(age, &i->age) < 0) {
585                         log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
586                         r = -EBADMSG;
587                         goto finish;
588                 }
589
590                 i->age_set = true;
591         }
592
593         if ((r = hashmap_put(items, i->path, i)) < 0) {
594                 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
595                 goto finish;
596         }
597
598         i = NULL;
599         r = 0;
600
601 finish:
602         free(user);
603         free(group);
604         free(mode);
605         free(age);
606
607         if (i)
608                 item_free(i);
609
610         return r;
611 }
612
613 static int scandir_filter(const struct dirent *d) {
614         assert(d);
615
616         if (ignore_file(d->d_name))
617                 return 0;
618
619         if (d->d_type != DT_REG &&
620             d->d_type != DT_LNK)
621                 return 0;
622
623         return endswith(d->d_name, ".conf");
624 }
625
626 static int help(void) {
627
628         printf("%s [OPTIONS...]\n\n"
629                "Create and clean up temporary directories.\n\n"
630                "  -h --help             Show this help\n"
631                "     --create           Create marked files/directories\n"
632                "     --clean            Clean up marked directories\n"
633                "     --remove           Remove marked files/directories\n",
634                program_invocation_short_name);
635
636         return 0;
637 }
638
639 static int parse_argv(int argc, char *argv[]) {
640
641         enum {
642                 ARG_CREATE,
643                 ARG_CLEAN,
644                 ARG_REMOVE
645         };
646
647         static const struct option options[] = {
648                 { "help",      no_argument,       NULL, 'h'           },
649                 { "create",    no_argument,       NULL, ARG_CREATE    },
650                 { "clean",     no_argument,       NULL, ARG_CLEAN     },
651                 { "remove",    no_argument,       NULL, ARG_REMOVE    },
652                 { NULL,        0,                 NULL, 0             }
653         };
654
655         int c;
656
657         assert(argc >= 0);
658         assert(argv);
659
660         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
661
662                 switch (c) {
663
664                 case 'h':
665                         help();
666                         return 0;
667
668                 case ARG_CREATE:
669                         arg_create = true;
670                         break;
671
672                 case ARG_CLEAN:
673                         arg_clean = true;
674                         break;
675
676                 case ARG_REMOVE:
677                         arg_remove = true;
678                         break;
679
680                 case '?':
681                         return -EINVAL;
682
683                 default:
684                         log_error("Unknown option code %c", c);
685                         return -EINVAL;
686                 }
687         }
688
689         if (!arg_clean && !arg_create && !arg_remove) {
690                 help();
691                 return -EINVAL;
692         }
693
694         return 1;
695 }
696
697 int main(int argc, char *argv[]) {
698         struct dirent **de = NULL;
699         int r, n, j;
700         const char *prefix = NULL;
701         Item *i;
702         Iterator iterator;
703
704         if ((r = parse_argv(argc, argv)) <= 0)
705                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
706
707         if (optind < argc)
708                 prefix = argv[optind];
709         else
710                 prefix = "/";
711
712         log_set_target(LOG_TARGET_SYSLOG_OR_KMSG);
713         log_parse_environment();
714         log_open();
715
716         label_init();
717
718         if (!(items = hashmap_new(string_hash_func, string_compare_func))) {
719                 log_error("Out of memory");
720                 r = EXIT_FAILURE;
721                 goto finish;
722         }
723
724         if ((n = scandir("/etc/tmpfiles.d/", &de, scandir_filter, alphasort)) < 0) {
725
726                 if (errno == ENOENT)
727                         r = EXIT_SUCCESS;
728                 else {
729                         log_error("Failed to enumerate /etc/tmpfiles.d/ files: %m");
730                         r = EXIT_FAILURE;
731                 }
732
733                 goto finish;
734         }
735
736         r = EXIT_SUCCESS;
737
738         for (j = 0; j < n; j++) {
739                 int k;
740                 char *fn;
741                 FILE *f;
742                 unsigned v;
743
744                 k = asprintf(&fn, "/etc/tmpfiles.d/%s", de[j]->d_name);
745                 free(de[j]);
746
747                 if (k < 0) {
748                         log_error("Failed to allocate file name.");
749                         r = EXIT_FAILURE;
750                         continue;
751                 }
752
753                 if (!(f = fopen(fn, "re"))) {
754
755                         if (errno != ENOENT) {
756                                 log_error("Failed to open %s: %m", fn);
757                                 r = EXIT_FAILURE;
758                         }
759
760                         free(fn);
761                         continue;
762                 }
763
764                 v = 0;
765                 for (;;) {
766                         char line[LINE_MAX], *l;
767
768                         if (!(fgets(line, sizeof(line), f)))
769                                 break;
770
771                         v++;
772
773                         l = strstrip(line);
774                         if (*l == '#' || *l == 0)
775                                 continue;
776
777                         if (parse_line(fn, v, l, prefix) < 0)
778                                 r = EXIT_FAILURE;
779                 }
780
781                 if (ferror(f)) {
782                         r = EXIT_FAILURE;
783                         log_error("Failed to read from file %s: %m", fn);
784                 }
785
786                 free(fn);
787
788                 fclose(f);
789         }
790
791         free(de);
792
793         HASHMAP_FOREACH(i, items, iterator)
794                 if (process_item(i) < 0)
795                         r = EXIT_FAILURE;
796
797 finish:
798         while ((i = hashmap_steal_first(items)))
799                 item_free(i);
800
801         hashmap_free(items);
802
803         label_finish();
804
805         return r;
806 }