chiark / gitweb /
tmpfiles: add RECURSIVE_RELABEL_PATH ('Z')
[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 #include <glob.h>
40 #include <fnmatch.h>
41
42 #include "log.h"
43 #include "util.h"
44 #include "strv.h"
45 #include "label.h"
46 #include "set.h"
47
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. */
52
53 typedef enum ItemType {
54         /* These ones take file names */
55         CREATE_FILE = 'f',
56         TRUNCATE_FILE = 'F',
57         CREATE_DIRECTORY = 'd',
58         TRUNCATE_DIRECTORY = 'D',
59         CREATE_FIFO = 'p',
60
61         /* These ones take globs */
62         IGNORE_PATH = 'x',
63         REMOVE_PATH = 'r',
64         RECURSIVE_REMOVE_PATH = 'R',
65         RECURSIVE_RELABEL_PATH = 'Z'
66 } ItemType;
67
68 typedef struct Item {
69         ItemType type;
70
71         char *path;
72         uid_t uid;
73         gid_t gid;
74         mode_t mode;
75         usec_t age;
76
77         bool uid_set:1;
78         bool gid_set:1;
79         bool mode_set:1;
80         bool age_set:1;
81 } Item;
82
83 static Hashmap *items = NULL, *globs = NULL;
84 static Set *unix_sockets = NULL;
85
86 static bool arg_create = false;
87 static bool arg_clean = false;
88 static bool arg_remove = false;
89
90 static const char *arg_prefix = NULL;
91
92 #define MAX_DEPTH 256
93
94 static bool needs_glob(ItemType t) {
95         return t == IGNORE_PATH || t == REMOVE_PATH || t == RECURSIVE_REMOVE_PATH || t == RECURSIVE_RELABEL_PATH;
96 }
97
98 static struct Item* find_glob(Hashmap *h, const char *match) {
99         Item *j;
100         Iterator i;
101
102         HASHMAP_FOREACH(j, h, i)
103                 if (fnmatch(j->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
104                         return j;
105
106         return NULL;
107 }
108
109 static void load_unix_sockets(void) {
110         FILE *f = NULL;
111         char line[LINE_MAX];
112
113         if (unix_sockets)
114                 return;
115
116         /* We maintain a cache of the sockets we found in
117          * /proc/net/unix to speed things up a little. */
118
119         if (!(unix_sockets = set_new(string_hash_func, string_compare_func)))
120                 return;
121
122         if (!(f = fopen("/proc/net/unix", "re")))
123                 return;
124
125         if (!(fgets(line, sizeof(line), f)))
126                 goto fail;
127
128         for (;;) {
129                 char *p, *s;
130                 int k;
131
132                 if (!(fgets(line, sizeof(line), f)))
133                         break;
134
135                 truncate_nl(line);
136
137                 if (strlen(line) < 53)
138                         continue;
139
140                 p = line + 53;
141                 p += strspn(p, WHITESPACE);
142                 p += strcspn(p, WHITESPACE);
143                 p += strspn(p, WHITESPACE);
144
145                 if (*p != '/')
146                         continue;
147
148                 if (!(s = strdup(p)))
149                         goto fail;
150
151                 path_kill_slashes(s);
152
153                 if ((k = set_put(unix_sockets, s)) < 0) {
154                         free(s);
155
156                         if (k != -EEXIST)
157                                 goto fail;
158                 }
159         }
160
161         fclose(f);
162         return;
163
164 fail:
165         set_free_free(unix_sockets);
166         unix_sockets = NULL;
167
168         if (f)
169                 fclose(f);
170 }
171
172 static bool unix_socket_alive(const char *fn) {
173         assert(fn);
174
175         load_unix_sockets();
176
177         if (unix_sockets)
178                 return !!set_get(unix_sockets, (char*) fn);
179
180         /* We don't know, so assume yes */
181         return true;
182 }
183
184 static int dir_cleanup(
185                 const char *p,
186                 DIR *d,
187                 const struct stat *ds,
188                 usec_t cutoff,
189                 dev_t rootdev,
190                 bool mountpoint,
191                 int maxdepth)
192 {
193         struct dirent *dent;
194         struct timespec times[2];
195         bool deleted = false;
196         char *sub_path = NULL;
197         int r = 0;
198
199         while ((dent = readdir(d))) {
200                 struct stat s;
201                 usec_t age;
202
203                 if (streq(dent->d_name, ".") ||
204                     streq(dent->d_name, ".."))
205                         continue;
206
207                 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
208
209                         if (errno != ENOENT) {
210                                 log_error("stat(%s/%s) failed: %m", p, dent->d_name);
211                                 r = -errno;
212                         }
213
214                         continue;
215                 }
216
217                 /* Stay on the same filesystem */
218                 if (s.st_dev != rootdev)
219                         continue;
220
221                 /* Do not delete read-only files owned by root */
222                 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR))
223                         continue;
224
225                 free(sub_path);
226                 sub_path = NULL;
227
228                 if (asprintf(&sub_path, "%s/%s", p, dent->d_name) < 0) {
229                         log_error("Out of memory");
230                         r = -ENOMEM;
231                         goto finish;
232                 }
233
234                 /* Is there an item configured for this path? */
235                 if (hashmap_get(items, sub_path))
236                         continue;
237
238                 if (find_glob(globs, sub_path))
239                         continue;
240
241                 if (S_ISDIR(s.st_mode)) {
242
243                         if (mountpoint &&
244                             streq(dent->d_name, "lost+found") &&
245                             s.st_uid == 0)
246                                 continue;
247
248                         if (maxdepth <= 0)
249                                 log_warning("Reached max depth on %s.", sub_path);
250                         else {
251                                 DIR *sub_dir;
252                                 int q;
253
254                                 sub_dir = xopendirat(dirfd(d), dent->d_name, O_NOFOLLOW);
255                                 if (sub_dir == NULL) {
256                                         if (errno != ENOENT) {
257                                                 log_error("opendir(%s/%s) failed: %m", p, dent->d_name);
258                                                 r = -errno;
259                                         }
260
261                                         continue;
262                                 }
263
264                                 q = dir_cleanup(sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1);
265                                 closedir(sub_dir);
266
267                                 if (q < 0)
268                                         r = q;
269                         }
270
271                         /* Ignore ctime, we change it when deleting */
272                         age = MAX(timespec_load(&s.st_mtim),
273                                   timespec_load(&s.st_atim));
274                         if (age >= cutoff)
275                                 continue;
276
277                         log_debug("rmdir '%s'\n", sub_path);
278
279                         if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0) {
280                                 if (errno != ENOENT && errno != ENOTEMPTY) {
281                                         log_error("rmdir(%s): %m", sub_path);
282                                         r = -errno;
283                                 }
284                         }
285
286                 } else {
287                         /* Skip files for which the sticky bit is
288                          * set. These are semantics we define, and are
289                          * unknown elsewhere. See XDG_RUNTIME_DIR
290                          * specification for details. */
291                         if (s.st_mode & S_ISVTX)
292                                 continue;
293
294                         if (mountpoint && S_ISREG(s.st_mode)) {
295                                 if (streq(dent->d_name, ".journal") &&
296                                     s.st_uid == 0)
297                                         continue;
298
299                                 if (streq(dent->d_name, "aquota.user") ||
300                                     streq(dent->d_name, "aquota.group"))
301                                         continue;
302                         }
303
304                         /* Ignore sockets that are listed in /proc/net/unix */
305                         if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path))
306                                 continue;
307
308                         /* Ignore device nodes */
309                         if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode))
310                                 continue;
311
312                         age = MAX3(timespec_load(&s.st_mtim),
313                                    timespec_load(&s.st_atim),
314                                    timespec_load(&s.st_ctim));
315
316                         if (age >= cutoff)
317                                 continue;
318
319                         log_debug("unlink '%s'\n", sub_path);
320
321                         if (unlinkat(dirfd(d), dent->d_name, 0) < 0) {
322                                 if (errno != ENOENT) {
323                                         log_error("unlink(%s): %m", sub_path);
324                                         r = -errno;
325                                 }
326                         }
327
328                         deleted = true;
329                 }
330         }
331
332 finish:
333         if (deleted) {
334                 /* Restore original directory timestamps */
335                 times[0] = ds->st_atim;
336                 times[1] = ds->st_mtim;
337
338                 if (futimens(dirfd(d), times) < 0)
339                         log_error("utimensat(%s): %m", p);
340         }
341
342         free(sub_path);
343
344         return r;
345 }
346
347 static int clean_item(Item *i) {
348         DIR *d;
349         struct stat s, ps;
350         bool mountpoint;
351         int r;
352         usec_t cutoff, n;
353
354         assert(i);
355
356         if (i->type != CREATE_DIRECTORY &&
357             i->type != TRUNCATE_DIRECTORY &&
358             i->type != IGNORE_PATH)
359                 return 0;
360
361         if (!i->age_set || i->age <= 0)
362                 return 0;
363
364         n = now(CLOCK_REALTIME);
365         if (n < i->age)
366                 return 0;
367
368         cutoff = n - i->age;
369
370         d = opendir(i->path);
371         if (!d) {
372                 if (errno == ENOENT)
373                         return 0;
374
375                 log_error("Failed to open directory %s: %m", i->path);
376                 return -errno;
377         }
378
379         if (fstat(dirfd(d), &s) < 0) {
380                 log_error("stat(%s) failed: %m", i->path);
381                 r = -errno;
382                 goto finish;
383         }
384
385         if (!S_ISDIR(s.st_mode)) {
386                 log_error("%s is not a directory.", i->path);
387                 r = -ENOTDIR;
388                 goto finish;
389         }
390
391         if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0) {
392                 log_error("stat(%s/..) failed: %m", i->path);
393                 r = -errno;
394                 goto finish;
395         }
396
397         mountpoint = s.st_dev != ps.st_dev ||
398                      (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
399
400         r = dir_cleanup(i->path, d, &s, cutoff, s.st_dev, mountpoint, MAX_DEPTH);
401
402 finish:
403         if (d)
404                 closedir(d);
405
406         return r;
407 }
408
409 static int recursive_relabel_children(const char *path) {
410         DIR *d;
411         int ret = 0;
412
413         /* This returns the first error we run into, but nevertheless
414          * tries to go on */
415
416         d = opendir(path);
417         if (!d)
418                 return errno == ENOENT ? 0 : -errno;
419
420         for (;;) {
421                 struct dirent buf, *de;
422                 bool is_dir;
423                 int r;
424                 char *entry_path;
425
426                 r = readdir_r(d, &buf, &de);
427                 if (r != 0) {
428                         if (ret == 0)
429                                 ret = -r;
430                         break;
431                 }
432
433                 if (!de)
434                         break;
435
436                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
437                         continue;
438
439                 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
440                         if (ret == 0)
441                                 ret = -ENOMEM;
442                         continue;
443                 }
444
445                 if (de->d_type == DT_UNKNOWN) {
446                         struct stat st;
447
448                         if (lstat(entry_path, &st) < 0) {
449                                 if (ret == 0 && errno != ENOENT)
450                                         ret = -errno;
451                                 free(entry_path);
452                                 continue;
453                         }
454
455                         is_dir = S_ISDIR(st.st_mode);
456
457                 } else
458                         is_dir = de->d_type == DT_DIR;
459
460                 r = label_fix(entry_path, false);
461                 if (r < 0) {
462                         if (ret == 0 && r != -ENOENT)
463                                 ret = r;
464                         free(entry_path);
465                         continue;
466                 }
467
468                 if (is_dir) {
469                         r = recursive_relabel_children(entry_path);
470                         if (r < 0 && ret == 0)
471                                 ret = r;
472                 }
473
474                 free(entry_path);
475         }
476
477         closedir(d);
478
479         return ret;
480 }
481
482 static int recursive_relabel(Item *i, const char *path) {
483         int r;
484         struct stat st;
485
486         r = label_fix(path, false);
487         if (r < 0)
488                 return r;
489
490         if (lstat(path, &st) < 0)
491                 return -errno;
492
493         if (S_ISDIR(st.st_mode))
494                 r = recursive_relabel_children(path);
495
496         return r;
497 }
498
499 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
500         int r = 0, k;
501         glob_t g;
502         char **fn;
503
504         zero(g);
505
506         errno = 0;
507         if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
508
509                 if (k != GLOB_NOMATCH) {
510                         if (errno != 0)
511                                 errno = EIO;
512
513                         log_error("glob(%s) failed: %m", i->path);
514                         return -errno;
515                 }
516         }
517
518         STRV_FOREACH(fn, g.gl_pathv)
519                 if ((k = action(i, *fn)) < 0)
520                         r = k;
521
522         globfree(&g);
523         return r;
524 }
525
526 static int item_set_perms(Item *i) {
527         if (i->mode_set)
528                 if (chmod(i->path, i->mode) < 0) {
529                         log_error("chmod(%s) failed: %m", i->path);
530                         return -errno;
531                 }
532
533         if (i->uid_set || i->gid_set)
534                 if (chown(i->path,
535                           i->uid_set ? i->uid : (uid_t) -1,
536                           i->gid_set ? i->gid : (gid_t) -1) < 0) {
537
538                         log_error("chown(%s) failed: %m", i->path);
539                         return -errno;
540                 }
541
542         return label_fix(i->path, false);
543 }
544
545 static int create_item(Item *i) {
546         int r;
547         mode_t u;
548         struct stat st;
549
550         assert(i);
551
552         switch (i->type) {
553
554         case IGNORE_PATH:
555         case REMOVE_PATH:
556         case RECURSIVE_REMOVE_PATH:
557                 return 0;
558
559         case CREATE_FILE:
560         case TRUNCATE_FILE: {
561                 int fd;
562
563                 u = umask(0);
564                 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
565                           (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
566                 umask(u);
567
568                 if (fd < 0) {
569                         log_error("Failed to create file %s: %m", i->path);
570                         return -errno;
571                 }
572
573                 close_nointr_nofail(fd);
574
575                 if (stat(i->path, &st) < 0) {
576                         log_error("stat(%s) failed: %m", i->path);
577                         return -errno;
578                 }
579
580                 if (!S_ISREG(st.st_mode)) {
581                         log_error("%s is not a file.", i->path);
582                         return -EEXIST;
583                 }
584
585                 r = item_set_perms(i);
586                 if (r < 0)
587                         return r;
588
589                 break;
590         }
591
592         case TRUNCATE_DIRECTORY:
593         case CREATE_DIRECTORY:
594
595                 u = umask(0);
596                 mkdir_parents(i->path, 0755);
597                 r = mkdir(i->path, i->mode);
598                 umask(u);
599
600                 if (r < 0 && errno != EEXIST) {
601                         log_error("Failed to create directory %s: %m", i->path);
602                         return -errno;
603                 }
604
605                 if (stat(i->path, &st) < 0) {
606                         log_error("stat(%s) failed: %m", i->path);
607                         return -errno;
608                 }
609
610                 if (!S_ISDIR(st.st_mode)) {
611                         log_error("%s is not a directory.", i->path);
612                         return -EEXIST;
613                 }
614
615                 r = item_set_perms(i);
616                 if (r < 0)
617                         return r;
618
619                 break;
620
621         case CREATE_FIFO:
622
623                 u = umask(0);
624                 r = mkfifo(i->path, i->mode);
625                 umask(u);
626
627                 if (r < 0 && errno != EEXIST) {
628                         log_error("Failed to create fifo %s: %m", i->path);
629                         return -errno;
630                 }
631
632                 if (stat(i->path, &st) < 0) {
633                         log_error("stat(%s) failed: %m", i->path);
634                         return -errno;
635                 }
636
637                 if (!S_ISFIFO(st.st_mode)) {
638                         log_error("%s is not a fifo.", i->path);
639                         return -EEXIST;
640                 }
641
642                 r = item_set_perms(i);
643                 if (r < 0)
644                         return r;
645
646                 break;
647
648         case RECURSIVE_RELABEL_PATH:
649
650                 r = glob_item(i, recursive_relabel);
651                 if (r < 0)
652                         return r;
653         }
654
655         log_debug("%s created successfully.", i->path);
656
657         return 0;
658 }
659
660 static int remove_item_instance(Item *i, const char *instance) {
661         int r;
662
663         assert(i);
664
665         switch (i->type) {
666
667         case CREATE_FILE:
668         case TRUNCATE_FILE:
669         case CREATE_DIRECTORY:
670         case CREATE_FIFO:
671         case IGNORE_PATH:
672         case RECURSIVE_RELABEL_PATH:
673                 break;
674
675         case REMOVE_PATH:
676                 if (remove(instance) < 0 && errno != ENOENT) {
677                         log_error("remove(%s): %m", instance);
678                         return -errno;
679                 }
680
681                 break;
682
683         case TRUNCATE_DIRECTORY:
684         case RECURSIVE_REMOVE_PATH:
685                 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
686                     r != -ENOENT) {
687                         log_error("rm_rf(%s): %s", instance, strerror(-r));
688                         return r;
689                 }
690
691                 break;
692         }
693
694         return 0;
695 }
696
697 static int remove_item(Item *i) {
698         int r = 0;
699
700         assert(i);
701
702         switch (i->type) {
703
704         case CREATE_FILE:
705         case TRUNCATE_FILE:
706         case CREATE_DIRECTORY:
707         case CREATE_FIFO:
708         case IGNORE_PATH:
709         case RECURSIVE_RELABEL_PATH:
710                 break;
711
712         case REMOVE_PATH:
713         case TRUNCATE_DIRECTORY:
714         case RECURSIVE_REMOVE_PATH:
715                 r = glob_item(i, remove_item_instance);
716                 break;
717         }
718
719         return r;
720 }
721
722 static int process_item(Item *i) {
723         int r, q, p;
724
725         assert(i);
726
727         r = arg_create ? create_item(i) : 0;
728         q = arg_remove ? remove_item(i) : 0;
729         p = arg_clean ? clean_item(i) : 0;
730
731         if (r < 0)
732                 return r;
733
734         if (q < 0)
735                 return q;
736
737         return p;
738 }
739
740 static void item_free(Item *i) {
741         assert(i);
742
743         free(i->path);
744         free(i);
745 }
746
747 static bool item_equal(Item *a, Item *b) {
748         assert(a);
749         assert(b);
750
751         if (!streq_ptr(a->path, b->path))
752                 return false;
753
754         if (a->type != b->type)
755                 return false;
756
757         if (a->uid_set != b->uid_set ||
758             (a->uid_set && a->uid != b->uid))
759             return false;
760
761         if (a->gid_set != b->gid_set ||
762             (a->gid_set && a->gid != b->gid))
763             return false;
764
765         if (a->mode_set != b->mode_set ||
766             (a->mode_set && a->mode != b->mode))
767             return false;
768
769         if (a->age_set != b->age_set ||
770             (a->age_set && a->age != b->age))
771             return false;
772
773         return true;
774 }
775
776 static int parse_line(const char *fname, unsigned line, const char *buffer) {
777         Item *i, *existing;
778         char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
779         char type;
780         Hashmap *h;
781         int r;
782
783         assert(fname);
784         assert(line >= 1);
785         assert(buffer);
786
787         if (!(i = new0(Item, 1))) {
788                 log_error("Out of memory");
789                 return -ENOMEM;
790         }
791
792         if (sscanf(buffer,
793                    "%c "
794                    "%ms "
795                    "%ms "
796                    "%ms "
797                    "%ms "
798                    "%ms",
799                    &type,
800                    &i->path,
801                    &mode,
802                    &user,
803                    &group,
804                    &age) < 2) {
805                 log_error("[%s:%u] Syntax error.", fname, line);
806                 r = -EIO;
807                 goto finish;
808         }
809
810         if (type != CREATE_FILE &&
811             type != TRUNCATE_FILE &&
812             type != CREATE_DIRECTORY &&
813             type != TRUNCATE_DIRECTORY &&
814             type != CREATE_FIFO &&
815             type != IGNORE_PATH &&
816             type != REMOVE_PATH &&
817             type != RECURSIVE_REMOVE_PATH &&
818             type != RECURSIVE_RELABEL_PATH) {
819                 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
820                 r = -EBADMSG;
821                 goto finish;
822         }
823         i->type = type;
824
825         if (!path_is_absolute(i->path)) {
826                 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
827                 r = -EBADMSG;
828                 goto finish;
829         }
830
831         path_kill_slashes(i->path);
832
833         if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
834                 r = 0;
835                 goto finish;
836         }
837
838         if (user && !streq(user, "-")) {
839                 const char *u = user;
840
841                 r = get_user_creds(&u, &i->uid, NULL, NULL);
842                 if (r < 0) {
843                         log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
844                         goto finish;
845                 }
846
847                 i->uid_set = true;
848         }
849
850         if (group && !streq(group, "-")) {
851                 const char *g = group;
852
853                 r = get_group_creds(&g, &i->gid);
854                 if (r < 0) {
855                         log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
856                         goto finish;
857                 }
858
859                 i->gid_set = true;
860         }
861
862         if (mode && !streq(mode, "-")) {
863                 unsigned m;
864
865                 if (sscanf(mode, "%o", &m) != 1) {
866                         log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
867                         r = -ENOENT;
868                         goto finish;
869                 }
870
871                 i->mode = m;
872                 i->mode_set = true;
873         } else
874                 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
875
876         if (age && !streq(age, "-")) {
877                 if (parse_usec(age, &i->age) < 0) {
878                         log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
879                         r = -EBADMSG;
880                         goto finish;
881                 }
882
883                 i->age_set = true;
884         }
885
886         h = needs_glob(i->type) ? globs : items;
887
888         if ((existing = hashmap_get(h, i->path))) {
889
890                 /* Two identical items are fine */
891                 if (!item_equal(existing, i))
892                         log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
893
894                 r = 0;
895                 goto finish;
896         }
897
898         if ((r = hashmap_put(h, i->path, i)) < 0) {
899                 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
900                 goto finish;
901         }
902
903         i = NULL;
904         r = 0;
905
906 finish:
907         free(user);
908         free(group);
909         free(mode);
910         free(age);
911
912         if (i)
913                 item_free(i);
914
915         return r;
916 }
917
918 static int help(void) {
919
920         printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
921                "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
922                "  -h --help             Show this help\n"
923                "     --create           Create marked files/directories\n"
924                "     --clean            Clean up marked directories\n"
925                "     --remove           Remove marked files/directories\n"
926                "     --prefix=PATH      Only apply rules that apply to paths with the specified prefix\n",
927                program_invocation_short_name);
928
929         return 0;
930 }
931
932 static int parse_argv(int argc, char *argv[]) {
933
934         enum {
935                 ARG_CREATE,
936                 ARG_CLEAN,
937                 ARG_REMOVE,
938                 ARG_PREFIX
939         };
940
941         static const struct option options[] = {
942                 { "help",      no_argument,       NULL, 'h'           },
943                 { "create",    no_argument,       NULL, ARG_CREATE    },
944                 { "clean",     no_argument,       NULL, ARG_CLEAN     },
945                 { "remove",    no_argument,       NULL, ARG_REMOVE    },
946                 { "prefix",    required_argument, NULL, ARG_PREFIX    },
947                 { NULL,        0,                 NULL, 0             }
948         };
949
950         int c;
951
952         assert(argc >= 0);
953         assert(argv);
954
955         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
956
957                 switch (c) {
958
959                 case 'h':
960                         help();
961                         return 0;
962
963                 case ARG_CREATE:
964                         arg_create = true;
965                         break;
966
967                 case ARG_CLEAN:
968                         arg_clean = true;
969                         break;
970
971                 case ARG_REMOVE:
972                         arg_remove = true;
973                         break;
974
975                 case ARG_PREFIX:
976                         arg_prefix = optarg;
977                         break;
978
979                 case '?':
980                         return -EINVAL;
981
982                 default:
983                         log_error("Unknown option code %c", c);
984                         return -EINVAL;
985                 }
986         }
987
988         if (!arg_clean && !arg_create && !arg_remove) {
989                 log_error("You need to specify at least one of --clean, --create or --remove.");
990                 return -EINVAL;
991         }
992
993         return 1;
994 }
995
996 static int read_config_file(const char *fn, bool ignore_enoent) {
997         FILE *f;
998         unsigned v = 0;
999         int r = 0;
1000
1001         assert(fn);
1002
1003         if (!(f = fopen(fn, "re"))) {
1004
1005                 if (ignore_enoent && errno == ENOENT)
1006                         return 0;
1007
1008                 log_error("Failed to open %s: %m", fn);
1009                 return -errno;
1010         }
1011
1012         log_debug("apply: %s\n", fn);
1013         for (;;) {
1014                 char line[LINE_MAX], *l;
1015                 int k;
1016
1017                 if (!(fgets(line, sizeof(line), f)))
1018                         break;
1019
1020                 v++;
1021
1022                 l = strstrip(line);
1023                 if (*l == '#' || *l == 0)
1024                         continue;
1025
1026                 if ((k = parse_line(fn, v, l)) < 0)
1027                         if (r == 0)
1028                                 r = k;
1029         }
1030
1031         if (ferror(f)) {
1032                 log_error("Failed to read from file %s: %m", fn);
1033                 if (r == 0)
1034                         r = -EIO;
1035         }
1036
1037         fclose(f);
1038
1039         return r;
1040 }
1041
1042 int main(int argc, char *argv[]) {
1043         int r;
1044         Item *i;
1045         Iterator iterator;
1046
1047         if ((r = parse_argv(argc, argv)) <= 0)
1048                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1049
1050         log_set_target(LOG_TARGET_AUTO);
1051         log_parse_environment();
1052         log_open();
1053
1054         umask(0022);
1055
1056         label_init();
1057
1058         items = hashmap_new(string_hash_func, string_compare_func);
1059         globs = hashmap_new(string_hash_func, string_compare_func);
1060
1061         if (!items || !globs) {
1062                 log_error("Out of memory");
1063                 r = EXIT_FAILURE;
1064                 goto finish;
1065         }
1066
1067         r = EXIT_SUCCESS;
1068
1069         if (optind < argc) {
1070                 int j;
1071
1072                 for (j = optind; j < argc; j++)
1073                         if (read_config_file(argv[j], false) < 0)
1074                                 r = EXIT_FAILURE;
1075
1076         } else {
1077                 char **files, **f;
1078
1079                 r = conf_files_list(&files, ".conf",
1080                                     "/run/tmpfiles.d",
1081                                     "/etc/tmpfiles.d",
1082                                     "/usr/local/lib/tmpfiles.d",
1083                                     "/usr/lib/tmpfiles.d",
1084                                     NULL);
1085                 if (r < 0) {
1086                         r = EXIT_FAILURE;
1087                         log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1088                         goto finish;
1089                 }
1090
1091                 STRV_FOREACH(f, files) {
1092                         if (read_config_file(*f, true) < 0)
1093                                 r = EXIT_FAILURE;
1094                 }
1095
1096                 strv_free(files);
1097         }
1098
1099         HASHMAP_FOREACH(i, globs, iterator)
1100                 process_item(i);
1101
1102         HASHMAP_FOREACH(i, items, iterator)
1103                 process_item(i);
1104
1105 finish:
1106         while ((i = hashmap_steal_first(items)))
1107                 item_free(i);
1108
1109         while ((i = hashmap_steal_first(globs)))
1110                 item_free(i);
1111
1112         hashmap_free(items);
1113         hashmap_free(globs);
1114
1115         set_free_free(unix_sockets);
1116
1117         label_finish();
1118
1119         return r;
1120 }