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