]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/tmpfiles/tmpfiles.c
Merge pull request #22791 from keszybz/bootctl-invert-order
[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 assert(i);
1048 assert(fd >= 0);
1049 assert(path);
1050
1051 STRV_FOREACH_PAIR(name, value, i->xattrs) {
1052 log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
1053 if (setxattr(FORMAT_PROC_FD_PATH(fd), *name, *value, strlen(*value), 0) < 0)
1054 return log_error_errno(errno, "Setting extended attribute %s=%s on %s failed: %m",
1055 *name, *value, path);
1056 }
1057 return 0;
1058 }
1059
1060 static int path_set_xattrs(Item *i, const char *path) {
1061 _cleanup_close_ int fd = -1;
1062
1063 assert(i);
1064 assert(path);
1065
1066 fd = path_open_safe(path);
1067 if (fd < 0)
1068 return fd;
1069
1070 return fd_set_xattrs(i, fd, path, NULL);
1071 }
1072
1073 static int parse_acls_from_arg(Item *item) {
1074 #if HAVE_ACL
1075 int r;
1076
1077 assert(item);
1078
1079 /* If append_or_force (= modify) is set, we will not modify the acl
1080 * afterwards, so the mask can be added now if necessary. */
1081
1082 r = parse_acl(item->argument, &item->acl_access, &item->acl_default, !item->append_or_force);
1083 if (r < 0)
1084 log_warning_errno(r, "Failed to parse ACL \"%s\": %m. Ignoring", item->argument);
1085 #else
1086 log_warning("ACLs are not supported. Ignoring.");
1087 #endif
1088
1089 return 0;
1090 }
1091
1092 #if HAVE_ACL
1093 static int path_set_acl(const char *path, const char *pretty, acl_type_t type, acl_t acl, bool modify) {
1094 _cleanup_(acl_free_charpp) char *t = NULL;
1095 _cleanup_(acl_freep) acl_t dup = NULL;
1096 int r;
1097
1098 /* Returns 0 for success, positive error if already warned,
1099 * negative error otherwise. */
1100
1101 if (modify) {
1102 r = acls_for_file(path, type, acl, &dup);
1103 if (r < 0)
1104 return r;
1105
1106 r = calc_acl_mask_if_needed(&dup);
1107 if (r < 0)
1108 return r;
1109 } else {
1110 dup = acl_dup(acl);
1111 if (!dup)
1112 return -errno;
1113
1114 /* the mask was already added earlier if needed */
1115 }
1116
1117 r = add_base_acls_if_needed(&dup, path);
1118 if (r < 0)
1119 return r;
1120
1121 t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
1122 log_debug("Setting %s ACL %s on %s.",
1123 type == ACL_TYPE_ACCESS ? "access" : "default",
1124 strna(t), pretty);
1125
1126 r = acl_set_file(path, type, dup);
1127 if (r < 0) {
1128 if (ERRNO_IS_NOT_SUPPORTED(errno))
1129 /* No error if filesystem doesn't support ACLs. Return negative. */
1130 return -errno;
1131 else
1132 /* Return positive to indicate we already warned */
1133 return -log_error_errno(errno,
1134 "Setting %s ACL \"%s\" on %s failed: %m",
1135 type == ACL_TYPE_ACCESS ? "access" : "default",
1136 strna(t), pretty);
1137 }
1138 return 0;
1139 }
1140 #endif
1141
1142 static int fd_set_acls(Item *item, int fd, const char *path, const struct stat *st) {
1143 int r = 0;
1144 #if HAVE_ACL
1145 struct stat stbuf;
1146
1147 assert(item);
1148 assert(fd >= 0);
1149 assert(path);
1150
1151 if (!st) {
1152 if (fstat(fd, &stbuf) < 0)
1153 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1154 st = &stbuf;
1155 }
1156
1157 if (hardlink_vulnerable(st))
1158 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1159 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1160 path);
1161
1162 if (S_ISLNK(st->st_mode)) {
1163 log_debug("Skipping ACL fix for symlink %s.", path);
1164 return 0;
1165 }
1166
1167 if (item->acl_access)
1168 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
1169
1170 /* set only default acls to folders */
1171 if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
1172 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
1173
1174 if (ERRNO_IS_NOT_SUPPORTED(r)) {
1175 log_debug_errno(r, "ACLs not supported by file system at %s", path);
1176 return 0;
1177 }
1178
1179 if (r > 0)
1180 return -r; /* already warned */
1181
1182 /* The above procfs paths don't work if /proc is not mounted. */
1183 if (r == -ENOENT && proc_mounted() == 0)
1184 r = -ENOSYS;
1185
1186 if (r < 0)
1187 return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
1188 #endif
1189 return r;
1190 }
1191
1192 static int path_set_acls(Item *item, const char *path) {
1193 int r = 0;
1194 #if HAVE_ACL
1195 _cleanup_close_ int fd = -1;
1196
1197 assert(item);
1198 assert(path);
1199
1200 fd = path_open_safe(path);
1201 if (fd < 0)
1202 return fd;
1203
1204 r = fd_set_acls(item, fd, path, NULL);
1205 #endif
1206 return r;
1207 }
1208
1209 static int parse_attribute_from_arg(Item *item) {
1210
1211 static const struct {
1212 char character;
1213 unsigned value;
1214 } attributes[] = {
1215 { 'A', FS_NOATIME_FL }, /* do not update atime */
1216 { 'S', FS_SYNC_FL }, /* Synchronous updates */
1217 { 'D', FS_DIRSYNC_FL }, /* dirsync behaviour (directories only) */
1218 { 'a', FS_APPEND_FL }, /* writes to file may only append */
1219 { 'c', FS_COMPR_FL }, /* Compress file */
1220 { 'd', FS_NODUMP_FL }, /* do not dump file */
1221 { 'e', FS_EXTENT_FL }, /* Extents */
1222 { 'i', FS_IMMUTABLE_FL }, /* Immutable file */
1223 { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1224 { 's', FS_SECRM_FL }, /* Secure deletion */
1225 { 'u', FS_UNRM_FL }, /* Undelete */
1226 { 't', FS_NOTAIL_FL }, /* file tail should not be merged */
1227 { 'T', FS_TOPDIR_FL }, /* Top of directory hierarchies */
1228 { 'C', FS_NOCOW_FL }, /* Do not cow file */
1229 { 'P', FS_PROJINHERIT_FL }, /* Inherit the quota project ID */
1230 };
1231
1232 enum {
1233 MODE_ADD,
1234 MODE_DEL,
1235 MODE_SET
1236 } mode = MODE_ADD;
1237
1238 unsigned value = 0, mask = 0;
1239 const char *p;
1240
1241 assert(item);
1242
1243 p = item->argument;
1244 if (p) {
1245 if (*p == '+') {
1246 mode = MODE_ADD;
1247 p++;
1248 } else if (*p == '-') {
1249 mode = MODE_DEL;
1250 p++;
1251 } else if (*p == '=') {
1252 mode = MODE_SET;
1253 p++;
1254 }
1255 }
1256
1257 if (isempty(p) && mode != MODE_SET)
1258 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1259 "Setting file attribute on '%s' needs an attribute specification.",
1260 item->path);
1261
1262 for (; p && *p ; p++) {
1263 unsigned i, v;
1264
1265 for (i = 0; i < ELEMENTSOF(attributes); i++)
1266 if (*p == attributes[i].character)
1267 break;
1268
1269 if (i >= ELEMENTSOF(attributes))
1270 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1271 "Unknown file attribute '%c' on '%s'.",
1272 *p, item->path);
1273
1274 v = attributes[i].value;
1275
1276 SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
1277
1278 mask |= v;
1279 }
1280
1281 if (mode == MODE_SET)
1282 mask |= CHATTR_ALL_FL;
1283
1284 assert(mask != 0);
1285
1286 item->attribute_mask = mask;
1287 item->attribute_value = value;
1288 item->attribute_set = true;
1289
1290 return 0;
1291 }
1292
1293 static int fd_set_attribute(Item *item, int fd, const char *path, const struct stat *st) {
1294 _cleanup_close_ int procfs_fd = -1;
1295 struct stat stbuf;
1296 unsigned f;
1297 int r;
1298
1299 assert(item);
1300 assert(fd >= 0);
1301 assert(path);
1302
1303 if (!item->attribute_set || item->attribute_mask == 0)
1304 return 0;
1305
1306 if (!st) {
1307 if (fstat(fd, &stbuf) < 0)
1308 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1309 st = &stbuf;
1310 }
1311
1312 /* Issuing the file attribute ioctls on device nodes is not
1313 * safe, as that will be delivered to the drivers, not the
1314 * file system containing the device node. */
1315 if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode))
1316 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1317 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1318 path);
1319
1320 f = item->attribute_value & item->attribute_mask;
1321
1322 /* Mask away directory-specific flags */
1323 if (!S_ISDIR(st->st_mode))
1324 f &= ~FS_DIRSYNC_FL;
1325
1326 procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
1327 if (procfs_fd < 0)
1328 return log_error_errno(procfs_fd, "Failed to re-open '%s': %m", path);
1329
1330 unsigned previous, current;
1331 r = chattr_full(NULL, procfs_fd, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
1332 if (r == -ENOANO)
1333 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
1334 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1335 path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1336 else if (r < 0)
1337 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
1338 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
1339 path, item->attribute_value, item->attribute_mask);
1340
1341 return 0;
1342 }
1343
1344 static int path_set_attribute(Item *item, const char *path) {
1345 _cleanup_close_ int fd = -1;
1346
1347 if (!item->attribute_set || item->attribute_mask == 0)
1348 return 0;
1349
1350 fd = path_open_safe(path);
1351 if (fd < 0)
1352 return fd;
1353
1354 return fd_set_attribute(item, fd, path, NULL);
1355 }
1356
1357 static int write_one_file(Item *i, const char *path) {
1358 _cleanup_close_ int fd = -1, dir_fd = -1;
1359 char *bn;
1360 int r;
1361
1362 assert(i);
1363 assert(path);
1364 assert(i->argument);
1365 assert(i->type == WRITE_FILE);
1366
1367 /* Validate the path and keep the fd on the directory for opening the
1368 * file so we're sure that it can't be changed behind our back. */
1369 dir_fd = path_open_parent_safe(path);
1370 if (dir_fd < 0)
1371 return dir_fd;
1372
1373 bn = basename(path);
1374
1375 /* Follows symlinks */
1376 fd = openat(dir_fd, bn,
1377 O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY|(i->append_or_force ? O_APPEND : 0),
1378 i->mode);
1379 if (fd < 0) {
1380 if (errno == ENOENT) {
1381 log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
1382 return 0;
1383 }
1384
1385 if (i->allow_failure)
1386 return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
1387
1388 return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
1389 }
1390
1391 /* 'w' is allowed to write into any kind of files. */
1392 log_debug("Writing to \"%s\".", path);
1393
1394 r = loop_write(fd, i->argument, strlen(i->argument), false);
1395 if (r < 0)
1396 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
1397
1398 return fd_set_perms(i, fd, path, NULL);
1399 }
1400
1401 static int create_file(Item *i, const char *path) {
1402 _cleanup_close_ int fd = -1, dir_fd = -1;
1403 struct stat stbuf, *st = NULL;
1404 int r = 0;
1405 char *bn;
1406
1407 assert(i);
1408 assert(path);
1409 assert(i->type == CREATE_FILE);
1410
1411 /* 'f' operates on regular files exclusively. */
1412
1413 /* Validate the path and keep the fd on the directory for opening the
1414 * file so we're sure that it can't be changed behind our back. */
1415 dir_fd = path_open_parent_safe(path);
1416 if (dir_fd < 0)
1417 return dir_fd;
1418
1419 bn = basename(path);
1420
1421 RUN_WITH_UMASK(0000) {
1422 mac_selinux_create_file_prepare(path, S_IFREG);
1423 fd = openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode);
1424 mac_selinux_create_file_clear();
1425 }
1426
1427 if (fd < 0) {
1428 /* Even on a read-only filesystem, open(2) returns EEXIST if the
1429 * file already exists. It returns EROFS only if it needs to
1430 * create the file. */
1431 if (errno != EEXIST)
1432 return log_error_errno(errno, "Failed to create file %s: %m", path);
1433
1434 /* Re-open the file. At that point it must exist since open(2)
1435 * failed with EEXIST. We still need to check if the perms/mode
1436 * need to be changed. For read-only filesystems, we let
1437 * fd_set_perms() report the error if the perms need to be
1438 * modified. */
1439 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1440 if (fd < 0)
1441 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1442
1443 if (fstat(fd, &stbuf) < 0)
1444 return log_error_errno(errno, "stat(%s) failed: %m", path);
1445
1446 if (!S_ISREG(stbuf.st_mode))
1447 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1448 "%s exists and is not a regular file.",
1449 path);
1450
1451 st = &stbuf;
1452 } else {
1453
1454 log_debug("\"%s\" has been created.", path);
1455
1456 if (i->argument) {
1457 log_debug("Writing to \"%s\".", path);
1458
1459 r = loop_write(fd, i->argument, strlen(i->argument), false);
1460 if (r < 0)
1461 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
1462 }
1463 }
1464
1465 return fd_set_perms(i, fd, path, st);
1466 }
1467
1468 static int truncate_file(Item *i, const char *path) {
1469 _cleanup_close_ int fd = -1, dir_fd = -1;
1470 struct stat stbuf, *st = NULL;
1471 bool erofs = false;
1472 int r = 0;
1473 char *bn;
1474
1475 assert(i);
1476 assert(path);
1477 assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
1478
1479 /* We want to operate on regular file exclusively especially since
1480 * O_TRUNC is unspecified if the file is neither a regular file nor a
1481 * fifo nor a terminal device. Therefore we first open the file and make
1482 * sure it's a regular one before truncating it. */
1483
1484 /* Validate the path and keep the fd on the directory for opening the
1485 * file so we're sure that it can't be changed behind our back. */
1486 dir_fd = path_open_parent_safe(path);
1487 if (dir_fd < 0)
1488 return dir_fd;
1489
1490 bn = basename(path);
1491
1492 RUN_WITH_UMASK(0000) {
1493 mac_selinux_create_file_prepare(path, S_IFREG);
1494 fd = openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode);
1495 mac_selinux_create_file_clear();
1496 }
1497
1498 if (fd < 0) {
1499 if (errno != EROFS)
1500 return log_error_errno(errno, "Failed to open/create file %s: %m", path);
1501
1502 /* On a read-only filesystem, we don't want to fail if the
1503 * target is already empty and the perms are set. So we still
1504 * proceed with the sanity checks and let the remaining
1505 * operations fail with EROFS if they try to modify the target
1506 * file. */
1507
1508 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1509 if (fd < 0) {
1510 if (errno == ENOENT)
1511 return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1512 "Cannot create file %s on a read-only file system.",
1513 path);
1514
1515 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1516 }
1517
1518 erofs = true;
1519 }
1520
1521 if (fstat(fd, &stbuf) < 0)
1522 return log_error_errno(errno, "stat(%s) failed: %m", path);
1523
1524 if (!S_ISREG(stbuf.st_mode))
1525 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1526 "%s exists and is not a regular file.",
1527 path);
1528
1529 if (stbuf.st_size > 0) {
1530 if (ftruncate(fd, 0) < 0) {
1531 r = erofs ? -EROFS : -errno;
1532 return log_error_errno(r, "Failed to truncate file %s: %m", path);
1533 }
1534 } else
1535 st = &stbuf;
1536
1537 log_debug("\"%s\" has been created.", path);
1538
1539 if (i->argument) {
1540 log_debug("Writing to \"%s\".", path);
1541
1542 r = loop_write(fd, i->argument, strlen(i->argument), false);
1543 if (r < 0) {
1544 r = erofs ? -EROFS : r;
1545 return log_error_errno(r, "Failed to write file %s: %m", path);
1546 }
1547 }
1548
1549 return fd_set_perms(i, fd, path, st);
1550 }
1551
1552 static int copy_files(Item *i) {
1553 _cleanup_close_ int dfd = -1, fd = -1;
1554 char *bn;
1555 int r;
1556
1557 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
1558
1559 bn = basename(i->path);
1560
1561 /* Validate the path and use the returned directory fd for copying the
1562 * target so we're sure that the path can't be changed behind our
1563 * back. */
1564 dfd = path_open_parent_safe(i->path);
1565 if (dfd < 0)
1566 return dfd;
1567
1568 r = copy_tree_at(AT_FDCWD, i->argument,
1569 dfd, bn,
1570 i->uid_set ? i->uid : UID_INVALID,
1571 i->gid_set ? i->gid : GID_INVALID,
1572 COPY_REFLINK | COPY_MERGE_EMPTY | COPY_MAC_CREATE | COPY_HARDLINKS);
1573 if (r < 0) {
1574 struct stat a, b;
1575
1576 /* If the target already exists on read-only filesystems, trying
1577 * to create the target will not fail with EEXIST but with
1578 * EROFS. */
1579 if (r == -EROFS && faccessat(dfd, bn, F_OK, AT_SYMLINK_NOFOLLOW) == 0)
1580 r = -EEXIST;
1581
1582 if (r != -EEXIST)
1583 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
1584
1585 if (stat(i->argument, &a) < 0)
1586 return log_error_errno(errno, "stat(%s) failed: %m", i->argument);
1587
1588 if (fstatat(dfd, bn, &b, AT_SYMLINK_NOFOLLOW) < 0)
1589 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
1590
1591 if ((a.st_mode ^ b.st_mode) & S_IFMT) {
1592 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1593 return 0;
1594 }
1595 }
1596
1597 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1598 if (fd < 0)
1599 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1600
1601 return fd_set_perms(i, fd, i->path, NULL);
1602 }
1603
1604 typedef enum {
1605 CREATION_NORMAL,
1606 CREATION_EXISTING,
1607 CREATION_FORCE,
1608 _CREATION_MODE_MAX,
1609 _CREATION_MODE_INVALID = -EINVAL,
1610 } CreationMode;
1611
1612 static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
1613 [CREATION_NORMAL] = "Created",
1614 [CREATION_EXISTING] = "Found existing",
1615 [CREATION_FORCE] = "Created replacement",
1616 };
1617
1618 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
1619
1620 static int create_directory_or_subvolume(const char *path, mode_t mode, bool subvol, CreationMode *creation) {
1621 _cleanup_close_ int pfd = -1;
1622 CreationMode c;
1623 int r;
1624
1625 assert(path);
1626
1627 if (!creation)
1628 creation = &c;
1629
1630 pfd = path_open_parent_safe(path);
1631 if (pfd < 0)
1632 return pfd;
1633
1634 if (subvol) {
1635 r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1636 if (r < 0) {
1637 if (r != -ENXIO) /* env var is unset */
1638 log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1639 r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
1640 }
1641 if (!r)
1642 /* Don't create a subvolume unless the root directory is
1643 * one, too. We do this under the assumption that if the
1644 * root directory is just a plain directory (i.e. very
1645 * light-weight), we shouldn't try to split it up into
1646 * subvolumes (i.e. more heavy-weight). Thus, chroot()
1647 * environments and suchlike will get a full brtfs
1648 * subvolume set up below their tree only if they
1649 * specifically set up a btrfs subvolume for the root
1650 * dir too. */
1651
1652 subvol = false;
1653 else {
1654 RUN_WITH_UMASK((~mode) & 0777)
1655 r = btrfs_subvol_make_fd(pfd, basename(path));
1656 }
1657 } else
1658 r = 0;
1659
1660 if (!subvol || r == -ENOTTY)
1661 RUN_WITH_UMASK(0000)
1662 r = mkdirat_label(pfd, basename(path), mode);
1663
1664 if (r < 0) {
1665 int k;
1666
1667 if (!IN_SET(r, -EEXIST, -EROFS))
1668 return log_error_errno(r, "Failed to create directory or subvolume \"%s\": %m", path);
1669
1670 k = is_dir_fd(pfd);
1671 if (k == -ENOENT && r == -EROFS)
1672 return log_error_errno(r, "%s does not exist and cannot be created as the file system is read-only.", path);
1673 if (k < 0)
1674 return log_error_errno(k, "Failed to check if %s exists: %m", path);
1675 if (!k)
1676 return log_warning_errno(SYNTHETIC_ERRNO(EEXIST),
1677 "\"%s\" already exists and is not a directory.", path);
1678
1679 *creation = CREATION_EXISTING;
1680 } else
1681 *creation = CREATION_NORMAL;
1682
1683 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(*creation), path);
1684
1685 r = openat(pfd, basename(path), O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
1686 if (r < 0)
1687 return log_error_errno(errno, "Failed to open directory '%s': %m", basename(path));
1688
1689 return r;
1690 }
1691
1692 static int create_directory(Item *i, const char *path) {
1693 _cleanup_close_ int fd = -1;
1694
1695 assert(i);
1696 assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
1697
1698 fd = create_directory_or_subvolume(path, i->mode, false, NULL);
1699 if (fd == -EEXIST)
1700 return 0;
1701 if (fd < 0)
1702 return fd;
1703
1704 return fd_set_perms(i, fd, path, NULL);
1705 }
1706
1707 static int create_subvolume(Item *i, const char *path) {
1708 _cleanup_close_ int fd = -1;
1709 CreationMode creation;
1710 int r, q = 0;
1711
1712 assert(i);
1713 assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
1714
1715 fd = create_directory_or_subvolume(path, i->mode, true, &creation);
1716 if (fd == -EEXIST)
1717 return 0;
1718 if (fd < 0)
1719 return fd;
1720
1721 if (creation == CREATION_NORMAL &&
1722 IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
1723 r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
1724 if (r == -ENOTTY)
1725 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
1726 else if (r == -EROFS)
1727 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
1728 else if (r == -ENOTCONN)
1729 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
1730 else if (r < 0)
1731 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
1732 else if (r > 0)
1733 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
1734 else if (r == 0)
1735 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
1736 }
1737
1738 r = fd_set_perms(i, fd, path, NULL);
1739 if (q < 0) /* prefer the quota change error from above */
1740 return q;
1741
1742 return r;
1743 }
1744
1745 static int empty_directory(Item *i, const char *path) {
1746 int r;
1747
1748 assert(i);
1749 assert(i->type == EMPTY_DIRECTORY);
1750
1751 r = is_dir(path, false);
1752 if (r == -ENOENT) {
1753 /* Option "e" operates only on existing objects. Do not
1754 * print errors about non-existent files or directories */
1755 log_debug("Skipping missing directory: %s", path);
1756 return 0;
1757 }
1758 if (r < 0)
1759 return log_error_errno(r, "is_dir() failed on path %s: %m", path);
1760 if (r == 0) {
1761 log_warning("\"%s\" already exists and is not a directory.", path);
1762 return 0;
1763 }
1764
1765 return path_set_perms(i, path);
1766 }
1767
1768 static int create_device(Item *i, mode_t file_type) {
1769 _cleanup_close_ int dfd = -1, fd = -1;
1770 CreationMode creation;
1771 char *bn;
1772 int r;
1773
1774 assert(i);
1775 assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1776
1777 bn = basename(i->path);
1778
1779 /* Validate the path and use the returned directory fd for copying the
1780 * target so we're sure that the path can't be changed behind our
1781 * back. */
1782 dfd = path_open_parent_safe(i->path);
1783 if (dfd < 0)
1784 return dfd;
1785
1786 RUN_WITH_UMASK(0000) {
1787 mac_selinux_create_file_prepare(i->path, file_type);
1788 r = mknodat(dfd, bn, i->mode | file_type, i->major_minor);
1789 mac_selinux_create_file_clear();
1790 }
1791
1792 if (r < 0) {
1793 struct stat st;
1794
1795 if (errno == EPERM) {
1796 log_debug("We lack permissions, possibly because of cgroup configuration; "
1797 "skipping creation of device node %s.", i->path);
1798 return 0;
1799 }
1800
1801 if (errno != EEXIST)
1802 return log_error_errno(errno, "Failed to create device node %s: %m", i->path);
1803
1804 if (fstatat(dfd, bn, &st, 0) < 0)
1805 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
1806
1807 if ((st.st_mode & S_IFMT) != file_type) {
1808
1809 if (i->append_or_force) {
1810
1811 RUN_WITH_UMASK(0000) {
1812 mac_selinux_create_file_prepare(i->path, file_type);
1813 /* FIXME: need to introduce mknodat_atomic() */
1814 r = mknod_atomic(i->path, i->mode | file_type, i->major_minor);
1815 mac_selinux_create_file_clear();
1816 }
1817
1818 if (r < 0)
1819 return log_error_errno(r, "Failed to create device node \"%s\": %m", i->path);
1820 creation = CREATION_FORCE;
1821 } else {
1822 log_warning("\"%s\" already exists is not a device node.", i->path);
1823 return 0;
1824 }
1825 } else
1826 creation = CREATION_EXISTING;
1827 } else
1828 creation = CREATION_NORMAL;
1829
1830 log_debug("%s %s device node \"%s\" %u:%u.",
1831 creation_mode_verb_to_string(creation),
1832 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1833 i->path, major(i->mode), minor(i->mode));
1834
1835 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1836 if (fd < 0)
1837 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1838
1839 return fd_set_perms(i, fd, i->path, NULL);
1840 }
1841
1842 static int create_fifo(Item *i, const char *path) {
1843 _cleanup_close_ int pfd = -1, fd = -1;
1844 CreationMode creation;
1845 struct stat st;
1846 char *bn;
1847 int r;
1848
1849 pfd = path_open_parent_safe(path);
1850 if (pfd < 0)
1851 return pfd;
1852
1853 bn = basename(path);
1854
1855 RUN_WITH_UMASK(0000) {
1856 mac_selinux_create_file_prepare(path, S_IFIFO);
1857 r = mkfifoat(pfd, bn, i->mode);
1858 mac_selinux_create_file_clear();
1859 }
1860
1861 if (r < 0) {
1862 if (errno != EEXIST)
1863 return log_error_errno(errno, "Failed to create fifo %s: %m", path);
1864
1865 if (fstatat(pfd, bn, &st, AT_SYMLINK_NOFOLLOW) < 0)
1866 return log_error_errno(errno, "stat(%s) failed: %m", path);
1867
1868 if (!S_ISFIFO(st.st_mode)) {
1869
1870 if (i->append_or_force) {
1871 RUN_WITH_UMASK(0000) {
1872 mac_selinux_create_file_prepare(path, S_IFIFO);
1873 r = mkfifoat_atomic(pfd, bn, i->mode);
1874 mac_selinux_create_file_clear();
1875 }
1876
1877 if (r < 0)
1878 return log_error_errno(r, "Failed to create fifo %s: %m", path);
1879 creation = CREATION_FORCE;
1880 } else {
1881 log_warning("\"%s\" already exists and is not a fifo.", path);
1882 return 0;
1883 }
1884 } else
1885 creation = CREATION_EXISTING;
1886 } else
1887 creation = CREATION_NORMAL;
1888
1889 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), path);
1890
1891 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1892 if (fd < 0)
1893 return log_error_errno(errno, "Failed to openat(%s): %m", path);
1894
1895 return fd_set_perms(i, fd, i->path, NULL);
1896 }
1897
1898 typedef int (*action_t)(Item *i, const char *path);
1899 typedef int (*fdaction_t)(Item *i, int fd, const char *path, const struct stat *st);
1900
1901 static int item_do(Item *i, int fd, const char *path, fdaction_t action) {
1902 struct stat st;
1903 int r = 0, q;
1904
1905 assert(i);
1906 assert(path);
1907 assert(fd >= 0);
1908
1909 if (fstat(fd, &st) < 0) {
1910 r = log_error_errno(errno, "fstat() on file failed: %m");
1911 goto finish;
1912 }
1913
1914 /* This returns the first error we run into, but nevertheless
1915 * tries to go on */
1916 r = action(i, fd, path, &st);
1917
1918 if (S_ISDIR(st.st_mode)) {
1919 _cleanup_closedir_ DIR *d = NULL;
1920
1921 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
1922 * reading the directory content. */
1923 d = opendir(FORMAT_PROC_FD_PATH(fd));
1924 if (!d) {
1925 log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd));
1926 if (r == 0)
1927 r = -errno;
1928 goto finish;
1929 }
1930
1931 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
1932 int de_fd;
1933
1934 if (dot_or_dot_dot(de->d_name))
1935 continue;
1936
1937 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1938 if (de_fd < 0)
1939 q = log_error_errno(errno, "Failed to open() file '%s': %m", de->d_name);
1940 else {
1941 _cleanup_free_ char *de_path = NULL;
1942
1943 de_path = path_join(path, de->d_name);
1944 if (!de_path)
1945 q = log_oom();
1946 else
1947 /* Pass ownership of dirent fd over */
1948 q = item_do(i, de_fd, de_path, action);
1949 }
1950
1951 if (q < 0 && r == 0)
1952 r = q;
1953 }
1954 }
1955 finish:
1956 safe_close(fd);
1957 return r;
1958 }
1959
1960 static int glob_item(Item *i, action_t action) {
1961 _cleanup_globfree_ glob_t g = {
1962 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
1963 };
1964 int r = 0, k;
1965
1966 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1967 if (k < 0 && k != -ENOENT)
1968 return log_error_errno(k, "glob(%s) failed: %m", i->path);
1969
1970 STRV_FOREACH(fn, g.gl_pathv) {
1971 k = action(i, *fn);
1972 if (k < 0 && r == 0)
1973 r = k;
1974 }
1975
1976 return r;
1977 }
1978
1979 static int glob_item_recursively(Item *i, fdaction_t action) {
1980 _cleanup_globfree_ glob_t g = {
1981 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
1982 };
1983 int r = 0, k;
1984
1985 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1986 if (k < 0 && k != -ENOENT)
1987 return log_error_errno(k, "glob(%s) failed: %m", i->path);
1988
1989 STRV_FOREACH(fn, g.gl_pathv) {
1990 _cleanup_close_ int fd = -1;
1991
1992 /* Make sure we won't trigger/follow file object (such as
1993 * device nodes, automounts, ...) pointed out by 'fn' with
1994 * O_PATH. Note, when O_PATH is used, flags other than
1995 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1996
1997 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
1998 if (fd < 0) {
1999 log_error_errno(errno, "Opening '%s' failed: %m", *fn);
2000 if (r == 0)
2001 r = -errno;
2002 continue;
2003 }
2004
2005 k = item_do(i, fd, *fn, action);
2006 if (k < 0 && r == 0)
2007 r = k;
2008
2009 /* we passed fd ownership to the previous call */
2010 fd = -1;
2011 }
2012
2013 return r;
2014 }
2015
2016 static int rm_if_wrong_type_safe(
2017 mode_t mode,
2018 int parent_fd,
2019 const struct stat *parent_st, /* Only used if follow_links below is true. */
2020 const char *name,
2021 int flags) {
2022 _cleanup_free_ char *parent_name = NULL;
2023 bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
2024 struct stat st;
2025 int r;
2026
2027 assert(name);
2028 assert((mode & ~S_IFMT) == 0);
2029 assert(!follow_links || parent_st);
2030 assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
2031
2032 if (!filename_is_valid(name))
2033 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
2034
2035 r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2036 if (r < 0) {
2037 (void) fd_get_path(parent_fd, &parent_name);
2038 return log_full_errno(r == -ENOENT? LOG_DEBUG : LOG_ERR, r,
2039 "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2040 }
2041
2042 /* Fail before removing anything if this is an unsafe transition. */
2043 if (follow_links && unsafe_transition(parent_st, &st)) {
2044 (void) fd_get_path(parent_fd, &parent_name);
2045 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
2046 "Unsafe transition from \"%s\" to \"%s\".", parent_name, name);
2047 }
2048
2049 if ((st.st_mode & S_IFMT) == mode)
2050 return 0;
2051
2052 (void) fd_get_path(parent_fd, &parent_name);
2053 log_notice("Wrong file type 0x%x; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, strna(parent_name), name);
2054
2055 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2056 * target, so make sure it is identified as a link and not a directory. */
2057 if (follow_links) {
2058 r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2059 if (r < 0)
2060 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2061 }
2062
2063 /* Do not remove mount points. */
2064 r = fd_is_mount_point(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
2065 if (r < 0)
2066 (void) log_warning_errno(r, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2067 strna(parent_name), name);
2068 else if (r > 0)
2069 return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
2070 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name), name);
2071
2072 if ((st.st_mode & S_IFMT) == S_IFDIR) {
2073 _cleanup_close_ int child_fd = -1;
2074
2075 child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2076 if (child_fd < 0)
2077 return log_error_errno(errno, "Failed to open \"%s\" at \"%s\": %m", name, strna(parent_name));
2078
2079 r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);
2080 if (r < 0)
2081 return log_error_errno(r, "Failed to remove contents of \"%s\" at \"%s\": %m", name, strna(parent_name));
2082
2083 r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2084 } else
2085 r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2086 if (r < 0)
2087 return log_error_errno(r, "Failed to remove \"%s\" at \"%s\": %m", name, strna(parent_name));
2088
2089 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2090 * context to other error messages that might follow. */
2091 return -ENOENT;
2092 }
2093
2094 /* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2095 static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
2096 _cleanup_close_ int parent_fd = -1;
2097 struct stat parent_st;
2098 size_t path_len;
2099 int r;
2100
2101 assert(path);
2102 assert((child_mode & ~S_IFMT) == 0);
2103
2104 path_len = strlen(path);
2105
2106 if (!is_path(path))
2107 /* rm_if_wrong_type_safe already logs errors. */
2108 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW) : 0;
2109
2110 if (child_mode != 0 && endswith(path, "/"))
2111 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2112 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2113
2114 /* Get the parent_fd and stat. */
2115 parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2116 if (parent_fd < 0)
2117 return log_error_errno(errno, "Failed to open root: %m");
2118
2119 if (fstat(parent_fd, &parent_st) < 0)
2120 return log_error_errno(errno, "Failed to stat root: %m");
2121
2122 /* Check every parent directory in the path, except the last component */
2123 for (const char *e = path;;) {
2124 _cleanup_close_ int next_fd = -1;
2125 char t[path_len + 1];
2126 const char *s;
2127
2128 /* Find the start of the next path component. */
2129 s = e + strspn(e, "/");
2130 /* Find the end of the next path component. */
2131 e = s + strcspn(s, "/");
2132
2133 /* Copy the path component to t so it can be a null terminated string. */
2134 *((char*) mempcpy(t, s, e - s)) = 0;
2135
2136 /* Is this the last component? If so, then check the type */
2137 if (*e == 0)
2138 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW) : 0;
2139
2140 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
2141 /* Remove dangling symlinks. */
2142 if (r == -ENOENT)
2143 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
2144 if (r == -ENOENT) {
2145 RUN_WITH_UMASK(0000)
2146 r = mkdirat_label(parent_fd, t, 0755);
2147 if (r < 0) {
2148 _cleanup_free_ char *parent_name = NULL;
2149
2150 (void) fd_get_path(parent_fd, &parent_name);
2151 return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
2152 }
2153 } else if (r < 0)
2154 /* rm_if_wrong_type_safe already logs errors. */
2155 return r;
2156
2157 next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
2158 if (next_fd < 0) {
2159 _cleanup_free_ char *parent_name = NULL;
2160
2161 (void) fd_get_path(parent_fd, &parent_name);
2162 return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
2163 }
2164 r = RET_NERRNO(fstat(next_fd, &parent_st));
2165 if (r < 0) {
2166 _cleanup_free_ char *parent_name = NULL;
2167
2168 (void) fd_get_path(parent_fd, &parent_name);
2169 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
2170 }
2171
2172 CLOSE_AND_REPLACE(parent_fd, next_fd);
2173 }
2174 }
2175
2176 static int mkdir_parents_item(Item *i, mode_t child_mode) {
2177 int r;
2178 if (i->try_replace) {
2179 r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
2180 if (r < 0 && r != -ENOENT)
2181 return r;
2182 } else
2183 RUN_WITH_UMASK(0000)
2184 (void) mkdir_parents_label(i->path, 0755);
2185
2186 return 0;
2187 }
2188
2189 static int create_item(Item *i) {
2190 CreationMode creation;
2191 int r = 0;
2192
2193 assert(i);
2194
2195 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
2196
2197 switch (i->type) {
2198
2199 case IGNORE_PATH:
2200 case IGNORE_DIRECTORY_PATH:
2201 case REMOVE_PATH:
2202 case RECURSIVE_REMOVE_PATH:
2203 return 0;
2204
2205 case TRUNCATE_FILE:
2206 case CREATE_FILE:
2207 r = mkdir_parents_item(i, S_IFREG);
2208 if (r < 0)
2209 return r;
2210
2211 if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
2212 r = truncate_file(i, i->path);
2213 else
2214 r = create_file(i, i->path);
2215
2216 if (r < 0)
2217 return r;
2218 break;
2219
2220 case COPY_FILES:
2221 r = mkdir_parents_item(i, 0);
2222 if (r < 0)
2223 return r;
2224
2225 r = copy_files(i);
2226 if (r < 0)
2227 return r;
2228 break;
2229
2230 case WRITE_FILE:
2231 r = glob_item(i, write_one_file);
2232 if (r < 0)
2233 return r;
2234
2235 break;
2236
2237 case CREATE_DIRECTORY:
2238 case TRUNCATE_DIRECTORY:
2239 r = mkdir_parents_item(i, S_IFDIR);
2240 if (r < 0)
2241 return r;
2242
2243 r = create_directory(i, i->path);
2244 if (r < 0)
2245 return r;
2246 break;
2247
2248 case CREATE_SUBVOLUME:
2249 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2250 case CREATE_SUBVOLUME_NEW_QUOTA:
2251 r = mkdir_parents_item(i, S_IFDIR);
2252 if (r < 0)
2253 return r;
2254
2255 r = create_subvolume(i, i->path);
2256 if (r < 0)
2257 return r;
2258 break;
2259
2260 case EMPTY_DIRECTORY:
2261 r = glob_item(i, empty_directory);
2262 if (r < 0)
2263 return r;
2264 break;
2265
2266 case CREATE_FIFO:
2267 r = mkdir_parents_item(i, S_IFIFO);
2268 if (r < 0)
2269 return r;
2270
2271 r = create_fifo(i, i->path);
2272 if (r < 0)
2273 return r;
2274 break;
2275
2276 case CREATE_SYMLINK: {
2277 r = mkdir_parents_item(i, S_IFLNK);
2278 if (r < 0)
2279 return r;
2280
2281 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2282 r = symlink(i->argument, i->path);
2283 mac_selinux_create_file_clear();
2284
2285 if (r < 0) {
2286 _cleanup_free_ char *x = NULL;
2287
2288 if (errno != EEXIST)
2289 return log_error_errno(errno, "symlink(%s, %s) failed: %m", i->argument, i->path);
2290
2291 r = readlink_malloc(i->path, &x);
2292 if (r < 0 || !streq(i->argument, x)) {
2293
2294 if (i->append_or_force) {
2295 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2296 r = symlink_atomic(i->argument, i->path);
2297 mac_selinux_create_file_clear();
2298
2299 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2300 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL);
2301 if (r < 0)
2302 return log_error_errno(r, "rm -fr %s failed: %m", i->path);
2303
2304 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2305 r = RET_NERRNO(symlink(i->argument, i->path));
2306 mac_selinux_create_file_clear();
2307 }
2308 if (r < 0)
2309 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
2310
2311 creation = CREATION_FORCE;
2312 } else {
2313 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
2314 return 0;
2315 }
2316 } else
2317 creation = CREATION_EXISTING;
2318 } else
2319
2320 creation = CREATION_NORMAL;
2321 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
2322 break;
2323 }
2324
2325 case CREATE_BLOCK_DEVICE:
2326 case CREATE_CHAR_DEVICE:
2327 if (have_effective_cap(CAP_MKNOD) == 0) {
2328 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2329 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2330
2331 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
2332 return 0;
2333 }
2334
2335 r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2336 if (r < 0)
2337 return r;
2338
2339 r = create_device(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2340 if (r < 0)
2341 return r;
2342
2343 break;
2344
2345 case ADJUST_MODE:
2346 case RELABEL_PATH:
2347 r = glob_item(i, path_set_perms);
2348 if (r < 0)
2349 return r;
2350 break;
2351
2352 case RECURSIVE_RELABEL_PATH:
2353 r = glob_item_recursively(i, fd_set_perms);
2354 if (r < 0)
2355 return r;
2356 break;
2357
2358 case SET_XATTR:
2359 r = glob_item(i, path_set_xattrs);
2360 if (r < 0)
2361 return r;
2362 break;
2363
2364 case RECURSIVE_SET_XATTR:
2365 r = glob_item_recursively(i, fd_set_xattrs);
2366 if (r < 0)
2367 return r;
2368 break;
2369
2370 case SET_ACL:
2371 r = glob_item(i, path_set_acls);
2372 if (r < 0)
2373 return r;
2374 break;
2375
2376 case RECURSIVE_SET_ACL:
2377 r = glob_item_recursively(i, fd_set_acls);
2378 if (r < 0)
2379 return r;
2380 break;
2381
2382 case SET_ATTRIBUTE:
2383 r = glob_item(i, path_set_attribute);
2384 if (r < 0)
2385 return r;
2386 break;
2387
2388 case RECURSIVE_SET_ATTRIBUTE:
2389 r = glob_item_recursively(i, fd_set_attribute);
2390 if (r < 0)
2391 return r;
2392 break;
2393 }
2394
2395 return 0;
2396 }
2397
2398 static int remove_item_instance(Item *i, const char *instance) {
2399 int r;
2400
2401 assert(i);
2402
2403 switch (i->type) {
2404
2405 case REMOVE_PATH:
2406 if (remove(instance) < 0 && errno != ENOENT)
2407 return log_error_errno(errno, "rm(%s): %m", instance);
2408
2409 break;
2410
2411 case RECURSIVE_REMOVE_PATH:
2412 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2413 log_debug("rm -rf \"%s\"", instance);
2414 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
2415 if (r < 0 && r != -ENOENT)
2416 return log_error_errno(r, "rm_rf(%s): %m", instance);
2417
2418 break;
2419
2420 default:
2421 assert_not_reached();
2422 }
2423
2424 return 0;
2425 }
2426
2427 static int remove_item(Item *i) {
2428 int r;
2429
2430 assert(i);
2431
2432 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2433
2434 switch (i->type) {
2435
2436 case TRUNCATE_DIRECTORY:
2437 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2438 log_debug("rm -rf \"%s\"", i->path);
2439 r = rm_rf(i->path, REMOVE_PHYSICAL);
2440 if (r < 0 && r != -ENOENT)
2441 return log_error_errno(r, "rm_rf(%s): %m", i->path);
2442
2443 return 0;
2444
2445 case REMOVE_PATH:
2446 case RECURSIVE_REMOVE_PATH:
2447 return glob_item(i, remove_item_instance);
2448
2449 default:
2450 return 0;
2451 }
2452 }
2453
2454 static char *age_by_to_string(AgeBy ab, bool is_dir) {
2455 static const char ab_map[] = { 'a', 'b', 'c', 'm' };
2456 size_t j = 0;
2457 char *ret;
2458
2459 ret = new(char, ELEMENTSOF(ab_map) + 1);
2460 if (!ret)
2461 return NULL;
2462
2463 for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
2464 if (FLAGS_SET(ab, 1U << i))
2465 ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
2466
2467 ret[j] = 0;
2468 return ret;
2469 }
2470
2471 static int clean_item_instance(Item *i, const char* instance) {
2472 _cleanup_closedir_ DIR *d = NULL;
2473 STRUCT_STATX_DEFINE(sx);
2474 int mountpoint, r;
2475 usec_t cutoff, n;
2476
2477 assert(i);
2478
2479 if (!i->age_set)
2480 return 0;
2481
2482 n = now(CLOCK_REALTIME);
2483 if (n < i->age)
2484 return 0;
2485
2486 cutoff = n - i->age;
2487
2488 d = opendir_nomod(instance);
2489 if (!d) {
2490 if (IN_SET(errno, ENOENT, ENOTDIR)) {
2491 log_debug_errno(errno, "Directory \"%s\": %m", instance);
2492 return 0;
2493 }
2494
2495 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
2496 }
2497
2498 r = statx_fallback(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx);
2499 if (r < 0)
2500 return log_error_errno(r, "statx(%s) failed: %m", instance);
2501
2502 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
2503 mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
2504 else {
2505 struct stat ps;
2506
2507 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
2508 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
2509
2510 mountpoint =
2511 sx.stx_dev_major != major(ps.st_dev) ||
2512 sx.stx_dev_minor != minor(ps.st_dev) ||
2513 sx.stx_ino != ps.st_ino;
2514 }
2515
2516 if (DEBUG_LOGGING) {
2517 _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
2518
2519 ab_f = age_by_to_string(i->age_by_file, false);
2520 if (!ab_f)
2521 return log_oom();
2522
2523 ab_d = age_by_to_string(i->age_by_dir, true);
2524 if (!ab_d)
2525 return log_oom();
2526
2527 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
2528 mountpoint ? "mount point" : "directory",
2529 instance,
2530 FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
2531 ab_f, ab_d);
2532 }
2533
2534 return dir_cleanup(i, instance, d,
2535 load_statx_timestamp_nsec(&sx.stx_atime),
2536 load_statx_timestamp_nsec(&sx.stx_mtime),
2537 cutoff * NSEC_PER_USEC,
2538 sx.stx_dev_major, sx.stx_dev_minor, mountpoint,
2539 MAX_DEPTH, i->keep_first_level,
2540 i->age_by_file, i->age_by_dir);
2541 }
2542
2543 static int clean_item(Item *i) {
2544 assert(i);
2545
2546 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
2547
2548 switch (i->type) {
2549 case CREATE_DIRECTORY:
2550 case CREATE_SUBVOLUME:
2551 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2552 case CREATE_SUBVOLUME_NEW_QUOTA:
2553 case TRUNCATE_DIRECTORY:
2554 case IGNORE_PATH:
2555 case COPY_FILES:
2556 clean_item_instance(i, i->path);
2557 return 0;
2558 case EMPTY_DIRECTORY:
2559 case IGNORE_DIRECTORY_PATH:
2560 return glob_item(i, clean_item_instance);
2561 default:
2562 return 0;
2563 }
2564 }
2565
2566 static int process_item(Item *i, OperationMask operation) {
2567 OperationMask todo;
2568 _cleanup_free_ char *_path = NULL;
2569 const char *path;
2570 int r, q, p;
2571
2572 assert(i);
2573
2574 todo = operation & ~i->done;
2575 if (todo == 0) /* Everything already done? */
2576 return 0;
2577
2578 i->done |= operation;
2579
2580 path = i->path;
2581 if (string_is_glob(path)) {
2582 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
2583 * for the non-glob part. */
2584
2585 r = glob_non_glob_prefix(path, &_path);
2586 if (r < 0 && r != -ENOENT)
2587 return log_debug_errno(r, "Failed to deglob path: %m");
2588 if (r >= 0)
2589 path = _path;
2590 }
2591
2592 r = chase_symlinks(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
2593 if (r == -EREMOTE) {
2594 log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
2595 return 0;
2596 }
2597 if (r < 0)
2598 log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
2599
2600 r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(i) : 0;
2601 /* Failure can only be tolerated for create */
2602 if (i->allow_failure)
2603 r = 0;
2604
2605 q = FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(i) : 0;
2606 p = FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(i) : 0;
2607
2608 return r < 0 ? r :
2609 q < 0 ? q :
2610 p;
2611 }
2612
2613 static int process_item_array(ItemArray *array, OperationMask operation) {
2614 int r = 0;
2615 size_t n;
2616
2617 assert(array);
2618
2619 /* Create any parent first. */
2620 if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
2621 r = process_item_array(array->parent, operation & OPERATION_CREATE);
2622
2623 /* Clean up all children first */
2624 if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN)) && !set_isempty(array->children)) {
2625 ItemArray *c;
2626
2627 SET_FOREACH(c, array->children) {
2628 int k;
2629
2630 k = process_item_array(c, operation & (OPERATION_REMOVE|OPERATION_CLEAN));
2631 if (k < 0 && r == 0)
2632 r = k;
2633 }
2634 }
2635
2636 for (n = 0; n < array->n_items; n++) {
2637 int k;
2638
2639 k = process_item(array->items + n, operation);
2640 if (k < 0 && r == 0)
2641 r = k;
2642 }
2643
2644 return r;
2645 }
2646
2647 static void item_free_contents(Item *i) {
2648 assert(i);
2649 free(i->path);
2650 free(i->argument);
2651 strv_free(i->xattrs);
2652
2653 #if HAVE_ACL
2654 acl_free(i->acl_access);
2655 acl_free(i->acl_default);
2656 #endif
2657 }
2658
2659 static ItemArray* item_array_free(ItemArray *a) {
2660 size_t n;
2661
2662 if (!a)
2663 return NULL;
2664
2665 for (n = 0; n < a->n_items; n++)
2666 item_free_contents(a->items + n);
2667
2668 set_free(a->children);
2669 free(a->items);
2670 return mfree(a);
2671 }
2672
2673 static int item_compare(const Item *a, const Item *b) {
2674 /* Make sure that the ownership taking item is put first, so
2675 * that we first create the node, and then can adjust it */
2676
2677 if (takes_ownership(a->type) && !takes_ownership(b->type))
2678 return -1;
2679 if (!takes_ownership(a->type) && takes_ownership(b->type))
2680 return 1;
2681
2682 return CMP(a->type, b->type);
2683 }
2684
2685 static bool item_compatible(Item *a, Item *b) {
2686 assert(a);
2687 assert(b);
2688 assert(streq(a->path, b->path));
2689
2690 if (takes_ownership(a->type) && takes_ownership(b->type))
2691 /* check if the items are the same */
2692 return streq_ptr(a->argument, b->argument) &&
2693
2694 a->uid_set == b->uid_set &&
2695 a->uid == b->uid &&
2696
2697 a->gid_set == b->gid_set &&
2698 a->gid == b->gid &&
2699
2700 a->mode_set == b->mode_set &&
2701 a->mode == b->mode &&
2702
2703 a->age_set == b->age_set &&
2704 a->age == b->age &&
2705
2706 a->age_by_file == b->age_by_file &&
2707 a->age_by_dir == b->age_by_dir &&
2708
2709 a->mask_perms == b->mask_perms &&
2710
2711 a->keep_first_level == b->keep_first_level &&
2712
2713 a->major_minor == b->major_minor;
2714
2715 return true;
2716 }
2717
2718 static bool should_include_path(const char *path) {
2719 STRV_FOREACH(prefix, arg_exclude_prefixes)
2720 if (path_startswith(path, *prefix)) {
2721 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2722 path, *prefix);
2723 return false;
2724 }
2725
2726 STRV_FOREACH(prefix, arg_include_prefixes)
2727 if (path_startswith(path, *prefix)) {
2728 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
2729 return true;
2730 }
2731
2732 /* no matches, so we should include this path only if we have no allow list at all */
2733 if (strv_isempty(arg_include_prefixes))
2734 return true;
2735
2736 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
2737 return false;
2738 }
2739
2740 static int specifier_expansion_from_arg(Item *i) {
2741 int r;
2742
2743 assert(i);
2744
2745 if (!i->argument)
2746 return 0;
2747
2748 switch (i->type) {
2749 case COPY_FILES:
2750 case CREATE_SYMLINK:
2751 case CREATE_FILE:
2752 case TRUNCATE_FILE:
2753 case WRITE_FILE: {
2754 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2755 ssize_t l;
2756
2757 l = cunescape(i->argument, 0, &unescaped);
2758 if (l < 0)
2759 return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
2760
2761 r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
2762 if (r < 0)
2763 return r;
2764
2765 return free_and_replace(i->argument, resolved);
2766 }
2767 case SET_XATTR:
2768 case RECURSIVE_SET_XATTR:
2769 STRV_FOREACH(xattr, i->xattrs) {
2770 _cleanup_free_ char *resolved = NULL;
2771
2772 r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
2773 if (r < 0)
2774 return r;
2775
2776 free_and_replace(*xattr, resolved);
2777 }
2778 return 0;
2779
2780 default:
2781 return 0;
2782 }
2783 }
2784
2785 static int patch_var_run(const char *fname, unsigned line, char **path) {
2786 const char *k;
2787 char *n;
2788
2789 assert(path);
2790 assert(*path);
2791
2792 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2793 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2794 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2795 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2796 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2797 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2798 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2799 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2800 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2801
2802 k = path_startswith(*path, "/var/run/");
2803 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2804 return 0;
2805
2806 n = path_join("/run", k);
2807 if (!n)
2808 return log_oom();
2809
2810 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2811 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2812 * to the user, let's still inform the user that these snippets should really be updated. */
2813 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
2814 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
2815 *path, n);
2816
2817 free_and_replace(*path, n);
2818
2819 return 0;
2820 }
2821
2822 static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
2823 int r;
2824
2825 assert(user);
2826 assert(ret_uid);
2827
2828 /* First: parse as numeric UID string */
2829 r = parse_uid(user, ret_uid);
2830 if (r >= 0)
2831 return r;
2832
2833 /* Second: pass to NSS if we are running "online" */
2834 if (!arg_root)
2835 return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
2836
2837 /* Third, synthesize "root" unconditionally */
2838 if (streq(user, "root")) {
2839 *ret_uid = 0;
2840 return 0;
2841 }
2842
2843 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
2844 return name_to_uid_offline(arg_root, user, ret_uid, cache);
2845 }
2846
2847 static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
2848 int r;
2849
2850 assert(group);
2851 assert(ret_gid);
2852
2853 /* First: parse as numeric GID string */
2854 r = parse_gid(group, ret_gid);
2855 if (r >= 0)
2856 return r;
2857
2858 /* Second: pass to NSS if we are running "online" */
2859 if (!arg_root)
2860 return get_group_creds(&group, ret_gid, 0);
2861
2862 /* Third, synthesize "root" unconditionally */
2863 if (streq(group, "root")) {
2864 *ret_gid = 0;
2865 return 0;
2866 }
2867
2868 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
2869 return name_to_gid_offline(arg_root, group, ret_gid, cache);
2870 }
2871
2872 static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
2873 AgeBy ab_f = 0, ab_d = 0;
2874
2875 static const struct {
2876 char age_by_chr;
2877 AgeBy age_by_flag;
2878 } age_by_types[] = {
2879 { 'a', AGE_BY_ATIME },
2880 { 'b', AGE_BY_BTIME },
2881 { 'c', AGE_BY_CTIME },
2882 { 'm', AGE_BY_MTIME },
2883 };
2884
2885 assert(age_by_str);
2886 assert(item);
2887
2888 if (isempty(age_by_str))
2889 return -EINVAL;
2890
2891 for (const char *s = age_by_str; *s != 0; s++) {
2892 size_t i;
2893
2894 /* Ignore whitespace. */
2895 if (strchr(WHITESPACE, *s))
2896 continue;
2897
2898 for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
2899 /* Check lower-case for files, upper-case for directories. */
2900 if (*s == age_by_types[i].age_by_chr) {
2901 ab_f |= age_by_types[i].age_by_flag;
2902 break;
2903 } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
2904 ab_d |= age_by_types[i].age_by_flag;
2905 break;
2906 }
2907 }
2908
2909 /* Invalid character. */
2910 if (i >= ELEMENTSOF(age_by_types))
2911 return -EINVAL;
2912 }
2913
2914 /* No match. */
2915 if (ab_f == 0 && ab_d == 0)
2916 return -EINVAL;
2917
2918 item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
2919 item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
2920
2921 return 0;
2922 }
2923
2924 static int parse_line(
2925 const char *fname,
2926 unsigned line,
2927 const char *buffer,
2928 bool *invalid_config,
2929 Hashmap **uid_cache,
2930 Hashmap **gid_cache) {
2931
2932 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
2933 _cleanup_(item_free_contents) Item i = {
2934 /* The "age-by" argument considers all file timestamp types by default. */
2935 .age_by_file = AGE_BY_DEFAULT_FILE,
2936 .age_by_dir = AGE_BY_DEFAULT_DIR,
2937 };
2938 ItemArray *existing;
2939 OrderedHashmap *h;
2940 int r, pos;
2941 bool append_or_force = false, boot = false, allow_failure = false, try_replace = false;
2942
2943 assert(fname);
2944 assert(line >= 1);
2945 assert(buffer);
2946
2947 r = extract_many_words(
2948 &buffer,
2949 NULL,
2950 EXTRACT_UNQUOTE,
2951 &action,
2952 &path,
2953 &mode,
2954 &user,
2955 &group,
2956 &age,
2957 NULL);
2958 if (r < 0) {
2959 if (IN_SET(r, -EINVAL, -EBADSLT))
2960 /* invalid quoting and such or an unknown specifier */
2961 *invalid_config = true;
2962 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
2963 } else if (r < 2) {
2964 *invalid_config = true;
2965 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
2966 }
2967
2968 if (!empty_or_dash(buffer)) {
2969 i.argument = strdup(buffer);
2970 if (!i.argument)
2971 return log_oom();
2972 }
2973
2974 if (isempty(action)) {
2975 *invalid_config = true;
2976 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Command too short '%s'.", action);
2977 }
2978
2979 for (pos = 1; action[pos]; pos++) {
2980 if (action[pos] == '!' && !boot)
2981 boot = true;
2982 else if (action[pos] == '+' && !append_or_force)
2983 append_or_force = true;
2984 else if (action[pos] == '-' && !allow_failure)
2985 allow_failure = true;
2986 else if (action[pos] == '=' && !try_replace)
2987 try_replace = true;
2988 else {
2989 *invalid_config = true;
2990 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Unknown modifiers in command '%s'", action);
2991 }
2992 }
2993
2994 if (boot && !arg_boot) {
2995 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
2996 return 0;
2997 }
2998
2999 i.type = action[0];
3000 i.append_or_force = append_or_force;
3001 i.allow_failure = allow_failure;
3002 i.try_replace = try_replace;
3003
3004 r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
3005 if (r == -ENXIO)
3006 return log_unresolvable_specifier(fname, line);
3007 if (r < 0) {
3008 if (IN_SET(r, -EINVAL, -EBADSLT))
3009 *invalid_config = true;
3010 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", path);
3011 }
3012
3013 r = patch_var_run(fname, line, &i.path);
3014 if (r < 0)
3015 return r;
3016
3017 switch (i.type) {
3018
3019 case CREATE_DIRECTORY:
3020 case CREATE_SUBVOLUME:
3021 case CREATE_SUBVOLUME_INHERIT_QUOTA:
3022 case CREATE_SUBVOLUME_NEW_QUOTA:
3023 case EMPTY_DIRECTORY:
3024 case TRUNCATE_DIRECTORY:
3025 case CREATE_FIFO:
3026 case IGNORE_PATH:
3027 case IGNORE_DIRECTORY_PATH:
3028 case REMOVE_PATH:
3029 case RECURSIVE_REMOVE_PATH:
3030 case ADJUST_MODE:
3031 case RELABEL_PATH:
3032 case RECURSIVE_RELABEL_PATH:
3033 if (i.argument)
3034 log_syntax(NULL, LOG_WARNING, fname, line, 0, "%c lines don't take argument fields, ignoring.", i.type);
3035
3036 break;
3037
3038 case CREATE_FILE:
3039 case TRUNCATE_FILE:
3040 break;
3041
3042 case CREATE_SYMLINK:
3043 if (!i.argument) {
3044 i.argument = path_join("/usr/share/factory", i.path);
3045 if (!i.argument)
3046 return log_oom();
3047 }
3048 break;
3049
3050 case WRITE_FILE:
3051 if (!i.argument) {
3052 *invalid_config = true;
3053 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Write file requires argument.");
3054 }
3055 break;
3056
3057 case COPY_FILES:
3058 if (!i.argument) {
3059 i.argument = path_join("/usr/share/factory", i.path);
3060 if (!i.argument)
3061 return log_oom();
3062
3063 } else if (!path_is_absolute(i.argument)) {
3064 *invalid_config = true;
3065 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Source path '%s' is not absolute.", i.argument);
3066
3067 }
3068
3069 if (!empty_or_root(arg_root)) {
3070 char *p;
3071
3072 p = path_join(arg_root, i.argument);
3073 if (!p)
3074 return log_oom();
3075 free_and_replace(i.argument, p);
3076 }
3077
3078 path_simplify(i.argument);
3079 break;
3080
3081 case CREATE_CHAR_DEVICE:
3082 case CREATE_BLOCK_DEVICE:
3083 if (!i.argument) {
3084 *invalid_config = true;
3085 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Device file requires argument.");
3086 }
3087
3088 r = parse_dev(i.argument, &i.major_minor);
3089 if (r < 0) {
3090 *invalid_config = true;
3091 return log_syntax(NULL, LOG_ERR, fname, line, r, "Can't parse device file major/minor '%s'.", i.argument);
3092 }
3093
3094 break;
3095
3096 case SET_XATTR:
3097 case RECURSIVE_SET_XATTR:
3098 if (!i.argument) {
3099 *invalid_config = true;
3100 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3101 "Set extended attribute requires argument.");
3102 }
3103 r = parse_xattrs_from_arg(&i);
3104 if (r < 0)
3105 return r;
3106 break;
3107
3108 case SET_ACL:
3109 case RECURSIVE_SET_ACL:
3110 if (!i.argument) {
3111 *invalid_config = true;
3112 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3113 "Set ACLs requires argument.");
3114 }
3115 r = parse_acls_from_arg(&i);
3116 if (r < 0)
3117 return r;
3118 break;
3119
3120 case SET_ATTRIBUTE:
3121 case RECURSIVE_SET_ATTRIBUTE:
3122 if (!i.argument) {
3123 *invalid_config = true;
3124 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3125 "Set file attribute requires argument.");
3126 }
3127 r = parse_attribute_from_arg(&i);
3128 if (IN_SET(r, -EINVAL, -EBADSLT))
3129 *invalid_config = true;
3130 if (r < 0)
3131 return r;
3132 break;
3133
3134 default:
3135 *invalid_config = true;
3136 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3137 "Unknown command type '%c'.", (char) i.type);
3138 }
3139
3140 if (!path_is_absolute(i.path)) {
3141 *invalid_config = true;
3142 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3143 "Path '%s' not absolute.", i.path);
3144 }
3145
3146 path_simplify(i.path);
3147
3148 if (!should_include_path(i.path))
3149 return 0;
3150
3151 r = specifier_expansion_from_arg(&i);
3152 if (r == -ENXIO)
3153 return log_unresolvable_specifier(fname, line);
3154 if (r < 0) {
3155 if (IN_SET(r, -EINVAL, -EBADSLT))
3156 *invalid_config = true;
3157 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to substitute specifiers in argument: %m");
3158 }
3159
3160 if (!empty_or_root(arg_root)) {
3161 char *p;
3162
3163 p = path_join(arg_root, i.path);
3164 if (!p)
3165 return log_oom();
3166 free_and_replace(i.path, p);
3167 }
3168
3169 if (!empty_or_dash(user)) {
3170 r = find_uid(user, &i.uid, uid_cache);
3171 if (r < 0) {
3172 *invalid_config = true;
3173 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", user);
3174 }
3175
3176 i.uid_set = true;
3177 }
3178
3179 if (!empty_or_dash(group)) {
3180 r = find_gid(group, &i.gid, gid_cache);
3181 if (r < 0) {
3182 *invalid_config = true;
3183 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s'.", group);
3184 }
3185
3186 i.gid_set = true;
3187 }
3188
3189 if (!empty_or_dash(mode)) {
3190 const char *mm = mode;
3191 unsigned m;
3192
3193 if (*mm == '~') {
3194 i.mask_perms = true;
3195 mm++;
3196 }
3197
3198 r = parse_mode(mm, &m);
3199 if (r < 0) {
3200 *invalid_config = true;
3201 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
3202 }
3203
3204 i.mode = m;
3205 i.mode_set = true;
3206 } else
3207 i.mode = IN_SET(i.type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
3208
3209 if (!empty_or_dash(age)) {
3210 const char *a = age;
3211 _cleanup_free_ char *seconds = NULL, *age_by = NULL;
3212
3213 if (*a == '~') {
3214 i.keep_first_level = true;
3215 a++;
3216 }
3217
3218 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3219 r = split_pair(a, ":", &age_by, &seconds);
3220 if (r == -ENOMEM)
3221 return log_oom();
3222 if (r < 0 && r != -EINVAL)
3223 return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
3224 if (r >= 0) {
3225 /* We found a ":", parse the "age-by" part. */
3226 r = parse_age_by_from_arg(age_by, &i);
3227 if (r == -ENOMEM)
3228 return log_oom();
3229 if (r < 0) {
3230 *invalid_config = true;
3231 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
3232 }
3233
3234 /* For parsing the "age" part, after the ":". */
3235 a = seconds;
3236 }
3237
3238 r = parse_sec(a, &i.age);
3239 if (r < 0) {
3240 *invalid_config = true;
3241 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
3242 }
3243
3244 i.age_set = true;
3245 }
3246
3247 h = needs_glob(i.type) ? globs : items;
3248
3249 existing = ordered_hashmap_get(h, i.path);
3250 if (existing) {
3251 size_t n;
3252
3253 for (n = 0; n < existing->n_items; n++) {
3254 if (!item_compatible(existing->items + n, &i) && !i.append_or_force) {
3255 log_syntax(NULL, LOG_NOTICE, fname, line, 0, "Duplicate line for path \"%s\", ignoring.", i.path);
3256 return 0;
3257 }
3258 }
3259 } else {
3260 existing = new0(ItemArray, 1);
3261 if (!existing)
3262 return log_oom();
3263
3264 r = ordered_hashmap_put(h, i.path, existing);
3265 if (r < 0) {
3266 free(existing);
3267 return log_oom();
3268 }
3269 }
3270
3271 if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
3272 return log_oom();
3273
3274 existing->items[existing->n_items++] = i;
3275 i = (struct Item) {};
3276
3277 /* Sort item array, to enforce stable ordering of application */
3278 typesafe_qsort(existing->items, existing->n_items, item_compare);
3279
3280 return 0;
3281 }
3282
3283 static int cat_config(char **config_dirs, char **args) {
3284 _cleanup_strv_free_ char **files = NULL;
3285 int r;
3286
3287 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
3288 if (r < 0)
3289 return r;
3290
3291 return cat_files(NULL, files, 0);
3292 }
3293
3294 static int exclude_default_prefixes(void) {
3295 int r;
3296
3297 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3298 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3299 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3300 * all kinds of files created/adjusted underneath these mount points. */
3301
3302 r = strv_extend_strv(
3303 &arg_exclude_prefixes,
3304 STRV_MAKE("/dev",
3305 "/proc",
3306 "/run",
3307 "/sys"),
3308 true);
3309 if (r < 0)
3310 return log_oom();
3311
3312 return 0;
3313 }
3314
3315 static int help(void) {
3316 _cleanup_free_ char *link = NULL;
3317 int r;
3318
3319 r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
3320 if (r < 0)
3321 return log_oom();
3322
3323 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3324 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3325 " -h --help Show this help\n"
3326 " --user Execute user configuration\n"
3327 " --version Show package version\n"
3328 " --cat-config Show configuration files\n"
3329 " --create Create marked files/directories\n"
3330 " --clean Clean up marked directories\n"
3331 " --remove Remove marked files/directories\n"
3332 " --boot Execute actions only safe at boot\n"
3333 " --prefix=PATH Only apply rules with the specified prefix\n"
3334 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3335 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3336 " --root=PATH Operate on an alternate filesystem root\n"
3337 " --image=PATH Operate on disk image as filesystem root\n"
3338 " --replace=PATH Treat arguments as replacement for PATH\n"
3339 " --no-pager Do not pipe output into a pager\n"
3340 "\nSee the %s for details.\n",
3341 program_invocation_short_name,
3342 ansi_highlight(),
3343 ansi_normal(),
3344 link);
3345
3346 return 0;
3347 }
3348
3349 static int parse_argv(int argc, char *argv[]) {
3350
3351 enum {
3352 ARG_VERSION = 0x100,
3353 ARG_CAT_CONFIG,
3354 ARG_USER,
3355 ARG_CREATE,
3356 ARG_CLEAN,
3357 ARG_REMOVE,
3358 ARG_BOOT,
3359 ARG_PREFIX,
3360 ARG_EXCLUDE_PREFIX,
3361 ARG_ROOT,
3362 ARG_IMAGE,
3363 ARG_REPLACE,
3364 ARG_NO_PAGER,
3365 };
3366
3367 static const struct option options[] = {
3368 { "help", no_argument, NULL, 'h' },
3369 { "user", no_argument, NULL, ARG_USER },
3370 { "version", no_argument, NULL, ARG_VERSION },
3371 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
3372 { "create", no_argument, NULL, ARG_CREATE },
3373 { "clean", no_argument, NULL, ARG_CLEAN },
3374 { "remove", no_argument, NULL, ARG_REMOVE },
3375 { "boot", no_argument, NULL, ARG_BOOT },
3376 { "prefix", required_argument, NULL, ARG_PREFIX },
3377 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
3378 { "root", required_argument, NULL, ARG_ROOT },
3379 { "image", required_argument, NULL, ARG_IMAGE },
3380 { "replace", required_argument, NULL, ARG_REPLACE },
3381 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
3382 {}
3383 };
3384
3385 int c, r;
3386
3387 assert(argc >= 0);
3388 assert(argv);
3389
3390 while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3391
3392 switch (c) {
3393
3394 case 'h':
3395 return help();
3396
3397 case ARG_VERSION:
3398 return version();
3399
3400 case ARG_CAT_CONFIG:
3401 arg_cat_config = true;
3402 break;
3403
3404 case ARG_USER:
3405 arg_user = true;
3406 break;
3407
3408 case ARG_CREATE:
3409 arg_operation |= OPERATION_CREATE;
3410 break;
3411
3412 case ARG_CLEAN:
3413 arg_operation |= OPERATION_CLEAN;
3414 break;
3415
3416 case ARG_REMOVE:
3417 arg_operation |= OPERATION_REMOVE;
3418 break;
3419
3420 case ARG_BOOT:
3421 arg_boot = true;
3422 break;
3423
3424 case ARG_PREFIX:
3425 if (strv_push(&arg_include_prefixes, optarg) < 0)
3426 return log_oom();
3427 break;
3428
3429 case ARG_EXCLUDE_PREFIX:
3430 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
3431 return log_oom();
3432 break;
3433
3434 case ARG_ROOT:
3435 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
3436 if (r < 0)
3437 return r;
3438 break;
3439
3440 case ARG_IMAGE:
3441 #ifdef STANDALONE
3442 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3443 "This systemd-tmpfiles version is compiled without support for --image=.");
3444 #else
3445 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
3446 if (r < 0)
3447 return r;
3448 #endif
3449 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
3450 _fallthrough_;
3451
3452 case 'E':
3453 r = exclude_default_prefixes();
3454 if (r < 0)
3455 return r;
3456
3457 break;
3458
3459 case ARG_REPLACE:
3460 if (!path_is_absolute(optarg) ||
3461 !endswith(optarg, ".conf"))
3462 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3463 "The argument to --replace= must an absolute path to a config file");
3464
3465 arg_replace = optarg;
3466 break;
3467
3468 case ARG_NO_PAGER:
3469 arg_pager_flags |= PAGER_DISABLE;
3470 break;
3471
3472 case '?':
3473 return -EINVAL;
3474
3475 default:
3476 assert_not_reached();
3477 }
3478
3479 if (arg_operation == 0 && !arg_cat_config)
3480 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3481 "You need to specify at least one of --clean, --create or --remove.");
3482
3483 if (arg_replace && arg_cat_config)
3484 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3485 "Option --replace= is not supported with --cat-config");
3486
3487 if (arg_replace && optind >= argc)
3488 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3489 "When --replace= is given, some configuration items must be specified");
3490
3491 if (arg_root && arg_user)
3492 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3493 "Combination of --user and --root= is not supported.");
3494
3495 if (arg_image && arg_root)
3496 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
3497
3498 return 1;
3499 }
3500
3501 static int read_config_file(char **config_dirs, const char *fn, bool ignore_enoent, bool *invalid_config) {
3502 _cleanup_(hashmap_freep) Hashmap *uid_cache = NULL, *gid_cache = NULL;
3503 _cleanup_fclose_ FILE *_f = NULL;
3504 _cleanup_free_ char *pp = NULL;
3505 unsigned v = 0;
3506 FILE *f;
3507 ItemArray *ia;
3508 int r = 0;
3509
3510 assert(fn);
3511
3512 if (streq(fn, "-")) {
3513 log_debug("Reading config from stdin…");
3514 fn = "<stdin>";
3515 f = stdin;
3516 } else {
3517 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f, &pp);
3518 if (r < 0) {
3519 if (ignore_enoent && r == -ENOENT) {
3520 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
3521 return 0;
3522 }
3523
3524 return log_error_errno(r, "Failed to open '%s': %m", fn);
3525 }
3526
3527 log_debug("Reading config file \"%s\"…", pp);
3528 fn = pp;
3529 f = _f;
3530 }
3531
3532 for (;;) {
3533 _cleanup_free_ char *line = NULL;
3534 bool invalid_line = false;
3535 char *l;
3536 int k;
3537
3538 k = read_line(f, LONG_LINE_MAX, &line);
3539 if (k < 0)
3540 return log_error_errno(k, "Failed to read '%s': %m", fn);
3541 if (k == 0)
3542 break;
3543
3544 v++;
3545
3546 l = strstrip(line);
3547 if (IN_SET(*l, 0, '#'))
3548 continue;
3549
3550 k = parse_line(fn, v, l, &invalid_line, &uid_cache, &gid_cache);
3551 if (k < 0) {
3552 if (invalid_line)
3553 /* Allow reporting with a special code if the caller requested this */
3554 *invalid_config = true;
3555 else if (r == 0)
3556 /* The first error becomes our return value */
3557 r = k;
3558 }
3559 }
3560
3561 /* we have to determine age parameter for each entry of type X */
3562 ORDERED_HASHMAP_FOREACH(ia, globs)
3563 for (size_t ni = 0; ni < ia->n_items; ni++) {
3564 ItemArray *ja;
3565 Item *i = ia->items + ni, *candidate_item = NULL;
3566
3567 if (i->type != IGNORE_DIRECTORY_PATH)
3568 continue;
3569
3570 ORDERED_HASHMAP_FOREACH(ja, items)
3571 for (size_t nj = 0; nj < ja->n_items; nj++) {
3572 Item *j = ja->items + nj;
3573
3574 if (!IN_SET(j->type, CREATE_DIRECTORY,
3575 TRUNCATE_DIRECTORY,
3576 CREATE_SUBVOLUME,
3577 CREATE_SUBVOLUME_INHERIT_QUOTA,
3578 CREATE_SUBVOLUME_NEW_QUOTA))
3579 continue;
3580
3581 if (path_equal(j->path, i->path)) {
3582 candidate_item = j;
3583 break;
3584 }
3585
3586 if (candidate_item
3587 ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
3588 : path_startswith(i->path, j->path) != NULL)
3589 candidate_item = j;
3590 }
3591
3592 if (candidate_item && candidate_item->age_set) {
3593 i->age = candidate_item->age;
3594 i->age_set = true;
3595 }
3596 }
3597
3598 if (ferror(f)) {
3599 log_error_errno(errno, "Failed to read from file %s: %m", fn);
3600 if (r == 0)
3601 r = -EIO;
3602 }
3603
3604 return r;
3605 }
3606
3607 static int parse_arguments(char **config_dirs, char **args, bool *invalid_config) {
3608 int r;
3609
3610 STRV_FOREACH(arg, args) {
3611 r = read_config_file(config_dirs, *arg, false, invalid_config);
3612 if (r < 0)
3613 return r;
3614 }
3615
3616 return 0;
3617 }
3618
3619 static int read_config_files(char **config_dirs, char **args, bool *invalid_config) {
3620 _cleanup_strv_free_ char **files = NULL;
3621 _cleanup_free_ char *p = NULL;
3622 int r;
3623
3624 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
3625 if (r < 0)
3626 return r;
3627
3628 STRV_FOREACH(f, files)
3629 if (p && path_equal(*f, p)) {
3630 log_debug("Parsing arguments at position \"%s\"…", *f);
3631
3632 r = parse_arguments(config_dirs, args, invalid_config);
3633 if (r < 0)
3634 return r;
3635 } else
3636 /* Just warn, ignore result otherwise.
3637 * read_config_file() has some debug output, so no need to print anything. */
3638 (void) read_config_file(config_dirs, *f, true, invalid_config);
3639
3640 return 0;
3641 }
3642
3643 static int link_parent(ItemArray *a) {
3644 const char *path;
3645 char *prefix;
3646 int r;
3647
3648 assert(a);
3649
3650 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
3651 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3652 * before their children, and clean up/remove children before their parents. */
3653
3654 if (a->n_items <= 0)
3655 return 0;
3656
3657 path = a->items[0].path;
3658 prefix = newa(char, strlen(path) + 1);
3659 PATH_FOREACH_PREFIX(prefix, path) {
3660 ItemArray *j;
3661
3662 j = ordered_hashmap_get(items, prefix);
3663 if (!j)
3664 j = ordered_hashmap_get(globs, prefix);
3665 if (j) {
3666 r = set_ensure_put(&j->children, NULL, a);
3667 if (r < 0)
3668 return log_oom();
3669
3670 a->parent = j;
3671 return 1;
3672 }
3673 }
3674
3675 return 0;
3676 }
3677
3678 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
3679 ItemArray, item_array_free);
3680
3681 static int run(int argc, char *argv[]) {
3682 #ifndef STANDALONE
3683 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3684 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3685 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
3686 #endif
3687 _cleanup_strv_free_ char **config_dirs = NULL;
3688 bool invalid_config = false;
3689 ItemArray *a;
3690 enum {
3691 PHASE_REMOVE_AND_CLEAN,
3692 PHASE_CREATE,
3693 _PHASE_MAX
3694 } phase;
3695 int r, k;
3696
3697 r = parse_argv(argc, argv);
3698 if (r <= 0)
3699 return r;
3700
3701 log_setup();
3702
3703 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
3704 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
3705 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
3706 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
3707 * and output a nice and friendly warning. */
3708 if (proc_mounted() == 0)
3709 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3710 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
3711 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
3712
3713 /* Descending down file system trees might take a lot of fds */
3714 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
3715
3716 if (arg_user) {
3717 r = user_config_paths(&config_dirs);
3718 if (r < 0)
3719 return log_error_errno(r, "Failed to initialize configuration directory list: %m");
3720 } else {
3721 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
3722 if (!config_dirs)
3723 return log_oom();
3724 }
3725
3726 if (DEBUG_LOGGING) {
3727 _cleanup_free_ char *t = NULL;
3728
3729 STRV_FOREACH(i, config_dirs) {
3730 _cleanup_free_ char *j = NULL;
3731
3732 j = path_join(arg_root, *i);
3733 if (!j)
3734 return log_oom();
3735
3736 if (!strextend(&t, "\n\t", j))
3737 return log_oom();
3738 }
3739
3740 log_debug("Looking for configuration files in (higher priority first):%s", t);
3741 }
3742
3743 if (arg_cat_config) {
3744 pager_open(arg_pager_flags);
3745
3746 return cat_config(config_dirs, argv + optind);
3747 }
3748
3749 umask(0022);
3750
3751 r = mac_selinux_init();
3752 if (r < 0)
3753 return r;
3754
3755 #ifndef STANDALONE
3756 if (arg_image) {
3757 assert(!arg_root);
3758
3759 r = mount_image_privately_interactively(
3760 arg_image,
3761 DISSECT_IMAGE_GENERIC_ROOT |
3762 DISSECT_IMAGE_REQUIRE_ROOT |
3763 DISSECT_IMAGE_VALIDATE_OS |
3764 DISSECT_IMAGE_RELAX_VAR_CHECK |
3765 DISSECT_IMAGE_FSCK |
3766 DISSECT_IMAGE_GROWFS,
3767 &unlink_dir,
3768 &loop_device,
3769 &decrypted_image);
3770 if (r < 0)
3771 return r;
3772
3773 arg_root = strdup(unlink_dir);
3774 if (!arg_root)
3775 return log_oom();
3776 }
3777 #else
3778 assert(!arg_image);
3779 #endif
3780
3781 items = ordered_hashmap_new(&item_array_hash_ops);
3782 globs = ordered_hashmap_new(&item_array_hash_ops);
3783 if (!items || !globs)
3784 return log_oom();
3785
3786 /* If command line arguments are specified along with --replace, read all
3787 * configuration files and insert the positional arguments at the specified
3788 * place. Otherwise, if command line arguments are specified, execute just
3789 * them, and finally, without --replace= or any positional arguments, just
3790 * read configuration and execute it.
3791 */
3792 if (arg_replace || optind >= argc)
3793 r = read_config_files(config_dirs, argv + optind, &invalid_config);
3794 else
3795 r = parse_arguments(config_dirs, argv + optind, &invalid_config);
3796 if (r < 0)
3797 return r;
3798
3799 /* Let's now link up all child/parent relationships */
3800 ORDERED_HASHMAP_FOREACH(a, items) {
3801 r = link_parent(a);
3802 if (r < 0)
3803 return r;
3804 }
3805 ORDERED_HASHMAP_FOREACH(a, globs) {
3806 r = link_parent(a);
3807 if (r < 0)
3808 return r;
3809 }
3810
3811 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
3812 * operations. i.e. that we first clean out the platform we then build on. */
3813 for (phase = 0; phase < _PHASE_MAX; phase++) {
3814 OperationMask op;
3815
3816 if (phase == PHASE_REMOVE_AND_CLEAN)
3817 op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
3818 else if (phase == PHASE_CREATE)
3819 op = arg_operation & OPERATION_CREATE;
3820 else
3821 assert_not_reached();
3822
3823 if (op == 0) /* Nothing requested in this phase */
3824 continue;
3825
3826 /* The non-globbing ones usually create things, hence we apply them first */
3827 ORDERED_HASHMAP_FOREACH(a, items) {
3828 k = process_item_array(a, op);
3829 if (k < 0 && r >= 0)
3830 r = k;
3831 }
3832
3833 /* The globbing ones usually alter things, hence we apply them second. */
3834 ORDERED_HASHMAP_FOREACH(a, globs) {
3835 k = process_item_array(a, op);
3836 if (k < 0 && r >= 0)
3837 r = k;
3838 }
3839 }
3840
3841 if (ERRNO_IS_RESOURCE(r))
3842 return r;
3843 if (invalid_config)
3844 return EX_DATAERR;
3845 if (r < 0)
3846 return EX_CANTCREAT;
3847 return 0;
3848 }
3849
3850 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);