]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/tmpfiles/tmpfiles.c
tmpfiles: eat up empty columns
[thirdparty/systemd.git] / src / tmpfiles / tmpfiles.c
CommitLineData
5008d581
LP
1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3/***
4 This file is part of systemd.
5
3b63d2d3 6 Copyright 2010 Lennart Poettering, Kay Sievers
3f93da98 7 Copyright 2015 Zbigniew Jędrzejewski-Szmek
5008d581
LP
8
9 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
10 under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or
5008d581
LP
12 (at your option) any later version.
13
14 systemd is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 17 Lesser General Public License for more details.
5008d581 18
5430f7f2 19 You should have received a copy of the GNU Lesser General Public License
5008d581
LP
20 along with systemd; If not, see <http://www.gnu.org/licenses/>.
21***/
22
23#include <unistd.h>
24#include <fcntl.h>
25#include <errno.h>
26#include <string.h>
5008d581
LP
27#include <limits.h>
28#include <dirent.h>
3b63d2d3
LP
29#include <stdio.h>
30#include <stdlib.h>
31#include <stddef.h>
32#include <getopt.h>
33#include <stdbool.h>
34#include <time.h>
b8bb3e8f
LP
35#include <glob.h>
36#include <fnmatch.h>
505ef0e3 37#include <sys/stat.h>
ebf4e801 38#include <sys/xattr.h>
22c3a6ca 39#include <linux/fs.h>
5008d581
LP
40
41#include "log.h"
42#include "util.h"
54693d9b 43#include "macro.h"
d39efe74 44#include "missing.h"
49e942b2 45#include "mkdir.h"
9eb977db 46#include "path-util.h"
5008d581
LP
47#include "strv.h"
48#include "label.h"
3b63d2d3 49#include "set.h"
2c21044f 50#include "conf-files.h"
cb7ed9df 51#include "capability.h"
1731e34a 52#include "specifier.h"
eb9da376 53#include "build.h"
849958d1 54#include "copy.h"
c6878637 55#include "rm-rf.h"
d7b8eec7
LP
56#include "selinux-util.h"
57#include "btrfs-util.h"
f8eeeaf9 58#include "acl-util.h"
5008d581 59
01000479 60/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
5008d581 61 * them in the file system. This is intended to be used to create
db019b8d
KS
62 * properly owned directories beneath /tmp, /var/tmp, /run, which are
63 * volatile and hence need to be recreated on bootup. */
5008d581 64
66ccd038 65typedef enum ItemType {
b8bb3e8f 66 /* These ones take file names */
3b63d2d3
LP
67 CREATE_FILE = 'f',
68 TRUNCATE_FILE = 'F',
69 CREATE_DIRECTORY = 'd',
70 TRUNCATE_DIRECTORY = 'D',
d7b8eec7 71 CREATE_SUBVOLUME = 'v',
ee17ee7c 72 CREATE_FIFO = 'p',
468d726b
LP
73 CREATE_SYMLINK = 'L',
74 CREATE_CHAR_DEVICE = 'c',
75 CREATE_BLOCK_DEVICE = 'b',
849958d1 76 COPY_FILES = 'C',
b8bb3e8f
LP
77
78 /* These ones take globs */
b705ab6a
ZJS
79 SET_XATTR = 't',
80 RECURSIVE_SET_XATTR = 'T',
81 SET_ACL = 'a',
82 RECURSIVE_SET_ACL = 'A',
cde684a2 83 WRITE_FILE = 'w',
3b63d2d3 84 IGNORE_PATH = 'x',
78a92a5a 85 IGNORE_DIRECTORY_PATH = 'X',
3b63d2d3 86 REMOVE_PATH = 'r',
a8d88783 87 RECURSIVE_REMOVE_PATH = 'R',
e73a03e0 88 ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
777b87e7 89 RELABEL_PATH = 'z',
e73a03e0 90 RECURSIVE_RELABEL_PATH = 'Z',
88ec4dfa
LP
91 SET_ATTRIBUTE = 'h',
92 RECURSIVE_SET_ATTRIBUTE = 'H',
66ccd038 93} ItemType;
3b63d2d3
LP
94
95typedef struct Item {
66ccd038 96 ItemType type;
3b63d2d3
LP
97
98 char *path;
468d726b 99 char *argument;
ebf4e801 100 char **xattrs;
f8eeeaf9
ZJS
101#ifdef HAVE_ACL
102 acl_t acl_access;
103 acl_t acl_default;
104#endif
5008d581
LP
105 uid_t uid;
106 gid_t gid;
3b63d2d3
LP
107 mode_t mode;
108 usec_t age;
109
468d726b 110 dev_t major_minor;
88ec4dfa
LP
111 unsigned attribute_value;
112 unsigned attribute_mask;
468d726b 113
3b63d2d3
LP
114 bool uid_set:1;
115 bool gid_set:1;
116 bool mode_set:1;
117 bool age_set:1;
abef3f91 118 bool mask_perms:1;
88ec4dfa 119 bool attribute_set:1;
24f3a374
LP
120
121 bool keep_first_level:1;
1910cd0e 122
2e78fa79
LP
123 bool force:1;
124
1910cd0e 125 bool done:1;
3b63d2d3
LP
126} Item;
127
3f93da98
ZJS
128typedef struct ItemArray {
129 Item *items;
130 size_t count;
131 size_t size;
132} ItemArray;
133
3b63d2d3
LP
134static bool arg_create = false;
135static bool arg_clean = false;
136static bool arg_remove = false;
81815651 137static bool arg_boot = false;
3b63d2d3 138
7bc040fa
LP
139static char **arg_include_prefixes = NULL;
140static char **arg_exclude_prefixes = NULL;
cf9a4abd 141static char *arg_root = NULL;
fba6e687 142
7f0a55d4 143static const char conf_file_dirs[] = CONF_DIRS_NULSTR("tmpfiles");
9125670f 144
3b63d2d3
LP
145#define MAX_DEPTH 256
146
7bc040fa
LP
147static Hashmap *items = NULL, *globs = NULL;
148static Set *unix_sockets = NULL;
149
bd550f78
LP
150static const Specifier specifier_table[] = {
151 { 'm', specifier_machine_id, NULL },
152 { 'b', specifier_boot_id, NULL },
153 { 'H', specifier_host_name, NULL },
154 { 'v', specifier_kernel_release, NULL },
155 {}
156};
157
66ccd038 158static bool needs_glob(ItemType t) {
cde684a2
LP
159 return IN_SET(t,
160 WRITE_FILE,
161 IGNORE_PATH,
162 IGNORE_DIRECTORY_PATH,
163 REMOVE_PATH,
164 RECURSIVE_REMOVE_PATH,
e73a03e0 165 ADJUST_MODE,
cde684a2 166 RELABEL_PATH,
b705ab6a
ZJS
167 RECURSIVE_RELABEL_PATH,
168 SET_XATTR,
169 RECURSIVE_SET_XATTR,
170 SET_ACL,
34f64536
LP
171 RECURSIVE_SET_ACL,
172 SET_ATTRIBUTE,
173 RECURSIVE_SET_ATTRIBUTE);
b8bb3e8f
LP
174}
175
3f93da98
ZJS
176static bool takes_ownership(ItemType t) {
177 return IN_SET(t,
178 CREATE_FILE,
179 TRUNCATE_FILE,
180 CREATE_DIRECTORY,
181 TRUNCATE_DIRECTORY,
182 CREATE_SUBVOLUME,
183 CREATE_FIFO,
184 CREATE_SYMLINK,
185 CREATE_CHAR_DEVICE,
186 CREATE_BLOCK_DEVICE,
187 COPY_FILES,
3f93da98
ZJS
188 WRITE_FILE,
189 IGNORE_PATH,
190 IGNORE_DIRECTORY_PATH,
191 REMOVE_PATH,
192 RECURSIVE_REMOVE_PATH);
193}
194
b8bb3e8f 195static struct Item* find_glob(Hashmap *h, const char *match) {
3f93da98 196 ItemArray *j;
b8bb3e8f
LP
197 Iterator i;
198
3f93da98
ZJS
199 HASHMAP_FOREACH(j, h, i) {
200 unsigned n;
201
202 for (n = 0; n < j->count; n++) {
203 Item *item = j->items + n;
204
205 if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
206 return item;
207 }
208 }
b8bb3e8f
LP
209
210 return NULL;
211}
212
17b90525 213static void load_unix_sockets(void) {
7fd1b19b 214 _cleanup_fclose_ FILE *f = NULL;
17b90525
LP
215 char line[LINE_MAX];
216
217 if (unix_sockets)
218 return;
219
220 /* We maintain a cache of the sockets we found in
221 * /proc/net/unix to speed things up a little. */
222
d5099efc 223 unix_sockets = set_new(&string_hash_ops);
fdcad0c2 224 if (!unix_sockets)
17b90525
LP
225 return;
226
fdcad0c2
LP
227 f = fopen("/proc/net/unix", "re");
228 if (!f)
17b90525
LP
229 return;
230
fdcad0c2
LP
231 /* Skip header */
232 if (!fgets(line, sizeof(line), f))
17b90525
LP
233 goto fail;
234
235 for (;;) {
236 char *p, *s;
237 int k;
238
fdcad0c2 239 if (!fgets(line, sizeof(line), f))
17b90525
LP
240 break;
241
242 truncate_nl(line);
243
fdcad0c2
LP
244 p = strchr(line, ':');
245 if (!p)
246 continue;
247
248 if (strlen(p) < 37)
17b90525
LP
249 continue;
250
fdcad0c2 251 p += 37;
17b90525 252 p += strspn(p, WHITESPACE);
fdcad0c2 253 p += strcspn(p, WHITESPACE); /* skip one more word */
17b90525
LP
254 p += strspn(p, WHITESPACE);
255
256 if (*p != '/')
257 continue;
258
fdcad0c2
LP
259 s = strdup(p);
260 if (!s)
17b90525
LP
261 goto fail;
262
4ff21d85
LP
263 path_kill_slashes(s);
264
ef42202a
ZJS
265 k = set_consume(unix_sockets, s);
266 if (k < 0 && k != -EEXIST)
267 goto fail;
17b90525
LP
268 }
269
270 return;
271
272fail:
273 set_free_free(unix_sockets);
274 unix_sockets = NULL;
17b90525
LP
275}
276
277static bool unix_socket_alive(const char *fn) {
278 assert(fn);
279
280 load_unix_sockets();
281
282 if (unix_sockets)
283 return !!set_get(unix_sockets, (char*) fn);
284
285 /* We don't know, so assume yes */
286 return true;
287}
288
99d680ac 289static int dir_is_mount_point(DIR *d, const char *subdir) {
cde684a2 290
2695c5c4 291 union file_handle_union h = FILE_HANDLE_INIT;
99d680ac
KS
292 int mount_id_parent, mount_id;
293 int r_p, r;
294
370c860f 295 r_p = name_to_handle_at(dirfd(d), ".", &h.handle, &mount_id_parent, 0);
99d680ac
KS
296 if (r_p < 0)
297 r_p = -errno;
298
370c860f
DR
299 h.handle.handle_bytes = MAX_HANDLE_SZ;
300 r = name_to_handle_at(dirfd(d), subdir, &h.handle, &mount_id, 0);
99d680ac
KS
301 if (r < 0)
302 r = -errno;
303
304 /* got no handle; make no assumptions, return error */
305 if (r_p < 0 && r < 0)
306 return r_p;
307
308 /* got both handles; if they differ, it is a mount point */
309 if (r_p >= 0 && r >= 0)
310 return mount_id_parent != mount_id;
311
312 /* got only one handle; assume different mount points if one
313 * of both queries was not supported by the filesystem */
e7aab541 314 if (r_p == -ENOSYS || r_p == -EOPNOTSUPP || r == -ENOSYS || r == -EOPNOTSUPP)
99d680ac
KS
315 return true;
316
317 /* return error */
318 if (r_p < 0)
319 return r_p;
320 return r;
321}
322
df99a9ef
ZJS
323static DIR* xopendirat_nomod(int dirfd, const char *path) {
324 DIR *dir;
325
326 dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
1532227a
LP
327 if (dir)
328 return dir;
329
330 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
331 if (errno != EPERM)
332 return NULL;
333
334 dir = xopendirat(dirfd, path, O_NOFOLLOW);
335 if (!dir)
336 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
df99a9ef
ZJS
337
338 return dir;
339}
340
341static DIR* opendir_nomod(const char *path) {
342 return xopendirat_nomod(AT_FDCWD, path);
343}
344
3b63d2d3 345static int dir_cleanup(
78a92a5a 346 Item *i,
3b63d2d3
LP
347 const char *p,
348 DIR *d,
349 const struct stat *ds,
350 usec_t cutoff,
351 dev_t rootdev,
352 bool mountpoint,
24f3a374 353 int maxdepth,
265ffa1e
LP
354 bool keep_this_level) {
355
3b63d2d3
LP
356 struct dirent *dent;
357 struct timespec times[2];
358 bool deleted = false;
3b63d2d3
LP
359 int r = 0;
360
361 while ((dent = readdir(d))) {
362 struct stat s;
363 usec_t age;
7fd1b19b 364 _cleanup_free_ char *sub_path = NULL;
3b63d2d3 365
7fcb4b9b 366 if (STR_IN_SET(dent->d_name, ".", ".."))
3b63d2d3 367 continue;
5008d581 368
3b63d2d3 369 if (fstatat(dirfd(d), dent->d_name, &s, AT_SYMLINK_NOFOLLOW) < 0) {
ca2f4176
KS
370 if (errno == ENOENT)
371 continue;
5008d581 372
ca2f4176
KS
373 /* FUSE, NFS mounts, SELinux might return EACCES */
374 if (errno == EACCES)
56f64d95 375 log_debug_errno(errno, "stat(%s/%s) failed: %m", p, dent->d_name);
ca2f4176 376 else
56f64d95 377 log_error_errno(errno, "stat(%s/%s) failed: %m", p, dent->d_name);
ca2f4176 378 r = -errno;
3b63d2d3
LP
379 continue;
380 }
381
382 /* Stay on the same filesystem */
582deb84
ZJS
383 if (s.st_dev != rootdev) {
384 log_debug("Ignoring \"%s/%s\": different filesystem.", p, dent->d_name);
3b63d2d3 385 continue;
582deb84 386 }
3b63d2d3 387
99d680ac
KS
388 /* Try to detect bind mounts of the same filesystem instance; they
389 * do not differ in device major/minors. This type of query is not
390 * supported on all kernels or filesystem types though. */
582deb84
ZJS
391 if (S_ISDIR(s.st_mode) && dir_is_mount_point(d, dent->d_name) > 0) {
392 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.",
393 p, dent->d_name);
99d680ac 394 continue;
582deb84 395 }
99d680ac 396
3b63d2d3 397 /* Do not delete read-only files owned by root */
582deb84
ZJS
398 if (s.st_uid == 0 && !(s.st_mode & S_IWUSR)) {
399 log_debug("Ignoring \"%s/%s\": read-only and owner by root.", p, dent->d_name);
3b63d2d3 400 continue;
582deb84 401 }
3b63d2d3 402
cde684a2
LP
403 sub_path = strjoin(p, "/", dent->d_name, NULL);
404 if (!sub_path) {
0d0f0c50 405 r = log_oom();
3b63d2d3
LP
406 goto finish;
407 }
408
409 /* Is there an item configured for this path? */
582deb84
ZJS
410 if (hashmap_get(items, sub_path)) {
411 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
3b63d2d3 412 continue;
582deb84 413 }
3b63d2d3 414
582deb84
ZJS
415 if (find_glob(globs, sub_path)) {
416 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
b8bb3e8f 417 continue;
582deb84 418 }
b8bb3e8f 419
3b63d2d3
LP
420 if (S_ISDIR(s.st_mode)) {
421
422 if (mountpoint &&
423 streq(dent->d_name, "lost+found") &&
582deb84
ZJS
424 s.st_uid == 0) {
425 log_debug("Ignoring \"%s\".", sub_path);
3b63d2d3 426 continue;
582deb84 427 }
3b63d2d3
LP
428
429 if (maxdepth <= 0)
582deb84 430 log_warning("Reached max depth on \"%s\".", sub_path);
3b63d2d3 431 else {
7fd1b19b 432 _cleanup_closedir_ DIR *sub_dir;
3b63d2d3
LP
433 int q;
434
df99a9ef 435 sub_dir = xopendirat_nomod(dirfd(d), dent->d_name);
cde684a2 436 if (!sub_dir) {
582deb84
ZJS
437 if (errno != ENOENT)
438 r = log_error_errno(errno, "opendir(%s) failed: %m", sub_path);
3b63d2d3
LP
439
440 continue;
441 }
442
78a92a5a 443 q = dir_cleanup(i, sub_path, sub_dir, &s, cutoff, rootdev, false, maxdepth-1, false);
3b63d2d3
LP
444 if (q < 0)
445 r = q;
446 }
447
24f3a374
LP
448 /* Note: if you are wondering why we don't
449 * support the sticky bit for excluding
450 * directories from cleaning like we do it for
451 * other file system objects: well, the sticky
452 * bit already has a meaning for directories,
453 * so we don't want to overload that. */
454
582deb84
ZJS
455 if (keep_this_level) {
456 log_debug("Keeping \"%s\".", sub_path);
24f3a374 457 continue;
582deb84 458 }
24f3a374 459
3b63d2d3 460 /* Ignore ctime, we change it when deleting */
582deb84
ZJS
461 age = timespec_load(&s.st_mtim);
462 if (age >= cutoff) {
463 char a[FORMAT_TIMESTAMP_MAX];
464 /* Follows spelling in stat(1). */
465 log_debug("Directory \"%s\": modify time %s is too new.",
466 sub_path,
467 format_timestamp_us(a, sizeof(a), age));
3b63d2d3 468 continue;
582deb84
ZJS
469 }
470
471 age = timespec_load(&s.st_atim);
472 if (age >= cutoff) {
473 char a[FORMAT_TIMESTAMP_MAX];
474 log_debug("Directory \"%s\": access time %s is too new.",
475 sub_path,
476 format_timestamp_us(a, sizeof(a), age));
477 continue;
478 }
3b63d2d3 479
61253220
ZJS
480 log_debug("Removing directory \"%s\".", sub_path);
481 if (unlinkat(dirfd(d), dent->d_name, AT_REMOVEDIR) < 0)
482 if (errno != ENOENT && errno != ENOTEMPTY) {
483 log_error_errno(errno, "rmdir(%s): %m", sub_path);
484 r = -errno;
3b63d2d3 485 }
3b63d2d3
LP
486
487 } else {
9c73736d
LP
488 /* Skip files for which the sticky bit is
489 * set. These are semantics we define, and are
490 * unknown elsewhere. See XDG_RUNTIME_DIR
491 * specification for details. */
582deb84
ZJS
492 if (s.st_mode & S_ISVTX) {
493 log_debug("Skipping \"%s\": sticky bit set.", sub_path);
9c73736d 494 continue;
582deb84 495 }
9c73736d 496
582deb84
ZJS
497 if (mountpoint && S_ISREG(s.st_mode))
498 if ((streq(dent->d_name, ".journal") && s.st_uid == 0) ||
499 streq(dent->d_name, "aquota.user") ||
500 streq(dent->d_name, "aquota.group")) {
501 log_debug("Skipping \"%s\".", sub_path);
3b63d2d3 502 continue;
582deb84 503 }
3b63d2d3 504
17b90525 505 /* Ignore sockets that are listed in /proc/net/unix */
582deb84
ZJS
506 if (S_ISSOCK(s.st_mode) && unix_socket_alive(sub_path)) {
507 log_debug("Skipping \"%s\": live socket.", sub_path);
17b90525 508 continue;
582deb84 509 }
17b90525 510
78ab08eb 511 /* Ignore device nodes */
582deb84
ZJS
512 if (S_ISCHR(s.st_mode) || S_ISBLK(s.st_mode)) {
513 log_debug("Skipping \"%s\": a device.", sub_path);
78ab08eb 514 continue;
582deb84 515 }
78ab08eb 516
24f3a374
LP
517 /* Keep files on this level around if this is
518 * requested */
582deb84
ZJS
519 if (keep_this_level) {
520 log_debug("Keeping \"%s\".", sub_path);
24f3a374 521 continue;
582deb84 522 }
24f3a374 523
582deb84
ZJS
524 age = timespec_load(&s.st_mtim);
525 if (age >= cutoff) {
526 char a[FORMAT_TIMESTAMP_MAX];
527 /* Follows spelling in stat(1). */
528 log_debug("File \"%s\": modify time %s is too new.",
529 sub_path,
530 format_timestamp_us(a, sizeof(a), age));
3b63d2d3 531 continue;
582deb84 532 }
3b63d2d3 533
582deb84
ZJS
534 age = timespec_load(&s.st_atim);
535 if (age >= cutoff) {
536 char a[FORMAT_TIMESTAMP_MAX];
537 log_debug("File \"%s\": access time %s is too new.",
538 sub_path,
539 format_timestamp_us(a, sizeof(a), age));
540 continue;
541 }
3b63d2d3 542
582deb84
ZJS
543 age = timespec_load(&s.st_ctim);
544 if (age >= cutoff) {
545 char a[FORMAT_TIMESTAMP_MAX];
546 log_debug("File \"%s\": change time %s is too new.",
547 sub_path,
548 format_timestamp_us(a, sizeof(a), age));
549 continue;
3b63d2d3
LP
550 }
551
582deb84
ZJS
552 log_debug("unlink \"%s\"", sub_path);
553
554 if (unlinkat(dirfd(d), dent->d_name, 0) < 0)
555 if (errno != ENOENT)
556 r = log_error_errno(errno, "unlink(%s): %m", sub_path);
557
3b63d2d3
LP
558 deleted = true;
559 }
560 }
561
562finish:
563 if (deleted) {
582deb84
ZJS
564 usec_t age1, age2;
565 char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX];
566
3b63d2d3
LP
567 /* Restore original directory timestamps */
568 times[0] = ds->st_atim;
569 times[1] = ds->st_mtim;
570
582deb84
ZJS
571 age1 = timespec_load(&ds->st_atim);
572 age2 = timespec_load(&ds->st_mtim);
573 log_debug("Restoring access and modification time on \"%s\": %s, %s",
574 p,
575 format_timestamp_us(a, sizeof(a), age1),
576 format_timestamp_us(b, sizeof(b), age2));
3b63d2d3 577 if (futimens(dirfd(d), times) < 0)
56f64d95 578 log_error_errno(errno, "utimensat(%s): %m", p);
3b63d2d3
LP
579 }
580
3b63d2d3
LP
581 return r;
582}
583
b705ab6a 584static int path_set_perms(Item *i, const char *path) {
1924a97d
MO
585 struct stat st;
586 bool st_valid;
587
cde684a2
LP
588 assert(i);
589 assert(path);
590
1924a97d
MO
591 st_valid = stat(path, &st) == 0;
592
062e01bb 593 /* not using i->path directly because it may be a glob */
abef3f91
LP
594 if (i->mode_set) {
595 mode_t m = i->mode;
596
1924a97d
MO
597 if (i->mask_perms && st_valid) {
598 if (!(st.st_mode & 0111))
599 m &= ~0111;
600 if (!(st.st_mode & 0222))
601 m &= ~0222;
602 if (!(st.st_mode & 0444))
603 m &= ~0444;
604 if (!S_ISDIR(st.st_mode))
605 m &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
abef3f91
LP
606 }
607
582deb84
ZJS
608 if (st_valid && m == (st.st_mode & 07777))
609 log_debug("\"%s\" has right mode %o", path, st.st_mode);
610 else {
611 log_debug("chmod \"%s\" to mode %o", path, m);
4a62c710
MS
612 if (chmod(path, m) < 0)
613 return log_error_errno(errno, "chmod(%s) failed: %m", path);
062e01bb 614 }
abef3f91 615 }
062e01bb 616
582deb84
ZJS
617 if ((!st_valid || i->uid != st.st_uid || i->gid != st.st_gid) &&
618 (i->uid_set || i->gid_set)) {
619 log_debug("chown \"%s\" to "UID_FMT"."GID_FMT,
620 path,
621 i->uid_set ? i->uid : UID_INVALID,
622 i->gid_set ? i->gid : GID_INVALID);
062e01bb 623 if (chown(path,
fed1e721 624 i->uid_set ? i->uid : UID_INVALID,
505ef0e3 625 i->gid_set ? i->gid : GID_INVALID) < 0)
062e01bb 626
505ef0e3 627 return log_error_errno(errno, "chown(%s) failed: %m", path);
582deb84 628 }
062e01bb 629
9855d6c7 630 return label_fix(path, false, false);
062e01bb
MS
631}
632
bd550f78 633static int parse_xattrs_from_arg(Item *i) {
ebf4e801
MW
634 const char *p;
635 int r;
636
637 assert(i);
505ef0e3 638 assert(i->argument);
ebf4e801 639
ebf4e801
MW
640 p = i->argument;
641
4034a06d 642 for (;;) {
bd550f78 643 _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL, *xattr_replaced = NULL;
4034a06d
LP
644
645 r = unquote_first_word(&p, &xattr, UNQUOTE_CUNESCAPE);
646 if (r < 0)
bd550f78 647 log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
4034a06d
LP
648 if (r <= 0)
649 break;
505ef0e3 650
bd550f78
LP
651 r = specifier_printf(xattr, specifier_table, NULL, &xattr_replaced);
652 if (r < 0)
653 return log_error_errno(r, "Failed to replace specifiers in extended attribute '%s': %m", xattr);
654
655 r = split_pair(xattr_replaced, "=", &name, &value);
ebf4e801 656 if (r < 0) {
4034a06d 657 log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
ebf4e801
MW
658 continue;
659 }
505ef0e3 660
4034a06d 661 if (isempty(name) || isempty(value)) {
bd550f78 662 log_warning("Malformed extended attribute found, ignoring: %s", xattr);
ebf4e801
MW
663 continue;
664 }
505ef0e3 665
4034a06d 666 if (strv_push_pair(&i->xattrs, name, value) < 0)
ebf4e801 667 return log_oom();
505ef0e3 668
4034a06d 669 name = value = NULL;
ebf4e801
MW
670 }
671
4034a06d 672 return 0;
ebf4e801
MW
673}
674
b705ab6a 675static int path_set_xattrs(Item *i, const char *path) {
ebf4e801
MW
676 char **name, **value;
677
678 assert(i);
679 assert(path);
680
ebf4e801
MW
681 STRV_FOREACH_PAIR(name, value, i->xattrs) {
682 int n;
505ef0e3 683
ebf4e801 684 n = strlen(*value);
bd550f78 685 log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
ebf4e801 686 if (lsetxattr(path, *name, *value, n, 0) < 0) {
bd550f78 687 log_error("Setting extended attribute %s=%s on %s failed: %m", *name, *value, path);
ebf4e801
MW
688 return -errno;
689 }
690 }
691 return 0;
692}
693
bd550f78 694static int parse_acls_from_arg(Item *item) {
f8eeeaf9
ZJS
695#ifdef HAVE_ACL
696 int r;
f8eeeaf9
ZJS
697
698 assert(item);
699
50d9e46d
ZJS
700 /* If force (= modify) is set, we will not modify the acl
701 * afterwards, so the mask can be added now if necessary. */
bd550f78 702
50d9e46d 703 r = parse_acl(item->argument, &item->acl_access, &item->acl_default, !item->force);
f8eeeaf9 704 if (r < 0)
4034a06d 705 log_warning_errno(r, "Failed to parse ACL \"%s\": %m. Ignoring", item->argument);
f8eeeaf9
ZJS
706#else
707 log_warning_errno(ENOSYS, "ACLs are not supported. Ignoring");
708#endif
709
710 return 0;
711}
712
35888b67 713#ifdef HAVE_ACL
50d9e46d 714static int path_set_acl(const char *path, acl_type_t type, acl_t acl, bool modify) {
dd4105b0 715 _cleanup_(acl_freep) acl_t dup = NULL;
50d9e46d 716 int r;
582deb84 717 _cleanup_(acl_free_charpp) char *t = NULL;
50d9e46d 718
d873e877
HPD
719 /* Returns 0 for success, positive error if already warned,
720 * negative error otherwise. */
721
50d9e46d 722 if (modify) {
dd4105b0 723 r = acls_for_file(path, type, acl, &dup);
50d9e46d
ZJS
724 if (r < 0)
725 return r;
50d9e46d 726
dd4105b0
ZJS
727 r = calc_acl_mask_if_needed(&dup);
728 if (r < 0)
729 return r;
730 } else {
731 dup = acl_dup(acl);
732 if (!dup)
733 return -errno;
734
735 /* the mask was already added earlier if needed */
736 }
737
738 r = add_base_acls_if_needed(&dup, path);
739 if (r < 0)
740 return r;
741
582deb84
ZJS
742 t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
743 log_debug("\"%s\": setting %s ACL \"%s\"", path,
744 type == ACL_TYPE_ACCESS ? "access" : "default",
745 strna(t));
50d9e46d 746
582deb84
ZJS
747 r = acl_set_file(path, type, dup);
748 if (r < 0)
3ea40b78
LP
749 /* Return positive to indicate we already warned */
750 return -log_error_errno(errno,
751 "Setting %s ACL \"%s\" on %s failed: %m",
752 type == ACL_TYPE_ACCESS ? "access" : "default",
753 strna(t), path);
d873e877 754
582deb84 755 return 0;
50d9e46d 756}
35888b67 757#endif
50d9e46d 758
b705ab6a 759static int path_set_acls(Item *item, const char *path) {
d873e877 760 int r = 0;
f8eeeaf9 761#ifdef HAVE_ACL
f8eeeaf9
ZJS
762 assert(item);
763 assert(path);
764
d873e877 765 if (item->acl_access)
50d9e46d 766 r = path_set_acl(path, ACL_TYPE_ACCESS, item->acl_access, item->force);
f8eeeaf9 767
d873e877 768 if (r == 0 && item->acl_default)
50d9e46d 769 r = path_set_acl(path, ACL_TYPE_DEFAULT, item->acl_default, item->force);
f8eeeaf9 770
d873e877
HPD
771 if (r > 0)
772 return -r; /* already warned */
15411c0c 773 else if (r == -EOPNOTSUPP) {
d873e877
HPD
774 log_debug_errno(r, "ACLs not supported by file system at %s", path);
775 return 0;
776 } else if (r < 0)
777 log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
778#endif
779 return r;
f8eeeaf9
ZJS
780}
781
88ec4dfa
LP
782#define ATTRIBUTES_ALL \
783 (FS_NOATIME_FL | \
784 FS_SYNC_FL | \
785 FS_DIRSYNC_FL | \
786 FS_APPEND_FL | \
787 FS_COMPR_FL | \
788 FS_NODUMP_FL | \
789 FS_EXTENT_FL | \
790 FS_IMMUTABLE_FL | \
791 FS_JOURNAL_DATA_FL | \
792 FS_SECRM_FL | \
793 FS_UNRM_FL | \
794 FS_NOTAIL_FL | \
795 FS_TOPDIR_FL | \
796 FS_NOCOW_FL)
797
bd550f78 798static int parse_attribute_from_arg(Item *item) {
88ec4dfa
LP
799
800 static const struct {
801 char character;
802 unsigned value;
803 } attributes[] = {
804 { 'A', FS_NOATIME_FL }, /* do not update atime */
805 { 'S', FS_SYNC_FL }, /* Synchronous updates */
806 { 'D', FS_DIRSYNC_FL }, /* dirsync behaviour (directories only) */
807 { 'a', FS_APPEND_FL }, /* writes to file may only append */
808 { 'c', FS_COMPR_FL }, /* Compress file */
809 { 'd', FS_NODUMP_FL }, /* do not dump file */
810 { 'e', FS_EXTENT_FL }, /* Top of directory hierarchies*/
811 { 'i', FS_IMMUTABLE_FL }, /* Immutable file */
812 { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
813 { 's', FS_SECRM_FL }, /* Secure deletion */
814 { 'u', FS_UNRM_FL }, /* Undelete */
815 { 't', FS_NOTAIL_FL }, /* file tail should not be merged */
816 { 'T', FS_TOPDIR_FL }, /* Top of directory hierarchies*/
817 { 'C', FS_NOCOW_FL }, /* Do not cow file */
22c3a6ca 818 };
88ec4dfa 819
22c3a6ca
GB
820 enum {
821 MODE_ADD,
822 MODE_DEL,
823 MODE_SET
824 } mode = MODE_ADD;
22c3a6ca 825
88ec4dfa
LP
826 unsigned value = 0, mask = 0;
827 const char *p;
22c3a6ca 828
88ec4dfa
LP
829 assert(item);
830
831 p = item->argument;
832 if (p) {
833 if (*p == '+') {
834 mode = MODE_ADD;
835 p++;
836 } else if (*p == '-') {
837 mode = MODE_DEL;
838 p++;
839 } else if (*p == '=') {
840 mode = MODE_SET;
841 p++;
842 }
22c3a6ca
GB
843 }
844
88ec4dfa
LP
845 if (isempty(p) && mode != MODE_SET) {
846 log_error("Setting file attribute on '%s' needs an attribute specification.", item->path);
22c3a6ca
GB
847 return -EINVAL;
848 }
88ec4dfa
LP
849
850 for (; p && *p ; p++) {
851 unsigned i, v;
852
853 for (i = 0; i < ELEMENTSOF(attributes); i++)
854 if (*p == attributes[i].character)
855 break;
856
857 if (i >= ELEMENTSOF(attributes)) {
858 log_error("Unknown file attribute '%c' on '%s'.", *p, item->path);
22c3a6ca
GB
859 return -EINVAL;
860 }
88ec4dfa
LP
861
862 v = attributes[i].value;
863
22c3a6ca 864 if (mode == MODE_ADD || mode == MODE_SET)
88ec4dfa 865 value |= v;
22c3a6ca 866 else
88ec4dfa
LP
867 value &= ~v;
868
869 mask |= v;
22c3a6ca
GB
870 }
871
872 if (mode == MODE_SET)
88ec4dfa 873 mask |= ATTRIBUTES_ALL;
22c3a6ca 874
88ec4dfa 875 assert(mask != 0);
22c3a6ca 876
88ec4dfa
LP
877 item->attribute_mask = mask;
878 item->attribute_value = value;
879 item->attribute_set = true;
22c3a6ca
GB
880
881 return 0;
22c3a6ca
GB
882}
883
88ec4dfa 884static int path_set_attribute(Item *item, const char *path) {
22c3a6ca 885 _cleanup_close_ int fd = -1;
22c3a6ca 886 struct stat st;
88ec4dfa
LP
887 unsigned f;
888 int r;
22c3a6ca 889
88ec4dfa 890 if (!item->attribute_set || item->attribute_mask == 0)
22c3a6ca 891 return 0;
22c3a6ca
GB
892
893 fd = open(path, O_RDONLY|O_NONBLOCK|O_CLOEXEC);
22c3a6ca 894 if (fd < 0)
88ec4dfa 895 return log_error_errno(errno, "Cannot open '%s': %m", path);
22c3a6ca 896
88ec4dfa
LP
897 if (fstat(fd, &st) < 0)
898 return log_error_errno(errno, "Cannot stat '%s': %m", path);
899
900 /* Issuing the file attribute ioctls on device nodes is not
901 * safe, as that will be delivered to the drivers, not the
902 * file system containing the device node. */
903 if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode)) {
904 log_error("Setting file flags is only supported on regular files and directories, cannot set on '%s'.", path);
905 return -EINVAL;
906 }
907
908 f = item->attribute_value & item->attribute_mask;
909
910 /* Mask away directory-specific flags */
22c3a6ca
GB
911 if (!S_ISDIR(st.st_mode))
912 f &= ~FS_DIRSYNC_FL;
88ec4dfa
LP
913
914 r = chattr_fd(fd, f, item->attribute_mask);
22c3a6ca 915 if (r < 0)
88ec4dfa
LP
916 return log_error_errno(r,
917 "Cannot set file attribute for '%s', value=0x%08x, mask=0x%08x: %m",
918 path, item->attribute_value, item->attribute_mask);
22c3a6ca
GB
919
920 return 0;
921}
922
d4e9eb91 923static int write_one_file(Item *i, const char *path) {
43ad6e31
LP
924 _cleanup_close_ int fd = -1;
925 int flags, r = 0;
d4e9eb91 926 struct stat st;
d4e9eb91 927
874f1947
LP
928 assert(i);
929 assert(path);
930
43ad6e31
LP
931 flags = i->type == CREATE_FILE ? O_CREAT|O_APPEND|O_NOFOLLOW :
932 i->type == TRUNCATE_FILE ? O_CREAT|O_TRUNC|O_NOFOLLOW : 0;
d4e9eb91 933
43ad6e31 934 RUN_WITH_UMASK(0000) {
ecabcf8b 935 mac_selinux_create_file_prepare(path, S_IFREG);
43ad6e31 936 fd = open(path, flags|O_NDELAY|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode);
ecabcf8b 937 mac_selinux_create_file_clear();
5c0d398d 938 }
d4e9eb91
DR
939
940 if (fd < 0) {
582deb84
ZJS
941 if (i->type == WRITE_FILE && errno == ENOENT) {
942 log_debug_errno(errno, "Not writing \"%s\": %m", path);
d4e9eb91 943 return 0;
582deb84 944 }
d4e9eb91 945
56f64d95 946 log_error_errno(errno, "Failed to create file %s: %m", path);
d4e9eb91
DR
947 return -errno;
948 }
949
950 if (i->argument) {
bd550f78 951 _cleanup_free_ char *unescaped = NULL, *replaced = NULL;
582deb84 952
4034a06d 953 log_debug("%s to \"%s\".", i->type == CREATE_FILE ? "Appending" : "Writing", path);
d4e9eb91 954
527b7a42
LP
955 r = cunescape(i->argument, 0, &unescaped);
956 if (r < 0)
957 return log_error_errno(r, "Failed to unescape parameter to write: %s", i->argument);
d4e9eb91 958
bd550f78
LP
959 r = specifier_printf(unescaped, specifier_table, NULL, &replaced);
960 if (r < 0)
961 return log_error_errno(r, "Failed to replace specifiers in parameter to write '%s': %m", unescaped);
962
963 r = loop_write(fd, replaced, strlen(replaced), false);
582deb84
ZJS
964 if (r < 0)
965 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
966 } else
967 log_debug("\"%s\" has been created.", path);
d4e9eb91 968
43ad6e31 969 fd = safe_close(fd);
3612fbc1 970
4a62c710
MS
971 if (stat(path, &st) < 0)
972 return log_error_errno(errno, "stat(%s) failed: %m", path);
d4e9eb91
DR
973
974 if (!S_ISREG(st.st_mode)) {
975 log_error("%s is not a file.", path);
976 return -EEXIST;
977 }
978
b705ab6a 979 r = path_set_perms(i, path);
d4e9eb91
DR
980 if (r < 0)
981 return r;
982
983 return 0;
984}
985
081043cf
ZJS
986typedef int (*action_t)(Item *, const char *);
987
988static int item_do_children(Item *i, const char *path, action_t action) {
7fd1b19b 989 _cleanup_closedir_ DIR *d;
e73a03e0
LP
990 int r = 0;
991
992 assert(i);
993 assert(path);
a8d88783
MS
994
995 /* This returns the first error we run into, but nevertheless
996 * tries to go on */
997
df99a9ef
ZJS
998 d = opendir_nomod(path);
999 if (!d)
e73a03e0 1000 return errno == ENOENT || errno == ENOTDIR ? 0 : -errno;
a8d88783
MS
1001
1002 for (;;) {
e73a03e0 1003 _cleanup_free_ char *p = NULL;
7d5e9c0f 1004 struct dirent *de;
e73a03e0 1005 int q;
a8d88783 1006
d78096b3
FW
1007 errno = 0;
1008 de = readdir(d);
e73a03e0
LP
1009 if (!de) {
1010 if (errno != 0 && r == 0)
1011 r = -errno;
a8d88783 1012
a8d88783 1013 break;
e73a03e0 1014 }
a8d88783 1015
7fcb4b9b 1016 if (STR_IN_SET(de->d_name, ".", ".."))
a8d88783
MS
1017 continue;
1018
e73a03e0
LP
1019 p = strjoin(path, "/", de->d_name, NULL);
1020 if (!p)
1021 return -ENOMEM;
a8d88783 1022
081043cf 1023 q = action(i, p);
e73a03e0
LP
1024 if (q < 0 && q != -ENOENT && r == 0)
1025 r = q;
a8d88783 1026
e73a03e0 1027 if (IN_SET(de->d_type, DT_UNKNOWN, DT_DIR)) {
081043cf 1028 q = item_do_children(i, p, action);
e73a03e0
LP
1029 if (q < 0 && r == 0)
1030 r = q;
a8d88783 1031 }
a8d88783
MS
1032 }
1033
e73a03e0 1034 return r;
a8d88783
MS
1035}
1036
081043cf 1037static int glob_item(Item *i, action_t action, bool recursive) {
df99a9ef 1038 _cleanup_globfree_ glob_t g = {
ebf31a1f
ZJS
1039 .gl_closedir = (void (*)(void *)) closedir,
1040 .gl_readdir = (struct dirent *(*)(void *)) readdir,
1041 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
df99a9ef
ZJS
1042 .gl_lstat = lstat,
1043 .gl_stat = stat,
1044 };
e73a03e0 1045 int r = 0, k;
99e68c0b
MS
1046 char **fn;
1047
99e68c0b 1048 errno = 0;
df99a9ef 1049 k = glob(i->path, GLOB_NOSORT|GLOB_BRACE|GLOB_ALTDIRFUNC, NULL, &g);
081043cf
ZJS
1050 if (k != 0 && k != GLOB_NOMATCH)
1051 return log_error_errno(errno ?: EIO, "glob(%s) failed: %m", i->path);
99e68c0b 1052
c84a9488
ZJS
1053 STRV_FOREACH(fn, g.gl_pathv) {
1054 k = action(i, *fn);
e73a03e0 1055 if (k < 0 && r == 0)
99e68c0b 1056 r = k;
081043cf
ZJS
1057
1058 if (recursive) {
1059 k = item_do_children(i, *fn, action);
1060 if (k < 0 && r == 0)
1061 r = k;
1062 }
c84a9488 1063 }
99e68c0b 1064
99e68c0b
MS
1065 return r;
1066}
1067
294929f8
ZJS
1068typedef enum {
1069 CREATION_NORMAL,
1070 CREATION_EXISTING,
1071 CREATION_FORCE,
7a7d5db7
LP
1072 _CREATION_MODE_MAX,
1073 _CREATION_MODE_INVALID = -1
294929f8
ZJS
1074} CreationMode;
1075
7a7d5db7
LP
1076static const char *creation_mode_verb_table[_CREATION_MODE_MAX] = {
1077 [CREATION_NORMAL] = "Created",
1078 [CREATION_EXISTING] = "Found existing",
1079 [CREATION_FORCE] = "Created replacement",
1080};
1081
1082DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
294929f8 1083
3b63d2d3 1084static int create_item(Item *i) {
3b63d2d3 1085 struct stat st;
df28bc08 1086 int r = 0;
294929f8 1087 CreationMode creation;
5008d581 1088
3b63d2d3 1089 assert(i);
5008d581 1090
582deb84
ZJS
1091 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
1092
3b63d2d3
LP
1093 switch (i->type) {
1094
1095 case IGNORE_PATH:
78a92a5a 1096 case IGNORE_DIRECTORY_PATH:
3b63d2d3
LP
1097 case REMOVE_PATH:
1098 case RECURSIVE_REMOVE_PATH:
1099 return 0;
5008d581 1100
3b63d2d3 1101 case CREATE_FILE:
31ed59c5 1102 case TRUNCATE_FILE:
1845fdd9
DR
1103 r = write_one_file(i, i->path);
1104 if (r < 0)
1105 return r;
1106 break;
265ffa1e 1107
849958d1 1108 case COPY_FILES:
582deb84 1109 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
e156347e 1110 r = copy_tree(i->argument, i->path, false);
849958d1 1111 if (r < 0) {
e156347e
LP
1112 struct stat a, b;
1113
8d3d7072
MS
1114 if (r != -EEXIST)
1115 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
e156347e 1116
4a62c710
MS
1117 if (stat(i->argument, &a) < 0)
1118 return log_error_errno(errno, "stat(%s) failed: %m", i->argument);
e156347e 1119
4a62c710
MS
1120 if (stat(i->path, &b) < 0)
1121 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
e156347e
LP
1122
1123 if ((a.st_mode ^ b.st_mode) & S_IFMT) {
1124 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1125 return 0;
1126 }
849958d1
LP
1127 }
1128
b705ab6a 1129 r = path_set_perms(i, i->path);
849958d1
LP
1130 if (r < 0)
1131 return r;
1132
1133 break;
1134
d4e9eb91 1135 case WRITE_FILE:
081043cf 1136 r = glob_item(i, write_one_file, false);
f05bc3f7
MS
1137 if (r < 0)
1138 return r;
5008d581 1139
3b63d2d3
LP
1140 break;
1141
3b63d2d3 1142 case CREATE_DIRECTORY:
d7b8eec7
LP
1143 case TRUNCATE_DIRECTORY:
1144 case CREATE_SUBVOLUME:
5008d581 1145
d7b8eec7 1146 RUN_WITH_UMASK(0000)
5c0d398d 1147 mkdir_parents_label(i->path, 0755);
d7b8eec7 1148
582deb84
ZJS
1149 if (i->type == CREATE_SUBVOLUME)
1150 RUN_WITH_UMASK((~i->mode) & 0777) {
d7b8eec7 1151 r = btrfs_subvol_make(i->path);
582deb84
ZJS
1152 log_debug_errno(r, "Creating subvolume \"%s\": %m", i->path);
1153 }
1154 else
d7b8eec7
LP
1155 r = 0;
1156
582deb84 1157 if (IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY) || r == -ENOTTY)
d7b8eec7
LP
1158 RUN_WITH_UMASK(0000)
1159 r = mkdir_label(i->path, i->mode);
5008d581 1160
e156347e 1161 if (r < 0) {
f647962d 1162 if (r != -EEXIST)
582deb84 1163 return log_error_errno(r, "Failed to create directory or subvolume \"%s\": %m", i->path);
5008d581 1164
4a62c710
MS
1165 if (stat(i->path, &st) < 0)
1166 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
5008d581 1167
e156347e 1168 if (!S_ISDIR(st.st_mode)) {
582deb84 1169 log_debug("\"%s\" already exists and is not a directory.", i->path);
e156347e
LP
1170 return 0;
1171 }
294929f8
ZJS
1172
1173 creation = CREATION_EXISTING;
1174 } else
1175 creation = CREATION_NORMAL;
7a7d5db7 1176 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), i->path);
5008d581 1177
b705ab6a 1178 r = path_set_perms(i, i->path);
f05bc3f7
MS
1179 if (r < 0)
1180 return r;
3b63d2d3
LP
1181
1182 break;
ee17ee7c
LP
1183
1184 case CREATE_FIFO:
1185
5c0d398d 1186 RUN_WITH_UMASK(0000) {
ecabcf8b 1187 mac_selinux_create_file_prepare(i->path, S_IFIFO);
5c0d398d 1188 r = mkfifo(i->path, i->mode);
ecabcf8b 1189 mac_selinux_create_file_clear();
5c0d398d 1190 }
ee17ee7c 1191
1554afae 1192 if (r < 0) {
4a62c710
MS
1193 if (errno != EEXIST)
1194 return log_error_errno(errno, "Failed to create fifo %s: %m", i->path);
ee17ee7c 1195
4a62c710
MS
1196 if (stat(i->path, &st) < 0)
1197 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
ee17ee7c 1198
1554afae
LP
1199 if (!S_ISFIFO(st.st_mode)) {
1200
1201 if (i->force) {
1202
1203 RUN_WITH_UMASK(0000) {
ecabcf8b 1204 mac_selinux_create_file_prepare(i->path, S_IFIFO);
1554afae 1205 r = mkfifo_atomic(i->path, i->mode);
ecabcf8b 1206 mac_selinux_create_file_clear();
1554afae
LP
1207 }
1208
f647962d
MS
1209 if (r < 0)
1210 return log_error_errno(r, "Failed to create fifo %s: %m", i->path);
294929f8 1211 creation = CREATION_FORCE;
1554afae
LP
1212 } else {
1213 log_debug("%s is not a fifo.", i->path);
1214 return 0;
1215 }
294929f8
ZJS
1216 } else
1217 creation = CREATION_EXISTING;
1218 } else
1219 creation = CREATION_NORMAL;
7a7d5db7 1220 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
ee17ee7c 1221
b705ab6a 1222 r = path_set_perms(i, i->path);
f05bc3f7
MS
1223 if (r < 0)
1224 return r;
ee17ee7c
LP
1225
1226 break;
a8d88783 1227
2e78fa79 1228 case CREATE_SYMLINK:
468d726b 1229
ecabcf8b 1230 mac_selinux_create_file_prepare(i->path, S_IFLNK);
468d726b 1231 r = symlink(i->argument, i->path);
ecabcf8b 1232 mac_selinux_create_file_clear();
e9a5ef7c 1233
468d726b 1234 if (r < 0) {
2e78fa79 1235 _cleanup_free_ char *x = NULL;
468d726b 1236
4a62c710
MS
1237 if (errno != EEXIST)
1238 return log_error_errno(errno, "symlink(%s, %s) failed: %m", i->argument, i->path);
2e78fa79
LP
1239
1240 r = readlink_malloc(i->path, &x);
1241 if (r < 0 || !streq(i->argument, x)) {
1242
1243 if (i->force) {
ecabcf8b 1244 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2e78fa79 1245 r = symlink_atomic(i->argument, i->path);
ecabcf8b 1246 mac_selinux_create_file_clear();
2e78fa79 1247
f647962d
MS
1248 if (r < 0)
1249 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
294929f8 1250 creation = CREATION_FORCE;
1554afae 1251 } else {
582deb84 1252 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
1554afae
LP
1253 return 0;
1254 }
294929f8
ZJS
1255 } else
1256 creation = CREATION_EXISTING;
1257 } else
1258 creation = CREATION_NORMAL;
7a7d5db7 1259 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
468d726b 1260
468d726b 1261 break;
468d726b
LP
1262
1263 case CREATE_BLOCK_DEVICE:
1264 case CREATE_CHAR_DEVICE: {
cb7ed9df
LP
1265 mode_t file_type;
1266
1267 if (have_effective_cap(CAP_MKNOD) == 0) {
1268 /* In a container we lack CAP_MKNOD. We
ab06eef8 1269 shouldn't attempt to create the device node in
cb7ed9df
LP
1270 that case to avoid noise, and we don't support
1271 virtualized devices in containers anyway. */
1272
1273 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
1274 return 0;
1275 }
1276
1554afae 1277 file_type = i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR;
468d726b 1278
5c0d398d 1279 RUN_WITH_UMASK(0000) {
ecabcf8b 1280 mac_selinux_create_file_prepare(i->path, file_type);
5c0d398d 1281 r = mknod(i->path, i->mode | file_type, i->major_minor);
ecabcf8b 1282 mac_selinux_create_file_clear();
5c0d398d 1283 }
468d726b 1284
6555ad8e
KS
1285 if (r < 0) {
1286 if (errno == EPERM) {
1287 log_debug("We lack permissions, possibly because of cgroup configuration; "
1288 "skipping creation of device node %s.", i->path);
1289 return 0;
1290 }
1291
4a62c710
MS
1292 if (errno != EEXIST)
1293 return log_error_errno(errno, "Failed to create device node %s: %m", i->path);
468d726b 1294
4a62c710
MS
1295 if (stat(i->path, &st) < 0)
1296 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
468d726b 1297
1554afae
LP
1298 if ((st.st_mode & S_IFMT) != file_type) {
1299
1300 if (i->force) {
1301
1302 RUN_WITH_UMASK(0000) {
ecabcf8b 1303 mac_selinux_create_file_prepare(i->path, file_type);
1554afae 1304 r = mknod_atomic(i->path, i->mode | file_type, i->major_minor);
ecabcf8b 1305 mac_selinux_create_file_clear();
1554afae
LP
1306 }
1307
f647962d 1308 if (r < 0)
294929f8
ZJS
1309 return log_error_errno(r, "Failed to create device node \"%s\": %m", i->path);
1310 creation = CREATION_FORCE;
1554afae
LP
1311 } else {
1312 log_debug("%s is not a device node.", i->path);
1313 return 0;
1314 }
294929f8
ZJS
1315 } else
1316 creation = CREATION_EXISTING;
1317 } else
1318 creation = CREATION_NORMAL;
1319 log_debug("%s %s device node \"%s\" %u:%u.",
7a7d5db7 1320 creation_mode_verb_to_string(creation),
582deb84
ZJS
1321 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1322 i->path, major(i->mode), minor(i->mode));
468d726b 1323
b705ab6a 1324 r = path_set_perms(i, i->path);
468d726b
LP
1325 if (r < 0)
1326 return r;
1327
1328 break;
1329 }
1330
e73a03e0 1331 case ADJUST_MODE:
777b87e7 1332 case RELABEL_PATH:
b705ab6a 1333 r = glob_item(i, path_set_perms, false);
777b87e7 1334 if (r < 0)
96ca8194 1335 return r;
777b87e7
MS
1336 break;
1337
a8d88783 1338 case RECURSIVE_RELABEL_PATH:
b705ab6a 1339 r = glob_item(i, path_set_perms, true);
a8d88783
MS
1340 if (r < 0)
1341 return r;
ebf4e801 1342 break;
e73a03e0 1343
ebf4e801 1344 case SET_XATTR:
b705ab6a
ZJS
1345 r = glob_item(i, path_set_xattrs, false);
1346 if (r < 0)
1347 return r;
1348 break;
1349
1350 case RECURSIVE_SET_XATTR:
1351 r = glob_item(i, path_set_xattrs, true);
ebf4e801
MW
1352 if (r < 0)
1353 return r;
e73a03e0 1354 break;
f8eeeaf9
ZJS
1355
1356 case SET_ACL:
b705ab6a 1357 r = glob_item(i, path_set_acls, false);
f8eeeaf9
ZJS
1358 if (r < 0)
1359 return r;
b705ab6a
ZJS
1360 break;
1361
1362 case RECURSIVE_SET_ACL:
1363 r = glob_item(i, path_set_acls, true);
1364 if (r < 0)
1365 return r;
1366 break;
22c3a6ca 1367
88ec4dfa
LP
1368 case SET_ATTRIBUTE:
1369 r = glob_item(i, path_set_attribute, false);
22c3a6ca
GB
1370 if (r < 0)
1371 return r;
1372 break;
1373
88ec4dfa
LP
1374 case RECURSIVE_SET_ATTRIBUTE:
1375 r = glob_item(i, path_set_attribute, true);
22c3a6ca
GB
1376 if (r < 0)
1377 return r;
1378 break;
3b63d2d3
LP
1379 }
1380
f05bc3f7 1381 return 0;
3b63d2d3
LP
1382}
1383
a0896123 1384static int remove_item_instance(Item *i, const char *instance) {
3b63d2d3
LP
1385 int r;
1386
1387 assert(i);
1388
1389 switch (i->type) {
1390
3b63d2d3 1391 case REMOVE_PATH:
4a62c710 1392 if (remove(instance) < 0 && errno != ENOENT)
3f93da98 1393 return log_error_errno(errno, "rm(%s): %m", instance);
3b63d2d3
LP
1394
1395 break;
1396
1397 case TRUNCATE_DIRECTORY:
1398 case RECURSIVE_REMOVE_PATH:
d139b24a
LP
1399 /* FIXME: we probably should use dir_cleanup() here
1400 * instead of rm_rf() so that 'x' is honoured. */
582deb84 1401 log_debug("rm -rf \"%s\"", instance);
c6878637 1402 r = rm_rf(instance, (i->type == RECURSIVE_REMOVE_PATH ? REMOVE_ROOT : 0) | REMOVE_PHYSICAL);
f647962d
MS
1403 if (r < 0 && r != -ENOENT)
1404 return log_error_errno(r, "rm_rf(%s): %m", instance);
3b63d2d3
LP
1405
1406 break;
7fcb4b9b
ZJS
1407
1408 default:
1409 assert_not_reached("wut?");
3b63d2d3
LP
1410 }
1411
1412 return 0;
1413}
1414
a0896123 1415static int remove_item(Item *i) {
99e68c0b
MS
1416 int r = 0;
1417
b8bb3e8f
LP
1418 assert(i);
1419
582deb84
ZJS
1420 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
1421
b8bb3e8f
LP
1422 switch (i->type) {
1423
1424 case CREATE_FILE:
1425 case TRUNCATE_FILE:
1426 case CREATE_DIRECTORY:
d7b8eec7 1427 case CREATE_SUBVOLUME:
ee17ee7c 1428 case CREATE_FIFO:
468d726b
LP
1429 case CREATE_SYMLINK:
1430 case CREATE_CHAR_DEVICE:
1431 case CREATE_BLOCK_DEVICE:
b8bb3e8f 1432 case IGNORE_PATH:
78a92a5a 1433 case IGNORE_DIRECTORY_PATH:
e73a03e0 1434 case ADJUST_MODE:
777b87e7 1435 case RELABEL_PATH:
a8d88783 1436 case RECURSIVE_RELABEL_PATH:
31ed59c5 1437 case WRITE_FILE:
849958d1 1438 case COPY_FILES:
ebf4e801 1439 case SET_XATTR:
b705ab6a 1440 case RECURSIVE_SET_XATTR:
f8eeeaf9 1441 case SET_ACL:
b705ab6a 1442 case RECURSIVE_SET_ACL:
88ec4dfa
LP
1443 case SET_ATTRIBUTE:
1444 case RECURSIVE_SET_ATTRIBUTE:
b8bb3e8f
LP
1445 break;
1446
1447 case REMOVE_PATH:
1448 case TRUNCATE_DIRECTORY:
99e68c0b 1449 case RECURSIVE_REMOVE_PATH:
081043cf 1450 r = glob_item(i, remove_item_instance, false);
99e68c0b 1451 break;
b8bb3e8f
LP
1452 }
1453
99e68c0b 1454 return r;
b8bb3e8f
LP
1455}
1456
78a92a5a 1457static int clean_item_instance(Item *i, const char* instance) {
7fd1b19b 1458 _cleanup_closedir_ DIR *d = NULL;
78a92a5a
MS
1459 struct stat s, ps;
1460 bool mountpoint;
78a92a5a 1461 usec_t cutoff, n;
582deb84 1462 char timestamp[FORMAT_TIMESTAMP_MAX];
78a92a5a
MS
1463
1464 assert(i);
1465
1466 if (!i->age_set)
1467 return 0;
1468
1469 n = now(CLOCK_REALTIME);
1470 if (n < i->age)
1471 return 0;
1472
1473 cutoff = n - i->age;
1474
df99a9ef 1475 d = opendir_nomod(instance);
78a92a5a 1476 if (!d) {
582deb84
ZJS
1477 if (errno == ENOENT || errno == ENOTDIR) {
1478 log_debug_errno(errno, "Directory \"%s\": %m", instance);
78a92a5a 1479 return 0;
582deb84 1480 }
78a92a5a 1481
582deb84 1482 log_error_errno(errno, "Failed to open directory %s: %m", instance);
78a92a5a
MS
1483 return -errno;
1484 }
1485
4a62c710
MS
1486 if (fstat(dirfd(d), &s) < 0)
1487 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
78a92a5a
MS
1488
1489 if (!S_ISDIR(s.st_mode)) {
1490 log_error("%s is not a directory.", i->path);
19fbec19 1491 return -ENOTDIR;
78a92a5a
MS
1492 }
1493
4a62c710
MS
1494 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
1495 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
78a92a5a
MS
1496
1497 mountpoint = s.st_dev != ps.st_dev ||
1498 (s.st_dev == ps.st_dev && s.st_ino == ps.st_ino);
1499
582deb84
ZJS
1500 log_debug("Cleanup threshold for %s \"%s\" is %s",
1501 mountpoint ? "mount point" : "directory",
1502 instance,
1503 format_timestamp_us(timestamp, sizeof(timestamp), cutoff));
1504
1505 return dir_cleanup(i, instance, d, &s, cutoff, s.st_dev, mountpoint,
1506 MAX_DEPTH, i->keep_first_level);
78a92a5a
MS
1507}
1508
1509static int clean_item(Item *i) {
1510 int r = 0;
1511
1512 assert(i);
1513
582deb84
ZJS
1514 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
1515
78a92a5a
MS
1516 switch (i->type) {
1517 case CREATE_DIRECTORY:
d7b8eec7 1518 case CREATE_SUBVOLUME:
78a92a5a
MS
1519 case TRUNCATE_DIRECTORY:
1520 case IGNORE_PATH:
849958d1 1521 case COPY_FILES:
78a92a5a
MS
1522 clean_item_instance(i, i->path);
1523 break;
1524 case IGNORE_DIRECTORY_PATH:
081043cf 1525 r = glob_item(i, clean_item_instance, false);
78a92a5a
MS
1526 break;
1527 default:
1528 break;
1529 }
1530
1531 return r;
1532}
1533
3f93da98
ZJS
1534static int process_item_array(ItemArray *array);
1535
3b63d2d3 1536static int process_item(Item *i) {
1e95893a 1537 int r, q, p, t = 0;
9348f0e6 1538 _cleanup_free_ char *prefix = NULL;
3b63d2d3
LP
1539
1540 assert(i);
1541
1910cd0e
LP
1542 if (i->done)
1543 return 0;
1544
1545 i->done = true;
1546
9348f0e6
ZJS
1547 prefix = malloc(strlen(i->path) + 1);
1548 if (!prefix)
1549 return log_oom();
1550
1910cd0e 1551 PATH_FOREACH_PREFIX(prefix, i->path) {
3f93da98 1552 ItemArray *j;
1910cd0e
LP
1553
1554 j = hashmap_get(items, prefix);
1db50423
ZJS
1555 if (j) {
1556 int s;
1557
3f93da98 1558 s = process_item_array(j);
1db50423
ZJS
1559 if (s < 0 && t == 0)
1560 t = s;
1561 }
1910cd0e
LP
1562 }
1563
3b63d2d3 1564 r = arg_create ? create_item(i) : 0;
a0896123 1565 q = arg_remove ? remove_item(i) : 0;
3b63d2d3
LP
1566 p = arg_clean ? clean_item(i) : 0;
1567
1db50423
ZJS
1568 return t < 0 ? t :
1569 r < 0 ? r :
1570 q < 0 ? q :
1571 p;
3b63d2d3
LP
1572}
1573
3f93da98
ZJS
1574static int process_item_array(ItemArray *array) {
1575 unsigned n;
1576 int r = 0, k;
753615e8 1577
3f93da98
ZJS
1578 assert(array);
1579
1580 for (n = 0; n < array->count; n++) {
1581 k = process_item(array->items + n);
1582 if (k < 0 && r == 0)
1583 r = k;
1584 }
1585
1586 return r;
1587}
3b63d2d3 1588
3f93da98
ZJS
1589static void item_free_contents(Item *i) {
1590 assert(i);
3b63d2d3 1591 free(i->path);
468d726b 1592 free(i->argument);
ebf4e801 1593 strv_free(i->xattrs);
f8eeeaf9
ZJS
1594
1595#ifdef HAVE_ACL
1596 acl_free(i->acl_access);
1597 acl_free(i->acl_default);
1598#endif
3b63d2d3
LP
1599}
1600
3f93da98
ZJS
1601static void item_array_free(ItemArray *a) {
1602 unsigned n;
1603
1604 if (!a)
1605 return;
1606
1607 for (n = 0; n < a->count; n++)
1608 item_free_contents(a->items + n);
1609 free(a->items);
1610 free(a);
1611}
e2f2fb78 1612
3f93da98 1613static bool item_compatible(Item *a, Item *b) {
bfe95f35
LP
1614 assert(a);
1615 assert(b);
3f93da98 1616 assert(streq(a->path, b->path));
bfe95f35 1617
3f93da98
ZJS
1618 if (takes_ownership(a->type) && takes_ownership(b->type))
1619 /* check if the items are the same */
1620 return streq_ptr(a->argument, b->argument) &&
bfe95f35 1621
3f93da98
ZJS
1622 a->uid_set == b->uid_set &&
1623 a->uid == b->uid &&
bfe95f35 1624
3f93da98
ZJS
1625 a->gid_set == b->gid_set &&
1626 a->gid == b->gid &&
bfe95f35 1627
3f93da98
ZJS
1628 a->mode_set == b->mode_set &&
1629 a->mode == b->mode &&
bfe95f35 1630
3f93da98
ZJS
1631 a->age_set == b->age_set &&
1632 a->age == b->age &&
bfe95f35 1633
3f93da98 1634 a->mask_perms == b->mask_perms &&
bfe95f35 1635
3f93da98 1636 a->keep_first_level == b->keep_first_level &&
468d726b 1637
3f93da98 1638 a->major_minor == b->major_minor;
468d726b 1639
bfe95f35
LP
1640 return true;
1641}
1642
a2aced4a
DR
1643static bool should_include_path(const char *path) {
1644 char **prefix;
1645
abef3f91 1646 STRV_FOREACH(prefix, arg_exclude_prefixes)
582deb84
ZJS
1647 if (path_startswith(path, *prefix)) {
1648 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
1649 path, *prefix);
5c795114 1650 return false;
582deb84 1651 }
a2aced4a 1652
abef3f91 1653 STRV_FOREACH(prefix, arg_include_prefixes)
582deb84
ZJS
1654 if (path_startswith(path, *prefix)) {
1655 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
a2aced4a 1656 return true;
582deb84 1657 }
a2aced4a 1658
5c795114
DR
1659 /* no matches, so we should include this path only if we
1660 * have no whitelist at all */
582deb84
ZJS
1661 if (strv_length(arg_include_prefixes) == 0)
1662 return true;
1663
1664 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
1665 return false;
a2aced4a
DR
1666}
1667
fba6e687 1668static int parse_line(const char *fname, unsigned line, const char *buffer) {
1731e34a 1669
cde684a2 1670 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
3f93da98
ZJS
1671 _cleanup_(item_free_contents) Item i = {};
1672 ItemArray *existing;
bfe95f35 1673 Hashmap *h;
657cf7f4 1674 int r, pos;
5f255144 1675 bool force = false, boot = false;
3b63d2d3
LP
1676
1677 assert(fname);
1678 assert(line >= 1);
1679 assert(buffer);
1680
4034a06d
LP
1681 r = unquote_many_words(
1682 &buffer,
1683 0,
1684 &action,
1685 &path,
1686 &mode,
1687 &user,
1688 &group,
1689 &age,
1690 NULL);
657cf7f4 1691 if (r < 0)
1692 return log_error_errno(r, "[%s:%u] Failed to parse line: %m", fname, line);
1693 else if (r < 2) {
3b63d2d3 1694 log_error("[%s:%u] Syntax error.", fname, line);
7f2c1f4d 1695 return -EIO;
5008d581
LP
1696 }
1697
4034a06d
LP
1698 if (!isempty(buffer)) {
1699 i.argument = strdup(buffer);
1700 if (!i.argument)
1701 return log_oom();
1702 }
1703
2e78fa79
LP
1704 if (isempty(action)) {
1705 log_error("[%s:%u] Command too short '%s'.", fname, line, action);
c4708f13 1706 return -EINVAL;
2e78fa79
LP
1707 }
1708
5f255144
ZJS
1709 for (pos = 1; action[pos]; pos++) {
1710 if (action[pos] == '!' && !boot)
1711 boot = true;
1712 else if (action[pos] == '+' && !force)
1713 force = true;
1714 else {
1715 log_error("[%s:%u] Unknown modifiers in command '%s'",
1716 fname, line, action);
1717 return -EINVAL;
1718 }
2e78fa79
LP
1719 }
1720
582deb84
ZJS
1721 if (boot && !arg_boot) {
1722 log_debug("Ignoring entry %s \"%s\" because --boot is not specified.",
1723 action, path);
c4708f13 1724 return 0;
582deb84 1725 }
c4708f13 1726
3f93da98
ZJS
1727 i.type = action[0];
1728 i.force = force;
2e78fa79 1729
3f93da98 1730 r = specifier_printf(path, specifier_table, NULL, &i.path);
1731e34a
LP
1731 if (r < 0) {
1732 log_error("[%s:%u] Failed to replace specifiers: %s", fname, line, path);
1733 return r;
1734 }
1735
3f93da98 1736 switch (i.type) {
468d726b 1737
777b87e7 1738 case CREATE_DIRECTORY:
d7b8eec7 1739 case CREATE_SUBVOLUME:
777b87e7
MS
1740 case TRUNCATE_DIRECTORY:
1741 case CREATE_FIFO:
1742 case IGNORE_PATH:
78a92a5a 1743 case IGNORE_DIRECTORY_PATH:
777b87e7
MS
1744 case REMOVE_PATH:
1745 case RECURSIVE_REMOVE_PATH:
e73a03e0 1746 case ADJUST_MODE:
777b87e7
MS
1747 case RELABEL_PATH:
1748 case RECURSIVE_RELABEL_PATH:
c82500c6 1749 if (i.argument)
bd550f78 1750 log_warning("[%s:%u] %c lines don't take argument fields, ignoring.", fname, line, i.type);
c82500c6
LP
1751
1752 break;
1753
1754 case CREATE_FILE:
1755 case TRUNCATE_FILE:
777b87e7 1756 break;
468d726b
LP
1757
1758 case CREATE_SYMLINK:
3f93da98
ZJS
1759 if (!i.argument) {
1760 i.argument = strappend("/usr/share/factory/", i.path);
1761 if (!i.argument)
2f3b873a 1762 return log_oom();
468d726b
LP
1763 }
1764 break;
1765
31ed59c5 1766 case WRITE_FILE:
3f93da98 1767 if (!i.argument) {
31ed59c5 1768 log_error("[%s:%u] Write file requires argument.", fname, line);
7f2c1f4d 1769 return -EBADMSG;
31ed59c5
LP
1770 }
1771 break;
1772
849958d1 1773 case COPY_FILES:
3f93da98
ZJS
1774 if (!i.argument) {
1775 i.argument = strappend("/usr/share/factory/", i.path);
1776 if (!i.argument)
2f3b873a 1777 return log_oom();
3f93da98 1778 } else if (!path_is_absolute(i.argument)) {
849958d1
LP
1779 log_error("[%s:%u] Source path is not absolute.", fname, line);
1780 return -EBADMSG;
1781 }
1782
3f93da98 1783 path_kill_slashes(i.argument);
849958d1
LP
1784 break;
1785
468d726b
LP
1786 case CREATE_CHAR_DEVICE:
1787 case CREATE_BLOCK_DEVICE: {
1788 unsigned major, minor;
1789
3f93da98 1790 if (!i.argument) {
468d726b 1791 log_error("[%s:%u] Device file requires argument.", fname, line);
7f2c1f4d 1792 return -EBADMSG;
468d726b
LP
1793 }
1794
3f93da98
ZJS
1795 if (sscanf(i.argument, "%u:%u", &major, &minor) != 2) {
1796 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i.argument);
7f2c1f4d 1797 return -EBADMSG;
468d726b
LP
1798 }
1799
3f93da98 1800 i.major_minor = makedev(major, minor);
468d726b
LP
1801 break;
1802 }
1803
ebf4e801 1804 case SET_XATTR:
b705ab6a 1805 case RECURSIVE_SET_XATTR:
3f93da98 1806 if (!i.argument) {
ebf4e801
MW
1807 log_error("[%s:%u] Set extended attribute requires argument.", fname, line);
1808 return -EBADMSG;
1809 }
bd550f78 1810 r = parse_xattrs_from_arg(&i);
ebf4e801
MW
1811 if (r < 0)
1812 return r;
1813 break;
1814
f8eeeaf9 1815 case SET_ACL:
b705ab6a 1816 case RECURSIVE_SET_ACL:
f8eeeaf9
ZJS
1817 if (!i.argument) {
1818 log_error("[%s:%u] Set ACLs requires argument.", fname, line);
1819 return -EBADMSG;
1820 }
bd550f78 1821 r = parse_acls_from_arg(&i);
f8eeeaf9
ZJS
1822 if (r < 0)
1823 return r;
1824 break;
1825
88ec4dfa
LP
1826 case SET_ATTRIBUTE:
1827 case RECURSIVE_SET_ATTRIBUTE:
22c3a6ca 1828 if (!i.argument) {
88ec4dfa 1829 log_error("[%s:%u] Set file attribute requires argument.", fname, line);
22c3a6ca
GB
1830 return -EBADMSG;
1831 }
bd550f78 1832 r = parse_attribute_from_arg(&i);
22c3a6ca
GB
1833 if (r < 0)
1834 return r;
1835 break;
1836
777b87e7 1837 default:
582deb84 1838 log_error("[%s:%u] Unknown command type '%c'.", fname, line, (char) i.type);
7f2c1f4d 1839 return -EBADMSG;
3b63d2d3 1840 }
468d726b 1841
3f93da98
ZJS
1842 if (!path_is_absolute(i.path)) {
1843 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i.path);
7f2c1f4d 1844 return -EBADMSG;
3b63d2d3
LP
1845 }
1846
3f93da98 1847 path_kill_slashes(i.path);
3b63d2d3 1848
3f93da98 1849 if (!should_include_path(i.path))
7f2c1f4d 1850 return 0;
5008d581 1851
cf9a4abd 1852 if (arg_root) {
cde684a2
LP
1853 char *p;
1854
3f93da98 1855 p = strappend(arg_root, i.path);
cf9a4abd
MM
1856 if (!p)
1857 return log_oom();
1858
3f93da98
ZJS
1859 free(i.path);
1860 i.path = p;
cf9a4abd
MM
1861 }
1862
90937fe3 1863 if (!isempty(user) && !streq(user, "-")) {
4b67834e
LP
1864 const char *u = user;
1865
3f93da98 1866 r = get_user_creds(&u, &i.uid, NULL, NULL, NULL);
4b67834e 1867 if (r < 0) {
3b63d2d3 1868 log_error("[%s:%u] Unknown user '%s'.", fname, line, user);
7f2c1f4d 1869 return r;
3b63d2d3
LP
1870 }
1871
3f93da98 1872 i.uid_set = true;
3b63d2d3
LP
1873 }
1874
90937fe3 1875 if (!isempty(group) && !streq(group, "-")) {
4b67834e
LP
1876 const char *g = group;
1877
3f93da98 1878 r = get_group_creds(&g, &i.gid);
4b67834e 1879 if (r < 0) {
3b63d2d3 1880 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
7f2c1f4d 1881 return r;
3b63d2d3
LP
1882 }
1883
3f93da98 1884 i.gid_set = true;
3b63d2d3
LP
1885 }
1886
90937fe3 1887 if (!isempty(mode) && !streq(mode, "-")) {
abef3f91 1888 const char *mm = mode;
3b63d2d3
LP
1889 unsigned m;
1890
abef3f91 1891 if (*mm == '~') {
3f93da98 1892 i.mask_perms = true;
abef3f91
LP
1893 mm++;
1894 }
1895
2ff7b0a5 1896 if (parse_mode(mm, &m) < 0) {
3b63d2d3 1897 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
2ff7b0a5 1898 return -EBADMSG;
3b63d2d3
LP
1899 }
1900
3f93da98
ZJS
1901 i.mode = m;
1902 i.mode_set = true;
3b63d2d3 1903 } else
3f93da98
ZJS
1904 i.mode = IN_SET(i.type, CREATE_DIRECTORY, CREATE_SUBVOLUME, TRUNCATE_DIRECTORY)
1905 ? 0755 : 0644;
3b63d2d3 1906
90937fe3 1907 if (!isempty(age) && !streq(age, "-")) {
24f3a374
LP
1908 const char *a = age;
1909
1910 if (*a == '~') {
3f93da98 1911 i.keep_first_level = true;
24f3a374
LP
1912 a++;
1913 }
1914
3f93da98 1915 if (parse_sec(a, &i.age) < 0) {
3b63d2d3 1916 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
7f2c1f4d 1917 return -EBADMSG;
3b63d2d3
LP
1918 }
1919
3f93da98 1920 i.age_set = true;
3b63d2d3
LP
1921 }
1922
3f93da98 1923 h = needs_glob(i.type) ? globs : items;
bfe95f35 1924
3f93da98 1925 existing = hashmap_get(h, i.path);
468d726b 1926 if (existing) {
3f93da98
ZJS
1927 unsigned n;
1928
1929 for (n = 0; n < existing->count; n++) {
6487ada8 1930 if (!item_compatible(existing->items + n, &i)) {
505ef0e3 1931 log_warning("[%s:%u] Duplicate line for path \"%s\", ignoring.",
3f93da98 1932 fname, line, i.path);
6487ada8
MP
1933 return 0;
1934 }
ebf4e801
MW
1935 }
1936 } else {
3f93da98
ZJS
1937 existing = new0(ItemArray, 1);
1938 r = hashmap_put(h, i.path, existing);
1939 if (r < 0)
1940 return log_oom();
bfe95f35
LP
1941 }
1942
3f93da98
ZJS
1943 if (!GREEDY_REALLOC(existing->items, existing->size, existing->count + 1))
1944 return log_oom();
5008d581 1945
3f93da98
ZJS
1946 memcpy(existing->items + existing->count++, &i, sizeof(i));
1947 zero(i);
7f2c1f4d 1948 return 0;
5008d581
LP
1949}
1950
601185b4 1951static void help(void) {
522d4a49
LP
1952 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1953 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
5c795114 1954 " -h --help Show this help\n"
eb9da376 1955 " --version Show package version\n"
5c795114
DR
1956 " --create Create marked files/directories\n"
1957 " --clean Clean up marked directories\n"
1958 " --remove Remove marked files/directories\n"
81815651 1959 " --boot Execute actions only safe at boot\n"
79ca888f
ZJS
1960 " --prefix=PATH Only apply rules with the specified prefix\n"
1961 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
cf9a4abd 1962 " --root=PATH Operate on an alternate filesystem root\n",
3b63d2d3 1963 program_invocation_short_name);
3b63d2d3
LP
1964}
1965
1966static int parse_argv(int argc, char *argv[]) {
1967
1968 enum {
eb9da376 1969 ARG_VERSION = 0x100,
3b63d2d3
LP
1970 ARG_CREATE,
1971 ARG_CLEAN,
fba6e687 1972 ARG_REMOVE,
81815651 1973 ARG_BOOT,
5c795114
DR
1974 ARG_PREFIX,
1975 ARG_EXCLUDE_PREFIX,
cf9a4abd 1976 ARG_ROOT,
3b63d2d3
LP
1977 };
1978
1979 static const struct option options[] = {
5c795114 1980 { "help", no_argument, NULL, 'h' },
eb9da376 1981 { "version", no_argument, NULL, ARG_VERSION },
5c795114
DR
1982 { "create", no_argument, NULL, ARG_CREATE },
1983 { "clean", no_argument, NULL, ARG_CLEAN },
1984 { "remove", no_argument, NULL, ARG_REMOVE },
81815651 1985 { "boot", no_argument, NULL, ARG_BOOT },
5c795114
DR
1986 { "prefix", required_argument, NULL, ARG_PREFIX },
1987 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
cf9a4abd 1988 { "root", required_argument, NULL, ARG_ROOT },
eb9da376 1989 {}
3b63d2d3
LP
1990 };
1991
1992 int c;
1993
1994 assert(argc >= 0);
1995 assert(argv);
1996
601185b4 1997 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
3b63d2d3
LP
1998
1999 switch (c) {
2000
2001 case 'h':
601185b4
ZJS
2002 help();
2003 return 0;
eb9da376
LP
2004
2005 case ARG_VERSION:
2006 puts(PACKAGE_STRING);
2007 puts(SYSTEMD_FEATURES);
3b63d2d3
LP
2008 return 0;
2009
2010 case ARG_CREATE:
2011 arg_create = true;
2012 break;
2013
2014 case ARG_CLEAN:
2015 arg_clean = true;
2016 break;
2017
2018 case ARG_REMOVE:
2019 arg_remove = true;
2020 break;
2021
81815651
ZJS
2022 case ARG_BOOT:
2023 arg_boot = true;
c4708f13
ZJS
2024 break;
2025
fba6e687 2026 case ARG_PREFIX:
7bc040fa 2027 if (strv_push(&arg_include_prefixes, optarg) < 0)
a2aced4a 2028 return log_oom();
fba6e687
LP
2029 break;
2030
5c795114 2031 case ARG_EXCLUDE_PREFIX:
7bc040fa 2032 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
5c795114
DR
2033 return log_oom();
2034 break;
2035
cf9a4abd 2036 case ARG_ROOT:
753615e8 2037 free(arg_root);
cf9a4abd
MM
2038 arg_root = path_make_absolute_cwd(optarg);
2039 if (!arg_root)
2040 return log_oom();
753615e8 2041
cf9a4abd
MM
2042 path_kill_slashes(arg_root);
2043 break;
2044
3b63d2d3
LP
2045 case '?':
2046 return -EINVAL;
2047
2048 default:
eb9da376 2049 assert_not_reached("Unhandled option");
3b63d2d3 2050 }
3b63d2d3
LP
2051
2052 if (!arg_clean && !arg_create && !arg_remove) {
35b8ca3a 2053 log_error("You need to specify at least one of --clean, --create or --remove.");
3b63d2d3
LP
2054 return -EINVAL;
2055 }
2056
2057 return 1;
2058}
2059
fba6e687 2060static int read_config_file(const char *fn, bool ignore_enoent) {
1731e34a
LP
2061 _cleanup_fclose_ FILE *f = NULL;
2062 char line[LINE_MAX];
78a92a5a 2063 Iterator iterator;
1731e34a 2064 unsigned v = 0;
78a92a5a 2065 Item *i;
1731e34a 2066 int r;
fba6e687
LP
2067
2068 assert(fn);
2069
cf9a4abd 2070 r = search_and_fopen_nulstr(fn, "re", arg_root, conf_file_dirs, &f);
fabe5c0e 2071 if (r < 0) {
582deb84
ZJS
2072 if (ignore_enoent && r == -ENOENT) {
2073 log_debug_errno(r, "Failed to open \"%s\": %m", fn);
fba6e687 2074 return 0;
582deb84 2075 }
fba6e687 2076
8d3d7072 2077 return log_error_errno(r, "Failed to open '%s', ignoring: %m", fn);
fba6e687 2078 }
582deb84 2079 log_debug("Reading config file \"%s\".", fn);
fba6e687 2080
1731e34a
LP
2081 FOREACH_LINE(line, f, break) {
2082 char *l;
fba6e687
LP
2083 int k;
2084
fba6e687
LP
2085 v++;
2086
2087 l = strstrip(line);
2088 if (*l == '#' || *l == 0)
2089 continue;
2090
1731e34a
LP
2091 k = parse_line(fn, v, l);
2092 if (k < 0 && r == 0)
2093 r = k;
fba6e687
LP
2094 }
2095
78a92a5a
MS
2096 /* we have to determine age parameter for each entry of type X */
2097 HASHMAP_FOREACH(i, globs, iterator) {
2098 Iterator iter;
2099 Item *j, *candidate_item = NULL;
2100
2101 if (i->type != IGNORE_DIRECTORY_PATH)
2102 continue;
2103
2104 HASHMAP_FOREACH(j, items, iter) {
d7b8eec7 2105 if (j->type != CREATE_DIRECTORY && j->type != TRUNCATE_DIRECTORY && j->type != CREATE_SUBVOLUME)
78a92a5a
MS
2106 continue;
2107
2108 if (path_equal(j->path, i->path)) {
2109 candidate_item = j;
2110 break;
2111 }
2112
2113 if ((!candidate_item && path_startswith(i->path, j->path)) ||
2114 (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
2115 candidate_item = j;
2116 }
2117
9ed2a35e 2118 if (candidate_item && candidate_item->age_set) {
78a92a5a
MS
2119 i->age = candidate_item->age;
2120 i->age_set = true;
2121 }
2122 }
2123
fba6e687 2124 if (ferror(f)) {
56f64d95 2125 log_error_errno(errno, "Failed to read from file %s: %m", fn);
fba6e687
LP
2126 if (r == 0)
2127 r = -EIO;
2128 }
2129
fba6e687
LP
2130 return r;
2131}
2132
5008d581 2133int main(int argc, char *argv[]) {
fabe5c0e 2134 int r, k;
3f93da98 2135 ItemArray *a;
3b63d2d3
LP
2136 Iterator iterator;
2137
fdcad0c2
LP
2138 r = parse_argv(argc, argv);
2139 if (r <= 0)
753615e8 2140 goto finish;
5008d581 2141
eb0ca9eb 2142 log_set_target(LOG_TARGET_AUTO);
5008d581
LP
2143 log_parse_environment();
2144 log_open();
2145
4c12626c
LP
2146 umask(0022);
2147
cc56fafe 2148 mac_selinux_init(NULL);
5008d581 2149
d5099efc
MS
2150 items = hashmap_new(&string_hash_ops);
2151 globs = hashmap_new(&string_hash_ops);
b8bb3e8f
LP
2152
2153 if (!items || !globs) {
fabe5c0e 2154 r = log_oom();
3b63d2d3
LP
2155 goto finish;
2156 }
2157
fabe5c0e 2158 r = 0;
5008d581 2159
fba6e687
LP
2160 if (optind < argc) {
2161 int j;
5008d581 2162
9125670f 2163 for (j = optind; j < argc; j++) {
fabe5c0e
LP
2164 k = read_config_file(argv[j], false);
2165 if (k < 0 && r == 0)
2166 r = k;
9125670f 2167 }
5008d581 2168
fba6e687 2169 } else {
fabe5c0e
LP
2170 _cleanup_strv_free_ char **files = NULL;
2171 char **f;
5008d581 2172
cf9a4abd 2173 r = conf_files_list_nulstr(&files, ".conf", arg_root, conf_file_dirs);
44143309 2174 if (r < 0) {
da927ba9 2175 log_error_errno(r, "Failed to enumerate tmpfiles.d files: %m");
44143309
KS
2176 goto finish;
2177 }
3b63d2d3 2178
772f8371 2179 STRV_FOREACH(f, files) {
fabe5c0e
LP
2180 k = read_config_file(*f, true);
2181 if (k < 0 && r == 0)
2182 r = k;
5008d581 2183 }
772f8371 2184 }
5008d581 2185
3f93da98
ZJS
2186 HASHMAP_FOREACH(a, globs, iterator) {
2187 k = process_item_array(a);
1db50423
ZJS
2188 if (k < 0 && r == 0)
2189 r = k;
2190 }
b8bb3e8f 2191
3f93da98
ZJS
2192 HASHMAP_FOREACH(a, items, iterator) {
2193 k = process_item_array(a);
1db50423
ZJS
2194 if (k < 0 && r == 0)
2195 r = k;
2196 }
3b63d2d3 2197
5008d581 2198finish:
3f93da98
ZJS
2199 while ((a = hashmap_steal_first(items)))
2200 item_array_free(a);
3b63d2d3 2201
3f93da98
ZJS
2202 while ((a = hashmap_steal_first(globs)))
2203 item_array_free(a);
17b90525 2204
3b63d2d3 2205 hashmap_free(items);
b8bb3e8f 2206 hashmap_free(globs);
5008d581 2207
7bc040fa
LP
2208 free(arg_include_prefixes);
2209 free(arg_exclude_prefixes);
cf9a4abd 2210 free(arg_root);
a2aced4a 2211
17b90525
LP
2212 set_free_free(unix_sockets);
2213
cc56fafe 2214 mac_selinux_finish();
29003cff 2215
fabe5c0e 2216 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
5008d581 2217}