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