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