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