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