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