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