Debian Codegraph @

src/tmpfiles/tmpfiles.c

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