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