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