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