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