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