]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/tmpfiles/tmpfiles.c
Merge pull request #19226 from keszybz/reenable-maybe-unitialized-warning
[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 log_warning("\"%s\" already exists and is not a directory.", path);
1661 return -EEXIST;
1662 }
1663
1664 *creation = CREATION_EXISTING;
1665 } else
1666 *creation = CREATION_NORMAL;
1667
1668 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(*creation), path);
1669
1670 r = openat(pfd, basename(path), O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
1671 if (r < 0)
1672 return log_error_errno(errno, "Failed to open directory '%s': %m", basename(path));
1673
1674 return r;
1675 }
1676
1677 static int create_directory(Item *i, const char *path) {
1678 _cleanup_close_ int fd = -1;
1679
1680 assert(i);
1681 assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
1682
1683 fd = create_directory_or_subvolume(path, i->mode, false, NULL);
1684 if (fd == -EEXIST)
1685 return 0;
1686 if (fd < 0)
1687 return fd;
1688
1689 return fd_set_perms(i, fd, path, NULL);
1690 }
1691
1692 static int create_subvolume(Item *i, const char *path) {
1693 _cleanup_close_ int fd = -1;
1694 CreationMode creation;
1695 int r, q = 0;
1696
1697 assert(i);
1698 assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
1699
1700 fd = create_directory_or_subvolume(path, i->mode, true, &creation);
1701 if (fd == -EEXIST)
1702 return 0;
1703 if (fd < 0)
1704 return fd;
1705
1706 if (creation == CREATION_NORMAL &&
1707 IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
1708 r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
1709 if (r == -ENOTTY)
1710 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
1711 else if (r == -EROFS)
1712 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
1713 else if (r == -ENOTCONN)
1714 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
1715 else if (r < 0)
1716 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
1717 else if (r > 0)
1718 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
1719 else if (r == 0)
1720 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
1721 }
1722
1723 r = fd_set_perms(i, fd, path, NULL);
1724 if (q < 0) /* prefer the quota change error from above */
1725 return q;
1726
1727 return r;
1728 }
1729
1730 static int empty_directory(Item *i, const char *path) {
1731 int r;
1732
1733 assert(i);
1734 assert(i->type == EMPTY_DIRECTORY);
1735
1736 r = is_dir(path, false);
1737 if (r == -ENOENT) {
1738 /* Option "e" operates only on existing objects. Do not
1739 * print errors about non-existent files or directories */
1740 log_debug("Skipping missing directory: %s", path);
1741 return 0;
1742 }
1743 if (r < 0)
1744 return log_error_errno(r, "is_dir() failed on path %s: %m", path);
1745 if (r == 0)
1746 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1747 "'%s' already exists and is not a directory.",
1748 path);
1749
1750 return path_set_perms(i, path);
1751 }
1752
1753 static int create_device(Item *i, mode_t file_type) {
1754 _cleanup_close_ int dfd = -1, fd = -1;
1755 CreationMode creation;
1756 char *bn;
1757 int r;
1758
1759 assert(i);
1760 assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1761
1762 bn = basename(i->path);
1763
1764 /* Validate the path and use the returned directory fd for copying the
1765 * target so we're sure that the path can't be changed behind our
1766 * back. */
1767 dfd = path_open_parent_safe(i->path);
1768 if (dfd < 0)
1769 return dfd;
1770
1771 RUN_WITH_UMASK(0000) {
1772 mac_selinux_create_file_prepare(i->path, file_type);
1773 r = mknodat(dfd, bn, i->mode | file_type, i->major_minor);
1774 mac_selinux_create_file_clear();
1775 }
1776
1777 if (r < 0) {
1778 struct stat st;
1779
1780 if (errno == EPERM) {
1781 log_debug("We lack permissions, possibly because of cgroup configuration; "
1782 "skipping creation of device node %s.", i->path);
1783 return 0;
1784 }
1785
1786 if (errno != EEXIST)
1787 return log_error_errno(errno, "Failed to create device node %s: %m", i->path);
1788
1789 if (fstatat(dfd, bn, &st, 0) < 0)
1790 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
1791
1792 if ((st.st_mode & S_IFMT) != file_type) {
1793
1794 if (i->append_or_force) {
1795
1796 RUN_WITH_UMASK(0000) {
1797 mac_selinux_create_file_prepare(i->path, file_type);
1798 /* FIXME: need to introduce mknodat_atomic() */
1799 r = mknod_atomic(i->path, i->mode | file_type, i->major_minor);
1800 mac_selinux_create_file_clear();
1801 }
1802
1803 if (r < 0)
1804 return log_error_errno(r, "Failed to create device node \"%s\": %m", i->path);
1805 creation = CREATION_FORCE;
1806 } else {
1807 log_debug("%s is not a device node.", i->path);
1808 return 0;
1809 }
1810 } else
1811 creation = CREATION_EXISTING;
1812 } else
1813 creation = CREATION_NORMAL;
1814
1815 log_debug("%s %s device node \"%s\" %u:%u.",
1816 creation_mode_verb_to_string(creation),
1817 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1818 i->path, major(i->mode), minor(i->mode));
1819
1820 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1821 if (fd < 0)
1822 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1823
1824 return fd_set_perms(i, fd, i->path, NULL);
1825 }
1826
1827 static int create_fifo(Item *i, const char *path) {
1828 _cleanup_close_ int pfd = -1, fd = -1;
1829 CreationMode creation;
1830 struct stat st;
1831 char *bn;
1832 int r;
1833
1834 pfd = path_open_parent_safe(path);
1835 if (pfd < 0)
1836 return pfd;
1837
1838 bn = basename(path);
1839
1840 RUN_WITH_UMASK(0000) {
1841 mac_selinux_create_file_prepare(path, S_IFIFO);
1842 r = mkfifoat(pfd, bn, i->mode);
1843 mac_selinux_create_file_clear();
1844 }
1845
1846 if (r < 0) {
1847 if (errno != EEXIST)
1848 return log_error_errno(errno, "Failed to create fifo %s: %m", path);
1849
1850 if (fstatat(pfd, bn, &st, AT_SYMLINK_NOFOLLOW) < 0)
1851 return log_error_errno(errno, "stat(%s) failed: %m", path);
1852
1853 if (!S_ISFIFO(st.st_mode)) {
1854
1855 if (i->append_or_force) {
1856 RUN_WITH_UMASK(0000) {
1857 mac_selinux_create_file_prepare(path, S_IFIFO);
1858 r = mkfifoat_atomic(pfd, bn, i->mode);
1859 mac_selinux_create_file_clear();
1860 }
1861
1862 if (r < 0)
1863 return log_error_errno(r, "Failed to create fifo %s: %m", path);
1864 creation = CREATION_FORCE;
1865 } else {
1866 log_warning("\"%s\" already exists and is not a fifo.", path);
1867 return 0;
1868 }
1869 } else
1870 creation = CREATION_EXISTING;
1871 } else
1872 creation = CREATION_NORMAL;
1873
1874 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), path);
1875
1876 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1877 if (fd < 0)
1878 return log_error_errno(errno, "Failed to openat(%s): %m", path);
1879
1880 return fd_set_perms(i, fd, i->path, NULL);
1881 }
1882
1883 typedef int (*action_t)(Item *i, const char *path);
1884 typedef int (*fdaction_t)(Item *i, int fd, const char *path, const struct stat *st);
1885
1886 static int item_do(Item *i, int fd, const char *path, fdaction_t action) {
1887 struct stat st;
1888 int r = 0, q;
1889
1890 assert(i);
1891 assert(path);
1892 assert(fd >= 0);
1893
1894 if (fstat(fd, &st) < 0) {
1895 r = log_error_errno(errno, "fstat() on file failed: %m");
1896 goto finish;
1897 }
1898
1899 /* This returns the first error we run into, but nevertheless
1900 * tries to go on */
1901 r = action(i, fd, path, &st);
1902
1903 if (S_ISDIR(st.st_mode)) {
1904 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
1905 _cleanup_closedir_ DIR *d = NULL;
1906 struct dirent *de;
1907
1908 /* The passed 'fd' was opened with O_PATH. We need to convert
1909 * it into a 'regular' fd before reading the directory content. */
1910 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
1911
1912 d = opendir(procfs_path);
1913 if (!d) {
1914 log_error_errno(errno, "Failed to opendir() '%s': %m", procfs_path);
1915 if (r == 0)
1916 r = -errno;
1917 goto finish;
1918 }
1919
1920 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
1921 int de_fd;
1922
1923 if (dot_or_dot_dot(de->d_name))
1924 continue;
1925
1926 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1927 if (de_fd < 0)
1928 q = log_error_errno(errno, "Failed to open() file '%s': %m", de->d_name);
1929 else {
1930 _cleanup_free_ char *de_path = NULL;
1931
1932 de_path = path_join(path, de->d_name);
1933 if (!de_path)
1934 q = log_oom();
1935 else
1936 /* Pass ownership of dirent fd over */
1937 q = item_do(i, de_fd, de_path, action);
1938 }
1939
1940 if (q < 0 && r == 0)
1941 r = q;
1942 }
1943 }
1944 finish:
1945 safe_close(fd);
1946 return r;
1947 }
1948
1949 static int glob_item(Item *i, action_t action) {
1950 _cleanup_globfree_ glob_t g = {
1951 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
1952 };
1953 int r = 0, k;
1954 char **fn;
1955
1956 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1957 if (k < 0 && k != -ENOENT)
1958 return log_error_errno(k, "glob(%s) failed: %m", i->path);
1959
1960 STRV_FOREACH(fn, g.gl_pathv) {
1961 k = action(i, *fn);
1962 if (k < 0 && r == 0)
1963 r = k;
1964 }
1965
1966 return r;
1967 }
1968
1969 static int glob_item_recursively(Item *i, fdaction_t action) {
1970 _cleanup_globfree_ glob_t g = {
1971 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
1972 };
1973 int r = 0, k;
1974 char **fn;
1975
1976 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1977 if (k < 0 && k != -ENOENT)
1978 return log_error_errno(k, "glob(%s) failed: %m", i->path);
1979
1980 STRV_FOREACH(fn, g.gl_pathv) {
1981 _cleanup_close_ int fd = -1;
1982
1983 /* Make sure we won't trigger/follow file object (such as
1984 * device nodes, automounts, ...) pointed out by 'fn' with
1985 * O_PATH. Note, when O_PATH is used, flags other than
1986 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1987
1988 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
1989 if (fd < 0) {
1990 log_error_errno(errno, "Opening '%s' failed: %m", *fn);
1991 if (r == 0)
1992 r = -errno;
1993 continue;
1994 }
1995
1996 k = item_do(i, fd, *fn, action);
1997 if (k < 0 && r == 0)
1998 r = k;
1999
2000 /* we passed fd ownership to the previous call */
2001 fd = -1;
2002 }
2003
2004 return r;
2005 }
2006
2007 static int create_item(Item *i) {
2008 CreationMode creation;
2009 int r = 0;
2010
2011 assert(i);
2012
2013 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
2014
2015 switch (i->type) {
2016
2017 case IGNORE_PATH:
2018 case IGNORE_DIRECTORY_PATH:
2019 case REMOVE_PATH:
2020 case RECURSIVE_REMOVE_PATH:
2021 return 0;
2022
2023 case TRUNCATE_FILE:
2024 case CREATE_FILE:
2025 RUN_WITH_UMASK(0000)
2026 (void) mkdir_parents_label(i->path, 0755);
2027
2028 if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
2029 r = truncate_file(i, i->path);
2030 else
2031 r = create_file(i, i->path);
2032
2033 if (r < 0)
2034 return r;
2035 break;
2036
2037 case COPY_FILES:
2038 RUN_WITH_UMASK(0000)
2039 (void) mkdir_parents_label(i->path, 0755);
2040
2041 r = copy_files(i);
2042 if (r < 0)
2043 return r;
2044 break;
2045
2046 case WRITE_FILE:
2047 r = glob_item(i, write_one_file);
2048 if (r < 0)
2049 return r;
2050
2051 break;
2052
2053 case CREATE_DIRECTORY:
2054 case TRUNCATE_DIRECTORY:
2055 RUN_WITH_UMASK(0000)
2056 (void) mkdir_parents_label(i->path, 0755);
2057
2058 r = create_directory(i, i->path);
2059 if (r < 0)
2060 return r;
2061 break;
2062
2063 case CREATE_SUBVOLUME:
2064 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2065 case CREATE_SUBVOLUME_NEW_QUOTA:
2066 RUN_WITH_UMASK(0000)
2067 (void) mkdir_parents_label(i->path, 0755);
2068
2069 r = create_subvolume(i, i->path);
2070 if (r < 0)
2071 return r;
2072 break;
2073
2074 case EMPTY_DIRECTORY:
2075 r = glob_item(i, empty_directory);
2076 if (r < 0)
2077 return r;
2078 break;
2079
2080 case CREATE_FIFO:
2081 RUN_WITH_UMASK(0000)
2082 (void) mkdir_parents_label(i->path, 0755);
2083
2084 r = create_fifo(i, i->path);
2085 if (r < 0)
2086 return r;
2087 break;
2088
2089 case CREATE_SYMLINK: {
2090 RUN_WITH_UMASK(0000)
2091 (void) mkdir_parents_label(i->path, 0755);
2092
2093 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2094 r = symlink(i->argument, i->path);
2095 mac_selinux_create_file_clear();
2096
2097 if (r < 0) {
2098 _cleanup_free_ char *x = NULL;
2099
2100 if (errno != EEXIST)
2101 return log_error_errno(errno, "symlink(%s, %s) failed: %m", i->argument, i->path);
2102
2103 r = readlink_malloc(i->path, &x);
2104 if (r < 0 || !streq(i->argument, x)) {
2105
2106 if (i->append_or_force) {
2107 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2108 r = symlink_atomic(i->argument, i->path);
2109 mac_selinux_create_file_clear();
2110
2111 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2112 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL);
2113 if (r < 0)
2114 return log_error_errno(r, "rm -fr %s failed: %m", i->path);
2115
2116 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2117 r = symlink(i->argument, i->path) < 0 ? -errno : 0;
2118 mac_selinux_create_file_clear();
2119 }
2120 if (r < 0)
2121 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
2122
2123 creation = CREATION_FORCE;
2124 } else {
2125 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
2126 return 0;
2127 }
2128 } else
2129 creation = CREATION_EXISTING;
2130 } else
2131
2132 creation = CREATION_NORMAL;
2133 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
2134 break;
2135 }
2136
2137 case CREATE_BLOCK_DEVICE:
2138 case CREATE_CHAR_DEVICE:
2139 if (have_effective_cap(CAP_MKNOD) == 0) {
2140 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2141 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
2142
2143 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
2144 return 0;
2145 }
2146
2147 RUN_WITH_UMASK(0000)
2148 (void) mkdir_parents_label(i->path, 0755);
2149
2150 r = create_device(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2151 if (r < 0)
2152 return r;
2153
2154 break;
2155
2156 case ADJUST_MODE:
2157 case RELABEL_PATH:
2158 r = glob_item(i, path_set_perms);
2159 if (r < 0)
2160 return r;
2161 break;
2162
2163 case RECURSIVE_RELABEL_PATH:
2164 r = glob_item_recursively(i, fd_set_perms);
2165 if (r < 0)
2166 return r;
2167 break;
2168
2169 case SET_XATTR:
2170 r = glob_item(i, path_set_xattrs);
2171 if (r < 0)
2172 return r;
2173 break;
2174
2175 case RECURSIVE_SET_XATTR:
2176 r = glob_item_recursively(i, fd_set_xattrs);
2177 if (r < 0)
2178 return r;
2179 break;
2180
2181 case SET_ACL:
2182 r = glob_item(i, path_set_acls);
2183 if (r < 0)
2184 return r;
2185 break;
2186
2187 case RECURSIVE_SET_ACL:
2188 r = glob_item_recursively(i, fd_set_acls);
2189 if (r < 0)
2190 return r;
2191 break;
2192
2193 case SET_ATTRIBUTE:
2194 r = glob_item(i, path_set_attribute);
2195 if (r < 0)
2196 return r;
2197 break;
2198
2199 case RECURSIVE_SET_ATTRIBUTE:
2200 r = glob_item_recursively(i, fd_set_attribute);
2201 if (r < 0)
2202 return r;
2203 break;
2204 }
2205
2206 return 0;
2207 }
2208
2209 static int remove_item_instance(Item *i, const char *instance) {
2210 int r;
2211
2212 assert(i);
2213
2214 switch (i->type) {
2215
2216 case REMOVE_PATH:
2217 if (remove(instance) < 0 && errno != ENOENT)
2218 return log_error_errno(errno, "rm(%s): %m", instance);
2219
2220 break;
2221
2222 case RECURSIVE_REMOVE_PATH:
2223 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2224 log_debug("rm -rf \"%s\"", instance);
2225 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
2226 if (r < 0 && r != -ENOENT)
2227 return log_error_errno(r, "rm_rf(%s): %m", instance);
2228
2229 break;
2230
2231 default:
2232 assert_not_reached("wut?");
2233 }
2234
2235 return 0;
2236 }
2237
2238 static int remove_item(Item *i) {
2239 int r;
2240
2241 assert(i);
2242
2243 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2244
2245 switch (i->type) {
2246
2247 case TRUNCATE_DIRECTORY:
2248 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2249 log_debug("rm -rf \"%s\"", i->path);
2250 r = rm_rf(i->path, REMOVE_PHYSICAL);
2251 if (r < 0 && r != -ENOENT)
2252 return log_error_errno(r, "rm_rf(%s): %m", i->path);
2253
2254 return 0;
2255
2256 case REMOVE_PATH:
2257 case RECURSIVE_REMOVE_PATH:
2258 return glob_item(i, remove_item_instance);
2259
2260 default:
2261 return 0;
2262 }
2263 }
2264
2265 static int clean_item_instance(Item *i, const char* instance) {
2266 char timestamp[FORMAT_TIMESTAMP_MAX];
2267 _cleanup_closedir_ DIR *d = NULL;
2268 STRUCT_STATX_DEFINE(sx);
2269 int mountpoint, r;
2270 usec_t cutoff, n;
2271
2272 assert(i);
2273
2274 if (!i->age_set)
2275 return 0;
2276
2277 n = now(CLOCK_REALTIME);
2278 if (n < i->age)
2279 return 0;
2280
2281 cutoff = n - i->age;
2282
2283 d = opendir_nomod(instance);
2284 if (!d) {
2285 if (IN_SET(errno, ENOENT, ENOTDIR)) {
2286 log_debug_errno(errno, "Directory \"%s\": %m", instance);
2287 return 0;
2288 }
2289
2290 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
2291 }
2292
2293 r = statx_fallback(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx);
2294 if (r < 0)
2295 return log_error_errno(r, "statx(%s) failed: %m", instance);
2296
2297 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
2298 mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
2299 else {
2300 struct stat ps;
2301
2302 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
2303 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
2304
2305 mountpoint =
2306 sx.stx_dev_major != major(ps.st_dev) ||
2307 sx.stx_dev_minor != minor(ps.st_dev) ||
2308 sx.stx_ino != ps.st_ino;
2309 }
2310
2311 log_debug("Cleanup threshold for %s \"%s\" is %s",
2312 mountpoint ? "mount point" : "directory",
2313 instance,
2314 format_timestamp_style(timestamp, sizeof(timestamp), cutoff, TIMESTAMP_US));
2315
2316 return dir_cleanup(i, instance, d,
2317 load_statx_timestamp_nsec(&sx.stx_atime),
2318 load_statx_timestamp_nsec(&sx.stx_mtime),
2319 cutoff * NSEC_PER_USEC,
2320 sx.stx_dev_major, sx.stx_dev_minor, mountpoint,
2321 MAX_DEPTH, i->keep_first_level);
2322 }
2323
2324 static int clean_item(Item *i) {
2325 assert(i);
2326
2327 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
2328
2329 switch (i->type) {
2330 case CREATE_DIRECTORY:
2331 case CREATE_SUBVOLUME:
2332 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2333 case CREATE_SUBVOLUME_NEW_QUOTA:
2334 case TRUNCATE_DIRECTORY:
2335 case IGNORE_PATH:
2336 case COPY_FILES:
2337 clean_item_instance(i, i->path);
2338 return 0;
2339 case EMPTY_DIRECTORY:
2340 case IGNORE_DIRECTORY_PATH:
2341 return glob_item(i, clean_item_instance);
2342 default:
2343 return 0;
2344 }
2345 }
2346
2347 static int process_item(Item *i, OperationMask operation) {
2348 OperationMask todo;
2349 int r, q, p;
2350
2351 assert(i);
2352
2353 todo = operation & ~i->done;
2354 if (todo == 0) /* Everything already done? */
2355 return 0;
2356
2357 i->done |= operation;
2358
2359 r = chase_symlinks(i->path, arg_root, CHASE_NO_AUTOFS|CHASE_WARN, NULL, NULL);
2360 if (r == -EREMOTE) {
2361 log_notice_errno(r, "Skipping %s", i->path);
2362 return 0;
2363 }
2364 if (r < 0)
2365 log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
2366
2367 r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(i) : 0;
2368 /* Failure can only be tolerated for create */
2369 if (i->allow_failure)
2370 r = 0;
2371
2372 q = FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(i) : 0;
2373 p = FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(i) : 0;
2374
2375 return r < 0 ? r :
2376 q < 0 ? q :
2377 p;
2378 }
2379
2380 static int process_item_array(ItemArray *array, OperationMask operation) {
2381 int r = 0;
2382 size_t n;
2383
2384 assert(array);
2385
2386 /* Create any parent first. */
2387 if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
2388 r = process_item_array(array->parent, operation & OPERATION_CREATE);
2389
2390 /* Clean up all children first */
2391 if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN)) && !set_isempty(array->children)) {
2392 ItemArray *c;
2393
2394 SET_FOREACH(c, array->children) {
2395 int k;
2396
2397 k = process_item_array(c, operation & (OPERATION_REMOVE|OPERATION_CLEAN));
2398 if (k < 0 && r == 0)
2399 r = k;
2400 }
2401 }
2402
2403 for (n = 0; n < array->n_items; n++) {
2404 int k;
2405
2406 k = process_item(array->items + n, operation);
2407 if (k < 0 && r == 0)
2408 r = k;
2409 }
2410
2411 return r;
2412 }
2413
2414 static void item_free_contents(Item *i) {
2415 assert(i);
2416 free(i->path);
2417 free(i->argument);
2418 strv_free(i->xattrs);
2419
2420 #if HAVE_ACL
2421 acl_free(i->acl_access);
2422 acl_free(i->acl_default);
2423 #endif
2424 }
2425
2426 static ItemArray* item_array_free(ItemArray *a) {
2427 size_t n;
2428
2429 if (!a)
2430 return NULL;
2431
2432 for (n = 0; n < a->n_items; n++)
2433 item_free_contents(a->items + n);
2434
2435 set_free(a->children);
2436 free(a->items);
2437 return mfree(a);
2438 }
2439
2440 static int item_compare(const Item *a, const Item *b) {
2441 /* Make sure that the ownership taking item is put first, so
2442 * that we first create the node, and then can adjust it */
2443
2444 if (takes_ownership(a->type) && !takes_ownership(b->type))
2445 return -1;
2446 if (!takes_ownership(a->type) && takes_ownership(b->type))
2447 return 1;
2448
2449 return CMP(a->type, b->type);
2450 }
2451
2452 static bool item_compatible(Item *a, Item *b) {
2453 assert(a);
2454 assert(b);
2455 assert(streq(a->path, b->path));
2456
2457 if (takes_ownership(a->type) && takes_ownership(b->type))
2458 /* check if the items are the same */
2459 return streq_ptr(a->argument, b->argument) &&
2460
2461 a->uid_set == b->uid_set &&
2462 a->uid == b->uid &&
2463
2464 a->gid_set == b->gid_set &&
2465 a->gid == b->gid &&
2466
2467 a->mode_set == b->mode_set &&
2468 a->mode == b->mode &&
2469
2470 a->age_set == b->age_set &&
2471 a->age == b->age &&
2472
2473 a->mask_perms == b->mask_perms &&
2474
2475 a->keep_first_level == b->keep_first_level &&
2476
2477 a->major_minor == b->major_minor;
2478
2479 return true;
2480 }
2481
2482 static bool should_include_path(const char *path) {
2483 char **prefix;
2484
2485 STRV_FOREACH(prefix, arg_exclude_prefixes)
2486 if (path_startswith(path, *prefix)) {
2487 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2488 path, *prefix);
2489 return false;
2490 }
2491
2492 STRV_FOREACH(prefix, arg_include_prefixes)
2493 if (path_startswith(path, *prefix)) {
2494 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
2495 return true;
2496 }
2497
2498 /* no matches, so we should include this path only if we have no allow list at all */
2499 if (strv_isempty(arg_include_prefixes))
2500 return true;
2501
2502 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
2503 return false;
2504 }
2505
2506 static int specifier_expansion_from_arg(Item *i) {
2507 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2508 char **xattr;
2509 int r;
2510
2511 assert(i);
2512
2513 if (!i->argument)
2514 return 0;
2515
2516 switch (i->type) {
2517 case COPY_FILES:
2518 case CREATE_SYMLINK:
2519 case CREATE_FILE:
2520 case TRUNCATE_FILE:
2521 case WRITE_FILE:
2522 r = cunescape(i->argument, 0, &unescaped);
2523 if (r < 0)
2524 return log_error_errno(r, "Failed to unescape parameter to write: %s", i->argument);
2525
2526 r = specifier_printf(unescaped, specifier_table, NULL, &resolved);
2527 if (r < 0)
2528 return r;
2529
2530 free_and_replace(i->argument, resolved);
2531 break;
2532
2533 case SET_XATTR:
2534 case RECURSIVE_SET_XATTR:
2535 STRV_FOREACH(xattr, i->xattrs) {
2536 r = specifier_printf(*xattr, specifier_table, NULL, &resolved);
2537 if (r < 0)
2538 return r;
2539
2540 free_and_replace(*xattr, resolved);
2541 }
2542 break;
2543
2544 default:
2545 break;
2546 }
2547 return 0;
2548 }
2549
2550 static int patch_var_run(const char *fname, unsigned line, char **path) {
2551 const char *k;
2552 char *n;
2553
2554 assert(path);
2555 assert(*path);
2556
2557 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2558 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2559 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2560 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2561 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2562 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2563 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2564 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2565 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2566
2567 k = path_startswith(*path, "/var/run/");
2568 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2569 return 0;
2570
2571 n = path_join("/run", k);
2572 if (!n)
2573 return log_oom();
2574
2575 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2576 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2577 * to the user, let's still inform the user that these snippets should really be updated. */
2578 log_syntax(NULL, LOG_NOTICE, fname, line, 0, "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.", *path, n);
2579
2580 free_and_replace(*path, n);
2581
2582 return 0;
2583 }
2584
2585 static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
2586 int r;
2587
2588 assert(user);
2589 assert(ret_uid);
2590
2591 /* First: parse as numeric UID string */
2592 r = parse_uid(user, ret_uid);
2593 if (r >= 0)
2594 return r;
2595
2596 /* Second: pass to NSS if we are running "online" */
2597 if (!arg_root)
2598 return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
2599
2600 /* Third, synthesize "root" unconditionally */
2601 if (streq(user, "root")) {
2602 *ret_uid = 0;
2603 return 0;
2604 }
2605
2606 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
2607 return name_to_uid_offline(arg_root, user, ret_uid, cache);
2608 }
2609
2610 static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
2611 int r;
2612
2613 assert(group);
2614 assert(ret_gid);
2615
2616 /* First: parse as numeric GID string */
2617 r = parse_gid(group, ret_gid);
2618 if (r >= 0)
2619 return r;
2620
2621 /* Second: pass to NSS if we are running "online" */
2622 if (!arg_root)
2623 return get_group_creds(&group, ret_gid, 0);
2624
2625 /* Third, synthesize "root" unconditionally */
2626 if (streq(group, "root")) {
2627 *ret_gid = 0;
2628 return 0;
2629 }
2630
2631 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
2632 return name_to_gid_offline(arg_root, group, ret_gid, cache);
2633 }
2634
2635 static int parse_line(
2636 const char *fname,
2637 unsigned line,
2638 const char *buffer,
2639 bool *invalid_config,
2640 Hashmap **uid_cache,
2641 Hashmap **gid_cache) {
2642
2643 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
2644 _cleanup_(item_free_contents) Item i = {};
2645 ItemArray *existing;
2646 OrderedHashmap *h;
2647 int r, pos;
2648 bool append_or_force = false, boot = false, allow_failure = false;
2649
2650 assert(fname);
2651 assert(line >= 1);
2652 assert(buffer);
2653
2654 r = extract_many_words(
2655 &buffer,
2656 NULL,
2657 EXTRACT_UNQUOTE,
2658 &action,
2659 &path,
2660 &mode,
2661 &user,
2662 &group,
2663 &age,
2664 NULL);
2665 if (r < 0) {
2666 if (IN_SET(r, -EINVAL, -EBADSLT))
2667 /* invalid quoting and such or an unknown specifier */
2668 *invalid_config = true;
2669 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
2670 } else if (r < 2) {
2671 *invalid_config = true;
2672 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
2673 }
2674
2675 if (!empty_or_dash(buffer)) {
2676 i.argument = strdup(buffer);
2677 if (!i.argument)
2678 return log_oom();
2679 }
2680
2681 if (isempty(action)) {
2682 *invalid_config = true;
2683 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Command too short '%s'.", action);
2684 }
2685
2686 for (pos = 1; action[pos]; pos++) {
2687 if (action[pos] == '!' && !boot)
2688 boot = true;
2689 else if (action[pos] == '+' && !append_or_force)
2690 append_or_force = true;
2691 else if (action[pos] == '-' && !allow_failure)
2692 allow_failure = true;
2693 else {
2694 *invalid_config = true;
2695 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Unknown modifiers in command '%s'", action);
2696 }
2697 }
2698
2699 if (boot && !arg_boot) {
2700 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
2701 return 0;
2702 }
2703
2704 i.type = action[0];
2705 i.append_or_force = append_or_force;
2706 i.allow_failure = allow_failure;
2707
2708 r = specifier_printf(path, specifier_table, NULL, &i.path);
2709 if (r == -ENXIO)
2710 return log_unresolvable_specifier(fname, line);
2711 if (r < 0) {
2712 if (IN_SET(r, -EINVAL, -EBADSLT))
2713 *invalid_config = true;
2714 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", path);
2715 }
2716
2717 r = patch_var_run(fname, line, &i.path);
2718 if (r < 0)
2719 return r;
2720
2721 switch (i.type) {
2722
2723 case CREATE_DIRECTORY:
2724 case CREATE_SUBVOLUME:
2725 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2726 case CREATE_SUBVOLUME_NEW_QUOTA:
2727 case EMPTY_DIRECTORY:
2728 case TRUNCATE_DIRECTORY:
2729 case CREATE_FIFO:
2730 case IGNORE_PATH:
2731 case IGNORE_DIRECTORY_PATH:
2732 case REMOVE_PATH:
2733 case RECURSIVE_REMOVE_PATH:
2734 case ADJUST_MODE:
2735 case RELABEL_PATH:
2736 case RECURSIVE_RELABEL_PATH:
2737 if (i.argument)
2738 log_syntax(NULL, LOG_WARNING, fname, line, 0, "%c lines don't take argument fields, ignoring.", i.type);
2739
2740 break;
2741
2742 case CREATE_FILE:
2743 case TRUNCATE_FILE:
2744 break;
2745
2746 case CREATE_SYMLINK:
2747 if (!i.argument) {
2748 i.argument = path_join("/usr/share/factory", i.path);
2749 if (!i.argument)
2750 return log_oom();
2751 }
2752 break;
2753
2754 case WRITE_FILE:
2755 if (!i.argument) {
2756 *invalid_config = true;
2757 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Write file requires argument.");
2758 }
2759 break;
2760
2761 case COPY_FILES:
2762 if (!i.argument) {
2763 i.argument = path_join("/usr/share/factory", i.path);
2764 if (!i.argument)
2765 return log_oom();
2766
2767 } else if (!path_is_absolute(i.argument)) {
2768 *invalid_config = true;
2769 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Source path '%s' is not absolute.", i.argument);
2770
2771 }
2772
2773 if (!empty_or_root(arg_root)) {
2774 char *p;
2775
2776 p = path_join(arg_root, i.argument);
2777 if (!p)
2778 return log_oom();
2779 free_and_replace(i.argument, p);
2780 }
2781
2782 path_simplify(i.argument, false);
2783 break;
2784
2785 case CREATE_CHAR_DEVICE:
2786 case CREATE_BLOCK_DEVICE:
2787 if (!i.argument) {
2788 *invalid_config = true;
2789 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Device file requires argument.");
2790 }
2791
2792 r = parse_dev(i.argument, &i.major_minor);
2793 if (r < 0) {
2794 *invalid_config = true;
2795 return log_syntax(NULL, LOG_ERR, fname, line, r, "Can't parse device file major/minor '%s'.", i.argument);
2796 }
2797
2798 break;
2799
2800 case SET_XATTR:
2801 case RECURSIVE_SET_XATTR:
2802 if (!i.argument) {
2803 *invalid_config = true;
2804 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
2805 "Set extended attribute requires argument.");
2806 }
2807 r = parse_xattrs_from_arg(&i);
2808 if (r < 0)
2809 return r;
2810 break;
2811
2812 case SET_ACL:
2813 case RECURSIVE_SET_ACL:
2814 if (!i.argument) {
2815 *invalid_config = true;
2816 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
2817 "Set ACLs requires argument.");
2818 }
2819 r = parse_acls_from_arg(&i);
2820 if (r < 0)
2821 return r;
2822 break;
2823
2824 case SET_ATTRIBUTE:
2825 case RECURSIVE_SET_ATTRIBUTE:
2826 if (!i.argument) {
2827 *invalid_config = true;
2828 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
2829 "Set file attribute requires argument.");
2830 }
2831 r = parse_attribute_from_arg(&i);
2832 if (IN_SET(r, -EINVAL, -EBADSLT))
2833 *invalid_config = true;
2834 if (r < 0)
2835 return r;
2836 break;
2837
2838 default:
2839 *invalid_config = true;
2840 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
2841 "Unknown command type '%c'.", (char) i.type);
2842 }
2843
2844 if (!path_is_absolute(i.path)) {
2845 *invalid_config = true;
2846 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
2847 "Path '%s' not absolute.", i.path);
2848 }
2849
2850 path_simplify(i.path, false);
2851
2852 if (!should_include_path(i.path))
2853 return 0;
2854
2855 r = specifier_expansion_from_arg(&i);
2856 if (r == -ENXIO)
2857 return log_unresolvable_specifier(fname, line);
2858 if (r < 0) {
2859 if (IN_SET(r, -EINVAL, -EBADSLT))
2860 *invalid_config = true;
2861 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to substitute specifiers in argument: %m");
2862 }
2863
2864 if (!empty_or_root(arg_root)) {
2865 char *p;
2866
2867 p = path_join(arg_root, i.path);
2868 if (!p)
2869 return log_oom();
2870 free_and_replace(i.path, p);
2871 }
2872
2873 if (!empty_or_dash(user)) {
2874 r = find_uid(user, &i.uid, uid_cache);
2875 if (r < 0) {
2876 *invalid_config = true;
2877 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", user);
2878 }
2879
2880 i.uid_set = true;
2881 }
2882
2883 if (!empty_or_dash(group)) {
2884 r = find_gid(group, &i.gid, gid_cache);
2885 if (r < 0) {
2886 *invalid_config = true;
2887 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s'.", group);
2888 }
2889
2890 i.gid_set = true;
2891 }
2892
2893 if (!empty_or_dash(mode)) {
2894 const char *mm = mode;
2895 unsigned m;
2896
2897 if (*mm == '~') {
2898 i.mask_perms = true;
2899 mm++;
2900 }
2901
2902 r = parse_mode(mm, &m);
2903 if (r < 0) {
2904 *invalid_config = true;
2905 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
2906 }
2907
2908 i.mode = m;
2909 i.mode_set = true;
2910 } else
2911 i.mode = IN_SET(i.type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
2912
2913 if (!empty_or_dash(age)) {
2914 const char *a = age;
2915
2916 if (*a == '~') {
2917 i.keep_first_level = true;
2918 a++;
2919 }
2920
2921 r = parse_sec(a, &i.age);
2922 if (r < 0) {
2923 *invalid_config = true;
2924 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", age);
2925 }
2926
2927 i.age_set = true;
2928 }
2929
2930 h = needs_glob(i.type) ? globs : items;
2931
2932 existing = ordered_hashmap_get(h, i.path);
2933 if (existing) {
2934 size_t n;
2935
2936 for (n = 0; n < existing->n_items; n++) {
2937 if (!item_compatible(existing->items + n, &i) && !i.append_or_force) {
2938 log_syntax(NULL, LOG_NOTICE, fname, line, 0, "Duplicate line for path \"%s\", ignoring.", i.path);
2939 return 0;
2940 }
2941 }
2942 } else {
2943 existing = new0(ItemArray, 1);
2944 if (!existing)
2945 return log_oom();
2946
2947 r = ordered_hashmap_put(h, i.path, existing);
2948 if (r < 0) {
2949 free(existing);
2950 return log_oom();
2951 }
2952 }
2953
2954 if (!GREEDY_REALLOC(existing->items, existing->allocated, existing->n_items + 1))
2955 return log_oom();
2956
2957 existing->items[existing->n_items++] = i;
2958 i = (struct Item) {};
2959
2960 /* Sort item array, to enforce stable ordering of application */
2961 typesafe_qsort(existing->items, existing->n_items, item_compare);
2962
2963 return 0;
2964 }
2965
2966 static int cat_config(char **config_dirs, char **args) {
2967 _cleanup_strv_free_ char **files = NULL;
2968 int r;
2969
2970 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
2971 if (r < 0)
2972 return r;
2973
2974 return cat_files(NULL, files, 0);
2975 }
2976
2977 static int exclude_default_prefixes(void) {
2978 int r;
2979
2980 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
2981 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
2982 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
2983 * all kinds of files created/adjusted underneath these mount points. */
2984
2985 r = strv_extend_strv(
2986 &arg_exclude_prefixes,
2987 STRV_MAKE("/dev",
2988 "/proc",
2989 "/run",
2990 "/sys"),
2991 true);
2992 if (r < 0)
2993 return log_oom();
2994
2995 return 0;
2996 }
2997
2998 static int help(void) {
2999 _cleanup_free_ char *link = NULL;
3000 int r;
3001
3002 r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
3003 if (r < 0)
3004 return log_oom();
3005
3006 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3007 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
3008 " -h --help Show this help\n"
3009 " --user Execute user configuration\n"
3010 " --version Show package version\n"
3011 " --cat-config Show configuration files\n"
3012 " --create Create marked files/directories\n"
3013 " --clean Clean up marked directories\n"
3014 " --remove Remove marked files/directories\n"
3015 " --boot Execute actions only safe at boot\n"
3016 " --prefix=PATH Only apply rules with the specified prefix\n"
3017 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
3018 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
3019 " --root=PATH Operate on an alternate filesystem root\n"
3020 " --image=PATH Operate on disk image as filesystem root\n"
3021 " --replace=PATH Treat arguments as replacement for PATH\n"
3022 " --no-pager Do not pipe output into a pager\n"
3023 "\nSee the %s for details.\n",
3024 program_invocation_short_name,
3025 ansi_highlight(),
3026 ansi_normal(),
3027 link);
3028
3029 return 0;
3030 }
3031
3032 static int parse_argv(int argc, char *argv[]) {
3033
3034 enum {
3035 ARG_VERSION = 0x100,
3036 ARG_CAT_CONFIG,
3037 ARG_USER,
3038 ARG_CREATE,
3039 ARG_CLEAN,
3040 ARG_REMOVE,
3041 ARG_BOOT,
3042 ARG_PREFIX,
3043 ARG_EXCLUDE_PREFIX,
3044 ARG_ROOT,
3045 ARG_IMAGE,
3046 ARG_REPLACE,
3047 ARG_NO_PAGER,
3048 };
3049
3050 static const struct option options[] = {
3051 { "help", no_argument, NULL, 'h' },
3052 { "user", no_argument, NULL, ARG_USER },
3053 { "version", no_argument, NULL, ARG_VERSION },
3054 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
3055 { "create", no_argument, NULL, ARG_CREATE },
3056 { "clean", no_argument, NULL, ARG_CLEAN },
3057 { "remove", no_argument, NULL, ARG_REMOVE },
3058 { "boot", no_argument, NULL, ARG_BOOT },
3059 { "prefix", required_argument, NULL, ARG_PREFIX },
3060 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
3061 { "root", required_argument, NULL, ARG_ROOT },
3062 { "image", required_argument, NULL, ARG_IMAGE },
3063 { "replace", required_argument, NULL, ARG_REPLACE },
3064 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
3065 {}
3066 };
3067
3068 int c, r;
3069
3070 assert(argc >= 0);
3071 assert(argv);
3072
3073 while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3074
3075 switch (c) {
3076
3077 case 'h':
3078 return help();
3079
3080 case ARG_VERSION:
3081 return version();
3082
3083 case ARG_CAT_CONFIG:
3084 arg_cat_config = true;
3085 break;
3086
3087 case ARG_USER:
3088 arg_user = true;
3089 break;
3090
3091 case ARG_CREATE:
3092 arg_operation |= OPERATION_CREATE;
3093 break;
3094
3095 case ARG_CLEAN:
3096 arg_operation |= OPERATION_CLEAN;
3097 break;
3098
3099 case ARG_REMOVE:
3100 arg_operation |= OPERATION_REMOVE;
3101 break;
3102
3103 case ARG_BOOT:
3104 arg_boot = true;
3105 break;
3106
3107 case ARG_PREFIX:
3108 if (strv_push(&arg_include_prefixes, optarg) < 0)
3109 return log_oom();
3110 break;
3111
3112 case ARG_EXCLUDE_PREFIX:
3113 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
3114 return log_oom();
3115 break;
3116
3117 case ARG_ROOT:
3118 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
3119 if (r < 0)
3120 return r;
3121 break;
3122
3123 case ARG_IMAGE:
3124 #ifdef STANDALONE
3125 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3126 "This systemd-tmpfiles version is compiled without support for --image=.");
3127 #else
3128 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
3129 if (r < 0)
3130 return r;
3131 #endif
3132 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
3133 _fallthrough_;
3134
3135 case 'E':
3136 r = exclude_default_prefixes();
3137 if (r < 0)
3138 return r;
3139
3140 break;
3141
3142 case ARG_REPLACE:
3143 if (!path_is_absolute(optarg) ||
3144 !endswith(optarg, ".conf"))
3145 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3146 "The argument to --replace= must an absolute path to a config file");
3147
3148 arg_replace = optarg;
3149 break;
3150
3151 case ARG_NO_PAGER:
3152 arg_pager_flags |= PAGER_DISABLE;
3153 break;
3154
3155 case '?':
3156 return -EINVAL;
3157
3158 default:
3159 assert_not_reached("Unhandled option");
3160 }
3161
3162 if (arg_operation == 0 && !arg_cat_config)
3163 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3164 "You need to specify at least one of --clean, --create or --remove.");
3165
3166 if (arg_replace && arg_cat_config)
3167 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3168 "Option --replace= is not supported with --cat-config");
3169
3170 if (arg_replace && optind >= argc)
3171 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3172 "When --replace= is given, some configuration items must be specified");
3173
3174 if (arg_root && arg_user)
3175 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3176 "Combination of --user and --root= is not supported.");
3177
3178 if (arg_image && arg_root)
3179 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
3180
3181 return 1;
3182 }
3183
3184 static int read_config_file(char **config_dirs, const char *fn, bool ignore_enoent, bool *invalid_config) {
3185 _cleanup_(hashmap_freep) Hashmap *uid_cache = NULL, *gid_cache = NULL;
3186 _cleanup_fclose_ FILE *_f = NULL;
3187 unsigned v = 0;
3188 FILE *f;
3189 Item *i;
3190 int r = 0;
3191
3192 assert(fn);
3193
3194 if (streq(fn, "-")) {
3195 log_debug("Reading config from stdin…");
3196 fn = "<stdin>";
3197 f = stdin;
3198 } else {
3199 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f);
3200 if (r < 0) {
3201 if (ignore_enoent && r == -ENOENT) {
3202 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
3203 return 0;
3204 }
3205
3206 return log_error_errno(r, "Failed to open '%s': %m", fn);
3207 }
3208 log_debug("Reading config file \"%s\"…", fn);
3209 f = _f;
3210 }
3211
3212 for (;;) {
3213 _cleanup_free_ char *line = NULL;
3214 bool invalid_line = false;
3215 char *l;
3216 int k;
3217
3218 k = read_line(f, LONG_LINE_MAX, &line);
3219 if (k < 0)
3220 return log_error_errno(k, "Failed to read '%s': %m", fn);
3221 if (k == 0)
3222 break;
3223
3224 v++;
3225
3226 l = strstrip(line);
3227 if (IN_SET(*l, 0, '#'))
3228 continue;
3229
3230 k = parse_line(fn, v, l, &invalid_line, &uid_cache, &gid_cache);
3231 if (k < 0) {
3232 if (invalid_line)
3233 /* Allow reporting with a special code if the caller requested this */
3234 *invalid_config = true;
3235 else if (r == 0)
3236 /* The first error becomes our return value */
3237 r = k;
3238 }
3239 }
3240
3241 /* we have to determine age parameter for each entry of type X */
3242 ORDERED_HASHMAP_FOREACH(i, globs) {
3243 Item *j, *candidate_item = NULL;
3244
3245 if (i->type != IGNORE_DIRECTORY_PATH)
3246 continue;
3247
3248 ORDERED_HASHMAP_FOREACH(j, items) {
3249 if (!IN_SET(j->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA))
3250 continue;
3251
3252 if (path_equal(j->path, i->path)) {
3253 candidate_item = j;
3254 break;
3255 }
3256
3257 if ((!candidate_item && path_startswith(i->path, j->path)) ||
3258 (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
3259 candidate_item = j;
3260 }
3261
3262 if (candidate_item && candidate_item->age_set) {
3263 i->age = candidate_item->age;
3264 i->age_set = true;
3265 }
3266 }
3267
3268 if (ferror(f)) {
3269 log_error_errno(errno, "Failed to read from file %s: %m", fn);
3270 if (r == 0)
3271 r = -EIO;
3272 }
3273
3274 return r;
3275 }
3276
3277 static int parse_arguments(char **config_dirs, char **args, bool *invalid_config) {
3278 char **arg;
3279 int r;
3280
3281 STRV_FOREACH(arg, args) {
3282 r = read_config_file(config_dirs, *arg, false, invalid_config);
3283 if (r < 0)
3284 return r;
3285 }
3286
3287 return 0;
3288 }
3289
3290 static int read_config_files(char **config_dirs, char **args, bool *invalid_config) {
3291 _cleanup_strv_free_ char **files = NULL;
3292 _cleanup_free_ char *p = NULL;
3293 char **f;
3294 int r;
3295
3296 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
3297 if (r < 0)
3298 return r;
3299
3300 STRV_FOREACH(f, files)
3301 if (p && path_equal(*f, p)) {
3302 log_debug("Parsing arguments at position \"%s\"…", *f);
3303
3304 r = parse_arguments(config_dirs, args, invalid_config);
3305 if (r < 0)
3306 return r;
3307 } else
3308 /* Just warn, ignore result otherwise.
3309 * read_config_file() has some debug output, so no need to print anything. */
3310 (void) read_config_file(config_dirs, *f, true, invalid_config);
3311
3312 return 0;
3313 }
3314
3315 static int link_parent(ItemArray *a) {
3316 const char *path;
3317 char *prefix;
3318 int r;
3319
3320 assert(a);
3321
3322 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
3323 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3324 * before their children, and clean up/remove children before their parents. */
3325
3326 if (a->n_items <= 0)
3327 return 0;
3328
3329 path = a->items[0].path;
3330 prefix = newa(char, strlen(path) + 1);
3331 PATH_FOREACH_PREFIX(prefix, path) {
3332 ItemArray *j;
3333
3334 j = ordered_hashmap_get(items, prefix);
3335 if (!j)
3336 j = ordered_hashmap_get(globs, prefix);
3337 if (j) {
3338 r = set_ensure_put(&j->children, NULL, a);
3339 if (r < 0)
3340 return log_oom();
3341
3342 a->parent = j;
3343 return 1;
3344 }
3345 }
3346
3347 return 0;
3348 }
3349
3350 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
3351 ItemArray, item_array_free);
3352
3353 static int run(int argc, char *argv[]) {
3354 #ifndef STANDALONE
3355 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
3356 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
3357 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
3358 #endif
3359 _cleanup_strv_free_ char **config_dirs = NULL;
3360 bool invalid_config = false;
3361 ItemArray *a;
3362 enum {
3363 PHASE_REMOVE_AND_CLEAN,
3364 PHASE_CREATE,
3365 _PHASE_MAX
3366 } phase;
3367 int r, k;
3368
3369 r = parse_argv(argc, argv);
3370 if (r <= 0)
3371 return r;
3372
3373 log_setup();
3374
3375 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
3376 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
3377 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
3378 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
3379 * and output a nice and friendly warning. */
3380 if (proc_mounted() == 0)
3381 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
3382 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
3383 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
3384
3385 /* Descending down file system trees might take a lot of fds */
3386 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
3387
3388 if (arg_user) {
3389 r = user_config_paths(&config_dirs);
3390 if (r < 0)
3391 return log_error_errno(r, "Failed to initialize configuration directory list: %m");
3392 } else {
3393 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
3394 if (!config_dirs)
3395 return log_oom();
3396 }
3397
3398 if (DEBUG_LOGGING) {
3399 _cleanup_free_ char *t = NULL;
3400 char **i;
3401
3402 STRV_FOREACH(i, config_dirs) {
3403 _cleanup_free_ char *j = NULL;
3404
3405 j = path_join(arg_root, *i);
3406 if (!j)
3407 return log_oom();
3408
3409 if (!strextend(&t, "\n\t", j))
3410 return log_oom();
3411 }
3412
3413 log_debug("Looking for configuration files in (higher priority first):%s", t);
3414 }
3415
3416 if (arg_cat_config) {
3417 (void) pager_open(arg_pager_flags);
3418
3419 return cat_config(config_dirs, argv + optind);
3420 }
3421
3422 umask(0022);
3423
3424 r = mac_selinux_init();
3425 if (r < 0)
3426 return r;
3427
3428 #ifndef STANDALONE
3429 if (arg_image) {
3430 assert(!arg_root);
3431
3432 r = mount_image_privately_interactively(
3433 arg_image,
3434 DISSECT_IMAGE_GENERIC_ROOT |
3435 DISSECT_IMAGE_REQUIRE_ROOT |
3436 DISSECT_IMAGE_VALIDATE_OS |
3437 DISSECT_IMAGE_RELAX_VAR_CHECK |
3438 DISSECT_IMAGE_FSCK,
3439 &unlink_dir,
3440 &loop_device,
3441 &decrypted_image);
3442 if (r < 0)
3443 return r;
3444
3445 arg_root = strdup(unlink_dir);
3446 if (!arg_root)
3447 return log_oom();
3448 }
3449 #else
3450 assert(!arg_image);
3451 #endif
3452
3453 items = ordered_hashmap_new(&item_array_hash_ops);
3454 globs = ordered_hashmap_new(&item_array_hash_ops);
3455 if (!items || !globs)
3456 return log_oom();
3457
3458 /* If command line arguments are specified along with --replace, read all
3459 * configuration files and insert the positional arguments at the specified
3460 * place. Otherwise, if command line arguments are specified, execute just
3461 * them, and finally, without --replace= or any positional arguments, just
3462 * read configuration and execute it.
3463 */
3464 if (arg_replace || optind >= argc)
3465 r = read_config_files(config_dirs, argv + optind, &invalid_config);
3466 else
3467 r = parse_arguments(config_dirs, argv + optind, &invalid_config);
3468 if (r < 0)
3469 return r;
3470
3471 /* Let's now link up all child/parent relationships */
3472 ORDERED_HASHMAP_FOREACH(a, items) {
3473 r = link_parent(a);
3474 if (r < 0)
3475 return r;
3476 }
3477 ORDERED_HASHMAP_FOREACH(a, globs) {
3478 r = link_parent(a);
3479 if (r < 0)
3480 return r;
3481 }
3482
3483 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
3484 * operations. i.e. that we first clean out the platform we then build on. */
3485 for (phase = 0; phase < _PHASE_MAX; phase++) {
3486 OperationMask op;
3487
3488 if (phase == PHASE_REMOVE_AND_CLEAN)
3489 op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
3490 else if (phase == PHASE_CREATE)
3491 op = arg_operation & OPERATION_CREATE;
3492 else
3493 assert_not_reached("unexpected phase");
3494
3495 if (op == 0) /* Nothing requested in this phase */
3496 continue;
3497
3498 /* The non-globbing ones usually create things, hence we apply them first */
3499 ORDERED_HASHMAP_FOREACH(a, items) {
3500 k = process_item_array(a, op);
3501 if (k < 0 && r >= 0)
3502 r = k;
3503 }
3504
3505 /* The globbing ones usually alter things, hence we apply them second. */
3506 ORDERED_HASHMAP_FOREACH(a, globs) {
3507 k = process_item_array(a, op);
3508 if (k < 0 && r >= 0)
3509 r = k;
3510 }
3511 }
3512
3513 if (ERRNO_IS_RESOURCE(r))
3514 return r;
3515 if (invalid_config)
3516 return EX_DATAERR;
3517 if (r < 0)
3518 return EX_CANTCREAT;
3519 return 0;
3520 }
3521
3522 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);