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