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