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