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