]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/tmpfiles/tmpfiles.c
tmpfiles: introduce copy_files() routine
[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
FB
1462static int copy_files(Item *i) {
1463 struct stat st;
1464 int r;
1465
1466 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
1467
1468 r = copy_tree(i->argument, i->path,
1469 i->uid_set ? i->uid : UID_INVALID,
1470 i->gid_set ? i->gid : GID_INVALID,
1471 COPY_REFLINK);
1472
1473 if (r == -EROFS && stat(i->path, &st) == 0)
1474 r = -EEXIST;
1475
1476 if (r < 0) {
1477 struct stat a, b;
1478
1479 if (r != -EEXIST)
1480 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
1481
1482 if (stat(i->argument, &a) < 0)
1483 return log_error_errno(errno, "stat(%s) failed: %m", i->argument);
1484
1485 if (stat(i->path, &b) < 0)
1486 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
1487
1488 if ((a.st_mode ^ b.st_mode) & S_IFMT) {
1489 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1490 return 0;
1491 }
1492 }
1493
1494 return path_set_perms(i, i->path);
1495}
1496
081043cf 1497typedef int (*action_t)(Item *, const char *);
936f6bdb 1498typedef int (*fdaction_t)(Item *, int fd, const struct stat *st);
081043cf 1499
14f3480a
FB
1500static int item_do(Item *i, int fd, fdaction_t action) {
1501 struct stat st;
936f6bdb 1502 int r = 0, q;
e73a03e0
LP
1503
1504 assert(i);
936f6bdb 1505 assert(fd >= 0);
14f3480a
FB
1506
1507 if (fstat(fd, &st) < 0) {
1508 r = -errno;
1509 goto finish;
1510 }
a8d88783
MS
1511
1512 /* This returns the first error we run into, but nevertheless
1513 * tries to go on */
14f3480a 1514 r = action(i, fd, &st);
a8d88783 1515
14f3480a 1516 if (S_ISDIR(st.st_mode)) {
22dd8d35 1517 char procfs_path[STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int)];
936f6bdb
FB
1518 _cleanup_closedir_ DIR *d = NULL;
1519 struct dirent *de;
a8d88783 1520
936f6bdb
FB
1521 /* The passed 'fd' was opened with O_PATH. We need to convert
1522 * it into a 'regular' fd before reading the directory content. */
1523 xsprintf(procfs_path, "/proc/self/fd/%i", fd);
a8d88783 1524
936f6bdb
FB
1525 d = opendir(procfs_path);
1526 if (!d) {
1527 r = r ?: -errno;
1528 goto finish;
1529 }
a8d88783 1530
936f6bdb 1531 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
936f6bdb 1532 int de_fd;
a8d88783 1533
936f6bdb
FB
1534 if (dot_or_dot_dot(de->d_name))
1535 continue;
1536
1537 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
14f3480a 1538 if (de_fd >= 0)
936f6bdb 1539 /* pass ownership of dirent fd over */
14f3480a 1540 q = item_do(i, de_fd, action);
936f6bdb
FB
1541 else
1542 q = -errno;
a8d88783 1543
e73a03e0
LP
1544 if (q < 0 && r == 0)
1545 r = q;
a8d88783 1546 }
a8d88783 1547 }
936f6bdb
FB
1548finish:
1549 safe_close(fd);
e73a03e0 1550 return r;
a8d88783
MS
1551}
1552
936f6bdb 1553static int glob_item(Item *i, action_t action) {
df99a9ef 1554 _cleanup_globfree_ glob_t g = {
ebf31a1f 1555 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
df99a9ef 1556 };
e73a03e0 1557 int r = 0, k;
99e68c0b
MS
1558 char **fn;
1559
84e72b5e
ZJS
1560 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1561 if (k < 0 && k != -ENOENT)
1562 return log_error_errno(k, "glob(%s) failed: %m", i->path);
99e68c0b 1563
c84a9488
ZJS
1564 STRV_FOREACH(fn, g.gl_pathv) {
1565 k = action(i, *fn);
e73a03e0 1566 if (k < 0 && r == 0)
99e68c0b 1567 r = k;
936f6bdb
FB
1568 }
1569
1570 return r;
1571}
081043cf 1572
936f6bdb
FB
1573static int glob_item_recursively(Item *i, fdaction_t action) {
1574 _cleanup_globfree_ glob_t g = {
1575 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
1576 };
1577 int r = 0, k;
1578 char **fn;
1579
1580 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
1581 if (k < 0 && k != -ENOENT)
1582 return log_error_errno(k, "glob(%s) failed: %m", i->path);
1583
1584 STRV_FOREACH(fn, g.gl_pathv) {
1585 _cleanup_close_ int fd = -1;
936f6bdb
FB
1586
1587 /* Make sure we won't trigger/follow file object (such as
1588 * device nodes, automounts, ...) pointed out by 'fn' with
1589 * O_PATH. Note, when O_PATH is used, flags other than
1590 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
1591
1592 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
1593 if (fd < 0) {
1594 r = r ?: -errno;
1595 continue;
1596 }
1597
14f3480a 1598 k = item_do(i, fd, action);
936f6bdb
FB
1599 if (k < 0 && r == 0)
1600 r = k;
1601
1602 /* we passed fd ownership to the previous call */
1603 fd = -1;
c84a9488 1604 }
99e68c0b 1605
99e68c0b
MS
1606 return r;
1607}
1608
294929f8
ZJS
1609typedef enum {
1610 CREATION_NORMAL,
1611 CREATION_EXISTING,
1612 CREATION_FORCE,
7a7d5db7
LP
1613 _CREATION_MODE_MAX,
1614 _CREATION_MODE_INVALID = -1
294929f8
ZJS
1615} CreationMode;
1616
7a7d5db7
LP
1617static const char *creation_mode_verb_table[_CREATION_MODE_MAX] = {
1618 [CREATION_NORMAL] = "Created",
1619 [CREATION_EXISTING] = "Found existing",
1620 [CREATION_FORCE] = "Created replacement",
1621};
1622
1623DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
294929f8 1624
3b63d2d3 1625static int create_item(Item *i) {
3b63d2d3 1626 struct stat st;
df28bc08 1627 int r = 0;
114a17d2 1628 int q = 0;
294929f8 1629 CreationMode creation;
5008d581 1630
3b63d2d3 1631 assert(i);
5008d581 1632
582deb84
ZJS
1633 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
1634
3b63d2d3
LP
1635 switch (i->type) {
1636
1637 case IGNORE_PATH:
78a92a5a 1638 case IGNORE_DIRECTORY_PATH:
3b63d2d3
LP
1639 case REMOVE_PATH:
1640 case RECURSIVE_REMOVE_PATH:
1641 return 0;
5008d581 1642
3b63d2d3 1643 case CREATE_FILE:
7fa10748
LP
1644 RUN_WITH_UMASK(0000)
1645 (void) mkdir_parents_label(i->path, 0755);
1646
31c84ff1 1647 r = create_file(i, i->path);
1845fdd9
DR
1648 if (r < 0)
1649 return r;
1650 break;
265ffa1e 1651
5ec9d065
FB
1652 case TRUNCATE_FILE:
1653 RUN_WITH_UMASK(0000)
1654 (void) mkdir_parents_label(i->path, 0755);
1655
1656 r = truncate_file(i, i->path);
1657 if (r < 0)
1658 return r;
1659 break;
1660
7b887f22 1661 case COPY_FILES:
7fa10748
LP
1662 RUN_WITH_UMASK(0000)
1663 (void) mkdir_parents_label(i->path, 0755);
1664
b1f7b17f 1665 r = copy_files(i);
849958d1
LP
1666 if (r < 0)
1667 return r;
849958d1
LP
1668 break;
1669
d4e9eb91 1670 case WRITE_FILE:
936f6bdb 1671 r = glob_item(i, write_one_file);
f05bc3f7
MS
1672 if (r < 0)
1673 return r;
5008d581 1674
3b63d2d3
LP
1675 break;
1676
3b63d2d3 1677 case CREATE_DIRECTORY:
d7b8eec7
LP
1678 case TRUNCATE_DIRECTORY:
1679 case CREATE_SUBVOLUME:
5fb13eb5
LP
1680 case CREATE_SUBVOLUME_INHERIT_QUOTA:
1681 case CREATE_SUBVOLUME_NEW_QUOTA:
d7b8eec7 1682 RUN_WITH_UMASK(0000)
7fa10748 1683 (void) mkdir_parents_label(i->path, 0755);
d7b8eec7 1684
5fb13eb5 1685 if (IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA)) {
2904e949 1686
945403e6 1687 if (btrfs_is_subvol(empty_to_root(arg_root)) <= 0)
2904e949
LP
1688
1689 /* Don't create a subvolume unless the
1690 * root directory is one, too. We do
1691 * this under the assumption that if
1692 * the root directory is just a plain
1693 * directory (i.e. very light-weight),
1694 * we shouldn't try to split it up
1695 * into subvolumes (i.e. more
1696 * heavy-weight). Thus, chroot()
1697 * environments and suchlike will get
1698 * a full brtfs subvolume set up below
1699 * their tree only if they
1700 * specifically set up a btrfs
1701 * subvolume for the root dir too. */
1702
1703 r = -ENOTTY;
1704 else {
1705 RUN_WITH_UMASK((~i->mode) & 0777)
1706 r = btrfs_subvol_make(i->path);
1707 }
5fb13eb5 1708 } else
d7b8eec7
LP
1709 r = 0;
1710
582deb84 1711 if (IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY) || r == -ENOTTY)
d7b8eec7
LP
1712 RUN_WITH_UMASK(0000)
1713 r = mkdir_label(i->path, i->mode);
5008d581 1714
e156347e 1715 if (r < 0) {
7b135a73 1716 int k;
5008d581 1717
4c701096 1718 if (!IN_SET(r, -EEXIST, -EROFS))
7b135a73 1719 return log_error_errno(r, "Failed to create directory or subvolume \"%s\": %m", i->path);
5008d581 1720
7b135a73
LP
1721 k = is_dir(i->path, false);
1722 if (k == -ENOENT && r == -EROFS)
1723 return log_error_errno(r, "%s does not exist and cannot be created as the file system is read-only.", i->path);
1724 if (k < 0)
1725 return log_error_errno(k, "Failed to check if %s exists: %m", i->path);
1726 if (!k) {
1727 log_warning("\"%s\" already exists and is not a directory.", i->path);
e156347e
LP
1728 return 0;
1729 }
294929f8
ZJS
1730
1731 creation = CREATION_EXISTING;
1732 } else
1733 creation = CREATION_NORMAL;
7b135a73 1734
7a7d5db7 1735 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), i->path);
5008d581 1736
5fb13eb5
LP
1737 if (IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
1738 r = btrfs_subvol_auto_qgroup(i->path, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
114a17d2 1739 if (r == -ENOTTY)
022ffe4c 1740 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
114a17d2 1741 else if (r == -EROFS)
022ffe4c 1742 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
114a17d2 1743 else if (r == -ENOPROTOOPT)
022ffe4c 1744 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
114a17d2
EV
1745 else if (r < 0)
1746 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
1747 else if (r > 0)
5fb13eb5 1748 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
114a17d2 1749 else if (r == 0)
5fb13eb5
LP
1750 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
1751 }
1752
4831981d 1753 _fallthrough_;
df8dee85 1754 case EMPTY_DIRECTORY:
939ca213 1755 r = glob_item(i, path_set_perms);
114a17d2
EV
1756 if (q < 0)
1757 return q;
f05bc3f7
MS
1758 if (r < 0)
1759 return r;
3b63d2d3
LP
1760
1761 break;
ee17ee7c
LP
1762
1763 case CREATE_FIFO:
5c0d398d 1764 RUN_WITH_UMASK(0000) {
7fa10748
LP
1765 (void) mkdir_parents_label(i->path, 0755);
1766
ecabcf8b 1767 mac_selinux_create_file_prepare(i->path, S_IFIFO);
5c0d398d 1768 r = mkfifo(i->path, i->mode);
ecabcf8b 1769 mac_selinux_create_file_clear();
5c0d398d 1770 }
ee17ee7c 1771
1554afae 1772 if (r < 0) {
4a62c710
MS
1773 if (errno != EEXIST)
1774 return log_error_errno(errno, "Failed to create fifo %s: %m", i->path);
ee17ee7c 1775
a542c4dc 1776 if (lstat(i->path, &st) < 0)
4a62c710 1777 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
ee17ee7c 1778
1554afae
LP
1779 if (!S_ISFIFO(st.st_mode)) {
1780
1781 if (i->force) {
1554afae 1782 RUN_WITH_UMASK(0000) {
ecabcf8b 1783 mac_selinux_create_file_prepare(i->path, S_IFIFO);
1554afae 1784 r = mkfifo_atomic(i->path, i->mode);
ecabcf8b 1785 mac_selinux_create_file_clear();
1554afae
LP
1786 }
1787
f647962d
MS
1788 if (r < 0)
1789 return log_error_errno(r, "Failed to create fifo %s: %m", i->path);
294929f8 1790 creation = CREATION_FORCE;
1554afae 1791 } else {
a542c4dc 1792 log_warning("\"%s\" already exists and is not a fifo.", i->path);
1554afae
LP
1793 return 0;
1794 }
294929f8
ZJS
1795 } else
1796 creation = CREATION_EXISTING;
1797 } else
1798 creation = CREATION_NORMAL;
7a7d5db7 1799 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
ee17ee7c 1800
b705ab6a 1801 r = path_set_perms(i, i->path);
f05bc3f7
MS
1802 if (r < 0)
1803 return r;
ee17ee7c
LP
1804
1805 break;
a8d88783 1806
5c5ccf12 1807 case CREATE_SYMLINK: {
7fa10748
LP
1808 RUN_WITH_UMASK(0000)
1809 (void) mkdir_parents_label(i->path, 0755);
1810
ecabcf8b 1811 mac_selinux_create_file_prepare(i->path, S_IFLNK);
4cef1923 1812 r = symlink(i->argument, i->path);
ecabcf8b 1813 mac_selinux_create_file_clear();
e9a5ef7c 1814
468d726b 1815 if (r < 0) {
2e78fa79 1816 _cleanup_free_ char *x = NULL;
468d726b 1817
4a62c710 1818 if (errno != EEXIST)
4cef1923 1819 return log_error_errno(errno, "symlink(%s, %s) failed: %m", i->argument, i->path);
2e78fa79
LP
1820
1821 r = readlink_malloc(i->path, &x);
4cef1923 1822 if (r < 0 || !streq(i->argument, x)) {
2e78fa79
LP
1823
1824 if (i->force) {
ecabcf8b 1825 mac_selinux_create_file_prepare(i->path, S_IFLNK);
4cef1923 1826 r = symlink_atomic(i->argument, i->path);
ecabcf8b 1827 mac_selinux_create_file_clear();
2e78fa79 1828
2ef5de1b 1829 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
b3f5897f
WD
1830 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL);
1831 if (r < 0)
1832 return log_error_errno(r, "rm -fr %s failed: %m", i->path);
1833
1834 mac_selinux_create_file_prepare(i->path, S_IFLNK);
4cef1923 1835 r = symlink(i->argument, i->path) < 0 ? -errno : 0;
b3f5897f
WD
1836 mac_selinux_create_file_clear();
1837 }
f647962d 1838 if (r < 0)
4cef1923 1839 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
a542c4dc 1840
294929f8 1841 creation = CREATION_FORCE;
1554afae 1842 } else {
582deb84 1843 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
1554afae
LP
1844 return 0;
1845 }
294929f8
ZJS
1846 } else
1847 creation = CREATION_EXISTING;
1848 } else
a542c4dc 1849
294929f8 1850 creation = CREATION_NORMAL;
7a7d5db7 1851 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
468d726b 1852 break;
5c5ccf12 1853 }
468d726b
LP
1854
1855 case CREATE_BLOCK_DEVICE:
1856 case CREATE_CHAR_DEVICE: {
cb7ed9df
LP
1857 mode_t file_type;
1858
1859 if (have_effective_cap(CAP_MKNOD) == 0) {
1860 /* In a container we lack CAP_MKNOD. We
ab06eef8 1861 shouldn't attempt to create the device node in
cb7ed9df
LP
1862 that case to avoid noise, and we don't support
1863 virtualized devices in containers anyway. */
1864
1865 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
1866 return 0;
1867 }
1868
7fa10748
LP
1869 RUN_WITH_UMASK(0000)
1870 (void) mkdir_parents_label(i->path, 0755);
1871
1554afae 1872 file_type = i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR;
468d726b 1873
5c0d398d 1874 RUN_WITH_UMASK(0000) {
ecabcf8b 1875 mac_selinux_create_file_prepare(i->path, file_type);
5c0d398d 1876 r = mknod(i->path, i->mode | file_type, i->major_minor);
ecabcf8b 1877 mac_selinux_create_file_clear();
5c0d398d 1878 }
468d726b 1879
6555ad8e
KS
1880 if (r < 0) {
1881 if (errno == EPERM) {
1882 log_debug("We lack permissions, possibly because of cgroup configuration; "
1883 "skipping creation of device node %s.", i->path);
1884 return 0;
1885 }
1886
4a62c710
MS
1887 if (errno != EEXIST)
1888 return log_error_errno(errno, "Failed to create device node %s: %m", i->path);
468d726b 1889
a542c4dc 1890 if (lstat(i->path, &st) < 0)
4a62c710 1891 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
468d726b 1892
1554afae
LP
1893 if ((st.st_mode & S_IFMT) != file_type) {
1894
1895 if (i->force) {
1896
1897 RUN_WITH_UMASK(0000) {
ecabcf8b 1898 mac_selinux_create_file_prepare(i->path, file_type);
1554afae 1899 r = mknod_atomic(i->path, i->mode | file_type, i->major_minor);
ecabcf8b 1900 mac_selinux_create_file_clear();
1554afae
LP
1901 }
1902
f647962d 1903 if (r < 0)
294929f8
ZJS
1904 return log_error_errno(r, "Failed to create device node \"%s\": %m", i->path);
1905 creation = CREATION_FORCE;
1554afae
LP
1906 } else {
1907 log_debug("%s is not a device node.", i->path);
1908 return 0;
1909 }
294929f8
ZJS
1910 } else
1911 creation = CREATION_EXISTING;
1912 } else
1913 creation = CREATION_NORMAL;
a542c4dc 1914
294929f8 1915 log_debug("%s %s device node \"%s\" %u:%u.",
7a7d5db7 1916 creation_mode_verb_to_string(creation),
582deb84
ZJS
1917 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1918 i->path, major(i->mode), minor(i->mode));
468d726b 1919
b705ab6a 1920 r = path_set_perms(i, i->path);
468d726b
LP
1921 if (r < 0)
1922 return r;
1923
1924 break;
1925 }
1926
e73a03e0 1927 case ADJUST_MODE:
777b87e7 1928 case RELABEL_PATH:
936f6bdb 1929 r = glob_item(i, path_set_perms);
777b87e7 1930 if (r < 0)
96ca8194 1931 return r;
777b87e7
MS
1932 break;
1933
a8d88783 1934 case RECURSIVE_RELABEL_PATH:
936f6bdb 1935 r = glob_item_recursively(i, fd_set_perms);
a8d88783
MS
1936 if (r < 0)
1937 return r;
ebf4e801 1938 break;
e73a03e0 1939
ebf4e801 1940 case SET_XATTR:
936f6bdb 1941 r = glob_item(i, path_set_xattrs);
b705ab6a
ZJS
1942 if (r < 0)
1943 return r;
1944 break;
1945
1946 case RECURSIVE_SET_XATTR:
936f6bdb 1947 r = glob_item_recursively(i, fd_set_xattrs);
ebf4e801
MW
1948 if (r < 0)
1949 return r;
e73a03e0 1950 break;
f8eeeaf9
ZJS
1951
1952 case SET_ACL:
936f6bdb 1953 r = glob_item(i, path_set_acls);
f8eeeaf9
ZJS
1954 if (r < 0)
1955 return r;
b705ab6a
ZJS
1956 break;
1957
1958 case RECURSIVE_SET_ACL:
936f6bdb 1959 r = glob_item_recursively(i, fd_set_acls);
b705ab6a
ZJS
1960 if (r < 0)
1961 return r;
1962 break;
22c3a6ca 1963
88ec4dfa 1964 case SET_ATTRIBUTE:
936f6bdb 1965 r = glob_item(i, path_set_attribute);
22c3a6ca
GB
1966 if (r < 0)
1967 return r;
1968 break;
1969
88ec4dfa 1970 case RECURSIVE_SET_ATTRIBUTE:
936f6bdb 1971 r = glob_item_recursively(i, fd_set_attribute);
22c3a6ca
GB
1972 if (r < 0)
1973 return r;
1974 break;
3b63d2d3
LP
1975 }
1976
f05bc3f7 1977 return 0;
3b63d2d3
LP
1978}
1979
a0896123 1980static int remove_item_instance(Item *i, const char *instance) {
3b63d2d3
LP
1981 int r;
1982
1983 assert(i);
1984
1985 switch (i->type) {
1986
3b63d2d3 1987 case REMOVE_PATH:
4a62c710 1988 if (remove(instance) < 0 && errno != ENOENT)
3f93da98 1989 return log_error_errno(errno, "rm(%s): %m", instance);
3b63d2d3
LP
1990
1991 break;
1992
1993 case TRUNCATE_DIRECTORY:
1994 case RECURSIVE_REMOVE_PATH:
d139b24a
LP
1995 /* FIXME: we probably should use dir_cleanup() here
1996 * instead of rm_rf() so that 'x' is honoured. */
582deb84 1997 log_debug("rm -rf \"%s\"", instance);
1b26f09e 1998 r = rm_rf(instance, (i->type == RECURSIVE_REMOVE_PATH ? REMOVE_ROOT|REMOVE_SUBVOLUME : 0) | REMOVE_PHYSICAL);
f647962d
MS
1999 if (r < 0 && r != -ENOENT)
2000 return log_error_errno(r, "rm_rf(%s): %m", instance);
3b63d2d3
LP
2001
2002 break;
7fcb4b9b
ZJS
2003
2004 default:
2005 assert_not_reached("wut?");
3b63d2d3
LP
2006 }
2007
2008 return 0;
2009}
2010
a0896123 2011static int remove_item(Item *i) {
b8bb3e8f
LP
2012 assert(i);
2013
582deb84
ZJS
2014 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2015
b8bb3e8f
LP
2016 switch (i->type) {
2017
b8bb3e8f
LP
2018 case REMOVE_PATH:
2019 case TRUNCATE_DIRECTORY:
99e68c0b 2020 case RECURSIVE_REMOVE_PATH:
936f6bdb 2021 return glob_item(i, remove_item_instance);
b8bb3e8f 2022
df8dee85
ZJS
2023 default:
2024 return 0;
2025 }
b8bb3e8f
LP
2026}
2027
78a92a5a 2028static int clean_item_instance(Item *i, const char* instance) {
7fd1b19b 2029 _cleanup_closedir_ DIR *d = NULL;
78a92a5a
MS
2030 struct stat s, ps;
2031 bool mountpoint;
78a92a5a 2032 usec_t cutoff, n;
582deb84 2033 char timestamp[FORMAT_TIMESTAMP_MAX];
78a92a5a
MS
2034
2035 assert(i);
2036
2037 if (!i->age_set)
2038 return 0;
2039
2040 n = now(CLOCK_REALTIME);
2041 if (n < i->age)
2042 return 0;
2043
2044 cutoff = n - i->age;
2045
df99a9ef 2046 d = opendir_nomod(instance);
78a92a5a 2047 if (!d) {
d710aaf7 2048 if (IN_SET(errno, ENOENT, ENOTDIR)) {
582deb84 2049 log_debug_errno(errno, "Directory \"%s\": %m", instance);
78a92a5a 2050 return 0;
582deb84 2051 }
78a92a5a 2052
d710aaf7 2053 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
78a92a5a
MS
2054 }
2055
4a62c710
MS
2056 if (fstat(dirfd(d), &s) < 0)
2057 return log_error_errno(errno, "stat(%s) failed: %m", i->path);
78a92a5a
MS
2058
2059 if (!S_ISDIR(s.st_mode)) {
2060 log_error("%s is not a directory.", i->path);
19fbec19 2061 return -ENOTDIR;
78a92a5a
MS
2062 }
2063
4a62c710
MS
2064 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
2065 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
78a92a5a 2066
2bb158c1 2067 mountpoint = s.st_dev != ps.st_dev || s.st_ino == ps.st_ino;
78a92a5a 2068
582deb84
ZJS
2069 log_debug("Cleanup threshold for %s \"%s\" is %s",
2070 mountpoint ? "mount point" : "directory",
2071 instance,
2072 format_timestamp_us(timestamp, sizeof(timestamp), cutoff));
2073
2074 return dir_cleanup(i, instance, d, &s, cutoff, s.st_dev, mountpoint,
2075 MAX_DEPTH, i->keep_first_level);
78a92a5a
MS
2076}
2077
2078static int clean_item(Item *i) {
78a92a5a
MS
2079 assert(i);
2080
582deb84
ZJS
2081 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
2082
78a92a5a
MS
2083 switch (i->type) {
2084 case CREATE_DIRECTORY:
d7b8eec7 2085 case CREATE_SUBVOLUME:
5fb13eb5
LP
2086 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2087 case CREATE_SUBVOLUME_NEW_QUOTA:
78a92a5a
MS
2088 case TRUNCATE_DIRECTORY:
2089 case IGNORE_PATH:
849958d1 2090 case COPY_FILES:
78a92a5a 2091 clean_item_instance(i, i->path);
df8dee85 2092 return 0;
65241c14 2093 case EMPTY_DIRECTORY:
78a92a5a 2094 case IGNORE_DIRECTORY_PATH:
936f6bdb 2095 return glob_item(i, clean_item_instance);
78a92a5a 2096 default:
df8dee85 2097 return 0;
78a92a5a 2098 }
78a92a5a
MS
2099}
2100
3f93da98
ZJS
2101static int process_item_array(ItemArray *array);
2102
3b63d2d3 2103static int process_item(Item *i) {
1e95893a 2104 int r, q, p, t = 0;
9348f0e6 2105 _cleanup_free_ char *prefix = NULL;
3b63d2d3
LP
2106
2107 assert(i);
2108
1910cd0e
LP
2109 if (i->done)
2110 return 0;
2111
2112 i->done = true;
2113
9348f0e6
ZJS
2114 prefix = malloc(strlen(i->path) + 1);
2115 if (!prefix)
2116 return log_oom();
2117
1910cd0e 2118 PATH_FOREACH_PREFIX(prefix, i->path) {
3f93da98 2119 ItemArray *j;
1910cd0e 2120
ef43a391 2121 j = ordered_hashmap_get(items, prefix);
1db50423
ZJS
2122 if (j) {
2123 int s;
2124
3f93da98 2125 s = process_item_array(j);
1db50423
ZJS
2126 if (s < 0 && t == 0)
2127 t = s;
2128 }
1910cd0e
LP
2129 }
2130
655f2da0
N
2131 if (chase_symlinks(i->path, NULL, CHASE_NO_AUTOFS, NULL) == -EREMOTE)
2132 return t;
2133
3b63d2d3 2134 r = arg_create ? create_item(i) : 0;
a0896123 2135 q = arg_remove ? remove_item(i) : 0;
3b63d2d3
LP
2136 p = arg_clean ? clean_item(i) : 0;
2137
1db50423
ZJS
2138 return t < 0 ? t :
2139 r < 0 ? r :
2140 q < 0 ? q :
2141 p;
3b63d2d3
LP
2142}
2143
3f93da98
ZJS
2144static int process_item_array(ItemArray *array) {
2145 unsigned n;
2146 int r = 0, k;
753615e8 2147
3f93da98
ZJS
2148 assert(array);
2149
2150 for (n = 0; n < array->count; n++) {
2151 k = process_item(array->items + n);
2152 if (k < 0 && r == 0)
2153 r = k;
2154 }
2155
2156 return r;
2157}
3b63d2d3 2158
3f93da98
ZJS
2159static void item_free_contents(Item *i) {
2160 assert(i);
3b63d2d3 2161 free(i->path);
468d726b 2162 free(i->argument);
ebf4e801 2163 strv_free(i->xattrs);
f8eeeaf9 2164
349cc4a5 2165#if HAVE_ACL
f8eeeaf9
ZJS
2166 acl_free(i->acl_access);
2167 acl_free(i->acl_default);
2168#endif
3b63d2d3
LP
2169}
2170
3f93da98
ZJS
2171static void item_array_free(ItemArray *a) {
2172 unsigned n;
2173
2174 if (!a)
2175 return;
2176
2177 for (n = 0; n < a->count; n++)
2178 item_free_contents(a->items + n);
2179 free(a->items);
2180 free(a);
2181}
e2f2fb78 2182
17493fa5
LP
2183static int item_compare(const void *a, const void *b) {
2184 const Item *x = a, *y = b;
2185
2186 /* Make sure that the ownership taking item is put first, so
2187 * that we first create the node, and then can adjust it */
2188
2189 if (takes_ownership(x->type) && !takes_ownership(y->type))
2190 return -1;
2191 if (!takes_ownership(x->type) && takes_ownership(y->type))
2192 return 1;
2193
2194 return (int) x->type - (int) y->type;
2195}
2196
3f93da98 2197static bool item_compatible(Item *a, Item *b) {
bfe95f35
LP
2198 assert(a);
2199 assert(b);
3f93da98 2200 assert(streq(a->path, b->path));
bfe95f35 2201
3f93da98
ZJS
2202 if (takes_ownership(a->type) && takes_ownership(b->type))
2203 /* check if the items are the same */
2204 return streq_ptr(a->argument, b->argument) &&
bfe95f35 2205
3f93da98
ZJS
2206 a->uid_set == b->uid_set &&
2207 a->uid == b->uid &&
bfe95f35 2208
3f93da98
ZJS
2209 a->gid_set == b->gid_set &&
2210 a->gid == b->gid &&
bfe95f35 2211
3f93da98
ZJS
2212 a->mode_set == b->mode_set &&
2213 a->mode == b->mode &&
bfe95f35 2214
3f93da98
ZJS
2215 a->age_set == b->age_set &&
2216 a->age == b->age &&
bfe95f35 2217
3f93da98 2218 a->mask_perms == b->mask_perms &&
bfe95f35 2219
3f93da98 2220 a->keep_first_level == b->keep_first_level &&
468d726b 2221
3f93da98 2222 a->major_minor == b->major_minor;
468d726b 2223
bfe95f35
LP
2224 return true;
2225}
2226
a2aced4a
DR
2227static bool should_include_path(const char *path) {
2228 char **prefix;
2229
abef3f91 2230 STRV_FOREACH(prefix, arg_exclude_prefixes)
582deb84
ZJS
2231 if (path_startswith(path, *prefix)) {
2232 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2233 path, *prefix);
5c795114 2234 return false;
582deb84 2235 }
a2aced4a 2236
abef3f91 2237 STRV_FOREACH(prefix, arg_include_prefixes)
582deb84
ZJS
2238 if (path_startswith(path, *prefix)) {
2239 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
a2aced4a 2240 return true;
582deb84 2241 }
a2aced4a 2242
5c795114
DR
2243 /* no matches, so we should include this path only if we
2244 * have no whitelist at all */
7b943bb7 2245 if (strv_isempty(arg_include_prefixes))
582deb84
ZJS
2246 return true;
2247
2248 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
2249 return false;
a2aced4a
DR
2250}
2251
4cef1923
FB
2252static int specifier_expansion_from_arg(Item *i) {
2253 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2254 char **xattr;
2255 int r;
2256
2257 assert(i);
2258
2259 if (i->argument == NULL)
2260 return 0;
2261
2262 switch (i->type) {
2263 case COPY_FILES:
2264 case CREATE_SYMLINK:
2265 case CREATE_FILE:
2266 case TRUNCATE_FILE:
2267 case WRITE_FILE:
2268 r = cunescape(i->argument, 0, &unescaped);
2269 if (r < 0)
2270 return log_error_errno(r, "Failed to unescape parameter to write: %s", i->argument);
2271
2272 r = specifier_printf(unescaped, specifier_table, NULL, &resolved);
2273 if (r < 0)
2274 return r;
2275
2276 free_and_replace(i->argument, resolved);
2277 break;
2278
2279 case SET_XATTR:
2280 case RECURSIVE_SET_XATTR:
2281 assert(i->xattrs);
2282
2283 STRV_FOREACH (xattr, i->xattrs) {
2284 r = specifier_printf(*xattr, specifier_table, NULL, &resolved);
2285 if (r < 0)
2286 return r;
2287
2288 free_and_replace(*xattr, resolved);
2289 }
2290 break;
2291
2292 default:
2293 break;
2294 }
2295 return 0;
2296}
2297
a2d1fb88
LP
2298static int patch_var_run(const char *fname, unsigned line, char **path) {
2299 const char *k;
2300 char *n;
2301
2302 assert(path);
2303 assert(*path);
2304
2305 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2306 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2307 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2308 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2309 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2310 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2311 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2312 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2313 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2314
2315 k = path_startswith(*path, "/var/run/");
2316 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2317 return 0;
2318
2319 n = strjoin("/run/", k);
2320 if (!n)
2321 return log_oom();
2322
2323 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2324 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2325 * to the user, let's still inform the user that these snippets should really be updated. */
2326
2327 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);
2328
2329 free(*path);
2330 *path = n;
2331
2332 return 0;
2333}
2334
d9daae55 2335static int parse_line(const char *fname, unsigned line, const char *buffer, bool *invalid_config) {
1731e34a 2336
cde684a2 2337 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
3f93da98
ZJS
2338 _cleanup_(item_free_contents) Item i = {};
2339 ItemArray *existing;
ef43a391 2340 OrderedHashmap *h;
657cf7f4 2341 int r, pos;
5f255144 2342 bool force = false, boot = false;
3b63d2d3
LP
2343
2344 assert(fname);
2345 assert(line >= 1);
2346 assert(buffer);
2347
68685607 2348 r = extract_many_words(
4034a06d 2349 &buffer,
68685607 2350 NULL,
12ba2c44 2351 EXTRACT_QUOTES,
4034a06d
LP
2352 &action,
2353 &path,
2354 &mode,
2355 &user,
2356 &group,
2357 &age,
2358 NULL);
d9daae55 2359 if (r < 0) {
751223fe
ZJS
2360 if (IN_SET(r, -EINVAL, -EBADSLT))
2361 /* invalid quoting and such or an unknown specifier */
d9daae55 2362 *invalid_config = true;
657cf7f4 2363 return log_error_errno(r, "[%s:%u] Failed to parse line: %m", fname, line);
4b93699d 2364 } else if (r < 2) {
d9daae55 2365 *invalid_config = true;
3b63d2d3 2366 log_error("[%s:%u] Syntax error.", fname, line);
7f2c1f4d 2367 return -EIO;
5008d581
LP
2368 }
2369
aa5f6817 2370 if (!isempty(buffer) && !streq(buffer, "-")) {
4034a06d
LP
2371 i.argument = strdup(buffer);
2372 if (!i.argument)
2373 return log_oom();
2374 }
2375
2e78fa79 2376 if (isempty(action)) {
d9daae55 2377 *invalid_config = true;
2e78fa79 2378 log_error("[%s:%u] Command too short '%s'.", fname, line, action);
c4708f13 2379 return -EINVAL;
2e78fa79
LP
2380 }
2381
5f255144
ZJS
2382 for (pos = 1; action[pos]; pos++) {
2383 if (action[pos] == '!' && !boot)
2384 boot = true;
2385 else if (action[pos] == '+' && !force)
2386 force = true;
2387 else {
d9daae55 2388 *invalid_config = true;
5f255144
ZJS
2389 log_error("[%s:%u] Unknown modifiers in command '%s'",
2390 fname, line, action);
2391 return -EINVAL;
2392 }
2e78fa79
LP
2393 }
2394
582deb84
ZJS
2395 if (boot && !arg_boot) {
2396 log_debug("Ignoring entry %s \"%s\" because --boot is not specified.",
2397 action, path);
c4708f13 2398 return 0;
582deb84 2399 }
c4708f13 2400
3f93da98
ZJS
2401 i.type = action[0];
2402 i.force = force;
2e78fa79 2403
3f93da98 2404 r = specifier_printf(path, specifier_table, NULL, &i.path);
5a8575ef 2405 if (r == -ENXIO)
4cef1923 2406 return log_unresolvable_specifier(fname, line);
d9daae55 2407 if (r < 0) {
751223fe
ZJS
2408 if (IN_SET(r, -EINVAL, -EBADSLT))
2409 *invalid_config = true;
4cef1923 2410 return log_error_errno(r, "[%s:%u] Failed to replace specifiers: %s", fname, line, path);
d9daae55 2411 }
1731e34a 2412
a2d1fb88
LP
2413 r = patch_var_run(fname, line, &i.path);
2414 if (r < 0)
2415 return r;
2416
3f93da98 2417 switch (i.type) {
468d726b 2418
777b87e7 2419 case CREATE_DIRECTORY:
d7b8eec7 2420 case CREATE_SUBVOLUME:
5fb13eb5
LP
2421 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2422 case CREATE_SUBVOLUME_NEW_QUOTA:
df8dee85 2423 case EMPTY_DIRECTORY:
777b87e7
MS
2424 case TRUNCATE_DIRECTORY:
2425 case CREATE_FIFO:
2426 case IGNORE_PATH:
78a92a5a 2427 case IGNORE_DIRECTORY_PATH:
777b87e7
MS
2428 case REMOVE_PATH:
2429 case RECURSIVE_REMOVE_PATH:
e73a03e0 2430 case ADJUST_MODE:
777b87e7
MS
2431 case RELABEL_PATH:
2432 case RECURSIVE_RELABEL_PATH:
c82500c6 2433 if (i.argument)
bd550f78 2434 log_warning("[%s:%u] %c lines don't take argument fields, ignoring.", fname, line, i.type);
c82500c6
LP
2435
2436 break;
2437
2438 case CREATE_FILE:
2439 case TRUNCATE_FILE:
777b87e7 2440 break;
468d726b
LP
2441
2442 case CREATE_SYMLINK:
3f93da98
ZJS
2443 if (!i.argument) {
2444 i.argument = strappend("/usr/share/factory/", i.path);
2445 if (!i.argument)
2f3b873a 2446 return log_oom();
468d726b
LP
2447 }
2448 break;
2449
31ed59c5 2450 case WRITE_FILE:
3f93da98 2451 if (!i.argument) {
d9daae55 2452 *invalid_config = true;
31ed59c5 2453 log_error("[%s:%u] Write file requires argument.", fname, line);
7f2c1f4d 2454 return -EBADMSG;
31ed59c5
LP
2455 }
2456 break;
2457
849958d1 2458 case COPY_FILES:
3f93da98
ZJS
2459 if (!i.argument) {
2460 i.argument = strappend("/usr/share/factory/", i.path);
2461 if (!i.argument)
2f3b873a 2462 return log_oom();
3f93da98 2463 } else if (!path_is_absolute(i.argument)) {
d9daae55 2464 *invalid_config = true;
849958d1
LP
2465 log_error("[%s:%u] Source path is not absolute.", fname, line);
2466 return -EBADMSG;
2467 }
2468
858d36c1 2469 path_simplify(i.argument, false);
849958d1
LP
2470 break;
2471
468d726b
LP
2472 case CREATE_CHAR_DEVICE:
2473 case CREATE_BLOCK_DEVICE: {
2474 unsigned major, minor;
2475
3f93da98 2476 if (!i.argument) {
d9daae55 2477 *invalid_config = true;
468d726b 2478 log_error("[%s:%u] Device file requires argument.", fname, line);
7f2c1f4d 2479 return -EBADMSG;
468d726b
LP
2480 }
2481
3f93da98 2482 if (sscanf(i.argument, "%u:%u", &major, &minor) != 2) {
d9daae55 2483 *invalid_config = true;
3f93da98 2484 log_error("[%s:%u] Can't parse device file major/minor '%s'.", fname, line, i.argument);
7f2c1f4d 2485 return -EBADMSG;
468d726b
LP
2486 }
2487
3f93da98 2488 i.major_minor = makedev(major, minor);
468d726b
LP
2489 break;
2490 }
2491
ebf4e801 2492 case SET_XATTR:
b705ab6a 2493 case RECURSIVE_SET_XATTR:
3f93da98 2494 if (!i.argument) {
d9daae55 2495 *invalid_config = true;
ebf4e801
MW
2496 log_error("[%s:%u] Set extended attribute requires argument.", fname, line);
2497 return -EBADMSG;
2498 }
bd550f78 2499 r = parse_xattrs_from_arg(&i);
ebf4e801
MW
2500 if (r < 0)
2501 return r;
2502 break;
2503
f8eeeaf9 2504 case SET_ACL:
b705ab6a 2505 case RECURSIVE_SET_ACL:
f8eeeaf9 2506 if (!i.argument) {
d9daae55 2507 *invalid_config = true;
f8eeeaf9
ZJS
2508 log_error("[%s:%u] Set ACLs requires argument.", fname, line);
2509 return -EBADMSG;
2510 }
bd550f78 2511 r = parse_acls_from_arg(&i);
f8eeeaf9
ZJS
2512 if (r < 0)
2513 return r;
2514 break;
2515
88ec4dfa
LP
2516 case SET_ATTRIBUTE:
2517 case RECURSIVE_SET_ATTRIBUTE:
22c3a6ca 2518 if (!i.argument) {
d9daae55 2519 *invalid_config = true;
88ec4dfa 2520 log_error("[%s:%u] Set file attribute requires argument.", fname, line);
22c3a6ca
GB
2521 return -EBADMSG;
2522 }
bd550f78 2523 r = parse_attribute_from_arg(&i);
751223fe 2524 if (IN_SET(r, -EINVAL, -EBADSLT))
d9daae55 2525 *invalid_config = true;
22c3a6ca
GB
2526 if (r < 0)
2527 return r;
2528 break;
2529
777b87e7 2530 default:
582deb84 2531 log_error("[%s:%u] Unknown command type '%c'.", fname, line, (char) i.type);
d9daae55 2532 *invalid_config = true;
7f2c1f4d 2533 return -EBADMSG;
3b63d2d3 2534 }
468d726b 2535
3f93da98
ZJS
2536 if (!path_is_absolute(i.path)) {
2537 log_error("[%s:%u] Path '%s' not absolute.", fname, line, i.path);
d9daae55 2538 *invalid_config = true;
7f2c1f4d 2539 return -EBADMSG;
3b63d2d3
LP
2540 }
2541
858d36c1 2542 path_simplify(i.path, false);
3b63d2d3 2543
3f93da98 2544 if (!should_include_path(i.path))
7f2c1f4d 2545 return 0;
5008d581 2546
4cef1923 2547 r = specifier_expansion_from_arg(&i);
5a8575ef 2548 if (r == -ENXIO)
4cef1923 2549 return log_unresolvable_specifier(fname, line);
751223fe
ZJS
2550 if (r < 0) {
2551 if (IN_SET(r, -EINVAL, -EBADSLT))
2552 *invalid_config = true;
4cef1923
FB
2553 return log_error_errno(r, "[%s:%u] Failed to substitute specifiers in argument: %m",
2554 fname, line);
751223fe 2555 }
4cef1923 2556
cf9a4abd 2557 if (arg_root) {
cde684a2
LP
2558 char *p;
2559
1d13f648 2560 p = prefix_root(arg_root, i.path);
cf9a4abd
MM
2561 if (!p)
2562 return log_oom();
2563
3f93da98
ZJS
2564 free(i.path);
2565 i.path = p;
cf9a4abd
MM
2566 }
2567
90937fe3 2568 if (!isempty(user) && !streq(user, "-")) {
4b67834e
LP
2569 const char *u = user;
2570
3f93da98 2571 r = get_user_creds(&u, &i.uid, NULL, NULL, NULL);
4b67834e 2572 if (r < 0) {
d9daae55
ZJS
2573 *invalid_config = true;
2574 return log_error_errno(r, "[%s:%u] Unknown user '%s'.", fname, line, user);
3b63d2d3
LP
2575 }
2576
3f93da98 2577 i.uid_set = true;
3b63d2d3
LP
2578 }
2579
90937fe3 2580 if (!isempty(group) && !streq(group, "-")) {
4b67834e
LP
2581 const char *g = group;
2582
3f93da98 2583 r = get_group_creds(&g, &i.gid);
4b67834e 2584 if (r < 0) {
d9daae55 2585 *invalid_config = true;
3b63d2d3 2586 log_error("[%s:%u] Unknown group '%s'.", fname, line, group);
7f2c1f4d 2587 return r;
3b63d2d3
LP
2588 }
2589
3f93da98 2590 i.gid_set = true;
3b63d2d3
LP
2591 }
2592
90937fe3 2593 if (!isempty(mode) && !streq(mode, "-")) {
abef3f91 2594 const char *mm = mode;
3b63d2d3
LP
2595 unsigned m;
2596
abef3f91 2597 if (*mm == '~') {
3f93da98 2598 i.mask_perms = true;
abef3f91
LP
2599 mm++;
2600 }
2601
2ff7b0a5 2602 if (parse_mode(mm, &m) < 0) {
d9daae55 2603 *invalid_config = true;
3b63d2d3 2604 log_error("[%s:%u] Invalid mode '%s'.", fname, line, mode);
2ff7b0a5 2605 return -EBADMSG;
3b63d2d3
LP
2606 }
2607
3f93da98
ZJS
2608 i.mode = m;
2609 i.mode_set = true;
3b63d2d3 2610 } else
5fb13eb5 2611 i.mode = IN_SET(i.type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
3b63d2d3 2612
90937fe3 2613 if (!isempty(age) && !streq(age, "-")) {
24f3a374
LP
2614 const char *a = age;
2615
2616 if (*a == '~') {
3f93da98 2617 i.keep_first_level = true;
24f3a374
LP
2618 a++;
2619 }
2620
3f93da98 2621 if (parse_sec(a, &i.age) < 0) {
d9daae55 2622 *invalid_config = true;
3b63d2d3 2623 log_error("[%s:%u] Invalid age '%s'.", fname, line, age);
7f2c1f4d 2624 return -EBADMSG;
3b63d2d3
LP
2625 }
2626
3f93da98 2627 i.age_set = true;
3b63d2d3
LP
2628 }
2629
3f93da98 2630 h = needs_glob(i.type) ? globs : items;
bfe95f35 2631
ef43a391 2632 existing = ordered_hashmap_get(h, i.path);
468d726b 2633 if (existing) {
3f93da98
ZJS
2634 unsigned n;
2635
2636 for (n = 0; n < existing->count; n++) {
6487ada8 2637 if (!item_compatible(existing->items + n, &i)) {
e286dbaf
ZJS
2638 log_notice("[%s:%u] Duplicate line for path \"%s\", ignoring.",
2639 fname, line, i.path);
6487ada8
MP
2640 return 0;
2641 }
ebf4e801
MW
2642 }
2643 } else {
3f93da98 2644 existing = new0(ItemArray, 1);
07982ed1
LP
2645 if (!existing)
2646 return log_oom();
2647
ef43a391 2648 r = ordered_hashmap_put(h, i.path, existing);
3f93da98
ZJS
2649 if (r < 0)
2650 return log_oom();
bfe95f35
LP
2651 }
2652
3f93da98
ZJS
2653 if (!GREEDY_REALLOC(existing->items, existing->size, existing->count + 1))
2654 return log_oom();
5008d581 2655
3f93da98 2656 memcpy(existing->items + existing->count++, &i, sizeof(i));
dd449aca
ZJS
2657
2658 /* Sort item array, to enforce stable ordering of application */
2659 qsort_safe(existing->items, existing->count, sizeof(Item), item_compare);
17493fa5 2660
3f93da98 2661 zero(i);
7f2c1f4d 2662 return 0;
5008d581
LP
2663}
2664
ceaaeb9b
ZJS
2665static int cat_config(char **config_dirs, char **args) {
2666 _cleanup_strv_free_ char **files = NULL;
2667 int r;
2668
2669 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
2670 if (r < 0)
2671 return r;
2672
2673 return cat_files(NULL, files, 0);
2674}
2675
601185b4 2676static void help(void) {
522d4a49
LP
2677 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
2678 "Creates, deletes and cleans up volatile and temporary files and directories.\n\n"
5c795114 2679 " -h --help Show this help\n"
f2b5ca0e 2680 " --user Execute user configuration\n"
eb9da376 2681 " --version Show package version\n"
ceaaeb9b 2682 " --cat-config Show configuration files\n"
5c795114
DR
2683 " --create Create marked files/directories\n"
2684 " --clean Clean up marked directories\n"
2685 " --remove Remove marked files/directories\n"
81815651 2686 " --boot Execute actions only safe at boot\n"
79ca888f
ZJS
2687 " --prefix=PATH Only apply rules with the specified prefix\n"
2688 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
d9daae55 2689 " --root=PATH Operate on an alternate filesystem root\n"
a6d8474f 2690 " --replace=PATH Treat arguments as replacement for PATH\n"
dcd5c891 2691 " --no-pager Do not pipe output into a pager\n"
d9daae55 2692 , program_invocation_short_name);
3b63d2d3
LP
2693}
2694
2695static int parse_argv(int argc, char *argv[]) {
2696
2697 enum {
eb9da376 2698 ARG_VERSION = 0x100,
ceaaeb9b 2699 ARG_CAT_CONFIG,
f2b5ca0e 2700 ARG_USER,
3b63d2d3
LP
2701 ARG_CREATE,
2702 ARG_CLEAN,
fba6e687 2703 ARG_REMOVE,
81815651 2704 ARG_BOOT,
5c795114
DR
2705 ARG_PREFIX,
2706 ARG_EXCLUDE_PREFIX,
cf9a4abd 2707 ARG_ROOT,
a6d8474f 2708 ARG_REPLACE,
dcd5c891 2709 ARG_NO_PAGER,
3b63d2d3
LP
2710 };
2711
2712 static const struct option options[] = {
5c795114 2713 { "help", no_argument, NULL, 'h' },
f2b5ca0e 2714 { "user", no_argument, NULL, ARG_USER },
eb9da376 2715 { "version", no_argument, NULL, ARG_VERSION },
ceaaeb9b 2716 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
5c795114
DR
2717 { "create", no_argument, NULL, ARG_CREATE },
2718 { "clean", no_argument, NULL, ARG_CLEAN },
2719 { "remove", no_argument, NULL, ARG_REMOVE },
81815651 2720 { "boot", no_argument, NULL, ARG_BOOT },
5c795114
DR
2721 { "prefix", required_argument, NULL, ARG_PREFIX },
2722 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
cf9a4abd 2723 { "root", required_argument, NULL, ARG_ROOT },
a6d8474f 2724 { "replace", required_argument, NULL, ARG_REPLACE },
dcd5c891 2725 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
eb9da376 2726 {}
3b63d2d3
LP
2727 };
2728
0f474365 2729 int c, r;
3b63d2d3
LP
2730
2731 assert(argc >= 0);
2732 assert(argv);
2733
601185b4 2734 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
3b63d2d3
LP
2735
2736 switch (c) {
2737
2738 case 'h':
601185b4
ZJS
2739 help();
2740 return 0;
eb9da376
LP
2741
2742 case ARG_VERSION:
3f6fd1ba 2743 return version();
3b63d2d3 2744
ceaaeb9b
ZJS
2745 case ARG_CAT_CONFIG:
2746 arg_cat_config = true;
2747 break;
2748
f2b5ca0e
ZJS
2749 case ARG_USER:
2750 arg_user = true;
2751 break;
2752
3b63d2d3
LP
2753 case ARG_CREATE:
2754 arg_create = true;
2755 break;
2756
2757 case ARG_CLEAN:
2758 arg_clean = true;
2759 break;
2760
2761 case ARG_REMOVE:
2762 arg_remove = true;
2763 break;
2764
81815651
ZJS
2765 case ARG_BOOT:
2766 arg_boot = true;
c4708f13
ZJS
2767 break;
2768
fba6e687 2769 case ARG_PREFIX:
7bc040fa 2770 if (strv_push(&arg_include_prefixes, optarg) < 0)
a2aced4a 2771 return log_oom();
fba6e687
LP
2772 break;
2773
5c795114 2774 case ARG_EXCLUDE_PREFIX:
7bc040fa 2775 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
5c795114
DR
2776 return log_oom();
2777 break;
2778
cf9a4abd 2779 case ARG_ROOT:
0f03c2a4 2780 r = parse_path_argument_and_warn(optarg, true, &arg_root);
0f474365 2781 if (r < 0)
0f03c2a4 2782 return r;
cf9a4abd
MM
2783 break;
2784
a6d8474f
ZJS
2785 case ARG_REPLACE:
2786 if (!path_is_absolute(optarg) ||
2787 !endswith(optarg, ".conf")) {
2788 log_error("The argument to --replace= must an absolute path to a config file");
2789 return -EINVAL;
2790 }
2791
2792 arg_replace = optarg;
2793 break;
2794
dcd5c891
LP
2795 case ARG_NO_PAGER:
2796 arg_no_pager = true;
2797 break;
2798
3b63d2d3
LP
2799 case '?':
2800 return -EINVAL;
2801
2802 default:
eb9da376 2803 assert_not_reached("Unhandled option");
3b63d2d3 2804 }
3b63d2d3 2805
ceaaeb9b 2806 if (!arg_clean && !arg_create && !arg_remove && !arg_cat_config) {
35b8ca3a 2807 log_error("You need to specify at least one of --clean, --create or --remove.");
3b63d2d3
LP
2808 return -EINVAL;
2809 }
2810
ceaaeb9b
ZJS
2811 if (arg_replace && arg_cat_config) {
2812 log_error("Option --replace= is not supported with --cat-config");
2813 return -EINVAL;
2814 }
2815
a6d8474f
ZJS
2816 if (arg_replace && optind >= argc) {
2817 log_error("When --replace= is given, some configuration items must be specified");
2818 return -EINVAL;
2819 }
2820
3b63d2d3
LP
2821 return 1;
2822}
2823
a6d8474f 2824static int read_config_file(char **config_dirs, const char *fn, bool ignore_enoent, bool *invalid_config) {
f7ac1ed2
ZJS
2825 _cleanup_fclose_ FILE *_f = NULL;
2826 FILE *f;
1731e34a 2827 char line[LINE_MAX];
78a92a5a 2828 Iterator iterator;
1731e34a 2829 unsigned v = 0;
78a92a5a 2830 Item *i;
4e68ec18 2831 int r = 0;
fba6e687
LP
2832
2833 assert(fn);
2834
f7ac1ed2 2835 if (streq(fn, "-")) {
a6d8474f 2836 log_debug("Reading config from stdin…");
f7ac1ed2
ZJS
2837 fn = "<stdin>";
2838 f = stdin;
2839 } else {
a6d8474f 2840 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f);
f7ac1ed2
ZJS
2841 if (r < 0) {
2842 if (ignore_enoent && r == -ENOENT) {
2843 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
2844 return 0;
2845 }
fba6e687 2846
f7ac1ed2
ZJS
2847 return log_error_errno(r, "Failed to open '%s': %m", fn);
2848 }
a6d8474f 2849 log_debug("Reading config file \"%s\"…", fn);
f7ac1ed2 2850 f = _f;
fba6e687
LP
2851 }
2852
1731e34a
LP
2853 FOREACH_LINE(line, f, break) {
2854 char *l;
fba6e687 2855 int k;
d9daae55 2856 bool invalid_line = false;
fba6e687 2857
fba6e687
LP
2858 v++;
2859
2860 l = strstrip(line);
4c701096 2861 if (IN_SET(*l, 0, '#'))
fba6e687
LP
2862 continue;
2863
d9daae55
ZJS
2864 k = parse_line(fn, v, l, &invalid_line);
2865 if (k < 0) {
2866 if (invalid_line)
2867 /* Allow reporting with a special code if the caller requested this */
2868 *invalid_config = true;
2869 else if (r == 0)
2870 /* The first error becomes our return value */
2871 r = k;
2872 }
fba6e687
LP
2873 }
2874
78a92a5a 2875 /* we have to determine age parameter for each entry of type X */
ef43a391 2876 ORDERED_HASHMAP_FOREACH(i, globs, iterator) {
78a92a5a
MS
2877 Iterator iter;
2878 Item *j, *candidate_item = NULL;
2879
2880 if (i->type != IGNORE_DIRECTORY_PATH)
2881 continue;
2882
ef43a391 2883 ORDERED_HASHMAP_FOREACH(j, items, iter) {
5fb13eb5 2884 if (!IN_SET(j->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA))
78a92a5a
MS
2885 continue;
2886
2887 if (path_equal(j->path, i->path)) {
2888 candidate_item = j;
2889 break;
2890 }
2891
2892 if ((!candidate_item && path_startswith(i->path, j->path)) ||
2893 (candidate_item && path_startswith(j->path, candidate_item->path) && (fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)))
2894 candidate_item = j;
2895 }
2896
9ed2a35e 2897 if (candidate_item && candidate_item->age_set) {
78a92a5a
MS
2898 i->age = candidate_item->age;
2899 i->age_set = true;
2900 }
2901 }
2902
fba6e687 2903 if (ferror(f)) {
56f64d95 2904 log_error_errno(errno, "Failed to read from file %s: %m", fn);
fba6e687
LP
2905 if (r == 0)
2906 r = -EIO;
2907 }
2908
fba6e687
LP
2909 return r;
2910}
2911
a6d8474f
ZJS
2912static int parse_arguments(char **config_dirs, char **args, bool *invalid_config) {
2913 char **arg;
2914 int r;
2915
2916 STRV_FOREACH(arg, args) {
2917 r = read_config_file(config_dirs, *arg, false, invalid_config);
2918 if (r < 0)
2919 return r;
2920 }
2921
2922 return 0;
2923}
2924
2925static int read_config_files(char **config_dirs, char **args, bool *invalid_config) {
2926 _cleanup_strv_free_ char **files = NULL;
2927 _cleanup_free_ char *p = NULL;
2928 char **f;
2929 int r;
2930
ceaaeb9b 2931 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
a6d8474f 2932 if (r < 0)
ceaaeb9b 2933 return r;
a6d8474f
ZJS
2934
2935 STRV_FOREACH(f, files)
2936 if (p && path_equal(*f, p)) {
2937 log_debug("Parsing arguments at position \"%s\"…", *f);
2938
2939 r = parse_arguments(config_dirs, args, invalid_config);
2940 if (r < 0)
2941 return r;
2942 } else
2943 /* Just warn, ignore result otherwise.
2944 * read_config_file() has some debug output, so no need to print anything. */
2945 (void) read_config_file(config_dirs, *f, true, invalid_config);
2946
2947 return 0;
2948}
2949
5008d581 2950int main(int argc, char *argv[]) {
bb9947be 2951 int r, k, r_process = 0;
3f93da98 2952 ItemArray *a;
3b63d2d3 2953 Iterator iterator;
f2b5ca0e 2954 _cleanup_strv_free_ char **config_dirs = NULL;
d9daae55 2955 bool invalid_config = false;
3b63d2d3 2956
fdcad0c2
LP
2957 r = parse_argv(argc, argv);
2958 if (r <= 0)
753615e8 2959 goto finish;
5008d581 2960
eb0ca9eb 2961 log_set_target(LOG_TARGET_AUTO);
5008d581
LP
2962 log_parse_environment();
2963 log_open();
2964
f2b5ca0e
ZJS
2965 if (arg_user) {
2966 r = user_config_paths(&config_dirs);
2967 if (r < 0) {
2968 log_error_errno(r, "Failed to initialize configuration directory list: %m");
2969 goto finish;
2970 }
2971 } else {
2972 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
2973 if (!config_dirs) {
2974 r = log_oom();
2975 goto finish;
2976 }
2977 }
2978
79c91cec 2979 if (DEBUG_LOGGING) {
f2b5ca0e
ZJS
2980 _cleanup_free_ char *t = NULL;
2981
2982 t = strv_join(config_dirs, "\n\t");
2983 if (t)
bb9947be 2984 log_debug("Looking for configuration files in (higher priority first):\n\t%s", t);
f2b5ca0e
ZJS
2985 }
2986
ceaaeb9b 2987 if (arg_cat_config) {
dcd5c891
LP
2988 (void) pager_open(arg_no_pager, false);
2989
ceaaeb9b
ZJS
2990 r = cat_config(config_dirs, argv + optind);
2991 goto finish;
2992 }
2993
2994 umask(0022);
2995
2996 mac_selinux_init();
2997
2998 items = ordered_hashmap_new(&string_hash_ops);
2999 globs = ordered_hashmap_new(&string_hash_ops);
3000
3001 if (!items || !globs) {
3002 r = log_oom();
3003 goto finish;
3004 }
3005
a6d8474f
ZJS
3006 /* If command line arguments are specified along with --replace, read all
3007 * configuration files and insert the positional arguments at the specified
3008 * place. Otherwise, if command line arguments are specified, execute just
3009 * them, and finally, without --replace= or any positional arguments, just
3010 * read configuration and execute it.
3011 */
3012 if (arg_replace || optind >= argc)
3013 r = read_config_files(config_dirs, argv + optind, &invalid_config);
3014 else
3015 r = parse_arguments(config_dirs, argv + optind, &invalid_config);
3016 if (r < 0)
3017 goto finish;
5008d581 3018
17493fa5
LP
3019 /* The non-globbing ones usually create things, hence we apply
3020 * them first */
ef43a391 3021 ORDERED_HASHMAP_FOREACH(a, items, iterator) {
3f93da98 3022 k = process_item_array(a);
bb9947be
ZJS
3023 if (k < 0 && r_process == 0)
3024 r_process = k;
1db50423 3025 }
b8bb3e8f 3026
17493fa5
LP
3027 /* The globbing ones usually alter things, hence we apply them
3028 * second. */
ef43a391 3029 ORDERED_HASHMAP_FOREACH(a, globs, iterator) {
3f93da98 3030 k = process_item_array(a);
bb9947be
ZJS
3031 if (k < 0 && r_process == 0)
3032 r_process = k;
1db50423 3033 }
3b63d2d3 3034
5008d581 3035finish:
dcd5c891
LP
3036 pager_close();
3037
224b0e7a
ZJS
3038 ordered_hashmap_free_with_destructor(items, item_array_free);
3039 ordered_hashmap_free_with_destructor(globs, item_array_free);
5008d581 3040
7bc040fa
LP
3041 free(arg_include_prefixes);
3042 free(arg_exclude_prefixes);
cf9a4abd 3043 free(arg_root);
a2aced4a 3044
17b90525
LP
3045 set_free_free(unix_sockets);
3046
cc56fafe 3047 mac_selinux_finish();
29003cff 3048
bb9947be 3049 if (r < 0 || ERRNO_IS_RESOURCE(-r_process))
d9daae55
ZJS
3050 return EXIT_FAILURE;
3051 else if (invalid_config)
3052 return EX_DATAERR;
bb9947be
ZJS
3053 else if (r_process < 0)
3054 return EX_CANTCREAT;
d9daae55
ZJS
3055 else
3056 return EXIT_SUCCESS;
5008d581 3057}