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