]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/tmpfiles/tmpfiles.c
6cd76e8df844af9503b87d8977ef83fa9fd17603
[thirdparty/systemd.git] / src / tmpfiles / tmpfiles.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <fnmatch.h>
6 #include <getopt.h>
7 #include <limits.h>
8 #include <linux/fs.h>
9 #include <stdbool.h>
10 #include <stddef.h>
11 #include <stdlib.h>
12 #include <sys/file.h>
13 #include <sys/xattr.h>
14 #include <sysexits.h>
15 #include <time.h>
16 #include <unistd.h>
17
18 #include "sd-path.h"
19
20 #include "acl-util.h"
21 #include "alloc-util.h"
22 #include "btrfs-util.h"
23 #include "build.h"
24 #include "capability-util.h"
25 #include "chase.h"
26 #include "chattr-util.h"
27 #include "conf-files.h"
28 #include "constants.h"
29 #include "copy.h"
30 #include "creds-util.h"
31 #include "devnum-util.h"
32 #include "dirent-util.h"
33 #include "dissect-image.h"
34 #include "env-util.h"
35 #include "errno-util.h"
36 #include "escape.h"
37 #include "fd-util.h"
38 #include "fileio.h"
39 #include "format-util.h"
40 #include "fs-util.h"
41 #include "glob-util.h"
42 #include "hexdecoct.h"
43 #include "io-util.h"
44 #include "label.h"
45 #include "log.h"
46 #include "macro.h"
47 #include "main-func.h"
48 #include "missing_stat.h"
49 #include "missing_syscall.h"
50 #include "mkdir-label.h"
51 #include "mount-util.h"
52 #include "mountpoint-util.h"
53 #include "nulstr-util.h"
54 #include "offline-passwd.h"
55 #include "pager.h"
56 #include "parse-argument.h"
57 #include "parse-util.h"
58 #include "path-lookup.h"
59 #include "path-util.h"
60 #include "pretty-print.h"
61 #include "rlimit-util.h"
62 #include "rm-rf.h"
63 #include "selinux-util.h"
64 #include "set.h"
65 #include "sort-util.h"
66 #include "specifier.h"
67 #include "stdio-util.h"
68 #include "string-table.h"
69 #include "string-util.h"
70 #include "strv.h"
71 #include "terminal-util.h"
72 #include "umask-util.h"
73 #include "user-util.h"
74 #include "virt.h"
75
76 /* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
77 * them in the file system. This is intended to be used to create
78 * properly owned directories beneath /tmp, /var/tmp, /run, which are
79 * volatile and hence need to be recreated on bootup. */
80
81 typedef enum OperationMask {
82 OPERATION_CREATE = 1 << 0,
83 OPERATION_REMOVE = 1 << 1,
84 OPERATION_CLEAN = 1 << 2,
85 } OperationMask;
86
87 typedef enum ItemType {
88 /* These ones take file names */
89 CREATE_FILE = 'f',
90 TRUNCATE_FILE = 'F', /* deprecated: use f+ */
91 CREATE_DIRECTORY = 'd',
92 TRUNCATE_DIRECTORY = 'D',
93 CREATE_SUBVOLUME = 'v',
94 CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
95 CREATE_SUBVOLUME_NEW_QUOTA = 'Q',
96 CREATE_FIFO = 'p',
97 CREATE_SYMLINK = 'L',
98 CREATE_CHAR_DEVICE = 'c',
99 CREATE_BLOCK_DEVICE = 'b',
100 COPY_FILES = 'C',
101
102 /* These ones take globs */
103 WRITE_FILE = 'w',
104 EMPTY_DIRECTORY = 'e',
105 SET_XATTR = 't',
106 RECURSIVE_SET_XATTR = 'T',
107 SET_ACL = 'a',
108 RECURSIVE_SET_ACL = 'A',
109 SET_ATTRIBUTE = 'h',
110 RECURSIVE_SET_ATTRIBUTE = 'H',
111 IGNORE_PATH = 'x',
112 IGNORE_DIRECTORY_PATH = 'X',
113 REMOVE_PATH = 'r',
114 RECURSIVE_REMOVE_PATH = 'R',
115 RELABEL_PATH = 'z',
116 RECURSIVE_RELABEL_PATH = 'Z',
117 ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
118 } ItemType;
119
120 typedef enum AgeBy {
121 AGE_BY_ATIME = 1 << 0,
122 AGE_BY_BTIME = 1 << 1,
123 AGE_BY_CTIME = 1 << 2,
124 AGE_BY_MTIME = 1 << 3,
125
126 /* All file timestamp types are checked by default. */
127 AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
128 AGE_BY_DEFAULT_DIR = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME
129 } AgeBy;
130
131 typedef struct Item {
132 ItemType type;
133
134 char *path;
135 char *argument;
136 void *binary_argument; /* set if binary data, in which case it takes precedence over 'argument' */
137 size_t binary_argument_size;
138 char **xattrs;
139 #if HAVE_ACL
140 acl_t acl_access;
141 acl_t acl_default;
142 #endif
143 uid_t uid;
144 gid_t gid;
145 mode_t mode;
146 usec_t age;
147 AgeBy age_by_file, age_by_dir;
148
149 dev_t major_minor;
150 unsigned attribute_value;
151 unsigned attribute_mask;
152
153 bool uid_set:1;
154 bool gid_set:1;
155 bool mode_set:1;
156 bool uid_only_create:1;
157 bool gid_only_create:1;
158 bool mode_only_create:1;
159 bool age_set:1;
160 bool mask_perms:1;
161 bool attribute_set:1;
162
163 bool keep_first_level:1;
164
165 bool append_or_force:1;
166
167 bool allow_failure:1;
168
169 bool try_replace:1;
170
171 OperationMask done;
172 } Item;
173
174 typedef struct ItemArray {
175 Item *items;
176 size_t n_items;
177
178 struct ItemArray *parent;
179 Set *children;
180 } ItemArray;
181
182 typedef enum DirectoryType {
183 DIRECTORY_RUNTIME,
184 DIRECTORY_STATE,
185 DIRECTORY_CACHE,
186 DIRECTORY_LOGS,
187 _DIRECTORY_TYPE_MAX,
188 } DirectoryType;
189
190 typedef enum {
191 CREATION_NORMAL,
192 CREATION_EXISTING,
193 CREATION_FORCE,
194 _CREATION_MODE_MAX,
195 _CREATION_MODE_INVALID = -EINVAL,
196 } CreationMode;
197
198 static bool arg_cat_config = false;
199 static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
200 static OperationMask arg_operation = 0;
201 static bool arg_boot = false;
202 static PagerFlags arg_pager_flags = 0;
203
204 static char **arg_include_prefixes = NULL;
205 static char **arg_exclude_prefixes = NULL;
206 static char *arg_root = NULL;
207 static char *arg_image = NULL;
208 static char *arg_replace = NULL;
209
210 #define MAX_DEPTH 256
211
212 static OrderedHashmap *items = NULL, *globs = NULL;
213 static Set *unix_sockets = NULL;
214
215 STATIC_DESTRUCTOR_REGISTER(items, ordered_hashmap_freep);
216 STATIC_DESTRUCTOR_REGISTER(globs, ordered_hashmap_freep);
217 STATIC_DESTRUCTOR_REGISTER(unix_sockets, set_freep);
218 STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, freep);
219 STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, freep);
220 STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
221 STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
222
223 static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
224 [CREATION_NORMAL] = "Created",
225 [CREATION_EXISTING] = "Found existing",
226 [CREATION_FORCE] = "Created replacement",
227 };
228
229 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
230
231 /* Different kinds of errors that mean that information is not available in the environment. */
232 static inline bool ERRNO_IS_NOINFO(int r) {
233 return IN_SET(abs(r),
234 EUNATCH, /* os-release or machine-id missing */
235 ENOMEDIUM, /* machine-id or another file empty */
236 ENXIO); /* env var is unset */
237 }
238
239 static int specifier_directory(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
240 struct table_entry {
241 uint64_t type;
242 const char *suffix;
243 };
244
245 static const struct table_entry paths_system[] = {
246 [DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME },
247 [DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE },
248 [DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE },
249 [DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS },
250 };
251
252 static const struct table_entry paths_user[] = {
253 [DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME },
254 [DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION },
255 [DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE },
256 [DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
257 };
258
259 const struct table_entry *paths;
260 _cleanup_free_ char *p = NULL;
261 unsigned i;
262 int r;
263
264 assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
265 paths = arg_runtime_scope == RUNTIME_SCOPE_USER ? paths_user : paths_system;
266
267 i = PTR_TO_UINT(data);
268 assert(i < ELEMENTSOF(paths_system));
269
270 r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
271 if (r < 0)
272 return r;
273
274 if (arg_root) {
275 _cleanup_free_ char *j = NULL;
276
277 j = path_join(arg_root, p);
278 if (!j)
279 return -ENOMEM;
280
281 *ret = TAKE_PTR(j);
282 } else
283 *ret = TAKE_PTR(p);
284
285 return 0;
286 }
287
288 static int log_unresolvable_specifier(const char *filename, unsigned line) {
289 static bool notified = false;
290
291 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
292 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
293 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
294 * to LOG_DEBUG for the rest.
295 *
296 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
297 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
298 * expectation that machine-id and other files will be populated.
299 */
300
301 int log_level = notified || arg_root || running_in_chroot() > 0 ?
302 LOG_DEBUG : LOG_NOTICE;
303
304 log_syntax(NULL,
305 log_level,
306 filename, line, 0,
307 "Failed to resolve specifier: %s, skipping.",
308 arg_runtime_scope == RUNTIME_SCOPE_USER ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
309
310 if (!notified)
311 log_full(log_level,
312 "All rules containing unresolvable specifiers will be skipped.");
313
314 notified = true;
315 return 0;
316 }
317
318 static int user_config_paths(char*** ret) {
319 _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
320 _cleanup_free_ char *persistent_config = NULL, *runtime_config = NULL, *data_home = NULL;
321 _cleanup_strv_free_ char **res = NULL;
322 int r;
323
324 r = xdg_user_dirs(&config_dirs, &data_dirs);
325 if (r < 0)
326 return r;
327
328 r = xdg_user_config_dir(&persistent_config, "/user-tmpfiles.d");
329 if (r < 0 && !ERRNO_IS_NOINFO(r))
330 return r;
331
332 r = xdg_user_runtime_dir(&runtime_config, "/user-tmpfiles.d");
333 if (r < 0 && !ERRNO_IS_NOINFO(r))
334 return r;
335
336 r = xdg_user_data_dir(&data_home, "/user-tmpfiles.d");
337 if (r < 0 && !ERRNO_IS_NOINFO(r))
338 return r;
339
340 r = strv_extend_strv_concat(&res, config_dirs, "/user-tmpfiles.d");
341 if (r < 0)
342 return r;
343
344 r = strv_extend(&res, persistent_config);
345 if (r < 0)
346 return r;
347
348 r = strv_extend(&res, runtime_config);
349 if (r < 0)
350 return r;
351
352 r = strv_extend(&res, data_home);
353 if (r < 0)
354 return r;
355
356 r = strv_extend_strv_concat(&res, data_dirs, "/user-tmpfiles.d");
357 if (r < 0)
358 return r;
359
360 r = path_strv_make_absolute_cwd(res);
361 if (r < 0)
362 return r;
363
364 *ret = TAKE_PTR(res);
365 return 0;
366 }
367
368 static bool needs_glob(ItemType t) {
369 return IN_SET(t,
370 WRITE_FILE,
371 IGNORE_PATH,
372 IGNORE_DIRECTORY_PATH,
373 REMOVE_PATH,
374 RECURSIVE_REMOVE_PATH,
375 EMPTY_DIRECTORY,
376 ADJUST_MODE,
377 RELABEL_PATH,
378 RECURSIVE_RELABEL_PATH,
379 SET_XATTR,
380 RECURSIVE_SET_XATTR,
381 SET_ACL,
382 RECURSIVE_SET_ACL,
383 SET_ATTRIBUTE,
384 RECURSIVE_SET_ATTRIBUTE);
385 }
386
387 static bool takes_ownership(ItemType t) {
388 return IN_SET(t,
389 CREATE_FILE,
390 TRUNCATE_FILE,
391 CREATE_DIRECTORY,
392 EMPTY_DIRECTORY,
393 TRUNCATE_DIRECTORY,
394 CREATE_SUBVOLUME,
395 CREATE_SUBVOLUME_INHERIT_QUOTA,
396 CREATE_SUBVOLUME_NEW_QUOTA,
397 CREATE_FIFO,
398 CREATE_SYMLINK,
399 CREATE_CHAR_DEVICE,
400 CREATE_BLOCK_DEVICE,
401 COPY_FILES,
402 WRITE_FILE,
403 IGNORE_PATH,
404 IGNORE_DIRECTORY_PATH,
405 REMOVE_PATH,
406 RECURSIVE_REMOVE_PATH);
407 }
408
409 static struct Item* find_glob(OrderedHashmap *h, const char *match) {
410 ItemArray *j;
411
412 ORDERED_HASHMAP_FOREACH(j, h) {
413 size_t n;
414
415 for (n = 0; n < j->n_items; n++) {
416 Item *item = j->items + n;
417
418 if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
419 return item;
420 }
421 }
422
423 return NULL;
424 }
425
426 static int load_unix_sockets(void) {
427 _cleanup_set_free_ Set *sockets = NULL;
428 _cleanup_fclose_ FILE *f = NULL;
429 int r;
430
431 if (unix_sockets)
432 return 0;
433
434 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
435
436 f = fopen("/proc/net/unix", "re");
437 if (!f)
438 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
439 "Failed to open /proc/net/unix, ignoring: %m");
440
441 /* Skip header */
442 r = read_line(f, LONG_LINE_MAX, NULL);
443 if (r < 0)
444 return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
445 if (r == 0)
446 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
447
448 for (;;) {
449 _cleanup_free_ char *line = NULL;
450 char *p;
451
452 r = read_line(f, LONG_LINE_MAX, &line);
453 if (r < 0)
454 return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
455 if (r == 0) /* EOF */
456 break;
457
458 p = strchr(line, ':');
459 if (!p)
460 continue;
461
462 if (strlen(p) < 37)
463 continue;
464
465 p += 37;
466 p += strspn(p, WHITESPACE);
467 p += strcspn(p, WHITESPACE); /* skip one more word */
468 p += strspn(p, WHITESPACE);
469
470 if (!path_is_absolute(p))
471 continue;
472
473 r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
474 if (r < 0)
475 return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
476 }
477
478 unix_sockets = TAKE_PTR(sockets);
479 return 1;
480 }
481
482 static bool unix_socket_alive(const char *fn) {
483 assert(fn);
484
485 if (load_unix_sockets() < 0)
486 return true; /* We don't know, so assume yes */
487
488 return set_contains(unix_sockets, fn);
489 }
490
491 /* Accessors for the argument in binary format */
492 static const void* item_binary_argument(const Item *i) {
493 assert(i);
494 return i->binary_argument ?: i->argument;
495 }
496
497 static size_t item_binary_argument_size(const Item *i) {
498 assert(i);
499 return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
500 }
501
502 static DIR* xopendirat_nomod(int dirfd, const char *path) {
503 DIR *dir;
504
505 dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
506 if (dir)
507 return dir;
508
509 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
510 if (errno != EPERM)
511 return NULL;
512
513 dir = xopendirat(dirfd, path, O_NOFOLLOW);
514 if (!dir)
515 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
516
517 return dir;
518 }
519
520 static DIR* opendir_nomod(const char *path) {
521 return xopendirat_nomod(AT_FDCWD, path);
522 }
523
524 static inline nsec_t load_statx_timestamp_nsec(const struct statx_timestamp *ts) {
525 assert(ts);
526
527 if (ts->tv_sec < 0)
528 return NSEC_INFINITY;
529
530 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
531 return NSEC_INFINITY;
532
533 return ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec;
534 }
535
536 static bool needs_cleanup(
537 nsec_t atime,
538 nsec_t btime,
539 nsec_t ctime,
540 nsec_t mtime,
541 nsec_t cutoff,
542 const char *sub_path,
543 AgeBy age_by,
544 bool is_dir) {
545
546 if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
547 /* Follows spelling in stat(1). */
548 log_debug("%s \"%s\": modify time %s is too new.",
549 is_dir ? "Directory" : "File",
550 sub_path,
551 FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
552
553 return false;
554 }
555
556 if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
557 log_debug("%s \"%s\": access time %s is too new.",
558 is_dir ? "Directory" : "File",
559 sub_path,
560 FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
561
562 return false;
563 }
564
565 /*
566 * Note: Unless explicitly specified by the user, "ctime" is ignored
567 * by default for directories, because we change it when deleting.
568 */
569 if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
570 log_debug("%s \"%s\": change time %s is too new.",
571 is_dir ? "Directory" : "File",
572 sub_path,
573 FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
574
575 return false;
576 }
577
578 if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
579 log_debug("%s \"%s\": birth time %s is too new.",
580 is_dir ? "Directory" : "File",
581 sub_path,
582 FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
583
584 return false;
585 }
586
587 return true;
588 }
589
590 static int dir_cleanup(
591 Item *i,
592 const char *p,
593 DIR *d,
594 nsec_t self_atime_nsec,
595 nsec_t self_mtime_nsec,
596 nsec_t cutoff_nsec,
597 dev_t rootdev_major,
598 dev_t rootdev_minor,
599 bool mountpoint,
600 int maxdepth,
601 bool keep_this_level,
602 AgeBy age_by_file,
603 AgeBy age_by_dir) {
604
605 bool deleted = false;
606 int r = 0;
607
608 FOREACH_DIRENT_ALL(de, d, break) {
609 _cleanup_free_ char *sub_path = NULL;
610 nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
611
612 if (dot_or_dot_dot(de->d_name))
613 continue;
614
615 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
616 * explicitly where we are looking at a mount point, for free as side information. Determining
617 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
618 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
619 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
620 * while on older kernels's well do traditional st_dev based detection of mount points.
621 *
622 * Using statx() for detecting mount points also has the benfit that we handle weird file
623 * systems such as overlayfs better where each file is originating from a different
624 * st_dev. */
625
626 STRUCT_STATX_DEFINE(sx);
627
628 r = statx_fallback(
629 dirfd(d), de->d_name,
630 AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
631 STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
632 &sx);
633 if (r == -ENOENT)
634 continue;
635 if (r < 0) {
636 /* FUSE, NFS mounts, SELinux might return EACCES */
637 r = log_full_errno(r == -EACCES ? LOG_DEBUG : LOG_ERR, r,
638 "statx(%s/%s) failed: %m", p, de->d_name);
639 continue;
640 }
641
642 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) {
643 /* Yay, we have the mount point API, use it */
644 if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
645 log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
646 continue;
647 }
648 } else {
649 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
650 * back to traditional stx_dev checking. */
651 if (sx.stx_dev_major != rootdev_major ||
652 sx.stx_dev_minor != rootdev_minor) {
653 log_debug("Ignoring \"%s/%s\": different filesystem.", p, de->d_name);
654 continue;
655 }
656
657 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
658 * major/minors. This type of query is not supported on all kernels or filesystem types
659 * though. */
660 if (S_ISDIR(sx.stx_mode)) {
661 int q;
662
663 q = fd_is_mount_point(dirfd(d), de->d_name, 0);
664 if (q < 0)
665 log_debug_errno(q, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p, de->d_name);
666 else if (q > 0) {
667 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p, de->d_name);
668 continue;
669 }
670 }
671 }
672
673 atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? load_statx_timestamp_nsec(&sx.stx_atime) : 0;
674 mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? load_statx_timestamp_nsec(&sx.stx_mtime) : 0;
675 ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? load_statx_timestamp_nsec(&sx.stx_ctime) : 0;
676 btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? load_statx_timestamp_nsec(&sx.stx_btime) : 0;
677
678 sub_path = path_join(p, de->d_name);
679 if (!sub_path) {
680 r = log_oom();
681 goto finish;
682 }
683
684 /* Is there an item configured for this path? */
685 if (ordered_hashmap_get(items, sub_path)) {
686 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
687 continue;
688 }
689
690 if (find_glob(globs, sub_path)) {
691 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
692 continue;
693 }
694
695 if (S_ISDIR(sx.stx_mode)) {
696 _cleanup_closedir_ DIR *sub_dir = NULL;
697
698 if (mountpoint &&
699 streq(de->d_name, "lost+found") &&
700 sx.stx_uid == 0) {
701 log_debug("Ignoring directory \"%s\".", sub_path);
702 continue;
703 }
704
705 if (maxdepth <= 0)
706 log_warning("Reached max depth on \"%s\".", sub_path);
707 else {
708 int q;
709
710 sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
711 if (!sub_dir) {
712 if (errno != ENOENT)
713 r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
714
715 continue;
716 }
717
718 if (flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
719 log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p);
720 continue;
721 }
722
723 q = dir_cleanup(i,
724 sub_path, sub_dir,
725 atime_nsec, mtime_nsec, cutoff_nsec,
726 rootdev_major, rootdev_minor,
727 false, maxdepth-1, false,
728 age_by_file, age_by_dir);
729 if (q < 0)
730 r = q;
731 }
732
733 /* Note: if you are wondering why we don't support the sticky bit for excluding
734 * directories from cleaning like we do it for other file system objects: well, the
735 * sticky bit already has a meaning for directories, so we don't want to overload
736 * that. */
737
738 if (keep_this_level) {
739 log_debug("Keeping directory \"%s\".", sub_path);
740 continue;
741 }
742
743 /*
744 * Check the file timestamps of an entry against the
745 * given cutoff time; delete if it is older.
746 */
747 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
748 cutoff_nsec, sub_path, age_by_dir, true))
749 continue;
750
751 log_debug("Removing directory \"%s\".", sub_path);
752 if (unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0)
753 if (!IN_SET(errno, ENOENT, ENOTEMPTY))
754 r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
755
756 } else {
757 _cleanup_close_ int fd = -EBADF;
758
759 /* Skip files for which the sticky bit is set. These are semantics we define, and are
760 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
761 if (sx.stx_mode & S_ISVTX) {
762 log_debug("Skipping \"%s\": sticky bit set.", sub_path);
763 continue;
764 }
765
766 if (mountpoint &&
767 S_ISREG(sx.stx_mode) &&
768 sx.stx_uid == 0 &&
769 STR_IN_SET(de->d_name,
770 ".journal",
771 "aquota.user",
772 "aquota.group")) {
773 log_debug("Skipping \"%s\".", sub_path);
774 continue;
775 }
776
777 /* Ignore sockets that are listed in /proc/net/unix */
778 if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(sub_path)) {
779 log_debug("Skipping \"%s\": live socket.", sub_path);
780 continue;
781 }
782
783 /* Ignore device nodes */
784 if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
785 log_debug("Skipping \"%s\": a device.", sub_path);
786 continue;
787 }
788
789 /* Keep files on this level around if this is requested */
790 if (keep_this_level) {
791 log_debug("Keeping \"%s\".", sub_path);
792 continue;
793 }
794
795 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
796 cutoff_nsec, sub_path, age_by_file, false))
797 continue;
798
799 fd = xopenat(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME, 0);
800 if (fd < 0 && fd != -ENOENT)
801 log_warning_errno(fd, "Opening file \"%s\" failed, ignoring: %m", sub_path);
802 if (fd >= 0 && flock(fd, LOCK_EX|LOCK_NB) < 0 && errno == EAGAIN) {
803 log_debug_errno(errno, "Couldn't acquire shared BSD lock on file \"%s\", skipping: %m", p);
804 continue;
805 }
806
807 log_debug("Removing \"%s\".", sub_path);
808 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
809 if (errno != ENOENT)
810 r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
811
812 deleted = true;
813 }
814 }
815
816 finish:
817 if (deleted) {
818 struct timespec ts[2];
819
820 log_debug("Restoring access and modification time on \"%s\": %s, %s",
821 p,
822 FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
823 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
824
825 timespec_store_nsec(ts + 0, self_atime_nsec);
826 timespec_store_nsec(ts + 1, self_mtime_nsec);
827
828 /* Restore original directory timestamps */
829 if (futimens(dirfd(d), ts) < 0)
830 log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
831 }
832
833 return r;
834 }
835
836 static bool dangerous_hardlinks(void) {
837 _cleanup_free_ char *value = NULL;
838 static int cached = -1;
839 int r;
840
841 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
842 * what the upstream default is. */
843
844 if (cached >= 0)
845 return cached;
846
847 r = read_one_line_file("/proc/sys/fs/protected_hardlinks", &value);
848 if (r < 0) {
849 log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl: %m");
850 return true;
851 }
852
853 r = parse_boolean(value);
854 if (r < 0) {
855 log_debug_errno(r, "Failed to parse fs.protected_hardlinks sysctl: %m");
856 return true;
857 }
858
859 cached = r == 0;
860 return cached;
861 }
862
863 static bool hardlink_vulnerable(const struct stat *st) {
864 assert(st);
865
866 return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && dangerous_hardlinks();
867 }
868
869 static mode_t process_mask_perms(mode_t mode, mode_t current) {
870
871 if ((current & 0111) == 0)
872 mode &= ~0111;
873 if ((current & 0222) == 0)
874 mode &= ~0222;
875 if ((current & 0444) == 0)
876 mode &= ~0444;
877 if (!S_ISDIR(current))
878 mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
879
880 return mode;
881 }
882
883 static int fd_set_perms(
884 Item *i,
885 int fd,
886 const char *path,
887 const struct stat *st,
888 CreationMode creation) {
889
890 bool do_chown, do_chmod;
891 struct stat stbuf;
892 mode_t new_mode;
893 uid_t new_uid;
894 gid_t new_gid;
895 int r;
896
897 assert(i);
898 assert(fd >= 0);
899 assert(path);
900
901 if (!i->mode_set && !i->uid_set && !i->gid_set)
902 goto shortcut;
903
904 if (!st) {
905 if (fstat(fd, &stbuf) < 0)
906 return log_error_errno(errno, "fstat(%s) failed: %m", path);
907 st = &stbuf;
908 }
909
910 if (hardlink_vulnerable(st))
911 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
912 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
913 path);
914 new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
915 new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
916
917 /* Do we need a chown()? */
918 do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
919
920 /* Calculate the mode to apply */
921 new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
922 (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
923 (st->st_mode & 07777);
924
925 do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
926
927 if (do_chmod && do_chown) {
928 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
929 * the new mode. That way there's no time window where the file exists under the old owner
930 * with more than the old access modes — and not under the new owner with more than the new
931 * access modes either. */
932
933 if (S_ISLNK(st->st_mode))
934 log_debug("Skipping temporary mode fix for symlink %s.", path);
935 else {
936 mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
937
938 if (((m ^ st->st_mode) & 07777) == 0)
939 log_debug("\"%s\" matches temporary mode %o already.", path, m);
940 else {
941 log_debug("Temporarily changing \"%s\" to mode %o.", path, m);
942 r = fchmod_opath(fd, m);
943 if (r < 0)
944 return log_error_errno(r, "fchmod() of %s failed: %m", path);
945 }
946 }
947 }
948
949 if (do_chown) {
950 log_debug("Changing \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
951
952 if (fchownat(fd, "",
953 new_uid != st->st_uid ? new_uid : UID_INVALID,
954 new_gid != st->st_gid ? new_gid : GID_INVALID,
955 AT_EMPTY_PATH) < 0)
956 return log_error_errno(errno, "fchownat() of %s failed: %m", path);
957 }
958
959 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
960 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
961 if (do_chmod || do_chown) {
962 if (S_ISLNK(st->st_mode))
963 log_debug("Skipping mode fix for symlink %s.", path);
964 else {
965 log_debug("Changing \"%s\" to mode %o.", path, new_mode);
966 r = fchmod_opath(fd, new_mode);
967 if (r < 0)
968 return log_error_errno(r, "fchmod() of %s failed: %m", path);
969 }
970 }
971
972 shortcut:
973 return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
974 }
975
976 static int path_open_parent_safe(const char *path, bool allow_failure) {
977 _cleanup_free_ char *dn = NULL;
978 int r, fd;
979
980 if (!path_is_normalized(path))
981 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
982 SYNTHETIC_ERRNO(EINVAL),
983 "Failed to open parent of '%s': path not normalized%s.",
984 path,
985 allow_failure ? ", ignoring" : "");
986
987 r = path_extract_directory(path, &dn);
988 if (r < 0)
989 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
990 r,
991 "Unable to determine parent directory of '%s'%s: %m",
992 path,
993 allow_failure ? ", ignoring" : "");
994
995 r = chase(dn, arg_root, allow_failure ? CHASE_SAFE : CHASE_SAFE|CHASE_WARN, NULL, &fd);
996 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
997 return r;
998 if (r < 0)
999 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1000 r,
1001 "Failed to open path '%s'%s: %m",
1002 dn,
1003 allow_failure ? ", ignoring" : "");
1004
1005 return fd;
1006 }
1007
1008 static int path_open_safe(const char *path) {
1009 int r, fd;
1010
1011 /* path_open_safe() returns a file descriptor opened with O_PATH after
1012 * verifying that the path doesn't contain unsafe transitions, except
1013 * for its final component as the function does not follow symlink. */
1014
1015 assert(path);
1016
1017 if (!path_is_normalized(path))
1018 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
1019
1020 r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
1021 if (r == -ENOLINK)
1022 return r; /* Unsafe symlink: already covered by CHASE_WARN */
1023 if (r < 0)
1024 return log_error_errno(r, "Failed to open path %s: %m", path);
1025
1026 return fd;
1027 }
1028
1029 static int path_set_perms(
1030 Item *i,
1031 const char *path,
1032 CreationMode creation) {
1033
1034 _cleanup_close_ int fd = -EBADF;
1035
1036 assert(i);
1037 assert(path);
1038
1039 fd = path_open_safe(path);
1040 if (fd < 0)
1041 return fd;
1042
1043 return fd_set_perms(i, fd, path, /* st= */ NULL, creation);
1044 }
1045
1046 static int parse_xattrs_from_arg(Item *i) {
1047 const char *p;
1048 int r;
1049
1050 assert(i);
1051
1052 assert_se(p = i->argument);
1053 for (;;) {
1054 _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
1055
1056 r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
1057 if (r < 0)
1058 log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
1059 if (r <= 0)
1060 break;
1061
1062 r = split_pair(xattr, "=", &name, &value);
1063 if (r < 0) {
1064 log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
1065 continue;
1066 }
1067
1068 if (isempty(name) || isempty(value)) {
1069 log_warning("Malformed extended attribute found, ignoring: %s", xattr);
1070 continue;
1071 }
1072
1073 if (strv_push_pair(&i->xattrs, name, value) < 0)
1074 return log_oom();
1075
1076 name = value = NULL;
1077 }
1078
1079 return 0;
1080 }
1081
1082 static int fd_set_xattrs(
1083 Item *i,
1084 int fd,
1085 const char *path,
1086 const struct stat *st,
1087 CreationMode creation) {
1088
1089 assert(i);
1090 assert(fd >= 0);
1091 assert(path);
1092
1093 STRV_FOREACH_PAIR(name, value, i->xattrs) {
1094 log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
1095 if (setxattr(FORMAT_PROC_FD_PATH(fd), *name, *value, strlen(*value), 0) < 0)
1096 return log_error_errno(errno, "Setting extended attribute %s=%s on %s failed: %m",
1097 *name, *value, path);
1098 }
1099 return 0;
1100 }
1101
1102 static int path_set_xattrs(
1103 Item *i,
1104 const char *path,
1105 CreationMode creation) {
1106
1107 _cleanup_close_ int fd = -EBADF;
1108
1109 assert(i);
1110 assert(path);
1111
1112 fd = path_open_safe(path);
1113 if (fd < 0)
1114 return fd;
1115
1116 return fd_set_xattrs(i, fd, path, /* st = */ NULL, creation);
1117 }
1118
1119 static int parse_acls_from_arg(Item *item) {
1120 #if HAVE_ACL
1121 int r;
1122
1123 assert(item);
1124
1125 /* If append_or_force (= modify) is set, we will not modify the acl
1126 * afterwards, so the mask can be added now if necessary. */
1127
1128 r = parse_acl(item->argument, &item->acl_access, &item->acl_default, !item->append_or_force);
1129 if (r < 0)
1130 log_warning_errno(r, "Failed to parse ACL \"%s\": %m. Ignoring", item->argument);
1131 #else
1132 log_warning("ACLs are not supported. Ignoring.");
1133 #endif
1134
1135 return 0;
1136 }
1137
1138 #if HAVE_ACL
1139 static int path_set_acl(
1140 const char *path,
1141 const char *pretty,
1142 acl_type_t type,
1143 acl_t acl,
1144 bool modify) {
1145
1146 _cleanup_(acl_free_charpp) char *t = NULL;
1147 _cleanup_(acl_freep) acl_t dup = NULL;
1148 int r;
1149
1150 /* Returns 0 for success, positive error if already warned,
1151 * negative error otherwise. */
1152
1153 if (modify) {
1154 r = acls_for_file(path, type, acl, &dup);
1155 if (r < 0)
1156 return r;
1157
1158 r = calc_acl_mask_if_needed(&dup);
1159 if (r < 0)
1160 return r;
1161 } else {
1162 dup = acl_dup(acl);
1163 if (!dup)
1164 return -errno;
1165
1166 /* the mask was already added earlier if needed */
1167 }
1168
1169 r = add_base_acls_if_needed(&dup, path);
1170 if (r < 0)
1171 return r;
1172
1173 t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1174 log_debug("Setting %s ACL %s on %s.",
1175 type == ACL_TYPE_ACCESS ? "access" : "default",
1176 strna(t), pretty);
1177
1178 r = acl_set_file(path, type, dup);
1179 if (r < 0) {
1180 if (ERRNO_IS_NOT_SUPPORTED(errno))
1181 /* No error if filesystem doesn't support ACLs. Return negative. */
1182 return -errno;
1183 else
1184 /* Return positive to indicate we already warned */
1185 return -log_error_errno(errno,
1186 "Setting %s ACL \"%s\" on %s failed: %m",
1187 type == ACL_TYPE_ACCESS ? "access" : "default",
1188 strna(t), pretty);
1189 }
1190 return 0;
1191 }
1192 #endif
1193
1194 static int fd_set_acls(
1195 Item *item,
1196 int fd,
1197 const char *path,
1198 const struct stat *st,
1199 CreationMode creation) {
1200
1201 int r = 0;
1202 #if HAVE_ACL
1203 struct stat stbuf;
1204
1205 assert(item);
1206 assert(fd >= 0);
1207 assert(path);
1208
1209 if (!st) {
1210 if (fstat(fd, &stbuf) < 0)
1211 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1212 st = &stbuf;
1213 }
1214
1215 if (hardlink_vulnerable(st))
1216 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1217 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1218 path);
1219
1220 if (S_ISLNK(st->st_mode)) {
1221 log_debug("Skipping ACL fix for symlink %s.", path);
1222 return 0;
1223 }
1224
1225 if (item->acl_access)
1226 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
1227
1228 /* set only default acls to folders */
1229 if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
1230 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
1231
1232 if (ERRNO_IS_NOT_SUPPORTED(r)) {
1233 log_debug_errno(r, "ACLs not supported by file system at %s", path);
1234 return 0;
1235 }
1236
1237 if (r > 0)
1238 return -r; /* already warned */
1239
1240 /* The above procfs paths don't work if /proc is not mounted. */
1241 if (r == -ENOENT && proc_mounted() == 0)
1242 r = -ENOSYS;
1243
1244 if (r < 0)
1245 return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
1246 #endif
1247 return r;
1248 }
1249
1250 static int path_set_acls(Item *item, const char *path, CreationMode creation) {
1251 int r = 0;
1252 #if HAVE_ACL
1253 _cleanup_close_ int fd = -EBADF;
1254
1255 assert(item);
1256 assert(path);
1257
1258 fd = path_open_safe(path);
1259 if (fd < 0)
1260 return fd;
1261
1262 r = fd_set_acls(item, fd, path, /* st= */ NULL, creation);
1263 #endif
1264 return r;
1265 }
1266
1267 static int parse_attribute_from_arg(Item *item) {
1268
1269 static const struct {
1270 char character;
1271 unsigned value;
1272 } attributes[] = {
1273 { 'A', FS_NOATIME_FL }, /* do not update atime */
1274 { 'S', FS_SYNC_FL }, /* Synchronous updates */
1275 { 'D', FS_DIRSYNC_FL }, /* dirsync behaviour (directories only) */
1276 { 'a', FS_APPEND_FL }, /* writes to file may only append */
1277 { 'c', FS_COMPR_FL }, /* Compress file */
1278 { 'd', FS_NODUMP_FL }, /* do not dump file */
1279 { 'e', FS_EXTENT_FL }, /* Extents */
1280 { 'i', FS_IMMUTABLE_FL }, /* Immutable file */
1281 { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1282 { 's', FS_SECRM_FL }, /* Secure deletion */
1283 { 'u', FS_UNRM_FL }, /* Undelete */
1284 { 't', FS_NOTAIL_FL }, /* file tail should not be merged */
1285 { 'T', FS_TOPDIR_FL }, /* Top of directory hierarchies */
1286 { 'C', FS_NOCOW_FL }, /* Do not cow file */
1287 { 'P', FS_PROJINHERIT_FL }, /* Inherit the quota project ID */
1288 };
1289
1290 enum {
1291 MODE_ADD,
1292 MODE_DEL,
1293 MODE_SET
1294 } mode = MODE_ADD;
1295
1296 unsigned value = 0, mask = 0;
1297 const char *p;
1298
1299 assert(item);
1300
1301 p = item->argument;
1302 if (p) {
1303 if (*p == '+') {
1304 mode = MODE_ADD;
1305 p++;
1306 } else if (*p == '-') {
1307 mode = MODE_DEL;
1308 p++;
1309 } else if (*p == '=') {
1310 mode = MODE_SET;
1311 p++;
1312 }
1313 }
1314
1315 if (isempty(p) && mode != MODE_SET)
1316 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1317 "Setting file attribute on '%s' needs an attribute specification.",
1318 item->path);
1319
1320 for (; p && *p ; p++) {
1321 unsigned i, v;
1322
1323 for (i = 0; i < ELEMENTSOF(attributes); i++)
1324 if (*p == attributes[i].character)
1325 break;
1326
1327 if (i >= ELEMENTSOF(attributes))
1328 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1329 "Unknown file attribute '%c' on '%s'.",
1330 *p, item->path);
1331
1332 v = attributes[i].value;
1333
1334 SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1335
1336 mask |= v;
1337 }
1338
1339 if (mode == MODE_SET)
1340 mask |= CHATTR_ALL_FL;
1341
1342 assert(mask != 0);
1343
1344 item->attribute_mask = mask;
1345 item->attribute_value = value;
1346 item->attribute_set = true;
1347
1348 return 0;
1349 }
1350
1351 static int fd_set_attribute(
1352 Item *item,
1353 int fd,
1354 const char *path,
1355 const struct stat *st,
1356 CreationMode creation) {
1357
1358 _cleanup_close_ int procfs_fd = -EBADF;
1359 struct stat stbuf;
1360 unsigned f;
1361 int r;
1362
1363 assert(item);
1364 assert(fd >= 0);
1365 assert(path);
1366
1367 if (!item->attribute_set || item->attribute_mask == 0)
1368 return 0;
1369
1370 if (!st) {
1371 if (fstat(fd, &stbuf) < 0)
1372 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1373 st = &stbuf;
1374 }
1375
1376 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1377 * drivers, not the file system containing the device node. */
1378 if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode))
1379 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1380 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1381 path);
1382
1383 f = item->attribute_value & item->attribute_mask;
1384
1385 /* Mask away directory-specific flags */
1386 if (!S_ISDIR(st->st_mode))
1387 f &= ~FS_DIRSYNC_FL;
1388
1389 procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
1390 if (procfs_fd < 0)
1391 return log_error_errno(procfs_fd, "Failed to re-open '%s': %m", path);
1392
1393 unsigned previous, current;
1394 r = chattr_full(NULL, procfs_fd, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
1395 if (r == -ENOANO)
1396 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1397 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1398 path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1399 else if (r < 0)
1400 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
1401 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1402 path, item->attribute_value, item->attribute_mask);
1403
1404 return 0;
1405 }
1406
1407 static int path_set_attribute(Item *item, const char *path, CreationMode creation) {
1408 _cleanup_close_ int fd = -EBADF;
1409
1410 if (!item->attribute_set || item->attribute_mask == 0)
1411 return 0;
1412
1413 fd = path_open_safe(path);
1414 if (fd < 0)
1415 return fd;
1416
1417 return fd_set_attribute(item, fd, path, /* st= */ NULL, creation);
1418 }
1419
1420 static int write_argument_data(Item *i, int fd, const char *path) {
1421 int r;
1422
1423 assert(i);
1424 assert(fd >= 0);
1425 assert(path);
1426
1427 if (item_binary_argument_size(i) == 0)
1428 return 0;
1429
1430 assert(item_binary_argument(i));
1431
1432 log_debug("Writing to \"%s\".", path);
1433
1434 r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i), /* do_poll= */ false);
1435 if (r < 0)
1436 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
1437
1438 return 0;
1439 }
1440
1441 static int write_one_file(Item *i, const char *path, CreationMode creation) {
1442 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1443 _cleanup_free_ char *bn = NULL;
1444 int r;
1445
1446 assert(i);
1447 assert(path);
1448 assert(i->type == WRITE_FILE);
1449
1450 r = path_extract_filename(path, &bn);
1451 if (r < 0)
1452 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1453 if (r == O_DIRECTORY)
1454 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1455
1456 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1457 * can't be changed behind our back. */
1458 dir_fd = path_open_parent_safe(path, i->allow_failure);
1459 if (dir_fd < 0)
1460 return dir_fd;
1461
1462 /* Follows symlinks */
1463 fd = openat(dir_fd, bn,
1464 O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY|(i->append_or_force ? O_APPEND : 0),
1465 i->mode);
1466 if (fd < 0) {
1467 if (errno == ENOENT) {
1468 log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
1469 return 0;
1470 }
1471
1472 if (i->allow_failure)
1473 return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
1474
1475 return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
1476 }
1477
1478 /* 'w' is allowed to write into any kind of files. */
1479
1480 r = write_argument_data(i, fd, path);
1481 if (r < 0)
1482 return r;
1483
1484 return fd_set_perms(i, fd, path, NULL, creation);
1485 }
1486
1487 static int create_file(Item *i, const char *path) {
1488 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1489 _cleanup_free_ char *bn = NULL;
1490 struct stat stbuf, *st = NULL;
1491 CreationMode creation;
1492 int r = 0;
1493
1494 assert(i);
1495 assert(path);
1496 assert(i->type == CREATE_FILE);
1497
1498 /* 'f' operates on regular files exclusively. */
1499
1500 r = path_extract_filename(path, &bn);
1501 if (r < 0)
1502 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1503 if (r == O_DIRECTORY)
1504 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1505
1506 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1507 * can't be changed behind our back. */
1508 dir_fd = path_open_parent_safe(path, i->allow_failure);
1509 if (dir_fd < 0)
1510 return dir_fd;
1511
1512 WITH_UMASK(0000) {
1513 mac_selinux_create_file_prepare(path, S_IFREG);
1514 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1515 mac_selinux_create_file_clear();
1516 }
1517
1518 if (fd < 0) {
1519 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1520 * returns EROFS only if it needs to create the file. */
1521 if (fd != -EEXIST)
1522 return log_error_errno(fd, "Failed to create file %s: %m", path);
1523
1524 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1525 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1526 * fd_set_perms() report the error if the perms need to be modified. */
1527 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1528 if (fd < 0)
1529 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1530
1531 if (fstat(fd, &stbuf) < 0)
1532 return log_error_errno(errno, "stat(%s) failed: %m", path);
1533
1534 if (!S_ISREG(stbuf.st_mode))
1535 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1536 "%s exists and is not a regular file.",
1537 path);
1538
1539 st = &stbuf;
1540 creation = CREATION_EXISTING;
1541 } else {
1542 r = write_argument_data(i, fd, path);
1543 if (r < 0)
1544 return r;
1545
1546 creation = CREATION_NORMAL;
1547 }
1548
1549 return fd_set_perms(i, fd, path, st, creation);
1550 }
1551
1552 static int truncate_file(Item *i, const char *path) {
1553 _cleanup_close_ int fd = -EBADF, dir_fd = -EBADF;
1554 _cleanup_free_ char *bn = NULL;
1555 struct stat stbuf, *st = NULL;
1556 CreationMode creation;
1557 bool erofs = false;
1558 int r = 0;
1559
1560 assert(i);
1561 assert(path);
1562 assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
1563
1564 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1565 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1566 * make sure it's a regular one before truncating it. */
1567
1568 r = path_extract_filename(path, &bn);
1569 if (r < 0)
1570 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1571 if (r == O_DIRECTORY)
1572 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
1573
1574 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1575 * can't be changed behind our back. */
1576 dir_fd = path_open_parent_safe(path, i->allow_failure);
1577 if (dir_fd < 0)
1578 return dir_fd;
1579
1580 creation = CREATION_EXISTING;
1581 fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1582 if (fd == -ENOENT) {
1583 creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
1584
1585 WITH_UMASK(0000) {
1586 mac_selinux_create_file_prepare(path, S_IFREG);
1587 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1588 mac_selinux_create_file_clear();
1589 }
1590 }
1591
1592 if (fd < 0) {
1593 if (fd != -EROFS)
1594 return log_error_errno(fd, "Failed to open/create file %s: %m", path);
1595
1596 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1597 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1598 * fail with EROFS if they try to modify the target file. */
1599
1600 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1601 if (fd < 0) {
1602 if (errno == ENOENT)
1603 return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1604 "Cannot create file %s on a read-only file system.",
1605 path);
1606
1607 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1608 }
1609
1610 erofs = true;
1611 creation = CREATION_EXISTING;
1612 }
1613
1614 if (fstat(fd, &stbuf) < 0)
1615 return log_error_errno(errno, "stat(%s) failed: %m", path);
1616
1617 if (!S_ISREG(stbuf.st_mode))
1618 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1619 "%s exists and is not a regular file.",
1620 path);
1621
1622 if (stbuf.st_size > 0) {
1623 if (ftruncate(fd, 0) < 0) {
1624 r = erofs ? -EROFS : -errno;
1625 return log_error_errno(r, "Failed to truncate file %s: %m", path);
1626 }
1627 } else
1628 st = &stbuf;
1629
1630 log_debug("\"%s\" has been created.", path);
1631
1632 if (item_binary_argument(i)) {
1633 r = write_argument_data(i, fd, path);
1634 if (r < 0)
1635 return r;
1636 }
1637
1638 return fd_set_perms(i, fd, path, st, creation);
1639 }
1640
1641 static int copy_files(Item *i) {
1642 _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
1643 _cleanup_free_ char *bn = NULL;
1644 struct stat st, a;
1645 int r;
1646
1647 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
1648
1649 r = path_extract_filename(i->path, &bn);
1650 if (r < 0)
1651 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
1652
1653 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1654 * path can't be changed behind our back. */
1655 dfd = path_open_parent_safe(i->path, i->allow_failure);
1656 if (dfd < 0)
1657 return dfd;
1658
1659 r = copy_tree_at(AT_FDCWD, i->argument,
1660 dfd, bn,
1661 i->uid_set ? i->uid : UID_INVALID,
1662 i->gid_set ? i->gid : GID_INVALID,
1663 COPY_REFLINK | COPY_MERGE_EMPTY | COPY_MAC_CREATE | COPY_HARDLINKS,
1664 NULL);
1665
1666 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1667 if (fd < 0) {
1668 if (r < 0) /* Look at original error first */
1669 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
1670
1671 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1672 }
1673
1674 if (fstat(fd, &st) < 0)
1675 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1676
1677 if (stat(i->argument, &a) < 0)
1678 return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
1679
1680 if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
1681 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1682 return 0;
1683 }
1684
1685 return fd_set_perms(i, fd, i->path, &st, _CREATION_MODE_INVALID);
1686 }
1687
1688 static int create_directory_or_subvolume(
1689 const char *path,
1690 mode_t mode,
1691 bool subvol,
1692 bool allow_failure,
1693 struct stat *ret_st,
1694 CreationMode *ret_creation) {
1695
1696 _cleanup_free_ char *bn = NULL;
1697 _cleanup_close_ int pfd = -EBADF;
1698 CreationMode creation;
1699 struct stat st;
1700 int r, fd;
1701
1702 assert(path);
1703
1704 r = path_extract_filename(path, &bn);
1705 if (r < 0)
1706 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1707
1708 pfd = path_open_parent_safe(path, allow_failure);
1709 if (pfd < 0)
1710 return pfd;
1711
1712 if (subvol) {
1713 r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1714 if (r < 0) {
1715 if (r != -ENXIO) /* env var is unset */
1716 log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1717 r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
1718 }
1719 if (r == 0)
1720 /* Don't create a subvolume unless the root directory is one, too. We do this under
1721 * the assumption that if the root directory is just a plain directory (i.e. very
1722 * light-weight), we shouldn't try to split it up into subvolumes (i.e. more
1723 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1724 * subvolume set up below their tree only if they specifically set up a btrfs
1725 * subvolume for the root dir too. */
1726
1727 subvol = false;
1728 else {
1729 WITH_UMASK((~mode) & 0777)
1730 r = btrfs_subvol_make_fd(pfd, bn);
1731 }
1732 } else
1733 r = 0;
1734
1735 if (!subvol || ERRNO_IS_NOT_SUPPORTED(r))
1736 WITH_UMASK(0000)
1737 r = mkdirat_label(pfd, bn, mode);
1738
1739 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1740
1741 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
1742 if (fd < 0) {
1743 /* We couldn't open it because it is not actually a directory? */
1744 if (errno == ENOTDIR)
1745 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
1746
1747 /* Then look at the original error */
1748 if (r < 0)
1749 return log_full_errno(allow_failure ? LOG_INFO : LOG_ERR,
1750 r,
1751 "Failed to create directory or subvolume \"%s\"%s: %m",
1752 path,
1753 allow_failure ? ", ignoring" : "");
1754
1755 return log_error_errno(errno, "Failed to open directory/subvolume we just created '%s': %m", path);
1756 }
1757
1758 if (fstat(fd, &st) < 0)
1759 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
1760
1761 assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
1762
1763 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
1764
1765 if (ret_st)
1766 *ret_st = st;
1767 if (ret_creation)
1768 *ret_creation = creation;
1769
1770 return fd;
1771 }
1772
1773 static int create_directory(Item *i, const char *path) {
1774 _cleanup_close_ int fd = -EBADF;
1775 CreationMode creation;
1776 struct stat st;
1777
1778 assert(i);
1779 assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
1780
1781 fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, i->allow_failure, &st, &creation);
1782 if (fd == -EEXIST)
1783 return 0;
1784 if (fd < 0)
1785 return fd;
1786
1787 return fd_set_perms(i, fd, path, &st, creation);
1788 }
1789
1790 static int create_subvolume(Item *i, const char *path) {
1791 _cleanup_close_ int fd = -EBADF;
1792 CreationMode creation;
1793 struct stat st;
1794 int r, q = 0;
1795
1796 assert(i);
1797 assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
1798
1799 fd = create_directory_or_subvolume(path, i->mode, /* subvol = */ true, i->allow_failure, &st, &creation);
1800 if (fd == -EEXIST)
1801 return 0;
1802 if (fd < 0)
1803 return fd;
1804
1805 if (creation == CREATION_NORMAL &&
1806 IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
1807 r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
1808 if (r == -ENOTTY)
1809 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
1810 else if (r == -EROFS)
1811 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
1812 else if (r == -ENOTCONN)
1813 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
1814 else if (r < 0)
1815 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
1816 else if (r > 0)
1817 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
1818 else if (r == 0)
1819 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
1820 }
1821
1822 r = fd_set_perms(i, fd, path, &st, creation);
1823 if (q < 0) /* prefer the quota change error from above */
1824 return q;
1825
1826 return r;
1827 }
1828
1829 static int empty_directory(Item *i, const char *path, CreationMode creation) {
1830 _cleanup_close_ int fd = -EBADF;
1831 struct stat st;
1832 int r;
1833
1834 assert(i);
1835 assert(i->type == EMPTY_DIRECTORY);
1836
1837 r = chase(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
1838 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
1839 return r;
1840 if (r == -ENOENT) {
1841 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
1842 * or directories */
1843 log_debug_errno(r, "Skipping missing directory: %s", path);
1844 return 0;
1845 }
1846 if (r < 0)
1847 return log_error_errno(r, "Failed to open directory '%s': %m", path);
1848
1849 if (fstat(fd, &st) < 0)
1850 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
1851 if (!S_ISDIR(st.st_mode)) {
1852 log_warning("'%s' already exists and is not a directory.", path);
1853 return 0;
1854 }
1855
1856 return fd_set_perms(i, fd, path, &st, creation);
1857 }
1858
1859 static int create_device(Item *i, mode_t file_type) {
1860 _cleanup_close_ int dfd = -EBADF, fd = -EBADF;
1861 _cleanup_free_ char *bn = NULL;
1862 CreationMode creation;
1863 struct stat st;
1864 int r;
1865
1866 assert(i);
1867 assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
1868 assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1869
1870 r = path_extract_filename(i->path, &bn);
1871 if (r < 0)
1872 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
1873 if (r == O_DIRECTORY)
1874 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating device node, is a directory.", i->path);
1875
1876 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1877 * path can't be changed behind our back. */
1878 dfd = path_open_parent_safe(i->path, i->allow_failure);
1879 if (dfd < 0)
1880 return dfd;
1881
1882 WITH_UMASK(0000) {
1883 mac_selinux_create_file_prepare(i->path, file_type);
1884 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
1885 mac_selinux_create_file_clear();
1886 }
1887 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1888
1889 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
1890 * order anyway and we hence can ignore the error to create the device node */
1891 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1892 if (fd < 0) {
1893 /* OK, so opening the inode failed, let's look at the original error then. */
1894
1895 if (r < 0) {
1896 if (ERRNO_IS_PRIVILEGE(r))
1897 goto handle_privilege;
1898
1899 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
1900 }
1901
1902 return log_error_errno(errno, "Failed to open device node '%s' we just created: %m", i->path);
1903 }
1904
1905 if (fstat(fd, &st) < 0)
1906 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1907
1908 if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
1909
1910 if (i->append_or_force) {
1911 fd = safe_close(fd);
1912
1913 WITH_UMASK(0000) {
1914 mac_selinux_create_file_prepare(i->path, file_type);
1915 r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
1916 mac_selinux_create_file_clear();
1917 }
1918 if (ERRNO_IS_PRIVILEGE(r))
1919 goto handle_privilege;
1920 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1921 r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
1922 if (r < 0)
1923 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
1924
1925 mac_selinux_create_file_prepare(i->path, file_type);
1926 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
1927 mac_selinux_create_file_clear();
1928 }
1929 if (r < 0)
1930 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
1931
1932 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1933 if (fd < 0)
1934 return log_error_errno(errno, "Failed to open device node we just created '%s': %m", i->path);
1935
1936 /* Validate type before change ownership below */
1937 if (fstat(fd, &st) < 0)
1938 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1939
1940 if (((st.st_mode ^ file_type) & S_IFMT) != 0)
1941 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Device node we just created is not a device node, refusing.");
1942
1943 creation = CREATION_FORCE;
1944 } else {
1945 log_warning("\"%s\" already exists and is not a device node.", i->path);
1946 return 0;
1947 }
1948 }
1949
1950 log_debug("%s %s device node \"%s\" %u:%u.",
1951 creation_mode_verb_to_string(creation),
1952 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1953 i->path, major(i->mode), minor(i->mode));
1954
1955 return fd_set_perms(i, fd, i->path, &st, creation);
1956
1957 handle_privilege:
1958 log_debug_errno(r,
1959 "We lack permissions, possibly because of cgroup configuration; "
1960 "skipping creation of device node '%s'.", i->path);
1961 return 0;
1962 }
1963
1964 static int create_fifo(Item *i) {
1965 _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
1966 _cleanup_free_ char *bn = NULL;
1967 CreationMode creation;
1968 struct stat st;
1969 int r;
1970
1971 assert(i);
1972 assert(i->type == CREATE_FIFO);
1973
1974 r = path_extract_filename(i->path, &bn);
1975 if (r < 0)
1976 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
1977 if (r == O_DIRECTORY)
1978 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
1979
1980 pfd = path_open_parent_safe(i->path, i->allow_failure);
1981 if (pfd < 0)
1982 return pfd;
1983
1984 WITH_UMASK(0000) {
1985 mac_selinux_create_file_prepare(i->path, S_IFIFO);
1986 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
1987 mac_selinux_create_file_clear();
1988 }
1989
1990 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
1991
1992 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is already the FIFO we want */
1993 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1994 if (fd < 0) {
1995 if (r < 0)
1996 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path); /* original error! */
1997
1998 return log_error_errno(errno, "Failed to open FIFO we just created %s: %m", i->path);
1999 }
2000
2001 if (fstat(fd, &st) < 0)
2002 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2003
2004 if (!S_ISFIFO(st.st_mode)) {
2005
2006 if (i->append_or_force) {
2007 fd = safe_close(fd);
2008
2009 WITH_UMASK(0000) {
2010 mac_selinux_create_file_prepare(i->path, S_IFIFO);
2011 r = mkfifoat_atomic(pfd, bn, i->mode);
2012 mac_selinux_create_file_clear();
2013 }
2014 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2015 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
2016 if (r < 0)
2017 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2018
2019 mac_selinux_create_file_prepare(i->path, S_IFIFO);
2020 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
2021 mac_selinux_create_file_clear();
2022 }
2023 if (r < 0)
2024 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
2025
2026 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2027 if (fd < 0)
2028 return log_error_errno(errno, "Failed to open FIFO we just created '%s': %m", i->path);
2029
2030 /* Validate type before change ownership below */
2031 if (fstat(fd, &st) < 0)
2032 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2033
2034 if (!S_ISFIFO(st.st_mode))
2035 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "FIFO inode we just created is not a FIFO, refusing.");
2036
2037 creation = CREATION_FORCE;
2038 } else {
2039 log_warning("\"%s\" already exists and is not a FIFO.", i->path);
2040 return 0;
2041 }
2042 }
2043
2044 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
2045
2046 return fd_set_perms(i, fd, i->path, &st, creation);
2047 }
2048
2049 static int create_symlink(Item *i) {
2050 _cleanup_close_ int pfd = -EBADF, fd = -EBADF;
2051 _cleanup_free_ char *bn = NULL;
2052 CreationMode creation;
2053 struct stat st;
2054 bool good = false;
2055 int r;
2056
2057 assert(i);
2058
2059 r = path_extract_filename(i->path, &bn);
2060 if (r < 0)
2061 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
2062 if (r == O_DIRECTORY)
2063 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2064
2065 pfd = path_open_parent_safe(i->path, i->allow_failure);
2066 if (pfd < 0)
2067 return pfd;
2068
2069 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2070 r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
2071 mac_selinux_create_file_clear();
2072
2073 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2074
2075 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2076 if (fd < 0) {
2077 if (r < 0)
2078 return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
2079
2080 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2081 }
2082
2083 if (fstat(fd, &st) < 0)
2084 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2085
2086 if (S_ISLNK(st.st_mode)) {
2087 _cleanup_free_ char *x = NULL;
2088
2089 r = readlinkat_malloc(fd, "", &x);
2090 if (r < 0)
2091 return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
2092
2093 good = streq(x, i->argument);
2094 } else
2095 good = false;
2096
2097 if (!good) {
2098 if (!i->append_or_force) {
2099 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
2100 return 0;
2101 }
2102
2103 fd = safe_close(fd);
2104
2105 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2106 r = symlinkat_atomic_full(i->argument, pfd, bn, /* make_relative= */ false);
2107 mac_selinux_create_file_clear();
2108 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2109 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
2110 if (r < 0)
2111 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2112
2113 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2114 r = RET_NERRNO(symlinkat(i->argument, pfd, i->path));
2115 mac_selinux_create_file_clear();
2116 }
2117 if (r < 0)
2118 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
2119
2120 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2121 if (fd < 0)
2122 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2123
2124 /* Validate type before change ownership below */
2125 if (fstat(fd, &st) < 0)
2126 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2127
2128 if (!S_ISLNK(st.st_mode))
2129 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
2130
2131 creation = CREATION_FORCE;
2132 }
2133
2134 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
2135 return fd_set_perms(i, fd, i->path, &st, creation);
2136 }
2137
2138 typedef int (*action_t)(Item *i, const char *path, CreationMode creation);
2139 typedef int (*fdaction_t)(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2140
2141 static int item_do(
2142 Item *i,
2143 int fd,
2144 const char *path,
2145 CreationMode creation,
2146 fdaction_t action) {
2147
2148 struct stat st;
2149 int r = 0, q;
2150
2151 assert(i);
2152 assert(path);
2153 assert(fd >= 0);
2154
2155 if (fstat(fd, &st) < 0) {
2156 r = log_error_errno(errno, "fstat() on file failed: %m");
2157 goto finish;
2158 }
2159
2160 /* This returns the first error we run into, but nevertheless tries to go on */
2161 r = action(i, fd, path, &st, creation);
2162
2163 if (S_ISDIR(st.st_mode)) {
2164 _cleanup_closedir_ DIR *d = NULL;
2165
2166 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2167 * reading the directory content. */
2168 d = opendir(FORMAT_PROC_FD_PATH(fd));
2169 if (!d) {
2170 log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd));
2171 if (r == 0)
2172 r = -errno;
2173 goto finish;
2174 }
2175
2176 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
2177 int de_fd;
2178
2179 if (dot_or_dot_dot(de->d_name))
2180 continue;
2181
2182 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2183 if (de_fd < 0)
2184 q = log_error_errno(errno, "Failed to open() file '%s': %m", de->d_name);
2185 else {
2186 _cleanup_free_ char *de_path = NULL;
2187
2188 de_path = path_join(path, de->d_name);
2189 if (!de_path)
2190 q = log_oom();
2191 else
2192 /* Pass ownership of dirent fd over */
2193 q = item_do(i, de_fd, de_path, CREATION_EXISTING, action);
2194 }
2195
2196 if (q < 0 && r == 0)
2197 r = q;
2198 }
2199 }
2200 finish:
2201 safe_close(fd);
2202 return r;
2203 }
2204
2205 static int glob_item(Item *i, action_t action) {
2206 _cleanup_globfree_ glob_t g = {
2207 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2208 };
2209 int r = 0, k;
2210
2211 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2212 if (k < 0 && k != -ENOENT)
2213 return log_error_errno(k, "glob(%s) failed: %m", i->path);
2214
2215 STRV_FOREACH(fn, g.gl_pathv) {
2216 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2217 k = action(i, *fn, CREATION_EXISTING);
2218 if (k < 0 && r == 0)
2219 r = k;
2220 }
2221
2222 return r;
2223 }
2224
2225 static int glob_item_recursively(Item *i, fdaction_t action) {
2226 _cleanup_globfree_ glob_t g = {
2227 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2228 };
2229 int r = 0, k;
2230
2231 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2232 if (k < 0 && k != -ENOENT)
2233 return log_error_errno(k, "glob(%s) failed: %m", i->path);
2234
2235 STRV_FOREACH(fn, g.gl_pathv) {
2236 _cleanup_close_ int fd = -EBADF;
2237
2238 /* Make sure we won't trigger/follow file object (such as
2239 * device nodes, automounts, ...) pointed out by 'fn' with
2240 * O_PATH. Note, when O_PATH is used, flags other than
2241 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2242
2243 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
2244 if (fd < 0) {
2245 log_error_errno(errno, "Opening '%s' failed: %m", *fn);
2246 if (r == 0)
2247 r = -errno;
2248 continue;
2249 }
2250
2251 k = item_do(i, fd, *fn, CREATION_EXISTING, action);
2252 if (k < 0 && r == 0)
2253 r = k;
2254
2255 /* we passed fd ownership to the previous call */
2256 fd = -EBADF;
2257 }
2258
2259 return r;
2260 }
2261
2262 static int rm_if_wrong_type_safe(
2263 mode_t mode,
2264 int parent_fd,
2265 const struct stat *parent_st, /* Only used if follow_links below is true. */
2266 const char *name,
2267 int flags) {
2268 _cleanup_free_ char *parent_name = NULL;
2269 bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
2270 struct stat st;
2271 int r;
2272
2273 assert(name);
2274 assert((mode & ~S_IFMT) == 0);
2275 assert(!follow_links || parent_st);
2276 assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
2277
2278 if (!filename_is_valid(name))
2279 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
2280
2281 r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2282 if (r < 0) {
2283 (void) fd_get_path(parent_fd, &parent_name);
2284 return log_full_errno(r == -ENOENT? LOG_DEBUG : LOG_ERR, r,
2285 "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2286 }
2287
2288 /* Fail before removing anything if this is an unsafe transition. */
2289 if (follow_links && unsafe_transition(parent_st, &st)) {
2290 (void) fd_get_path(parent_fd, &parent_name);
2291 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
2292 "Unsafe transition from \"%s\" to \"%s\".", parent_name, name);
2293 }
2294
2295 if ((st.st_mode & S_IFMT) == mode)
2296 return 0;
2297
2298 (void) fd_get_path(parent_fd, &parent_name);
2299 log_notice("Wrong file type 0o%o; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, strna(parent_name), name);
2300
2301 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2302 * target, so make sure it is identified as a link and not a directory. */
2303 if (follow_links) {
2304 r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2305 if (r < 0)
2306 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2307 }
2308
2309 /* Do not remove mount points. */
2310 r = fd_is_mount_point(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
2311 if (r < 0)
2312 (void) log_warning_errno(r, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2313 strna(parent_name), name);
2314 else if (r > 0)
2315 return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
2316 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name), name);
2317
2318 if ((st.st_mode & S_IFMT) == S_IFDIR) {
2319 _cleanup_close_ int child_fd = -EBADF;
2320
2321 child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2322 if (child_fd < 0)
2323 return log_error_errno(errno, "Failed to open \"%s\" at \"%s\": %m", name, strna(parent_name));
2324
2325 r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);
2326 if (r < 0)
2327 return log_error_errno(r, "Failed to remove contents of \"%s\" at \"%s\": %m", name, strna(parent_name));
2328
2329 r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2330 } else
2331 r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2332 if (r < 0)
2333 return log_error_errno(r, "Failed to remove \"%s\" at \"%s\": %m", name, strna(parent_name));
2334
2335 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2336 * context to other error messages that might follow. */
2337 return -ENOENT;
2338 }
2339
2340 /* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2341 static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
2342 _cleanup_close_ int parent_fd = -EBADF;
2343 struct stat parent_st;
2344 size_t path_len;
2345 int r;
2346
2347 assert(path);
2348 assert((child_mode & ~S_IFMT) == 0);
2349
2350 path_len = strlen(path);
2351
2352 if (!is_path(path))
2353 /* rm_if_wrong_type_safe already logs errors. */
2354 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW) : 0;
2355
2356 if (child_mode != 0 && endswith(path, "/"))
2357 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2358 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2359
2360 /* Get the parent_fd and stat. */
2361 parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2362 if (parent_fd < 0)
2363 return log_error_errno(errno, "Failed to open root: %m");
2364
2365 if (fstat(parent_fd, &parent_st) < 0)
2366 return log_error_errno(errno, "Failed to stat root: %m");
2367
2368 /* Check every parent directory in the path, except the last component */
2369 for (const char *e = path;;) {
2370 _cleanup_close_ int next_fd = -EBADF;
2371 char t[path_len + 1];
2372 const char *s;
2373
2374 /* Find the start of the next path component. */
2375 s = e + strspn(e, "/");
2376 /* Find the end of the next path component. */
2377 e = s + strcspn(s, "/");
2378
2379 /* Copy the path component to t so it can be a null terminated string. */
2380 *((char*) mempcpy(t, s, e - s)) = 0;
2381
2382 /* Is this the last component? If so, then check the type */
2383 if (*e == 0)
2384 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW) : 0;
2385
2386 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
2387 /* Remove dangling symlinks. */
2388 if (r == -ENOENT)
2389 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
2390 if (r == -ENOENT) {
2391 WITH_UMASK(0000)
2392 r = mkdirat_label(parent_fd, t, 0755);
2393 if (r < 0) {
2394 _cleanup_free_ char *parent_name = NULL;
2395
2396 (void) fd_get_path(parent_fd, &parent_name);
2397 return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
2398 }
2399 } else if (r < 0)
2400 /* rm_if_wrong_type_safe already logs errors. */
2401 return r;
2402
2403 next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
2404 if (next_fd < 0) {
2405 _cleanup_free_ char *parent_name = NULL;
2406
2407 (void) fd_get_path(parent_fd, &parent_name);
2408 return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
2409 }
2410 r = RET_NERRNO(fstat(next_fd, &parent_st));
2411 if (r < 0) {
2412 _cleanup_free_ char *parent_name = NULL;
2413
2414 (void) fd_get_path(parent_fd, &parent_name);
2415 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
2416 }
2417
2418 close_and_replace(parent_fd, next_fd);
2419 }
2420 }
2421
2422 static int mkdir_parents_item(Item *i, mode_t child_mode) {
2423 int r;
2424 if (i->try_replace) {
2425 r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
2426 if (r < 0 && r != -ENOENT)
2427 return r;
2428 } else
2429 WITH_UMASK(0000)
2430 (void) mkdir_parents_label(i->path, 0755);
2431
2432 return 0;
2433 }
2434
2435 static int create_item(Item *i) {
2436 int r;
2437
2438 assert(i);
2439
2440 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
2441
2442 switch (i->type) {
2443
2444 case IGNORE_PATH:
2445 case IGNORE_DIRECTORY_PATH:
2446 case REMOVE_PATH:
2447 case RECURSIVE_REMOVE_PATH:
2448 return 0;
2449
2450 case TRUNCATE_FILE:
2451 case CREATE_FILE:
2452 r = mkdir_parents_item(i, S_IFREG);
2453 if (r < 0)
2454 return r;
2455
2456 if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
2457 r = truncate_file(i, i->path);
2458 else
2459 r = create_file(i, i->path);
2460 if (r < 0)
2461 return r;
2462 break;
2463
2464 case COPY_FILES:
2465 r = mkdir_parents_item(i, 0);
2466 if (r < 0)
2467 return r;
2468
2469 r = copy_files(i);
2470 if (r < 0)
2471 return r;
2472 break;
2473
2474 case WRITE_FILE:
2475 r = glob_item(i, write_one_file);
2476 if (r < 0)
2477 return r;
2478
2479 break;
2480
2481 case CREATE_DIRECTORY:
2482 case TRUNCATE_DIRECTORY:
2483 r = mkdir_parents_item(i, S_IFDIR);
2484 if (r < 0)
2485 return r;
2486
2487 r = create_directory(i, i->path);
2488 if (r < 0)
2489 return r;
2490 break;
2491
2492 case CREATE_SUBVOLUME:
2493 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2494 case CREATE_SUBVOLUME_NEW_QUOTA:
2495 r = mkdir_parents_item(i, S_IFDIR);
2496 if (r < 0)
2497 return r;
2498
2499 r = create_subvolume(i, i->path);
2500 if (r < 0)
2501 return r;
2502 break;
2503
2504 case EMPTY_DIRECTORY:
2505 r = glob_item(i, empty_directory);
2506 if (r < 0)
2507 return r;
2508 break;
2509
2510 case CREATE_FIFO:
2511 r = mkdir_parents_item(i, S_IFIFO);
2512 if (r < 0)
2513 return r;
2514
2515 r = create_fifo(i);
2516 if (r < 0)
2517 return r;
2518 break;
2519
2520 case CREATE_SYMLINK:
2521 r = mkdir_parents_item(i, S_IFLNK);
2522 if (r < 0)
2523 return r;
2524
2525 r = create_symlink(i);
2526 if (r < 0)
2527 return r;
2528
2529 break;
2530
2531 case CREATE_BLOCK_DEVICE:
2532 case CREATE_CHAR_DEVICE:
2533 if (have_effective_cap(CAP_MKNOD) <= 0) {
2534 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2535 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2536
2537 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
2538 return 0;
2539 }
2540
2541 r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2542 if (r < 0)
2543 return r;
2544
2545 r = create_device(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2546 if (r < 0)
2547 return r;
2548
2549 break;
2550
2551 case ADJUST_MODE:
2552 case RELABEL_PATH:
2553 r = glob_item(i, path_set_perms);
2554 if (r < 0)
2555 return r;
2556 break;
2557
2558 case RECURSIVE_RELABEL_PATH:
2559 r = glob_item_recursively(i, fd_set_perms);
2560 if (r < 0)
2561 return r;
2562 break;
2563
2564 case SET_XATTR:
2565 r = glob_item(i, path_set_xattrs);
2566 if (r < 0)
2567 return r;
2568 break;
2569
2570 case RECURSIVE_SET_XATTR:
2571 r = glob_item_recursively(i, fd_set_xattrs);
2572 if (r < 0)
2573 return r;
2574 break;
2575
2576 case SET_ACL:
2577 r = glob_item(i, path_set_acls);
2578 if (r < 0)
2579 return r;
2580 break;
2581
2582 case RECURSIVE_SET_ACL:
2583 r = glob_item_recursively(i, fd_set_acls);
2584 if (r < 0)
2585 return r;
2586 break;
2587
2588 case SET_ATTRIBUTE:
2589 r = glob_item(i, path_set_attribute);
2590 if (r < 0)
2591 return r;
2592 break;
2593
2594 case RECURSIVE_SET_ATTRIBUTE:
2595 r = glob_item_recursively(i, fd_set_attribute);
2596 if (r < 0)
2597 return r;
2598 break;
2599 }
2600
2601 return 0;
2602 }
2603
2604 static int remove_item_instance(Item *i, const char *instance, CreationMode creation) {
2605 int r;
2606
2607 assert(i);
2608
2609 switch (i->type) {
2610
2611 case REMOVE_PATH:
2612 if (remove(instance) < 0 && errno != ENOENT)
2613 return log_error_errno(errno, "rm(%s): %m", instance);
2614
2615 break;
2616
2617 case RECURSIVE_REMOVE_PATH:
2618 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2619 log_debug("rm -rf \"%s\"", instance);
2620 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
2621 if (r < 0 && r != -ENOENT)
2622 return log_error_errno(r, "rm_rf(%s): %m", instance);
2623
2624 break;
2625
2626 default:
2627 assert_not_reached();
2628 }
2629
2630 return 0;
2631 }
2632
2633 static int remove_item(Item *i) {
2634 int r;
2635
2636 assert(i);
2637
2638 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2639
2640 switch (i->type) {
2641
2642 case TRUNCATE_DIRECTORY:
2643 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2644 log_debug("rm -rf \"%s\"", i->path);
2645 r = rm_rf(i->path, REMOVE_PHYSICAL);
2646 if (r < 0 && r != -ENOENT)
2647 return log_error_errno(r, "rm_rf(%s): %m", i->path);
2648
2649 return 0;
2650
2651 case REMOVE_PATH:
2652 case RECURSIVE_REMOVE_PATH:
2653 return glob_item(i, remove_item_instance);
2654
2655 default:
2656 return 0;
2657 }
2658 }
2659
2660 static char *age_by_to_string(AgeBy ab, bool is_dir) {
2661 static const char ab_map[] = { 'a', 'b', 'c', 'm' };
2662 size_t j = 0;
2663 char *ret;
2664
2665 ret = new(char, ELEMENTSOF(ab_map) + 1);
2666 if (!ret)
2667 return NULL;
2668
2669 for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
2670 if (FLAGS_SET(ab, 1U << i))
2671 ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
2672
2673 ret[j] = 0;
2674 return ret;
2675 }
2676
2677 static int clean_item_instance(
2678 Item *i,
2679 const char* instance,
2680 CreationMode creation) {
2681
2682 _cleanup_closedir_ DIR *d = NULL;
2683 STRUCT_STATX_DEFINE(sx);
2684 int mountpoint, r;
2685 usec_t cutoff, n;
2686
2687 assert(i);
2688
2689 if (!i->age_set)
2690 return 0;
2691
2692 n = now(CLOCK_REALTIME);
2693 if (n < i->age)
2694 return 0;
2695
2696 cutoff = n - i->age;
2697
2698 d = opendir_nomod(instance);
2699 if (!d) {
2700 if (IN_SET(errno, ENOENT, ENOTDIR)) {
2701 log_debug_errno(errno, "Directory \"%s\": %m", instance);
2702 return 0;
2703 }
2704
2705 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
2706 }
2707
2708 r = statx_fallback(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx);
2709 if (r < 0)
2710 return log_error_errno(r, "statx(%s) failed: %m", instance);
2711
2712 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
2713 mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
2714 else {
2715 struct stat ps;
2716
2717 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
2718 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
2719
2720 mountpoint =
2721 sx.stx_dev_major != major(ps.st_dev) ||
2722 sx.stx_dev_minor != minor(ps.st_dev) ||
2723 sx.stx_ino != ps.st_ino;
2724 }
2725
2726 if (DEBUG_LOGGING) {
2727 _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
2728
2729 ab_f = age_by_to_string(i->age_by_file, false);
2730 if (!ab_f)
2731 return log_oom();
2732
2733 ab_d = age_by_to_string(i->age_by_dir, true);
2734 if (!ab_d)
2735 return log_oom();
2736
2737 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
2738 mountpoint ? "mount point" : "directory",
2739 instance,
2740 FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
2741 ab_f, ab_d);
2742 }
2743
2744 return dir_cleanup(i, instance, d,
2745 load_statx_timestamp_nsec(&sx.stx_atime),
2746 load_statx_timestamp_nsec(&sx.stx_mtime),
2747 cutoff * NSEC_PER_USEC,
2748 sx.stx_dev_major, sx.stx_dev_minor, mountpoint,
2749 MAX_DEPTH, i->keep_first_level,
2750 i->age_by_file, i->age_by_dir);
2751 }
2752
2753 static int clean_item(Item *i) {
2754 assert(i);
2755
2756 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
2757
2758 switch (i->type) {
2759 case CREATE_DIRECTORY:
2760 case CREATE_SUBVOLUME:
2761 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2762 case CREATE_SUBVOLUME_NEW_QUOTA:
2763 case TRUNCATE_DIRECTORY:
2764 case IGNORE_PATH:
2765 case COPY_FILES:
2766 clean_item_instance(i, i->path, CREATION_EXISTING);
2767 return 0;
2768 case EMPTY_DIRECTORY:
2769 case IGNORE_DIRECTORY_PATH:
2770 return glob_item(i, clean_item_instance);
2771 default:
2772 return 0;
2773 }
2774 }
2775
2776 static int process_item(Item *i, OperationMask operation) {
2777 OperationMask todo;
2778 _cleanup_free_ char *_path = NULL;
2779 const char *path;
2780 int r, q, p;
2781
2782 assert(i);
2783
2784 todo = operation & ~i->done;
2785 if (todo == 0) /* Everything already done? */
2786 return 0;
2787
2788 i->done |= operation;
2789
2790 path = i->path;
2791 if (string_is_glob(path)) {
2792 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
2793 * for the non-glob part. */
2794
2795 r = glob_non_glob_prefix(path, &_path);
2796 if (r < 0 && r != -ENOENT)
2797 return log_debug_errno(r, "Failed to deglob path: %m");
2798 if (r >= 0)
2799 path = _path;
2800 }
2801
2802 r = chase(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
2803 if (r == -EREMOTE) {
2804 log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
2805 return 0;
2806 }
2807 if (r < 0)
2808 log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
2809
2810 r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(i) : 0;
2811 /* Failure can only be tolerated for create */
2812 if (i->allow_failure)
2813 r = 0;
2814
2815 q = FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(i) : 0;
2816 p = FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(i) : 0;
2817
2818 return r < 0 ? r :
2819 q < 0 ? q :
2820 p;
2821 }
2822
2823 static int process_item_array(ItemArray *array, OperationMask operation) {
2824 int r = 0;
2825 size_t n;
2826
2827 assert(array);
2828
2829 /* Create any parent first. */
2830 if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
2831 r = process_item_array(array->parent, operation & OPERATION_CREATE);
2832
2833 /* Clean up all children first */
2834 if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN)) && !set_isempty(array->children)) {
2835 ItemArray *c;
2836
2837 SET_FOREACH(c, array->children) {
2838 int k;
2839
2840 k = process_item_array(c, operation & (OPERATION_REMOVE|OPERATION_CLEAN));
2841 if (k < 0 && r == 0)
2842 r = k;
2843 }
2844 }
2845
2846 for (n = 0; n < array->n_items; n++) {
2847 int k;
2848
2849 k = process_item(array->items + n, operation);
2850 if (k < 0 && r == 0)
2851 r = k;
2852 }
2853
2854 return r;
2855 }
2856
2857 static void item_free_contents(Item *i) {
2858 assert(i);
2859 free(i->path);
2860 free(i->argument);
2861 free(i->binary_argument);
2862 strv_free(i->xattrs);
2863
2864 #if HAVE_ACL
2865 if (i->acl_access)
2866 acl_free(i->acl_access);
2867
2868 if (i->acl_default)
2869 acl_free(i->acl_default);
2870 #endif
2871 }
2872
2873 static ItemArray* item_array_free(ItemArray *a) {
2874 size_t n;
2875
2876 if (!a)
2877 return NULL;
2878
2879 for (n = 0; n < a->n_items; n++)
2880 item_free_contents(a->items + n);
2881
2882 set_free(a->children);
2883 free(a->items);
2884 return mfree(a);
2885 }
2886
2887 static int item_compare(const Item *a, const Item *b) {
2888 /* Make sure that the ownership taking item is put first, so
2889 * that we first create the node, and then can adjust it */
2890
2891 if (takes_ownership(a->type) && !takes_ownership(b->type))
2892 return -1;
2893 if (!takes_ownership(a->type) && takes_ownership(b->type))
2894 return 1;
2895
2896 return CMP(a->type, b->type);
2897 }
2898
2899 static bool item_compatible(const Item *a, const Item *b) {
2900 assert(a);
2901 assert(b);
2902 assert(streq(a->path, b->path));
2903
2904 if (takes_ownership(a->type) && takes_ownership(b->type))
2905 /* check if the items are the same */
2906 return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
2907 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
2908
2909 a->uid_set == b->uid_set &&
2910 a->uid == b->uid &&
2911 a->uid_only_create == b->uid_only_create &&
2912
2913 a->gid_set == b->gid_set &&
2914 a->gid == b->gid &&
2915 a->gid_only_create == b->gid_only_create &&
2916
2917 a->mode_set == b->mode_set &&
2918 a->mode == b->mode &&
2919 a->mode_only_create == b->mode_only_create &&
2920
2921 a->age_set == b->age_set &&
2922 a->age == b->age &&
2923
2924 a->age_by_file == b->age_by_file &&
2925 a->age_by_dir == b->age_by_dir &&
2926
2927 a->mask_perms == b->mask_perms &&
2928
2929 a->keep_first_level == b->keep_first_level &&
2930
2931 a->major_minor == b->major_minor;
2932
2933 return true;
2934 }
2935
2936 static bool should_include_path(const char *path) {
2937 STRV_FOREACH(prefix, arg_exclude_prefixes)
2938 if (path_startswith(path, *prefix)) {
2939 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2940 path, *prefix);
2941 return false;
2942 }
2943
2944 STRV_FOREACH(prefix, arg_include_prefixes)
2945 if (path_startswith(path, *prefix)) {
2946 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
2947 return true;
2948 }
2949
2950 /* no matches, so we should include this path only if we have no allow list at all */
2951 if (strv_isempty(arg_include_prefixes))
2952 return true;
2953
2954 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
2955 return false;
2956 }
2957
2958 static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
2959 int r;
2960
2961 assert(i);
2962
2963 if (!i->argument)
2964 return 0;
2965
2966 switch (i->type) {
2967 case COPY_FILES:
2968 case CREATE_SYMLINK:
2969 case CREATE_FILE:
2970 case TRUNCATE_FILE:
2971 case WRITE_FILE: {
2972 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2973 ssize_t l;
2974
2975 l = cunescape(i->argument, 0, &unescaped);
2976 if (l < 0)
2977 return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
2978
2979 r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
2980 if (r < 0)
2981 return r;
2982
2983 return free_and_replace(i->argument, resolved);
2984 }
2985 case SET_XATTR:
2986 case RECURSIVE_SET_XATTR:
2987 STRV_FOREACH(xattr, i->xattrs) {
2988 _cleanup_free_ char *resolved = NULL;
2989
2990 r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
2991 if (r < 0)
2992 return r;
2993
2994 free_and_replace(*xattr, resolved);
2995 }
2996 return 0;
2997
2998 default:
2999 return 0;
3000 }
3001 }
3002
3003 static int patch_var_run(const char *fname, unsigned line, char **path) {
3004 const char *k;
3005 char *n;
3006
3007 assert(path);
3008 assert(*path);
3009
3010 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
3011 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
3012 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
3013 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
3014 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
3015 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
3016 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
3017 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
3018 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
3019
3020 k = path_startswith(*path, "/var/run/");
3021 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
3022 return 0;
3023
3024 n = path_join("/run", k);
3025 if (!n)
3026 return log_oom();
3027
3028 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
3029 * there's no immediate need for action by the user. However, in the interest of making things less confusing
3030 * to the user, let's still inform the user that these snippets should really be updated. */
3031 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3032 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3033 *path, n);
3034
3035 free_and_replace(*path, n);
3036
3037 return 0;
3038 }
3039
3040 static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
3041 int r;
3042
3043 assert(user);
3044 assert(ret_uid);
3045
3046 /* First: parse as numeric UID string */
3047 r = parse_uid(user, ret_uid);
3048 if (r >= 0)
3049 return r;
3050
3051 /* Second: pass to NSS if we are running "online" */
3052 if (!arg_root)
3053 return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
3054
3055 /* Third, synthesize "root" unconditionally */
3056 if (streq(user, "root")) {
3057 *ret_uid = 0;
3058 return 0;
3059 }
3060
3061 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3062 return name_to_uid_offline(arg_root, user, ret_uid, cache);
3063 }
3064
3065 static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
3066 int r;
3067
3068 assert(group);
3069 assert(ret_gid);
3070
3071 /* First: parse as numeric GID string */
3072 r = parse_gid(group, ret_gid);
3073 if (r >= 0)
3074 return r;
3075
3076 /* Second: pass to NSS if we are running "online" */
3077 if (!arg_root)
3078 return get_group_creds(&group, ret_gid, 0);
3079
3080 /* Third, synthesize "root" unconditionally */
3081 if (streq(group, "root")) {
3082 *ret_gid = 0;
3083 return 0;
3084 }
3085
3086 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3087 return name_to_gid_offline(arg_root, group, ret_gid, cache);
3088 }
3089
3090 static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
3091 AgeBy ab_f = 0, ab_d = 0;
3092
3093 static const struct {
3094 char age_by_chr;
3095 AgeBy age_by_flag;
3096 } age_by_types[] = {
3097 { 'a', AGE_BY_ATIME },
3098 { 'b', AGE_BY_BTIME },
3099 { 'c', AGE_BY_CTIME },
3100 { 'm', AGE_BY_MTIME },
3101 };
3102
3103 assert(age_by_str);
3104 assert(item);
3105
3106 if (isempty(age_by_str))
3107 return -EINVAL;
3108
3109 for (const char *s = age_by_str; *s != 0; s++) {
3110 size_t i;
3111
3112 /* Ignore whitespace. */
3113 if (strchr(WHITESPACE, *s))
3114 continue;
3115
3116 for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
3117 /* Check lower-case for files, upper-case for directories. */
3118 if (*s == age_by_types[i].age_by_chr) {
3119 ab_f |= age_by_types[i].age_by_flag;
3120 break;
3121 } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
3122 ab_d |= age_by_types[i].age_by_flag;
3123 break;
3124 }
3125 }
3126
3127 /* Invalid character. */
3128 if (i >= ELEMENTSOF(age_by_types))
3129 return -EINVAL;
3130 }
3131
3132 /* No match. */
3133 if (ab_f == 0 && ab_d == 0)
3134 return -EINVAL;
3135
3136 item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
3137 item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
3138
3139 return 0;
3140 }
3141
3142 static bool is_duplicated_item(ItemArray *existing, const Item *i) {
3143
3144 assert(existing);
3145 assert(i);
3146
3147 for (size_t n = 0; n < existing->n_items; n++) {
3148 const Item *e = existing->items + n;
3149
3150 if (item_compatible(e, i))
3151 continue;
3152
3153 /* Only multiple 'w+' lines for the same path are allowed. */
3154 if (e->type != WRITE_FILE || !e->append_or_force ||
3155 i->type != WRITE_FILE || !i->append_or_force)
3156 return true;
3157 }
3158
3159 return false;
3160 }
3161
3162 static int parse_line(
3163 const char *fname,
3164 unsigned line,
3165 const char *buffer,
3166 bool *invalid_config,
3167 Hashmap **uid_cache,
3168 Hashmap **gid_cache) {
3169
3170 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
3171 _cleanup_(item_free_contents) Item i = {
3172 /* The "age-by" argument considers all file timestamp types by default. */
3173 .age_by_file = AGE_BY_DEFAULT_FILE,
3174 .age_by_dir = AGE_BY_DEFAULT_DIR,
3175 };
3176 ItemArray *existing;
3177 OrderedHashmap *h;
3178 int r, pos;
3179 bool append_or_force = false, boot = false, allow_failure = false, try_replace = false, unbase64 = false, from_cred = false;
3180
3181 assert(fname);
3182 assert(line >= 1);
3183 assert(buffer);
3184
3185 const Specifier specifier_table[] = {
3186 { 'a', specifier_architecture, NULL },
3187 { 'b', specifier_boot_id, NULL },
3188 { 'B', specifier_os_build_id, NULL },
3189 { 'H', specifier_hostname, NULL },
3190 { 'l', specifier_short_hostname, NULL },
3191 { 'm', specifier_machine_id, NULL },
3192 { 'o', specifier_os_id, NULL },
3193 { 'v', specifier_kernel_release, NULL },
3194 { 'w', specifier_os_version_id, NULL },
3195 { 'W', specifier_os_variant_id, NULL },
3196
3197 { 'h', specifier_user_home, NULL },
3198
3199 { 'C', specifier_directory, UINT_TO_PTR(DIRECTORY_CACHE) },
3200 { 'L', specifier_directory, UINT_TO_PTR(DIRECTORY_LOGS) },
3201 { 'S', specifier_directory, UINT_TO_PTR(DIRECTORY_STATE) },
3202 { 't', specifier_directory, UINT_TO_PTR(DIRECTORY_RUNTIME) },
3203
3204 COMMON_CREDS_SPECIFIERS(arg_runtime_scope),
3205 COMMON_TMP_SPECIFIERS,
3206 {}
3207 };
3208
3209 r = extract_many_words(
3210 &buffer,
3211 NULL,
3212 EXTRACT_UNQUOTE,
3213 &action,
3214 &path,
3215 &mode,
3216 &user,
3217 &group,
3218 &age,
3219 NULL);
3220 if (r < 0) {
3221 if (IN_SET(r, -EINVAL, -EBADSLT))
3222 /* invalid quoting and such or an unknown specifier */
3223 *invalid_config = true;
3224 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
3225 } else if (r < 2) {
3226 *invalid_config = true;
3227 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
3228 }
3229
3230 if (!empty_or_dash(buffer)) {
3231 i.argument = strdup(buffer);
3232 if (!i.argument)
3233 return log_oom();
3234 }
3235
3236 if (isempty(action)) {
3237 *invalid_config = true;
3238 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Command too short '%s'.", action);
3239 }
3240
3241 for (pos = 1; action[pos]; pos++) {
3242 if (action[pos] == '!' && !boot)
3243 boot = true;
3244 else if (action[pos] == '+' && !append_or_force)
3245 append_or_force = true;
3246 else if (action[pos] == '-' && !allow_failure)
3247 allow_failure = true;
3248 else if (action[pos] == '=' && !try_replace)
3249 try_replace = true;
3250 else if (action[pos] == '~' && !unbase64)
3251 unbase64 = true;
3252 else if (action[pos] == '^' && !from_cred)
3253 from_cred = true;
3254 else {
3255 *invalid_config = true;
3256 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Unknown modifiers in command '%s'", action);
3257 }
3258 }
3259
3260 if (boot && !arg_boot) {
3261 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
3262 return 0;
3263 }
3264
3265 i.type = action[0];
3266 i.append_or_force = append_or_force;
3267 i.allow_failure = allow_failure;
3268 i.try_replace = try_replace;
3269
3270 r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
3271 if (ERRNO_IS_NOINFO(r))
3272 return log_unresolvable_specifier(fname, line);
3273 if (r < 0) {
3274 if (IN_SET(r, -EINVAL, -EBADSLT))
3275 *invalid_config = true;
3276 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", path);
3277 }
3278
3279 r = patch_var_run(fname, line, &i.path);
3280 if (r < 0)
3281 return r;
3282
3283 if (!path_is_absolute(i.path)) {
3284 *invalid_config = true;
3285 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3286 "Path '%s' not absolute.", i.path);
3287 }
3288
3289 path_simplify(i.path);
3290
3291 switch (i.type) {
3292
3293 case CREATE_DIRECTORY:
3294 case CREATE_SUBVOLUME:
3295 case CREATE_SUBVOLUME_INHERIT_QUOTA:
3296 case CREATE_SUBVOLUME_NEW_QUOTA:
3297 case EMPTY_DIRECTORY:
3298 case TRUNCATE_DIRECTORY:
3299 case CREATE_FIFO:
3300 case IGNORE_PATH:
3301 case IGNORE_DIRECTORY_PATH:
3302 case REMOVE_PATH:
3303 case RECURSIVE_REMOVE_PATH:
3304 case ADJUST_MODE:
3305 case RELABEL_PATH:
3306 case RECURSIVE_RELABEL_PATH:
3307 if (i.argument)
3308 log_syntax(NULL,
3309 LOG_WARNING,
3310 fname,
3311 line,
3312 0,
3313 "%c lines don't take argument fields, ignoring.",
3314 (char) i.type);
3315
3316 break;
3317
3318 case CREATE_FILE:
3319 case TRUNCATE_FILE:
3320 break;
3321
3322 case CREATE_SYMLINK:
3323 if (unbase64) {
3324 *invalid_config = true;
3325 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for symlink targets.");
3326 }
3327 break;
3328
3329 case WRITE_FILE:
3330 if (!i.argument) {
3331 *invalid_config = true;
3332 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Write file requires argument.");
3333 }
3334 break;
3335
3336 case COPY_FILES:
3337 if (unbase64) {
3338 *invalid_config = true;
3339 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for copy sources.");
3340 }
3341 break;
3342
3343 case CREATE_CHAR_DEVICE:
3344 case CREATE_BLOCK_DEVICE:
3345 if (unbase64) {
3346 *invalid_config = true;
3347 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for device node creation.");
3348 }
3349
3350 if (!i.argument) {
3351 *invalid_config = true;
3352 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Device file requires argument.");
3353 }
3354
3355 r = parse_devnum(i.argument, &i.major_minor);
3356 if (r < 0) {
3357 *invalid_config = true;
3358 return log_syntax(NULL, LOG_ERR, fname, line, r, "Can't parse device file major/minor '%s'.", i.argument);
3359 }
3360
3361 break;
3362
3363 case SET_XATTR:
3364 case RECURSIVE_SET_XATTR:
3365 if (unbase64) {
3366 *invalid_config = true;
3367 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for extended attributes.");
3368 }
3369 if (!i.argument) {
3370 *invalid_config = true;
3371 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3372 "Set extended attribute requires argument.");
3373 }
3374 r = parse_xattrs_from_arg(&i);
3375 if (r < 0)
3376 return r;
3377 break;
3378
3379 case SET_ACL:
3380 case RECURSIVE_SET_ACL:
3381 if (unbase64) {
3382 *invalid_config = true;
3383 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for ACLs.");
3384 }
3385 if (!i.argument) {
3386 *invalid_config = true;
3387 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3388 "Set ACLs requires argument.");
3389 }
3390 r = parse_acls_from_arg(&i);
3391 if (r < 0)
3392 return r;
3393 break;
3394
3395 case SET_ATTRIBUTE:
3396 case RECURSIVE_SET_ATTRIBUTE:
3397 if (unbase64) {
3398 *invalid_config = true;
3399 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for file attributes.");
3400 }
3401 if (!i.argument) {
3402 *invalid_config = true;
3403 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3404 "Set file attribute requires argument.");
3405 }
3406 r = parse_attribute_from_arg(&i);
3407 if (IN_SET(r, -EINVAL, -EBADSLT))
3408 *invalid_config = true;
3409 if (r < 0)
3410 return r;
3411 break;
3412
3413 default:
3414 *invalid_config = true;
3415 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3416 "Unknown command type '%c'.", (char) i.type);
3417 }
3418
3419 if (!should_include_path(i.path))
3420 return 0;
3421
3422 if (!unbase64) {
3423 /* Do specifier expansion except if base64 mode is enabled */
3424 r = specifier_expansion_from_arg(specifier_table, &i);
3425 if (ERRNO_IS_NOINFO(r))
3426 return log_unresolvable_specifier(fname, line);
3427 if (r < 0) {
3428 if (IN_SET(r, -EINVAL, -EBADSLT))
3429 *invalid_config = true;
3430 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to substitute specifiers in argument: %m");
3431 }
3432 }
3433
3434 switch (i.type) {
3435 case CREATE_SYMLINK:
3436 if (!i.argument) {
3437 i.argument = path_join("/usr/share/factory", i.path);
3438 if (!i.argument)
3439 return log_oom();
3440 }
3441 break;
3442
3443 case COPY_FILES:
3444 if (!i.argument) {
3445 i.argument = path_join("/usr/share/factory", i.path);
3446 if (!i.argument)
3447 return log_oom();
3448 } else if (!path_is_absolute(i.argument)) {
3449 *invalid_config = true;
3450 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Source path '%s' is not absolute.", i.argument);
3451
3452 }
3453
3454 if (!empty_or_root(arg_root)) {
3455 char *p;
3456
3457 p = path_join(arg_root, i.argument);
3458 if (!p)
3459 return log_oom();
3460 free_and_replace(i.argument, p);
3461 }
3462
3463 path_simplify(i.argument);
3464
3465 if (laccess(i.argument, F_OK) == -ENOENT) {
3466 /* Silently skip over lines where the source file is missing. */
3467 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Copy source path '%s' does not exist, skipping line.", i.argument);
3468 return 0;
3469 }
3470
3471 break;
3472
3473 default:
3474 break;
3475 }
3476
3477 if (from_cred) {
3478 if (!i.argument)
3479 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Reading from credential requested, but no credential name specified.");
3480 if (!credential_name_valid(i.argument))
3481 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Credential name not valid: %s", i.argument);
3482
3483 r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
3484 if (IN_SET(r, -ENXIO, -ENOENT)) {
3485 /* Silently skip over lines that have no credentials passed */
3486 log_syntax(NULL, LOG_DEBUG, fname, line, 0,
3487 "Credential '%s' not specified, skipping line.", i.argument);
3488 return 0;
3489 }
3490 if (r < 0)
3491 return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
3492 }
3493
3494 /* If base64 decoding is requested, do so now */
3495 if (unbase64 && item_binary_argument(&i)) {
3496 _cleanup_free_ void *data = NULL;
3497 size_t data_size = 0;
3498
3499 r = unbase64mem(item_binary_argument(&i), item_binary_argument_size(&i), &data, &data_size);
3500 if (r < 0)
3501 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to base64 decode specified argument '%s': %m", i.argument);
3502
3503 free_and_replace(i.binary_argument, data);
3504 i.binary_argument_size = data_size;
3505 }
3506
3507 if (!empty_or_root(arg_root)) {
3508 char *p;
3509
3510 p = path_join(arg_root, i.path);
3511 if (!p)
3512 return log_oom();
3513 free_and_replace(i.path, p);
3514 }
3515
3516 if (!empty_or_dash(user)) {
3517 const char *u;
3518
3519 u = startswith(user, ":");
3520 if (u)
3521 i.uid_only_create = true;
3522 else
3523 u = user;
3524
3525 r = find_uid(u, &i.uid, uid_cache);
3526 if (r < 0) {
3527 *invalid_config = true;
3528 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", u);
3529 }
3530
3531 i.uid_set = true;
3532 }
3533
3534 if (!empty_or_dash(group)) {
3535 const char *g;
3536
3537 g = startswith(group, ":");
3538 if (g)
3539 i.gid_only_create = true;
3540 else
3541 g = group;
3542
3543 r = find_gid(g, &i.gid, gid_cache);
3544 if (r < 0) {
3545 *invalid_config = true;
3546 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s'.", g);
3547 }
3548
3549 i.gid_set = true;
3550 }
3551
3552 if (!empty_or_dash(mode)) {
3553 const char *mm;
3554 unsigned m;
3555
3556 for (mm = mode;; mm++) {
3557 if (*mm == '~')
3558 i.mask_perms = true;
3559 else if (*mm == ':')
3560 i.mode_only_create = true;
3561 else
3562 break;
3563 }
3564
3565 r = parse_mode(mm, &m);
3566 if (r < 0) {
3567 *invalid_config = true;
3568 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
3569 }
3570
3571 i.mode = m;
3572 i.mode_set = true;
3573 } else
3574 i.mode = IN_SET(i.type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
3575
3576 if (!empty_or_dash(age)) {
3577 const char *a = age;
3578 _cleanup_free_ char *seconds = NULL, *age_by = NULL;
3579
3580 if (*a == '~') {
3581 i.keep_first_level = true;
3582 a++;
3583 }
3584
3585 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3586 r = split_pair(a, ":", &age_by, &seconds);
3587 if (r == -ENOMEM)
3588 return log_oom();
3589 if (r < 0 && r != -EINVAL)
3590 return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
3591 if (r >= 0) {
3592 /* We found a ":", parse the "age-by" part. */
3593 r = parse_age_by_from_arg(age_by, &i);
3594 if (r == -ENOMEM)
3595 return log_oom();
3596 if (r < 0) {
3597 *invalid_config = true;
3598 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
3599 }
3600
3601 /* For parsing the "age" part, after the ":". */
3602 a = seconds;
3603 }
3604
3605 r = parse_sec(a, &i.age);
3606 if (r < 0) {
3607 *invalid_config = true;
3608 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
3609 }
3610
3611 i.age_set = true;
3612 }
3613
3614 h = needs_glob(i.type) ? globs : items;
3615
3616 existing = ordered_hashmap_get(h, i.path);
3617 if (existing) {
3618 if (is_duplicated_item(existing, &i)) {
3619 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3620 "Duplicate line for path \"%s\", ignoring.", i.path);
3621 return 0;
3622 }
3623 } else {
3624 existing = new0(ItemArray, 1);
3625 if (!existing)
3626 return log_oom();
3627
3628 r = ordered_hashmap_put(h, i.path, existing);
3629 if (r < 0) {
3630 free(existing);
3631 return log_oom();
3632 }
3633 }
3634
3635 if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
3636 return log_oom();
3637
3638 existing->items[existing->n_items++] = i;
3639 i = (struct Item) {};
3640
3641 /* Sort item array, to enforce stable ordering of application */
3642 typesafe_qsort(existing->items, existing->n_items, item_compare);
3643
3644 return 0;
3645 }
3646
3647 static int cat_config(char **config_dirs, char **args) {
3648 _cleanup_strv_free_ char **files = NULL;
3649 int r;
3650
3651 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
3652 if (r < 0)
3653 return r;
3654
3655 return cat_files(NULL, files, 0);
3656 }
3657
3658 static int exclude_default_prefixes(void) {
3659 int r;
3660
3661 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3662 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3663 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3664 * all kinds of files created/adjusted underneath these mount points. */
3665
3666 r = strv_extend_strv(
3667 &arg_exclude_prefixes,
3668 STRV_MAKE("/dev",
3669 "/proc",
3670 "/run",
3671 "/sys"),
3672 true);
3673 if (r < 0)
3674 return log_oom();
3675
3676 return 0;
3677 }
3678
3679 static int help(void) {
3680 _cleanup_free_ char *link = NULL;
3681 int r;
3682
3683 r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
3684 if (r < 0)
3685 return log_oom();
3686
3687 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3688 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3689 " -h --help Show this help\n"
3690 " --user Execute user configuration\n"
3691 " --version Show package version\n"
3692 " --cat-config Show configuration files\n"
3693 " --create Create marked files/directories\n"
3694 " --clean Clean up marked directories\n"
3695 " --remove Remove marked files/directories\n"
3696 " --boot Execute actions only safe at boot\n"
3697 " --prefix=PATH Only apply rules with the specified prefix\n"
3698 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3699 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3700 " --root=PATH Operate on an alternate filesystem root\n"
3701 " --image=PATH Operate on disk image as filesystem root\n"
3702 " --replace=PATH Treat arguments as replacement for PATH\n"
3703 " --no-pager Do not pipe output into a pager\n"
3704 "\nSee the %s for details.\n",
3705 program_invocation_short_name,
3706 ansi_highlight(),
3707 ansi_normal(),
3708 link);
3709
3710 return 0;
3711 }
3712
3713 static int parse_argv(int argc, char *argv[]) {
3714
3715 enum {
3716 ARG_VERSION = 0x100,
3717 ARG_CAT_CONFIG,
3718 ARG_USER,
3719 ARG_CREATE,
3720 ARG_CLEAN,
3721 ARG_REMOVE,
3722 ARG_BOOT,
3723 ARG_PREFIX,
3724 ARG_EXCLUDE_PREFIX,
3725 ARG_ROOT,
3726 ARG_IMAGE,
3727 ARG_REPLACE,
3728 ARG_NO_PAGER,
3729 };
3730
3731 static const struct option options[] = {
3732 { "help", no_argument, NULL, 'h' },
3733 { "user", no_argument, NULL, ARG_USER },
3734 { "version", no_argument, NULL, ARG_VERSION },
3735 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
3736 { "create", no_argument, NULL, ARG_CREATE },
3737 { "clean", no_argument, NULL, ARG_CLEAN },
3738 { "remove", no_argument, NULL, ARG_REMOVE },
3739 { "boot", no_argument, NULL, ARG_BOOT },
3740 { "prefix", required_argument, NULL, ARG_PREFIX },
3741 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
3742 { "root", required_argument, NULL, ARG_ROOT },
3743 { "image", required_argument, NULL, ARG_IMAGE },
3744 { "replace", required_argument, NULL, ARG_REPLACE },
3745 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
3746 {}
3747 };
3748
3749 int c, r;
3750
3751 assert(argc >= 0);
3752 assert(argv);
3753
3754 while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3755
3756 switch (c) {
3757
3758 case 'h':
3759 return help();
3760
3761 case ARG_VERSION:
3762 return version();
3763
3764 case ARG_CAT_CONFIG:
3765 arg_cat_config = true;
3766 break;
3767
3768 case ARG_USER:
3769 arg_runtime_scope = RUNTIME_SCOPE_USER;
3770 break;
3771
3772 case ARG_CREATE:
3773 arg_operation |= OPERATION_CREATE;
3774 break;
3775
3776 case ARG_CLEAN:
3777 arg_operation |= OPERATION_CLEAN;
3778 break;
3779
3780 case ARG_REMOVE:
3781 arg_operation |= OPERATION_REMOVE;
3782 break;
3783
3784 case ARG_BOOT:
3785 arg_boot = true;
3786 break;
3787
3788 case ARG_PREFIX:
3789 if (strv_push(&arg_include_prefixes, optarg) < 0)
3790 return log_oom();
3791 break;
3792
3793 case ARG_EXCLUDE_PREFIX:
3794 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
3795 return log_oom();
3796 break;
3797
3798 case ARG_ROOT:
3799 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
3800 if (r < 0)
3801 return r;
3802 break;
3803
3804 case ARG_IMAGE:
3805 #ifdef STANDALONE
3806 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3807 "This systemd-tmpfiles version is compiled without support for --image=.");
3808 #else
3809 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
3810 if (r < 0)
3811 return r;
3812 #endif
3813 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
3814 _fallthrough_;
3815
3816 case 'E':
3817 r = exclude_default_prefixes();
3818 if (r < 0)
3819 return r;
3820
3821 break;
3822
3823 case ARG_REPLACE:
3824 if (!path_is_absolute(optarg) ||
3825 !endswith(optarg, ".conf"))
3826 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3827 "The argument to --replace= must an absolute path to a config file");
3828
3829 arg_replace = optarg;
3830 break;
3831
3832 case ARG_NO_PAGER:
3833 arg_pager_flags |= PAGER_DISABLE;
3834 break;
3835
3836 case '?':
3837 return -EINVAL;
3838
3839 default:
3840 assert_not_reached();
3841 }
3842
3843 if (arg_operation == 0 && !arg_cat_config)
3844 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3845 "You need to specify at least one of --clean, --create or --remove.");
3846
3847 if (arg_replace && arg_cat_config)
3848 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3849 "Option --replace= is not supported with --cat-config");
3850
3851 if (arg_replace && optind >= argc)
3852 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3853 "When --replace= is given, some configuration items must be specified");
3854
3855 if (arg_root && arg_runtime_scope == RUNTIME_SCOPE_USER)
3856 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3857 "Combination of --user and --root= is not supported.");
3858
3859 if (arg_image && arg_root)
3860 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
3861
3862 return 1;
3863 }
3864
3865 static int read_config_file(
3866 char **config_dirs,
3867 const char *fn,
3868 bool ignore_enoent,
3869 bool *invalid_config) {
3870
3871 _cleanup_(hashmap_freep) Hashmap *uid_cache = NULL, *gid_cache = NULL;
3872 _cleanup_fclose_ FILE *_f = NULL;
3873 _cleanup_free_ char *pp = NULL;
3874 unsigned v = 0;
3875 FILE *f;
3876 ItemArray *ia;
3877 int r = 0;
3878
3879 assert(fn);
3880
3881 if (streq(fn, "-")) {
3882 log_debug("Reading config from stdin%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
3883 fn = "<stdin>";
3884 f = stdin;
3885 } else {
3886 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f, &pp);
3887 if (r < 0) {
3888 if (ignore_enoent && r == -ENOENT) {
3889 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
3890 return 0;
3891 }
3892
3893 return log_error_errno(r, "Failed to open '%s': %m", fn);
3894 }
3895
3896 log_debug("Reading config file \"%s\"%s", pp, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
3897 fn = pp;
3898 f = _f;
3899 }
3900
3901 for (;;) {
3902 _cleanup_free_ char *line = NULL;
3903 bool invalid_line = false;
3904 char *l;
3905 int k;
3906
3907 k = read_line(f, LONG_LINE_MAX, &line);
3908 if (k < 0)
3909 return log_error_errno(k, "Failed to read '%s': %m", fn);
3910 if (k == 0)
3911 break;
3912
3913 v++;
3914
3915 l = strstrip(line);
3916 if (IN_SET(*l, 0, '#'))
3917 continue;
3918
3919 k = parse_line(fn, v, l, &invalid_line, &uid_cache, &gid_cache);
3920 if (k < 0) {
3921 if (invalid_line)
3922 /* Allow reporting with a special code if the caller requested this */
3923 *invalid_config = true;
3924 else if (r == 0)
3925 /* The first error becomes our return value */
3926 r = k;
3927 }
3928 }
3929
3930 /* we have to determine age parameter for each entry of type X */
3931 ORDERED_HASHMAP_FOREACH(ia, globs)
3932 for (size_t ni = 0; ni < ia->n_items; ni++) {
3933 ItemArray *ja;
3934 Item *i = ia->items + ni, *candidate_item = NULL;
3935
3936 if (i->type != IGNORE_DIRECTORY_PATH)
3937 continue;
3938
3939 ORDERED_HASHMAP_FOREACH(ja, items)
3940 for (size_t nj = 0; nj < ja->n_items; nj++) {
3941 Item *j = ja->items + nj;
3942
3943 if (!IN_SET(j->type, CREATE_DIRECTORY,
3944 TRUNCATE_DIRECTORY,
3945 CREATE_SUBVOLUME,
3946 CREATE_SUBVOLUME_INHERIT_QUOTA,
3947 CREATE_SUBVOLUME_NEW_QUOTA))
3948 continue;
3949
3950 if (path_equal(j->path, i->path)) {
3951 candidate_item = j;
3952 break;
3953 }
3954
3955 if (candidate_item
3956 ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
3957 : path_startswith(i->path, j->path) != NULL)
3958 candidate_item = j;
3959 }
3960
3961 if (candidate_item && candidate_item->age_set) {
3962 i->age = candidate_item->age;
3963 i->age_set = true;
3964 }
3965 }
3966
3967 if (ferror(f)) {
3968 log_error_errno(errno, "Failed to read from file %s: %m", fn);
3969 if (r == 0)
3970 r = -EIO;
3971 }
3972
3973 return r;
3974 }
3975
3976 static int parse_arguments(char **config_dirs, char **args, bool *invalid_config) {
3977 int r;
3978
3979 STRV_FOREACH(arg, args) {
3980 r = read_config_file(config_dirs, *arg, false, invalid_config);
3981 if (r < 0)
3982 return r;
3983 }
3984
3985 return 0;
3986 }
3987
3988 static int read_config_files(char **config_dirs, char **args, bool *invalid_config) {
3989 _cleanup_strv_free_ char **files = NULL;
3990 _cleanup_free_ char *p = NULL;
3991 int r;
3992
3993 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
3994 if (r < 0)
3995 return r;
3996
3997 STRV_FOREACH(f, files)
3998 if (p && path_equal(*f, p)) {
3999 log_debug("Parsing arguments at position \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
4000
4001 r = parse_arguments(config_dirs, args, invalid_config);
4002 if (r < 0)
4003 return r;
4004 } else
4005 /* Just warn, ignore result otherwise.
4006 * read_config_file() has some debug output, so no need to print anything. */
4007 (void) read_config_file(config_dirs, *f, true, invalid_config);
4008
4009 return 0;
4010 }
4011
4012 static int read_credential_lines(bool *invalid_config) {
4013 _cleanup_free_ char *j = NULL;
4014 const char *d;
4015 int r;
4016
4017 r = get_credentials_dir(&d);
4018 if (r == -ENXIO)
4019 return 0;
4020 if (r < 0)
4021 return log_error_errno(r, "Failed to get credentials directory: %m");
4022
4023 j = path_join(d, "tmpfiles.extra");
4024 if (!j)
4025 return log_oom();
4026
4027 (void) read_config_file(/* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
4028 return 0;
4029 }
4030
4031 static int link_parent(ItemArray *a) {
4032 const char *path;
4033 char *prefix;
4034 int r;
4035
4036 assert(a);
4037
4038 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
4039 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
4040 * before their children, and clean up/remove children before their parents. */
4041
4042 if (a->n_items <= 0)
4043 return 0;
4044
4045 path = a->items[0].path;
4046 prefix = newa(char, strlen(path) + 1);
4047 PATH_FOREACH_PREFIX(prefix, path) {
4048 ItemArray *j;
4049
4050 j = ordered_hashmap_get(items, prefix);
4051 if (!j)
4052 j = ordered_hashmap_get(globs, prefix);
4053 if (j) {
4054 r = set_ensure_put(&j->children, NULL, a);
4055 if (r < 0)
4056 return log_oom();
4057
4058 a->parent = j;
4059 return 1;
4060 }
4061 }
4062
4063 return 0;
4064 }
4065
4066 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
4067 ItemArray, item_array_free);
4068
4069 static int run(int argc, char *argv[]) {
4070 #ifndef STANDALONE
4071 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
4072 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
4073 #endif
4074 _cleanup_strv_free_ char **config_dirs = NULL;
4075 bool invalid_config = false;
4076 ItemArray *a;
4077 enum {
4078 PHASE_REMOVE_AND_CLEAN,
4079 PHASE_CREATE,
4080 _PHASE_MAX
4081 } phase;
4082 int r, k;
4083
4084 r = parse_argv(argc, argv);
4085 if (r <= 0)
4086 return r;
4087
4088 log_setup();
4089
4090 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4091 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4092 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4093 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4094 * and output a nice and friendly warning. */
4095 if (proc_mounted() == 0)
4096 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
4097 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4098 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4099
4100 /* Descending down file system trees might take a lot of fds */
4101 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
4102
4103 switch (arg_runtime_scope) {
4104
4105 case RUNTIME_SCOPE_USER:
4106 r = user_config_paths(&config_dirs);
4107 if (r < 0)
4108 return log_error_errno(r, "Failed to initialize configuration directory list: %m");
4109 break;
4110
4111 case RUNTIME_SCOPE_SYSTEM:
4112 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
4113 if (!config_dirs)
4114 return log_oom();
4115 break;
4116
4117 default:
4118 assert_not_reached();
4119 }
4120
4121 if (DEBUG_LOGGING) {
4122 _cleanup_free_ char *t = NULL;
4123
4124 STRV_FOREACH(i, config_dirs) {
4125 _cleanup_free_ char *j = NULL;
4126
4127 j = path_join(arg_root, *i);
4128 if (!j)
4129 return log_oom();
4130
4131 if (!strextend(&t, "\n\t", j))
4132 return log_oom();
4133 }
4134
4135 log_debug("Looking for configuration files in (higher priority first):%s", t);
4136 }
4137
4138 if (arg_cat_config) {
4139 pager_open(arg_pager_flags);
4140
4141 return cat_config(config_dirs, argv + optind);
4142 }
4143
4144 umask(0022);
4145
4146 r = mac_selinux_init();
4147 if (r < 0)
4148 return r;
4149
4150 #ifndef STANDALONE
4151 if (arg_image) {
4152 assert(!arg_root);
4153
4154 r = mount_image_privately_interactively(
4155 arg_image,
4156 DISSECT_IMAGE_GENERIC_ROOT |
4157 DISSECT_IMAGE_REQUIRE_ROOT |
4158 DISSECT_IMAGE_VALIDATE_OS |
4159 DISSECT_IMAGE_RELAX_VAR_CHECK |
4160 DISSECT_IMAGE_FSCK |
4161 DISSECT_IMAGE_GROWFS,
4162 &unlink_dir,
4163 /* ret_dir_fd= */ NULL,
4164 &loop_device);
4165 if (r < 0)
4166 return r;
4167
4168 arg_root = strdup(unlink_dir);
4169 if (!arg_root)
4170 return log_oom();
4171 }
4172 #else
4173 assert(!arg_image);
4174 #endif
4175
4176 items = ordered_hashmap_new(&item_array_hash_ops);
4177 globs = ordered_hashmap_new(&item_array_hash_ops);
4178 if (!items || !globs)
4179 return log_oom();
4180
4181 /* If command line arguments are specified along with --replace, read all
4182 * configuration files and insert the positional arguments at the specified
4183 * place. Otherwise, if command line arguments are specified, execute just
4184 * them, and finally, without --replace= or any positional arguments, just
4185 * read configuration and execute it.
4186 */
4187 if (arg_replace || optind >= argc)
4188 r = read_config_files(config_dirs, argv + optind, &invalid_config);
4189 else
4190 r = parse_arguments(config_dirs, argv + optind, &invalid_config);
4191 if (r < 0)
4192 return r;
4193
4194 r = read_credential_lines(&invalid_config);
4195 if (r < 0)
4196 return r;
4197
4198 /* Let's now link up all child/parent relationships */
4199 ORDERED_HASHMAP_FOREACH(a, items) {
4200 r = link_parent(a);
4201 if (r < 0)
4202 return r;
4203 }
4204 ORDERED_HASHMAP_FOREACH(a, globs) {
4205 r = link_parent(a);
4206 if (r < 0)
4207 return r;
4208 }
4209
4210 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
4211 * operations. i.e. that we first clean out the platform we then build on. */
4212 for (phase = 0; phase < _PHASE_MAX; phase++) {
4213 OperationMask op;
4214
4215 if (phase == PHASE_REMOVE_AND_CLEAN)
4216 op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
4217 else if (phase == PHASE_CREATE)
4218 op = arg_operation & OPERATION_CREATE;
4219 else
4220 assert_not_reached();
4221
4222 if (op == 0) /* Nothing requested in this phase */
4223 continue;
4224
4225 /* The non-globbing ones usually create things, hence we apply them first */
4226 ORDERED_HASHMAP_FOREACH(a, items) {
4227 k = process_item_array(a, op);
4228 if (k < 0 && r >= 0)
4229 r = k;
4230 }
4231
4232 /* The globbing ones usually alter things, hence we apply them second. */
4233 ORDERED_HASHMAP_FOREACH(a, globs) {
4234 k = process_item_array(a, op);
4235 if (k < 0 && r >= 0)
4236 r = k;
4237 }
4238 }
4239
4240 if (ERRNO_IS_RESOURCE(r))
4241 return r;
4242 if (invalid_config)
4243 return EX_DATAERR;
4244 if (r < 0)
4245 return EX_CANTCREAT;
4246 return 0;
4247 }
4248
4249 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);