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