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