]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/tmpfiles/tmpfiles.c
basic,shared: move disable_coredumps() to coredump-util.[ch]
[thirdparty/systemd.git] / src / tmpfiles / tmpfiles.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
5008d581 2
5008d581 3#include <errno.h>
3f6fd1ba
LP
4#include <fcntl.h>
5#include <fnmatch.h>
6#include <getopt.h>
5008d581 7#include <limits.h>
3f6fd1ba
LP
8#include <linux/fs.h>
9#include <stdbool.h>
10#include <stddef.h>
3b63d2d3 11#include <stdlib.h>
52b32b2a 12#include <sys/file.h>
ebf4e801 13#include <sys/xattr.h>
d9daae55 14#include <sysexits.h>
3f6fd1ba
LP
15#include <time.h>
16#include <unistd.h>
5008d581 17
5a8575ef
ZJS
18#include "sd-path.h"
19
3f6fd1ba 20#include "acl-util.h"
b5efdb8a 21#include "alloc-util.h"
3f6fd1ba 22#include "btrfs-util.h"
430f0182 23#include "capability-util.h"
f4351959 24#include "chase-symlinks.h"
c8b3094d 25#include "chattr-util.h"
3f6fd1ba
LP
26#include "conf-files.h"
27#include "copy.h"
1d77721f 28#include "creds-util.h"
a0f29c76 29#include "def.h"
7176f06c 30#include "devnum-util.h"
8fb3f009 31#include "dirent-util.h"
63d3d0a5 32#include "dissect-image.h"
4368c60c 33#include "env-util.h"
8f6fb95c 34#include "errno-util.h"
4f5dd394 35#include "escape.h"
3ffd4af2 36#include "fd-util.h"
0d39fa9c 37#include "fileio.h"
f97b34a6 38#include "format-util.h"
f4f15635 39#include "fs-util.h"
7d50b32a 40#include "glob-util.h"
708daf42 41#include "hexdecoct.h"
c004493c 42#include "io-util.h"
3f6fd1ba 43#include "label.h"
5008d581 44#include "log.h"
54693d9b 45#include "macro.h"
87938c3b 46#include "main-func.h"
ddb439b8
LP
47#include "missing_stat.h"
48#include "missing_syscall.h"
35cd0ba5 49#include "mkdir-label.h"
63d3d0a5 50#include "mount-util.h"
049af8ad 51#include "mountpoint-util.h"
a3451c2c 52#include "offline-passwd.h"
dcd5c891 53#include "pager.h"
614b022c 54#include "parse-argument.h"
6bedfcbb 55#include "parse-util.h"
f2b5ca0e 56#include "path-lookup.h"
9eb977db 57#include "path-util.h"
294bf0c3 58#include "pretty-print.h"
e5358401 59#include "rlimit-util.h"
c6878637 60#include "rm-rf.h"
d7b8eec7 61#include "selinux-util.h"
3f6fd1ba 62#include "set.h"
760877e9 63#include "sort-util.h"
3f6fd1ba 64#include "specifier.h"
15a5e950 65#include "stdio-util.h"
8b43440b 66#include "string-table.h"
07630cea 67#include "string-util.h"
3f6fd1ba 68#include "strv.h"
3f532a59 69#include "terminal-util.h"
affb60b1 70#include "umask-util.h"
b1d4f8e1 71#include "user-util.h"
1401882f 72#include "virt.h"
5008d581 73
01000479 74/* This reads all files listed in /etc/tmpfiles.d/?*.conf and creates
5008d581 75 * them in the file system. This is intended to be used to create
db019b8d
KS
76 * properly owned directories beneath /tmp, /var/tmp, /run, which are
77 * volatile and hence need to be recreated on bootup. */
5008d581 78
1a967b6b
LP
79typedef enum OperationMask {
80 OPERATION_CREATE = 1 << 0,
81 OPERATION_REMOVE = 1 << 1,
82 OPERATION_CLEAN = 1 << 2,
83} OperationMask;
84
66ccd038 85typedef enum ItemType {
b8bb3e8f 86 /* These ones take file names */
3b63d2d3 87 CREATE_FILE = 'f',
eccebf4b 88 TRUNCATE_FILE = 'F', /* deprecated: use f+ */
3b63d2d3
LP
89 CREATE_DIRECTORY = 'd',
90 TRUNCATE_DIRECTORY = 'D',
d7b8eec7 91 CREATE_SUBVOLUME = 'v',
5fb13eb5
LP
92 CREATE_SUBVOLUME_INHERIT_QUOTA = 'q',
93 CREATE_SUBVOLUME_NEW_QUOTA = 'Q',
ee17ee7c 94 CREATE_FIFO = 'p',
468d726b
LP
95 CREATE_SYMLINK = 'L',
96 CREATE_CHAR_DEVICE = 'c',
97 CREATE_BLOCK_DEVICE = 'b',
849958d1 98 COPY_FILES = 'C',
b8bb3e8f
LP
99
100 /* These ones take globs */
17493fa5 101 WRITE_FILE = 'w',
df8dee85 102 EMPTY_DIRECTORY = 'e',
b705ab6a
ZJS
103 SET_XATTR = 't',
104 RECURSIVE_SET_XATTR = 'T',
105 SET_ACL = 'a',
106 RECURSIVE_SET_ACL = 'A',
17493fa5
LP
107 SET_ATTRIBUTE = 'h',
108 RECURSIVE_SET_ATTRIBUTE = 'H',
3b63d2d3 109 IGNORE_PATH = 'x',
78a92a5a 110 IGNORE_DIRECTORY_PATH = 'X',
3b63d2d3 111 REMOVE_PATH = 'r',
a8d88783 112 RECURSIVE_REMOVE_PATH = 'R',
777b87e7 113 RELABEL_PATH = 'z',
e73a03e0 114 RECURSIVE_RELABEL_PATH = 'Z',
17493fa5 115 ADJUST_MODE = 'm', /* legacy, 'z' is identical to this */
66ccd038 116} ItemType;
3b63d2d3 117
7f7a50dd
SK
118typedef enum AgeBy {
119 AGE_BY_ATIME = 1 << 0,
120 AGE_BY_BTIME = 1 << 1,
121 AGE_BY_CTIME = 1 << 2,
122 AGE_BY_MTIME = 1 << 3,
123
124 /* All file timestamp types are checked by default. */
125 AGE_BY_DEFAULT_FILE = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_CTIME | AGE_BY_MTIME,
126 AGE_BY_DEFAULT_DIR = AGE_BY_ATIME | AGE_BY_BTIME | AGE_BY_MTIME
127} AgeBy;
128
3b63d2d3 129typedef struct Item {
66ccd038 130 ItemType type;
3b63d2d3
LP
131
132 char *path;
468d726b 133 char *argument;
708daf42
LP
134 void *binary_argument; /* set if binary data, in which case it takes precedence over 'argument' */
135 size_t binary_argument_size;
ebf4e801 136 char **xattrs;
349cc4a5 137#if HAVE_ACL
f8eeeaf9
ZJS
138 acl_t acl_access;
139 acl_t acl_default;
140#endif
5008d581
LP
141 uid_t uid;
142 gid_t gid;
3b63d2d3
LP
143 mode_t mode;
144 usec_t age;
7f7a50dd 145 AgeBy age_by_file, age_by_dir;
3b63d2d3 146
468d726b 147 dev_t major_minor;
88ec4dfa
LP
148 unsigned attribute_value;
149 unsigned attribute_mask;
468d726b 150
3b63d2d3
LP
151 bool uid_set:1;
152 bool gid_set:1;
153 bool mode_set:1;
cc43328c
LP
154 bool uid_only_create:1;
155 bool gid_only_create:1;
156 bool mode_only_create:1;
3b63d2d3 157 bool age_set:1;
abef3f91 158 bool mask_perms:1;
88ec4dfa 159 bool attribute_set:1;
24f3a374
LP
160
161 bool keep_first_level:1;
1910cd0e 162
c55ac248 163 bool append_or_force:1;
2e78fa79 164
6d7b5433
WD
165 bool allow_failure:1;
166
c46c3233
AW
167 bool try_replace:1;
168
811a1587 169 OperationMask done;
3b63d2d3
LP
170} Item;
171
3f93da98
ZJS
172typedef struct ItemArray {
173 Item *items;
96d10d78 174 size_t n_items;
811a1587
LP
175
176 struct ItemArray *parent;
177 Set *children;
3f93da98
ZJS
178} ItemArray;
179
5a8575ef 180typedef enum DirectoryType {
133bbca4 181 DIRECTORY_RUNTIME,
5a8575ef
ZJS
182 DIRECTORY_STATE,
183 DIRECTORY_CACHE,
184 DIRECTORY_LOGS,
185 _DIRECTORY_TYPE_MAX,
186} DirectoryType;
187
a9bc518c
LP
188typedef enum {
189 CREATION_NORMAL,
190 CREATION_EXISTING,
191 CREATION_FORCE,
192 _CREATION_MODE_MAX,
193 _CREATION_MODE_INVALID = -EINVAL,
194} CreationMode;
195
ceaaeb9b 196static bool arg_cat_config = false;
f2b5ca0e 197static bool arg_user = false;
1a967b6b 198static OperationMask arg_operation = 0;
81815651 199static bool arg_boot = false;
0221d68a 200static PagerFlags arg_pager_flags = 0;
3b63d2d3 201
7bc040fa
LP
202static char **arg_include_prefixes = NULL;
203static char **arg_exclude_prefixes = NULL;
cf9a4abd 204static char *arg_root = NULL;
63d3d0a5 205static char *arg_image = NULL;
a6d8474f 206static char *arg_replace = NULL;
fba6e687 207
3b63d2d3
LP
208#define MAX_DEPTH 256
209
ef43a391 210static OrderedHashmap *items = NULL, *globs = NULL;
7bc040fa
LP
211static Set *unix_sockets = NULL;
212
87938c3b
YW
213STATIC_DESTRUCTOR_REGISTER(items, ordered_hashmap_freep);
214STATIC_DESTRUCTOR_REGISTER(globs, ordered_hashmap_freep);
fe2f05b7 215STATIC_DESTRUCTOR_REGISTER(unix_sockets, set_freep);
87938c3b
YW
216STATIC_DESTRUCTOR_REGISTER(arg_include_prefixes, freep);
217STATIC_DESTRUCTOR_REGISTER(arg_exclude_prefixes, freep);
218STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
63d3d0a5 219STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
87938c3b 220
a9bc518c
LP
221static const char *const creation_mode_verb_table[_CREATION_MODE_MAX] = {
222 [CREATION_NORMAL] = "Created",
223 [CREATION_EXISTING] = "Found existing",
224 [CREATION_FORCE] = "Created replacement",
225};
226
227DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(creation_mode_verb, CreationMode);
228
6db98098
ZJS
229/* Different kinds of errors that mean that information is not available in the environment. */
230static inline bool ERRNO_IS_NOINFO(int r) {
231 return IN_SET(abs(r),
232 EUNATCH, /* os-release or machine-id missing */
233 ENOMEDIUM, /* machine-id or another file empty */
234 ENXIO); /* env var is unset */
4cef1923
FB
235}
236
de61a04b 237static int specifier_directory(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
5a8575ef
ZJS
238 struct table_entry {
239 uint64_t type;
240 const char *suffix;
241 };
242
243 static const struct table_entry paths_system[] = {
244 [DIRECTORY_RUNTIME] = { SD_PATH_SYSTEM_RUNTIME },
245 [DIRECTORY_STATE] = { SD_PATH_SYSTEM_STATE_PRIVATE },
246 [DIRECTORY_CACHE] = { SD_PATH_SYSTEM_STATE_CACHE },
247 [DIRECTORY_LOGS] = { SD_PATH_SYSTEM_STATE_LOGS },
248 };
249
250 static const struct table_entry paths_user[] = {
251 [DIRECTORY_RUNTIME] = { SD_PATH_USER_RUNTIME },
252 [DIRECTORY_STATE] = { SD_PATH_USER_CONFIGURATION },
253 [DIRECTORY_CACHE] = { SD_PATH_USER_STATE_CACHE },
254 [DIRECTORY_LOGS] = { SD_PATH_USER_CONFIGURATION, "log" },
255 };
256
5a8575ef 257 const struct table_entry *paths;
de61a04b
LP
258 _cleanup_free_ char *p = NULL;
259 unsigned i;
260 int r;
5a8575ef
ZJS
261
262 assert_cc(ELEMENTSOF(paths_system) == ELEMENTSOF(paths_user));
263 paths = arg_user ? paths_user : paths_system;
264
265 i = PTR_TO_UINT(data);
266 assert(i < ELEMENTSOF(paths_system));
267
de61a04b
LP
268 r = sd_path_lookup(paths[i].type, paths[i].suffix, &p);
269 if (r < 0)
270 return r;
271
272 if (arg_root) {
273 _cleanup_free_ char *j = NULL;
274
275 j = path_join(arg_root, p);
276 if (!j)
277 return -ENOMEM;
278
279 *ret = TAKE_PTR(j);
280 } else
281 *ret = TAKE_PTR(p);
282
283 return 0;
5a8575ef
ZJS
284}
285
4cef1923
FB
286static int log_unresolvable_specifier(const char *filename, unsigned line) {
287 static bool notified = false;
288
1401882f
ZJS
289 /* In system mode, this is called when /etc is not fully initialized and some specifiers are
290 * unresolvable. In user mode, this is called when some variables are not defined. These cases are
291 * not considered a fatal error, so log at LOG_NOTICE only for the first time and then downgrade this
292 * to LOG_DEBUG for the rest.
293 *
294 * If we're running in a chroot (--root was used or sd_booted() reports that systemd is not running),
295 * always use LOG_DEBUG. We may be called to initialize a chroot before booting and there is no
296 * expectation that machine-id and other files will be populated.
297 */
298
299 int log_level = notified || arg_root || running_in_chroot() > 0 ?
300 LOG_DEBUG : LOG_NOTICE;
4cef1923 301
d02933fd 302 log_syntax(NULL,
1401882f 303 log_level,
d02933fd 304 filename, line, 0,
1401882f 305 "Failed to resolve specifier: %s, skipping.",
c5be1ceb 306 arg_user ? "Required $XDG_... variable not defined" : "uninitialized /etc/ detected");
4cef1923
FB
307
308 if (!notified)
1401882f
ZJS
309 log_full(log_level,
310 "All rules containing unresolvable specifiers will be skipped.");
4cef1923
FB
311
312 notified = true;
313 return 0;
314}
315
f2b5ca0e
ZJS
316static int user_config_paths(char*** ret) {
317 _cleanup_strv_free_ char **config_dirs = NULL, **data_dirs = NULL;
318 _cleanup_free_ char *persistent_config = NULL, *runtime_config = NULL, *data_home = NULL;
319 _cleanup_strv_free_ char **res = NULL;
320 int r;
321
322 r = xdg_user_dirs(&config_dirs, &data_dirs);
323 if (r < 0)
324 return r;
325
326 r = xdg_user_config_dir(&persistent_config, "/user-tmpfiles.d");
6db98098 327 if (r < 0 && !ERRNO_IS_NOINFO(r))
f2b5ca0e
ZJS
328 return r;
329
330 r = xdg_user_runtime_dir(&runtime_config, "/user-tmpfiles.d");
6db98098 331 if (r < 0 && !ERRNO_IS_NOINFO(r))
f2b5ca0e
ZJS
332 return r;
333
334 r = xdg_user_data_dir(&data_home, "/user-tmpfiles.d");
6db98098 335 if (r < 0 && !ERRNO_IS_NOINFO(r))
f2b5ca0e
ZJS
336 return r;
337
338 r = strv_extend_strv_concat(&res, config_dirs, "/user-tmpfiles.d");
339 if (r < 0)
340 return r;
341
342 r = strv_extend(&res, persistent_config);
343 if (r < 0)
344 return r;
345
346 r = strv_extend(&res, runtime_config);
347 if (r < 0)
348 return r;
349
350 r = strv_extend(&res, data_home);
351 if (r < 0)
352 return r;
353
354 r = strv_extend_strv_concat(&res, data_dirs, "/user-tmpfiles.d");
355 if (r < 0)
356 return r;
357
358 r = path_strv_make_absolute_cwd(res);
359 if (r < 0)
360 return r;
361
ae2a15bc 362 *ret = TAKE_PTR(res);
f2b5ca0e
ZJS
363 return 0;
364}
365
66ccd038 366static bool needs_glob(ItemType t) {
cde684a2
LP
367 return IN_SET(t,
368 WRITE_FILE,
369 IGNORE_PATH,
370 IGNORE_DIRECTORY_PATH,
371 REMOVE_PATH,
372 RECURSIVE_REMOVE_PATH,
df8dee85 373 EMPTY_DIRECTORY,
e73a03e0 374 ADJUST_MODE,
cde684a2 375 RELABEL_PATH,
b705ab6a
ZJS
376 RECURSIVE_RELABEL_PATH,
377 SET_XATTR,
378 RECURSIVE_SET_XATTR,
379 SET_ACL,
34f64536
LP
380 RECURSIVE_SET_ACL,
381 SET_ATTRIBUTE,
382 RECURSIVE_SET_ATTRIBUTE);
b8bb3e8f
LP
383}
384
3f93da98
ZJS
385static bool takes_ownership(ItemType t) {
386 return IN_SET(t,
387 CREATE_FILE,
388 TRUNCATE_FILE,
389 CREATE_DIRECTORY,
df8dee85 390 EMPTY_DIRECTORY,
3f93da98
ZJS
391 TRUNCATE_DIRECTORY,
392 CREATE_SUBVOLUME,
5fb13eb5
LP
393 CREATE_SUBVOLUME_INHERIT_QUOTA,
394 CREATE_SUBVOLUME_NEW_QUOTA,
3f93da98
ZJS
395 CREATE_FIFO,
396 CREATE_SYMLINK,
397 CREATE_CHAR_DEVICE,
398 CREATE_BLOCK_DEVICE,
399 COPY_FILES,
3f93da98
ZJS
400 WRITE_FILE,
401 IGNORE_PATH,
402 IGNORE_DIRECTORY_PATH,
403 REMOVE_PATH,
404 RECURSIVE_REMOVE_PATH);
405}
406
ef43a391 407static struct Item* find_glob(OrderedHashmap *h, const char *match) {
3f93da98 408 ItemArray *j;
b8bb3e8f 409
90e74a66 410 ORDERED_HASHMAP_FOREACH(j, h) {
96d10d78 411 size_t n;
3f93da98 412
96d10d78 413 for (n = 0; n < j->n_items; n++) {
3f93da98
ZJS
414 Item *item = j->items + n;
415
416 if (fnmatch(item->path, match, FNM_PATHNAME|FNM_PERIOD) == 0)
417 return item;
418 }
419 }
b8bb3e8f
LP
420
421 return NULL;
422}
423
71a0be76 424static int load_unix_sockets(void) {
fe2f05b7 425 _cleanup_set_free_ Set *sockets = NULL;
7fd1b19b 426 _cleanup_fclose_ FILE *f = NULL;
f1ff734f 427 int r;
17b90525
LP
428
429 if (unix_sockets)
71a0be76 430 return 0;
17b90525 431
f1ff734f 432 /* We maintain a cache of the sockets we found in /proc/net/unix to speed things up a little. */
17b90525 433
fdcad0c2 434 f = fopen("/proc/net/unix", "re");
71a0be76
YW
435 if (!f)
436 return log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
437 "Failed to open /proc/net/unix, ignoring: %m");
17b90525 438
fdcad0c2 439 /* Skip header */
f1ff734f 440 r = read_line(f, LONG_LINE_MAX, NULL);
71a0be76
YW
441 if (r < 0)
442 return log_warning_errno(r, "Failed to skip /proc/net/unix header line: %m");
443 if (r == 0)
444 return log_warning_errno(SYNTHETIC_ERRNO(EIO), "Premature end of file reading /proc/net/unix.");
17b90525
LP
445
446 for (;;) {
fe2f05b7 447 _cleanup_free_ char *line = NULL;
71a0be76 448 char *p;
17b90525 449
f1ff734f 450 r = read_line(f, LONG_LINE_MAX, &line);
71a0be76
YW
451 if (r < 0)
452 return log_warning_errno(r, "Failed to read /proc/net/unix line, ignoring: %m");
f1ff734f 453 if (r == 0) /* EOF */
17b90525
LP
454 break;
455
fdcad0c2
LP
456 p = strchr(line, ':');
457 if (!p)
458 continue;
459
460 if (strlen(p) < 37)
17b90525
LP
461 continue;
462
fdcad0c2 463 p += 37;
17b90525 464 p += strspn(p, WHITESPACE);
fdcad0c2 465 p += strcspn(p, WHITESPACE); /* skip one more word */
17b90525
LP
466 p += strspn(p, WHITESPACE);
467
fe2f05b7 468 if (!path_is_absolute(p))
17b90525
LP
469 continue;
470
fe2f05b7 471 r = set_put_strdup_full(&sockets, &path_hash_ops_free, p);
71a0be76
YW
472 if (r < 0)
473 return log_warning_errno(r, "Failed to add AF_UNIX socket to set, ignoring: %m");
71a0be76 474 }
17b90525 475
71a0be76
YW
476 unix_sockets = TAKE_PTR(sockets);
477 return 1;
17b90525
LP
478}
479
480static bool unix_socket_alive(const char *fn) {
481 assert(fn);
482
71a0be76
YW
483 if (load_unix_sockets() < 0)
484 return true; /* We don't know, so assume yes */
17b90525 485
fe2f05b7 486 return set_contains(unix_sockets, fn);
17b90525
LP
487}
488
708daf42
LP
489/* Accessors for the argument in binary format */
490static const void* item_binary_argument(const Item *i) {
491 assert(i);
492 return i->binary_argument ?: i->argument;
493}
494
495static size_t item_binary_argument_size(const Item *i) {
496 assert(i);
497 return i->binary_argument ? i->binary_argument_size : strlen_ptr(i->argument);
498}
499
df99a9ef
ZJS
500static DIR* xopendirat_nomod(int dirfd, const char *path) {
501 DIR *dir;
502
503 dir = xopendirat(dirfd, path, O_NOFOLLOW|O_NOATIME);
1532227a
LP
504 if (dir)
505 return dir;
506
507 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
508 if (errno != EPERM)
509 return NULL;
510
511 dir = xopendirat(dirfd, path, O_NOFOLLOW);
512 if (!dir)
513 log_debug_errno(errno, "Cannot open %sdirectory \"%s\": %m", dirfd == AT_FDCWD ? "" : "sub", path);
df99a9ef
ZJS
514
515 return dir;
516}
517
518static DIR* opendir_nomod(const char *path) {
519 return xopendirat_nomod(AT_FDCWD, path);
520}
521
ddb439b8
LP
522static inline nsec_t load_statx_timestamp_nsec(const struct statx_timestamp *ts) {
523 assert(ts);
524
525 if (ts->tv_sec < 0)
526 return NSEC_INFINITY;
527
528 if ((nsec_t) ts->tv_sec >= (UINT64_MAX - ts->tv_nsec) / NSEC_PER_SEC)
529 return NSEC_INFINITY;
530
531 return ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec;
532}
533
7f7a50dd
SK
534static bool needs_cleanup(
535 nsec_t atime,
536 nsec_t btime,
537 nsec_t ctime,
538 nsec_t mtime,
539 nsec_t cutoff,
540 const char *sub_path,
541 AgeBy age_by,
542 bool is_dir) {
543
544 if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
7f7a50dd
SK
545 /* Follows spelling in stat(1). */
546 log_debug("%s \"%s\": modify time %s is too new.",
547 is_dir ? "Directory" : "File",
548 sub_path,
0086ef19 549 FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
7f7a50dd
SK
550
551 return false;
552 }
553
554 if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
7f7a50dd
SK
555 log_debug("%s \"%s\": access time %s is too new.",
556 is_dir ? "Directory" : "File",
557 sub_path,
0086ef19 558 FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
7f7a50dd
SK
559
560 return false;
561 }
562
563 /*
564 * Note: Unless explicitly specified by the user, "ctime" is ignored
565 * by default for directories, because we change it when deleting.
566 */
567 if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
7f7a50dd
SK
568 log_debug("%s \"%s\": change time %s is too new.",
569 is_dir ? "Directory" : "File",
570 sub_path,
0086ef19 571 FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
7f7a50dd
SK
572
573 return false;
574 }
575
576 if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
7f7a50dd
SK
577 log_debug("%s \"%s\": birth time %s is too new.",
578 is_dir ? "Directory" : "File",
579 sub_path,
0086ef19 580 FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
7f7a50dd
SK
581
582 return false;
583 }
584
585 return true;
586}
587
3b63d2d3 588static int dir_cleanup(
78a92a5a 589 Item *i,
3b63d2d3
LP
590 const char *p,
591 DIR *d,
ddb439b8
LP
592 nsec_t self_atime_nsec,
593 nsec_t self_mtime_nsec,
594 nsec_t cutoff_nsec,
595 dev_t rootdev_major,
596 dev_t rootdev_minor,
3b63d2d3 597 bool mountpoint,
24f3a374 598 int maxdepth,
7f7a50dd
SK
599 bool keep_this_level,
600 AgeBy age_by_file,
601 AgeBy age_by_dir) {
265ffa1e 602
3b63d2d3 603 bool deleted = false;
3b63d2d3
LP
604 int r = 0;
605
c7f0d9e5 606 FOREACH_DIRENT_ALL(de, d, break) {
7fd1b19b 607 _cleanup_free_ char *sub_path = NULL;
ddb439b8 608 nsec_t atime_nsec, mtime_nsec, ctime_nsec, btime_nsec;
3b63d2d3 609
c7f0d9e5 610 if (dot_or_dot_dot(de->d_name))
3b63d2d3 611 continue;
5008d581 612
ca194a2a 613 /* If statx() is supported, use it. It's preferable over fstatat() since it tells us
69e3234d 614 * explicitly where we are looking at a mount point, for free as side information. Determining
ca194a2a
LP
615 * the same information without statx() is hard, see the complexity of path_is_mount_point(),
616 * and also much slower as it requires a number of syscalls instead of just one. Hence, when
617 * we have modern statx() we use it instead of fstat() and do proper mount point checks,
618 * while on older kernels's well do traditional st_dev based detection of mount points.
619 *
620 * Using statx() for detecting mount points also has the benfit that we handle weird file
621 * systems such as overlayfs better where each file is originating from a different
622 * st_dev. */
623
624 STRUCT_STATX_DEFINE(sx);
625
626 r = statx_fallback(
c7f0d9e5 627 dirfd(d), de->d_name,
ca194a2a
LP
628 AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT,
629 STATX_TYPE|STATX_MODE|STATX_UID|STATX_ATIME|STATX_MTIME|STATX_CTIME|STATX_BTIME,
630 &sx);
631 if (r == -ENOENT)
632 continue;
633 if (r < 0) {
634 /* FUSE, NFS mounts, SELinux might return EACCES */
149e0ca6 635 r = log_full_errno(r == -EACCES ? LOG_DEBUG : LOG_ERR, r,
c7f0d9e5 636 "statx(%s/%s) failed: %m", p, de->d_name);
ca194a2a 637 continue;
3b63d2d3
LP
638 }
639
ca194a2a
LP
640 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT)) {
641 /* Yay, we have the mount point API, use it */
642 if (FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT)) {
c7f0d9e5 643 log_debug("Ignoring \"%s/%s\": different mount points.", p, de->d_name);
ddb439b8
LP
644 continue;
645 }
ca194a2a
LP
646 } else {
647 /* So we might have statx() but the STATX_ATTR_MOUNT_ROOT flag is not supported, fall
648 * back to traditional stx_dev checking. */
649 if (sx.stx_dev_major != rootdev_major ||
650 sx.stx_dev_minor != rootdev_minor) {
c7f0d9e5 651 log_debug("Ignoring \"%s/%s\": different filesystem.", p, de->d_name);
ddb439b8
LP
652 continue;
653 }
654
ca194a2a
LP
655 /* Try to detect bind mounts of the same filesystem instance; they do not differ in device
656 * major/minors. This type of query is not supported on all kernels or filesystem types
657 * though. */
658 if (S_ISDIR(sx.stx_mode)) {
659 int q;
3b63d2d3 660
c7f0d9e5 661 q = fd_is_mount_point(dirfd(d), de->d_name, 0);
ca194a2a 662 if (q < 0)
c7f0d9e5 663 log_debug_errno(q, "Failed to determine whether \"%s/%s\" is a mount point, ignoring: %m", p, de->d_name);
ca194a2a 664 else if (q > 0) {
c7f0d9e5 665 log_debug("Ignoring \"%s/%s\": different mount of the same filesystem.", p, de->d_name);
ca194a2a
LP
666 continue;
667 }
60bdc0ca 668 }
582deb84 669 }
99d680ac 670
ca194a2a
LP
671 atime_nsec = FLAGS_SET(sx.stx_mask, STATX_ATIME) ? load_statx_timestamp_nsec(&sx.stx_atime) : 0;
672 mtime_nsec = FLAGS_SET(sx.stx_mask, STATX_MTIME) ? load_statx_timestamp_nsec(&sx.stx_mtime) : 0;
673 ctime_nsec = FLAGS_SET(sx.stx_mask, STATX_CTIME) ? load_statx_timestamp_nsec(&sx.stx_ctime) : 0;
674 btime_nsec = FLAGS_SET(sx.stx_mask, STATX_BTIME) ? load_statx_timestamp_nsec(&sx.stx_btime) : 0;
675
c7f0d9e5 676 sub_path = path_join(p, de->d_name);
cde684a2 677 if (!sub_path) {
0d0f0c50 678 r = log_oom();
3b63d2d3
LP
679 goto finish;
680 }
681
682 /* Is there an item configured for this path? */
ef43a391 683 if (ordered_hashmap_get(items, sub_path)) {
582deb84 684 log_debug("Ignoring \"%s\": a separate entry exists.", sub_path);
3b63d2d3 685 continue;
582deb84 686 }
3b63d2d3 687
582deb84
ZJS
688 if (find_glob(globs, sub_path)) {
689 log_debug("Ignoring \"%s\": a separate glob exists.", sub_path);
b8bb3e8f 690 continue;
582deb84 691 }
b8bb3e8f 692
ca194a2a 693 if (S_ISDIR(sx.stx_mode)) {
52b32b2a 694 _cleanup_closedir_ DIR *sub_dir = NULL;
3b63d2d3
LP
695
696 if (mountpoint &&
c7f0d9e5 697 streq(de->d_name, "lost+found") &&
ca194a2a 698 sx.stx_uid == 0) {
781bc44e 699 log_debug("Ignoring directory \"%s\".", sub_path);
3b63d2d3 700 continue;
582deb84 701 }
3b63d2d3
LP
702
703 if (maxdepth <= 0)
582deb84 704 log_warning("Reached max depth on \"%s\".", sub_path);
3b63d2d3 705 else {
3b63d2d3
LP
706 int q;
707
c7f0d9e5 708 sub_dir = xopendirat_nomod(dirfd(d), de->d_name);
cde684a2 709 if (!sub_dir) {
582deb84 710 if (errno != ENOENT)
781bc44e 711 r = log_warning_errno(errno, "Opening directory \"%s\" failed, ignoring: %m", sub_path);
3b63d2d3
LP
712
713 continue;
714 }
715
52b32b2a
LP
716 if (flock(dirfd(sub_dir), LOCK_EX|LOCK_NB) < 0) {
717 log_debug_errno(errno, "Couldn't acquire shared BSD lock on directory \"%s\", skipping: %m", p);
718 continue;
719 }
720
ddb439b8
LP
721 q = dir_cleanup(i,
722 sub_path, sub_dir,
723 atime_nsec, mtime_nsec, cutoff_nsec,
724 rootdev_major, rootdev_minor,
7f7a50dd
SK
725 false, maxdepth-1, false,
726 age_by_file, age_by_dir);
3b63d2d3
LP
727 if (q < 0)
728 r = q;
729 }
730
a23fabc6
LP
731 /* Note: if you are wondering why we don't support the sticky bit for excluding
732 * directories from cleaning like we do it for other file system objects: well, the
733 * sticky bit already has a meaning for directories, so we don't want to overload
734 * that. */
24f3a374 735
582deb84 736 if (keep_this_level) {
781bc44e 737 log_debug("Keeping directory \"%s\".", sub_path);
24f3a374 738 continue;
582deb84 739 }
24f3a374 740
7f7a50dd
SK
741 /*
742 * Check the file timestamps of an entry against the
743 * given cutoff time; delete if it is older.
744 */
745 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
746 cutoff_nsec, sub_path, age_by_dir, true))
3b63d2d3
LP
747 continue;
748
61253220 749 log_debug("Removing directory \"%s\".", sub_path);
c7f0d9e5 750 if (unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0)
920ce828 751 if (!IN_SET(errno, ENOENT, ENOTEMPTY))
781bc44e 752 r = log_warning_errno(errno, "Failed to remove directory \"%s\", ignoring: %m", sub_path);
3b63d2d3
LP
753
754 } else {
a23fabc6
LP
755 /* Skip files for which the sticky bit is set. These are semantics we define, and are
756 * unknown elsewhere. See XDG_RUNTIME_DIR specification for details. */
ca194a2a 757 if (sx.stx_mode & S_ISVTX) {
582deb84 758 log_debug("Skipping \"%s\": sticky bit set.", sub_path);
9c73736d 759 continue;
582deb84 760 }
9c73736d 761
20b6bb95 762 if (mountpoint &&
ca194a2a
LP
763 S_ISREG(sx.stx_mode) &&
764 sx.stx_uid == 0 &&
c7f0d9e5 765 STR_IN_SET(de->d_name,
20b6bb95
LP
766 ".journal",
767 "aquota.user",
768 "aquota.group")) {
769 log_debug("Skipping \"%s\".", sub_path);
770 continue;
771 }
3b63d2d3 772
17b90525 773 /* Ignore sockets that are listed in /proc/net/unix */
ca194a2a 774 if (S_ISSOCK(sx.stx_mode) && unix_socket_alive(sub_path)) {
582deb84 775 log_debug("Skipping \"%s\": live socket.", sub_path);
17b90525 776 continue;
582deb84 777 }
17b90525 778
78ab08eb 779 /* Ignore device nodes */
ca194a2a 780 if (S_ISCHR(sx.stx_mode) || S_ISBLK(sx.stx_mode)) {
582deb84 781 log_debug("Skipping \"%s\": a device.", sub_path);
78ab08eb 782 continue;
582deb84 783 }
78ab08eb 784
a23fabc6 785 /* Keep files on this level around if this is requested */
582deb84
ZJS
786 if (keep_this_level) {
787 log_debug("Keeping \"%s\".", sub_path);
24f3a374 788 continue;
582deb84 789 }
24f3a374 790
7f7a50dd
SK
791 if (!needs_cleanup(atime_nsec, btime_nsec, ctime_nsec, mtime_nsec,
792 cutoff_nsec, sub_path, age_by_file, false))
3b63d2d3 793 continue;
3b63d2d3 794
781bc44e 795 log_debug("Removing \"%s\".", sub_path);
c7f0d9e5 796 if (unlinkat(dirfd(d), de->d_name, 0) < 0)
582deb84 797 if (errno != ENOENT)
781bc44e 798 r = log_warning_errno(errno, "Failed to remove \"%s\", ignoring: %m", sub_path);
582deb84 799
3b63d2d3
LP
800 deleted = true;
801 }
802 }
803
804finish:
805 if (deleted) {
ddb439b8 806 struct timespec ts[2];
76e15a9c 807
582deb84
ZJS
808 log_debug("Restoring access and modification time on \"%s\": %s, %s",
809 p,
0086ef19
ZJS
810 FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
811 FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
ddb439b8
LP
812
813 timespec_store_nsec(ts + 0, self_atime_nsec);
814 timespec_store_nsec(ts + 1, self_mtime_nsec);
76e15a9c
LP
815
816 /* Restore original directory timestamps */
ddb439b8 817 if (futimens(dirfd(d), ts) < 0)
76e15a9c 818 log_warning_errno(errno, "Failed to revert timestamps of '%s', ignoring: %m", p);
3b63d2d3
LP
819 }
820
3b63d2d3
LP
821 return r;
822}
823
5579f856
LP
824static bool dangerous_hardlinks(void) {
825 _cleanup_free_ char *value = NULL;
826 static int cached = -1;
827 int r;
828
829 /* Check whether the fs.protected_hardlinks sysctl is on. If we can't determine it we assume its off, as that's
830 * what the upstream default is. */
831
832 if (cached >= 0)
833 return cached;
834
835 r = read_one_line_file("/proc/sys/fs/protected_hardlinks", &value);
836 if (r < 0) {
837 log_debug_errno(r, "Failed to read fs.protected_hardlinks sysctl: %m");
838 return true;
839 }
840
841 r = parse_boolean(value);
842 if (r < 0) {
843 log_debug_errno(r, "Failed to parse fs.protected_hardlinks sysctl: %m");
844 return true;
845 }
846
847 cached = r == 0;
848 return cached;
849}
850
774f79b5 851static bool hardlink_vulnerable(const struct stat *st) {
5579f856
LP
852 assert(st);
853
854 return !S_ISDIR(st->st_mode) && st->st_nlink > 1 && dangerous_hardlinks();
855}
856
8b364a38
LP
857static mode_t process_mask_perms(mode_t mode, mode_t current) {
858
859 if ((current & 0111) == 0)
860 mode &= ~0111;
861 if ((current & 0222) == 0)
862 mode &= ~0222;
863 if ((current & 0444) == 0)
864 mode &= ~0444;
865 if (!S_ISDIR(current))
866 mode &= ~07000; /* remove sticky/sgid/suid bit, unless directory */
867
868 return mode;
869}
870
a9bc518c
LP
871static int fd_set_perms(
872 Item *i,
873 int fd,
874 const char *path,
875 const struct stat *st,
876 CreationMode creation) {
877
cc43328c 878 bool do_chown, do_chmod;
b206ac8e 879 struct stat stbuf;
a9f55d0e 880 mode_t new_mode;
cc43328c
LP
881 uid_t new_uid;
882 gid_t new_gid;
dee00c19 883 int r;
1924a97d 884
cde684a2 885 assert(i);
b4b0f87c 886 assert(fd >= 0);
4dc7bfdf 887 assert(path);
48b8aaa8 888
936f6bdb
FB
889 if (!i->mode_set && !i->uid_set && !i->gid_set)
890 goto shortcut;
1924a97d 891
b206ac8e
FB
892 if (!st) {
893 if (fstat(fd, &stbuf) < 0)
894 return log_error_errno(errno, "fstat(%s) failed: %m", path);
895 st = &stbuf;
896 }
897
baaa35ad
ZJS
898 if (hardlink_vulnerable(st))
899 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
900 "Refusing to set permissions on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
901 path);
cc43328c
LP
902 new_uid = i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create) ? i->uid : st->st_uid;
903 new_gid = i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create) ? i->gid : st->st_gid;
5579f856 904
a9f55d0e 905 /* Do we need a chown()? */
cc43328c 906 do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid);
8b364a38 907
a9f55d0e 908 /* Calculate the mode to apply */
cc43328c
LP
909 new_mode = i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create) ?
910 (i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode) :
911 (st->st_mode & 07777);
a9f55d0e 912
cc43328c
LP
913 do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0;
914
915 if (do_chmod && do_chown) {
a9f55d0e
LP
916 /* Before we issue the chmod() let's reduce the access mode to the common bits of the old and
917 * the new mode. That way there's no time window where the file exists under the old owner
918 * with more than the old access modes — and not under the new owner with more than the new
919 * access modes either. */
8b364a38 920
936f6bdb 921 if (S_ISLNK(st->st_mode))
a9f55d0e 922 log_debug("Skipping temporary mode fix for symlink %s.", path);
51207ca1 923 else {
a9f55d0e 924 mode_t m = new_mode & st->st_mode; /* Mask new mode by old mode */
abef3f91 925
a9f55d0e
LP
926 if (((m ^ st->st_mode) & 07777) == 0)
927 log_debug("\"%s\" matches temporary mode %o already.", path, m);
48b8aaa8 928 else {
a9f55d0e 929 log_debug("Temporarily changing \"%s\" to mode %o.", path, m);
dee00c19
LP
930 r = fchmod_opath(fd, m);
931 if (r < 0)
932 return log_error_errno(r, "fchmod() of %s failed: %m", path);
48b8aaa8 933 }
062e01bb 934 }
51207ca1 935 }
062e01bb 936
a9f55d0e 937 if (do_chown) {
cc43328c
LP
938 log_debug("Changing \"%s\" to owner "UID_FMT":"GID_FMT, path, new_uid, new_gid);
939
940 if (fchownat(fd, "",
941 new_uid != st->st_uid ? new_uid : UID_INVALID,
942 new_gid != st->st_gid ? new_gid : GID_INVALID,
936f6bdb
FB
943 AT_EMPTY_PATH) < 0)
944 return log_error_errno(errno, "fchownat() of %s failed: %m", path);
582deb84 945 }
062e01bb 946
a9f55d0e
LP
947 /* Now, apply the final mode. We do this in two cases: when the user set a mode explicitly, or after a
948 * chown(), since chown()'s mangle the access mode in regards to sgid/suid in some conditions. */
cc43328c 949 if (do_chmod || do_chown) {
a9f55d0e
LP
950 if (S_ISLNK(st->st_mode))
951 log_debug("Skipping mode fix for symlink %s.", path);
952 else {
cc43328c
LP
953 log_debug("Changing \"%s\" to mode %o.", path, new_mode);
954 r = fchmod_opath(fd, new_mode);
955 if (r < 0)
956 return log_error_errno(r, "fchmod() of %s failed: %m", path);
a9f55d0e
LP
957 }
958 }
959
59793c8f 960shortcut:
03bc11d1 961 return label_fix_full(fd, /* inode_path= */ NULL, /* label_path= */ path, 0);
062e01bb
MS
962}
963
5ec9d065
FB
964static int path_open_parent_safe(const char *path) {
965 _cleanup_free_ char *dn = NULL;
a5648b80 966 int r, fd;
5ec9d065 967
4609d3bb
LP
968 if (!path_is_normalized(path))
969 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open parent of '%s': path not normalized.", path);
5ec9d065 970
4609d3bb
LP
971 r = path_extract_directory(path, &dn);
972 if (r < 0)
973 return log_error_errno(r, "Unable to determine parent directory of '%s': %m", path);
5ec9d065 974
a5648b80 975 r = chase_symlinks(dn, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
4609d3bb
LP
976 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
977 return r;
978 if (r < 0)
979 return log_error_errno(r, "Failed to open path '%s': %m", dn);
5ec9d065 980
4609d3bb 981 return fd;
5ec9d065
FB
982}
983
addc3e30 984static int path_open_safe(const char *path) {
a5648b80 985 int r, fd;
addc3e30
FB
986
987 /* path_open_safe() returns a file descriptor opened with O_PATH after
988 * verifying that the path doesn't contain unsafe transitions, except
989 * for its final component as the function does not follow symlink. */
990
991 assert(path);
992
baaa35ad 993 if (!path_is_normalized(path))
4609d3bb 994 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to open invalid path '%s'.", path);
addc3e30 995
a5648b80 996 r = chase_symlinks(path, arg_root, CHASE_SAFE|CHASE_WARN|CHASE_NOFOLLOW, NULL, &fd);
4609d3bb
LP
997 if (r == -ENOLINK)
998 return r; /* Unsafe symlink: already covered by CHASE_WARN */
999 if (r < 0)
1000 return log_error_errno(r, "Failed to open path %s: %m", path);
addc3e30 1001
4609d3bb 1002 return fd;
addc3e30
FB
1003}
1004
a9bc518c
LP
1005static int path_set_perms(
1006 Item *i,
1007 const char *path,
1008 CreationMode creation) {
1009
936f6bdb 1010 _cleanup_close_ int fd = -1;
936f6bdb
FB
1011
1012 assert(i);
1013 assert(path);
1014
addc3e30 1015 fd = path_open_safe(path);
54946021 1016 if (fd < 0)
addc3e30 1017 return fd;
d460ba18 1018
a9bc518c 1019 return fd_set_perms(i, fd, path, /* st= */ NULL, creation);
936f6bdb
FB
1020}
1021
bd550f78 1022static int parse_xattrs_from_arg(Item *i) {
ebf4e801
MW
1023 const char *p;
1024 int r;
1025
1026 assert(i);
ebf4e801 1027
3a632fc1 1028 assert_se(p = i->argument);
4034a06d 1029 for (;;) {
4cef1923 1030 _cleanup_free_ char *name = NULL, *value = NULL, *xattr = NULL;
4034a06d 1031
4ec85141 1032 r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE);
4034a06d 1033 if (r < 0)
bd550f78 1034 log_warning_errno(r, "Failed to parse extended attribute '%s', ignoring: %m", p);
4034a06d
LP
1035 if (r <= 0)
1036 break;
505ef0e3 1037
4cef1923 1038 r = split_pair(xattr, "=", &name, &value);
ebf4e801 1039 if (r < 0) {
4034a06d 1040 log_warning_errno(r, "Failed to parse extended attribute, ignoring: %s", xattr);
ebf4e801
MW
1041 continue;
1042 }
505ef0e3 1043
4034a06d 1044 if (isempty(name) || isempty(value)) {
bd550f78 1045 log_warning("Malformed extended attribute found, ignoring: %s", xattr);
ebf4e801
MW
1046 continue;
1047 }
505ef0e3 1048
4034a06d 1049 if (strv_push_pair(&i->xattrs, name, value) < 0)
ebf4e801 1050 return log_oom();
505ef0e3 1051
4034a06d 1052 name = value = NULL;
ebf4e801
MW
1053 }
1054
4034a06d 1055 return 0;
ebf4e801
MW
1056}
1057
a9bc518c
LP
1058static int fd_set_xattrs(
1059 Item *i,
1060 int fd,
1061 const char *path,
1062 const struct stat *st,
1063 CreationMode creation) {
1064
ebf4e801 1065 assert(i);
b4b0f87c 1066 assert(fd >= 0);
4dc7bfdf 1067 assert(path);
936f6bdb 1068
ebf4e801 1069 STRV_FOREACH_PAIR(name, value, i->xattrs) {
bd550f78 1070 log_debug("Setting extended attribute '%s=%s' on %s.", *name, *value, path);
ddb6eeaf 1071 if (setxattr(FORMAT_PROC_FD_PATH(fd), *name, *value, strlen(*value), 0) < 0)
25f027c5
ZJS
1072 return log_error_errno(errno, "Setting extended attribute %s=%s on %s failed: %m",
1073 *name, *value, path);
ebf4e801
MW
1074 }
1075 return 0;
1076}
1077
a9bc518c
LP
1078static int path_set_xattrs(
1079 Item *i,
1080 const char *path,
1081 CreationMode creation) {
1082
936f6bdb
FB
1083 _cleanup_close_ int fd = -1;
1084
1085 assert(i);
1086 assert(path);
1087
addc3e30 1088 fd = path_open_safe(path);
936f6bdb 1089 if (fd < 0)
addc3e30 1090 return fd;
936f6bdb 1091
a9bc518c 1092 return fd_set_xattrs(i, fd, path, /* st = */ NULL, creation);
936f6bdb
FB
1093}
1094
bd550f78 1095static int parse_acls_from_arg(Item *item) {
349cc4a5 1096#if HAVE_ACL
f8eeeaf9 1097 int r;
f8eeeaf9
ZJS
1098
1099 assert(item);
1100
c55ac248 1101 /* If append_or_force (= modify) is set, we will not modify the acl
50d9e46d 1102 * afterwards, so the mask can be added now if necessary. */
bd550f78 1103
c55ac248 1104 r = parse_acl(item->argument, &item->acl_access, &item->acl_default, !item->append_or_force);
f8eeeaf9 1105 if (r < 0)
4034a06d 1106 log_warning_errno(r, "Failed to parse ACL \"%s\": %m. Ignoring", item->argument);
f8eeeaf9 1107#else
6008336f 1108 log_warning("ACLs are not supported. Ignoring.");
f8eeeaf9
ZJS
1109#endif
1110
1111 return 0;
1112}
1113
349cc4a5 1114#if HAVE_ACL
a9bc518c
LP
1115static int path_set_acl(
1116 const char *path,
1117 const char *pretty,
1118 acl_type_t type,
1119 acl_t acl,
1120 bool modify) {
1121
48b8aaa8 1122 _cleanup_(acl_free_charpp) char *t = NULL;
dd4105b0 1123 _cleanup_(acl_freep) acl_t dup = NULL;
50d9e46d
ZJS
1124 int r;
1125
d873e877
HPD
1126 /* Returns 0 for success, positive error if already warned,
1127 * negative error otherwise. */
1128
50d9e46d 1129 if (modify) {
dd4105b0 1130 r = acls_for_file(path, type, acl, &dup);
50d9e46d
ZJS
1131 if (r < 0)
1132 return r;
50d9e46d 1133
dd4105b0
ZJS
1134 r = calc_acl_mask_if_needed(&dup);
1135 if (r < 0)
1136 return r;
1137 } else {
1138 dup = acl_dup(acl);
1139 if (!dup)
1140 return -errno;
1141
1142 /* the mask was already added earlier if needed */
1143 }
1144
1145 r = add_base_acls_if_needed(&dup, path);
1146 if (r < 0)
1147 return r;
1148
582deb84 1149 t = acl_to_any_text(dup, NULL, ',', TEXT_ABBREVIATE);
48b8aaa8 1150 log_debug("Setting %s ACL %s on %s.",
582deb84 1151 type == ACL_TYPE_ACCESS ? "access" : "default",
48b8aaa8 1152 strna(t), pretty);
50d9e46d 1153
582deb84 1154 r = acl_set_file(path, type, dup);
3045c416
PC
1155 if (r < 0) {
1156 if (ERRNO_IS_NOT_SUPPORTED(errno))
1157 /* No error if filesystem doesn't support ACLs. Return negative. */
1158 return -errno;
1159 else
1160 /* Return positive to indicate we already warned */
1161 return -log_error_errno(errno,
1162 "Setting %s ACL \"%s\" on %s failed: %m",
1163 type == ACL_TYPE_ACCESS ? "access" : "default",
1164 strna(t), pretty);
1165 }
582deb84 1166 return 0;
50d9e46d 1167}
35888b67 1168#endif
50d9e46d 1169
a9bc518c
LP
1170static int fd_set_acls(
1171 Item *item,
1172 int fd,
1173 const char *path,
1174 const struct stat *st,
1175 CreationMode creation) {
1176
d873e877 1177 int r = 0;
349cc4a5 1178#if HAVE_ACL
b206ac8e 1179 struct stat stbuf;
48b8aaa8 1180
f8eeeaf9 1181 assert(item);
b4b0f87c 1182 assert(fd >= 0);
4dc7bfdf 1183 assert(path);
48b8aaa8 1184
b206ac8e
FB
1185 if (!st) {
1186 if (fstat(fd, &stbuf) < 0)
1187 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1188 st = &stbuf;
1189 }
1190
baaa35ad
ZJS
1191 if (hardlink_vulnerable(st))
1192 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
1193 "Refusing to set ACLs on hardlinked file %s while the fs.protected_hardlinks sysctl is turned off.",
1194 path);
5579f856 1195
936f6bdb 1196 if (S_ISLNK(st->st_mode)) {
48b8aaa8
LP
1197 log_debug("Skipping ACL fix for symlink %s.", path);
1198 return 0;
1199 }
1200
d873e877 1201 if (item->acl_access)
ddb6eeaf 1202 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_ACCESS, item->acl_access, item->append_or_force);
f8eeeaf9 1203
2667385b
RM
1204 /* set only default acls to folders */
1205 if (r == 0 && item->acl_default && S_ISDIR(st->st_mode))
ddb6eeaf 1206 r = path_set_acl(FORMAT_PROC_FD_PATH(fd), path, ACL_TYPE_DEFAULT, item->acl_default, item->append_or_force);
f8eeeaf9 1207
3045c416
PC
1208 if (ERRNO_IS_NOT_SUPPORTED(r)) {
1209 log_debug_errno(r, "ACLs not supported by file system at %s", path);
1210 return 0;
1211 }
1212
d873e877
HPD
1213 if (r > 0)
1214 return -r; /* already warned */
f8606626
LP
1215
1216 /* The above procfs paths don't work if /proc is not mounted. */
1217 if (r == -ENOENT && proc_mounted() == 0)
1218 r = -ENOSYS;
1219
936f6bdb
FB
1220 if (r < 0)
1221 return log_error_errno(r, "ACL operation on \"%s\" failed: %m", path);
d873e877
HPD
1222#endif
1223 return r;
f8eeeaf9
ZJS
1224}
1225
a9bc518c 1226static int path_set_acls(Item *item, const char *path, CreationMode creation) {
936f6bdb 1227 int r = 0;
545cdb90 1228#if HAVE_ACL
936f6bdb 1229 _cleanup_close_ int fd = -1;
936f6bdb
FB
1230
1231 assert(item);
1232 assert(path);
1233
addc3e30 1234 fd = path_open_safe(path);
936f6bdb 1235 if (fd < 0)
addc3e30 1236 return fd;
936f6bdb 1237
a9bc518c 1238 r = fd_set_acls(item, fd, path, /* st= */ NULL, creation);
545cdb90
YW
1239#endif
1240 return r;
1241}
936f6bdb 1242
bd550f78 1243static int parse_attribute_from_arg(Item *item) {
88ec4dfa
LP
1244
1245 static const struct {
1246 char character;
1247 unsigned value;
1248 } attributes[] = {
1249 { 'A', FS_NOATIME_FL }, /* do not update atime */
1250 { 'S', FS_SYNC_FL }, /* Synchronous updates */
1251 { 'D', FS_DIRSYNC_FL }, /* dirsync behaviour (directories only) */
1252 { 'a', FS_APPEND_FL }, /* writes to file may only append */
1253 { 'c', FS_COMPR_FL }, /* Compress file */
1254 { 'd', FS_NODUMP_FL }, /* do not dump file */
8c35b2ca 1255 { 'e', FS_EXTENT_FL }, /* Extents */
88ec4dfa
LP
1256 { 'i', FS_IMMUTABLE_FL }, /* Immutable file */
1257 { 'j', FS_JOURNAL_DATA_FL }, /* Reserved for ext3 */
1258 { 's', FS_SECRM_FL }, /* Secure deletion */
1259 { 'u', FS_UNRM_FL }, /* Undelete */
1260 { 't', FS_NOTAIL_FL }, /* file tail should not be merged */
13e785f7 1261 { 'T', FS_TOPDIR_FL }, /* Top of directory hierarchies */
88ec4dfa 1262 { 'C', FS_NOCOW_FL }, /* Do not cow file */
75006470 1263 { 'P', FS_PROJINHERIT_FL }, /* Inherit the quota project ID */
22c3a6ca 1264 };
88ec4dfa 1265
22c3a6ca
GB
1266 enum {
1267 MODE_ADD,
1268 MODE_DEL,
1269 MODE_SET
1270 } mode = MODE_ADD;
22c3a6ca 1271
88ec4dfa
LP
1272 unsigned value = 0, mask = 0;
1273 const char *p;
22c3a6ca 1274
88ec4dfa
LP
1275 assert(item);
1276
1277 p = item->argument;
1278 if (p) {
1279 if (*p == '+') {
1280 mode = MODE_ADD;
1281 p++;
1282 } else if (*p == '-') {
1283 mode = MODE_DEL;
1284 p++;
1285 } else if (*p == '=') {
1286 mode = MODE_SET;
1287 p++;
1288 }
22c3a6ca
GB
1289 }
1290
baaa35ad
ZJS
1291 if (isempty(p) && mode != MODE_SET)
1292 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1293 "Setting file attribute on '%s' needs an attribute specification.",
1294 item->path);
88ec4dfa
LP
1295
1296 for (; p && *p ; p++) {
1297 unsigned i, v;
1298
1299 for (i = 0; i < ELEMENTSOF(attributes); i++)
1300 if (*p == attributes[i].character)
1301 break;
1302
baaa35ad
ZJS
1303 if (i >= ELEMENTSOF(attributes))
1304 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1305 "Unknown file attribute '%c' on '%s'.",
1306 *p, item->path);
88ec4dfa
LP
1307
1308 v = attributes[i].value;
1309
3742095b 1310 SET_FLAG(value, v, IN_SET(mode, MODE_ADD, MODE_SET));
88ec4dfa
LP
1311
1312 mask |= v;
22c3a6ca
GB
1313 }
1314
1315 if (mode == MODE_SET)
d629ba70 1316 mask |= CHATTR_ALL_FL;
22c3a6ca 1317
88ec4dfa 1318 assert(mask != 0);
22c3a6ca 1319
88ec4dfa
LP
1320 item->attribute_mask = mask;
1321 item->attribute_value = value;
1322 item->attribute_set = true;
22c3a6ca
GB
1323
1324 return 0;
22c3a6ca
GB
1325}
1326
a9bc518c
LP
1327static int fd_set_attribute(
1328 Item *item,
1329 int fd,
1330 const char *path,
1331 const struct stat *st,
1332 CreationMode creation) {
1333
936f6bdb 1334 _cleanup_close_ int procfs_fd = -1;
b206ac8e 1335 struct stat stbuf;
88ec4dfa
LP
1336 unsigned f;
1337 int r;
22c3a6ca 1338
4dc7bfdf 1339 assert(item);
b4b0f87c 1340 assert(fd >= 0);
4dc7bfdf
FB
1341 assert(path);
1342
88ec4dfa 1343 if (!item->attribute_set || item->attribute_mask == 0)
22c3a6ca 1344 return 0;
22c3a6ca 1345
b206ac8e
FB
1346 if (!st) {
1347 if (fstat(fd, &stbuf) < 0)
1348 return log_error_errno(errno, "fstat(%s) failed: %m", path);
1349 st = &stbuf;
1350 }
1351
c5d554aa
LP
1352 /* Issuing the file attribute ioctls on device nodes is not safe, as that will be delivered to the
1353 * drivers, not the file system containing the device node. */
baaa35ad
ZJS
1354 if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode))
1355 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1356 "Setting file flags is only supported on regular files and directories, cannot set on '%s'.",
1357 path);
88ec4dfa
LP
1358
1359 f = item->attribute_value & item->attribute_mask;
1360
1361 /* Mask away directory-specific flags */
936f6bdb 1362 if (!S_ISDIR(st->st_mode))
22c3a6ca 1363 f &= ~FS_DIRSYNC_FL;
88ec4dfa 1364
f2324783 1365 procfs_fd = fd_reopen(fd, O_RDONLY|O_CLOEXEC|O_NOATIME);
936f6bdb 1366 if (procfs_fd < 0)
c3e03778 1367 return log_error_errno(procfs_fd, "Failed to re-open '%s': %m", path);
936f6bdb 1368
94566540 1369 unsigned previous, current;
c1631ee1 1370 r = chattr_full(NULL, procfs_fd, f, item->attribute_mask, &previous, &current, CHATTR_FALLBACK_BITWISE);
94566540 1371 if (r == -ENOANO)
d1a61dfa 1372 log_warning("Cannot set file attributes for '%s', maybe due to incompatibility in specified attributes, "
94566540
YW
1373 "previous=0x%08x, current=0x%08x, expected=0x%08x, ignoring.",
1374 path, previous, current, (previous & ~item->attribute_mask) | (f & item->attribute_mask));
1375 else if (r < 0)
1376 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r) ? LOG_DEBUG : LOG_WARNING, r,
1377 "Cannot set file attributes for '%s', value=0x%08x, mask=0x%08x, ignoring: %m",
ad75a97f 1378 path, item->attribute_value, item->attribute_mask);
22c3a6ca
GB
1379
1380 return 0;
1381}
1382
a9bc518c 1383static int path_set_attribute(Item *item, const char *path, CreationMode creation) {
936f6bdb 1384 _cleanup_close_ int fd = -1;
936f6bdb
FB
1385
1386 if (!item->attribute_set || item->attribute_mask == 0)
1387 return 0;
1388
addc3e30 1389 fd = path_open_safe(path);
936f6bdb 1390 if (fd < 0)
addc3e30 1391 return fd;
936f6bdb 1392
a9bc518c 1393 return fd_set_attribute(item, fd, path, /* st= */ NULL, creation);
936f6bdb
FB
1394}
1395
708daf42
LP
1396static int write_argument_data(Item *i, int fd, const char *path) {
1397 int r;
1398
1399 assert(i);
1400 assert(fd >= 0);
1401 assert(path);
1402
1403 if (item_binary_argument_size(i) == 0)
1404 return 0;
1405
1406 assert(item_binary_argument(i));
1407
1408 log_debug("Writing to \"%s\".", path);
1409
1410 r = loop_write(fd, item_binary_argument(i), item_binary_argument_size(i), /* do_poll= */ false);
1411 if (r < 0)
1412 return log_error_errno(r, "Failed to write file \"%s\": %m", path);
1413
1414 return 0;
1415}
1416
a9bc518c 1417static int write_one_file(Item *i, const char *path, CreationMode creation) {
551470ec 1418 _cleanup_close_ int fd = -1, dir_fd = -1;
4609d3bb 1419 _cleanup_free_ char *bn = NULL;
1baaf8aa 1420 int r;
31c84ff1
FB
1421
1422 assert(i);
1423 assert(path);
31c84ff1
FB
1424 assert(i->type == WRITE_FILE);
1425
4609d3bb
LP
1426 r = path_extract_filename(path, &bn);
1427 if (r < 0)
1428 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1429 if (r == O_DIRECTORY)
1430 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1431
1432 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1433 * can't be changed behind our back. */
551470ec
FB
1434 dir_fd = path_open_parent_safe(path);
1435 if (dir_fd < 0)
1436 return dir_fd;
1437
31c84ff1 1438 /* Follows symlinks */
1baaf8aa
LP
1439 fd = openat(dir_fd, bn,
1440 O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY|(i->append_or_force ? O_APPEND : 0),
1441 i->mode);
31c84ff1
FB
1442 if (fd < 0) {
1443 if (errno == ENOENT) {
1444 log_debug_errno(errno, "Not writing missing file \"%s\": %m", path);
1445 return 0;
1446 }
1baaf8aa
LP
1447
1448 if (i->allow_failure)
1449 return log_debug_errno(errno, "Failed to open file \"%s\", ignoring: %m", path);
1450
31c84ff1
FB
1451 return log_error_errno(errno, "Failed to open file \"%s\": %m", path);
1452 }
1453
1454 /* 'w' is allowed to write into any kind of files. */
31c84ff1 1455
708daf42 1456 r = write_argument_data(i, fd, path);
31c84ff1 1457 if (r < 0)
708daf42 1458 return r;
31c84ff1 1459
a9bc518c 1460 return fd_set_perms(i, fd, path, NULL, creation);
31c84ff1
FB
1461}
1462
1463static int create_file(Item *i, const char *path) {
5ec9d065 1464 _cleanup_close_ int fd = -1, dir_fd = -1;
4609d3bb 1465 _cleanup_free_ char *bn = NULL;
5ec9d065 1466 struct stat stbuf, *st = NULL;
a9bc518c 1467 CreationMode creation;
5ec9d065 1468 int r = 0;
d4e9eb91 1469
874f1947
LP
1470 assert(i);
1471 assert(path);
5ec9d065
FB
1472 assert(i->type == CREATE_FILE);
1473
1474 /* 'f' operates on regular files exclusively. */
1475
4609d3bb
LP
1476 r = path_extract_filename(path, &bn);
1477 if (r < 0)
1478 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1479 if (r == O_DIRECTORY)
1480 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for writing, is a directory.", path);
1481
1482 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1483 * can't be changed behind our back. */
5ec9d065
FB
1484 dir_fd = path_open_parent_safe(path);
1485 if (dir_fd < 0)
1486 return dir_fd;
874f1947 1487
43ad6e31 1488 RUN_WITH_UMASK(0000) {
ecabcf8b 1489 mac_selinux_create_file_prepare(path, S_IFREG);
05c4affe 1490 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_EXCL|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
ecabcf8b 1491 mac_selinux_create_file_clear();
5c0d398d 1492 }
d4e9eb91
DR
1493
1494 if (fd < 0) {
c5d554aa
LP
1495 /* Even on a read-only filesystem, open(2) returns EEXIST if the file already exists. It
1496 * returns EROFS only if it needs to create the file. */
05c4affe
LP
1497 if (fd != -EEXIST)
1498 return log_error_errno(fd, "Failed to create file %s: %m", path);
5ec9d065 1499
c5d554aa
LP
1500 /* Re-open the file. At that point it must exist since open(2) failed with EEXIST. We still
1501 * need to check if the perms/mode need to be changed. For read-only filesystems, we let
1502 * fd_set_perms() report the error if the perms need to be modified. */
5ec9d065
FB
1503 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
1504 if (fd < 0)
1505 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1506
1507 if (fstat(fd, &stbuf) < 0)
1508 return log_error_errno(errno, "stat(%s) failed: %m", path);
1509
d7a0f1f4
FS
1510 if (!S_ISREG(stbuf.st_mode))
1511 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1512 "%s exists and is not a regular file.",
1513 path);
d4e9eb91 1514
5ec9d065 1515 st = &stbuf;
a9bc518c
LP
1516 creation = CREATION_EXISTING;
1517 } else {
8f6fb95c
LP
1518 r = write_argument_data(i, fd, path);
1519 if (r < 0)
1520 return r;
a9bc518c
LP
1521
1522 creation = CREATION_NORMAL;
d4e9eb91
DR
1523 }
1524
a9bc518c 1525 return fd_set_perms(i, fd, path, st, creation);
5ec9d065 1526}
d4e9eb91 1527
5ec9d065 1528static int truncate_file(Item *i, const char *path) {
14ab804e 1529 _cleanup_close_ int fd = -1, dir_fd = -1;
4609d3bb 1530 _cleanup_free_ char *bn = NULL;
5ec9d065 1531 struct stat stbuf, *st = NULL;
a9bc518c 1532 CreationMode creation;
5ec9d065
FB
1533 bool erofs = false;
1534 int r = 0;
1535
1536 assert(i);
1537 assert(path);
eccebf4b 1538 assert(i->type == TRUNCATE_FILE || (i->type == CREATE_FILE && i->append_or_force));
d4e9eb91 1539
4609d3bb
LP
1540 /* We want to operate on regular file exclusively especially since O_TRUNC is unspecified if the file
1541 * is neither a regular file nor a fifo nor a terminal device. Therefore we first open the file and
1542 * make sure it's a regular one before truncating it. */
1543
1544 r = path_extract_filename(path, &bn);
1545 if (r < 0)
1546 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1547 if (r == O_DIRECTORY)
1548 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for truncation, is a directory.", path);
3612fbc1 1549
4609d3bb
LP
1550 /* Validate the path and keep the fd on the directory for opening the file so we're sure that it
1551 * can't be changed behind our back. */
14ab804e
FB
1552 dir_fd = path_open_parent_safe(path);
1553 if (dir_fd < 0)
1554 return dir_fd;
1555
a9bc518c
LP
1556 creation = CREATION_EXISTING;
1557 fd = RET_NERRNO(openat(dir_fd, bn, O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1558 if (fd == -ENOENT) {
1559 creation = CREATION_NORMAL; /* Didn't work without O_CREATE, try again with */
1560
1561 RUN_WITH_UMASK(0000) {
1562 mac_selinux_create_file_prepare(path, S_IFREG);
1563 fd = RET_NERRNO(openat(dir_fd, bn, O_CREAT|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC|O_WRONLY|O_NOCTTY, i->mode));
1564 mac_selinux_create_file_clear();
1565 }
5ec9d065
FB
1566 }
1567
1568 if (fd < 0) {
05c4affe
LP
1569 if (fd != -EROFS)
1570 return log_error_errno(fd, "Failed to open/create file %s: %m", path);
5ec9d065 1571
c5d554aa
LP
1572 /* On a read-only filesystem, we don't want to fail if the target is already empty and the
1573 * perms are set. So we still proceed with the sanity checks and let the remaining operations
1574 * fail with EROFS if they try to modify the target file. */
5ec9d065 1575
14ab804e 1576 fd = openat(dir_fd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH, i->mode);
5ec9d065 1577 if (fd < 0) {
d7a0f1f4
FS
1578 if (errno == ENOENT)
1579 return log_error_errno(SYNTHETIC_ERRNO(EROFS),
1580 "Cannot create file %s on a read-only file system.",
1581 path);
5ec9d065
FB
1582
1583 return log_error_errno(errno, "Failed to re-open file %s: %m", path);
1584 }
1585
1586 erofs = true;
a9bc518c 1587 creation = CREATION_EXISTING;
5ec9d065
FB
1588 }
1589
1590 if (fstat(fd, &stbuf) < 0)
4a62c710 1591 return log_error_errno(errno, "stat(%s) failed: %m", path);
d4e9eb91 1592
d7a0f1f4
FS
1593 if (!S_ISREG(stbuf.st_mode))
1594 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
1595 "%s exists and is not a regular file.",
1596 path);
d4e9eb91 1597
5ec9d065
FB
1598 if (stbuf.st_size > 0) {
1599 if (ftruncate(fd, 0) < 0) {
1600 r = erofs ? -EROFS : -errno;
1601 return log_error_errno(r, "Failed to truncate file %s: %m", path);
1602 }
1603 } else
1604 st = &stbuf;
d4e9eb91 1605
5ec9d065
FB
1606 log_debug("\"%s\" has been created.", path);
1607
708daf42
LP
1608 if (item_binary_argument(i)) {
1609 r = write_argument_data(i, fd, path);
2f3745dd 1610 if (r < 0)
708daf42 1611 return r;
5ec9d065
FB
1612 }
1613
a9bc518c 1614 return fd_set_perms(i, fd, path, st, creation);
d4e9eb91
DR
1615}
1616
b1f7b17f 1617static int copy_files(Item *i) {
16ba55ad 1618 _cleanup_close_ int dfd = -1, fd = -1;
4609d3bb 1619 _cleanup_free_ char *bn = NULL;
8f6fb95c 1620 struct stat st, a;
b1f7b17f
FB
1621 int r;
1622
1623 log_debug("Copying tree \"%s\" to \"%s\".", i->argument, i->path);
1624
4609d3bb
LP
1625 r = path_extract_filename(i->path, &bn);
1626 if (r < 0)
1627 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
b1f7b17f 1628
4609d3bb
LP
1629 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1630 * path can't be changed behind our back. */
16ba55ad
FB
1631 dfd = path_open_parent_safe(i->path);
1632 if (dfd < 0)
1633 return dfd;
b1f7b17f 1634
16ba55ad
FB
1635 r = copy_tree_at(AT_FDCWD, i->argument,
1636 dfd, bn,
1637 i->uid_set ? i->uid : UID_INVALID,
1638 i->gid_set ? i->gid : GID_INVALID,
652d9040 1639 COPY_REFLINK | COPY_MERGE_EMPTY | COPY_MAC_CREATE | COPY_HARDLINKS);
b1f7b17f 1640
8f6fb95c
LP
1641 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1642 if (fd < 0) {
1643 if (r < 0) /* Look at original error first */
b1f7b17f
FB
1644 return log_error_errno(r, "Failed to copy files to %s: %m", i->path);
1645
8f6fb95c
LP
1646 return log_error_errno(errno, "Failed to openat(%s): %m", i->path);
1647 }
1648
1649 if (fstat(fd, &st) < 0)
1650 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
b1f7b17f 1651
8f6fb95c
LP
1652 if (stat(i->argument, &a) < 0)
1653 return log_error_errno(errno, "Failed to stat(%s): %m", i->argument);
b1f7b17f 1654
8f6fb95c
LP
1655 if (((st.st_mode ^ a.st_mode) & S_IFMT) != 0) {
1656 log_debug("Can't copy to %s, file exists already and is of different type", i->path);
1657 return 0;
b1f7b17f
FB
1658 }
1659
8f6fb95c 1660 return fd_set_perms(i, fd, i->path, &st, _CREATION_MODE_INVALID);
b1f7b17f
FB
1661}
1662
a9bc518c
LP
1663static int create_directory_or_subvolume(
1664 const char *path,
1665 mode_t mode,
1666 bool subvol,
8f6fb95c 1667 struct stat *ret_st,
a9bc518c 1668 CreationMode *ret_creation) {
074bd73f 1669
4609d3bb 1670 _cleanup_free_ char *bn = NULL;
4c39d899 1671 _cleanup_close_ int pfd = -1;
8f6fb95c
LP
1672 CreationMode creation;
1673 struct stat st;
a9bc518c 1674 int r, fd;
4ad36844 1675
4c39d899 1676 assert(path);
4ad36844 1677
4609d3bb
LP
1678 r = path_extract_filename(path, &bn);
1679 if (r < 0)
1680 return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
1681
4c39d899
FB
1682 pfd = path_open_parent_safe(path);
1683 if (pfd < 0)
1684 return pfd;
4ad36844 1685
4c39d899 1686 if (subvol) {
4368c60c
AV
1687 r = getenv_bool("SYSTEMD_TMPFILES_FORCE_SUBVOL");
1688 if (r < 0) {
1689 if (r != -ENXIO) /* env var is unset */
1690 log_warning_errno(r, "Cannot parse value of $SYSTEMD_TMPFILES_FORCE_SUBVOL, ignoring.");
1691 r = btrfs_is_subvol(empty_to_root(arg_root)) > 0;
1692 }
8f6fb95c 1693 if (r == 0)
92631578
LP
1694 /* Don't create a subvolume unless the root directory is one, too. We do this under
1695 * the assumption that if the root directory is just a plain directory (i.e. very
1696 * light-weight), we shouldn't try to split it up into subvolumes (i.e. more
1697 * heavy-weight). Thus, chroot() environments and suchlike will get a full brtfs
1698 * subvolume set up below their tree only if they specifically set up a btrfs
1699 * subvolume for the root dir too. */
4ad36844 1700
4c39d899 1701 subvol = false;
4ad36844 1702 else {
4c39d899 1703 RUN_WITH_UMASK((~mode) & 0777)
4609d3bb 1704 r = btrfs_subvol_make_fd(pfd, bn);
4ad36844
FB
1705 }
1706 } else
1707 r = 0;
1708
8f6fb95c 1709 if (!subvol || ERRNO_IS_NOT_SUPPORTED(r))
4ad36844 1710 RUN_WITH_UMASK(0000)
4609d3bb 1711 r = mkdirat_label(pfd, bn, mode);
4ad36844 1712
8f6fb95c 1713 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
4ad36844 1714
8f6fb95c
LP
1715 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY|O_PATH);
1716 if (fd < 0) {
1717 /* We couldn't open it because it is not actually a directory? */
1718 if (errno == ENOTDIR)
1719 return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "\"%s\" already exists and is not a directory.", path);
1720
1721 /* Then look at the original error */
1722 if (r < 0)
4c39d899 1723 return log_error_errno(r, "Failed to create directory or subvolume \"%s\": %m", path);
4ad36844 1724
8f6fb95c
LP
1725 return log_error_errno(errno, "Failed to open directory/subvolume we just created '%s': %m", path);
1726 }
4ad36844 1727
8f6fb95c
LP
1728 if (fstat(fd, &st) < 0)
1729 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
4ad36844 1730
8f6fb95c 1731 assert(S_ISDIR(st.st_mode)); /* we used O_DIRECTORY above */
4c39d899 1732
8f6fb95c 1733 log_debug("%s directory \"%s\".", creation_mode_verb_to_string(creation), path);
09f12798 1734
8f6fb95c
LP
1735 if (ret_st)
1736 *ret_st = st;
a9bc518c 1737 if (ret_creation)
8f6fb95c 1738 *ret_creation = creation;
a9bc518c
LP
1739
1740 return fd;
4c39d899
FB
1741}
1742
1743static int create_directory(Item *i, const char *path) {
1744 _cleanup_close_ int fd = -1;
a9bc518c 1745 CreationMode creation;
8f6fb95c 1746 struct stat st;
4c39d899
FB
1747
1748 assert(i);
1749 assert(IN_SET(i->type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY));
1750
8f6fb95c 1751 fd = create_directory_or_subvolume(path, i->mode, /* subvol= */ false, &st, &creation);
4c39d899
FB
1752 if (fd == -EEXIST)
1753 return 0;
1754 if (fd < 0)
1755 return fd;
1756
8f6fb95c 1757 return fd_set_perms(i, fd, path, &st, creation);
4c39d899
FB
1758}
1759
1760static int create_subvolume(Item *i, const char *path) {
1761 _cleanup_close_ int fd = -1;
f17a8d61 1762 CreationMode creation;
8f6fb95c 1763 struct stat st;
4c39d899
FB
1764 int r, q = 0;
1765
1766 assert(i);
1767 assert(IN_SET(i->type, CREATE_SUBVOLUME, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA));
1768
8f6fb95c 1769 fd = create_directory_or_subvolume(path, i->mode, /* subvol = */ true, &st, &creation);
4c39d899
FB
1770 if (fd == -EEXIST)
1771 return 0;
1772 if (fd < 0)
1773 return fd;
4ad36844 1774
f17a8d61
FB
1775 if (creation == CREATION_NORMAL &&
1776 IN_SET(i->type, CREATE_SUBVOLUME_NEW_QUOTA, CREATE_SUBVOLUME_INHERIT_QUOTA)) {
4c39d899 1777 r = btrfs_subvol_auto_qgroup_fd(fd, 0, i->type == CREATE_SUBVOLUME_NEW_QUOTA);
4ad36844
FB
1778 if (r == -ENOTTY)
1779 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (unsupported fs or dir not a subvolume): %m", i->path);
1780 else if (r == -EROFS)
1781 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (fs is read-only).", i->path);
4b019d2f 1782 else if (r == -ENOTCONN)
4ad36844
FB
1783 log_debug_errno(r, "Couldn't adjust quota for subvolume \"%s\" (quota support is disabled).", i->path);
1784 else if (r < 0)
1785 q = log_error_errno(r, "Failed to adjust quota for subvolume \"%s\": %m", i->path);
1786 else if (r > 0)
1787 log_debug("Adjusted quota for subvolume \"%s\".", i->path);
1788 else if (r == 0)
1789 log_debug("Quota for subvolume \"%s\" already in place, no change made.", i->path);
1790 }
1791
8f6fb95c 1792 r = fd_set_perms(i, fd, path, &st, creation);
9d874aec 1793 if (q < 0) /* prefer the quota change error from above */
4ad36844
FB
1794 return q;
1795
1796 return r;
1797}
1798
a9bc518c 1799static int empty_directory(Item *i, const char *path, CreationMode creation) {
27f6aa0b
LP
1800 _cleanup_close_ int fd = -1;
1801 struct stat st;
54946021
FB
1802 int r;
1803
1804 assert(i);
1805 assert(i->type == EMPTY_DIRECTORY);
1806
27f6aa0b
LP
1807 r = chase_symlinks(path, arg_root, CHASE_SAFE|CHASE_WARN, NULL, &fd);
1808 if (r == -ENOLINK) /* Unsafe symlink: already covered by CHASE_WARN */
e56074a2 1809 return r;
54946021 1810 if (r == -ENOENT) {
27f6aa0b
LP
1811 /* Option "e" operates only on existing objects. Do not print errors about non-existent files
1812 * or directories */
1813 log_debug_errno(r, "Skipping missing directory: %s", path);
54946021
FB
1814 return 0;
1815 }
1816 if (r < 0)
27f6aa0b
LP
1817 return log_error_errno(r, "Failed to open directory '%s': %m", path);
1818
1819 if (fstat(fd, &st) < 0)
1820 return log_error_errno(errno, "Failed to fstat(%s): %m", path);
1821 if (!S_ISDIR(st.st_mode)) {
1822 log_warning("'%s' already exists and is not a directory.", path);
b88ba6c7
ZJS
1823 return 0;
1824 }
54946021 1825
27f6aa0b 1826 return fd_set_perms(i, fd, path, &st, creation);
54946021
FB
1827}
1828
074bd73f 1829static int create_device(Item *i, mode_t file_type) {
c7700a77 1830 _cleanup_close_ int dfd = -1, fd = -1;
4609d3bb 1831 _cleanup_free_ char *bn = NULL;
074bd73f 1832 CreationMode creation;
8f6fb95c 1833 struct stat st;
074bd73f
FB
1834 int r;
1835
1836 assert(i);
a8ec0abe 1837 assert(IN_SET(i->type, CREATE_BLOCK_DEVICE, CREATE_CHAR_DEVICE));
074bd73f
FB
1838 assert(IN_SET(file_type, S_IFBLK, S_IFCHR));
1839
4609d3bb
LP
1840 r = path_extract_filename(i->path, &bn);
1841 if (r < 0)
1842 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
1843 if (r == O_DIRECTORY)
1844 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating device node, is a directory.", i->path);
c7700a77 1845
4609d3bb
LP
1846 /* Validate the path and use the returned directory fd for copying the target so we're sure that the
1847 * path can't be changed behind our back. */
c7700a77
FB
1848 dfd = path_open_parent_safe(i->path);
1849 if (dfd < 0)
1850 return dfd;
1851
074bd73f
FB
1852 RUN_WITH_UMASK(0000) {
1853 mac_selinux_create_file_prepare(i->path, file_type);
05c4affe 1854 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
074bd73f
FB
1855 mac_selinux_create_file_clear();
1856 }
8f6fb95c 1857 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
074bd73f 1858
8f6fb95c
LP
1859 /* Try to open the inode via O_PATH, regardless if we could create it or not. Maybe everything is in
1860 * order anyway and we hence can ignore the error to create the device node */
1861 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1862 if (fd < 0) {
1863 /* OK, so opening the inode failed, let's look at the original error then. */
c7700a77 1864
8f6fb95c
LP
1865 if (r < 0) {
1866 if (ERRNO_IS_PRIVILEGE(r))
1867 goto handle_privilege;
074bd73f 1868
8f6fb95c
LP
1869 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
1870 }
074bd73f 1871
8f6fb95c
LP
1872 return log_error_errno(errno, "Failed to open device node '%s' we just created: %m", i->path);
1873 }
074bd73f 1874
8f6fb95c
LP
1875 if (fstat(fd, &st) < 0)
1876 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
074bd73f 1877
8f6fb95c 1878 if (((st.st_mode ^ file_type) & S_IFMT) != 0) {
074bd73f 1879
8f6fb95c
LP
1880 if (i->append_or_force) {
1881 fd = safe_close(fd);
074bd73f 1882
8f6fb95c
LP
1883 RUN_WITH_UMASK(0000) {
1884 mac_selinux_create_file_prepare(i->path, file_type);
1885 r = mknodat_atomic(dfd, bn, i->mode | file_type, i->major_minor);
1886 mac_selinux_create_file_clear();
1887 }
1888 if (ERRNO_IS_PRIVILEGE(r))
1889 goto handle_privilege;
1890 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1891 r = rm_rf_child(dfd, bn, REMOVE_PHYSICAL);
074bd73f 1892 if (r < 0)
8f6fb95c
LP
1893 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
1894
1895 mac_selinux_create_file_prepare(i->path, file_type);
1896 r = RET_NERRNO(mknodat(dfd, bn, i->mode | file_type, i->major_minor));
1897 mac_selinux_create_file_clear();
074bd73f 1898 }
8f6fb95c
LP
1899 if (r < 0)
1900 return log_error_errno(r, "Failed to create device node '%s': %m", i->path);
1901
1902 fd = openat(dfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1903 if (fd < 0)
1904 return log_error_errno(errno, "Failed to open device node we just created '%s': %m", i->path);
1905
1906 /* Validate type before change ownership below */
1907 if (fstat(fd, &st) < 0)
1908 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1909
1910 if (((st.st_mode ^ file_type) & S_IFMT) != 0)
1911 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Device node we just created is not a device node, refusing.");
1912
1913 creation = CREATION_FORCE;
1914 } else {
1915 log_warning("\"%s\" already exists and is not a device node.", i->path);
1916 return 0;
1917 }
1918 }
074bd73f
FB
1919
1920 log_debug("%s %s device node \"%s\" %u:%u.",
1921 creation_mode_verb_to_string(creation),
1922 i->type == CREATE_BLOCK_DEVICE ? "block" : "char",
1923 i->path, major(i->mode), minor(i->mode));
1924
8f6fb95c 1925 return fd_set_perms(i, fd, i->path, &st, creation);
c7700a77 1926
8f6fb95c
LP
1927handle_privilege:
1928 log_debug_errno(r,
1929 "We lack permissions, possibly because of cgroup configuration; "
1930 "skipping creation of device node '%s'.", i->path);
1931 return 0;
074bd73f
FB
1932}
1933
8f6fb95c 1934static int create_fifo(Item *i) {
7ea5a87f 1935 _cleanup_close_ int pfd = -1, fd = -1;
4609d3bb 1936 _cleanup_free_ char *bn = NULL;
a2fc2f8d
FB
1937 CreationMode creation;
1938 struct stat st;
1939 int r;
1940
8f6fb95c
LP
1941 assert(i);
1942 assert(i->type == CREATE_FIFO);
1943
4609d3bb
LP
1944 r = path_extract_filename(i->path, &bn);
1945 if (r < 0)
8f6fb95c 1946 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
4609d3bb 1947 if (r == O_DIRECTORY)
8f6fb95c 1948 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
4609d3bb 1949
8f6fb95c 1950 pfd = path_open_parent_safe(i->path);
7ea5a87f
FB
1951 if (pfd < 0)
1952 return pfd;
1953
a2fc2f8d 1954 RUN_WITH_UMASK(0000) {
8f6fb95c 1955 mac_selinux_create_file_prepare(i->path, S_IFIFO);
05c4affe 1956 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
a2fc2f8d
FB
1957 mac_selinux_create_file_clear();
1958 }
1959
8f6fb95c 1960 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
a2fc2f8d 1961
8f6fb95c
LP
1962 /* Open the inode via O_PATH, regardless if we managed to create it or not. Maybe it is is already the FIFO we want */
1963 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1964 if (fd < 0) {
1965 if (r < 0)
1966 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path); /* original error! */
a2fc2f8d 1967
8f6fb95c
LP
1968 return log_error_errno(errno, "Failed to open FIFO we just created %s: %m", i->path);
1969 }
a2fc2f8d 1970
8f6fb95c
LP
1971 if (fstat(fd, &st) < 0)
1972 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
1973
1974 if (!S_ISFIFO(st.st_mode)) {
a2fc2f8d 1975
8f6fb95c
LP
1976 if (i->append_or_force) {
1977 fd = safe_close(fd);
1978
1979 RUN_WITH_UMASK(0000) {
1980 mac_selinux_create_file_prepare(i->path, S_IFIFO);
1981 r = mkfifoat_atomic(pfd, bn, i->mode);
1982 mac_selinux_create_file_clear();
1983 }
1984 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
1985 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
a2fc2f8d 1986 if (r < 0)
8f6fb95c
LP
1987 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
1988
1989 mac_selinux_create_file_prepare(i->path, S_IFIFO);
1990 r = RET_NERRNO(mkfifoat(pfd, bn, i->mode));
1991 mac_selinux_create_file_clear();
a2fc2f8d 1992 }
8f6fb95c
LP
1993 if (r < 0)
1994 return log_error_errno(r, "Failed to create FIFO %s: %m", i->path);
7ea5a87f 1995
8f6fb95c
LP
1996 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
1997 if (fd < 0)
1998 return log_error_errno(errno, "Failed to open FIFO we just created '%s': %m", i->path);
a2fc2f8d 1999
8f6fb95c
LP
2000 /* Validate type before change ownership below */
2001 if (fstat(fd, &st) < 0)
2002 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2003
2004 if (!S_ISFIFO(st.st_mode))
2005 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "FIFO inode we just created is not a FIFO, refusing.");
2006
2007 creation = CREATION_FORCE;
2008 } else {
2009 log_warning("\"%s\" already exists and is not a FIFO.", i->path);
2010 return 0;
2011 }
2012 }
2013
2014 log_debug("%s fifo \"%s\".", creation_mode_verb_to_string(creation), i->path);
7ea5a87f 2015
8f6fb95c 2016 return fd_set_perms(i, fd, i->path, &st, creation);
a2fc2f8d
FB
2017}
2018
9e430ce3
LP
2019static int create_symlink(Item *i) {
2020 _cleanup_close_ int pfd = -1, fd = -1;
2021 _cleanup_free_ char *bn = NULL;
2022 CreationMode creation;
2023 struct stat st;
2024 bool good = false;
2025 int r;
2026
2027 assert(i);
2028
2029 r = path_extract_filename(i->path, &bn);
2030 if (r < 0)
2031 return log_error_errno(r, "Failed to extract filename from path '%s': %m", i->path);
2032 if (r == O_DIRECTORY)
2033 return log_error_errno(SYNTHETIC_ERRNO(EISDIR), "Cannot open path '%s' for creating FIFO, is a directory.", i->path);
2034
2035 pfd = path_open_parent_safe(i->path);
2036 if (pfd < 0)
2037 return pfd;
2038
2039 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2040 r = RET_NERRNO(symlinkat(i->argument, pfd, bn));
2041 mac_selinux_create_file_clear();
2042
2043 creation = r >= 0 ? CREATION_NORMAL : CREATION_EXISTING;
2044
2045 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2046 if (fd < 0) {
2047 if (r < 0)
2048 return log_error_errno(r, "Failed to create symlink '%s': %m", i->path); /* original error! */
2049
2050 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2051 }
2052
2053 if (fstat(fd, &st) < 0)
2054 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2055
2056 if (S_ISLNK(st.st_mode)) {
2057 _cleanup_free_ char *x = NULL;
2058
2059 r = readlinkat_malloc(fd, "", &x);
2060 if (r < 0)
2061 return log_error_errno(r, "readlinkat(%s) failed: %m", i->path);
2062
2063 good = streq(x, i->argument);
2064 } else
2065 good = false;
2066
2067 if (!good) {
2068 if (!i->append_or_force) {
2069 log_debug("\"%s\" is not a symlink or does not point to the correct path.", i->path);
2070 return 0;
2071 }
2072
2073 fd = safe_close(fd);
2074
2075 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2076 r = symlinkat_atomic_full(i->argument, pfd, bn, /* make_relative= */ false);
2077 mac_selinux_create_file_clear();
2078 if (IN_SET(r, -EISDIR, -EEXIST, -ENOTEMPTY)) {
2079 r = rm_rf_child(pfd, bn, REMOVE_PHYSICAL);
2080 if (r < 0)
2081 return log_error_errno(r, "rm -rf %s failed: %m", i->path);
2082
2083 mac_selinux_create_file_prepare(i->path, S_IFLNK);
2084 r = RET_NERRNO(symlinkat(i->argument, pfd, i->path));
2085 mac_selinux_create_file_clear();
2086 }
2087 if (r < 0)
2088 return log_error_errno(r, "symlink(%s, %s) failed: %m", i->argument, i->path);
2089
2090 fd = openat(pfd, bn, O_NOFOLLOW|O_CLOEXEC|O_PATH);
2091 if (fd < 0)
2092 return log_error_errno(errno, "Failed to open symlink we just created '%s': %m", i->path);
2093
2094 /* Validate type before change ownership below */
2095 if (fstat(fd, &st) < 0)
2096 return log_error_errno(errno, "Failed to fstat(%s): %m", i->path);
2097
2098 if (!S_ISLNK(st.st_mode))
2099 return log_error_errno(SYNTHETIC_ERRNO(EBADF), "Symlink we just created is not a symlink, refusing.");
2100
2101 creation = CREATION_FORCE;
2102 }
2103
2104 log_debug("%s symlink \"%s\".", creation_mode_verb_to_string(creation), i->path);
2105 return fd_set_perms(i, fd, i->path, &st, creation);
2106}
2107
a9bc518c
LP
2108typedef int (*action_t)(Item *i, const char *path, CreationMode creation);
2109typedef int (*fdaction_t)(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation);
2110
2111static int item_do(
2112 Item *i,
2113 int fd,
2114 const char *path,
2115 CreationMode creation,
2116 fdaction_t action) {
081043cf 2117
14f3480a 2118 struct stat st;
936f6bdb 2119 int r = 0, q;
e73a03e0
LP
2120
2121 assert(i);
4dc7bfdf 2122 assert(path);
936f6bdb 2123 assert(fd >= 0);
14f3480a
FB
2124
2125 if (fstat(fd, &st) < 0) {
09f12798 2126 r = log_error_errno(errno, "fstat() on file failed: %m");
14f3480a
FB
2127 goto finish;
2128 }
a8d88783 2129
a9bc518c
LP
2130 /* This returns the first error we run into, but nevertheless tries to go on */
2131 r = action(i, fd, path, &st, creation);
a8d88783 2132
14f3480a 2133 if (S_ISDIR(st.st_mode)) {
936f6bdb 2134 _cleanup_closedir_ DIR *d = NULL;
a8d88783 2135
ddb6eeaf
LP
2136 /* The passed 'fd' was opened with O_PATH. We need to convert it into a 'regular' fd before
2137 * reading the directory content. */
2138 d = opendir(FORMAT_PROC_FD_PATH(fd));
936f6bdb 2139 if (!d) {
ddb6eeaf 2140 log_error_errno(errno, "Failed to opendir() '%s': %m", FORMAT_PROC_FD_PATH(fd));
09f12798
LP
2141 if (r == 0)
2142 r = -errno;
936f6bdb
FB
2143 goto finish;
2144 }
a8d88783 2145
936f6bdb 2146 FOREACH_DIRENT_ALL(de, d, q = -errno; goto finish) {
936f6bdb 2147 int de_fd;
a8d88783 2148
936f6bdb
FB
2149 if (dot_or_dot_dot(de->d_name))
2150 continue;
2151
2152 de_fd = openat(fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_PATH);
9d874aec
LP
2153 if (de_fd < 0)
2154 q = log_error_errno(errno, "Failed to open() file '%s': %m", de->d_name);
4dc7bfdf
FB
2155 else {
2156 _cleanup_free_ char *de_path = NULL;
2157
62a85ee0 2158 de_path = path_join(path, de->d_name);
4dc7bfdf
FB
2159 if (!de_path)
2160 q = log_oom();
2161 else
2162 /* Pass ownership of dirent fd over */
a9bc518c 2163 q = item_do(i, de_fd, de_path, CREATION_EXISTING, action);
4dc7bfdf 2164 }
a8d88783 2165
e73a03e0
LP
2166 if (q < 0 && r == 0)
2167 r = q;
a8d88783 2168 }
a8d88783 2169 }
936f6bdb
FB
2170finish:
2171 safe_close(fd);
e73a03e0 2172 return r;
a8d88783
MS
2173}
2174
936f6bdb 2175static int glob_item(Item *i, action_t action) {
df99a9ef 2176 _cleanup_globfree_ glob_t g = {
ebf31a1f 2177 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
df99a9ef 2178 };
e73a03e0 2179 int r = 0, k;
99e68c0b 2180
84e72b5e
ZJS
2181 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2182 if (k < 0 && k != -ENOENT)
2183 return log_error_errno(k, "glob(%s) failed: %m", i->path);
99e68c0b 2184
c84a9488 2185 STRV_FOREACH(fn, g.gl_pathv) {
a9bc518c
LP
2186 /* We pass CREATION_EXISTING here, since if we are globbing for it, it always has to exist */
2187 k = action(i, *fn, CREATION_EXISTING);
e73a03e0 2188 if (k < 0 && r == 0)
99e68c0b 2189 r = k;
936f6bdb
FB
2190 }
2191
2192 return r;
2193}
081043cf 2194
936f6bdb
FB
2195static int glob_item_recursively(Item *i, fdaction_t action) {
2196 _cleanup_globfree_ glob_t g = {
2197 .gl_opendir = (void *(*)(const char *)) opendir_nomod,
2198 };
2199 int r = 0, k;
936f6bdb
FB
2200
2201 k = safe_glob(i->path, GLOB_NOSORT|GLOB_BRACE, &g);
2202 if (k < 0 && k != -ENOENT)
2203 return log_error_errno(k, "glob(%s) failed: %m", i->path);
2204
2205 STRV_FOREACH(fn, g.gl_pathv) {
2206 _cleanup_close_ int fd = -1;
936f6bdb
FB
2207
2208 /* Make sure we won't trigger/follow file object (such as
2209 * device nodes, automounts, ...) pointed out by 'fn' with
2210 * O_PATH. Note, when O_PATH is used, flags other than
2211 * O_CLOEXEC, O_DIRECTORY, and O_NOFOLLOW are ignored. */
2212
2213 fd = open(*fn, O_CLOEXEC|O_NOFOLLOW|O_PATH);
2214 if (fd < 0) {
09f12798
LP
2215 log_error_errno(errno, "Opening '%s' failed: %m", *fn);
2216 if (r == 0)
2217 r = -errno;
936f6bdb
FB
2218 continue;
2219 }
2220
a9bc518c 2221 k = item_do(i, fd, *fn, CREATION_EXISTING, action);
936f6bdb
FB
2222 if (k < 0 && r == 0)
2223 r = k;
2224
2225 /* we passed fd ownership to the previous call */
2226 fd = -1;
c84a9488 2227 }
99e68c0b 2228
99e68c0b
MS
2229 return r;
2230}
2231
c46c3233
AW
2232static int rm_if_wrong_type_safe(
2233 mode_t mode,
2234 int parent_fd,
21e43a7c 2235 const struct stat *parent_st, /* Only used if follow_links below is true. */
c46c3233
AW
2236 const char *name,
2237 int flags) {
2238 _cleanup_free_ char *parent_name = NULL;
2239 bool follow_links = !FLAGS_SET(flags, AT_SYMLINK_NOFOLLOW);
2240 struct stat st;
2241 int r;
2242
2243 assert(name);
2244 assert((mode & ~S_IFMT) == 0);
2245 assert(!follow_links || parent_st);
2246 assert((flags & ~AT_SYMLINK_NOFOLLOW) == 0);
2247
2248 if (!filename_is_valid(name))
2249 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "\"%s\" is not a valid filename.", name);
2250
2251 r = fstatat_harder(parent_fd, name, &st, flags, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2252 if (r < 0) {
2253 (void) fd_get_path(parent_fd, &parent_name);
2254 return log_full_errno(r == -ENOENT? LOG_DEBUG : LOG_ERR, r,
2255 "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2256 }
2257
2258 /* Fail before removing anything if this is an unsafe transition. */
2259 if (follow_links && unsafe_transition(parent_st, &st)) {
2260 (void) fd_get_path(parent_fd, &parent_name);
2261 return log_error_errno(SYNTHETIC_ERRNO(ENOLINK),
2262 "Unsafe transition from \"%s\" to \"%s\".", parent_name, name);
2263 }
2264
2265 if ((st.st_mode & S_IFMT) == mode)
2266 return 0;
2267
2268 (void) fd_get_path(parent_fd, &parent_name);
2269 log_notice("Wrong file type 0x%x; rm -rf \"%s/%s\"", st.st_mode & S_IFMT, strna(parent_name), name);
2270
2271 /* If the target of the symlink was the wrong type, the link needs to be removed instead of the
2272 * target, so make sure it is identified as a link and not a directory. */
2273 if (follow_links) {
2274 r = fstatat_harder(parent_fd, name, &st, AT_SYMLINK_NOFOLLOW, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2275 if (r < 0)
2276 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", name, strna(parent_name));
2277 }
2278
2279 /* Do not remove mount points. */
2280 r = fd_is_mount_point(parent_fd, name, follow_links ? AT_SYMLINK_FOLLOW : 0);
2281 if (r < 0)
2282 (void) log_warning_errno(r, "Failed to check if \"%s/%s\" is a mount point: %m; Continuing",
2283 strna(parent_name), name);
2284 else if (r > 0)
2285 return log_error_errno(SYNTHETIC_ERRNO(EBUSY),
2286 "Not removing \"%s/%s\" because it is a mount point.", strna(parent_name), name);
2287
2288 if ((st.st_mode & S_IFMT) == S_IFDIR) {
2289 _cleanup_close_ int child_fd = -1;
2290
2291 child_fd = openat(parent_fd, name, O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2292 if (child_fd < 0)
2293 return log_error_errno(errno, "Failed to open \"%s\" at \"%s\": %m", name, strna(parent_name));
2294
2295 r = rm_rf_children(TAKE_FD(child_fd), REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL, &st);
2296 if (r < 0)
2297 return log_error_errno(r, "Failed to remove contents of \"%s\" at \"%s\": %m", name, strna(parent_name));
2298
2299 r = unlinkat_harder(parent_fd, name, AT_REMOVEDIR, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2300 } else
2301 r = unlinkat_harder(parent_fd, name, 0, REMOVE_CHMOD | REMOVE_CHMOD_RESTORE);
2302 if (r < 0)
2303 return log_error_errno(r, "Failed to remove \"%s\" at \"%s\": %m", name, strna(parent_name));
2304
2305 /* This is covered by the log_notice "Wrong file type..." It is logged earlier because it gives
2306 * context to other error messages that might follow. */
2307 return -ENOENT;
2308}
2309
2310/* If child_mode is non-zero, rm_if_wrong_type_safe will be executed for the last path component. */
2311static int mkdir_parents_rm_if_wrong_type(mode_t child_mode, const char *path) {
21e43a7c 2312 _cleanup_close_ int parent_fd = -1;
c46c3233 2313 struct stat parent_st;
c46c3233 2314 size_t path_len;
21e43a7c 2315 int r;
c46c3233
AW
2316
2317 assert(path);
2318 assert((child_mode & ~S_IFMT) == 0);
2319
2320 path_len = strlen(path);
2321
2322 if (!is_path(path))
2323 /* rm_if_wrong_type_safe already logs errors. */
2324 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, AT_FDCWD, NULL, path, AT_SYMLINK_NOFOLLOW) : 0;
2325
2326 if (child_mode != 0 && endswith(path, "/"))
2327 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2328 "Trailing path separators are only allowed if child_mode is not set; got \"%s\"", path);
2329
2330 /* Get the parent_fd and stat. */
c68cafba
YW
2331 parent_fd = openat(AT_FDCWD, path_is_absolute(path) ? "/" : ".", O_NOCTTY | O_CLOEXEC | O_DIRECTORY);
2332 if (parent_fd < 0)
2333 return log_error_errno(errno, "Failed to open root: %m");
2334
c46c3233
AW
2335 if (fstat(parent_fd, &parent_st) < 0)
2336 return log_error_errno(errno, "Failed to stat root: %m");
2337
2338 /* Check every parent directory in the path, except the last component */
21e43a7c
YW
2339 for (const char *e = path;;) {
2340 _cleanup_close_ int next_fd = -1;
c46c3233 2341 char t[path_len + 1];
21e43a7c 2342 const char *s;
c46c3233
AW
2343
2344 /* Find the start of the next path component. */
2345 s = e + strspn(e, "/");
2346 /* Find the end of the next path component. */
2347 e = s + strcspn(s, "/");
2348
2349 /* Copy the path component to t so it can be a null terminated string. */
2350 *((char*) mempcpy(t, s, e - s)) = 0;
2351
2352 /* Is this the last component? If so, then check the type */
2353 if (*e == 0)
2354 return child_mode != 0 ? rm_if_wrong_type_safe(child_mode, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW) : 0;
c46c3233 2355
21e43a7c
YW
2356 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, 0);
2357 /* Remove dangling symlinks. */
2358 if (r == -ENOENT)
2359 r = rm_if_wrong_type_safe(S_IFDIR, parent_fd, &parent_st, t, AT_SYMLINK_NOFOLLOW);
c46c3233
AW
2360 if (r == -ENOENT) {
2361 RUN_WITH_UMASK(0000)
2362 r = mkdirat_label(parent_fd, t, 0755);
2363 if (r < 0) {
21e43a7c
YW
2364 _cleanup_free_ char *parent_name = NULL;
2365
c46c3233 2366 (void) fd_get_path(parent_fd, &parent_name);
21e43a7c 2367 return log_error_errno(r, "Failed to mkdir \"%s\" at \"%s\": %m", t, strnull(parent_name));
c46c3233
AW
2368 }
2369 } else if (r < 0)
2370 /* rm_if_wrong_type_safe already logs errors. */
2371 return r;
2372
7c248223 2373 next_fd = RET_NERRNO(openat(parent_fd, t, O_NOCTTY | O_CLOEXEC | O_DIRECTORY));
c46c3233 2374 if (next_fd < 0) {
21e43a7c
YW
2375 _cleanup_free_ char *parent_name = NULL;
2376
c46c3233 2377 (void) fd_get_path(parent_fd, &parent_name);
7c248223 2378 return log_error_errno(next_fd, "Failed to open \"%s\" at \"%s\": %m", t, strnull(parent_name));
c46c3233 2379 }
7c248223
LP
2380 r = RET_NERRNO(fstat(next_fd, &parent_st));
2381 if (r < 0) {
21e43a7c
YW
2382 _cleanup_free_ char *parent_name = NULL;
2383
c46c3233 2384 (void) fd_get_path(parent_fd, &parent_name);
21e43a7c 2385 return log_error_errno(r, "Failed to stat \"%s\" at \"%s\": %m", t, strnull(parent_name));
c46c3233
AW
2386 }
2387
ee3455cf 2388 close_and_replace(parent_fd, next_fd);
c46c3233
AW
2389 }
2390}
2391
2392static int mkdir_parents_item(Item *i, mode_t child_mode) {
2393 int r;
2394 if (i->try_replace) {
2395 r = mkdir_parents_rm_if_wrong_type(child_mode, i->path);
2396 if (r < 0 && r != -ENOENT)
2397 return r;
2398 } else
2399 RUN_WITH_UMASK(0000)
2400 (void) mkdir_parents_label(i->path, 0755);
2401
2402 return 0;
2403}
2404
3b63d2d3 2405static int create_item(Item *i) {
9e430ce3 2406 int r;
5008d581 2407
3b63d2d3 2408 assert(i);
5008d581 2409
582deb84
ZJS
2410 log_debug("Running create action for entry %c %s", (char) i->type, i->path);
2411
3b63d2d3
LP
2412 switch (i->type) {
2413
2414 case IGNORE_PATH:
78a92a5a 2415 case IGNORE_DIRECTORY_PATH:
3b63d2d3
LP
2416 case REMOVE_PATH:
2417 case RECURSIVE_REMOVE_PATH:
2418 return 0;
5008d581 2419
eccebf4b 2420 case TRUNCATE_FILE:
3b63d2d3 2421 case CREATE_FILE:
c46c3233
AW
2422 r = mkdir_parents_item(i, S_IFREG);
2423 if (r < 0)
2424 return r;
7fa10748 2425
eccebf4b
ZS
2426 if ((i->type == CREATE_FILE && i->append_or_force) || i->type == TRUNCATE_FILE)
2427 r = truncate_file(i, i->path);
2428 else
2429 r = create_file(i, i->path);
5ec9d065
FB
2430 if (r < 0)
2431 return r;
2432 break;
2433
7b887f22 2434 case COPY_FILES:
c46c3233
AW
2435 r = mkdir_parents_item(i, 0);
2436 if (r < 0)
2437 return r;
7fa10748 2438
b1f7b17f 2439 r = copy_files(i);
849958d1
LP
2440 if (r < 0)
2441 return r;
849958d1
LP
2442 break;
2443
d4e9eb91 2444 case WRITE_FILE:
936f6bdb 2445 r = glob_item(i, write_one_file);
f05bc3f7
MS
2446 if (r < 0)
2447 return r;
5008d581 2448
3b63d2d3
LP
2449 break;
2450
3b63d2d3 2451 case CREATE_DIRECTORY:
d7b8eec7 2452 case TRUNCATE_DIRECTORY:
c46c3233
AW
2453 r = mkdir_parents_item(i, S_IFDIR);
2454 if (r < 0)
2455 return r;
4c39d899
FB
2456
2457 r = create_directory(i, i->path);
2458 if (r < 0)
2459 return r;
2460 break;
2461
d7b8eec7 2462 case CREATE_SUBVOLUME:
5fb13eb5
LP
2463 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2464 case CREATE_SUBVOLUME_NEW_QUOTA:
c46c3233
AW
2465 r = mkdir_parents_item(i, S_IFDIR);
2466 if (r < 0)
2467 return r;
d7b8eec7 2468
4c39d899 2469 r = create_subvolume(i, i->path);
4ad36844
FB
2470 if (r < 0)
2471 return r;
2472 break;
5fb13eb5 2473
df8dee85 2474 case EMPTY_DIRECTORY:
54946021 2475 r = glob_item(i, empty_directory);
f05bc3f7
MS
2476 if (r < 0)
2477 return r;
3b63d2d3 2478 break;
ee17ee7c
LP
2479
2480 case CREATE_FIFO:
c46c3233
AW
2481 r = mkdir_parents_item(i, S_IFIFO);
2482 if (r < 0)
2483 return r;
7fa10748 2484
8f6fb95c 2485 r = create_fifo(i);
f05bc3f7
MS
2486 if (r < 0)
2487 return r;
ee17ee7c 2488 break;
a8d88783 2489
9e430ce3 2490 case CREATE_SYMLINK:
c46c3233
AW
2491 r = mkdir_parents_item(i, S_IFLNK);
2492 if (r < 0)
2493 return r;
7fa10748 2494
9e430ce3
LP
2495 r = create_symlink(i);
2496 if (r < 0)
2497 return r;
a542c4dc 2498
468d726b 2499 break;
468d726b
LP
2500
2501 case CREATE_BLOCK_DEVICE:
074bd73f 2502 case CREATE_CHAR_DEVICE:
cb7ed9df 2503 if (have_effective_cap(CAP_MKNOD) == 0) {
713998cf
LP
2504 /* In a container we lack CAP_MKNOD. We shouldn't attempt to create the device node in that
2505 * case to avoid noise, and we don't support virtualized devices in containers anyway. */
cb7ed9df
LP
2506
2507 log_debug("We lack CAP_MKNOD, skipping creation of device node %s.", i->path);
2508 return 0;
2509 }
2510
c46c3233
AW
2511 r = mkdir_parents_item(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
2512 if (r < 0)
2513 return r;
7fa10748 2514
074bd73f 2515 r = create_device(i, i->type == CREATE_BLOCK_DEVICE ? S_IFBLK : S_IFCHR);
468d726b
LP
2516 if (r < 0)
2517 return r;
2518
2519 break;
468d726b 2520
e73a03e0 2521 case ADJUST_MODE:
777b87e7 2522 case RELABEL_PATH:
936f6bdb 2523 r = glob_item(i, path_set_perms);
777b87e7 2524 if (r < 0)
96ca8194 2525 return r;
777b87e7
MS
2526 break;
2527
a8d88783 2528 case RECURSIVE_RELABEL_PATH:
936f6bdb 2529 r = glob_item_recursively(i, fd_set_perms);
a8d88783
MS
2530 if (r < 0)
2531 return r;
ebf4e801 2532 break;
e73a03e0 2533
ebf4e801 2534 case SET_XATTR:
936f6bdb 2535 r = glob_item(i, path_set_xattrs);
b705ab6a
ZJS
2536 if (r < 0)
2537 return r;
2538 break;
2539
2540 case RECURSIVE_SET_XATTR:
936f6bdb 2541 r = glob_item_recursively(i, fd_set_xattrs);
ebf4e801
MW
2542 if (r < 0)
2543 return r;
e73a03e0 2544 break;
f8eeeaf9
ZJS
2545
2546 case SET_ACL:
936f6bdb 2547 r = glob_item(i, path_set_acls);
f8eeeaf9
ZJS
2548 if (r < 0)
2549 return r;
b705ab6a
ZJS
2550 break;
2551
2552 case RECURSIVE_SET_ACL:
936f6bdb 2553 r = glob_item_recursively(i, fd_set_acls);
b705ab6a
ZJS
2554 if (r < 0)
2555 return r;
2556 break;
22c3a6ca 2557
88ec4dfa 2558 case SET_ATTRIBUTE:
936f6bdb 2559 r = glob_item(i, path_set_attribute);
22c3a6ca
GB
2560 if (r < 0)
2561 return r;
2562 break;
2563
88ec4dfa 2564 case RECURSIVE_SET_ATTRIBUTE:
936f6bdb 2565 r = glob_item_recursively(i, fd_set_attribute);
22c3a6ca
GB
2566 if (r < 0)
2567 return r;
2568 break;
3b63d2d3
LP
2569 }
2570
f05bc3f7 2571 return 0;
3b63d2d3
LP
2572}
2573
a9bc518c 2574static int remove_item_instance(Item *i, const char *instance, CreationMode creation) {
3b63d2d3
LP
2575 int r;
2576
2577 assert(i);
2578
2579 switch (i->type) {
2580
3b63d2d3 2581 case REMOVE_PATH:
4a62c710 2582 if (remove(instance) < 0 && errno != ENOENT)
3f93da98 2583 return log_error_errno(errno, "rm(%s): %m", instance);
3b63d2d3
LP
2584
2585 break;
2586
3b63d2d3 2587 case RECURSIVE_REMOVE_PATH:
2c575977 2588 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
582deb84 2589 log_debug("rm -rf \"%s\"", instance);
2c575977 2590 r = rm_rf(instance, REMOVE_ROOT|REMOVE_SUBVOLUME|REMOVE_PHYSICAL);
f647962d
MS
2591 if (r < 0 && r != -ENOENT)
2592 return log_error_errno(r, "rm_rf(%s): %m", instance);
3b63d2d3
LP
2593
2594 break;
7fcb4b9b
ZJS
2595
2596 default:
04499a70 2597 assert_not_reached();
3b63d2d3
LP
2598 }
2599
2600 return 0;
2601}
2602
a0896123 2603static int remove_item(Item *i) {
2c575977
LP
2604 int r;
2605
b8bb3e8f
LP
2606 assert(i);
2607
582deb84
ZJS
2608 log_debug("Running remove action for entry %c %s", (char) i->type, i->path);
2609
b8bb3e8f
LP
2610 switch (i->type) {
2611
b8bb3e8f 2612 case TRUNCATE_DIRECTORY:
2c575977
LP
2613 /* FIXME: we probably should use dir_cleanup() here instead of rm_rf() so that 'x' is honoured. */
2614 log_debug("rm -rf \"%s\"", i->path);
2615 r = rm_rf(i->path, REMOVE_PHYSICAL);
2616 if (r < 0 && r != -ENOENT)
2617 return log_error_errno(r, "rm_rf(%s): %m", i->path);
2618
2619 return 0;
2620
2621 case REMOVE_PATH:
99e68c0b 2622 case RECURSIVE_REMOVE_PATH:
936f6bdb 2623 return glob_item(i, remove_item_instance);
b8bb3e8f 2624
df8dee85
ZJS
2625 default:
2626 return 0;
2627 }
b8bb3e8f
LP
2628}
2629
7f7a50dd
SK
2630static char *age_by_to_string(AgeBy ab, bool is_dir) {
2631 static const char ab_map[] = { 'a', 'b', 'c', 'm' };
2632 size_t j = 0;
2633 char *ret;
2634
2635 ret = new(char, ELEMENTSOF(ab_map) + 1);
2636 if (!ret)
2637 return NULL;
2638
2639 for (size_t i = 0; i < ELEMENTSOF(ab_map); i++)
2640 if (FLAGS_SET(ab, 1U << i))
2641 ret[j++] = is_dir ? ascii_toupper(ab_map[i]) : ab_map[i];
2642
2643 ret[j] = 0;
2644 return ret;
2645}
2646
a9bc518c
LP
2647static int clean_item_instance(
2648 Item *i,
2649 const char* instance,
2650 CreationMode creation) {
2651
7fd1b19b 2652 _cleanup_closedir_ DIR *d = NULL;
7cd296c2 2653 STRUCT_STATX_DEFINE(sx);
ca194a2a 2654 int mountpoint, r;
78a92a5a 2655 usec_t cutoff, n;
ddb439b8 2656
78a92a5a
MS
2657 assert(i);
2658
2659 if (!i->age_set)
2660 return 0;
2661
2662 n = now(CLOCK_REALTIME);
2663 if (n < i->age)
2664 return 0;
2665
2666 cutoff = n - i->age;
2667
df99a9ef 2668 d = opendir_nomod(instance);
78a92a5a 2669 if (!d) {
d710aaf7 2670 if (IN_SET(errno, ENOENT, ENOTDIR)) {
582deb84 2671 log_debug_errno(errno, "Directory \"%s\": %m", instance);
78a92a5a 2672 return 0;
582deb84 2673 }
78a92a5a 2674
d710aaf7 2675 return log_error_errno(errno, "Failed to open directory %s: %m", instance);
78a92a5a
MS
2676 }
2677
ca194a2a
LP
2678 r = statx_fallback(dirfd(d), "", AT_EMPTY_PATH, STATX_MODE|STATX_INO|STATX_ATIME|STATX_MTIME, &sx);
2679 if (r < 0)
2680 return log_error_errno(r, "statx(%s) failed: %m", instance);
ddb439b8 2681
ca194a2a
LP
2682 if (FLAGS_SET(sx.stx_attributes_mask, STATX_ATTR_MOUNT_ROOT))
2683 mountpoint = FLAGS_SET(sx.stx_attributes, STATX_ATTR_MOUNT_ROOT);
2684 else {
ddb439b8 2685 struct stat ps;
78a92a5a 2686
ddb439b8
LP
2687 if (fstatat(dirfd(d), "..", &ps, AT_SYMLINK_NOFOLLOW) != 0)
2688 return log_error_errno(errno, "stat(%s/..) failed: %m", i->path);
78a92a5a 2689
ddb439b8 2690 mountpoint =
ca194a2a
LP
2691 sx.stx_dev_major != major(ps.st_dev) ||
2692 sx.stx_dev_minor != minor(ps.st_dev) ||
2693 sx.stx_ino != ps.st_ino;
ddb439b8 2694 }
78a92a5a 2695
7f7a50dd
SK
2696 if (DEBUG_LOGGING) {
2697 _cleanup_free_ char *ab_f = NULL, *ab_d = NULL;
2698
2699 ab_f = age_by_to_string(i->age_by_file, false);
2700 if (!ab_f)
2701 return log_oom();
2702
2703 ab_d = age_by_to_string(i->age_by_dir, true);
2704 if (!ab_d)
2705 return log_oom();
2706
2707 log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
2708 mountpoint ? "mount point" : "directory",
2709 instance,
0086ef19 2710 FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
7f7a50dd
SK
2711 ab_f, ab_d);
2712 }
582deb84 2713
ddb439b8 2714 return dir_cleanup(i, instance, d,
ca194a2a
LP
2715 load_statx_timestamp_nsec(&sx.stx_atime),
2716 load_statx_timestamp_nsec(&sx.stx_mtime),
2717 cutoff * NSEC_PER_USEC,
2718 sx.stx_dev_major, sx.stx_dev_minor, mountpoint,
7f7a50dd
SK
2719 MAX_DEPTH, i->keep_first_level,
2720 i->age_by_file, i->age_by_dir);
78a92a5a
MS
2721}
2722
2723static int clean_item(Item *i) {
78a92a5a
MS
2724 assert(i);
2725
582deb84
ZJS
2726 log_debug("Running clean action for entry %c %s", (char) i->type, i->path);
2727
78a92a5a
MS
2728 switch (i->type) {
2729 case CREATE_DIRECTORY:
d7b8eec7 2730 case CREATE_SUBVOLUME:
5fb13eb5
LP
2731 case CREATE_SUBVOLUME_INHERIT_QUOTA:
2732 case CREATE_SUBVOLUME_NEW_QUOTA:
78a92a5a
MS
2733 case TRUNCATE_DIRECTORY:
2734 case IGNORE_PATH:
849958d1 2735 case COPY_FILES:
a9bc518c 2736 clean_item_instance(i, i->path, CREATION_EXISTING);
df8dee85 2737 return 0;
65241c14 2738 case EMPTY_DIRECTORY:
78a92a5a 2739 case IGNORE_DIRECTORY_PATH:
936f6bdb 2740 return glob_item(i, clean_item_instance);
78a92a5a 2741 default:
df8dee85 2742 return 0;
78a92a5a 2743 }
78a92a5a
MS
2744}
2745
599ebe29 2746static int process_item(Item *i, OperationMask operation) {
811a1587 2747 OperationMask todo;
bd6d28f2
ZJS
2748 _cleanup_free_ char *_path = NULL;
2749 const char *path;
811a1587 2750 int r, q, p;
3b63d2d3
LP
2751
2752 assert(i);
2753
811a1587
LP
2754 todo = operation & ~i->done;
2755 if (todo == 0) /* Everything already done? */
1910cd0e
LP
2756 return 0;
2757
811a1587 2758 i->done |= operation;
1910cd0e 2759
bd6d28f2
ZJS
2760 path = i->path;
2761 if (string_is_glob(path)) {
2762 /* We can't easily check whether a glob matches any autofs path, so let's do the check only
2763 * for the non-glob part. */
2764
2765 r = glob_non_glob_prefix(path, &_path);
2766 if (r < 0 && r != -ENOENT)
2767 return log_debug_errno(r, "Failed to deglob path: %m");
2768 if (r >= 0)
2769 path = _path;
2770 }
2771
2772 r = chase_symlinks(path, arg_root, CHASE_NO_AUTOFS|CHASE_NONEXISTENT|CHASE_WARN, NULL, NULL);
21af3386 2773 if (r == -EREMOTE) {
bd6d28f2 2774 log_notice_errno(r, "Skipping %s", i->path); /* We log the configured path, to not confuse the user. */
811a1587 2775 return 0;
145b8d0f
FB
2776 }
2777 if (r < 0)
48d96904 2778 log_debug_errno(r, "Failed to determine whether '%s' is below autofs, ignoring: %m", i->path);
655f2da0 2779
599ebe29 2780 r = FLAGS_SET(operation, OPERATION_CREATE) ? create_item(i) : 0;
6d7b5433
WD
2781 /* Failure can only be tolerated for create */
2782 if (i->allow_failure)
2783 r = 0;
3b63d2d3 2784
599ebe29
LP
2785 q = FLAGS_SET(operation, OPERATION_REMOVE) ? remove_item(i) : 0;
2786 p = FLAGS_SET(operation, OPERATION_CLEAN) ? clean_item(i) : 0;
1a967b6b 2787
811a1587 2788 return r < 0 ? r :
1db50423
ZJS
2789 q < 0 ? q :
2790 p;
3b63d2d3
LP
2791}
2792
599ebe29 2793static int process_item_array(ItemArray *array, OperationMask operation) {
96d10d78
LP
2794 int r = 0;
2795 size_t n;
753615e8 2796
3f93da98
ZJS
2797 assert(array);
2798
811a1587
LP
2799 /* Create any parent first. */
2800 if (FLAGS_SET(operation, OPERATION_CREATE) && array->parent)
2801 r = process_item_array(array->parent, operation & OPERATION_CREATE);
2802
2803 /* Clean up all children first */
2804 if ((operation & (OPERATION_REMOVE|OPERATION_CLEAN)) && !set_isempty(array->children)) {
811a1587
LP
2805 ItemArray *c;
2806
90e74a66 2807 SET_FOREACH(c, array->children) {
811a1587
LP
2808 int k;
2809
2810 k = process_item_array(c, operation & (OPERATION_REMOVE|OPERATION_CLEAN));
2811 if (k < 0 && r == 0)
2812 r = k;
2813 }
2814 }
2815
96d10d78
LP
2816 for (n = 0; n < array->n_items; n++) {
2817 int k;
2818
599ebe29 2819 k = process_item(array->items + n, operation);
3f93da98
ZJS
2820 if (k < 0 && r == 0)
2821 r = k;
2822 }
2823
2824 return r;
2825}
3b63d2d3 2826
3f93da98
ZJS
2827static void item_free_contents(Item *i) {
2828 assert(i);
3b63d2d3 2829 free(i->path);
468d726b 2830 free(i->argument);
708daf42 2831 free(i->binary_argument);
ebf4e801 2832 strv_free(i->xattrs);
f8eeeaf9 2833
349cc4a5 2834#if HAVE_ACL
f8eeeaf9
ZJS
2835 acl_free(i->acl_access);
2836 acl_free(i->acl_default);
2837#endif
3b63d2d3
LP
2838}
2839
87938c3b 2840static ItemArray* item_array_free(ItemArray *a) {
96d10d78 2841 size_t n;
3f93da98
ZJS
2842
2843 if (!a)
87938c3b 2844 return NULL;
3f93da98 2845
96d10d78 2846 for (n = 0; n < a->n_items; n++)
3f93da98 2847 item_free_contents(a->items + n);
96d10d78 2848
811a1587 2849 set_free(a->children);
3f93da98 2850 free(a->items);
87938c3b 2851 return mfree(a);
3f93da98 2852}
e2f2fb78 2853
93bab288 2854static int item_compare(const Item *a, const Item *b) {
17493fa5
LP
2855 /* Make sure that the ownership taking item is put first, so
2856 * that we first create the node, and then can adjust it */
2857
93bab288 2858 if (takes_ownership(a->type) && !takes_ownership(b->type))
17493fa5 2859 return -1;
93bab288 2860 if (!takes_ownership(a->type) && takes_ownership(b->type))
17493fa5
LP
2861 return 1;
2862
93bab288 2863 return CMP(a->type, b->type);
17493fa5
LP
2864}
2865
a6aafd6a 2866static bool item_compatible(const Item *a, const Item *b) {
bfe95f35
LP
2867 assert(a);
2868 assert(b);
3f93da98 2869 assert(streq(a->path, b->path));
bfe95f35 2870
3f93da98
ZJS
2871 if (takes_ownership(a->type) && takes_ownership(b->type))
2872 /* check if the items are the same */
708daf42
LP
2873 return memcmp_nn(item_binary_argument(a), item_binary_argument_size(a),
2874 item_binary_argument(b), item_binary_argument_size(b)) == 0 &&
bfe95f35 2875
3f93da98
ZJS
2876 a->uid_set == b->uid_set &&
2877 a->uid == b->uid &&
cc43328c 2878 a->uid_only_create == b->uid_only_create &&
bfe95f35 2879
3f93da98
ZJS
2880 a->gid_set == b->gid_set &&
2881 a->gid == b->gid &&
cc43328c 2882 a->gid_only_create == b->gid_only_create &&
bfe95f35 2883
3f93da98
ZJS
2884 a->mode_set == b->mode_set &&
2885 a->mode == b->mode &&
cc43328c 2886 a->mode_only_create == b->mode_only_create &&
bfe95f35 2887
3f93da98
ZJS
2888 a->age_set == b->age_set &&
2889 a->age == b->age &&
bfe95f35 2890
7f7a50dd
SK
2891 a->age_by_file == b->age_by_file &&
2892 a->age_by_dir == b->age_by_dir &&
2893
3f93da98 2894 a->mask_perms == b->mask_perms &&
bfe95f35 2895
3f93da98 2896 a->keep_first_level == b->keep_first_level &&
468d726b 2897
3f93da98 2898 a->major_minor == b->major_minor;
468d726b 2899
bfe95f35
LP
2900 return true;
2901}
2902
a2aced4a 2903static bool should_include_path(const char *path) {
abef3f91 2904 STRV_FOREACH(prefix, arg_exclude_prefixes)
582deb84
ZJS
2905 if (path_startswith(path, *prefix)) {
2906 log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.",
2907 path, *prefix);
5c795114 2908 return false;
582deb84 2909 }
a2aced4a 2910
abef3f91 2911 STRV_FOREACH(prefix, arg_include_prefixes)
582deb84
ZJS
2912 if (path_startswith(path, *prefix)) {
2913 log_debug("Entry \"%s\" matches include prefix \"%s\".", path, *prefix);
a2aced4a 2914 return true;
582deb84 2915 }
a2aced4a 2916
6b000af4 2917 /* no matches, so we should include this path only if we have no allow list at all */
7b943bb7 2918 if (strv_isempty(arg_include_prefixes))
582deb84
ZJS
2919 return true;
2920
2921 log_debug("Entry \"%s\" does not match any include prefix, skipping.", path);
2922 return false;
a2aced4a
DR
2923}
2924
172e9cc3 2925static int specifier_expansion_from_arg(const Specifier *specifier_table, Item *i) {
4cef1923
FB
2926 int r;
2927
2928 assert(i);
2929
4e361acc 2930 if (!i->argument)
4cef1923
FB
2931 return 0;
2932
2933 switch (i->type) {
2934 case COPY_FILES:
2935 case CREATE_SYMLINK:
2936 case CREATE_FILE:
2937 case TRUNCATE_FILE:
e437538f
ZJS
2938 case WRITE_FILE: {
2939 _cleanup_free_ char *unescaped = NULL, *resolved = NULL;
2940 ssize_t l;
2941
2942 l = cunescape(i->argument, 0, &unescaped);
2943 if (l < 0)
2944 return log_error_errno(l, "Failed to unescape parameter to write: %s", i->argument);
4cef1923 2945
de61a04b 2946 r = specifier_printf(unescaped, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
4cef1923
FB
2947 if (r < 0)
2948 return r;
2949
e437538f
ZJS
2950 return free_and_replace(i->argument, resolved);
2951 }
4cef1923 2952 case SET_XATTR:
de010b0b 2953 case RECURSIVE_SET_XATTR:
dfe01841 2954 STRV_FOREACH(xattr, i->xattrs) {
e437538f
ZJS
2955 _cleanup_free_ char *resolved = NULL;
2956
de61a04b 2957 r = specifier_printf(*xattr, SIZE_MAX, specifier_table, arg_root, NULL, &resolved);
4cef1923
FB
2958 if (r < 0)
2959 return r;
2960
2961 free_and_replace(*xattr, resolved);
2962 }
e437538f 2963 return 0;
de010b0b 2964
4cef1923 2965 default:
e437538f 2966 return 0;
4cef1923 2967 }
4cef1923
FB
2968}
2969
a2d1fb88
LP
2970static int patch_var_run(const char *fname, unsigned line, char **path) {
2971 const char *k;
2972 char *n;
2973
2974 assert(path);
2975 assert(*path);
2976
2977 /* Optionally rewrites lines referencing /var/run/, to use /run/ instead. Why bother? tmpfiles merges lines in
2978 * some cases and detects conflicts in others. If files/directories are specified through two equivalent lines
2979 * this is problematic as neither case will be detected. Ideally we'd detect these cases by resolving symlinks
2980 * early, but that's precisely not what we can do here as this code very likely is running very early on, at a
2981 * time where the paths in question are not available yet, or even more importantly, our own tmpfiles rules
2982 * might create the paths that are intermediary to the listed paths. We can't really cover the generic case,
2983 * but the least we can do is cover the specific case of /var/run vs. /run, as /var/run is a legacy name for
2984 * /run only, and we explicitly document that and require that on systemd systems the former is a symlink to
2985 * the latter. Moreover files below this path are by far the primary usecase for tmpfiles.d/. */
2986
2987 k = path_startswith(*path, "/var/run/");
2988 if (isempty(k)) /* Don't complain about other paths than /var/run, and not about /var/run itself either. */
2989 return 0;
2990
2d9b74ba 2991 n = path_join("/run", k);
a2d1fb88
LP
2992 if (!n)
2993 return log_oom();
2994
2995 /* Also log about this briefly. We do so at LOG_NOTICE level, as we fixed up the situation automatically, hence
2996 * there's no immediate need for action by the user. However, in the interest of making things less confusing
2997 * to the user, let's still inform the user that these snippets should really be updated. */
b88ba6c7
ZJS
2998 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
2999 "Line references path below legacy directory /var/run/, updating %s → %s; please update the tmpfiles.d/ drop-in file accordingly.",
3000 *path, n);
a2d1fb88 3001
81fa4479 3002 free_and_replace(*path, n);
a2d1fb88
LP
3003
3004 return 0;
3005}
3006
a3451c2c
LP
3007static int find_uid(const char *user, uid_t *ret_uid, Hashmap **cache) {
3008 int r;
3009
3010 assert(user);
3011 assert(ret_uid);
3012
3013 /* First: parse as numeric UID string */
3014 r = parse_uid(user, ret_uid);
3015 if (r >= 0)
3016 return r;
3017
3018 /* Second: pass to NSS if we are running "online" */
3019 if (!arg_root)
3020 return get_user_creds(&user, ret_uid, NULL, NULL, NULL, 0);
3021
3022 /* Third, synthesize "root" unconditionally */
3023 if (streq(user, "root")) {
3024 *ret_uid = 0;
3025 return 0;
3026 }
3027
3028 /* Fourth: use fgetpwent() to read /etc/passwd directly, if we are "offline" */
3029 return name_to_uid_offline(arg_root, user, ret_uid, cache);
3030}
3031
3032static int find_gid(const char *group, gid_t *ret_gid, Hashmap **cache) {
3033 int r;
3034
3035 assert(group);
3036 assert(ret_gid);
3037
3038 /* First: parse as numeric GID string */
3039 r = parse_gid(group, ret_gid);
3040 if (r >= 0)
3041 return r;
3042
3043 /* Second: pass to NSS if we are running "online" */
3044 if (!arg_root)
3045 return get_group_creds(&group, ret_gid, 0);
3046
3047 /* Third, synthesize "root" unconditionally */
3048 if (streq(group, "root")) {
3049 *ret_gid = 0;
3050 return 0;
3051 }
3052
3053 /* Fourth: use fgetgrent() to read /etc/group directly, if we are "offline" */
3054 return name_to_gid_offline(arg_root, group, ret_gid, cache);
3055}
3056
7f7a50dd
SK
3057static int parse_age_by_from_arg(const char *age_by_str, Item *item) {
3058 AgeBy ab_f = 0, ab_d = 0;
3059
3060 static const struct {
3061 char age_by_chr;
3062 AgeBy age_by_flag;
3063 } age_by_types[] = {
3064 { 'a', AGE_BY_ATIME },
3065 { 'b', AGE_BY_BTIME },
3066 { 'c', AGE_BY_CTIME },
3067 { 'm', AGE_BY_MTIME },
3068 };
3069
3070 assert(age_by_str);
3071 assert(item);
3072
3073 if (isempty(age_by_str))
3074 return -EINVAL;
3075
3076 for (const char *s = age_by_str; *s != 0; s++) {
3077 size_t i;
3078
3079 /* Ignore whitespace. */
3080 if (strchr(WHITESPACE, *s))
3081 continue;
3082
3083 for (i = 0; i < ELEMENTSOF(age_by_types); i++) {
3084 /* Check lower-case for files, upper-case for directories. */
3085 if (*s == age_by_types[i].age_by_chr) {
3086 ab_f |= age_by_types[i].age_by_flag;
3087 break;
3088 } else if (*s == ascii_toupper(age_by_types[i].age_by_chr)) {
3089 ab_d |= age_by_types[i].age_by_flag;
3090 break;
3091 }
3092 }
3093
3094 /* Invalid character. */
3095 if (i >= ELEMENTSOF(age_by_types))
3096 return -EINVAL;
3097 }
3098
3099 /* No match. */
3100 if (ab_f == 0 && ab_d == 0)
3101 return -EINVAL;
3102
3103 item->age_by_file = ab_f > 0 ? ab_f : AGE_BY_DEFAULT_FILE;
3104 item->age_by_dir = ab_d > 0 ? ab_d : AGE_BY_DEFAULT_DIR;
3105
3106 return 0;
3107}
3108
a6aafd6a 3109static bool is_duplicated_item(ItemArray *existing, const Item *i) {
9af74e0f
FB
3110
3111 assert(existing);
3112 assert(i);
3113
3114 for (size_t n = 0; n < existing->n_items; n++) {
a6aafd6a 3115 const Item *e = existing->items + n;
9af74e0f
FB
3116
3117 if (item_compatible(e, i))
3118 continue;
3119
3120 /* Only multiple 'w+' lines for the same path are allowed. */
3121 if (e->type != WRITE_FILE || !e->append_or_force ||
3122 i->type != WRITE_FILE || !i->append_or_force)
3123 return true;
3124 }
3125
3126 return false;
3127}
3128
a3451c2c
LP
3129static int parse_line(
3130 const char *fname,
3131 unsigned line,
3132 const char *buffer,
3133 bool *invalid_config,
3134 Hashmap **uid_cache,
3135 Hashmap **gid_cache) {
1731e34a 3136
cde684a2 3137 _cleanup_free_ char *action = NULL, *mode = NULL, *user = NULL, *group = NULL, *age = NULL, *path = NULL;
7f7a50dd
SK
3138 _cleanup_(item_free_contents) Item i = {
3139 /* The "age-by" argument considers all file timestamp types by default. */
3140 .age_by_file = AGE_BY_DEFAULT_FILE,
3141 .age_by_dir = AGE_BY_DEFAULT_DIR,
3142 };
3f93da98 3143 ItemArray *existing;
ef43a391 3144 OrderedHashmap *h;
657cf7f4 3145 int r, pos;
e52f6f63 3146 bool append_or_force = false, boot = false, allow_failure = false, try_replace = false, unbase64 = false, from_cred = false;
3b63d2d3
LP
3147
3148 assert(fname);
3149 assert(line >= 1);
3150 assert(buffer);
3151
172e9cc3
ZJS
3152 const Specifier specifier_table[] = {
3153 { 'a', specifier_architecture, NULL },
3154 { 'b', specifier_boot_id, NULL },
3155 { 'B', specifier_os_build_id, NULL },
9a5893e9
ZJS
3156 { 'H', specifier_hostname, NULL },
3157 { 'l', specifier_short_hostname, NULL },
6db98098 3158 { 'm', specifier_machine_id, NULL },
172e9cc3
ZJS
3159 { 'o', specifier_os_id, NULL },
3160 { 'v', specifier_kernel_release, NULL },
3161 { 'w', specifier_os_version_id, NULL },
3162 { 'W', specifier_os_variant_id, NULL },
3163
3164 { 'h', specifier_user_home, NULL },
3165
3166 { 'C', specifier_directory, UINT_TO_PTR(DIRECTORY_CACHE) },
3167 { 'L', specifier_directory, UINT_TO_PTR(DIRECTORY_LOGS) },
3168 { 'S', specifier_directory, UINT_TO_PTR(DIRECTORY_STATE) },
3169 { 't', specifier_directory, UINT_TO_PTR(DIRECTORY_RUNTIME) },
3170
b380b643 3171 COMMON_CREDS_SPECIFIERS(arg_user ? LOOKUP_SCOPE_USER : LOOKUP_SCOPE_SYSTEM),
172e9cc3
ZJS
3172 COMMON_TMP_SPECIFIERS,
3173 {}
3174 };
3175
68685607 3176 r = extract_many_words(
4034a06d 3177 &buffer,
68685607 3178 NULL,
4ec85141 3179 EXTRACT_UNQUOTE,
4034a06d
LP
3180 &action,
3181 &path,
3182 &mode,
3183 &user,
3184 &group,
3185 &age,
3186 NULL);
d9daae55 3187 if (r < 0) {
751223fe
ZJS
3188 if (IN_SET(r, -EINVAL, -EBADSLT))
3189 /* invalid quoting and such or an unknown specifier */
d9daae55 3190 *invalid_config = true;
d02933fd 3191 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to parse line: %m");
4b93699d 3192 } else if (r < 2) {
d9daae55 3193 *invalid_config = true;
d02933fd 3194 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Syntax error.");
5008d581
LP
3195 }
3196
e7b88b7b 3197 if (!empty_or_dash(buffer)) {
4034a06d
LP
3198 i.argument = strdup(buffer);
3199 if (!i.argument)
3200 return log_oom();
3201 }
3202
2e78fa79 3203 if (isempty(action)) {
d9daae55 3204 *invalid_config = true;
d02933fd 3205 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Command too short '%s'.", action);
2e78fa79
LP
3206 }
3207
5f255144
ZJS
3208 for (pos = 1; action[pos]; pos++) {
3209 if (action[pos] == '!' && !boot)
3210 boot = true;
c55ac248
ZS
3211 else if (action[pos] == '+' && !append_or_force)
3212 append_or_force = true;
6d7b5433
WD
3213 else if (action[pos] == '-' && !allow_failure)
3214 allow_failure = true;
c46c3233
AW
3215 else if (action[pos] == '=' && !try_replace)
3216 try_replace = true;
708daf42
LP
3217 else if (action[pos] == '~' && !unbase64)
3218 unbase64 = true;
e52f6f63
LP
3219 else if (action[pos] == '^' && !from_cred)
3220 from_cred = true;
5f255144 3221 else {
d9daae55 3222 *invalid_config = true;
d02933fd 3223 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Unknown modifiers in command '%s'", action);
5f255144 3224 }
2e78fa79
LP
3225 }
3226
582deb84 3227 if (boot && !arg_boot) {
d02933fd 3228 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Ignoring entry %s \"%s\" because --boot is not specified.", action, path);
c4708f13 3229 return 0;
582deb84 3230 }
c4708f13 3231
3f93da98 3232 i.type = action[0];
c55ac248 3233 i.append_or_force = append_or_force;
6d7b5433 3234 i.allow_failure = allow_failure;
c46c3233 3235 i.try_replace = try_replace;
2e78fa79 3236
de61a04b 3237 r = specifier_printf(path, PATH_MAX-1, specifier_table, arg_root, NULL, &i.path);
6db98098 3238 if (ERRNO_IS_NOINFO(r))
4cef1923 3239 return log_unresolvable_specifier(fname, line);
d9daae55 3240 if (r < 0) {
751223fe
ZJS
3241 if (IN_SET(r, -EINVAL, -EBADSLT))
3242 *invalid_config = true;
d02933fd 3243 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", path);
d9daae55 3244 }
1731e34a 3245
a2d1fb88
LP
3246 r = patch_var_run(fname, line, &i.path);
3247 if (r < 0)
3248 return r;
3249
35c18a51
LP
3250 if (!path_is_absolute(i.path)) {
3251 *invalid_config = true;
3252 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3253 "Path '%s' not absolute.", i.path);
3254 }
3255
3256 path_simplify(i.path);
3257
3f93da98 3258 switch (i.type) {
468d726b 3259
777b87e7 3260 case CREATE_DIRECTORY:
d7b8eec7 3261 case CREATE_SUBVOLUME:
5fb13eb5
LP
3262 case CREATE_SUBVOLUME_INHERIT_QUOTA:
3263 case CREATE_SUBVOLUME_NEW_QUOTA:
df8dee85 3264 case EMPTY_DIRECTORY:
777b87e7
MS
3265 case TRUNCATE_DIRECTORY:
3266 case CREATE_FIFO:
3267 case IGNORE_PATH:
78a92a5a 3268 case IGNORE_DIRECTORY_PATH:
777b87e7
MS
3269 case REMOVE_PATH:
3270 case RECURSIVE_REMOVE_PATH:
e73a03e0 3271 case ADJUST_MODE:
777b87e7
MS
3272 case RELABEL_PATH:
3273 case RECURSIVE_RELABEL_PATH:
c82500c6 3274 if (i.argument)
2676befc
JJ
3275 log_syntax(NULL,
3276 LOG_WARNING,
3277 fname,
3278 line,
3279 0,
3280 "%c lines don't take argument fields, ignoring.",
3281 (char) i.type);
c82500c6
LP
3282
3283 break;
3284
3285 case CREATE_FILE:
3286 case TRUNCATE_FILE:
777b87e7 3287 break;
468d726b
LP
3288
3289 case CREATE_SYMLINK:
708daf42
LP
3290 if (unbase64) {
3291 *invalid_config = true;
3292 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for symlink targets.");
3293 }
3294
3f93da98 3295 if (!i.argument) {
b910cc72 3296 i.argument = path_join("/usr/share/factory", i.path);
3f93da98 3297 if (!i.argument)
2f3b873a 3298 return log_oom();
468d726b
LP
3299 }
3300 break;
3301
31ed59c5 3302 case WRITE_FILE:
3f93da98 3303 if (!i.argument) {
d9daae55 3304 *invalid_config = true;
d02933fd 3305 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Write file requires argument.");
31ed59c5
LP
3306 }
3307 break;
3308
849958d1 3309 case COPY_FILES:
708daf42
LP
3310 if (unbase64) {
3311 *invalid_config = true;
3312 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for copy sources.");
3313 }
3314
3f93da98 3315 if (!i.argument) {
7dc6477d 3316 i.argument = path_join("/usr/share/factory", i.path);
3f93da98 3317 if (!i.argument)
2f3b873a 3318 return log_oom();
3f93da98 3319 } else if (!path_is_absolute(i.argument)) {
d9daae55 3320 *invalid_config = true;
d02933fd 3321 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Source path '%s' is not absolute.", i.argument);
626f8d16 3322
7dc6477d
LP
3323 }
3324
3325 if (!empty_or_root(arg_root)) {
626f8d16
ZJS
3326 char *p;
3327
d34cd571 3328 p = path_join(arg_root, i.argument);
626f8d16
ZJS
3329 if (!p)
3330 return log_oom();
3331 free_and_replace(i.argument, p);
849958d1
LP
3332 }
3333
4ff361cc 3334 path_simplify(i.argument);
ce610af1
LP
3335
3336 if (laccess(i.argument, F_OK) == -ENOENT) {
3337 /* Silently skip over lines where the source file is missing. */
9109009d 3338 log_syntax(NULL, LOG_DEBUG, fname, line, 0, "Copy source path '%s' does not exist, skipping line.", i.argument);
ce610af1
LP
3339 return 0;
3340 }
3341
849958d1
LP
3342 break;
3343
468d726b 3344 case CREATE_CHAR_DEVICE:
3a47c40d 3345 case CREATE_BLOCK_DEVICE:
708daf42
LP
3346 if (unbase64) {
3347 *invalid_config = true;
3348 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for device node creation.");
3349 }
3350
3f93da98 3351 if (!i.argument) {
d9daae55 3352 *invalid_config = true;
d02933fd 3353 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "Device file requires argument.");
468d726b
LP
3354 }
3355
7176f06c 3356 r = parse_devnum(i.argument, &i.major_minor);
3a47c40d 3357 if (r < 0) {
d9daae55 3358 *invalid_config = true;
d02933fd 3359 return log_syntax(NULL, LOG_ERR, fname, line, r, "Can't parse device file major/minor '%s'.", i.argument);
468d726b
LP
3360 }
3361
468d726b 3362 break;
468d726b 3363
ebf4e801 3364 case SET_XATTR:
b705ab6a 3365 case RECURSIVE_SET_XATTR:
708daf42
LP
3366 if (unbase64) {
3367 *invalid_config = true;
3368 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for extended attributes.");
3369 }
3f93da98 3370 if (!i.argument) {
d9daae55 3371 *invalid_config = true;
d02933fd
LP
3372 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3373 "Set extended attribute requires argument.");
ebf4e801 3374 }
bd550f78 3375 r = parse_xattrs_from_arg(&i);
ebf4e801
MW
3376 if (r < 0)
3377 return r;
3378 break;
3379
f8eeeaf9 3380 case SET_ACL:
b705ab6a 3381 case RECURSIVE_SET_ACL:
708daf42
LP
3382 if (unbase64) {
3383 *invalid_config = true;
3384 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for ACLs.");
3385 }
f8eeeaf9 3386 if (!i.argument) {
d9daae55 3387 *invalid_config = true;
d02933fd
LP
3388 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3389 "Set ACLs requires argument.");
f8eeeaf9 3390 }
bd550f78 3391 r = parse_acls_from_arg(&i);
f8eeeaf9
ZJS
3392 if (r < 0)
3393 return r;
3394 break;
3395
88ec4dfa
LP
3396 case SET_ATTRIBUTE:
3397 case RECURSIVE_SET_ATTRIBUTE:
708daf42
LP
3398 if (unbase64) {
3399 *invalid_config = true;
3400 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG), "base64 decoding not supported for file attributes.");
3401 }
22c3a6ca 3402 if (!i.argument) {
d9daae55 3403 *invalid_config = true;
d02933fd
LP
3404 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3405 "Set file attribute requires argument.");
22c3a6ca 3406 }
bd550f78 3407 r = parse_attribute_from_arg(&i);
751223fe 3408 if (IN_SET(r, -EINVAL, -EBADSLT))
d9daae55 3409 *invalid_config = true;
22c3a6ca
GB
3410 if (r < 0)
3411 return r;
3412 break;
3413
777b87e7 3414 default:
d9daae55 3415 *invalid_config = true;
d02933fd
LP
3416 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
3417 "Unknown command type '%c'.", (char) i.type);
3b63d2d3 3418 }
468d726b 3419
3f93da98 3420 if (!should_include_path(i.path))
7f2c1f4d 3421 return 0;
5008d581 3422
e52f6f63
LP
3423 if (!unbase64) {
3424 /* Do specifier expansion except if base64 mode is enabled */
708daf42 3425 r = specifier_expansion_from_arg(specifier_table, &i);
6db98098 3426 if (ERRNO_IS_NOINFO(r))
708daf42
LP
3427 return log_unresolvable_specifier(fname, line);
3428 if (r < 0) {
3429 if (IN_SET(r, -EINVAL, -EBADSLT))
3430 *invalid_config = true;
3431 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to substitute specifiers in argument: %m");
3432 }
751223fe 3433 }
4cef1923 3434
e52f6f63
LP
3435 if (from_cred) {
3436 if (!i.argument)
3437 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Reading from credential requested, but no credential name specified.");
3438 if (!credential_name_valid(i.argument))
3439 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL), "Credential name not valid: %s", i.argument);
3440
3441 r = read_credential(i.argument, &i.binary_argument, &i.binary_argument_size);
3442 if (IN_SET(r, -ENXIO, -ENOENT)) {
3443 /* Silently skip over lines that have no credentials passed */
9109009d 3444 log_syntax(NULL, LOG_DEBUG, fname, line, 0,
6db98098 3445 "Credential '%s' not specified, skipping line.", i.argument);
e52f6f63
LP
3446 return 0;
3447 }
3448 if (r < 0)
3449 return log_error_errno(r, "Failed to read credential '%s': %m", i.argument);
3450 }
3451
3452 /* If base64 decoding is requested, do so now */
3453 if (unbase64 && item_binary_argument(&i)) {
3454 _cleanup_free_ void *data = NULL;
3455 size_t data_size = 0;
3456
3457 r = unbase64mem(item_binary_argument(&i), item_binary_argument_size(&i), &data, &data_size);
3458 if (r < 0)
3459 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to base64 decode specified argument '%s': %m", i.argument);
3460
3461 free_and_replace(i.binary_argument, data);
3462 i.binary_argument_size = data_size;
3463 }
3464
7dc6477d 3465 if (!empty_or_root(arg_root)) {
cde684a2
LP
3466 char *p;
3467
c6134d3e 3468 p = path_join(arg_root, i.path);
cf9a4abd
MM
3469 if (!p)
3470 return log_oom();
81fa4479 3471 free_and_replace(i.path, p);
cf9a4abd
MM
3472 }
3473
e7b88b7b 3474 if (!empty_or_dash(user)) {
cc43328c
LP
3475 const char *u;
3476
3477 u = startswith(user, ":");
3478 if (u)
3479 i.uid_only_create = true;
3480 else
3481 u = user;
3482
3483 r = find_uid(u, &i.uid, uid_cache);
4b67834e 3484 if (r < 0) {
d9daae55 3485 *invalid_config = true;
cc43328c 3486 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve user '%s': %m", u);
3b63d2d3
LP
3487 }
3488
3f93da98 3489 i.uid_set = true;
3b63d2d3
LP
3490 }
3491
e7b88b7b 3492 if (!empty_or_dash(group)) {
cc43328c
LP
3493 const char *g;
3494
3495 g = startswith(group, ":");
3496 if (g)
3497 i.gid_only_create = true;
3498 else
3499 g = group;
3500
3501 r = find_gid(g, &i.gid, gid_cache);
4b67834e 3502 if (r < 0) {
d9daae55 3503 *invalid_config = true;
cc43328c 3504 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to resolve group '%s'.", g);
3b63d2d3
LP
3505 }
3506
3f93da98 3507 i.gid_set = true;
3b63d2d3
LP
3508 }
3509
e7b88b7b 3510 if (!empty_or_dash(mode)) {
cc43328c 3511 const char *mm;
3b63d2d3
LP
3512 unsigned m;
3513
cc43328c
LP
3514 for (mm = mode;; mm++) {
3515 if (*mm == '~')
3516 i.mask_perms = true;
3517 else if (*mm == ':')
3518 i.mode_only_create = true;
3519 else
3520 break;
abef3f91
LP
3521 }
3522
d02933fd
LP
3523 r = parse_mode(mm, &m);
3524 if (r < 0) {
d9daae55 3525 *invalid_config = true;
d02933fd 3526 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid mode '%s'.", mode);
3b63d2d3
LP
3527 }
3528
3f93da98
ZJS
3529 i.mode = m;
3530 i.mode_set = true;
3b63d2d3 3531 } else
5fb13eb5 3532 i.mode = IN_SET(i.type, CREATE_DIRECTORY, TRUNCATE_DIRECTORY, CREATE_SUBVOLUME, CREATE_SUBVOLUME_INHERIT_QUOTA, CREATE_SUBVOLUME_NEW_QUOTA) ? 0755 : 0644;
3b63d2d3 3533
e7b88b7b 3534 if (!empty_or_dash(age)) {
24f3a374 3535 const char *a = age;
7f7a50dd 3536 _cleanup_free_ char *seconds = NULL, *age_by = NULL;
24f3a374
LP
3537
3538 if (*a == '~') {
3f93da98 3539 i.keep_first_level = true;
24f3a374
LP
3540 a++;
3541 }
3542
7f7a50dd
SK
3543 /* Format: "age-by:age"; where age-by is "[abcmABCM]+". */
3544 r = split_pair(a, ":", &age_by, &seconds);
3545 if (r == -ENOMEM)
3546 return log_oom();
3547 if (r < 0 && r != -EINVAL)
3548 return log_error_errno(r, "Failed to parse age-by for '%s': %m", age);
3549 if (r >= 0) {
3550 /* We found a ":", parse the "age-by" part. */
3551 r = parse_age_by_from_arg(age_by, &i);
3552 if (r == -ENOMEM)
3553 return log_oom();
3554 if (r < 0) {
3555 *invalid_config = true;
3556 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age-by '%s'.", age_by);
3557 }
3558
3559 /* For parsing the "age" part, after the ":". */
3560 a = seconds;
3561 }
3562
d02933fd
LP
3563 r = parse_sec(a, &i.age);
3564 if (r < 0) {
d9daae55 3565 *invalid_config = true;
7f7a50dd 3566 return log_syntax(NULL, LOG_ERR, fname, line, r, "Invalid age '%s'.", a);
3b63d2d3
LP
3567 }
3568
3f93da98 3569 i.age_set = true;
3b63d2d3
LP
3570 }
3571
3f93da98 3572 h = needs_glob(i.type) ? globs : items;
bfe95f35 3573
ef43a391 3574 existing = ordered_hashmap_get(h, i.path);
468d726b 3575 if (existing) {
9af74e0f
FB
3576 if (is_duplicated_item(existing, &i)) {
3577 log_syntax(NULL, LOG_NOTICE, fname, line, 0,
3578 "Duplicate line for path \"%s\", ignoring.", i.path);
3579 return 0;
ebf4e801
MW
3580 }
3581 } else {
3f93da98 3582 existing = new0(ItemArray, 1);
07982ed1
LP
3583 if (!existing)
3584 return log_oom();
3585
ef43a391 3586 r = ordered_hashmap_put(h, i.path, existing);
ccd114f0
LP
3587 if (r < 0) {
3588 free(existing);
3f93da98 3589 return log_oom();
ccd114f0 3590 }
bfe95f35
LP
3591 }
3592
319a4f4b 3593 if (!GREEDY_REALLOC(existing->items, existing->n_items + 1))
3f93da98 3594 return log_oom();
5008d581 3595
7ab7529d
LP
3596 existing->items[existing->n_items++] = i;
3597 i = (struct Item) {};
dd449aca
ZJS
3598
3599 /* Sort item array, to enforce stable ordering of application */
96d10d78 3600 typesafe_qsort(existing->items, existing->n_items, item_compare);
17493fa5 3601
7f2c1f4d 3602 return 0;
5008d581
LP
3603}
3604
ceaaeb9b
ZJS
3605static int cat_config(char **config_dirs, char **args) {
3606 _cleanup_strv_free_ char **files = NULL;
3607 int r;
3608
3609 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, NULL);
3610 if (r < 0)
3611 return r;
3612
3613 return cat_files(NULL, files, 0);
3614}
3615
dd04fb32
LP
3616static int exclude_default_prefixes(void) {
3617 int r;
3618
3619 /* Provide an easy way to exclude virtual/memory file systems from what we do here. Useful in
3620 * combination with --root= where we probably don't want to apply stuff to these dirs as they are
3621 * likely over-mounted if the root directory is actually used, and it wouldbe less than ideal to have
3622 * all kinds of files created/adjusted underneath these mount points. */
3623
3624 r = strv_extend_strv(
3625 &arg_exclude_prefixes,
3626 STRV_MAKE("/dev",
3627 "/proc",
3628 "/run",
3629 "/sys"),
3630 true);
3631 if (r < 0)
3632 return log_oom();
3633
3634 return 0;
3635}
3636
37ec0fdd
LP
3637static int help(void) {
3638 _cleanup_free_ char *link = NULL;
3639 int r;
3640
3641 r = terminal_urlify_man("systemd-tmpfiles", "8", &link);
3642 if (r < 0)
3643 return log_oom();
3644
3f532a59
LP
3645 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n"
3646 "\n%sCreates, deletes and cleans up volatile and temporary files and directories.%s\n\n"
5c795114 3647 " -h --help Show this help\n"
f2b5ca0e 3648 " --user Execute user configuration\n"
eb9da376 3649 " --version Show package version\n"
ceaaeb9b 3650 " --cat-config Show configuration files\n"
5c795114
DR
3651 " --create Create marked files/directories\n"
3652 " --clean Clean up marked directories\n"
3653 " --remove Remove marked files/directories\n"
81815651 3654 " --boot Execute actions only safe at boot\n"
79ca888f
ZJS
3655 " --prefix=PATH Only apply rules with the specified prefix\n"
3656 " --exclude-prefix=PATH Ignore rules with the specified prefix\n"
dd04fb32 3657 " -E Ignore rules prefixed with /dev, /proc, /run, /sys\n"
d9daae55 3658 " --root=PATH Operate on an alternate filesystem root\n"
63d3d0a5 3659 " --image=PATH Operate on disk image as filesystem root\n"
a6d8474f 3660 " --replace=PATH Treat arguments as replacement for PATH\n"
dcd5c891 3661 " --no-pager Do not pipe output into a pager\n"
bc556335
DDM
3662 "\nSee the %s for details.\n",
3663 program_invocation_short_name,
3664 ansi_highlight(),
3665 ansi_normal(),
3666 link);
37ec0fdd
LP
3667
3668 return 0;
3b63d2d3
LP
3669}
3670
3671static int parse_argv(int argc, char *argv[]) {
3672
3673 enum {
eb9da376 3674 ARG_VERSION = 0x100,
ceaaeb9b 3675 ARG_CAT_CONFIG,
f2b5ca0e 3676 ARG_USER,
3b63d2d3
LP
3677 ARG_CREATE,
3678 ARG_CLEAN,
fba6e687 3679 ARG_REMOVE,
81815651 3680 ARG_BOOT,
5c795114
DR
3681 ARG_PREFIX,
3682 ARG_EXCLUDE_PREFIX,
cf9a4abd 3683 ARG_ROOT,
63d3d0a5 3684 ARG_IMAGE,
a6d8474f 3685 ARG_REPLACE,
dcd5c891 3686 ARG_NO_PAGER,
3b63d2d3
LP
3687 };
3688
3689 static const struct option options[] = {
5c795114 3690 { "help", no_argument, NULL, 'h' },
f2b5ca0e 3691 { "user", no_argument, NULL, ARG_USER },
eb9da376 3692 { "version", no_argument, NULL, ARG_VERSION },
ceaaeb9b 3693 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
5c795114
DR
3694 { "create", no_argument, NULL, ARG_CREATE },
3695 { "clean", no_argument, NULL, ARG_CLEAN },
3696 { "remove", no_argument, NULL, ARG_REMOVE },
81815651 3697 { "boot", no_argument, NULL, ARG_BOOT },
5c795114
DR
3698 { "prefix", required_argument, NULL, ARG_PREFIX },
3699 { "exclude-prefix", required_argument, NULL, ARG_EXCLUDE_PREFIX },
cf9a4abd 3700 { "root", required_argument, NULL, ARG_ROOT },
63d3d0a5 3701 { "image", required_argument, NULL, ARG_IMAGE },
a6d8474f 3702 { "replace", required_argument, NULL, ARG_REPLACE },
dcd5c891 3703 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
eb9da376 3704 {}
3b63d2d3
LP
3705 };
3706
0f474365 3707 int c, r;
3b63d2d3
LP
3708
3709 assert(argc >= 0);
3710 assert(argv);
3711
dd04fb32 3712 while ((c = getopt_long(argc, argv, "hE", options, NULL)) >= 0)
3b63d2d3
LP
3713
3714 switch (c) {
3715
3716 case 'h':
37ec0fdd 3717 return help();
eb9da376
LP
3718
3719 case ARG_VERSION:
3f6fd1ba 3720 return version();
3b63d2d3 3721
ceaaeb9b
ZJS
3722 case ARG_CAT_CONFIG:
3723 arg_cat_config = true;
3724 break;
3725
f2b5ca0e
ZJS
3726 case ARG_USER:
3727 arg_user = true;
3728 break;
3729
3b63d2d3 3730 case ARG_CREATE:
1a967b6b 3731 arg_operation |= OPERATION_CREATE;
3b63d2d3
LP
3732 break;
3733
3734 case ARG_CLEAN:
1a967b6b 3735 arg_operation |= OPERATION_CLEAN;
3b63d2d3
LP
3736 break;
3737
3738 case ARG_REMOVE:
1a967b6b 3739 arg_operation |= OPERATION_REMOVE;
3b63d2d3
LP
3740 break;
3741
81815651
ZJS
3742 case ARG_BOOT:
3743 arg_boot = true;
c4708f13
ZJS
3744 break;
3745
fba6e687 3746 case ARG_PREFIX:
7bc040fa 3747 if (strv_push(&arg_include_prefixes, optarg) < 0)
a2aced4a 3748 return log_oom();
fba6e687
LP
3749 break;
3750
5c795114 3751 case ARG_EXCLUDE_PREFIX:
7bc040fa 3752 if (strv_push(&arg_exclude_prefixes, optarg) < 0)
5c795114
DR
3753 return log_oom();
3754 break;
3755
63d3d0a5 3756 case ARG_ROOT:
614b022c 3757 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
dd04fb32
LP
3758 if (r < 0)
3759 return r;
dd04fb32
LP
3760 break;
3761
63d3d0a5 3762 case ARG_IMAGE:
3537577c
ZJS
3763#ifdef STANDALONE
3764 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
3765 "This systemd-tmpfiles version is compiled without support for --image=.");
3766#else
614b022c 3767 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
63d3d0a5
LP
3768 if (r < 0)
3769 return r;
3537577c
ZJS
3770#endif
3771 /* Imply -E here since it makes little sense to create files persistently in the /run mountpoint of a disk image */
63d3d0a5
LP
3772 _fallthrough_;
3773
3774 case 'E':
3775 r = exclude_default_prefixes();
0f474365 3776 if (r < 0)
0f03c2a4 3777 return r;
63d3d0a5 3778
cf9a4abd
MM
3779 break;
3780
a6d8474f
ZJS
3781 case ARG_REPLACE:
3782 if (!path_is_absolute(optarg) ||
baaa35ad
ZJS
3783 !endswith(optarg, ".conf"))
3784 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3785 "The argument to --replace= must an absolute path to a config file");
a6d8474f
ZJS
3786
3787 arg_replace = optarg;
3788 break;
3789
dcd5c891 3790 case ARG_NO_PAGER:
0221d68a 3791 arg_pager_flags |= PAGER_DISABLE;
dcd5c891
LP
3792 break;
3793
3b63d2d3
LP
3794 case '?':
3795 return -EINVAL;
3796
3797 default:
04499a70 3798 assert_not_reached();
3b63d2d3 3799 }
3b63d2d3 3800
baaa35ad
ZJS
3801 if (arg_operation == 0 && !arg_cat_config)
3802 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3803 "You need to specify at least one of --clean, --create or --remove.");
3b63d2d3 3804
baaa35ad
ZJS
3805 if (arg_replace && arg_cat_config)
3806 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3807 "Option --replace= is not supported with --cat-config");
ceaaeb9b 3808
baaa35ad
ZJS
3809 if (arg_replace && optind >= argc)
3810 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3811 "When --replace= is given, some configuration items must be specified");
a6d8474f 3812
b63aacaa
LP
3813 if (arg_root && arg_user)
3814 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
3815 "Combination of --user and --root= is not supported.");
3816
63d3d0a5
LP
3817 if (arg_image && arg_root)
3818 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
3819
3b63d2d3
LP
3820 return 1;
3821}
3822
1d77721f
LP
3823static int read_config_file(
3824 char **config_dirs,
3825 const char *fn,
3826 bool ignore_enoent,
3827 bool *invalid_config) {
3828
a3451c2c 3829 _cleanup_(hashmap_freep) Hashmap *uid_cache = NULL, *gid_cache = NULL;
f7ac1ed2 3830 _cleanup_fclose_ FILE *_f = NULL;
2708160c 3831 _cleanup_free_ char *pp = NULL;
1731e34a 3832 unsigned v = 0;
2a98ae4a 3833 FILE *f;
bec890e3 3834 ItemArray *ia;
4e68ec18 3835 int r = 0;
fba6e687
LP
3836
3837 assert(fn);
3838
f7ac1ed2 3839 if (streq(fn, "-")) {
28e5e1e9 3840 log_debug("Reading config from stdin%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
f7ac1ed2
ZJS
3841 fn = "<stdin>";
3842 f = stdin;
3843 } else {
2708160c 3844 r = search_and_fopen(fn, "re", arg_root, (const char**) config_dirs, &_f, &pp);
f7ac1ed2
ZJS
3845 if (r < 0) {
3846 if (ignore_enoent && r == -ENOENT) {
3847 log_debug_errno(r, "Failed to open \"%s\", ignoring: %m", fn);
3848 return 0;
3849 }
fba6e687 3850
f7ac1ed2
ZJS
3851 return log_error_errno(r, "Failed to open '%s': %m", fn);
3852 }
2708160c 3853
28e5e1e9 3854 log_debug("Reading config file \"%s\"%s", pp, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
2708160c 3855 fn = pp;
f7ac1ed2 3856 f = _f;
fba6e687
LP
3857 }
3858
2a98ae4a
LP
3859 for (;;) {
3860 _cleanup_free_ char *line = NULL;
3861 bool invalid_line = false;
1731e34a 3862 char *l;
fba6e687 3863 int k;
2a98ae4a
LP
3864
3865 k = read_line(f, LONG_LINE_MAX, &line);
3866 if (k < 0)
3867 return log_error_errno(k, "Failed to read '%s': %m", fn);
3868 if (k == 0)
3869 break;
fba6e687 3870
fba6e687
LP
3871 v++;
3872
3873 l = strstrip(line);
4c701096 3874 if (IN_SET(*l, 0, '#'))
fba6e687
LP
3875 continue;
3876
a3451c2c 3877 k = parse_line(fn, v, l, &invalid_line, &uid_cache, &gid_cache);
d9daae55
ZJS
3878 if (k < 0) {
3879 if (invalid_line)
3880 /* Allow reporting with a special code if the caller requested this */
3881 *invalid_config = true;
3882 else if (r == 0)
3883 /* The first error becomes our return value */
3884 r = k;
3885 }
fba6e687
LP
3886 }
3887
78a92a5a 3888 /* we have to determine age parameter for each entry of type X */
bec890e3
MM
3889 ORDERED_HASHMAP_FOREACH(ia, globs)
3890 for (size_t ni = 0; ni < ia->n_items; ni++) {
3891 ItemArray *ja;
3892 Item *i = ia->items + ni, *candidate_item = NULL;
78a92a5a 3893
bec890e3 3894 if (i->type != IGNORE_DIRECTORY_PATH)
78a92a5a
MS
3895 continue;
3896
bec890e3
MM
3897 ORDERED_HASHMAP_FOREACH(ja, items)
3898 for (size_t nj = 0; nj < ja->n_items; nj++) {
3899 Item *j = ja->items + nj;
78a92a5a 3900
875e7b25
ZJS
3901 if (!IN_SET(j->type, CREATE_DIRECTORY,
3902 TRUNCATE_DIRECTORY,
3903 CREATE_SUBVOLUME,
3904 CREATE_SUBVOLUME_INHERIT_QUOTA,
3905 CREATE_SUBVOLUME_NEW_QUOTA))
bec890e3 3906 continue;
78a92a5a 3907
bec890e3
MM
3908 if (path_equal(j->path, i->path)) {
3909 candidate_item = j;
3910 break;
3911 }
3912
875e7b25
ZJS
3913 if (candidate_item
3914 ? (path_startswith(j->path, candidate_item->path) && fnmatch(i->path, j->path, FNM_PATHNAME | FNM_PERIOD) == 0)
3915 : path_startswith(i->path, j->path) != NULL)
bec890e3
MM
3916 candidate_item = j;
3917 }
3918
3919 if (candidate_item && candidate_item->age_set) {
3920 i->age = candidate_item->age;
3921 i->age_set = true;
3922 }
78a92a5a 3923 }
78a92a5a 3924
fba6e687 3925 if (ferror(f)) {
56f64d95 3926 log_error_errno(errno, "Failed to read from file %s: %m", fn);
fba6e687
LP
3927 if (r == 0)
3928 r = -EIO;
3929 }
3930
fba6e687
LP
3931 return r;
3932}
3933
a6d8474f 3934static int parse_arguments(char **config_dirs, char **args, bool *invalid_config) {
a6d8474f
ZJS
3935 int r;
3936
3937 STRV_FOREACH(arg, args) {
3938 r = read_config_file(config_dirs, *arg, false, invalid_config);
3939 if (r < 0)
3940 return r;
3941 }
3942
3943 return 0;
3944}
3945
3946static int read_config_files(char **config_dirs, char **args, bool *invalid_config) {
3947 _cleanup_strv_free_ char **files = NULL;
3948 _cleanup_free_ char *p = NULL;
a6d8474f
ZJS
3949 int r;
3950
ceaaeb9b 3951 r = conf_files_list_with_replacement(arg_root, config_dirs, arg_replace, &files, &p);
a6d8474f 3952 if (r < 0)
ceaaeb9b 3953 return r;
a6d8474f
ZJS
3954
3955 STRV_FOREACH(f, files)
3956 if (p && path_equal(*f, p)) {
28e5e1e9 3957 log_debug("Parsing arguments at position \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
a6d8474f
ZJS
3958
3959 r = parse_arguments(config_dirs, args, invalid_config);
3960 if (r < 0)
3961 return r;
3962 } else
3963 /* Just warn, ignore result otherwise.
3964 * read_config_file() has some debug output, so no need to print anything. */
3965 (void) read_config_file(config_dirs, *f, true, invalid_config);
3966
3967 return 0;
3968}
3969
1d77721f
LP
3970static int read_credential_lines(bool *invalid_config) {
3971 _cleanup_free_ char *j = NULL;
3972 const char *d;
3973 int r;
3974
3975 r = get_credentials_dir(&d);
3976 if (r == -ENXIO)
3977 return 0;
3978 if (r < 0)
3979 return log_error_errno(r, "Failed to get credentials directory: %m");
3980
3981 j = path_join(d, "tmpfiles.extra");
3982 if (!j)
3983 return log_oom();
3984
3985 (void) read_config_file(/* config_dirs= */ NULL, j, /* ignore_enoent= */ true, invalid_config);
3986 return 0;
3987}
3988
811a1587
LP
3989static int link_parent(ItemArray *a) {
3990 const char *path;
3991 char *prefix;
3992 int r;
3993
3994 assert(a);
3995
09f467ac 3996 /* Finds the closest "parent" item array for the specified item array. Then registers the specified item array
811a1587
LP
3997 * as child of it, and fills the parent in, linking them both ways. This allows us to later create parents
3998 * before their children, and clean up/remove children before their parents. */
3999
4000 if (a->n_items <= 0)
4001 return 0;
4002
4003 path = a->items[0].path;
6e9417f5 4004 prefix = newa(char, strlen(path) + 1);
811a1587
LP
4005 PATH_FOREACH_PREFIX(prefix, path) {
4006 ItemArray *j;
4007
4008 j = ordered_hashmap_get(items, prefix);
bd0ce244
LP
4009 if (!j)
4010 j = ordered_hashmap_get(globs, prefix);
811a1587 4011 if (j) {
de7fef4b 4012 r = set_ensure_put(&j->children, NULL, a);
811a1587
LP
4013 if (r < 0)
4014 return log_oom();
4015
4016 a->parent = j;
4017 return 1;
4018 }
4019 }
4020
4021 return 0;
4022}
4023
87938c3b
YW
4024DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_array_hash_ops, char, string_hash_func, string_compare_func,
4025 ItemArray, item_array_free);
4026
4027static int run(int argc, char *argv[]) {
3537577c 4028#ifndef STANDALONE
63d3d0a5 4029 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
63d3d0a5 4030 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
3537577c 4031#endif
f2b5ca0e 4032 _cleanup_strv_free_ char **config_dirs = NULL;
d9daae55 4033 bool invalid_config = false;
64adb379 4034 ItemArray *a;
44ac4f88
LP
4035 enum {
4036 PHASE_REMOVE_AND_CLEAN,
4037 PHASE_CREATE,
4038 _PHASE_MAX
4039 } phase;
87938c3b 4040 int r, k;
3b63d2d3 4041
fdcad0c2
LP
4042 r = parse_argv(argc, argv);
4043 if (r <= 0)
87938c3b 4044 return r;
5008d581 4045
d2acb93d 4046 log_setup();
5008d581 4047
01131684
LP
4048 /* We require /proc/ for a lot of our operations, i.e. for adjusting access modes, for anything
4049 * SELinux related, for recursive operation, for xattr, acl and chattr handling, for btrfs stuff and
4050 * a lot more. It's probably the majority of invocations where /proc/ is required. Since people
4051 * apparently invoke it without anyway and are surprised about the failures, let's catch this early
4052 * and output a nice and friendly warning. */
4053 if (proc_mounted() == 0)
4054 return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),
4055 "/proc/ is not mounted, but required for successful operation of systemd-tmpfiles. "
4056 "Please mount /proc/. Alternatively, consider using the --root= or --image= switches.");
4057
e5358401
LP
4058 /* Descending down file system trees might take a lot of fds */
4059 (void) rlimit_nofile_bump(HIGH_RLIMIT_NOFILE);
4060
f2b5ca0e
ZJS
4061 if (arg_user) {
4062 r = user_config_paths(&config_dirs);
87938c3b
YW
4063 if (r < 0)
4064 return log_error_errno(r, "Failed to initialize configuration directory list: %m");
f2b5ca0e
ZJS
4065 } else {
4066 config_dirs = strv_split_nulstr(CONF_PATHS_NULSTR("tmpfiles.d"));
87938c3b
YW
4067 if (!config_dirs)
4068 return log_oom();
f2b5ca0e
ZJS
4069 }
4070
79c91cec 4071 if (DEBUG_LOGGING) {
f2b5ca0e
ZJS
4072 _cleanup_free_ char *t = NULL;
4073
b8e35011
LP
4074 STRV_FOREACH(i, config_dirs) {
4075 _cleanup_free_ char *j = NULL;
4076
4077 j = path_join(arg_root, *i);
4078 if (!j)
4079 return log_oom();
4080
c2bc710b 4081 if (!strextend(&t, "\n\t", j))
b8e35011
LP
4082 return log_oom();
4083 }
4084
4085 log_debug("Looking for configuration files in (higher priority first):%s", t);
f2b5ca0e
ZJS
4086 }
4087
ceaaeb9b 4088 if (arg_cat_config) {
384c2c32 4089 pager_open(arg_pager_flags);
dcd5c891 4090
87938c3b 4091 return cat_config(config_dirs, argv + optind);
ceaaeb9b
ZJS
4092 }
4093
4094 umask(0022);
4095
a9ba0e32
CG
4096 r = mac_selinux_init();
4097 if (r < 0)
4098 return r;
ceaaeb9b 4099
3537577c 4100#ifndef STANDALONE
63d3d0a5
LP
4101 if (arg_image) {
4102 assert(!arg_root);
4103
4104 r = mount_image_privately_interactively(
4105 arg_image,
4b5de5dd
LP
4106 DISSECT_IMAGE_GENERIC_ROOT |
4107 DISSECT_IMAGE_REQUIRE_ROOT |
4108 DISSECT_IMAGE_VALIDATE_OS |
4109 DISSECT_IMAGE_RELAX_VAR_CHECK |
c65f854a
LP
4110 DISSECT_IMAGE_FSCK |
4111 DISSECT_IMAGE_GROWFS,
63d3d0a5 4112 &unlink_dir,
e330f97a 4113 &loop_device);
63d3d0a5
LP
4114 if (r < 0)
4115 return r;
4116
4117 arg_root = strdup(unlink_dir);
4118 if (!arg_root)
4119 return log_oom();
4120 }
3537577c
ZJS
4121#else
4122 assert(!arg_image);
4123#endif
63d3d0a5 4124
87938c3b
YW
4125 items = ordered_hashmap_new(&item_array_hash_ops);
4126 globs = ordered_hashmap_new(&item_array_hash_ops);
4127 if (!items || !globs)
4128 return log_oom();
ceaaeb9b 4129
a6d8474f
ZJS
4130 /* If command line arguments are specified along with --replace, read all
4131 * configuration files and insert the positional arguments at the specified
4132 * place. Otherwise, if command line arguments are specified, execute just
4133 * them, and finally, without --replace= or any positional arguments, just
4134 * read configuration and execute it.
4135 */
4136 if (arg_replace || optind >= argc)
4137 r = read_config_files(config_dirs, argv + optind, &invalid_config);
4138 else
4139 r = parse_arguments(config_dirs, argv + optind, &invalid_config);
4140 if (r < 0)
87938c3b 4141 return r;
5008d581 4142
1d77721f
LP
4143 r = read_credential_lines(&invalid_config);
4144 if (r < 0)
4145 return r;
4146
811a1587 4147 /* Let's now link up all child/parent relationships */
90e74a66 4148 ORDERED_HASHMAP_FOREACH(a, items) {
811a1587
LP
4149 r = link_parent(a);
4150 if (r < 0)
87938c3b 4151 return r;
1db50423 4152 }
90e74a66 4153 ORDERED_HASHMAP_FOREACH(a, globs) {
811a1587
LP
4154 r = link_parent(a);
4155 if (r < 0)
87938c3b 4156 return r;
811a1587
LP
4157 }
4158
64adb379
LP
4159 /* If multiple operations are requested, let's first run the remove/clean operations, and only then the create
4160 * operations. i.e. that we first clean out the platform we then build on. */
44ac4f88 4161 for (phase = 0; phase < _PHASE_MAX; phase++) {
64adb379 4162 OperationMask op;
b8bb3e8f 4163
44ac4f88 4164 if (phase == PHASE_REMOVE_AND_CLEAN)
64adb379 4165 op = arg_operation & (OPERATION_REMOVE|OPERATION_CLEAN);
44ac4f88 4166 else if (phase == PHASE_CREATE)
64adb379
LP
4167 op = arg_operation & OPERATION_CREATE;
4168 else
04499a70 4169 assert_not_reached();
64adb379
LP
4170
4171 if (op == 0) /* Nothing requested in this phase */
4172 continue;
4173
4174 /* The non-globbing ones usually create things, hence we apply them first */
90e74a66 4175 ORDERED_HASHMAP_FOREACH(a, items) {
64adb379 4176 k = process_item_array(a, op);
87938c3b
YW
4177 if (k < 0 && r >= 0)
4178 r = k;
64adb379
LP
4179 }
4180
4181 /* The globbing ones usually alter things, hence we apply them second. */
90e74a66 4182 ORDERED_HASHMAP_FOREACH(a, globs) {
64adb379 4183 k = process_item_array(a, op);
87938c3b
YW
4184 if (k < 0 && r >= 0)
4185 r = k;
64adb379 4186 }
1db50423 4187 }
3b63d2d3 4188
95d2155a 4189 if (ERRNO_IS_RESOURCE(r))
87938c3b
YW
4190 return r;
4191 if (invalid_config)
d9daae55 4192 return EX_DATAERR;
87938c3b 4193 if (r < 0)
bb9947be 4194 return EX_CANTCREAT;
87938c3b 4195 return 0;
5008d581 4196}
87938c3b
YW
4197
4198DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);