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