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