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