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