chiark / gitweb /
tmpfiles: apply chown, chmod for 'Z' entries too
[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 item_set_perms(Item *i, const char *path) {
410         /* not using i->path directly because it may be a glob */
411         if (i->mode_set)
412                 if (chmod(path, i->mode) < 0) {
413                         log_error("chmod(%s) failed: %m", path);
414                         return -errno;
415                 }
416
417         if (i->uid_set || i->gid_set)
418                 if (chown(path,
419                           i->uid_set ? i->uid : (uid_t) -1,
420                           i->gid_set ? i->gid : (gid_t) -1) < 0) {
421
422                         log_error("chown(%s) failed: %m", path);
423                         return -errno;
424                 }
425
426         return label_fix(path, false);
427 }
428
429 static int recursive_relabel_children(Item *i, const char *path) {
430         DIR *d;
431         int ret = 0;
432
433         /* This returns the first error we run into, but nevertheless
434          * tries to go on */
435
436         d = opendir(path);
437         if (!d)
438                 return errno == ENOENT ? 0 : -errno;
439
440         for (;;) {
441                 struct dirent buf, *de;
442                 bool is_dir;
443                 int r;
444                 char *entry_path;
445
446                 r = readdir_r(d, &buf, &de);
447                 if (r != 0) {
448                         if (ret == 0)
449                                 ret = -r;
450                         break;
451                 }
452
453                 if (!de)
454                         break;
455
456                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
457                         continue;
458
459                 if (asprintf(&entry_path, "%s/%s", path, de->d_name) < 0) {
460                         if (ret == 0)
461                                 ret = -ENOMEM;
462                         continue;
463                 }
464
465                 if (de->d_type == DT_UNKNOWN) {
466                         struct stat st;
467
468                         if (lstat(entry_path, &st) < 0) {
469                                 if (ret == 0 && errno != ENOENT)
470                                         ret = -errno;
471                                 free(entry_path);
472                                 continue;
473                         }
474
475                         is_dir = S_ISDIR(st.st_mode);
476
477                 } else
478                         is_dir = de->d_type == DT_DIR;
479
480                 r = item_set_perms(i, entry_path);
481                 if (r < 0) {
482                         if (ret == 0 && r != -ENOENT)
483                                 ret = r;
484                         free(entry_path);
485                         continue;
486                 }
487
488                 if (is_dir) {
489                         r = recursive_relabel_children(i, entry_path);
490                         if (r < 0 && ret == 0)
491                                 ret = r;
492                 }
493
494                 free(entry_path);
495         }
496
497         closedir(d);
498
499         return ret;
500 }
501
502 static int recursive_relabel(Item *i, const char *path) {
503         int r;
504         struct stat st;
505
506         r = item_set_perms(i, path);
507         if (r < 0)
508                 return r;
509
510         if (lstat(path, &st) < 0)
511                 return -errno;
512
513         if (S_ISDIR(st.st_mode))
514                 r = recursive_relabel_children(i, path);
515
516         return r;
517 }
518
519 static int glob_item(Item *i, int (*action)(Item *, const char *)) {
520         int r = 0, k;
521         glob_t g;
522         char **fn;
523
524         zero(g);
525
526         errno = 0;
527         if ((k = glob(i->path, GLOB_NOSORT|GLOB_BRACE, NULL, &g)) != 0) {
528
529                 if (k != GLOB_NOMATCH) {
530                         if (errno != 0)
531                                 errno = EIO;
532
533                         log_error("glob(%s) failed: %m", i->path);
534                         return -errno;
535                 }
536         }
537
538         STRV_FOREACH(fn, g.gl_pathv)
539                 if ((k = action(i, *fn)) < 0)
540                         r = k;
541
542         globfree(&g);
543         return r;
544 }
545
546 static int create_item(Item *i) {
547         int r;
548         mode_t u;
549         struct stat st;
550
551         assert(i);
552
553         switch (i->type) {
554
555         case IGNORE_PATH:
556         case REMOVE_PATH:
557         case RECURSIVE_REMOVE_PATH:
558                 return 0;
559
560         case CREATE_FILE:
561         case TRUNCATE_FILE: {
562                 int fd;
563
564                 u = umask(0);
565                 fd = open(i->path, O_CREAT|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY|O_NOFOLLOW|
566                           (i->type == TRUNCATE_FILE ? O_TRUNC : 0), i->mode);
567                 umask(u);
568
569                 if (fd < 0) {
570                         log_error("Failed to create file %s: %m", i->path);
571                         return -errno;
572                 }
573
574                 close_nointr_nofail(fd);
575
576                 if (stat(i->path, &st) < 0) {
577                         log_error("stat(%s) failed: %m", i->path);
578                         return -errno;
579                 }
580
581                 if (!S_ISREG(st.st_mode)) {
582                         log_error("%s is not a file.", i->path);
583                         return -EEXIST;
584                 }
585
586                 r = item_set_perms(i, i->path);
587                 if (r < 0)
588                         return r;
589
590                 break;
591         }
592
593         case TRUNCATE_DIRECTORY:
594         case CREATE_DIRECTORY:
595
596                 u = umask(0);
597                 mkdir_parents(i->path, 0755);
598                 r = mkdir(i->path, i->mode);
599                 umask(u);
600
601                 if (r < 0 && errno != EEXIST) {
602                         log_error("Failed to create directory %s: %m", i->path);
603                         return -errno;
604                 }
605
606                 if (stat(i->path, &st) < 0) {
607                         log_error("stat(%s) failed: %m", i->path);
608                         return -errno;
609                 }
610
611                 if (!S_ISDIR(st.st_mode)) {
612                         log_error("%s is not a directory.", i->path);
613                         return -EEXIST;
614                 }
615
616                 r = item_set_perms(i, i->path);
617                 if (r < 0)
618                         return r;
619
620                 break;
621
622         case CREATE_FIFO:
623
624                 u = umask(0);
625                 r = mkfifo(i->path, i->mode);
626                 umask(u);
627
628                 if (r < 0 && errno != EEXIST) {
629                         log_error("Failed to create fifo %s: %m", i->path);
630                         return -errno;
631                 }
632
633                 if (stat(i->path, &st) < 0) {
634                         log_error("stat(%s) failed: %m", i->path);
635                         return -errno;
636                 }
637
638                 if (!S_ISFIFO(st.st_mode)) {
639                         log_error("%s is not a fifo.", i->path);
640                         return -EEXIST;
641                 }
642
643                 r = item_set_perms(i, i->path);
644                 if (r < 0)
645                         return r;
646
647                 break;
648
649         case RECURSIVE_RELABEL_PATH:
650
651                 r = glob_item(i, recursive_relabel);
652                 if (r < 0)
653                         return r;
654         }
655
656         log_debug("%s created successfully.", i->path);
657
658         return 0;
659 }
660
661 static int remove_item_instance(Item *i, const char *instance) {
662         int r;
663
664         assert(i);
665
666         switch (i->type) {
667
668         case CREATE_FILE:
669         case TRUNCATE_FILE:
670         case CREATE_DIRECTORY:
671         case CREATE_FIFO:
672         case IGNORE_PATH:
673         case RECURSIVE_RELABEL_PATH:
674                 break;
675
676         case REMOVE_PATH:
677                 if (remove(instance) < 0 && errno != ENOENT) {
678                         log_error("remove(%s): %m", instance);
679                         return -errno;
680                 }
681
682                 break;
683
684         case TRUNCATE_DIRECTORY:
685         case RECURSIVE_REMOVE_PATH:
686                 if ((r = rm_rf(instance, false, i->type == RECURSIVE_REMOVE_PATH, false)) < 0 &&
687                     r != -ENOENT) {
688                         log_error("rm_rf(%s): %s", instance, strerror(-r));
689                         return r;
690                 }
691
692                 break;
693         }
694
695         return 0;
696 }
697
698 static int remove_item(Item *i) {
699         int r = 0;
700
701         assert(i);
702
703         switch (i->type) {
704
705         case CREATE_FILE:
706         case TRUNCATE_FILE:
707         case CREATE_DIRECTORY:
708         case CREATE_FIFO:
709         case IGNORE_PATH:
710         case RECURSIVE_RELABEL_PATH:
711                 break;
712
713         case REMOVE_PATH:
714         case TRUNCATE_DIRECTORY:
715         case RECURSIVE_REMOVE_PATH:
716                 r = glob_item(i, remove_item_instance);
717                 break;
718         }
719
720         return r;
721 }
722
723 static int process_item(Item *i) {
724         int r, q, p;
725
726         assert(i);
727
728         r = arg_create ? create_item(i) : 0;
729         q = arg_remove ? remove_item(i) : 0;
730         p = arg_clean ? clean_item(i) : 0;
731
732         if (r < 0)
733                 return r;
734
735         if (q < 0)
736                 return q;
737
738         return p;
739 }
740
741 static void item_free(Item *i) {
742         assert(i);
743
744         free(i->path);
745         free(i);
746 }
747
748 static bool item_equal(Item *a, Item *b) {
749         assert(a);
750         assert(b);
751
752         if (!streq_ptr(a->path, b->path))
753                 return false;
754
755         if (a->type != b->type)
756                 return false;
757
758         if (a->uid_set != b->uid_set ||
759             (a->uid_set && a->uid != b->uid))
760             return false;
761
762         if (a->gid_set != b->gid_set ||
763             (a->gid_set && a->gid != b->gid))
764             return false;
765
766         if (a->mode_set != b->mode_set ||
767             (a->mode_set && a->mode != b->mode))
768             return false;
769
770         if (a->age_set != b->age_set ||
771             (a->age_set && a->age != b->age))
772             return false;
773
774         return true;
775 }
776
777 static int parse_line(const char *fname, unsigned line, const char *buffer) {
778         Item *i, *existing;
779         char *mode = NULL, *user = NULL, *group = NULL, *age = NULL;
780         char type;
781         Hashmap *h;
782         int r;
783
784         assert(fname);
785         assert(line >= 1);
786         assert(buffer);
787
788         if (!(i = new0(Item, 1))) {
789                 log_error("Out of memory");
790                 return -ENOMEM;
791         }
792
793         if (sscanf(buffer,
794                    "%c "
795                    "%ms "
796                    "%ms "
797                    "%ms "
798                    "%ms "
799                    "%ms",
800                    &type,
801                    &i->path,
802                    &mode,
803                    &user,
804                    &group,
805                    &age) < 2) {
806                 log_error("[%s:%u] Syntax error.", fname, line);
807                 r = -EIO;
808                 goto finish;
809         }
810
811         if (type != CREATE_FILE &&
812             type != TRUNCATE_FILE &&
813             type != CREATE_DIRECTORY &&
814             type != TRUNCATE_DIRECTORY &&
815             type != CREATE_FIFO &&
816             type != IGNORE_PATH &&
817             type != REMOVE_PATH &&
818             type != RECURSIVE_REMOVE_PATH &&
819             type != RECURSIVE_RELABEL_PATH) {
820                 log_error("[%s:%u] Unknown file type '%c'.", fname, line, type);
821                 r = -EBADMSG;
822                 goto finish;
823         }
824         i->type = type;
825
826         if (!path_is_absolute(i->path)) {
827                 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i->path);
828                 r = -EBADMSG;
829                 goto finish;
830         }
831
832         path_kill_slashes(i->path);
833
834         if (arg_prefix && !path_startswith(i->path, arg_prefix)) {
835                 r = 0;
836                 goto finish;
837         }
838
839         if (user && !streq(user, "-")) {
840                 const char *u = user;
841
842                 r = get_user_creds(&u, &i->uid, NULL, NULL);
843                 if (r < 0) {
844                         log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
845                         goto finish;
846                 }
847
848                 i->uid_set = true;
849         }
850
851         if (group && !streq(group, "-")) {
852                 const char *g = group;
853
854                 r = get_group_creds(&g, &i->gid);
855                 if (r < 0) {
856                         log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
857                         goto finish;
858                 }
859
860                 i->gid_set = true;
861         }
862
863         if (mode && !streq(mode, "-")) {
864                 unsigned m;
865
866                 if (sscanf(mode, "%o", &m) != 1) {
867                         log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
868                         r = -ENOENT;
869                         goto finish;
870                 }
871
872                 i->mode = m;
873                 i->mode_set = true;
874         } else
875                 i->mode = i->type == CREATE_DIRECTORY ? 0755 : 0644;
876
877         if (age && !streq(age, "-")) {
878                 if (parse_usec(age, &i->age) < 0) {
879                         log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
880                         r = -EBADMSG;
881                         goto finish;
882                 }
883
884                 i->age_set = true;
885         }
886
887         h = needs_glob(i->type) ? globs : items;
888
889         if ((existing = hashmap_get(h, i->path))) {
890
891                 /* Two identical items are fine */
892                 if (!item_equal(existing, i))
893                         log_warning("Two or more conflicting lines for %s configured, ignoring.", i->path);
894
895                 r = 0;
896                 goto finish;
897         }
898
899         if ((r = hashmap_put(h, i->path, i)) < 0) {
900                 log_error("Failed to insert item %s: %s", i->path, strerror(-r));
901                 goto finish;
902         }
903
904         i = NULL;
905         r = 0;
906
907 finish:
908         free(user);
909         free(group);
910         free(mode);
911         free(age);
912
913         if (i)
914                 item_free(i);
915
916         return r;
917 }
918
919 static int help(void) {
920
921         printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
922                "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
923                "  -h --help             Show this help\n"
924                "     --create           Create marked files/directories\n"
925                "     --clean            Clean up marked directories\n"
926                "     --remove           Remove marked files/directories\n"
927                "     --prefix=PATH      Only apply rules that apply to paths with the specified prefix\n",
928                program_invocation_short_name);
929
930         return 0;
931 }
932
933 static int parse_argv(int argc, char *argv[]) {
934
935         enum {
936                 ARG_CREATE,
937                 ARG_CLEAN,
938                 ARG_REMOVE,
939                 ARG_PREFIX
940         };
941
942         static const struct option options[] = {
943                 { "help",      no_argument,       NULL, 'h'           },
944                 { "create",    no_argument,       NULL, ARG_CREATE    },
945                 { "clean",     no_argument,       NULL, ARG_CLEAN     },
946                 { "remove",    no_argument,       NULL, ARG_REMOVE    },
947                 { "prefix",    required_argument, NULL, ARG_PREFIX    },
948                 { NULL,        0,                 NULL, 0             }
949         };
950
951         int c;
952
953         assert(argc >= 0);
954         assert(argv);
955
956         while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) {
957
958                 switch (c) {
959
960                 case 'h':
961                         help();
962                         return 0;
963
964                 case ARG_CREATE:
965                         arg_create = true;
966                         break;
967
968                 case ARG_CLEAN:
969                         arg_clean = true;
970                         break;
971
972                 case ARG_REMOVE:
973                         arg_remove = true;
974                         break;
975
976                 case ARG_PREFIX:
977                         arg_prefix = optarg;
978                         break;
979
980                 case '?':
981                         return -EINVAL;
982
983                 default:
984                         log_error("Unknown option code %c", c);
985                         return -EINVAL;
986                 }
987         }
988
989         if (!arg_clean && !arg_create && !arg_remove) {
990                 log_error("You need to specify at least one of --clean, --create or --remove.");
991                 return -EINVAL;
992         }
993
994         return 1;
995 }
996
997 static int read_config_file(const char *fn, bool ignore_enoent) {
998         FILE *f;
999         unsigned v = 0;
1000         int r = 0;
1001
1002         assert(fn);
1003
1004         if (!(f = fopen(fn, "re"))) {
1005
1006                 if (ignore_enoent && errno == ENOENT)
1007                         return 0;
1008
1009                 log_error("Failed to open %s: %m", fn);
1010                 return -errno;
1011         }
1012
1013         log_debug("apply: %s\n", fn);
1014         for (;;) {
1015                 char line[LINE_MAX], *l;
1016                 int k;
1017
1018                 if (!(fgets(line, sizeof(line), f)))
1019                         break;
1020
1021                 v++;
1022
1023                 l = strstrip(line);
1024                 if (*l == '#' || *l == 0)
1025                         continue;
1026
1027                 if ((k = parse_line(fn, v, l)) < 0)
1028                         if (r == 0)
1029                                 r = k;
1030         }
1031
1032         if (ferror(f)) {
1033                 log_error("Failed to read from file %s: %m", fn);
1034                 if (r == 0)
1035                         r = -EIO;
1036         }
1037
1038         fclose(f);
1039
1040         return r;
1041 }
1042
1043 int main(int argc, char *argv[]) {
1044         int r;
1045         Item *i;
1046         Iterator iterator;
1047
1048         if ((r = parse_argv(argc, argv)) <= 0)
1049                 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1050
1051         log_set_target(LOG_TARGET_AUTO);
1052         log_parse_environment();
1053         log_open();
1054
1055         umask(0022);
1056
1057         label_init();
1058
1059         items = hashmap_new(string_hash_func, string_compare_func);
1060         globs = hashmap_new(string_hash_func, string_compare_func);
1061
1062         if (!items || !globs) {
1063                 log_error("Out of memory");
1064                 r = EXIT_FAILURE;
1065                 goto finish;
1066         }
1067
1068         r = EXIT_SUCCESS;
1069
1070         if (optind < argc) {
1071                 int j;
1072
1073                 for (j = optind; j < argc; j++)
1074                         if (read_config_file(argv[j], false) < 0)
1075                                 r = EXIT_FAILURE;
1076
1077         } else {
1078                 char **files, **f;
1079
1080                 r = conf_files_list(&files, ".conf",
1081                                     "/run/tmpfiles.d",
1082                                     "/etc/tmpfiles.d",
1083                                     "/usr/local/lib/tmpfiles.d",
1084                                     "/usr/lib/tmpfiles.d",
1085                                     NULL);
1086                 if (r < 0) {
1087                         r = EXIT_FAILURE;
1088                         log_error("Failed to enumerate tmpfiles.d files: %s", strerror(-r));
1089                         goto finish;
1090                 }
1091
1092                 STRV_FOREACH(f, files) {
1093                         if (read_config_file(*f, true) < 0)
1094                                 r = EXIT_FAILURE;
1095                 }
1096
1097                 strv_free(files);
1098         }
1099
1100         HASHMAP_FOREACH(i, globs, iterator)
1101                 process_item(i);
1102
1103         HASHMAP_FOREACH(i, items, iterator)
1104                 process_item(i);
1105
1106 finish:
1107         while ((i = hashmap_steal_first(items)))
1108                 item_free(i);
1109
1110         while ((i = hashmap_steal_first(globs)))
1111                 item_free(i);
1112
1113         hashmap_free(items);
1114         hashmap_free(globs);
1115
1116         set_free_free(unix_sockets);
1117
1118         label_finish();
1119
1120         return r;
1121 }